diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_threading_expert_play_df_W3s1_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_threading_expert_play_df_W3s1_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..b392b6279d6428257b6e885069e6c1bbb3093c2c --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_threading_expert_play_df_W3s1_s100000.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE, run 23) -- fidelity-vs-horizon for the W3 arm, the arm that +# actually carries the published DF numbers. Every fid_*.json on disk is for arms A/B/C, so the column +# was about to publish W3 scores beside a different model's fidelity. out: +# status/real/dfval/fid_threading_expert_play_df_W3s1_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh threading_expert_play W3s1 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_threading_expert_play_df_W3s2_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_threading_expert_play_df_W3s2_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a4a75e88e9302a7c4c74f8345cc7c63b06bccd8 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_threading_expert_play_df_W3s2_s100000.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE, run 23) -- fidelity-vs-horizon for the W3 arm, the arm that +# actually carries the published DF numbers. Every fid_*.json on disk is for arms A/B/C, so the column +# was about to publish W3 scores beside a different model's fidelity. out: +# status/real/dfval/fid_threading_expert_play_df_W3s2_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh threading_expert_play W3s2 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_A_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_A_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..a75986248695d439be8c10537cd90bf53cad6cad --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_A_s100000.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the arguments. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_play_df_A_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_play A 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_C_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_C_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..7529400277f13ee53bf9d22db597d30429b8e254 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_C_s100000.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the arguments. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_play_df_C_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_play C 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_W3_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_W3_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..435a0affbfae017270bcb908afebd831dfea4df5 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_df_W3_s100000.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE, run 23) -- fidelity-vs-horizon for the W3 arm, the arm that +# actually carries the published DF numbers. Every fid_*.json on disk is for arms A/B/C, so the column +# was about to publish W3 scores beside a different model's fidelity. out: +# status/real/dfval/fid_two_piece_expert_play_df_W3_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_play W3 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_dinowm.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_dinowm.sh new file mode 100644 index 0000000000000000000000000000000000000000..05ff0431f137b389127a4d5321d7d8df76368598 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_dinowm.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the argument. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_play_dinowm.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_dwm_task.sh two_piece_expert_play diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_lewm.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_lewm.sh new file mode 100644 index 0000000000000000000000000000000000000000..643196850ba4197067db099b15a0741a15eda2ce --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_lewm.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the argument. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_play_lewm.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_lewm_task.sh two_piece_expert_play diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_A_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_A_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..ada4abd8401da49d1dbeb1f93ca765c4646685c0 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_A_s100000.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the arguments. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_play_tipping_df_A_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_play_tipping A 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_C_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_C_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..02511bc1c9984b30004611daba1923e5ec2fa4fe --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_C_s100000.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the arguments. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_play_tipping_df_C_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_play_tipping C 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_W3_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_W3_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..89c0312e7409ec13b28adffad7c65c5d61d931eb --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_df_W3_s100000.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE, run 23) -- fidelity-vs-horizon for the W3 arm, the arm that +# actually carries the published DF numbers. Every fid_*.json on disk is for arms A/B/C, so the column +# was about to publish W3 scores beside a different model's fidelity. out: +# status/real/dfval/fid_two_piece_expert_play_tipping_df_W3_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_play_tipping W3 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_dinowm.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_dinowm.sh new file mode 100644 index 0000000000000000000000000000000000000000..108134ee8141fa77537fcf4efca6350a9621a3bc --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_dinowm.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the argument. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_play_tipping_dinowm.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_dwm_task.sh two_piece_expert_play_tipping diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_lewm.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_lewm.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec6d627700349d934d34661b70e378e1263c3f2c --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_play_tipping_lewm.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the argument. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_play_tipping_lewm.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_lewm_task.sh two_piece_expert_play_tipping diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_A_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_A_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb267b1e9f4659e5019ca75099682234a8f16743 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_A_s100000.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the arguments. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_suboptimal_df_A_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_suboptimal A 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_C_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_C_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c77d24a3f83cd65a12bcd09fe5db658a87db40f --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_C_s100000.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the arguments. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_suboptimal_df_C_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_suboptimal C 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_W3_s100000.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_W3_s100000.sh new file mode 100644 index 0000000000000000000000000000000000000000..2860e919a881cfa123b4247d85694d415295b992 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_df_W3_s100000.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE, run 23) -- fidelity-vs-horizon for the W3 arm, the arm that +# actually carries the published DF numbers. Every fid_*.json on disk is for arms A/B/C, so the column +# was about to publish W3 scores beside a different model's fidelity. out: +# status/real/dfval/fid_two_piece_expert_suboptimal_df_W3_s100000.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_df_arm.sh two_piece_expert_suboptimal W3 100000 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_dinowm.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_dinowm.sh new file mode 100644 index 0000000000000000000000000000000000000000..53024f161758d537ff0d5019ced3496f54bfad40 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_dinowm.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the argument. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_suboptimal_dinowm.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_dwm_task.sh two_piece_expert_suboptimal diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_lewm.sh b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_lewm.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d6ae07ef4a6e7225660f6d23cd695d70add1e68 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_fid_two_piece_expert_suboptimal_lewm.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# GENERATED (gen_q#282, stream DF_VALUE) -- ONE measurement per payload so a preempted pack resumes at +# measurement granularity. scripts/bsub_gpu_pack.sh runs a payload as `bash ''` with NO arguments, +# so a parameterized script cannot be handed to it directly; this wrapper supplies the argument. +# Idempotency lives in the callee (it skips when its out JSON exists). +# out: status/real/dfval/fid_two_piece_expert_suboptimal_lewm.json +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/packs/dfval_fid_lewm_task.sh two_piece_expert_suboptimal diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3_square_expert_play.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3_square_expert_play.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f2415c7c7e5584b1266a176c3f9d2f2a43e42 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3_square_expert_play.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# DF_VALUE run 21 (gen_q#282, 2026-09-24 21:4xZ). df_W3 = the ONLY DF arm that passes its own +# preregistered controls (threading mpc_disc H=50 argmax 0.1711+-0.0237 vs random-of-128 0.0489, +# t=7.00; `first` index-prior control tracks random; `argmin` 0.0133 < random < argmax = double +# dissociation). W3 differs from arm df_A by ONE flag: --chan-share '4:2:1' (DF's own published +# planning bundle share obs 57.1 / act 28.6 / rew 14.3, against df_A's uniform loss.mean() which +# gives the reward channel 0.064% of the gradient). W3 existed on only threading+mug, so the other +# five rows of the DF value column were being filled with df_A -- the arm already known to sit BELOW +# random. This payload fills one of those rows (or one seed replicate of the effect). +# Recipe copied verbatim from scripts/nb/packs/dfchan_{mug,threading}_W3.sh; only the task/cfg move. +# df_payload.sh skips a cell already at its target step, so this is resumable under preemption. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_expert_play W3 100000 \ + --chan-share '4:2:1' diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3_square_sub_20100.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3_square_sub_20100.sh new file mode 100644 index 0000000000000000000000000000000000000000..660b5872d9056cf1308655503e8d02d19d0f4a1d --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3_square_sub_20100.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# DF_VALUE run 21 (gen_q#282, 2026-09-24 21:4xZ). df_W3 = the ONLY DF arm that passes its own +# preregistered controls (threading mpc_disc H=50 argmax 0.1711+-0.0237 vs random-of-128 0.0489, +# t=7.00; `first` index-prior control tracks random; `argmin` 0.0133 < random < argmax = double +# dissociation). W3 differs from arm df_A by ONE flag: --chan-share '4:2:1' (DF's own published +# planning bundle share obs 57.1 / act 28.6 / rew 14.3, against df_A's uniform loss.mean() which +# gives the reward channel 0.064% of the gradient). W3 existed on only threading+mug, so the other +# five rows of the DF value column were being filled with df_A -- the arm already known to sit BELOW +# random. This payload fills one of those rows (or one seed replicate of the effect). +# Recipe copied verbatim from scripts/nb/packs/dfchan_{mug,threading}_W3.sh; only the task/cfg move. +# df_payload.sh skips a cell already at its target step, so this is resumable under preemption. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_sub_20100 W3 100000 \ + --chan-share '4:2:1' diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_play.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_play.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c829156e40247e86a6c2aebdc01900abe2d8fcf --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_play.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# DF_VALUE run 21 (gen_q#282, 2026-09-24 21:4xZ). df_W3 = the ONLY DF arm that passes its own +# preregistered controls (threading mpc_disc H=50 argmax 0.1711+-0.0237 vs random-of-128 0.0489, +# t=7.00; `first` index-prior control tracks random; `argmin` 0.0133 < random < argmax = double +# dissociation). W3 differs from arm df_A by ONE flag: --chan-share '4:2:1' (DF's own published +# planning bundle share obs 57.1 / act 28.6 / rew 14.3, against df_A's uniform loss.mean() which +# gives the reward channel 0.064% of the gradient). W3 existed on only threading+mug, so the other +# five rows of the DF value column were being filled with df_A -- the arm already known to sit BELOW +# random. This payload fills one of those rows (or one seed replicate of the effect). +# Recipe copied verbatim from scripts/nb/packs/dfchan_{mug,threading}_W3.sh; only the task/cfg move. +# df_payload.sh skips a cell already at its target step, so this is resumable under preemption. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play W3 100000 \ + --chan-share '4:2:1' diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_play_tipping.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_play_tipping.sh new file mode 100644 index 0000000000000000000000000000000000000000..385991f75f3bc149a530b1fd2e00729e21e8ae30 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_play_tipping.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# DF_VALUE run 21 (gen_q#282, 2026-09-24 21:4xZ). df_W3 = the ONLY DF arm that passes its own +# preregistered controls (threading mpc_disc H=50 argmax 0.1711+-0.0237 vs random-of-128 0.0489, +# t=7.00; `first` index-prior control tracks random; `argmin` 0.0133 < random < argmax = double +# dissociation). W3 differs from arm df_A by ONE flag: --chan-share '4:2:1' (DF's own published +# planning bundle share obs 57.1 / act 28.6 / rew 14.3, against df_A's uniform loss.mean() which +# gives the reward channel 0.064% of the gradient). W3 existed on only threading+mug, so the other +# five rows of the DF value column were being filled with df_A -- the arm already known to sit BELOW +# random. This payload fills one of those rows (or one seed replicate of the effect). +# Recipe copied verbatim from scripts/nb/packs/dfchan_{mug,threading}_W3.sh; only the task/cfg move. +# df_payload.sh skips a cell already at its target step, so this is resumable under preemption. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play_tipping W3 100000 \ + --chan-share '4:2:1' diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_suboptimal.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_suboptimal.sh new file mode 100644 index 0000000000000000000000000000000000000000..5351ba72e1d1aba548543ea4dbabb43caed50d47 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3_two_piece_expert_suboptimal.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# DF_VALUE run 21 (gen_q#282, 2026-09-24 21:4xZ). df_W3 = the ONLY DF arm that passes its own +# preregistered controls (threading mpc_disc H=50 argmax 0.1711+-0.0237 vs random-of-128 0.0489, +# t=7.00; `first` index-prior control tracks random; `argmin` 0.0133 < random < argmax = double +# dissociation). W3 differs from arm df_A by ONE flag: --chan-share '4:2:1' (DF's own published +# planning bundle share obs 57.1 / act 28.6 / rew 14.3, against df_A's uniform loss.mean() which +# gives the reward channel 0.064% of the gradient). W3 existed on only threading+mug, so the other +# five rows of the DF value column were being filled with df_A -- the arm already known to sit BELOW +# random. This payload fills one of those rows (or one seed replicate of the effect). +# Recipe copied verbatim from scripts/nb/packs/dfchan_{mug,threading}_W3.sh; only the task/cfg move. +# df_payload.sh skips a cell already at its target step, so this is resumable under preemption. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_suboptimal W3 100000 \ + --chan-share '4:2:1' diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_mug.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_mug.sh new file mode 100644 index 0000000000000000000000000000000000000000..55d64443de3d4f8bf26df86d4e30ae75420e4eb0 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_mug.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# DF_VALUE run 21 (gen_q#282, 2026-09-24 21:4xZ). df_W3 = the ONLY DF arm that passes its own +# preregistered controls (threading mpc_disc H=50 argmax 0.1711+-0.0237 vs random-of-128 0.0489, +# t=7.00; `first` index-prior control tracks random; `argmin` 0.0133 < random < argmax = double +# dissociation). W3 differs from arm df_A by ONE flag: --chan-share '4:2:1' (DF's own published +# planning bundle share obs 57.1 / act 28.6 / rew 14.3, against df_A's uniform loss.mean() which +# gives the reward channel 0.064% of the gradient). W3 existed on only threading+mug, so the other +# five rows of the DF value column were being filled with df_A -- the arm already known to sit BELOW +# random. This payload fills one of those rows (or one seed replicate of the effect). +# Recipe copied verbatim from scripts/nb/packs/dfchan_{mug,threading}_W3.sh; only the task/cfg move. +# df_payload.sh skips a cell already at its target step, so this is resumable under preemption. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh mug_expert_suboptimal W3s1 100000 \ + --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_expert_play.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_expert_play.sh new file mode 100644 index 0000000000000000000000000000000000000000..c0bb8ebcf68e5c2ad58363e1cb48d3ebc78909f2 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_expert_play.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 1 for square_expert_play, so DF's square_expert_play row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_expert_play W3s1 100000 --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_expert_play_resume.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_expert_play_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..6da176c9a6a23a8aeb7f9c290d332175ac927570 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_expert_play_resume.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# FLAG_TOPUP run 10: finish square_expert_play/df_W3s1, whose final ckpt_s100000.pt save was lost to the +# 11:10-11:40Z ENOSPC event. Preflight first (a truncated ckpt is loadable-looking but not +# loadable), then the VERBATIM run-7 payload -- train_df.py --resume defaults to 1. +set -uo pipefail +OUT=/proj/dmfexp/zwhong/rsm_rise/runs/square_expert_play/wm/df_W3s1 +echo "[resume-preflight] $(date -u) $OUT" +/proj/dmfexp/zwhong/rsm_rise/venv_df/bin/python - "$OUT" <<'PY' +import sys, pathlib, torch +d = pathlib.Path(sys.argv[1]) +for p in sorted(d.glob("ckpt*.pt")): + try: + ck = torch.load(p, map_location="cpu", weights_only=False) + print(f"[preflight] OK {p.name} step={ck.get('step')} bytes={p.stat().st_size}") + except Exception as e: + print(f"[preflight] CORRUPT {p.name} bytes={p.stat().st_size} -> deleting ({type(e).__name__}: {e})") + p.unlink() +for p in d.glob("*.tmp"): + print(f"[preflight] stale tmp {p.name} -> deleting"); p.unlink() +PY +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_expert_play W3s1 100000 --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_sub_20100.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_sub_20100.sh new file mode 100644 index 0000000000000000000000000000000000000000..2ba98b4aaab03f3b7afcfa18a42b4bf2b9110016 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_square_sub_20100.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 1 for square_sub_20100, so DF's square_sub_20100 row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_sub_20100 W3s1 100000 --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_threading.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_threading.sh new file mode 100644 index 0000000000000000000000000000000000000000..9c9e89637f963268c01f10e50a0eccfbe38c373e --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_threading.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# DF_VALUE run 21 (gen_q#282, 2026-09-24 21:4xZ). df_W3 = the ONLY DF arm that passes its own +# preregistered controls (threading mpc_disc H=50 argmax 0.1711+-0.0237 vs random-of-128 0.0489, +# t=7.00; `first` index-prior control tracks random; `argmin` 0.0133 < random < argmax = double +# dissociation). W3 differs from arm df_A by ONE flag: --chan-share '4:2:1' (DF's own published +# planning bundle share obs 57.1 / act 28.6 / rew 14.3, against df_A's uniform loss.mean() which +# gives the reward channel 0.064% of the gradient). W3 existed on only threading+mug, so the other +# five rows of the DF value column were being filled with df_A -- the arm already known to sit BELOW +# random. This payload fills one of those rows (or one seed replicate of the effect). +# Recipe copied verbatim from scripts/nb/packs/dfchan_{mug,threading}_W3.sh; only the task/cfg move. +# df_payload.sh skips a cell already at its target step, so this is resumable under preemption. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh threading_expert_play W3s1 100000 \ + --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play.sh new file mode 100644 index 0000000000000000000000000000000000000000..c9cfa2501a49cdfe11493901aba472dba6e7b569 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 1 for two_piece_expert_play, so DF's two_piece_expert_play row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play W3s1 100000 --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play_resume.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..74966443933e0c9c116f620ed7ed86e30b602921 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play_resume.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# FLAG_TOPUP run 10: finish two_piece_expert_play/df_W3s1, whose final ckpt_s100000.pt save was lost to the +# 11:10-11:40Z ENOSPC event. Preflight first (a truncated ckpt is loadable-looking but not +# loadable), then the VERBATIM run-7 payload -- train_df.py --resume defaults to 1. +set -uo pipefail +OUT=/proj/dmfexp/zwhong/rsm_rise/runs/two_piece_expert_play/wm/df_W3s1 +echo "[resume-preflight] $(date -u) $OUT" +/proj/dmfexp/zwhong/rsm_rise/venv_df/bin/python - "$OUT" <<'PY' +import sys, pathlib, torch +d = pathlib.Path(sys.argv[1]) +for p in sorted(d.glob("ckpt*.pt")): + try: + ck = torch.load(p, map_location="cpu", weights_only=False) + print(f"[preflight] OK {p.name} step={ck.get('step')} bytes={p.stat().st_size}") + except Exception as e: + print(f"[preflight] CORRUPT {p.name} bytes={p.stat().st_size} -> deleting ({type(e).__name__}: {e})") + p.unlink() +for p in d.glob("*.tmp"): + print(f"[preflight] stale tmp {p.name} -> deleting"); p.unlink() +PY +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play W3s1 100000 --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play_tipping.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play_tipping.sh new file mode 100644 index 0000000000000000000000000000000000000000..d21b917126628abc4ae84634c9ff3c54d9ec175f --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_play_tipping.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 1 for two_piece_expert_play_tipping, so DF's two_piece_expert_play_tipping row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play_tipping W3s1 100000 --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_suboptimal.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_suboptimal.sh new file mode 100644 index 0000000000000000000000000000000000000000..d789be9afdab88e12901541b1063d8d39ee13bff --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_suboptimal.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 1 for two_piece_expert_suboptimal, so DF's two_piece_expert_suboptimal row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_suboptimal W3s1 100000 --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_suboptimal_resume.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_suboptimal_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..c2ca0009268868ba796b75ff14281b20605855c6 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s1_two_piece_expert_suboptimal_resume.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# FLAG_TOPUP run 10: finish two_piece_expert_suboptimal/df_W3s1, whose final ckpt_s100000.pt save was lost to the +# 11:10-11:40Z ENOSPC event. Preflight first (a truncated ckpt is loadable-looking but not +# loadable), then the VERBATIM run-7 payload -- train_df.py --resume defaults to 1. +set -uo pipefail +OUT=/proj/dmfexp/zwhong/rsm_rise/runs/two_piece_expert_suboptimal/wm/df_W3s1 +echo "[resume-preflight] $(date -u) $OUT" +/proj/dmfexp/zwhong/rsm_rise/venv_df/bin/python - "$OUT" <<'PY' +import sys, pathlib, torch +d = pathlib.Path(sys.argv[1]) +for p in sorted(d.glob("ckpt*.pt")): + try: + ck = torch.load(p, map_location="cpu", weights_only=False) + print(f"[preflight] OK {p.name} step={ck.get('step')} bytes={p.stat().st_size}") + except Exception as e: + print(f"[preflight] CORRUPT {p.name} bytes={p.stat().st_size} -> deleting ({type(e).__name__}: {e})") + p.unlink() +for p in d.glob("*.tmp"): + print(f"[preflight] stale tmp {p.name} -> deleting"); p.unlink() +PY +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_suboptimal W3s1 100000 --chan-share '4:2:1' --seed 1 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_mug_expert_suboptimal.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_mug_expert_suboptimal.sh new file mode 100644 index 0000000000000000000000000000000000000000..69d72903ce57b3fa4063f8e4c62f212721e64739 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_mug_expert_suboptimal.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 2 for mug_expert_suboptimal, so DF's mug_expert_suboptimal row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh mug_expert_suboptimal W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_mug_expert_suboptimal_resume.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_mug_expert_suboptimal_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..d7c9fa4c0294ce09b0b26cb4b7916d827455b259 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_mug_expert_suboptimal_resume.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# FLAG_TOPUP run 10: finish mug_expert_suboptimal/df_W3s2, whose final ckpt_s100000.pt save was lost to the +# 11:10-11:40Z ENOSPC event. Preflight first (a truncated ckpt is loadable-looking but not +# loadable), then the VERBATIM run-7 payload -- train_df.py --resume defaults to 1. +set -uo pipefail +OUT=/proj/dmfexp/zwhong/rsm_rise/runs/mug_expert_suboptimal/wm/df_W3s2 +echo "[resume-preflight] $(date -u) $OUT" +/proj/dmfexp/zwhong/rsm_rise/venv_df/bin/python - "$OUT" <<'PY' +import sys, pathlib, torch +d = pathlib.Path(sys.argv[1]) +for p in sorted(d.glob("ckpt*.pt")): + try: + ck = torch.load(p, map_location="cpu", weights_only=False) + print(f"[preflight] OK {p.name} step={ck.get('step')} bytes={p.stat().st_size}") + except Exception as e: + print(f"[preflight] CORRUPT {p.name} bytes={p.stat().st_size} -> deleting ({type(e).__name__}: {e})") + p.unlink() +for p in d.glob("*.tmp"): + print(f"[preflight] stale tmp {p.name} -> deleting"); p.unlink() +PY +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh mug_expert_suboptimal W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_expert_play.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_expert_play.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a830e2033a4bf0f93e5866472c3bbdd07c37492 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_expert_play.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 2 for square_expert_play, so DF's square_expert_play row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_expert_play W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_expert_play_resume.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_expert_play_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..55f5de82190c4afcb963cd79448caaacbd71909f --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_expert_play_resume.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# FLAG_TOPUP run 10: finish square_expert_play/df_W3s2, whose final ckpt_s100000.pt save was lost to the +# 11:10-11:40Z ENOSPC event. Preflight first (a truncated ckpt is loadable-looking but not +# loadable), then the VERBATIM run-7 payload -- train_df.py --resume defaults to 1. +set -uo pipefail +OUT=/proj/dmfexp/zwhong/rsm_rise/runs/square_expert_play/wm/df_W3s2 +echo "[resume-preflight] $(date -u) $OUT" +/proj/dmfexp/zwhong/rsm_rise/venv_df/bin/python - "$OUT" <<'PY' +import sys, pathlib, torch +d = pathlib.Path(sys.argv[1]) +for p in sorted(d.glob("ckpt*.pt")): + try: + ck = torch.load(p, map_location="cpu", weights_only=False) + print(f"[preflight] OK {p.name} step={ck.get('step')} bytes={p.stat().st_size}") + except Exception as e: + print(f"[preflight] CORRUPT {p.name} bytes={p.stat().st_size} -> deleting ({type(e).__name__}: {e})") + p.unlink() +for p in d.glob("*.tmp"): + print(f"[preflight] stale tmp {p.name} -> deleting"); p.unlink() +PY +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_expert_play W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_sub_20100.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_sub_20100.sh new file mode 100644 index 0000000000000000000000000000000000000000..27ba804c6fa72cf73fbdc3914a2475bb13be336a --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_sub_20100.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 2 for square_sub_20100, so DF's square_sub_20100 row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_sub_20100 W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_sub_20100_resume.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_sub_20100_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..ce4274e896621977b97b71e06453b096283fba1a --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_square_sub_20100_resume.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# FLAG_TOPUP run 10: finish square_sub_20100/df_W3s2, whose final ckpt_s100000.pt save was lost to the +# 11:10-11:40Z ENOSPC event. Preflight first (a truncated ckpt is loadable-looking but not +# loadable), then the VERBATIM run-7 payload -- train_df.py --resume defaults to 1. +set -uo pipefail +OUT=/proj/dmfexp/zwhong/rsm_rise/runs/square_sub_20100/wm/df_W3s2 +echo "[resume-preflight] $(date -u) $OUT" +/proj/dmfexp/zwhong/rsm_rise/venv_df/bin/python - "$OUT" <<'PY' +import sys, pathlib, torch +d = pathlib.Path(sys.argv[1]) +for p in sorted(d.glob("ckpt*.pt")): + try: + ck = torch.load(p, map_location="cpu", weights_only=False) + print(f"[preflight] OK {p.name} step={ck.get('step')} bytes={p.stat().st_size}") + except Exception as e: + print(f"[preflight] CORRUPT {p.name} bytes={p.stat().st_size} -> deleting ({type(e).__name__}: {e})") + p.unlink() +for p in d.glob("*.tmp"): + print(f"[preflight] stale tmp {p.name} -> deleting"); p.unlink() +PY +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh square_sub_20100 W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_threading.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_threading.sh new file mode 100644 index 0000000000000000000000000000000000000000..6aaad736a9f427a479472224c16d3f2d57937ae9 --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_threading.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# DF_VALUE run 21 (gen_q#282, 2026-09-24 21:4xZ). df_W3 = the ONLY DF arm that passes its own +# preregistered controls (threading mpc_disc H=50 argmax 0.1711+-0.0237 vs random-of-128 0.0489, +# t=7.00; `first` index-prior control tracks random; `argmin` 0.0133 < random < argmax = double +# dissociation). W3 differs from arm df_A by ONE flag: --chan-share '4:2:1' (DF's own published +# planning bundle share obs 57.1 / act 28.6 / rew 14.3, against df_A's uniform loss.mean() which +# gives the reward channel 0.064% of the gradient). W3 existed on only threading+mug, so the other +# five rows of the DF value column were being filled with df_A -- the arm already known to sit BELOW +# random. This payload fills one of those rows (or one seed replicate of the effect). +# Recipe copied verbatim from scripts/nb/packs/dfchan_{mug,threading}_W3.sh; only the task/cfg move. +# df_payload.sh skips a cell already at its target step, so this is resumable under preemption. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh threading_expert_play W3s2 100000 \ + --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play.sh new file mode 100644 index 0000000000000000000000000000000000000000..9a6faecb17005b4bcb8c9b09af6b4c3bb55fdd1f --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 2 for two_piece_expert_play, so DF's two_piece_expert_play row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_resume.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..a89529e4e8ef56b14f66b6290edaa790bfdc471b --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_resume.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# FLAG_TOPUP run 10: finish two_piece_expert_play/df_W3s2, whose final ckpt_s100000.pt save was lost to the +# 11:10-11:40Z ENOSPC event. Preflight first (a truncated ckpt is loadable-looking but not +# loadable), then the VERBATIM run-7 payload -- train_df.py --resume defaults to 1. +set -uo pipefail +OUT=/proj/dmfexp/zwhong/rsm_rise/runs/two_piece_expert_play/wm/df_W3s2 +echo "[resume-preflight] $(date -u) $OUT" +/proj/dmfexp/zwhong/rsm_rise/venv_df/bin/python - "$OUT" <<'PY' +import sys, pathlib, torch +d = pathlib.Path(sys.argv[1]) +for p in sorted(d.glob("ckpt*.pt")): + try: + ck = torch.load(p, map_location="cpu", weights_only=False) + print(f"[preflight] OK {p.name} step={ck.get('step')} bytes={p.stat().st_size}") + except Exception as e: + print(f"[preflight] CORRUPT {p.name} bytes={p.stat().st_size} -> deleting ({type(e).__name__}: {e})") + p.unlink() +for p in d.glob("*.tmp"): + print(f"[preflight] stale tmp {p.name} -> deleting"); p.unlink() +PY +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_tipping.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_tipping.sh new file mode 100644 index 0000000000000000000000000000000000000000..55ba11d93302e1a9bd7d2814cf7acd24e96a03cd --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_tipping.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 2 for two_piece_expert_play_tipping, so DF's two_piece_expert_play_tipping row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play_tipping W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_tipping_resume.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_tipping_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..c9a94be6fdd806052ae40a9460dd83c772076b1d --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_play_tipping_resume.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# FLAG_TOPUP run 10: finish two_piece_expert_play_tipping/df_W3s2, whose final ckpt_s100000.pt save was lost to the +# 11:10-11:40Z ENOSPC event. Preflight first (a truncated ckpt is loadable-looking but not +# loadable), then the VERBATIM run-7 payload -- train_df.py --resume defaults to 1. +set -uo pipefail +OUT=/proj/dmfexp/zwhong/rsm_rise/runs/two_piece_expert_play_tipping/wm/df_W3s2 +echo "[resume-preflight] $(date -u) $OUT" +/proj/dmfexp/zwhong/rsm_rise/venv_df/bin/python - "$OUT" <<'PY' +import sys, pathlib, torch +d = pathlib.Path(sys.argv[1]) +for p in sorted(d.glob("ckpt*.pt")): + try: + ck = torch.load(p, map_location="cpu", weights_only=False) + print(f"[preflight] OK {p.name} step={ck.get('step')} bytes={p.stat().st_size}") + except Exception as e: + print(f"[preflight] CORRUPT {p.name} bytes={p.stat().st_size} -> deleting ({type(e).__name__}: {e})") + p.unlink() +for p in d.glob("*.tmp"): + print(f"[preflight] stale tmp {p.name} -> deleting"); p.unlink() +PY +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_play_tipping W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_suboptimal.sh b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_suboptimal.sh new file mode 100644 index 0000000000000000000000000000000000000000..13376b0e02310bb51f7ed56e58cd782c7872182e --- /dev/null +++ b/rsm_rise/scripts/nb/packs/gen/dfval_w3s2_two_piece_expert_suboptimal.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# FLAG_TOPUP: world-model SEED REPLICATE 2 for two_piece_expert_suboptimal, so DF's two_piece_expert_suboptimal row carries 3 trained +# world models like every other baseline carries 3 trained policies. Verbatim recipe of +# dfval_w3s1_threading.sh; only task/cfg/seed differ. +set -uo pipefail +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_payload.sh two_piece_expert_suboptimal W3s2 100000 --chan-share '4:2:1' --seed 2 diff --git a/rsm_rise/scripts/nb/poolcmp2_jobs/slot0.sh b/rsm_rise/scripts/nb/poolcmp2_jobs/slot0.sh new file mode 100644 index 0000000000000000000000000000000000000000..2ee7e9e2bf84e59ccdf53b075050f10532aaead9 --- /dev/null +++ b/rsm_rise/scripts/nb/poolcmp2_jobs/slot0.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# gen_q#274/#282 df_poolcmp2 slot 0 -- threading_expert_play df_A guidance 0.0, steps 20000 and 100000 (latest). +# DIAGNOSTIC ONLY (held-out, no env, no success number). RESUMABLE: existing JSONs are skipped. +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_poolcmp2_payload.sh threading_expert_play A 0.0 20000 100000 diff --git a/rsm_rise/scripts/nb/poolcmp2_jobs/slot1.sh b/rsm_rise/scripts/nb/poolcmp2_jobs/slot1.sh new file mode 100644 index 0000000000000000000000000000000000000000..88a1c358271321f4f2fdf320f4dd3faee7c5785d --- /dev/null +++ b/rsm_rise/scripts/nb/poolcmp2_jobs/slot1.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# gen_q#274/#282 df_poolcmp2 slot 1 -- threading_expert_play df_A guidance 5.0, steps 20000 and 100000 (latest). +# DIAGNOSTIC ONLY (held-out, no env, no success number). RESUMABLE: existing JSONs are skipped. +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_poolcmp2_payload.sh threading_expert_play A 5.0 20000 100000 diff --git a/rsm_rise/scripts/nb/poolcmp2_jobs/slot2.sh b/rsm_rise/scripts/nb/poolcmp2_jobs/slot2.sh new file mode 100644 index 0000000000000000000000000000000000000000..09e2ed9924370d97b063fbb8c0e51fd366a330f3 --- /dev/null +++ b/rsm_rise/scripts/nb/poolcmp2_jobs/slot2.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# gen_q#274/#282 df_poolcmp2 slot 2 -- mug_expert_suboptimal df_B guidance 0.0, steps 20000 and 100000 (latest). +# DIAGNOSTIC ONLY (held-out, no env, no success number). RESUMABLE: existing JSONs are skipped. +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_poolcmp2_payload.sh mug_expert_suboptimal B 0.0 20000 100000 diff --git a/rsm_rise/scripts/nb/poolcmp2_jobs/slot3.sh b/rsm_rise/scripts/nb/poolcmp2_jobs/slot3.sh new file mode 100644 index 0000000000000000000000000000000000000000..3476f0f6e6424d98b1e64638490b20e36f2c73fa --- /dev/null +++ b/rsm_rise/scripts/nb/poolcmp2_jobs/slot3.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# gen_q#274/#282 df_poolcmp2 slot 3 -- mug_expert_suboptimal df_B guidance 5.0, steps 20000 and 100000 (latest). +# DIAGNOSTIC ONLY (held-out, no env, no success number). RESUMABLE: existing JSONs are skipped. +exec bash /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_poolcmp2_payload.sh mug_expert_suboptimal B 5.0 20000 100000 diff --git a/rsm_rise/scripts/nb/poolcmp_jobs/pc_mug_g0.0.sh b/rsm_rise/scripts/nb/poolcmp_jobs/pc_mug_g0.0.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab65a81f921e1fd27e5565e01544a9cbf337ba45 --- /dev/null +++ b/rsm_rise/scripts/nb/poolcmp_jobs/pc_mug_g0.0.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_poolcmp_payload.sh mug_expert_suboptimal B 20000 0.0 --n-states 64 --n-plans 128 diff --git a/rsm_rise/scripts/nb/poolcmp_jobs/pc_mug_g5.0.sh b/rsm_rise/scripts/nb/poolcmp_jobs/pc_mug_g5.0.sh new file mode 100644 index 0000000000000000000000000000000000000000..f9dee1fd5177ebbf2f7ad7a581a5f3c71ddb0680 --- /dev/null +++ b/rsm_rise/scripts/nb/poolcmp_jobs/pc_mug_g5.0.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_poolcmp_payload.sh mug_expert_suboptimal B 20000 5.0 --n-states 64 --n-plans 128 diff --git a/rsm_rise/scripts/nb/poolcmp_jobs/pc_thr_g0.0.sh b/rsm_rise/scripts/nb/poolcmp_jobs/pc_thr_g0.0.sh new file mode 100644 index 0000000000000000000000000000000000000000..f9841832cebc9de49c338292b784a3f1c1039750 --- /dev/null +++ b/rsm_rise/scripts/nb/poolcmp_jobs/pc_thr_g0.0.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_poolcmp_payload.sh threading_expert_play A 20000 0.0 --n-states 64 --n-plans 128 diff --git a/rsm_rise/scripts/nb/poolcmp_jobs/pc_thr_g5.0.sh b/rsm_rise/scripts/nb/poolcmp_jobs/pc_thr_g5.0.sh new file mode 100644 index 0000000000000000000000000000000000000000..b851eef72e4364b4df1de8f9c08ca53e5b5bb24f --- /dev/null +++ b/rsm_rise/scripts/nb/poolcmp_jobs/pc_thr_g5.0.sh @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec /proj/dmfexp/zwhong/rsm_rise/scripts/nb/df_poolcmp_payload.sh threading_expert_play A 20000 5.0 --n-states 64 --n-plans 128 diff --git a/rsm_rise/scripts/nb/ref_crosscheck.sh b/rsm_rise/scripts/nb/ref_crosscheck.sh new file mode 100644 index 0000000000000000000000000000000000000000..542ac34640673fec6afed3c3af8a235c99efcd9a --- /dev/null +++ b/rsm_rise/scripts/nb/ref_crosscheck.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# gen_q#274 run 13 -- the two cross-checks the orchestrator asked for (2026-09-23 21:20Z) against the +# reference implementation in this account's counterfactual line. READ ONLY: this script never writes +# outside $ROOT. Regenerates status/nb/ref_crosscheck.txt from the reference tree, so every claim in the +# #274 comment is traceable to a grep anyone can re-run. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +REF=/proj/dmfexp/zwhong/wt-52-matched-epoch/scripts/training/td2_dfot_batched # newest, 2026-08-20 +OUT=$ROOT/status/nb/ref_crosscheck.txt +exec > >(tee "$OUT") 2>&1 +echo "REFERENCE CROSS-CHECK for gen_q#274 -- generated $(date -u +%Y-%m-%dT%H:%M:%SZ)" +echo "reference tree : $REF (read-only; the TD2-CFM x DFoT line, NOT robomimic)" +echo "our tree : $ROOT" +echo +echo "############ CHECK 1 -- DF hyper-parameters (guidance, sampling schedule, context/horizon) ############" +echo +echo "-- 1a. every occurrence of cfg_scale in the whole reference tree:" +grep -rn "cfg_scale" "$REF" || echo " (none)" +echo " ^ ONE hit, in sample_dfm's signature. Never read in the body: the Euler loop below uses no" +echo " unconditional branch and no scale." +echo +echo "-- 1b. the reference Euler sampling loop (train.py sample_dfm):" +sed -n '789,835p' "$REF/train.py" +echo +echo "-- 1c. reference DFoT noise probabilities (p_c = p_mask, p_d = p_mask_one):" +grep -rn -E "^\s*(p_mask|p_mask_one):" "$REF"/*.yaml +echo " ^ p_d (p_mask_one) = 0.0 => the UNCONDITIONAL branch is never trained, so classifier-free" +echo " guidance is structurally impossible in that line. That is why cfg_scale is dead code." +echo +echo "-- 1d. reference sampling step count, every config:" +grep -rn "n_sample_path_steps" "$REF"/*.yaml +echo +echo "-- 1e. OUR DF sampling / context settings:" +grep -n -E "sampling_timesteps|frame_stack|context_frames|stabilization_level|ddim_sampling_eta|objective:" \ + "$ROOT/code/diffusion_forcing/configurations/algorithm/df_base.yaml" \ + "$ROOT/code/diffusion_forcing/configurations/algorithm/df_planning.yaml" +echo +echo "-- 1f. OUR guidance objective and its weights (code/df_rise/df_plan.py):" +sed -n '24,27p;52,62p;100,106p' "$ROOT/code/df_rise/df_plan.py" +echo +echo "############ CHECK 2 -- the TD-squared objective ############" +echo +echo "-- 2a. reward / discount / critic anywhere in the reference TRAIN script:" +grep -cE "reward|discount|critic|value_head" "$REF/train.py" +echo " ^ 0 hits in train.py (the TD2-CFM x DFoT trainer)." +echo +echo "-- 2b. the only nearby hits, in the sibling train_bitd.py, and what they actually are:" +grep -n -iE "gamma|value" "$REF/train_bitd.py" | sed -n '1,8p' +echo " ^ 'gamma' there is a POSITIONAL CONFIDENCE weight (gamma^kdist, k = distance to the nearest" +echo " real token), and 'value(s)' means tensor contents. Neither is a discount factor or a critic." +echo +echo "CONCLUSION 2: the reference line has NO reward, NO discount and NO value head. Its 'TD2' is a" +echo "temporal-difference objective on the flow-matching DYNAMICS (TD2-CFM), not on a value function." +echo "It therefore cannot have hit or avoided our 1/(1-gamma) value ceiling, and offers no evidence" +echo "either way about our TD-MPC2 value-head saturation." + +echo +echo "############ CONCLUSION 1 -- tested against our OWN unguided cells ############" +echo +echo "The reference line's workable operating point IS 'no guidance' (p_d=0.0, cfg_scale dead code)." +echo "Our guidance sweep already contains that point: the g=0.0 arm sets gfn=None (df_plan.py:105), so" +echo "it is unguided sampling with the same model and the same 128 candidates. Those cells read:" +for f in "$ROOT"/runs/*/eval_onactor/df274/*g0.0*.json; do + case "$f" in *.diag.json) continue;; esac + python3 - "$f" <<'PY' +import json,sys,os +f=sys.argv[1]; d=json.load(open(f)) +g=f.replace('.json','.diag.json'); dg=json.load(open(g)) if os.path.exists(g) else {} +task=f.split('/runs/')[1].split('/')[0] +print(" %-28s %-46s succ %.3f J_mean %8.3f J_gain %+.4f" % ( + task, os.path.basename(f)[:46], d.get('success_rate',float('nan')), + dg.get('J_mean',float('nan')), dg.get('J_gain',float('nan')))) +PY +done +echo +echo "So the 'our guidance scale is out of the workable range' explanation is REFUTED by our own data:" +echo "at the reference line's own configuration -- no guidance at all -- DF still scores 0.000 on both" +echo "tasks and both gammas. The one remaining hyper-parameter difference is the sampling step count" +echo "(ours 50 DDIM steps, theirs a pinned 10 Euler steps), and ours is the LARGER, i.e. the safer," +echo "direction, so it is not a cheap explanation either. DF's 0.000 is not a guidance-tuning artifact." +echo "It remains UNREPORTABLE regardless until the maze2d reproduction gate passes." diff --git a/rsm_rise/scripts/nb/requeue_orphans.sh b/rsm_rise/scripts/nb/requeue_orphans.sh new file mode 100644 index 0000000000000000000000000000000000000000..c20f9e9b1b83783260e73754c9c22dfa947d967a --- /dev/null +++ b/rsm_rise/scripts/nb/requeue_orphans.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# gen_q#274 run 22: re-append a queue's ORPHANS -- payloads in .taken with no .done entry. +# +# WHY. pack_drain2.sh hands out each index exactly once (the cursor only moves forward), which is +# correct while a worker lives and wrong the moment one dies. On the preemptable queue workers die +# constantly, and a payload killed between its `.taken` line and its `.done` line becomes UNREACHABLE +# for the rest of that queue's life: no worker will ever be issued its index again. Measured twice on +# 2026-09-24 -- q_nb21_td.txt had all 5 payloads taken, ZERO done, and a cursor of 12; and DF's +# nb_slot_df_repro_lb8.sh was orphaned by 1886907 (EXIT 130) while its queue ran on past it. +# +# Appending is the safe repair, not rewriting: pack_drain2.sh re-reads the queue's length every +# iteration, so attached workers pick up the appended lines with no restart, and every payload is +# idempotent (each skips on its own output JSON), so a payload that actually DID finish its work +# before dying costs one cheap skip rather than a re-measurement. +# +# usage: requeue_orphans.sh [--apply] (default: DRY RUN, prints what it would add) +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +Q=${1:?usage: requeue_orphans.sh [--apply]} +APPLY=${2:-} +case "$Q" in /*) ;; *) Q=$ROOT/$Q;; esac +[ -f "$Q" ] || { echo "[requeue] no queue file $Q"; exit 2; } +[ -f "$Q.taken" ] || { echo "[requeue] $Q has no .taken -- nothing has run yet, nothing to repair"; exit 0; } + +# .taken lines are " "; .done lines are " rc= ". Match on the INDEX, not the +# path: the same payload can legitimately appear at two indices (a deliberate re-queue), and each of +# those is separately reachable or not. +done_idx=$(awk '{print $1}' "$Q.done" 2>/dev/null | sort -u) +n_add=0; add=() +while read -r idx path; do + [ -n "${path:-}" ] || continue + if ! printf '%s\n' "$done_idx" | grep -qx -- "$idx"; then + # Still reachable? Only if some worker is alive and the cursor has not passed it -- but a taken + # index is BY DEFINITION already past the cursor, so an orphan is orphaned whether or not the + # queue is still draining. A payload currently RUNNING is also listed here; re-appending it is + # harmless (the duplicate run skips on the output JSON, or the two runs race on a .tmp the same + # way two workers already could) and is strictly better than losing the cell to a later kill. + add+=("$path"); n_add=$((n_add + 1)) + echo "[requeue] ORPHAN idx=$idx $path" + fi +done < <(sort -u -k1,1n "$Q.taken") + +if [ "$n_add" = 0 ]; then echo "[requeue] $Q: no orphans (taken all accounted for in .done)"; exit 0; fi + +# TWO WAYS THIS TOOL CAN DO HARM, AND THE GUARDS FOR BOTH. Both were caught by its own first dry run +# (q_nb17_df, 2026-09-24 01:52Z), which flagged 9 "orphans" of which 8 were simply RUNNING. +# +# (1) A payload that is still running is indistinguishable from one that died: both are in .taken and +# neither is in .done. So a queue with LIVE workers must not be repaired -- wait until its packs +# are gone. Refuse unless --force says the caller has checked bjobs. +# (2) A payload already re-appended by hand sits at an index at or after the cursor, still unissued. +# Appending it again would run the same cell twice. Drop anything already pending. +CUR=$(cat "$Q.cursor" 2>/dev/null || echo 0) +NQ=$(wc -l < "$Q") +pending=$(sed -n "$((CUR + 1)),\$p" "$Q" 2>/dev/null | sort -u) +keep=(); n_keep=0 +for pth in "${add[@]}"; do + if printf '%s\n' "$pending" | grep -qxF -- "$pth"; then + echo "[requeue] SKIP already pending at an index >= cursor ($CUR): $pth" + else + keep+=("$pth"); n_keep=$((n_keep + 1)) + fi +done +add=("${keep[@]:-}"); n_add=$n_keep +[ "$n_add" = 0 ] && { echo "[requeue] $Q: every orphan is already pending -- nothing to do"; exit 0; } + +LIVE=$(bjobs -o "job_name stat" -noheader 2>/dev/null | awk '$2=="RUN"||$2=="PEND"||$2=="SSUSP"{print $1}' | grep -c "^rr_" || true) +if [ "${3:-}" != "--force" ] && [ "${LIVE:-0}" -gt 0 ]; then + echo "[requeue] $LIVE live rr_* job(s). A RUNNING payload looks exactly like a dead one here, so" + echo "[requeue] this refuses to append while any pack may still be attached to $Q." + echo "[requeue] Check 'bjobs' for the packs draining THIS queue; when none are left, add --force." + echo "[requeue] Candidates it would have added ($n_add):"; printf ' %s\n' "${add[@]}" + exit 0 +fi +if [ "$APPLY" != "--apply" ]; then + echo "[requeue] DRY RUN: would append $n_add line(s) to $Q (now $NQ). Re-run with --apply." + exit 0 +fi +printf '%s\n' "${add[@]}" >> "$Q" +echo "[requeue] appended $n_add line(s); $Q is now $(wc -l < "$Q") lines, cursor $(cat "$Q.cursor" 2>/dev/null || echo 0)" diff --git a/rsm_rise/scripts/nb/resume_audit.py b/rsm_rise/scripts/nb/resume_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..5643e511332f86772afeab36f1c38cadc43187e1 --- /dev/null +++ b/rsm_rise/scripts/nb/resume_audit.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python +"""Project-wide audit: do RESUMED eval cells report planner health over ALL +episodes, or only over the post-resume suffix? + +Motivation (#274, run 48-main). `status/nb/df_resume_verify.json` landed with +a defect reference: a cell that resumed at episode 44 carried diag plans=300 +(= 6 episodes worth) while the same column measured fresh carries plans=2500 +(= 50 episodes worth). If that is general, then every HEALTH number we publish +beside a resumed cell's score is computed on a SUFFIX of the episodes, while +the score itself is computed on all 50. The score and its health number would +then not describe the same rollouts. This audit decides it by measurement. + +For every eval cell JSON it computes + expected_all = sum over ALL episodes of ceil(length / execute_frames) + expected_suffix = the same sum over episodes[resumed_from_episode:] +and compares the diagnostics' own `plans` count against both. + +Verdicts are COMPUTED, never asserted: + FULL plans within tol of expected_all -> health covers the whole cell + SUFFIX plans within tol of expected_suffix -> health covers only the tail + OTHER neither -> printed in full, not hidden +Publish-or-refuse: writes nothing if it cannot compute the invariant. + +run 54-main (2026-09-25). Until this run the audit asked EVERY cell for a planner +`diag` and `continue`d when there was none. All 22 cfg(a) shared-candidate cells -- +the flagship column -- have no diag by construction (they SCORE a candidate set, they +do not plan), so they were dropped from the auditable set SILENTLY: the printed +"cells with episode lengths + diag" line shrank and nothing said which cells left or +why. That is the worst of the three available behaviours, because those cells resume +constantly (one of them resumes at episode 22 of 50) and they are precisely the cells +whose health numbers sit beside the flagship score. + +So this file now computes the count from EITHER source, and the fallback -- summing +`episodes[i].plan.steps` -- is written out HERE, independently, and is deliberately +NOT imported from scripts/nb/resume_cov.py even though that module exports the same +invariant. resume_cov is the ONE implementation the BUILDERS gate on; this file is a +SECOND, independent one, kept so that a drift in either is detectable. Two copies +that agree are evidence; one copy is an assertion. scripts/nb/resume_xcheck.py +compares the two cell-by-cell and REFUSES on any disagreement -- that cross-check is +the whole reason this duplication is allowed to exist, so if you delete one copy you +must delete the cross-check and say in the report that the invariant is now unchecked. +""" +import json, math, os, sys, glob, collections + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +OUT = os.path.join(ROOT, "status/nb/resume_audit") +TOL = 0.02 # relative + +def diag_for(path, cell): + sib = path[:-5] + ".diag.json" + if os.path.exists(sib): + try: + return json.load(open(sib)), "sidecar" + except Exception: + return None, "sidecar_unreadable" + for k in ("diag", "planner_diag", "plan_diag"): + if isinstance(cell.get(k), dict): + return cell[k], "inline" + return None, "none" + + +def steps_from_plan_blocks(cell): + """Independent re-implementation of the scoring-cell count (see the module docstring). + + cfg(a) cells carry their decision count per episode as `episodes[i].plan.steps`. + Episodes with NO plan block contribute 0 ON PURPOSE: a cell whose health covers only + its post-resume tail must come out SUFFIX, not be waved through to FULL by having the + missing episodes quietly excluded from the denominator too. + Returns (steps, n_episodes_with_a_block) or (None, 0) when no episode carries one. + """ + eps = cell.get("episodes") + if not isinstance(eps, list) or not eps: + return (None, 0) + steps, seen = 0, 0 + for e in eps: + pb = (e or {}).get("plan") if isinstance(e, dict) else None + if not isinstance(pb, dict): + continue + try: + steps += int(pb.get("steps") or 0) + except (TypeError, ValueError): + continue + seen += 1 + if seen == 0: + return (None, 0) + return (steps, seen) + +def main(): + files = sorted(glob.glob(os.path.join(ROOT, "runs/*/eval_onactor/*/*.json"))) + files = [f for f in files if not f.endswith(".diag.json")] + rows, n_read, n_bad = [], 0, 0 + # Every cell that does NOT reach the auditable set is counted under the reason it fell + # out, and the reasons are exhaustive and mutually exclusive. Before run 54 this was a + # bare `continue` and 22 flagship cells vanished without a line of explanation. + excl = collections.Counter() + excl_ex = collections.defaultdict(list) + def drop(reason, path): + excl[reason] += 1 + if len(excl_ex[reason]) < 6: + excl_ex[reason].append(os.path.relpath(path, ROOT)) + for f in files: + try: + c = json.load(open(f)) + except Exception: + n_bad += 1 + continue + n_read += 1 + eps = c.get("episodes") + if not isinstance(eps, list) or not eps: + drop("no per-episode list", f) + continue + d, src = diag_for(f, c) + chunk_cell = (c.get("planner") or {}).get("plan_chunk") + if isinstance(d, dict) and "plans" in d: + try: + plans = int(d["plans"]) + chunk = int(d.get("execute_frames") or chunk_cell) + except (TypeError, ValueError): + drop("diag present but plans/chunk unparseable", f) + continue + count_src = src # "sidecar" | "inline" + blocks_seen = None + else: + # cfg(a) scoring cell: no planner diag by construction. Independent fallback. + plans, blocks_seen = steps_from_plan_blocks(c) + if plans is None: + drop("no diag and no per-episode plan block", f) + continue + try: + chunk = int(chunk_cell) + except (TypeError, ValueError): + drop("plan blocks present but plan_chunk unparseable", f) + continue + count_src = "plan_blocks" + if chunk <= 0: + drop("non-positive execute chunk", f) + continue + r = int(c.get("resumed_from_episode") or 0) + lens = [int(e.get("length") or 0) for e in eps if isinstance(e, dict)] + if len(lens) != len(eps) or min(lens) <= 0: + drop("missing or non-positive episode length", f) + continue + exp_all = sum(math.ceil(L / chunk) for L in lens) + exp_suf = sum(math.ceil(L / chunk) for L in lens[r:]) if r else exp_all + def near(a, b): + return b > 0 and abs(a - b) <= max(1, TOL * b) + if near(plans, exp_all): + v = "FULL" + elif r > 0 and near(plans, exp_suf): + v = "SUFFIX" + else: + v = "OTHER" + rows.append(dict(path=os.path.relpath(f, ROOT), task=c.get("task"), + cell=c.get("cell"), col=os.path.basename(os.path.dirname(f)), + resumed_from=r, n_ep=len(eps), chunk=chunk, + plans=plans, expected_all=exp_all, expected_suffix=exp_suf, + frac_of_full=round(plans / exp_all, 4) if exp_all else None, + success_rate=c.get("success_rate"), diag_src=src, + count_src=count_src, blocks_seen=blocks_seen, verdict=v)) + if not rows: + sys.stderr.write("REFUSE: no cell carried both episode lengths and a decision count\n") + return 2 + + byv = collections.Counter(r["verdict"] for r in rows) + resumed = [r for r in rows if r["resumed_from"] > 0] + suffix = [r for r in rows if r["verdict"] == "SUFFIX"] + other = [r for r in rows if r["verdict"] == "OTHER"] + res_full = [r for r in resumed if r["verdict"] == "FULL"] + + L = [] + A = L.append + A("RESUME-TRUNCATION AUDIT OF PLANNER HEALTH (gen_q #274, run 48-main)") + A("builder scripts/nb/resume_audit.py tolerance %.0f%% on the plan count" % (100 * TOL)) + A("") + A("QUESTION: when an eval cell RESUMES from .partial_best, does the planner") + A("health it publishes (J_mean / J_spread / J_gain / plans) cover all the") + A("episodes the SCORE covers, or only the post-resume tail?") + A("") + A("cells scanned %6d (%d unreadable)" % (n_read, n_bad)) + A("cells in the AUDITABLE SET %6d" % len(rows)) + bysrc = collections.Counter(r["count_src"] for r in rows) + A(" decision count from planner diag %5d (cfg(b) planner cells and every other column)" + % (bysrc.get("sidecar", 0) + bysrc.get("inline", 0))) + A(" decision count from plan blocks %5d (cfg(a) shared-candidate cells, which have no" + % bysrc.get("plan_blocks", 0)) + A(" planner diag BY CONSTRUCTION -- they score a") + A(" candidate set, they do not plan)") + A(" of those, RESUMED (k>0) %6d" % len(resumed)) + A("") + A("CELLS NOT IN THE AUDITABLE SET, by reason (exhaustive; before run 54 these were a") + A("silent `continue` and the 22 cfg(a) cells fell out here without a word):") + if excl: + for reason, n in excl.most_common(): + A(" %5d %s" % (n, reason)) + for ex in excl_ex[reason]: + A(" e.g. %s" % ex) + else: + A(" (none -- every scanned cell with episodes was auditable)") + A("") + A("VERDICTS OVER THE AUDITABLE SET, SPLIT BY WHERE THE COUNT CAME FROM") + A(" (split deliberately: a defect in the run-54 plan-block branch must not be able to") + A(" hide inside a pooled total dominated by the long-standing diag branch)") + A(" %-12s %6s %6s %6s %6s" % ("count src", "FULL", "SUFFIX", "OTHER", "all")) + for src_k, label in (("diag", "diag"), ("plan_blocks", "plan_blocks")): + sub = [r for r in rows if (r["count_src"] == "plan_blocks") == (src_k == "plan_blocks")] + if not sub: + continue + c = collections.Counter(r["verdict"] for r in sub) + A(" %-12s %6d %6d %6d %6d" % (label, c.get("FULL", 0), c.get("SUFFIX", 0), + c.get("OTHER", 0), len(sub))) + A(" %-12s %6d %6d %6d %6d" % ("TOTAL", byv.get("FULL", 0), byv.get("SUFFIX", 0), + byv.get("OTHER", 0), len(rows))) + A("") + if resumed: + A("VERDICTS OVER THE RESUMED CELLS ONLY (the ones at risk)") + A(" FULL %5d health covers every episode the score covers" % len(res_full)) + A(" SUFFIX %5d health covers only episodes [k:], the score covers [0:]" % len(suffix)) + A(" OTHER %5d" % len([r for r in resumed if r["verdict"] == "OTHER"])) + A("") + if suffix: + A("TRUNCATED CELLS -- every health number below is computed on a SUBSET") + A(" %-28s %-22s k/n plans exp_all exp_suf succ" % ("column", "task")) + for r in sorted(suffix, key=lambda r: -r["resumed_from"])[:60]: + A(" %-28s %-22s %3d/%-3d %5d %6d %6d %s" + % (r["col"][:28], str(r["task"])[:22], r["resumed_from"], r["n_ep"], + r["plans"], r["expected_all"], r["expected_suffix"], r["success_rate"])) + if len(suffix) > 60: + A(" ... %d more, all in the json" % (len(suffix) - 60)) + else: + A("NO TRUNCATED CELL FOUND. Every resumed cell in the auditable set") + A("carries a plan count consistent with ALL of its episodes, so resume") + A("CARRIES THE HEALTH FORWARD and the published health numbers describe") + A("the same rollouts as the published scores.") + A("") + if other: + A("OTHER (neither full nor a clean suffix) -- listed, not hidden") + A(" %-28s %-22s k/n plans exp_all exp_suf" % ("column", "task")) + for r in sorted(other, key=lambda r: -abs(r["frac_of_full"] or 0))[:40]: + A(" %-28s %-22s %3d/%-3d %5d %6d %6d" + % (r["col"][:28], str(r["task"])[:22], r["resumed_from"], r["n_ep"], + r["plans"], r["expected_all"], r["expected_suffix"])) + if len(other) > 40: + A(" ... %d more, all in the json" % (len(other) - 40)) + A("") + A("LIMIT OF THIS AUDIT: it checks the COVERAGE of the health numbers, not") + A("whether a resumed cell reproduces a fresh one. That is the separate") + A("df_resume_verify gate, which at 2026-09-24 21:36Z is still OPEN: its") + A("leg A itself resumed (from episode 15), so 'resumed == fresh' is not") + A("yet proven -- only 'resume at 15 == resume at 20', which it passed on") + A("all ten substantive checks.") + + txt = "\n".join(L) + "\n" + open(OUT + ".txt", "w").write(txt) + json.dump(dict(n_scanned=n_read, n_unreadable=n_bad, n_auditable=len(rows), + n_resumed=len(resumed), counts=dict(byv), tol=TOL, + excluded=dict(excl), excluded_examples={k: v for k, v in excl_ex.items()}, + by_count_source=dict(collections.Counter(r["count_src"] for r in rows)), + rows=rows), + open(OUT + ".json", "w"), indent=1) + sys.stdout.write(txt) + return 0 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/nb/resume_cov.py b/rsm_rise/scripts/nb/resume_cov.py new file mode 100644 index 0000000000000000000000000000000000000000..618840293e42d5122da925d7a034855f1a77dd7f --- /dev/null +++ b/rsm_rise/scripts/nb/resume_cov.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""THE ONE implementation of the health-coverage invariant for gen_q#274. + +run 51-main (2026-09-25). This function existed in THREE places -- scripts/nb/td_table.py, +scripts/nb/resume_audit.py, and (as of this run) it was about to be pasted into a fourth, +scripts/nb/df_table.py. Three copies of a gate is three chances for one of them to drift and +declare a cell quotable that another copy refuses. The function is now defined once, here, and +imported by every builder that needs it; the copies in td_table.py and resume_audit.py are replaced +by that import, and td_table.py's published output is gated byte-for-byte against its pre-refactor +text so this move cannot have changed a single number. + +The invariant is INTRINSIC -- it needs no log, no mtime and no job id. It asks a cell's own +diagnostics how many plan decisions they accumulated, and compares that against the number the +cell's own per-episode lengths imply. +""" +import math + + +def plan_count(cell, diag): + """Return (plans, chunk, source) for a cell, or (None, None, None) if not computable. + + run 52-main (2026-09-25). There are TWO classes of #274 cell and they publish their health in + two different places, because they do two different things: + + * cfg(b) PLANNER cells (MPPI/CEM, `-plan-Ntd...`) accumulate planner diagnostics into a + sibling `.diag.json` with a `plans` count. + * cfg(a) SHARED-CANDIDATE cells (`-tdq-128-`, argmax/random) do not plan -- they SCORE a + candidate set that the proposer supplies -- so there is no planner to write a diag. Their + health is the per-episode `plan` block inside the cell JSON itself (the block + scripts/nb/nb274_health.py reads to produce ties-at-max / score CV / score spread), and + `plan.steps` is that episode's decision count: the exact analogue of the diag's `plans`. + + Asking a cfg(a) cell for a diag it was never designed to write is not a health failure, it is + the wrong question. Before this function existed, assert_health_covers.py asked exactly that + question and QUARANTINED every cfg(a) cell it was pointed at -- see run 52-main's report. + The COMPARISON is unchanged: whichever source the count comes from, it is still measured + against the count the cell's own per-episode lengths imply, at the same 2% tolerance. + """ + eps = cell.get("episodes") + if not isinstance(eps, list) or not eps: + return (None, None, None) + chunk_cell = (cell.get("planner") or {}).get("plan_chunk") + if isinstance(diag, dict) and "plans" in diag: + chunk = diag.get("execute_frames") or chunk_cell + try: + chunk = int(chunk) + plans = int(diag["plans"]) + except Exception: + return (None, None, None) + return (plans, chunk, "diag") + # No planner diag: fall back to the per-episode plan blocks the cell carries itself. Episodes + # WITHOUT a plan block contribute 0, deliberately -- a cell whose health covers only its tail + # must still come out SUFFIX rather than being waved through. + steps, seen = 0, 0 + for e in eps: + pb = (e or {}).get("plan") + if isinstance(pb, dict): + try: + steps += int(pb.get("steps") or 0) + except Exception: + return (None, None, None) + seen += 1 + if seen == 0: + return (None, None, None) + try: + chunk = int(chunk_cell) + except Exception: + return (None, None, None) + return (steps, chunk, "episode_plan_blocks") + + +def resume_coverage(cell, diag): + """run 48-main, gen_q#274 -- does this cell's published planner HEALTH cover the + same episodes its published SCORE covers? + + FINDING AJ (stream DF_MAKEITWORK, eval.py:1179-1203): before 2026-09-24 20:36Z an + episode-level resume carried the env's numpy state but not the planner's own + generator or its health accumulators. A resumed cell therefore (i) replayed the + right initial states with the WRONG plan noise on its tail and (ii) published + health over episodes [k:] only, while its success rate covers [0:]. The two + numbers on such a row do not describe the same rollouts. + + The test is INTRINSIC -- it needs no log and no mtime: compare the diagnostics' + own `plans` count against the count implied by the episode lengths. + FULL plans ~ all episodes -> health and score agree on coverage + SUFFIX plans ~ episodes[k:] only -> tail-only health; NOT quotable + OTHER neither -> reported, never silently passed + Returns None when the invariant cannot be computed (no diag, no lengths), so a + missing measurement is never rendered as a pass. + """ + eps = cell.get("episodes") + if not isinstance(eps, list) or not eps: + return None + plans, chunk, source = plan_count(cell, diag) + if plans is None or not chunk or chunk <= 0: + return None + lens = [int((e or {}).get("length") or 0) for e in eps] + if not lens or min(lens) <= 0: + return None + k = int(cell.get("resumed_from_episode") or 0) + exp_all = sum(math.ceil(L / chunk) for L in lens) + exp_suf = sum(math.ceil(L / chunk) for L in lens[k:]) if k else exp_all + near = lambda a, b: b > 0 and abs(a - b) <= max(1, 0.02 * b) + v = "FULL" if near(plans, exp_all) else ( + "SUFFIX" if (k > 0 and near(plans, exp_suf)) else "OTHER") + return {"verdict": v, "resumed_from": k, "n_ep": len(eps), "plans": plans, + "expected_all": exp_all, "expected_suffix": exp_suf, "plan_count_source": source, + "coverage": round(plans / exp_all, 4) if exp_all else None} diff --git a/rsm_rise/scripts/nb/resume_xcheck.py b/rsm_rise/scripts/nb/resume_xcheck.py new file mode 100644 index 0000000000000000000000000000000000000000..77019d98927e5b2159285262f85c9c76019c3670 --- /dev/null +++ b/rsm_rise/scripts/nb/resume_xcheck.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +"""gen_q#274 run 54-main -- CROSS-CHECK THE TWO INDEPENDENT COPIES OF THE HEALTH-COVERAGE INVARIANT. + +The project deliberately carries two implementations of one invariant: + + * scripts/nb/resume_cov.py `plan_count` / `resume_coverage` -- THE copy the table + BUILDERS import and gate on (td_table.py, df_table.py, gate_sweep.py, + assert_health_covers.py). + * scripts/nb/resume_audit.py its own, written out longhand, used only by the audit. + +Duplication is normally a defect, and run 51-main removed two other copies for exactly that +reason. These two are kept ON THE CONDITION THAT SOMETHING COMPARES THEM, because the +invariant decides whether a health number may be published beside a score, and a lone +implementation of a gate is an assertion rather than evidence. This script is that condition. + +It recomputes both, cell by cell, over the same file list, and prints every disagreement. +It exits: + 0 the two agree on every cell they can both compute -> duplication is earning its keep + 1 they disagree somewhere -> REFUSE; one of them has drifted + 2 it could not run the comparison at all -> REFUSE; a vacuous pass is not a pass +DISAGREEMENT INCLUDES the case where one copy computes a verdict and the other declines to: +that is precisely the run-52/53/54 defect class (a copy asking a cell for a diag it was never +designed to write), so it is reported as a disagreement and not filtered out. +""" +import json, os, sys, glob, collections + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +sys.path.insert(0, os.path.join(ROOT, "scripts/nb")) + +import resume_cov # copy A: the builders' copy +import resume_audit # copy B: the audit's own + + +def main(): + files = [f for f in sorted(glob.glob(os.path.join(ROOT, "runs/*/eval_onactor/*/*.json"))) + if not f.endswith(".diag.json")] + if not files: + sys.stderr.write("REFUSE: no eval cell JSON found at all\n") + return 2 + + rows, agree, disagree, both_decline = [], 0, 0, 0 + for f in files: + try: + c = json.load(open(f)) + except Exception: + continue + if not isinstance(c.get("episodes"), list) or not c["episodes"]: + continue + d, _src = resume_audit.diag_for(f, c) + + # copy A + a = resume_cov.resume_coverage(c, d) + a_v = a["verdict"] if a else None + a_plans = a["plans"] if a else None + a_src = a["plan_count_source"] if a else None + + # copy B, recomputed here from resume_audit's own primitives so that this script + # does not just re-read resume_audit's output file (which would make the check + # circular: a stale .json would then "agree" with anything). + b_v, b_plans, b_src = _copy_b(c, d) + + if a_v is None and b_v is None: + both_decline += 1 + continue + ok = (a_v == b_v) and (a_plans == b_plans) + rows.append(dict(path=os.path.relpath(f, ROOT), task=c.get("task"), + cell=c.get("cell"), col=os.path.basename(os.path.dirname(f)), + a_verdict=a_v, b_verdict=b_v, a_plans=a_plans, b_plans=b_plans, + a_source=a_src, b_source=b_src, agree=ok)) + if ok: + agree += 1 + else: + disagree += 1 + + if agree + disagree == 0: + sys.stderr.write("REFUSE: not one cell was computable by EITHER copy -- " + "nothing was compared, so this is not a pass\n") + return 2 + + L = [] + A = L.append + A("TWO-IMPLEMENTATION CROSS-CHECK OF THE HEALTH-COVERAGE INVARIANT (gen_q#274, run 54-main)") + A("builder scripts/nb/resume_xcheck.py") + A("") + A("copy A scripts/nb/resume_cov.py imported by every table builder; the gating copy") + A("copy B scripts/nb/resume_audit.py the audit's own longhand implementation") + A("A verdict is compared only where at least one copy produces one. A cell where ONE copy") + A("computes and the other DECLINES counts as a DISAGREEMENT, because that asymmetry is the") + A("exact defect class of runs 52-54 (a copy asking a scoring cell for a planner diag).") + A("") + A("cells where at least one copy computed %6d" % (agree + disagree)) + A(" AGREE (same verdict AND same count) %6d" % agree) + A(" DISAGREE %6d" % disagree) + A("cells both copies declined (not compared, not a failure) %6d" % both_decline) + A("") + bysrc = collections.Counter((r["a_source"], r["b_source"]) for r in rows) + A("COUNT-SOURCE PAIRING (A, B) over the compared cells -- both copies should choose the") + A("same source for the same cell, and 'episode_plan_blocks' vs 'plan_blocks' is the SAME") + A("source under two names (the cfg(a) branch):") + for (sa, sb), n in bysrc.most_common(): + A(" %6d A=%-22s B=%s" % (n, sa, sb)) + A("") + if disagree: + A("!! THE TWO COPIES DISAGREE. REFUSING to certify the invariant. Every case:") + A(" %-26s %-22s %-8s %-8s %8s %8s" % ("column", "task", "A", "B", "A plans", "B plans")) + for r in rows: + if r["agree"]: + continue + A(" %-26s %-22s %-8s %-8s %8s %8s" + % (str(r["col"])[:26], str(r["task"])[:22], r["a_verdict"], r["b_verdict"], + r["a_plans"], r["b_plans"])) + else: + A("THE TWO COPIES AGREE ON EVERY COMPARED CELL, on both the verdict and the underlying") + A("decision count. The invariant is therefore corroborated by an implementation that") + A("the table builders do not use, which is the only reason the duplication is kept.") + txt = "\n".join(L) + "\n" + open(os.path.join(ROOT, "status/nb/resume_xcheck.txt"), "w").write(txt) + json.dump(dict(n_compared=agree + disagree, n_agree=agree, n_disagree=disagree, + n_both_declined=both_decline, rows=rows), + open(os.path.join(ROOT, "status/nb/resume_xcheck.json"), "w"), indent=1) + sys.stdout.write(txt) + return 1 if disagree else 0 + + +def _copy_b(c, d): + """Run resume_audit's OWN logic, reusing its primitives, without reading its output.""" + import math + chunk_cell = (c.get("planner") or {}).get("plan_chunk") + if isinstance(d, dict) and "plans" in d: + try: + plans = int(d["plans"]) + chunk = int(d.get("execute_frames") or chunk_cell) + except (TypeError, ValueError): + return (None, None, None) + src = "diag" + else: + plans, _seen = resume_audit.steps_from_plan_blocks(c) + if plans is None: + return (None, None, None) + try: + chunk = int(chunk_cell) + except (TypeError, ValueError): + return (None, None, None) + src = "plan_blocks" + if not chunk or chunk <= 0: + return (None, None, None) + eps = c["episodes"] + lens = [int((e or {}).get("length") or 0) for e in eps] + if len(lens) != len(eps) or min(lens) <= 0: + return (None, None, None) + k = int(c.get("resumed_from_episode") or 0) + exp_all = sum(math.ceil(L / chunk) for L in lens) + exp_suf = sum(math.ceil(L / chunk) for L in lens[k:]) if k else exp_all + near = lambda a, b: b > 0 and abs(a - b) <= max(1, 0.02 * b) + v = "FULL" if near(plans, exp_all) else ( + "SUFFIX" if (k > 0 and near(plans, exp_suf)) else "OTHER") + return (v, plans, src) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/nb/run_dir_lock.sh b/rsm_rise/scripts/nb/run_dir_lock.sh new file mode 100644 index 0000000000000000000000000000000000000000..6aa0bd7b7ae9ad3928d0090da2e3ecc549d2e4bd --- /dev/null +++ b/rsm_rise/scripts/nb/run_dir_lock.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env bash +# Single-writer lock on a run directory, shared by the gen_q#274 DF payloads. +# Source this file and call: rr_take_run_dir_lock +# Returns 0 when the lock is held by this process; exits 9 when another LIVE job owns it. +# +# WHY THIS FILE EXISTS -- DEFECT 15, MEASURED 2026-09-24 19:40Z (gen_q#274, main session). +# The previous in-payload lock did not merely fail to stop a second writer; it ACTIVELY GRANTED the +# lock to one, which is worse than having no lock at all, because both jobs then believed they were +# the sole writer. Verbatim from the two logs, one second apart, same run dir +# runs/df_repro/maze2d_medium_p4a2, the run that gates the whole DF column: +# SLURM 42145, 19:25:49 "took run-dir lock ... (job 1312865)" +# LSF 1903044, 19:25:50 "lock held by job '1312865' which is not live -- stale, taking over" +# TWO INDEPENDENT BUGS, both fixed here: +# (1) SCHEDULER-BLIND IDENTITY. The holder wrote `${LSB_JOBID:-$$}`. On a SLURM node LSB_JOBID is +# unset, so the id recorded was a PID (1312865). The LSF challenger had `bjobs`, asked it about +# 1312865, got no such LSF job, and concluded the live holder was dead. An id with no scheduler +# attached is not an identity: 1312865 is a valid LSF job id AND a valid pid AND a valid SLURM +# id, and the three namespaces overlap. => the holder now records sched= AND id= AND host=, and +# a liveness query is only ever trusted when the holder's scheduler is one this host can query. +# (2) NO HEARTBEAT, SO THE AGE FALLBACK WAS BACKWARDS. The age branch stat'ed the LOCKDIR, whose +# mtime is set once at creation and never refreshed. A perfectly healthy multi-hour training +# therefore looked "stale" to any challenger 1800 s after it started -- i.e. the longer the run +# the gate depends on had been alive, the more certainly the fallback would hand its run dir to +# a second writer. => the holder now touches $LOCKDIR/hb every RR_LOCK_HB_SECS (60 s) in the +# background, and staleness is judged on the HEARTBEAT, not on creation time. +# FAIL-CLOSED EVERYWHERE. Unknown scheduler, unreadable heartbeat, missing holder file, a holder +# file in the OLD bare-number format: every one of these is treated as "presumed live" and REFUSES. +# The cost of refusing wrongly is one requeue; the cost of granting wrongly is a corrupted resume on +# the only run that can make the DF column reportable. Exit 9 is "another live job owns this run +# dir" -- it is NOT a training failure and NOT a gate result. +RR_LOCK_HB_SECS=${RR_LOCK_HB_SECS:-60} +RR_LOCK_STALE_SECS=${RR_LOCK_STALE_SECS:-300} # >= 4x the heartbeat period + +# Which scheduler is THIS process running under? Batch-system variables only; never $$. +rr_lock_self_sched() { + if [ -n "${LSB_JOBID:-}" ]; then echo lsf + elif [ -n "${SLURM_JOB_ID:-}" ]; then echo slurm + else echo none; fi +} +rr_lock_self_id() { + if [ -n "${LSB_JOBID:-}" ]; then echo "$LSB_JOBID" + elif [ -n "${SLURM_JOB_ID:-}" ]; then echo "$SLURM_JOB_ID" + else echo "$$"; fi +} + +# Is holder live? Echoes live|dead|unknown. "unknown" is NOT "dead": it is only ever +# returned when this host cannot ask that scheduler, and the caller must fail closed on it. +rr_lock_holder_state() { + local sched="$1" id="$2" + [ -z "$id" ] && { echo unknown; return; } + case "$sched" in + lsf) + command -v bjobs >/dev/null 2>&1 || { echo unknown; return; } + if bjobs -o stat -noheader "$id" 2>/dev/null | grep -qE "RUN|PEND|SSUSP|PSUSP|USUSP"; then + echo live; else echo dead; fi ;; + slurm) + command -v squeue >/dev/null 2>&1 || { echo unknown; return; } + if squeue -h -j "$id" -o %T 2>/dev/null | grep -qE "RUNNING|PENDING|SUSPENDED|CONFIGURING|COMPLETING"; then + echo live; else echo dead; fi ;; + *) echo unknown ;; + esac +} + +rr_lock_hb_age() { # age of the heartbeat in seconds; empty when there is no readable heartbeat + local lockdir="$1" mt + mt=$(stat -c %Y "$lockdir/hb" 2>/dev/null || echo "") + [ -z "$mt" ] && { echo ""; return; } + echo $(( $(date +%s) - mt )) +} + +_rr_lock_write_holder() { # $1 lockdir + local sched id + sched=$(rr_lock_self_sched); id=$(rr_lock_self_id) + { echo "sched=$sched"; echo "id=$id"; echo "host=$(hostname)"; echo "taken=$(date -u +%FT%TZ)"; } > "$1/holder" + # The old bare-number file is kept so that an OLD payload still parses something, but the new + # reader ignores it: identity now lives in `holder`. + echo "$id" > "$1/jobid" +} + +_rr_lock_start_heartbeat() { # $1 lockdir -- background toucher, cleaned up by the EXIT trap + local lockdir="$1" + touch "$lockdir/hb" + ( while [ -d "$lockdir" ]; do touch "$lockdir/hb" 2>/dev/null || exit 0; sleep "$RR_LOCK_HB_SECS"; done ) & + RR_LOCK_HB_PID=$! +} + +rr_take_run_dir_lock() { # $1 lockdir, $2 log tag + local lockdir="$1" tag="${2:-run_dir_lock}" sched id state age + if mkdir "$lockdir" 2>/dev/null; then + _rr_lock_write_holder "$lockdir"; _rr_lock_start_heartbeat "$lockdir" + trap 'kill "${RR_LOCK_HB_PID:-0}" 2>/dev/null; rm -rf "'"$lockdir"'"' EXIT + echo "[$tag] took run-dir lock $lockdir ($(rr_lock_self_sched):$(rr_lock_self_id) on $(hostname))" + return 0 + fi + sched=$(sed -n 's/^sched=//p' "$lockdir/holder" 2>/dev/null | head -1) + id=$(sed -n 's/^id=//p' "$lockdir/holder" 2>/dev/null | head -1) + if [ -z "$sched" ]; then + echo "[$tag] lock $lockdir has no scheduler-tagged holder (pre-DEFECT-15 format or partial write)" + sched=unknown; id="" + fi + state=$(rr_lock_holder_state "$sched" "$id") + case "$state" in + live) echo "[$tag] REFUSING: $sched job $id is live and already owns $lockdir. exit 9"; exit 9 ;; + dead) echo "[$tag] holder $sched:$id confirmed not live by its own scheduler -- stale, taking over" ;; + *) + age=$(rr_lock_hb_age "$lockdir") + if [ -z "$age" ]; then + echo "[$tag] REFUSING: holder '$sched:$id' unverifiable from $(hostname) and NO readable heartbeat -- presumed live. exit 9"; exit 9 + fi + if [ "$age" -lt "$RR_LOCK_STALE_SECS" ]; then + echo "[$tag] REFUSING: holder '$sched:$id' unverifiable from $(hostname), heartbeat ${age}s old (<${RR_LOCK_STALE_SECS}s) -- live. exit 9"; exit 9 + fi + echo "[$tag] holder '$sched:$id' unverifiable, heartbeat ${age}s old (>=${RR_LOCK_STALE_SECS}s) -- presumed dead, taking over" ;; + esac + _rr_lock_write_holder "$lockdir"; _rr_lock_start_heartbeat "$lockdir" + trap 'kill "${RR_LOCK_HB_PID:-0}" 2>/dev/null; rm -rf "'"$lockdir"'"' EXIT + return 0 +} diff --git a/rsm_rise/scripts/nb/stale_derived.py b/rsm_rise/scripts/nb/stale_derived.py new file mode 100644 index 0000000000000000000000000000000000000000..421622f342af983403db314e5c497faeba8445dc --- /dev/null +++ b/rsm_rise/scripts/nb/stale_derived.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""gen_q#274 run 55 -- REFUSE TO LEAVE A PUBLISHED REPORT OLDER THAN THE FILE IT QUOTES. + +THE DEFECT THIS EXISTS FOR, measured not imagined. At 2026-09-25 04:00Z +`status/nb/td_ctl_pairs.json` was rebuilt with eval seed 3 and read 16 paired cells, 400 distinct +episodes, argmax 7/400 vs random 17/400, seeds [0,1,2,3]. `status/nb/td_dwm_rho.txt`, last built +01:14Z, was still on disk saying *in its own published text*: + + across the 10 PAIRED cells argmax-of-128 reads 12/500 episode-slots and + random-of-128 reads 11/500 ... Eval seeds present in that file: [0]. + +Both files are published status. Neither is wrong about its own computation; the rho report simply +quotes a SNAPSHOT of the other and nothing re-ran it. A reader landing on the older file gets a +retracted pooling (run 25 withdrew the 500-slot pool) presented as current. `td_ctl_pairs.py` is in +the rebuild chain and `td_dwm_rho_report.py` is not, and there was no check that would say so. + +WHAT THIS DOES. Declares the derived-file graph ONCE, then: + 1. verifies the declaration is EXHAUSTIVE -- every builder under scripts/nb that reads a + status/nb JSON must appear in it, or this exits 3. A dependency that is merely forgotten must + not read as a clean graph; + 2. reports every consumer whose published output is OLDER than an input it quotes. + +EXIT CODES. 0 = nothing stale. 1 = at least one stale consumer. 3 = the check could not be +trusted (undeclared builder, or zero edges examined). A vacuous scan is never a pass -- this +project has now shipped that fault twice (runs 53 and 54), so the refusal is explicit. +""" +import os, re, subprocess, sys, time + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +S = os.path.join(ROOT, "status/nb") + +# consumer script -> (its published outputs, the status/nb inputs it quotes) +# Every entry is checkable by eye against the script named on the left. +GRAPH = { + # --- the cfg(a) / TD-MPC2 chain -------------------------------------------------------- + "td_ctl_pairs.py": (["td_ctl_pairs.txt", "td_ctl_pairs.json"], []), + "nb274_health.py": (["nb274_health.txt", "nb274_health.json"], []), + "td_table.py": (["td_table.txt", "td_table.json"], ["nb274_health.json"]), + "td_dwm_rho_report.py": (["td_dwm_rho.txt", "td_dwm_rho.json"], ["td_ctl_pairs.json"]), + "td_dwm_rho_tab.py": (["td_dwm_rho_blocks.txt"], []), # renamed in run 55, see its header + "td_dynrange.py": (["td_dynrange.txt"], ["td_ctl_pairs.json"]), + "td_gamma_arm.py": (["td_gamma_arm.json"], ["td_jsplit.json"]), + "td_jsplit_tab.py": (["td_jsplit.json"], []), # quotes td_dwm_rho.txt in PROSE only + # --- the coverage / gate chain --------------------------------------------------------- + "resume_audit.py": (["resume_audit.txt", "resume_audit.json"], ["df_resume_verify.json"]), + "resume_xcheck.py": (["resume_xcheck.txt", "resume_xcheck.json"], []), + "gate_sweep.py": (["gate_sweep.txt", "gate_sweep.json"], []), + "gate_unquarantine.py": (["gate_unquarantine.txt", "gate_unquarantine.json"], []), + "egl_census.py": (["egl_census.txt", "egl_census.json"], []), + # --- the DF chain ---------------------------------------------------------------------- + "df_table.py": (["df_table.txt", "df_table.json"], ["resume_audit.json"]), + "df_idm_tab.py": ([], ["resume_audit.json"]), # prints; publishes no status file + # --- readers and one-shots: they publish no status file, so they cannot go stale -------- + "assert_health_covers.py": ([], []), # per-cell gate, run inside a payload + "test_td_resume.py": ([], []), # unit test + "td_scores_unmoved.py": ([], []), # handed both files on argv by the chain + "comment_274_run54.py": ([], []), # one-shot comment builder, not published state + "stale_derived.py": ([], []), # this file +} + +def declared_readers(): + return {k for k, (_, ins) in GRAPH.items() if ins} | {k for k in GRAPH} + +def actual_readers(): + """Every scripts/nb/*.py that mentions a status/nb JSON at all.""" + out = set() + d = os.path.join(ROOT, "scripts/nb") + for f in sorted(os.listdir(d)): + if not f.endswith(".py") or ".bak." in f: + continue + try: + src = open(os.path.join(d, f), encoding="utf-8", errors="replace").read() + except OSError: + continue + if re.search(r"status/nb/[A-Za-z0-9_]+\.json", src): + out.add(f) + return out + +def mtime(name): + p = os.path.join(S, name) + return os.path.getmtime(p) if os.path.exists(p) else None + +def main(): + missing = sorted(actual_readers() - declared_readers()) + print("== derived-file freshness, gen_q#274 run 55 ==") + print(f" {time.strftime('%Y-%m-%d %H:%MZ', time.gmtime())} root {S}") + if missing: + print(" UNDECLARED builders that touch a status/nb JSON -- the graph is not exhaustive:") + for m in missing: + print(f" {m}") + print(" REFUSING (rc=3): an incomplete graph cannot certify freshness.") + return 3 + + # TWO BUILDERS WRITING ONE PUBLISHED PATH is the same defect class with a different clock: + # the content then depends on run order rather than on rebuild order. Run 55 found exactly + # this -- td_dwm_rho_report.py and td_dwm_rho_tab.py both wrote status/nb/td_dwm_rho.txt with + # materially different renderings -- so the graph checks it and refuses. + owners = {} + for script, (outs, _) in GRAPH.items(): + for o in outs: + owners.setdefault(o, []).append(script) + clashes = {o: v for o, v in owners.items() if len(v) > 1} + if clashes: + print(" TWO OR MORE BUILDERS PUBLISH THE SAME PATH -- its content depends on run order:") + for o, v in sorted(clashes.items()): + print(f" {o} <- {', '.join(sorted(v))}") + print(" REFUSING (rc=3).") + return 3 + + edges = stale = 0 + for script, (outs, ins) in sorted(GRAPH.items()): + for o in outs: + for i in ins: + edges += 1 + to, ti = mtime(o), mtime(i) + if ti is None: + print(f" SKIP {o} <- {i}: input absent") + continue + if to is None: + stale += 1 + print(f" STALE {o} <- {i}: output has never been built") + continue + age = ti - to + flag = "STALE" if age > 0 else "ok " + if age > 0: + stale += 1 + print(f" {flag} {o} <- {i} out {time.strftime('%m-%d %H:%MZ', time.gmtime(to))}" + f" in {time.strftime('%m-%d %H:%MZ', time.gmtime(ti))}" + f" {'input newer by %.0f min' % (age/60) if age > 0 else ''}") + if edges == 0: + print(" REFUSING (rc=3): ZERO edges examined. A check that compared nothing is not a pass.") + return 3 + print(f" {edges} edge(s) examined, {stale} stale.") + if stale: + print(" -> rebuild the stale consumers before any of them is quoted.") + return 1 if stale else 0 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/nb/swap_readii.py b/rsm_rise/scripts/nb/swap_readii.py new file mode 100644 index 0000000000000000000000000000000000000000..ee0d0c331b5cb820d28650e6ca95d6a755b439cb --- /dev/null +++ b/rsm_rise/scripts/nb/swap_readii.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +"""gen_q#274 run 44-main -- READ (ii): the registered within-harness reproduction of DINO-WM's +published column, and the confound it was registered to detect. + +WHAT WAS REGISTERED, AND WHERE. scripts/nb/td_dual_swap_payload.sh (header, run 38) commits both +outcomes before any number existed: + + "2. A WITHIN-HARNESS REPRODUCTION OF DINO-WM'S OWN NUMBER. ... It should land near the + published 31.6 (threading) / 21.1 (mug). + * If it does: the harness, the proposer and the candidate pool are exonerated, and the + cfg(a)-vs-DINO-WM gap is the read-out. + * If it does NOT: the published cfg(a)-beside-DINO-WM comparison has a confound and no + cfg(a) number may be set beside a DINO-WM number until it is found." + +IT DOES NOT. The swap cell reads 0.070 (threading) and 0.100 (mug), not 0.316 / 0.211. So the +second branch binds and this file is the search for the confound. IT IS FOUND, and it is NOT +subtle: the published DINO-WM column and the cfg(a) column WERE NEVER RUN IN THE SAME +CONFIGURATION. They differ on three axes at once, every one of them read out of the cells' own +JSON below, none asserted here: + + axis cfg(a) column of record published DINO-WM column + actor checkpoint model_epoch_5000.pth model_epoch_500.pth <-- NOT THE SAME PROPOSER + plan_mode fold mpc_disc + plan rollout H 20 200 + +The first line is the one that matters for #274. cfg(a) is specified in the issue as the +SHARED-CANDIDATE column -- "scoring our proposer's same 128 candidates". A different actor +checkpoint is a different proposer, hence a different candidate pool, so the published side-by-side +does not measure what the issue asked for. This is a statement about the COMPARISON, not about +either method: nothing here says DINO-WM's 31.6 is wrong on its own terms. + +WHAT MAY BE SET BESIDE WHAT. The swap cell holds actor, plan_mode, plan_depth, plan_n and the +candidate pool at cfg(a)'s values and changes ONLY which read-out the planner acts on. That is the +matched comparison, and it is the one this file publishes. The published 31.6 is reported as what +it is -- a different configuration -- and the gap between them is decomposed rather than attributed. + +HEALTH / NO-SELECTION FLOOR. Every success rate here is printed beside the random-of-128 control +measured on the SAME actor and the same candidate construction (plan_rule=permuted), per the +2026-09-23 19:45Z blocker item 2. A cell that does not clear its own floor is reported as "AT +FLOOR", never as a success rate that ranks. +""" +import json, glob, os, sys +from math import comb + +ROOT = '/proj/dmfexp/zwhong/rsm_rise' + +# Every column is a GLOB, so the cell list is discovered, never hardcoded, and the printed n is the +# n that was actually read. DEFECT 12's lesson (run 43): the key must pin every axis that varies. +COLUMNS = [ + ('threading', 'published DINO-WM (mpc_disc H200, actor e500)', + 'runs/threading_expert_play/eval_onactor/E1-DINOWM-R0.95-200-mpcd-N128-argmax-DWMMPCS0AidqlE500D-es*.json'), + ('threading', 'DINO-WM read-out, MATCHED actor e5000 (depth 4)', + 'runs/threading_expert_play/eval_onactor/E1-DINOWM-R0.95-4-N128-argmax-DWMACTOR-es*.json'), + ('threading', 'FLOOR random-of-128, matched actor e5000', + 'runs/threading_expert_play/eval_onactor/E1-DINOWM-R0.95-4-N128-permuted-DWMACTOR-es*.json'), + ('threading', 'SWAP: DINO-WM read-out in cfg(a) chair (depth 2)', + 'runs/threading_expert_play/eval_onactor/td274smoke/*DUALSWAP*.json'), + ('threading', 'cfg(a) TD-MPC2 read-out, column of record', + 'runs/threading_expert_play/eval_onactor/td274/E1-TDMPC2-R0.95-20-tdq-128-argmax-TD274a-es*.json'), + ('mug', 'DINO-WM read-out, MATCHED actor e5000 (depth 4)', + 'runs/mug_expert_suboptimal/eval_onactor/E1-DINOWM-R0.95-4-N128-argmax-DWMACTOR-es*.json'), + ('mug', 'FLOOR random-of-128, matched actor e5000', + 'runs/mug_expert_suboptimal/eval_onactor/E1-DINOWM-R0.95-4-N128-permuted-DWMACTOR-es*.json'), + ('mug', 'SWAP: DINO-WM read-out in cfg(a) chair (depth 2)', + 'runs/mug_expert_suboptimal/eval_onactor/td274smoke/*DUALSWAP*.json'), + ('mug', 'cfg(a) TD-MPC2 read-out, column of record', + 'runs/mug_expert_suboptimal/eval_onactor/td274/E1-TDMPC2-R0.95-20-tdq-128-argmax-TD274a-es*.json'), +] + + +def fisher_two_sided(a, b, c, d): + """Exact two-sided Fisher on [[a,b],[c,d]] by summing tables no more likely than the observed.""" + n, r1, c1 = a + b + c + d, a + b, a + c + pr = lambda x: comb(r1, x) * comb(n - r1, c1 - x) / comb(n, c1) + p0 = pr(a) + lo, hi = max(0, c1 - (n - r1)), min(r1, c1) + return min(1.0, sum(pr(x) for x in range(lo, hi + 1) if pr(x) <= p0 * (1 + 1e-9))) + + +def read_column(pat): + """Pool a column. Successes are recovered as round(rate*n_ep) per cell and RE-CHECKED against the + episode list where one is present, so a rate/episode mismatch cannot pass silently.""" + s = n = 0 + cells, actors, planners, bad = [], set(), set(), [] + for f in sorted(glob.glob(os.path.join(ROOT, pat))): + d = json.load(open(f)) + ne = d['num_episodes'] + k = round(d['success_rate'] * ne) + eps = d.get('episodes') + if isinstance(eps, list) and len(eps) == ne: + kk = sum(1 for e in eps if (e.get('success') if isinstance(e, dict) else 0)) + if isinstance(eps[0], dict) and 'success' in eps[0] and kk != k: + bad.append((os.path.basename(f), k, kk)) + s += k; n += ne + cells.append(os.path.relpath(f, ROOT)) + actors.add(os.path.basename(str(d.get('eval_ckpt')))) + pl = d.get('planner', {}) + planners.add((pl.get('plan_mode'), pl.get('plan_depth'), pl.get('plan_n'), pl.get('plan_rule'))) + return dict(s=s, n=n, cells=cells, actors=sorted(actors), planners=sorted(planners), bad=bad) + + +def ci95(s, n): + p = s / n + se = (p * (1 - p) / n) ** 0.5 + return p, max(0.0, p - 1.96 * se), min(1.0, p + 1.96 * se) + + +def main(): + R = {} + for task, label, pat in COLUMNS: + R[(task, label)] = read_column(pat) + + out = [] + w = out.append + w('=' * 104) + w('READ (ii) -- THE REGISTERED WITHIN-HARNESS REPRODUCTION OF DINO-WM, AND THE CONFOUND IT FOUND') + w('gen_q#274 run 44-main. Builder: scripts/nb/swap_readii.py. Every row pooled from the cells listed.') + w('=' * 104) + w('') + w('REGISTERED OUTCOME (td_dual_swap_payload.sh header, run 38, before any number existed):') + w(' "It should land near the published 31.6 (threading) / 21.1 (mug)."') + w(' " * If it does NOT: the published cfg(a)-beside-DINO-WM comparison has a confound and no') + w(' cfg(a) number may be set beside a DINO-WM number until it is found."') + w('') + + for task in ('threading', 'mug'): + w('-' * 104) + w('TASK: %s' % task) + w('-' * 104) + w('%-52s %6s %-16s %8s %s' % ('column', 'succ', '95% CI', 'k/n', 'actor ckpt / planner')) + for t, label, _ in COLUMNS: + if t != task: + continue + r = R[(t, label)] + if r['n'] == 0: + w('%-52s -- NO CELLS FOUND --' % label) + continue + p, lo, hi = ci95(r['s'], r['n']) + w('%-52s %6.3f [%.3f,%.3f] %4d/%4d %s %s' + % (label, p, lo, hi, r['s'], r['n'], ','.join(r['actors']), r['planners'])) + w('') + + floor_key = (task, [l for t, l, _ in COLUMNS if t == task and l.startswith('FLOOR')][0]) + fl = R[floor_key] + w(' NO-SELECTION FLOOR (random-of-128 on the same actor): %.3f (%d/%d, %s)' + % (fl['s'] / fl['n'], fl['s'], fl['n'], floor_key[1])) + w(' Each scoring column against that floor -- a column that does not clear it DOES NOT RANK:') + for t, label, _ in COLUMNS: + if t != task or label.startswith('FLOOR'): + continue + r = R[(t, label)] + if r['n'] == 0: + continue + pv = fisher_two_sided(r['s'], r['n'] - r['s'], fl['s'], fl['n'] - fl['s']) + verdict = 'ABOVE FLOOR' if (pv < 0.05 and r['s'] / r['n'] > fl['s'] / fl['n']) else 'AT FLOOR (does not rank)' + w(' %-52s %.3f vs %.3f Fisher p=%.4f %s' + % (label, r['s'] / r['n'], fl['s'] / fl['n'], pv, verdict)) + w('') + + # ---- the decomposition, threading only (mug has no published matched arm in this build) ---- + pub = R[('threading', 'published DINO-WM (mpc_disc H200, actor e500)')] + swp = R[('threading', 'SWAP: DINO-WM read-out in cfg(a) chair (depth 2)')] + cfa = R[('threading', 'cfg(a) TD-MPC2 read-out, column of record')] + if pub['n'] and swp['n'] and cfa['n']: + P, S, C = pub['s'] / pub['n'], swp['s'] / swp['n'], cfa['s'] / cfa['n'] + gap = P - C + w('=' * 104) + w('DECOMPOSITION OF THE PUBLISHED THREADING GAP (published DINO-WM %.3f - cfg(a) %.3f = %.3f)' % (P, C, gap)) + w('=' * 104) + w(' READ-OUT, fully matched (actor, plan_mode, depth, N, candidate pool all held; only the') + w(' scorer the planner acts on changes): %.3f -> %.3f = %+.3f == %.1f%% of the gap' + % (C, S, S - C, 100 * (S - C) / gap)) + w(' CONFIGURATION (actor e5000->e500, fold->mpc_disc, H 20->200, all at once):') + w(' %.3f -> %.3f = %+.3f == %.1f%% of the gap' + % (S, P, P - S, 100 * (P - S) / gap)) + w('') + w(' So ~%.0f%% of the headline "DINO-WM beats TD-MPC2 cfg(a)" gap on threading is the surrounding' + % (100 * (P - S) / gap)) + w(' configuration, not the read-out. The read-out share is %.1f%% and is NOT individually' + % (100 * (S - C) / gap)) + pv = fisher_two_sided(cfa['s'], cfa['n'] - cfa['s'], swp['s'], swp['n'] - swp['s']) + w(' significant on the direct pairing (Fisher p=%.4f, cfg(a) has only %d episodes).' % (pv, cfa['n'])) + w(' What IS significant is each column against its own floor -- see the per-task blocks above.') + w('') + + w('=' * 104) + w('CAVEATS THAT TRAVEL WITH THESE NUMBERS') + w('=' * 104) + w(' * The swap column is 2 eval seeds x 50 episodes; cfg(a)\'s column of record is 1 x 50. The') + w(' floors are 9 x 50. n is printed on every row above; none of these are equal-n comparisons.') + w(' * "published DINO-WM 31.6" is reproduced here EXACTLY from its own cells (%d/%d) -- this file' + % (pub['s'], pub['n'])) + w(' does not dispute it, it disputes setting it beside a cfg(a) number run in another configuration.') + w(' * The depth-2 (swap) and depth-4 (DWMACTOR) DINO-WM columns agree to within 0.001 on threading,') + w(' so the plan_depth difference between them is not carrying the result.') + w(' * No IFQL cell is added anywhere here (owner decision 2026-09-23 20:20Z).') + + # integrity: any rate/episode mismatch found while pooling + allbad = [(k, b) for k, r in R.items() for b in r['bad']] + if allbad: + w('') + w(' !! RATE/EPISODE MISMATCH in %d cell(s) -- investigate before trusting the pooled row:' % len(allbad)) + for k, b in allbad: + w(' %s %s rate-implied k=%d, episode-list k=%d' % (k[1], b[0], b[1], b[2])) + + w('') + w('CELLS READ (every number above is pooled from exactly these files):') + for (t, label), r in R.items(): + w(' [%s] %s (%d cells)' % (t, label, len(r['cells']))) + for c in r['cells']: + w(' %s' % c) + + txt = '\n'.join(out) + '\n' + dest = os.path.join(ROOT, 'status/nb/td_swap_readii.txt') + open(dest, 'w').write(txt) + print(txt) + print('[swap_readii] wrote %s' % dest) + + +if __name__ == '__main__': + main() diff --git a/rsm_rise/scripts/nb/td_cfgb.py b/rsm_rise/scripts/nb/td_cfgb.py new file mode 100644 index 0000000000000000000000000000000000000000..4555e58ccd77fccd52cc166e504693c93e6b9f8e --- /dev/null +++ b/rsm_rise/scripts/nb/td_cfgb.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python +"""gen_q#274 configuration (b) -- the TD-MPC2 MPPI/CEM planner row, with its planner diagnostics. + +#274 requires a published health number beside every score, and for a PLANNER it names two in +particular: sample spread and per-iteration improvement. This file prints both for every cfg(b) +cell, next to the disclosed search size (num_samples x iterations x plan_horizon and the number of +policy-prior trajectories), so a cfg(b) row can never be read beside a 128-candidate column without +its own budget visible. + +**RETRACTION, 2026-09-24 run 43-main -- THE SATURATION ARGUMENT THIS FILE USED TO MAKE IS WITHDRAWN, +AND IT IS WITHDRAWN BY ITS OWN ARITHMETIC.** Every earlier version of this header divided the +elite objective by `1/(1-gamma)` and called the result `elite_sat`, "the fraction of the objective's +dynamic range used". That denominator is the ceiling of the TRUE discounted return under a binary +reward. It is NOT the ceiling of the estimator cfg(b) actually maximises. cfg(b)'s objective is + J = sum_{t= 1, growing with Hp. The realised factor per cell is +printed in the footer block below; it is COMPUTED, never asserted here. + +WHAT THAT COSTS THE OLD ARGUMENT. The corrected fraction is the `sat_obj` column, and the footer +prints its measured range over every cell together with how many cells exceed 0.30. At the time of +writing none did. The claim the old header made -- "for the gamma <= 0.98 cells saturation is +SUFFICIENT to explain why the planner's ranking is uninformative" -- is therefore withdrawn: those +cells are not near the objective's cap. Nothing MEASURED changes; J_elite, J_spread, J_gain and +every success rate are byte-identical to the pre-patch table (asserted by +scripts/rr_cpu_test_cfgb_ceiling.sh, block D). Only the explanation built on top of them goes. +Should a future cell ever read sat_obj > 1, the table says so on its own face in the footer rather +than relying on this paragraph. + +WHAT SURVIVES, AND IT IS SHARPER THAN WHAT IT REPLACES. `sat_true` = J_elite / (1/(1-gamma)) is +kept, relabelled for what it is: the fraction of the maximum ACHIEVABLE TRUE RETURN that the critic +assigns to the elite set. It lands within 1e-3 of 1.0 in most cells, across four gammas and three +planner horizons, while most of the estimator's own range sits unused above it -- both tallies are +COMPUTED in the footer. Landing on the true-return bound to five significant figures is not a cap +being hit, because there is no cap there: it is the value head predicting essentially the MAXIMUM +POSSIBLE RETURN for every elite candidate. The cells that land strictly ABOVE that bound are listed +in the footer under `<- J>RET-BOUND`; no real trajectory can achieve more, so the direction of the +error there is one-sided optimism. A critic that says "all of these +are already optimal" cannot order them, and the residual differences it does report are regression +noise -- which is the mechanism for cfg(b)'s flat search-budget response (run 32) and for the +ordering defect the #274 blocker asked to localise. Reported, not corrected: changing the head or +clamping the read-out would change the estimator's FORM, not its hyper-parameters. + +THE STRUCTURAL CAP ON cfg(b), MEASURED 2026-09-24 07:17:06Z (run 31). Configuration (b) as +gen_q#274 defines it -- MPPI/CEM seeded by our RISE actor as the policy prior -- CANNOT BE RUN at a +planner horizon greater than 8. The RISE actor emits an 8-frame executed action chunk +(rsm_planner._executed_window, Ta = algo_config.horizon.action_horizon), so at Hp=16 td_policy's +`_prior_actions` raises + "the actor's executed window is 8 frames but the planner horizon is 16" +and the cell produces nothing. Evidence: LSF 1893275 slot0, +logs/lsf/rr_pack4_nb30rc_b.slot0.1893275.out. So cfg(b)-with-our-actor optimises over at most 8 of +the H = 1/(1-0.95) = 20 frames the column is compared over, and that ratio belongs in the search-size +disclosure next to the score. + +The cap is REPORTED, not worked around. The actor's chunk is not extended and no prior is +fabricated. The two honest ways to reach a longer horizon both use the METHOD'S OWN ingredients and +both name themselves in the cell name and in the `prior` column below: + prior=rise_actor configuration (b) exactly as the issue specifies it. Hp <= 8. + prior=tdmpc2_pi TD-MPC2's OWN published prior (`model.pi`). This is upstream's design and is + NOT our actor, so such a row must never be credited to the RISE actor. + prior=none pure CEM, no prior. The ablation that says what the prior is worth at a + matched search budget. + +`prior_frac` is the share of elites contributed by the RISE actor prior. It is the fairness read: +if the prior's own trajectories are no more likely to be elite than sampled noise, the objective is +not recognising the behaviour policy either. + +Every number here is traceable to the named file in the last column. +""" +import json, glob, os, re, sys + +ROOT = '/proj/dmfexp/zwhong/rsm_rise' + + +def j_ceiling_head(gamma, hp): + """The ANALYTIC ceiling of the objective td_plan._estimate_value actually maximises. + + NOT 1/(1-gamma). That is the ceiling of the true discounted return under a binary reward; the + objective sums a LEARNED reward head whose decoded support is set by the two-hot bins. With + cfg.vmin = 0 and cfg.vmax = log1p(1/(1-gamma)) (td_corpus.py:109-110) and two_hot_inv's closing + `symexp` (tdmpc2/common/math.py:84), both r_hat and Q decode into [0, 1/(1-gamma)]. Hence + + J_max = R * sum_{t4s} {'Hp':>3s} {'S':>4s} {'it':>3s} {'pi':>4s} {'prior':>10s} " + f"{'succ':>7s} {'n':>4s} |{'J_mean':>9s}{'J_spread':>9s}{'J_gain':>11s}" + f"{'J_elite':>9s}{'ret_bnd':>8s}{'sat_true':>9s}{'obj_ceil':>9s}{'sat_obj':>8s}" + f"{'prior_f':>9s} file") +out.append(hdr); out.append('-' * len(hdr)) +for r in rows: + flag = ' <- PARTIAL' if r['partial'] else '' + out.append( + f"{r['task'][:10]:10s} {r['gamma']:6s} {r['H']:4d} {r['hp']:3d} {r['S']:4d} {r['it']:3d} " + f"{(r['pi'] if r['pi'] is not None else -1):4d} " + f"{(r['prior_ran'] or r['prior_src'] or 'n/a')[:10]:>10s} " + f"{(r['sr'] if r['sr'] is not None else float('nan')):7.3f} {(r['n'] or 0):4d} |" + f"{fmt(r['Jmean'], '.4f', 9)}{fmt(r['Jspread'], '.4f', 9)}{fmt(r['Jgain'], '.2e', 11)}" + f"{fmt(r['Jel'], '.4f', 9)}{fmt(r['ceil'], '.2f', 8)}{fmt(r['sat'], '.5f', 9)}" + f"{fmt(r['obj_ceil'], '.2f', 9)}{fmt(r['sat_obj'], '.4f', 8)}" + f"{fmt(r['prior'], '.4f', 9)} {r['f']}{flag}" + + (' <- J>RET-BOUND' if (r['sat'] is not None and r['sat'] > 1.0) else '') + + (' <- J>OBJ-CEIL' if (r['sat_obj'] is not None and r['sat_obj'] > 1.0) else '')) + +out.append('') +# run 43-main: the old `<- Q>CEIL` flag is WITHDRAWN as printed. It compared J against +# 1/(1-gamma) -- the TRUE-return bound -- and called that "the objective's own analytic ceiling". +# It is not: the reward head's decoded support is itself [0, 1/(1-gamma)] (see j_ceiling_head). +# Both facts are now printed, each under its own name, and each is COMPUTED, never asserted. +_over_obj = [r for r in rows if r['sat_obj'] is not None and r['sat_obj'] > 1.0] +_over_ret = [r for r in rows if r['sat'] is not None and r['sat'] > 1.0] +out.append('WITHDRAWN 2026-09-24 (run 43-main): earlier versions of this table flagged %d cells' + % len(_over_ret)) +out.append(' `<- Q>CEIL`, "OBJECTIVE ABOVE ITS OWN ANALYTIC CEILING". That comparison used the') +out.append(' wrong denominator. Recomputed from the weights the objective actually uses:') +out.append(' cells above the ESTIMATOR ceiling j_ceiling_head(gamma,Hp): %d of %d' + % (len(_over_obj), len(rows))) +if not _over_obj: + out.append(' -- NONE. sat_obj peaks at %.4f, so no cfg(b) cell has ever exceeded the ceiling' + % max([r['sat_obj'] for r in rows if r['sat_obj'] is not None] or [float('nan')])) + out.append(' of the objective it maximises. The flag was an artefact of the denominator.') +else: + for r in _over_obj: + out.append(' %s g=%s Hp=%d J_elite %.4f > obj_ceil %.2f (excess %.2e)' + % (r['task'][:22], r['gamma'], r['hp'], r['Jel'], r['obj_ceil'], + r['Jel'] - r['obj_ceil'])) +out.append('') +if _over_ret: + out.append('WHAT THE SAME CELLS DO SHOW, UNDER ITS CORRECT NAME (flagged <- J>RET-BOUND),' + ' %d of %d cells:' % (len(_over_ret), len(rows))) + for r in _over_ret: + out.append(' %s g=%s Hp=%d J_elite %.4f > max achievable TRUE return %.2f (excess %.2e,' + ' and only %.1f%% of the estimator ceiling %.2f)' + % (r['task'][:22], r['gamma'], r['hp'], r['Jel'], r['ceil'], + r['Jel'] - r['ceil'], 100.0 * r['sat_obj'], r['obj_ceil'])) + out.append(' No real trajectory under a binary reward can return more than 1/(1-gamma), so the') + out.append(' critic is biased OPTIMISTIC on these cells -- one-sided, by ~1e-4 relative. This is') + out.append(' a health flag on the VALUE. It is NOT a dynamic-range or clipping story: there is') + out.append(' 70-91% of estimator headroom above every one of these numbers.') + out.append('') +out.append('READING:') +out.append(' ret_bnd 1/(1-gamma): the largest TRUE discounted return a binary reward admits.') +out.append(' Not a property of the estimator. `H_terminal_q` in the diag file.') +out.append(' sat_true J_elite / ret_bnd -- the share of the maximum ACHIEVABLE return the critic') +out.append(' assigns the elite set. ~1.000 means the critic calls every elite candidate') +out.append(' already optimal, so it has nothing left to rank them by. This is the') +out.append(' column the old `elite_sat` actually was.') +out.append(' obj_ceil j_ceiling_head(gamma,Hp) -- the ceiling of the objective itself, given that') +out.append(' the reward head decodes into [0, 1/(1-gamma)] too. ALWAYS the larger one.') +out.append(' sat_obj J_elite / obj_ceil -- the real dynamic-range fraction. Never above 0.29 in') +out.append(' any cell measured, so saturation of the objective explains NOTHING here.') +out.append(' J_gain mean change in the elite objective per CEM iteration. ~0 or negative means') +out.append(' the iterations buy nothing.') +out.append(' prior_f share of elites coming from the RISE actor prior. Small means the objective') +out.append(' does not prefer the behaviour policy to noise.') +out.append('') +out.append(' THE ONE THING NOT TO READ OFF THIS TABLE: sat_true ~ 1 is NOT evidence that the') +out.append(' objective ran out of range. sat_obj is the range column and it is ~0.1-0.3 everywhere.') +sat = [r for r in rows if r['sat'] is not None] +if sat: + _so = [r['sat_obj'] for r in sat if r['sat_obj'] is not None] + _near = [r for r in sat if abs(r['sat'] - 1.0) < 1e-3] + out.append('') + out.append(f' Across {len(sat)} cfg(b) cells with diagnostics: sat_true in ' + f'[{min(r["sat"] for r in sat):.5f}, {max(r["sat"] for r in sat):.5f}]; ' + f'sat_obj in [{min(_so):.4f}, {max(_so):.4f}]; ' + f'success_rate in [{min(r["sr"] for r in sat if r["sr"] is not None):.3f}, ' + f'{max(r["sr"] for r in sat if r["sr"] is not None):.3f}].') + out.append(' sat_true is within 1e-3 of 1.000 in %d of %d cells; sat_obj exceeds 0.30 in %d.' + % (len(_near), len(sat), sum(1 for v in _so if v > 0.30))) + out.append(' So in every cell where the critic calls the elite set maximal, the objective it') + out.append(' maximises still had %.1fx-%.1fx more range available and did not use it.' + % (1.0 / max(_so), 1.0 / min(_so))) +print('\n'.join(out)) diff --git a/rsm_rise/scripts/nb/td_ctl_pairs.py b/rsm_rise/scripts/nb/td_ctl_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..88257ccd8f6e321762bc78e25125f68ad964a0bd --- /dev/null +++ b/rsm_rise/scripts/nb/td_ctl_pairs.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""gen_q#274 blocker item 2, POOLED: TD-MPC2 cfg(a) argmax-of-128 vs random-of-128 on IDENTICAL candidates. + +Every cfg(a) cell is `...-tdq-128-argmax-TD274a-es-sS0As0-s`; its control is the byte-identical +cell name with `argmax` -> `random`, produced by RR_TD_RULE=random in scripts/nb/td_eval_payload.sh -- +same task, same gamma, same 128 candidates from the same proposer, same eval seed, same 400-frame +episodes. The ONLY difference is that the control ignores the score and picks uniformly. So the +paired difference is exactly "what the cfg(a) read-out's ordering is worth", with no world-model or +proposer confound. + +Fisher exact is computed in closed form (math.comb) so this has no scipy dependency and every digit is +reproducible from the counts printed beside it. + +RUN 51 (2026-09-25) -- THE EVAL-SEED AXIS. This builder used to hard-code `-es0-` in the two paths it +opened, which was correct only for as long as eval seed 0 was the only seed that existed. Run 50 +launched cfg(a) at eval seeds 1 and 2 (LSF 1907410 / 1907411) precisely to break the limit this file +documents, and with the seed hard-coded those cells would have been INVISIBLE here: the pooled row +would have stayed at eval seed 0, and the printed sentence "distinct states across both tasks = 100, +NOT 350" -- true today -- would have silently become FALSE the moment the new cells landed, telling a +reader cfg(a) has 50 distinct states per task when it had 150. The seed is now DISCOVERED from disk +(glob + parse), never assumed, and the independence bookkeeping is computed from the seeds actually +present. + +WHAT IS AND IS NOT INDEPENDENT, which is the whole reason this file is careful: + * two cells at the same (task, eval seed) and different gamma -> SAME 50 initial states, so these + are re-evaluations and their episode-slots MUST NOT be added up as if independent; + * two cells at the same (task, gamma) and different eval seed -> DISJOINT initial states, so these + ARE independent and may be pooled with a real interval; + * two cells on different tasks -> independent. +So the widest HONEST interval is: fix one gamma per task (the cell of record), pool across its eval +seeds, and pool the two tasks. That row is printed with a Wilson interval. The all-cells row is +still printed, still WITHOUT an interval, for continuity with what was published. +""" +import json, glob, os, math, re, sys + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +TASKS = ("threading_expert_play", "mug_expert_suboptimal") +# H IS READ OFF THE CELL NAME, NOT LOOKED UP. The version of this file before run 51 carried a +# hard-coded H_OF = {0.90,0.95,0.98,0.99} and built its paths from that dict's keys, so when the +# gamma 0.995 rung was added to the ladder its argmax/random PAIR -- which is on disk for both tasks +# -- was silently dropped: the published pooled row "7/350" excluded a rung that had been measured. +# A table must not have a private list of which measurements exist. H now comes from the filename's +# own H token and is CROSS-CHECKED against 1/(1-gamma); a mismatch is printed, never absorbed. +H_CHECK = {"0.90": 10, "0.95": 20, "0.98": 50, "0.99": 100, "0.995": 200} +# The cell of record for cfg(a): gamma 0.95 => H = 1/(1-gamma) = 20 frames. Named here, before any +# number is read, so the "independent states" row below cannot be chosen after seeing the scores. +GAMMA_OF_RECORD = "0.95" +H_MISMATCH = [] + +CELL_RE = re.compile( + r"^E1-TDMPC2-R(?P0\.\d+)-(?P\d+)-tdq-128-(?Pargmax|random)-TD274a" + r"-es(?P\d+)-sS0As0-s(?P\d+)\.json$") + + +def fisher_two_sided(a, b, c, d): + """2x2 [[a,b],[c,d]]; two-sided = sum of tables no more probable than the observed one.""" + n = a + b + c + d + r1, r2, c1 = a + b, c + d, a + c + def p(x): + return (math.comb(r1, x) * math.comb(r2, c1 - x)) / math.comb(n, c1) + p0 = p(a) + lo, hi = max(0, c1 - r2), min(r1, c1) + return sum(p(x) for x in range(lo, hi + 1) if p(x) <= p0 * (1 + 1e-12)) + + +def wilson(k, n, z=1.959963985): + if n == 0: + return (float("nan"), float("nan")) + ph = k / n + den = 1 + z * z / n + c = (ph + z * z / (2 * n)) / den + h = z * math.sqrt(ph * (1 - ph) / n + z * z / (4 * n * n)) / den + return (max(0.0, c - h), min(1.0, c + h)) + + +def load(p): + d = json.load(open(p)) + sr = d.get("success_rate", d.get("final_success_rate")) + n = d.get("num_episodes") or d.get("num_rollouts") or d.get("n_rollouts") \ + or len(d.get("rollouts", []) or []) or None + return sr, n, d + + +def discover(task): + """Every cfg(a) argmax cell on disk for this task, keyed (gamma, eval_seed) -> basename. + Seeds are read off the filename; nothing about which seeds exist is assumed.""" + out = {} + for f in sorted(glob.glob(f"{ROOT}/runs/{task}/eval_onactor/td274/" + f"E1-TDMPC2-R*-tdq-128-argmax-TD274a-es*-sS0As0-s*.json")): + m = CELL_RE.match(os.path.basename(f)) + if not m: + continue + g, H = m.group("gamma"), int(m.group("H")) + # Cross-check the name's own two encodings of the horizon against each other. A cell whose + # H token disagrees with 1/(1-gamma) is REPORTED, not dropped and not quietly renamed. + want = int(round(1.0 / (1.0 - float(g)))) + if H != want: + H_MISMATCH.append((task, os.path.basename(f), g, H, want)) + if g in H_CHECK and H_CHECK[g] != H: + H_MISMATCH.append((task, os.path.basename(f), g, H, H_CHECK[g])) + out[(g, int(m.group("es")))] = (os.path.basename(f), H) + return out + + +rows, missing = [], [] +for t in TASKS: + found = discover(t) + for (g, es) in sorted(found, key=lambda k: (float(k[0]), k[1])): + name, h = found[(g, es)] + pa = f"{ROOT}/runs/{t}/eval_onactor/td274/{name}" + pr = pa.replace("-argmax-", "-random-") + sa, na, _ = load(pa) + if sa is None: + continue + if not os.path.exists(pr): + missing.append((t, g, h, es, sa, pa)) + continue + sr, nr, _ = load(pr) + na = na or 50 + nr = nr or 50 + rows.append(dict(task=t, gamma=g, H=h, eval_seed=es, + sr_argmax=sa, n_argmax=na, sr_random=sr, n_random=nr, + k_argmax=round(sa * na), k_random=round(sr * nr), + argmax_file=os.path.basename(pa), random_file=os.path.basename(pr))) + +out = [] +w = out.append +w("gen_q#274 -- TD-MPC2 cfg(a): ARGMAX-OF-128 vs RANDOM-OF-128 ON IDENTICAL CANDIDATES") +w("Generated by scripts/nb/td_ctl_pairs.py. Every cell 400-frame episodes; the eval seed is a COLUMN") +w("below and is read off each cell's filename, never assumed. The control differs from the arm in ONE") +w("respect: it ignores the score and picks uniformly from the same 128 candidates.") +w("") +seeds_seen = sorted({r["eval_seed"] for r in rows}) +w(f"eval seeds present on disk: {seeds_seen if seeds_seen else 'NONE'} " + f"({len(rows)} paired cells, {len(missing)} unpaired)") +w(f"gammas present on disk: {sorted({r['gamma'] for r in rows} | {m[1] for m in missing})} " + "-- discovered, not from any list inside this builder") +for _t, _f, _g, _H, _want in H_MISMATCH: + w(f" !! HORIZON MISMATCH {_t} {_f}: name says H={_H}, gamma {_g} implies {_want}. REPORTED, NOT DROPPED.") +w("") +w(f"{'task':14s} {'gamma':6s} {'H':4s} {'es':3s} {'cfg(a) argmax':>14s} {'random-of-128':>14s} " + f"{'diff':>8s} {'Fisher p':>9s}") +for r in rows: + a, b = r["k_argmax"], r["n_argmax"] - r["k_argmax"] + c, d = r["k_random"], r["n_random"] - r["k_random"] + r["fisher_p"] = fisher_two_sided(a, b, c, d) + r["diff"] = r["sr_argmax"] - r["sr_random"] + w(f"{r['task'][:14]:14s} {r['gamma']:6s} {str(r['H']):<4s} {r['eval_seed']:<3d} " + f"{r['sr_argmax']:>8.3f} ({a:2d}/{r['n_argmax']:2d}) {r['sr_random']:>8.3f} ({c:2d}/{r['n_random']:2d}) " + f"{r['diff']:>+8.3f} {r['fisher_p']:>9.3f}") +for t, g, h, es, sa, pa in missing: + w(f"{t[:14]:14s} {g:6s} {str(h):<4s} {es:<3d} {sa:>8.3f} ( / ) {'NO CONTROL':>14s} " + f"{'--':>8s} {'--':>9s}") +w("") + +KA = sum(r["k_argmax"] for r in rows); NA = sum(r["n_argmax"] for r in rows) +KR = sum(r["k_random"] for r in rows); NR = sum(r["n_random"] for r in rows) +pp = fisher_two_sided(KA, NA - KA, KR, NR - KR) if NA and NR else float("nan") + +# --------------------------------------------------------------------------------------------- +# INDEPENDENCE BOOKKEEPING. Computed from the (task, eval_seed) pairs actually on disk. +# Cells sharing a (task, eval_seed) are re-evaluations of ONE initial-state set; each DISTINCT +# (task, eval_seed) contributes its own disjoint set of states. +# --------------------------------------------------------------------------------------------- +state_sets = {} # (task, eval_seed) -> episodes in that set +for r in rows: + key = (r["task"], r["eval_seed"]) + state_sets[key] = max(state_sets.get(key, 0), r["n_argmax"]) +distinct_states = sum(state_sets.values()) +reeval = {} +for r in rows: + reeval.setdefault((r["task"], r["eval_seed"]), []).append(r["gamma"]) + +# CORRECTION, run 25 (2026-09-24), KEPT: the pooled Wilson intervals this block used to print -- and +# which were posted to gen_q#274 and #267 on 2026-09-24 as "7/350 = 0.0200 [0.0097, 0.0407]" -- assumed +# 350 INDEPENDENT episodes. They are not: at that time every cell ran at exp.eval_seed = 0, so the +# threading cells were re-evaluations of ONE set of 50 threading initial states and likewise for mug. +# The POINT estimates and the per-cell Fisher tests were unaffected; only the WIDTH was wrong, so the +# width is not printed on the all-cells row. Run 51 keeps that refusal AND adds the row that IS +# legitimate once more than one eval seed exists (below). +w(f"ACROSS ALL {len(rows)} PAIRED cells (cells with no control are excluded, and listed above):") +w(f" cfg(a) argmax-of-128 {KA}/{NA} episode-slots = {KA/NA:.4f}" if NA else " (no paired cells)") +if NR: + w(f" random-of-128 control {KR}/{NR} episode-slots = {KR/NR:.4f}") + w(f" difference {KA/NA - KR/NR:+.4f}") +w(" NO POOLED CONFIDENCE INTERVAL IS PRINTED ON THIS ROW, and that is deliberate:") +for (_t, _es), _gs in sorted(reeval.items()): + w(f" {_t[:22]:22s} es{_es} {state_sets[(_t, _es)]} distinct initial states, " + f"re-evaluated {len(_gs)} times (gamma {', '.join(sorted(_gs))})") +if distinct_states: + w(f" distinct states across both tasks = {distinct_states}, NOT {NA}. A Wilson interval on " + f"{NA} would be ~{(NA/distinct_states)**0.5:.1f}x too narrow.") + +# --------------------------------------------------------------------------------------------- +# THE ROW THAT IS LEGITIMATE: one gamma per task (the cell of record, fixed above), pooled across +# eval seeds. Those episode sets are disjoint by construction, so this interval is real. +# --------------------------------------------------------------------------------------------- +rec = [r for r in rows if r["gamma"] == GAMMA_OF_RECORD] +H_REC = (rec[0]["H"] if rec else int(round(1.0 / (1.0 - float(GAMMA_OF_RECORD))))) +rec_seeds = sorted({(r["task"], r["eval_seed"]) for r in rec}) +w("") +w(f"INDEPENDENT-STATES ROW -- gamma {GAMMA_OF_RECORD} (H = {H_REC}) only, the cell of") +w(" record, pooled across eval seeds. Distinct eval seeds contribute DISJOINT initial states, so") +w(" unlike the row above this one may carry an interval.") +# The guard is on the number of distinct EVAL SEEDS, not on the number of (task, eval-seed) sets. +# Those differ, and getting it wrong is how this row would mislabel itself: with a single eval seed +# and two tasks there are still two DISJOINT episode sets, so an interval over them is arithmetically +# valid -- but it is a CROSS-TASK interval and calling it "across eval seeds" would claim a +# replication that has not happened. Both cases are printed; only the wording differs. +rec_seed_ids = sorted({s for _, s in rec_seeds}) +if not rec_seeds: + w(f" NOT AVAILABLE: no paired cfg(a) cell at gamma {GAMMA_OF_RECORD} exists on disk.") + ind = None +else: + ka = sum(r["k_argmax"] for r in rec); na_ = sum(r["n_argmax"] for r in rec) + kr = sum(r["k_random"] for r in rec); nr_ = sum(r["n_random"] for r in rec) + la_, ha_ = wilson(ka, na_); lr_, hr_ = wilson(kr, nr_) + pi = fisher_two_sided(ka, na_ - ka, kr, nr_ - kr) + if len(rec_seed_ids) < 2: + w(f" ONE EVAL SEED ONLY ({rec_seed_ids}). The {len({t for t, _ in rec_seeds})} task(s) below" + f" contribute DISJOINT episode sets, so the interval is") + w(f" arithmetically valid over {na_} distinct episodes -- but it is a CROSS-TASK interval and" + " NOT a replication") + w(" across eval seeds. cfg(a) does not yet have a second eval seed, so it cannot be reported") + w(" as reproduced; a second seed is in flight (run 50: LSF 1907410 / 1907411).") + else: + w(f" ACROSS EVAL SEEDS {rec_seed_ids} over {len({t for t, _ in rec_seeds})} task(s)" + f" = {na_} DISTINCT episodes -- a real replication.") + w(f" seeds pooled: {rec_seed_ids} over {len({t for t, _ in rec_seeds})} task(s)" + f" = {na_} DISTINCT episodes") + w(f" cfg(a) argmax-of-128 {ka}/{na_} = {ka/na_:.4f} [{la_:.4f}, {ha_:.4f}]") + w(f" random-of-128 control {kr}/{nr_} = {kr/nr_:.4f} [{lr_:.4f}, {hr_:.4f}]") + w(f" difference {ka/na_ - kr/nr_:+.4f} Fisher p = {pi:.4f}") + ind = dict(gamma=GAMMA_OF_RECORD, across_eval_seeds=(len(rec_seed_ids) >= 2), + k_argmax=ka, n_argmax=na_, k_random=kr, n_random=nr_, + wilson_argmax=[la_, ha_], wilson_random=[lr_, hr_], fisher_p=pi, + seeds=sorted({s for _, s in rec_seeds}), + tasks=sorted({t for t, _ in rec_seeds})) + +# --------------------------------------------------------------------------------------------- +# PER-TASK STRATA OF THE INDEPENDENT-STATES ROW (run 55, gen_q#274) +# +# WHY THIS EXISTS, AND WHY IT IS NOT A FISHING EXPEDITION. The pooled independent-states row above +# mixes the two tasks. Once eval seed 3 landed, the two tasks' cells at the cell of record point in +# OPPOSITE directions, so the pooled cell-level sign test returns p ~ 1 by CANCELLATION rather than +# by absence of an effect, and a reader who saw only the pooled line would conclude "no effect" +# where the data say "two effects with opposite signs". Stratifying by task is the ordinary unit +# every other table on this issue already uses (td_table, nb274_health and gate_sweep all key by +# task first), so this is a presentation of the SAME estimator, not a new one. +# +# HONEST ABOUT THE ORDER OF EVENTS: the task split was looked at in run 55 AFTER the pooled row was +# read, so the per-task p below is NOT corrected for having looked. A Bonferroni factor over the +# number of tasks actually printed is given beside it so the reader does not have to supply it. +# Neither p is the headline; the headline stays the pooled row and its sign test. +# --------------------------------------------------------------------------------------------- +w("") +w(f"PER-TASK STRATA of the independent-states row (gamma {GAMMA_OF_RECORD}), because the two tasks") +w(" disagree in SIGN and the pooled sign test cancels them. Post-hoc split: see the note below.") +strata = [] +_rec_tasks = sorted({t for t, _ in rec_seeds}) if rec_seeds else [] +for _t in _rec_tasks: + _tr = [r for r in rec if r["task"] == _t] + _ka = sum(r["k_argmax"] for r in _tr); _na = sum(r["n_argmax"] for r in _tr) + _kr = sum(r["k_random"] for r in _tr); _nr = sum(r["n_random"] for r in _tr) + _seeds = sorted({r["eval_seed"] for r in _tr}) + # Within ONE task at ONE gamma, one cell per eval seed, so these episodes are disjoint and the + # interval is real. If that ever stops being true the row refuses rather than narrowing. + _dup = len(_tr) != len(_seeds) + _la, _ha = wilson(_ka, _na); _lr, _hr = wilson(_kr, _nr) + _p = fisher_two_sided(_ka, _na - _ka, _kr, _nr - _kr) + _pos_t = len([r for r in _tr if r["diff"] > 0]); _neg_t = len([r for r in _tr if r["diff"] < 0]) + w(f" {_t} seeds {_seeds}") + if _dup: + w(f" REFUSING AN INTERVAL: {len(_tr)} cells over {len(_seeds)} eval seed(s) means a seed's" + " states are re-used here.") + w(f" cfg(a) argmax-of-128 {_ka}/{_na} = {_ka/_na:.4f}" + + ("" if _dup else f" [{_la:.4f}, {_ha:.4f}]")) + w(f" random-of-128 control {_kr}/{_nr} = {_kr/_nr:.4f}" + + ("" if _dup else f" [{_lr:.4f}, {_hr:.4f}]")) + w(f" difference {_ka/_na - _kr/_nr:+.4f} Fisher p = {_p:.4f}" + f" (x{len(_rec_tasks)} tasks -> Bonferroni p = {min(1.0, _p*len(_rec_tasks)):.4f})") + w(f" per-task cell signs: argmax better in {_pos_t}, worse in {_neg_t}, of {len(_tr)} cells") + strata.append(dict(task=_t, gamma=GAMMA_OF_RECORD, seeds=_seeds, + k_argmax=_ka, n_argmax=_na, k_random=_kr, n_random=_nr, + wilson_argmax=(None if _dup else [_la, _ha]), + wilson_random=(None if _dup else [_lr, _hr]), + fisher_p=_p, bonferroni_p=min(1.0, _p * len(_rec_tasks)), + n_tasks_compared=len(_rec_tasks), + cells_argmax_better=_pos_t, cells_argmax_worse=_neg_t, n_cells=len(_tr), + interval_refused=_dup, post_hoc=True)) +if len(_rec_tasks) < 2: + w(" ONLY ONE TASK at the cell of record, so there is no cancellation to expose and this block") + w(" adds nothing the pooled row does not already say.") + +# The valid distribution-free statement at the CELL level: each cell is a paired argmax/random +# comparison on its own identical candidates, so the SIGN of its difference is a legitimate unit even +# though cells within a (task, eval seed) share initial states. +_pos = len([r for r in rows if r["diff"] > 0]); _neg = len([r for r in rows if r["diff"] < 0]) +_tie = len(rows) - _pos - _neg +def _signp(a, b): + from math import comb + n = a + b + if n == 0: + return 1.0 + tot = sum(comb(n, i) for i in range(n + 1)) + k = min(a, b) + return min(1.0, 2 * sum(comb(n, i) for i in range(k + 1)) / tot) +w("") +w(f" CELL-LEVEL SIGN TEST (the unit is a cell, not an episode): argmax better in {_pos} cells," + f" worse in {_neg}, tied in {_tie}; two-sided sign-test p = {_signp(_pos, _neg):.4f}") +w("") +if pp == pp and pp > 0.05: + w("READING: at this sample size the cfg(a) read-out's ORDERING buys nothing that can be") + w(" distinguished from ignoring it. This is NOT the same claim as 'the scorer is inert' --") + w(" status/nb/nb274_health.txt shows cfg(a) does NOT tie at 128 and does produce a spread of") + w(" scores, and status/nb/td_dwm_rho_*.json shows its ordering is weakly and positively") + w(" correlated with DINO-WM's. The finding is that whatever ordering it produces does not") + w(" convert into success on these tasks at n=50 per cell.") + w(" READ THE SAMPLE SIZE LITERALLY: the resolution is ONE episode = 0.020 per cell, and cells") + w(" at the same (task, eval seed) re-use that seed's 50 initial states, so this excludes a") + w(" LARGE effect only. A 1-2 point gain from cfg(a)'s ordering would sit entirely inside what") + w(" this cannot see.") +w(" EVERY number above is an argmax/random PAIR on the same candidates AND THE SAME EVAL SEED, so") +w(" neither the TD-MPC2 world model nor the RISE proposer can explain the difference (or its") +w(" absence). A control at a different seed shares neither the states nor the candidates with the") +w(" arm beside it and is never paired here.") +if missing: + w(f" {len(missing)} cfg(a) cell(s) still have NO control at their own eval seed and are excluded") + w(" from every pooled row above.") + +txt = "\n".join(out) + "\n" +open(f"{ROOT}/status/nb/td_ctl_pairs.txt", "w").write(txt) +json.dump(dict(rows=rows, + missing=[dict(task=t, gamma=g, H=h, eval_seed=es, sr_argmax=s) + for t, g, h, es, s, _ in missing], + seeds_present=seeds_seen, + state_sets={f"{t}|es{es}": n for (t, es), n in sorted(state_sets.items())}, + distinct_states=distinct_states, + pooled_all_cells=dict(k_argmax=KA, n_argmax=NA, k_random=KR, n_random=NR, + sr_argmax=(KA / NA if NA else None), + sr_random=(KR / NR if NR else None), fisher_p=pp, + interval_refused_because="cells share initial states within " + "(task, eval seed)"), + pooled_independent_states=ind, + per_task_strata=strata, + per_task_strata_note=("post-hoc split examined in run 55 after the pooled " + "row; p values are uncorrected, Bonferroni given beside")), + open(f"{ROOT}/status/nb/td_ctl_pairs.json", "w"), indent=1) +print(txt) diff --git a/rsm_rise/scripts/nb/td_dual_payload.sh b/rsm_rise/scripts/nb/td_dual_payload.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c722a19d7a6258a60390d01d08c001024846e97 --- /dev/null +++ b/rsm_rise/scripts/nb/td_dual_payload.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# gen_q#274 blocker item 3: rank-correlate cfg(a)'s scores against the PUBLISHED DINO-WM read-out on +# the SAME anchors and the SAME 128 candidates, inside ONE eval (code/tdmpc2_rise/dual_scorer.py). +# +# The DINO-WM knobs below are copied from that column's own eval cells +# (runs//eval_onactor/E1-DINOWM-R0.95-4-N128-argmax-*.json -> planner block): fold, depth 4, +# beta 0.95, gamma 0.99, 16 particles, 8 flow steps, prob, chunk 8 -- so the second read-out here is +# the read-out that actually produced the published DINO-WM numbers, not a re-tuned stand-in. +# +# RR_TD_SMOKE=1: this run costs a second read-out per decision, so its wall clock is not the +# published cfg(a) cell's. It lands in td274smoke/ and no table reads it; the number it exists for +# is status/nb/td_dwm_rho__.json. +# +# usage: td_dual_payload.sh [rollouts] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +TASK=${1:?task}; GAMMA=${2:-0.95}; ROLL=${3:-10} +TAG=g$(echo "$GAMMA" | tr -d '.') +DWM=$ROOT/runs/$TASK/wm/dinowm/ckpt_best.pt +HOP=$ROOT/runs/$TASK/hop/gauss/policy_r1.pt +for f in "$DWM" "$HOP"; do [ -f "$f" ] || { echo "[td_dual] MISSING $f"; exit 2; }; done +OUT=$ROOT/status/nb/td_dwm_rho_${TASK}_${TAG}.json +if [ -s "$OUT" ]; then echo "[td_dual] $OUT exists -- skip"; exit 0; fi +# RR_TD_SUF_EXTRA=-DUAL (run 21): the dual run computes TWO read-outs per decision, so it is not the +# same computation as a plain smoke and must not share its cell name. Without this, an unrelated +# pre-existing smoke json made td_eval_payload.sh's skip-if-exists resume guard short-circuit the +# whole eval and the rho file was never written (threading, 00:54:22Z). The rho OUTPUT path above is +# unchanged, and mug's already-landed rho is not re-run (the `-s $OUT` guard on line 23), so this +# changes no measured number -- it only lets the threading half be measured at all. +export RR_TD_SUF_EXTRA=-DUAL +export RR_TD_SMOKE=1 RR_TD_DUAL_DWM=$DWM RR_TD_DUAL_HOP=$HOP RR_TD_DUAL_OUT=$OUT \ + RR_TD_DUAL_DEPTH=4 RR_TD_DUAL_BETA=0.95 RR_TD_DUAL_GAMMA=0.99 \ + RR_TD_DUAL_PARTICLES=16 RR_TD_DUAL_FLOW=8 RR_TD_DUAL_CELL="cfg(a) $TASK $GAMMA" +echo "[td_dual] $(date -u) task=$TASK gamma=$GAMMA rollouts=$ROLL -> $OUT" +bash $ROOT/scripts/nb/td_eval_payload.sh "$TASK" score "$GAMMA" 0 "$ROLL" +rc=$? +[ -s "$OUT" ] && { echo "[td_dual] RHO LANDED $OUT"; python3 -c " +import json;d=json.load(open('$OUT'))['summary'] +print('[td_dual] decisions',d.get('decisions'),'rho_mean',d.get('rho_mean'),'rho_median',d.get('rho_median'),'argmax_agreement',d.get('argmax_agreement'))"; } \ + || { echo "[td_dual] NO RHO FILE rc=$rc -- see the eval log for the secondary's error"; exit 1; } diff --git a/rsm_rise/scripts/nb/td_dual_swap_payload.sh b/rsm_rise/scripts/nb/td_dual_swap_payload.sh new file mode 100644 index 0000000000000000000000000000000000000000..b74d7a8c14b17d445f0f0ed476338a5d6b8fbca4 --- /dev/null +++ b/rsm_rise/scripts/nb/td_dual_swap_payload.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# gen_q#274 run 38 -- THE SWAPPED DUAL READ-OUT. DINO-WM SELECTS; TD-MPC2 cfg(a) OBSERVES. +# +# status/nb/td_dwm_rho.txt (the un-swapped instrument, blocker item 3) closes with its own caveat: +# +# "Every decision point here lies on cfg(a)'s OWN trajectory, and that trajectory fails. +# Agreement here is agreement about the states cfg(a) REACHED. It is not evidence about the +# states DINO-WM reaches on its own successful rollouts ... The matched-anchor version of that +# question needs DINO-WM's own rollout anchors and is NOT measured here." +# +# This payload measures it. Nothing about either estimator changes -- both are built from the same +# checkpoints with the same knobs as the un-swapped run -- only which one's scores the planner acts +# on (eval.py, RR_TD_DUAL_SWAP=1). That is a configuration choice, not a change to an estimator's +# form. +# +# TWO READS COME OUT OF ONE RUN: +# 1. THE MATCHED-ANCHOR RANK CORRELATION. With DINO-WM driving, the anchors are the states the +# PUBLISHED column actually visits. If cfg(a) ranks DINO-WM's chosen candidate badly THERE, its +# ordering is broken in the regime that decides the task. If it ranks it well, then cfg(a)'s +# read-out is fine at good states and the 0.020 is about where cfg(a) ENDS UP, not how it ranks. +# 2. A WITHIN-HARNESS REPRODUCTION OF DINO-WM'S OWN NUMBER. This cell's success rate is produced +# by the published DINO-WM read-out on the shared 128-candidate pool, inside OUR eval harness. +# It should land near the published 31.6 (threading) / 21.1 (mug). +# * If it does: the harness, the proposer and the candidate pool are exonerated, and the +# cfg(a)-vs-DINO-WM gap is the read-out. +# * If it does NOT: the published cfg(a)-beside-DINO-WM comparison has a confound and no +# cfg(a) number may be set beside a DINO-WM number until it is found. +# Registered BEFORE any number exists, so neither outcome can be chosen after the fact. +# +# LABELLING -- THIS IS NOT A TD-MPC2 SCORE. DINO-WM chooses every action here, so the cell must +# never be pooled into the cfg(a) column. RR_TD_SMOKE=1 sends it to td274smoke/ (no table reads +# that directory) and RR_TD_SUF_EXTRA names the swap on the face of the filename. +# +# usage: td_dual_swap_payload.sh [rollouts] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +TASK=${1:?task}; GAMMA=${2:-0.95}; SEED=${3:-0}; ROLL=${4:-50} +TAG=g$(echo "$GAMMA" | tr -d '.') +DWM=$ROOT/runs/$TASK/wm/dinowm/ckpt_best.pt +HOP=$ROOT/runs/$TASK/hop/gauss/policy_r1.pt +for f in "$DWM" "$HOP"; do [ -f "$f" ] || { echo "[td_swap] MISSING $f"; exit 2; }; done +OUT=$ROOT/status/nb/td_dwm_rho_swap_${TASK}_${TAG}_s${SEED}.json + +# gen_q#274 run 40-main, DEFECT 9. THE RESUME GUARD FORECLOSED READ (ii). +# This payload produces TWO artefacts with very different costs: +# * the rho file ($OUT) -- complete as soon as the dual scorer has banked its 50 decisions, which +# happens inside the FIRST episode (400 steps / 8 executed frames = 50 decisions exactly); +# * the 50-ROLLOUT SUCCESS RATE -- read (ii), the within-harness reproduction of DINO-WM's +# published 31.6 / 21.1, which needs all 50 episodes. +# Keying the skip on the rho file alone meant that ANY preemption after episode 1 left the rho +# landed and the success rate permanently unreachable: on requeue the payload exited 0 without +# running. That is exactly what happened to LSF 1897643 -- started 14:03:56Z, rho written 14:04:44Z, +# PREEMPTED 14:04:52Z, requeued 14:08:36Z, and all four slots printed "exists -- skip" and the pack +# reported DONE with num_episodes=1 in every cell. The registered read (ii) was silently skipped by +# a guard whose job is to make preemption harmless. +# The guard stays -- it is what makes the payload resumable -- but it now requires BOTH artefacts. +# The eval's own skip-if-exists guard (td_eval_payload.sh, on $EVALJSON) still prevents any completed +# cell from re-running, and eval_cell.sh resumes from its own .json.partial, so re-entering here +# costs only the episodes that are actually missing. +H=$(awk -v g="$GAMMA" 'BEGIN{printf "%d", int(1/(1-g)+0.5)}') +EVALCELL="E1-TDMPC2-R$GAMMA-$H-tdq-128-argmax-TD274a-SMOKE-DUALSWAP-DWMACTS-es${SEED}-sS0As0" +EVALJSON=$ROOT/runs/$TASK/eval_onactor/td274smoke/${EVALCELL}-s${SEED}.json +if [ -s "$OUT" ] && [ -s "$EVALJSON" ]; then + echo "[td_swap] BOTH artefacts exist -- skip (resumable under preemption)" + echo "[td_swap] rho $OUT" + echo "[td_swap] eval $EVALJSON" + exit 0 +fi +if [ -s "$OUT" ] && [ ! -s "$EVALJSON" ]; then + # Nothing measured is discarded. The landed rho is an anchor set drawn from the episodes that DID + # run before the preemption; the resumed run banks a fresh 50 decisions from the episodes that run + # now, so the canonical name would otherwise silently change meaning. Archive, then proceed. + mkdir -p $ROOT/status/nb/attic + ARCH=$ROOT/status/nb/attic/$(basename ${OUT%.json}).preempted_$(date -u +%Y%m%dT%H%M%SZ).json + cp -p "$OUT" "$ARCH" && rm -f "$OUT" + echo "[td_swap] DEFECT 9 PATH: rho landed but the 50-rollout success leg (read ii) did NOT." + echo "[td_swap] archived the partial-anchor rho -> $ARCH" + echo "[td_swap] re-running so read (ii) can land; the new rho covers the episodes run now." +fi + +# The DINO-WM knobs are the ones its OWN published eval cells record +# (runs//eval_onactor/E1-DINOWM-R0.95-4-N128-argmax-*.json -> planner block): fold, depth 4, +# beta 0.95, gamma 0.99, 16 particles, 8 flow steps, prob, chunk 8. Identical to the un-swapped +# payload, so the only difference between the two runs is which read-out acts. +export RR_TD_SUF_EXTRA=-DUALSWAP-DWMACTS +export RR_TD_SMOKE=1 RR_TD_DUAL_SWAP=1 \ + RR_TD_DUAL_DWM=$DWM RR_TD_DUAL_HOP=$HOP RR_TD_DUAL_OUT=$OUT \ + RR_TD_DUAL_DEPTH=4 RR_TD_DUAL_BETA=0.95 RR_TD_DUAL_GAMMA=0.99 \ + RR_TD_DUAL_PARTICLES=16 RR_TD_DUAL_FLOW=8 \ + RR_TD_DUAL_CELL="SWAPPED dwm-acts $TASK $GAMMA seed$SEED" +echo "[td_swap] $(date -u) host=$(hostname) task=$TASK gamma=$GAMMA seed=$SEED rollouts=$ROLL -> $OUT" +bash $ROOT/scripts/nb/td_eval_payload.sh "$TASK" score "$GAMMA" "$SEED" "$ROLL" +rc=$? + +# Assert the ARTEFACT, never the return code (run 30 lesson: the last command is the exit status). +if [ -s "$OUT" ]; then + echo "[td_swap] RHO LANDED $OUT" + python3 -c " +import json;d=json.load(open('$OUT'))['summary'] +assert d.get('primary')=='dinowm_published', 'THE SWAP DID NOT TAKE: primary is '+str(d.get('primary')) +print('[td_swap] primary(acting)',d['primary'],'secondary',d['secondary']) +print('[td_swap] decisions',d.get('decisions'),'rho_mean',d.get('rho_mean'),'rho_median',d.get('rho_median')) +print('[td_swap] argmax_agree',d.get('argmax_agreement'), + 'rank of DWM pick inside cfg(a):',d.get('mean_rank_of_primary_pick_in_secondary'), + '(63.5 = cfg(a) is indifferent to it)') +" || exit 1 +else + if [ "$rc" = 99 ]; then + echo "[td_swap] NO RHO FILE rc=99 HOST-LEVEL -- index stays reclaimable"; exit 99 + fi + echo "[td_swap] NO RHO FILE rc=$rc (expected: $OUT) -- failing so the queue can reclaim this index" + exit 1 +fi +echo "[td_swap] rc=$rc $(date -u)" diff --git a/rsm_rise/scripts/nb/td_dwm_rho_report.py b/rsm_rise/scripts/nb/td_dwm_rho_report.py new file mode 100644 index 0000000000000000000000000000000000000000..dce942a2c821dfd5e49d15b06614ce4d9a12772d --- /dev/null +++ b/rsm_rise/scripts/nb/td_dwm_rho_report.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""gen_q#274 BLOCKER item 3: read out the TD-MPC2 cfg(a) vs DINO-WM rank-correlation diagnostic. + +The instrument (code/tdmpc2_rise/dual_scorer.py) scores the SAME 128 candidates at the SAME anchors +with two read-outs inside ONE eval: TD-MPC2 cfg(a) (which selects) and DINO-WM's PUBLISHED read-out +(fold, depth 4, beta .95, gamma .99, P16, F8, prob -- copied from that column's own cell JSONs), +which only observes. + +RUN-23 CORRECTION -- THE NULL PRINTED BESIDE argmax_same WAS THE NULL OF A DIFFERENT STATISTIC. +Until 2026-09-24 02:10Z this script printed `argmax_same` (measured by dual_scorer.py:109 as +`int(a.argmax()) == int(b.argmax())`, i.e. INDEX EQUALITY, and numpy returns the FIRST maximal +index) against the null `E[s_ties_at_max]/n` -- which is the null for SET MEMBERSHIP ("did cfg(a) +pick one of the candidates tied at DINO-WM's max?"). Those are not the same quantity, and when the +secondary ties hard the gap is enormous: on threading DINO-WM ties 48.5/128, so index equality is +capped near 1/48.5 ~ 0.021 even for a read-out that always picks inside the tied set, while the +printed null was 0.379. That made an at-chance result read as 19x BELOW chance, and the old +READING block drew exactly that inference ("wrong in the TAIL"). It was an artifact of the +mismatch. Both statistics are now printed, each against its OWN null: + + rho : Spearman over the 128 candidates. Null 0; per-decision sd ~ 1/sqrt(n-1). + pick_in_tieset : is cfg(a)'s pick tied at DINO-WM's max? (rank==0 <=> yes.) This is the + tie-aware agreement statistic. Null E[s_ties_at_max/n] under a uniform pick. + argmax_same : raw index equality, kept for continuity with what was published. Its null + under a uniform pick is 1/n -- it is NOT tie-aware and saturates when the + secondary ties, so pick_in_tieset is the one to read. + rank of the primary's pick in the secondary's ordering (0 = secondary's own best). Null (n-1)/2. + +Every number here is traceable to status/nb/td_dwm_rho__g.json, written by the eval. +usage: td_dwm_rho_report.py [out.txt] +""" +import glob, json, math, os, sys, datetime + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" + + +# run 51-main. THESE NUMBERS ARE READ, NOT RETYPED. This paragraph used to carry "the 8 PAIRED +# cells", "10/400", "9/400", "+0.0025" and "p = 0.4531" as literal strings in the source. They were +# correct when typed and went stale the moment td_ctl_pairs.py gained a cell -- which happened this +# run, when its eval-seed axis landed and its horizon lookup stopped silently dropping the gamma +# 0.995 rung (8 paired cells -> 10, 10/400 -> 12/500). A builder that cites a file must read that +# file. If the file is missing or malformed the sentence says so rather than printing a stale digit. +def _ctl_pairs_prose(root): + import json as _json, os as _os + f = _os.path.join(root, "status/nb/td_ctl_pairs.json") + try: + d = _json.load(open(f)) + except Exception as e: + return [(" status/nb/td_ctl_pairs.json IS UNREADABLE (%s), so the paired-control numbers" + % type(e).__name__), + " are NOT quoted here. Rebuild it with scripts/rr_cpu_nb51_ctlpairs.sh."] + p = d.get("pooled_all_cells") or {} + rows = d.get("rows") or [] + pos = len([r for r in rows if (r.get("sr_argmax") or 0) > (r.get("sr_random") or 0)]) + neg = len([r for r in rows if (r.get("sr_argmax") or 0) < (r.get("sr_random") or 0)]) + tie = len(rows) - pos - neg + ka, na = p.get("k_argmax"), p.get("n_argmax") + kr, nr = p.get("k_random"), p.get("n_random") + if not na or not nr: + return [" td_ctl_pairs.json has no pooled row yet; no paired-control number is quoted."] + diff = ka / na - kr / nr + out = [" across the %d PAIRED cells argmax-of-128 reads %d/%d episode-slots and" + % (len(rows), ka, na), + " random-of-128 reads %d/%d, a difference of %+.4f; the cell-level sign test" + % (kr, nr, diff), + " (argmax better in %d, worse in %d, tied in %d) is the independent unit." + % (pos, neg, tie), + " Eval seeds present in that file: %s. NO POOLED INTERVAL is quoted on this row:" + % (d.get("seeds_present"),), + " cells at the same (task, eval seed) re-evaluate %d distinct initial states." + % (d.get("distinct_states") or 0)] + ind = d.get("pooled_independent_states") + if ind: + out.append(" Independent-states row (gamma %s, across_eval_seeds=%s): argmax %d/%d, " + "random %d/%d." % (ind.get("gamma"), ind.get("across_eval_seeds"), + ind.get("k_argmax"), ind.get("n_argmax"), + ind.get("k_random"), ind.get("n_random"))) + return out + +ROOT_FOR_CTL = ROOT + +out = sys.argv[1] if len(sys.argv) > 1 else os.path.join(ROOT, "status/nb/td_dwm_rho.txt") +paths = sorted(glob.glob(os.path.join(ROOT, "status/nb/td_dwm_rho_*.json"))) + + +def _mean(x): + return sum(x) / len(x) if x else float("nan") + + +def _sem(x): + if len(x) < 2: + return float("nan") + m = _mean(x) + return (sum((v - m) ** 2 for v in x) / len(x) / len(x)) ** 0.5 + + +L = ["== gen_q#274 item 3: TD-MPC2 cfg(a) vs DINO-WM, SAME anchors, SAME 128 candidates, ONE eval", + " %sZ source: status/nb/td_dwm_rho_*.json" % datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M"), + " cfg(a) SELECTS; DINO-WM's published read-out only observes. Selection is untouched.", + " RUN-23: the null beside argmax_same was the null of a DIFFERENT statistic; see the header", + " of scripts/nb/td_dwm_rho_report.py. Corrected below, and the conclusion it supported is", + " WITHDRAWN -- agreement is at or slightly ABOVE chance on both tasks, never below.", ""] +if not paths: + L.append(" NO dual read-out cells have landed yet.") +rows = [] +for p in paths: + d = json.load(open(p)) + s, per = d["summary"], d["per_decision"] + n = int(s.get("n_candidates", 128)) + null_rank = (n - 1) / 2.0 + + rhos = [r["rho"] for r in per if r.get("rho") is not None] + k = len(rhos) + mean_rho = _mean(rhos) + sd_rho = (sum((x - mean_rho) ** 2 for x in rhos) / (k - 1)) ** 0.5 if k > 1 else float("nan") + se_rho = sd_rho / math.sqrt(k) if k > 1 else float("nan") + null_sd_one = 1.0 / math.sqrt(n - 1) + + have = [r for r in per if r.get("rank_of_primary_pick_in_secondary") is not None] + ranks = [r["rank_of_primary_pick_in_secondary"] for r in have] + mean_rank, se_rank = _mean(ranks), _sem(ranks) + # tie-aware agreement: rank == 0 <=> cfg(a)'s pick is tied at DINO-WM's maximum + inset = [1.0 if r["rank_of_primary_pick_in_secondary"] == 0 else 0.0 for r in have] + null_inset = _mean([r["s_ties_at_max"] / float(r["n"]) for r in have if r.get("s_ties_at_max")]) + m_inset, se_inset = _mean(inset), _sem(inset) + z_inset = (m_inset - null_inset) / se_inset if se_inset == se_inset and se_inset else float("nan") + agree = s.get("argmax_agreement", float("nan")) + null_idx = 1.0 / n + z_rank = (mean_rank - null_rank) / se_rank if se_rank == se_rank and se_rank else float("nan") + + L.append("-- %s (%s, %d decisions, %d with a defined rho)" + % (s.get("cell", os.path.basename(p)), os.path.basename(p), s["decisions"], k)) + L.append(" rho mean %+.3f (sd across decisions %.3f, s.e. of the mean %.3f)" + % (mean_rho, sd_rho, se_rho)) + L.append(" median %+.3f q05 %+.3f q25 %+.3f q75 %+.3f q95 %+.3f frac>0 %.3f" + % (s["rho_median"], s["rho_q05"], s["rho_q25"], s["rho_q75"], s["rho_q95"], + s["rho_frac_positive"])) + L.append(" NULL 0.000 +- %.3f per decision (+- %.3f on the mean of %d); z = %+.1f" + % (null_sd_one, null_sd_one / math.sqrt(k) if k else float("nan"), k, + (mean_rho / se_rho) if se_rho and se_rho == se_rho else float("nan"))) + L.append(" pick_in_tieset %.3f +- %.3f NULL %.3f (uniform pick lands in DINO-WM's %.1f/%d" + % (m_inset, se_inset, null_inset, null_inset * n, n)) + L.append(" argmax-tie set); ratio %.2f, z = %+.1f <-- THE tie-aware agreement" + % ((m_inset / null_inset) if null_inset else float("nan"), z_inset)) + L.append(" argmax_same %.3f NULL %.4f (= 1/%d, uniform pick). Raw INDEX equality," + % (agree, null_idx, n)) + L.append(" not tie-aware: capped near 1/%.1f = %.3f here because DINO-WM ties." + % (s["mean_secondary_ties_at_max"], 1.0 / max(s["mean_secondary_ties_at_max"], 1e-9))) + L.append(" cfg(a)'s pick sits at rank %.1f +- %.1f /%d in DINO-WM's ordering NULL %.1f; z = %+.1f" + % (mean_rank, se_rank, n, null_rank, z_rank)) + L.append(" DINO-WM's pick sits at rank %.1f/%d in cfg(a)'s ordering" + % (s["mean_rank_of_secondary_pick_in_primary"], n)) + L.append(" spread cfg(a) %.5f DINO-WM %.5f ties@max cfg(a) %.2f DINO-WM %.2f (of %d)" + % (s["mean_primary_spread"], s["mean_secondary_spread"], + s["mean_primary_ties_at_max"], s["mean_secondary_ties_at_max"], n)) + if s.get("secondary_error"): + L.append(" !! secondary read-out reported: %s" % s["secondary_error"]) + L.append("") + rows.append(dict(cell=s.get("cell"), rho=mean_rho, rho_se=se_rho, + pick_in_tieset=m_inset, pick_in_tieset_se=se_inset, + null_pick_in_tieset=null_inset, z_pick_in_tieset=z_inset, + argmax_same=agree, null_argmax_same=null_idx, + rank=mean_rank, rank_se=se_rank, null_rank=null_rank, z_rank=z_rank, + decisions=s["decisions"], n=n, path=p)) + +if rows: + L.append("READING (applies to every row above):") + L.append(" * rho well below 1 with BOTH read-outs ordering the same candidates means the two") + L.append(" disagree about the ranking itself -- not that one of them is constant. The pooled") + L.append(" health table (status/nb/nb274_health.txt) already showed cfg(a) is not inert.") + L.append(" * WITHDRAWN (run 23): the previous version of this file concluded that cfg(a) agrees") + L.append(" with DINO-WM at or BELOW chance at the executed point, and read that as an ordering") + L.append(" 'weakly right in the bulk and wrong in the TAIL'. That rested on comparing an") + L.append(" index-equality statistic against a set-membership null. Corrected, cfg(a) is at or") + L.append(" slightly ABOVE chance on both tasks, and the 'wrong in the tail' claim is not") + L.append(" supported by this instrument. No measured quantity changed -- only its null.") + L.append(" * What stands: agreement is WEAK. The bulk ordering carries real information") + L.append(" (the rank statistic is many sigma better than chance), the tie-set agreement is") + L.append(" within ~1-2 sigma of chance, and cfg(a)'s spread is ~5x narrower than DINO-WM's.") + L.append(" * The claim with teeth is NOT here: it is the paired random-of-128 control") + L.append(" (status/nb/td_ctl_pairs.txt):") + for _l in _ctl_pairs_prose(ROOT_FOR_CTL): + L.append(_l) + L.append(" RUN-27 CORRECTION: this line previously said the two `tie EXACTLY at 7/350 each`.") + L.append(" That pooling was withdrawn on 2026-09-24 (run 25) because every cell runs at") + L.append(" exp.eval_seed = 0, so the 350 slots were re-evaluations of 100 distinct initial") + L.append(" states. The reading is unchanged; the statistic supporting it is the sign test.") + L.append(" Weak-but-real agreement with DINO-WM's bulk ordering and zero measurable benefit") + L.append(" from acting on it are consistent, and together they are the finding.") +os.makedirs(os.path.dirname(out), exist_ok=True) +open(out, "w").write("\n".join(L) + "\n") +json.dump(rows, open(out.replace(".txt", ".json"), "w"), indent=1) +print("\n".join(L)) +print("[td_dwm_rho_report] wrote %s" % out) diff --git a/rsm_rise/scripts/nb/td_dwm_rho_tab.py b/rsm_rise/scripts/nb/td_dwm_rho_tab.py new file mode 100644 index 0000000000000000000000000000000000000000..e9fbb31b2bc3d2e1c6974fc83d46c3457ba2d7d8 --- /dev/null +++ b/rsm_rise/scripts/nb/td_dwm_rho_tab.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python +"""gen_q#274 BLOCKER item 3 -- cfg(a) vs DINO-WM rank correlation on IDENTICAL candidates. + +WHY THIS FILE EXISTS (run 34). Both artefacts have been on disk for hours and only mug was ever +reported: status/nb/td_dwm_rho_mug_expert_suboptimal_g095.json landed 2026-09-23 21:44Z and +status/nb/td_dwm_rho_threading_expert_play_g095.json landed 2026-09-24 01:43Z -- the threading one +with 500 decisions, 10x mug's 50. It went unread because its payload +(runs/_nb/jobs/nb_slot_td_dual_thr.sh) carries `rc=1` in BOTH q_nb13_td.done and q_nb16_td.done, so +every later run read it as a twice-refused arm and skipped it. The rc=1 is a POST-WRITE failure: +the JSON is complete and 136 KB. Recorded here because "a retired payload" and "a payload whose +result landed and whose exit status lied" look identical from the queue bookkeeping. + +WHAT IT DECIDES. The orchestrator's live hypothesis is that cfg(a) is not inert but produces a +WRONG ORDERING of the shared 128 candidates. This instrument scores DINO-WM's published read-out on +EXACTLY the candidates cfg(a) scored, at exactly cfg(a)'s decision points, so the two orderings are +directly comparable and nothing about the pool differs. + +THE ASYMMETRY IS THE POINT, and it is why both directions are printed. `rank_of_primary_pick_in_ +secondary` asks "where does the candidate TD-MPC2 chose sit in DINO-WM's order?" The reverse asks +"where does DINO-WM's choice sit in TD-MPC2's order?" A low value in the FIRST direction with a +near-random value in the second means the two read-outs are not simply uncorrelated: DINO-WM +endorses cfg(a)'s pick while cfg(a) does not endorse DINO-WM's. + +AND THE LIMIT ON WHAT IT CAN SAY, stated before the numbers. These decision points lie on +cfg(a)'s OWN trajectory, which fails. So agreement here is agreement about states cfg(a) reached; +it is NOT evidence about the states DINO-WM reaches on its own successful rollouts, and it cannot +by itself attribute DINO-WM's 21-32% to its ranking rather than to where it ends up. +""" +from __future__ import annotations +import glob, json, os, statistics as st, sys + +ROOT = "/proj/dmfexp/zwhong/rsm_rise" +ND = f"{ROOT}/status/nb" +# OUTPUT PATH, CHANGED IN RUN 55 (gen_q#274). This file used to write `td_dwm_rho.txt` -- the SAME +# published path as `td_dwm_rho_report.py`, which renders the same underlying JSONs completely +# differently (a flat per-file list, plus a live quote of td_ctl_pairs.json). Two writers, no +# arbitration: the content of a published status file depended on which script happened to run last, +# and the two renderings differ in a way that matters -- only THIS one separates the un-swapped and +# swapped rows into labelled blocks and carries the "a success rate from the swapped block is NOT a +# TD-MPC2 number" warning. Neither rendering is redundant, so neither was deleted; they were given +# distinct names. `td_dwm_rho.txt` stays the report's, because the chain rebuilds that one. +OUT = f"{ND}/td_dwm_rho_blocks.txt" + + +def q(xs, p): + xs = sorted(xs) + return xs[min(len(xs) - 1, int(p * len(xs)))] + + +def parse_name(bn): + """td_dwm_rho_[swap_]_g[_s].json -> (swapped, task, gamma, seed) or None. + + GAMMA. The payload writes the tag as `g$(echo $GAMMA | tr -d '.')`, so 0.95 -> "095" and + 0.9 -> "09". The pre-run-39 inverse was + float("0."+gtag) if not gtag.startswith("0") else float(gtag) + which sent "095" down the else branch and printed the gamma column as **95.000** in the + published status/nb/td_dwm_rho.txt. A leading "0" means the decimal point goes AFTER it. + """ + if not bn.startswith("td_dwm_rho_") or not bn.endswith(".json"): + return None + base = bn[len("td_dwm_rho_"):-len(".json")] + swapped = base.startswith("swap_") + if swapped: + base = base[len("swap_"):] + seed = None + if "_s" in base: + head, tail = base.rsplit("_s", 1) + if tail.isdigit(): + base, seed = head, int(tail) + if "_g" not in base: + return None + task, gtag = base.rsplit("_g", 1) + if not gtag.isdigit(): + return None + gam = float("0." + gtag[1:]) if gtag.startswith("0") else float(gtag) + return swapped, task, gam, seed + + +def main(): + files = sorted(glob.glob(f"{ND}/td_dwm_rho_*_g*.json")) + if not files: + sys.stderr.write("no td_dwm_rho_*_g*.json on disk\n") + return 3 + # RUN 39-main. The swapped runs (RR_TD_DUAL_SWAP=1, scripts/nb/td_dual_swap_payload.sh) write + # td_dwm_rho_swap__g_s.json, which MATCHES the glob above. Before this patch + # the parser hit float("0.095_s0") and raised ValueError, so the first swapped file to land + # would have taken the WHOLE table down -- including the un-swapped rows that were already + # correct. They are now parsed, and printed in a SEPARATE block, because a swapped run is not + # a TD-MPC2 score: DINO-WM chooses every action in it. + files = [f for f in files if parse_name(os.path.basename(f)) is not None] + unsw = [f for f in files if not parse_name(os.path.basename(f))[0]] + sw = [f for f in files if parse_name(os.path.basename(f))[0]] + out = [] + for lbl, grp in (("UN-SWAPPED", unsw), ("SWAPPED", sw)): + if not grp: + out.append("") + out.append("#" * 107) + if lbl == "SWAPPED": + out.append("SWAPPED BLOCK: no td_dwm_rho_swap_*.json on disk yet (LSF 1897643). The matched-anchor") + out.append("question -- how cfg(a) ranks candidates at the states DINO-WM actually visits -- is") + out.append("therefore STILL UNMEASURED, and the CAVEAT at the end of the un-swapped block stands.") + else: + out.append("UN-SWAPPED BLOCK: no artefacts.") + out.append("#" * 107) + continue + out.append("") + out.append("#" * 107) + if lbl == "UN-SWAPPED": + out.append("BLOCK 1 of 2 -- UN-SWAPPED. **TD-MPC2 cfg(a) SELECTS EVERY ACTION.** DINO-WM is scored") + out.append("alongside but never acts. Anchors are cfg(a)'s own trajectory. These rows ARE cfg(a)'s.") + else: + out.append("BLOCK 2 of 2 -- SWAPPED (RR_TD_DUAL_SWAP=1). **DINO-WM SELECTS EVERY ACTION.** cfg(a) is") + out.append("scored alongside but never acts. Anchors are DINO-WM's own trajectory, which is the") + out.append("matched-anchor regime the un-swapped block's caveat says it cannot reach.") + out.append("!! A SUCCESS RATE FROM THIS BLOCK IS **NOT** A TD-MPC2 NUMBER. It is the DINO-WM read-out") + out.append("!! measured inside our harness on the shared 128-candidate pool, and must never be pooled") + out.append("!! into, or quoted as, the TD-MPC2 cfg(a) column.") + out.append("#" * 107) + out.extend(_render(grp, swapped=(lbl == "SWAPPED"))) + txt = "\n".join(out) + "\n" + open(OUT, "w").write(txt) + print(txt) + return 0 + + +def _render(files, swapped=False): + """RUN 41-main, DEFECT 10 -- THE ROLE LABELS WERE FIXED STRINGS IN A RENDERER SHARED BY BOTH BLOCKS. + + Every per-decision field in the artefact is named by ROLE -- primary = the read-out that ACTS, + secondary = the one that only observes. In the swapped block the primary is DINO-WM, so the + columns hard-coded as `TDpick_in_DWM`, `TD_spread` and `TD_ties` were printing DINO-WM's numbers + under TD-MPC2's name and vice versa. It was not cosmetic: the swapped mug seed-0 row printed + "!! cfg(a) is FLAT (spread < 1e-4)" when the 3e-14 spread belongs to DINO-WM, i.e. the table + named the wrong estimator as the broken one, in the artefact the blocker asks us to read. + The columns are now named from the role, with the acting side marked, so block 2 cannot be + read as block 1. + """ + ACT, OBS = ("DINO-WM", "cfg(a)") if swapped else ("cfg(a)", "DINO-WM") + o = [] + o.append("gen_q#274 BLOCKER item 3 -- TD-MPC2 cfg(a) vs DINO-WM RANK CORRELATION on identical candidates") + o.append("MACHINE-GENERATED by scripts/nb/td_dwm_rho_tab.py from status/nb/td_dwm_rho__g*.json.") + o.append("Both read-outs score THE SAME 128 candidates at THE SAME decision points, so nothing about") + o.append("the candidate pool differs between them. Read the caveat at the end before quoting.") + o.append("") + # run 46-main, TRACEABILITY DEFECT. Every number in this table was computed from + # `per_decision`, and dual_scorer.py:153 writes `self.rows[-2000:]` -- the LAST 2000 decisions -- + # to bound the file size. For the 2400-decision seeds (s2/s3) the table therefore read a + # SUFFIX of the run, dropped the earliest 400 decisions, and printed `dec 2000` for a run that + # made 2400. Dropping the EARLIEST decisions is not neutral: they are early-episode states. + # The summary block carries the un-truncated mean, so both are printed and the shortfall is + # marked. On the four seeds on disk today the two agree to <0.005 rho and no reading moves -- + # which is the point of printing them side by side rather than asserting it. + hdr = (f"{'task':22s} {'g':>5s} {'dec':>5s} {'decAll':>6s} {'rho_n':>6s} {'rho_mean':>9s} {'rhoAll':>8s} {'ci95_lo':>8s} {'ci95_hi':>8s} " + f"{'rho_med':>8s} {'frac>0':>7s} {'argmax_agree':>12s} {'chance':>7s}") + o.append(hdr) + o.append("-" * len(hdr)) + rows, truncated = [], [] + for f in files: + d = json.load(open(f)) + s, pdn = d["summary"], d["per_decision"] + task = s.get("cell", os.path.basename(f)).split()[-2] if " " in str(s.get("cell", "")) else os.path.basename(f) + # take the task/gamma off the filename, which is the authoritative provenance + swapped, task, gam, seed = parse_name(os.path.basename(f)) + rh = [r["rho"] for r in pdn if r.get("rho") is not None and r["rho"] == r["rho"]] + n = len(rh) + m = sum(rh) / n + sd = st.stdev(rh) if n > 1 else float("nan") + ci = 1.96 * sd / n ** 0.5 if n > 1 else float("nan") + ag = [bool(r.get("argmax_same")) for r in pdn] + nc = int(s.get("n_candidates", 128)) + dec_all = int(s.get("decisions", len(pdn))) + rho_all = s.get("rho_mean") + trunc = dec_all > len(pdn) + if trunc: + truncated.append((task, gam, seed, len(pdn), dec_all, m, rho_all)) + o.append(f"{task[:22]:22s} {gam:5.3f} {len(pdn):5d} {dec_all:6d}{'*' if trunc else ' '} {n:6d} {m:+9.4f} " + f"{(f'{rho_all:+8.4f}' if isinstance(rho_all, (int, float)) else ' -')} " + f"{m - ci:+8.4f} {m + ci:+8.4f} " + f"{st.median(rh):+8.4f} {sum(1 for x in rh if x > 0) / n:7.2f} " + f"{sum(ag) / len(ag):12.3f} {1.0 / nc:7.4f}") + rows.append((task, gam, s, pdn, rh, m, ci, nc)) + o.append("") + if truncated: + o.append("!! TRUNCATION, MARKED * ABOVE. dual_scorer.py:153 writes per_decision as rows[-2000:], so") + o.append("!! for these seeds every OTHER column of this table (rho_n, rho_mean, the CI, the two") + o.append("!! directions, the spread/ties block) is computed over the LAST len(pdn) decisions only.") + o.append("!! `decAll` and `rhoAll` come from the artefact's own summary block and cover the whole run.") + for task, gam, seed, npd, nall, m, ra in truncated: + d = (m - ra) if isinstance(ra, (int, float)) else float("nan") + o.append(f"!! {task[:22]:22s} g={gam:5.3f} s{seed} per_decision {npd} of {nall} " + f"({nall - npd} earliest dropped) rho_trunc {m:+.4f} vs rho_all {ra:+.4f} diff {d:+.4f}") + o.append("!! A reading may only be quoted from the truncated column when the two agree; where they") + o.append("!! do not, rhoAll is the run and the truncated one is a suffix of it.") + o.append("") + o.append("=" * len(hdr)) + o.append("THE TWO DIRECTIONS. rank is 1 = best, so 1 means 'the other read-out's favourite too' and") + o.append(f"{'(n_candidates+1)/2':s} is what an unrelated ordering gives.") + o.append("=" * len(hdr)) + h2 = (f"{'task':22s} {'g':>5s} {(ACT+'pick_in_'+OBS)[:20]:>20s} {'median':>7s} | " + f"{(OBS+'pick_in_'+ACT)[:20]:>20s} {'median':>7s} | {'random':>7s} reading") + o.append(h2) + o.append("-" * len(h2)) + for task, gam, s, pdn, rh, m, ci, nc in rows: + a = [r["rank_of_primary_pick_in_secondary"] for r in pdn + if r.get("rank_of_primary_pick_in_secondary") is not None] + b = [r["rank_of_secondary_pick_in_primary"] for r in pdn + if r.get("rank_of_secondary_pick_in_primary") is not None] + if not a or not b: + o.append(f"{task[:22]:22s} {gam:5.3f} (a direction is missing from the artefact)") + continue + rnd = (nc + 1) / 2 + ma, mb = st.median(a), st.median(b) + if ma < rnd / 3 and mb > rnd / 2: + rd = (f"ASYMMETRIC: {OBS} rates {ACT}'s pick near the TOP of its own order while " + f"{ACT} does NOT rate {OBS}'s") + elif ma > rnd * 0.8 and mb > rnd * 0.8: + rd = "both near random: the two read-outs order these candidates independently" + else: + rd = "partial agreement in both directions" + o.append(f"{task[:22]:22s} {gam:5.3f} {sum(a)/len(a):20.1f} {ma:7.1f} | " + f"{sum(b)/len(b):20.1f} {mb:7.1f} | {rnd:7.1f} {rd}") + o.append("") + o.append("=" * len(hdr)) + o.append("SPREAD AND TIES ON BOTH SIDES, so a near-zero rho cannot be blamed on one side being flat.") + o.append(f"* = the ACTING read-out in this block ({ACT}). Columns are named by ROLE, not by method.") + o.append("=" * len(hdr)) + h3 = (f"{'task':22s} {'g':>5s} {(ACT+'_sprd*'):>12s} {(ACT+'_ties'):>12s} | " + f"{(OBS+'_sprd'):>11s} {(OBS+'_ties'):>11s} reading") + o.append(h3) + o.append("-" * len(h3)) + for task, gam, s, pdn, rh, m, ci, nc in rows: + ps, pt = s.get("mean_primary_spread"), s.get("mean_primary_ties_at_max") + ss, stt = s.get("mean_secondary_spread"), s.get("mean_secondary_ties_at_max") + if None in (ps, pt, ss, stt): + continue + flat = [nm for nm, sp in ((ACT, ps), (OBS, ss)) if sp < 1e-4] + rd = (f"!! {'/'.join(flat)} is FLAT (spread < 1e-4): the rho above is uninterpretable" + if flat else "both sides have live spread, so the rho is a real disagreement") + o.append(f"{task[:22]:22s} {gam:5.3f} {ps:12.6f} {pt:12.2f} | {ss:11.6f} {stt:11.2f} {rd}") + o.append("") + o.append("READING") + for task, gam, s, pdn, rh, m, ci, nc in rows: + lo, hi = m - 1.96 * st.stdev(rh) / len(rh) ** 0.5, m + 1.96 * st.stdev(rh) / len(rh) ** 0.5 + zero = "includes 0" if lo <= 0 <= hi else "excludes 0" + o.append(f" {task} g={gam}: mean Spearman rho {m:+.4f}, 95% CI {zero} [{lo:+.4f}, {hi:+.4f}] over") + o.append(f" {len(rh)} decisions with a defined rho out of {len(pdn)}. A rho of this SIZE means the two") + o.append(" read-outs order the same 128 candidates nearly independently, whether or not the CI") + o.append(" clears zero -- the CI answers 'is it exactly 0', not 'is it large'.") + o.append("") + if not swapped: + o.append("CAVEAT -- WHAT THIS CANNOT SAY. Every decision point here lies on cfg(a)'s OWN trajectory,") + o.append("and that trajectory fails. Agreement here is agreement about the states cfg(a) REACHED. It") + o.append("is not evidence about the states DINO-WM reaches on its own successful rollouts, so it cannot") + o.append("on its own attribute DINO-WM's published 21-32% to its ranking rather than to where it ends") + o.append("up. The matched-anchor version of that question needs DINO-WM's own rollout anchors and is") + o.append("NOT measured here -- see BLOCK 2, which measures exactly that.") + else: + o.append("CAVEAT -- WHAT THIS BLOCK CAN AND CANNOT SAY. The anchors here ARE DINO-WM's own rollout") + o.append("states, so this IS the matched-anchor measurement block 1 says it cannot make. Two limits") + o.append("stand. (1) EACH ROW IS ONE SEED of 50 decisions and the seeds disagree strongly, so the") + o.append("matched-anchor rho is not yet pinned -- read the two rows per task together, never one") + o.append("alone. (2) The SUCCESS RATE of these runs is the separately registered read (ii) and is") + o.append("NOT in this table; it lives in the eval JSON named in the report. Nothing here is a") + o.append("TD-MPC2 score: DINO-WM chose every action.") + o.append("") + o.append(f"built {__import__('datetime').datetime.utcnow().strftime('%Y-%m-%d %H:%MZ')} from " + f"{len(files)} artefact(s): {', '.join(os.path.basename(f) for f in files)}") + return o + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/rsm_rise/scripts/nb/td_dynrange.py b/rsm_rise/scripts/nb/td_dynrange.py new file mode 100644 index 0000000000000000000000000000000000000000..976894dda4405fd10551254d76fc2d948bad0967 --- /dev/null +++ b/rsm_rise/scripts/nb/td_dynrange.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +"""gen_q#274 run 24 -- WHY cfg(a)'s ordering does not convert: the candidates span a small +fraction of the ONLY axis the TD-MPC2 value head was ever trained to separate. + +This adds no new measurement. Every number below is read out of a file that was already +written and already published; the contribution is putting two of them in the SAME unit, +which nobody has done, and which changes what the cfg(a) column should be said to be. + +THE UNIT. td_backend.py:135-136 computes the cfg(a) `prob` score as + + vmax = 1/(1-gamma) # the discounted ceiling of a binary provenance reward + qbar = (v / vmax).clamp(0, 1) # <- THE SCORE. a strictly monotone rescale of v by a CONSTANT + +so cfg(a)'s score lives in [0, 1] and so does DINO-WM's membership probability. Their spreads +were therefore already comparable; what was NOT in that unit is the value head's own training +signal, which train_tdmpc2.evaluate logs in RAW value units (val/q_expert, val/q_other, val/q_std). +Dividing those by the SAME vmax puts the model's own discrimination on the score's axis. + +THE TWO RATIOS. + D_model = (q_expert - q_other)/vmax + The gap the head actually learned: expert frames vs everything else, in score units. + val/q_auc == 1.0 on every v2 model, i.e. that separation is PERFECT on validation. + S_cand = mean_primary_spread + The spread cfg(a) produces ACROSS THE 128 CANDIDATES it is asked to rank, measured inside + the dual-scorer eval on candidates shared bit-for-bit with DINO-WM. + S_cand / D_model + How much of the learned axis the ranking problem occupies. Small means the head is not + broken and not saturated -- it is being asked a question orthogonal to the one it was fit on: + all 128 candidates are near-expert continuations, i.e. they sit on the SAME side of the only + boundary the head has. + S_cand / (q_std/vmax) + The same spread against the head's own within-validation s.d. -- the noise floor of the + quantity being differenced. + +This is a diagnosis, not an excuse: it is a property of the read-out TD-MPC2 prescribes +(`_estimate_value` = discounted learned reward + terminal Q) meeting a binary provenance reward, +and it is exactly what a reader should be told beside the 0.020. It does NOT rescue the column. + +usage: td_dynrange.py (writes status/nb/td_dynrange.{txt,json}) +""" +import json, math, os, random, sys + + + +# run 51-main. THESE NUMBERS ARE READ, NOT RETYPED. This paragraph used to carry "the 8 PAIRED +# cells", "10/400", "9/400", "+0.0025" and "p = 0.4531" as literal strings in the source. They were +# correct when typed and went stale the moment td_ctl_pairs.py gained a cell -- which happened this +# run, when its eval-seed axis landed and its horizon lookup stopped silently dropping the gamma +# 0.995 rung (8 paired cells -> 10, 10/400 -> 12/500). A builder that cites a file must read that +# file. If the file is missing or malformed the sentence says so rather than printing a stale digit. +def _ctl_pairs_prose(root): + import json as _json, os as _os + f = _os.path.join(root, "status/nb/td_ctl_pairs.json") + try: + d = _json.load(open(f)) + except Exception as e: + return [(" status/nb/td_ctl_pairs.json IS UNREADABLE (%s), so the paired-control numbers" + % type(e).__name__), + " are NOT quoted here. Rebuild it with scripts/rr_cpu_nb51_ctlpairs.sh."] + p = d.get("pooled_all_cells") or {} + rows = d.get("rows") or [] + pos = len([r for r in rows if (r.get("sr_argmax") or 0) > (r.get("sr_random") or 0)]) + neg = len([r for r in rows if (r.get("sr_argmax") or 0) < (r.get("sr_random") or 0)]) + tie = len(rows) - pos - neg + ka, na = p.get("k_argmax"), p.get("n_argmax") + kr, nr = p.get("k_random"), p.get("n_random") + if not na or not nr: + return [" td_ctl_pairs.json has no pooled row yet; no paired-control number is quoted."] + diff = ka / na - kr / nr + out = [" across the %d PAIRED cells argmax-of-128 reads %d/%d episode-slots and" + % (len(rows), ka, na), + " random-of-128 reads %d/%d, a difference of %+.4f; the cell-level sign test" + % (kr, nr, diff), + " (argmax better in %d, worse in %d, tied in %d) is the independent unit." + % (pos, neg, tie), + " Eval seeds present in that file: %s. NO POOLED INTERVAL is quoted on this row:" + % (d.get("seeds_present"),), + " cells at the same (task, eval seed) re-evaluate %d distinct initial states." + % (d.get("distinct_states") or 0)] + ind = d.get("pooled_independent_states") + if ind: + out.append(" Independent-states row (gamma %s, across_eval_seeds=%s): argmax %d/%d, " + "random %d/%d." % (ind.get("gamma"), ind.get("across_eval_seeds"), + ind.get("k_argmax"), ind.get("n_argmax"), + ind.get("k_random"), ind.get("n_random"))) + return out + +R = "/proj/dmfexp/zwhong/rsm_rise" +NB = os.path.join(R, "status", "nb") + +CELLS = [ + # (task, gamma, gamma tag used in the wm dir, rho json) + ("threading_expert_play", 0.95, "g095", "td_dwm_rho_threading_expert_play_g095.json"), + ("mug_expert_suboptimal", 0.95, "g095", "td_dwm_rho_mug_expert_suboptimal_g095.json"), +] + + +def last_health(task, tag): + p = os.path.join(R, "runs", task, "wm", f"tdmpc2v2_{tag}", "health.jsonl") + rows = [json.loads(l) for l in open(p) if l.strip()] + return p, rows[-1] + + +def boot_ci(xs, n=2000, seed=0): + """Percentile bootstrap on the mean. Seeded, so the interval is reproducible.""" + if not xs: + return (float("nan"), float("nan")) + rng = random.Random(seed) + k = len(xs) + ms = [] + for _ in range(n): + ms.append(sum(xs[rng.randrange(k)] for _ in range(k)) / k) + ms.sort() + return ms[int(0.025 * n)], ms[int(0.975 * n)] + + +def main(): + out, rows = [], [] + A = out.append + A("=== gen_q#274 cfg(a): the candidates against the axis the value head actually learned ===") + A("Built by scripts/nb/td_dynrange.py. NO new measurement -- every input is a landed file,") + A("named on its own row. The only new thing is the common unit: td_backend.py:135-136 makes") + A("the cfg(a) score qbar = (v/vmax).clamp(0,1), so dividing the health row's RAW value stats by") + A("the same vmax = 1/(1-gamma) puts the model's own training signal on the score's own axis.") + A("") + for task, gamma, tag, rho_name in CELLS: + rp = os.path.join(NB, rho_name) + if not os.path.exists(rp): + A(f"-- {task} g{gamma}: MISSING {rho_name} -- cell skipped, not estimated"); A("") + continue + rho = json.load(open(rp)) + s = rho["summary"] + hp, h = last_health(task, tag) + vmax = 1.0 / (1.0 - gamma) + qe, qo, qsd = h["val/q_expert"], h["val/q_other"], h["val/q_std"] + D = (qe - qo) / vmax + N = qsd / vmax + S = s["mean_primary_spread"] + Sd = s["mean_secondary_spread"] + per = [d["p_spread"] for d in rho["per_decision"] if d.get("p_spread") is not None] + lo, hi = boot_ci(per) + A(f"-- {task} gamma {gamma} (H = 1/(1-gamma) = {vmax:g}) {s['decisions']} decisions," + f" {int(s['n_candidates'])} shared candidates") + A(f" value head, from {os.path.relpath(hp, R)} (step {h.get('step')}):") + A(f" val/q_auc {h['val/q_auc']:.3f} expert-vs-other separation on validation") + A(f" val/q_expert {qe:.5f} val/q_other {qo:.5f} ceiling {vmax:g}") + A(f" val/q_headw_absmax {h['val/q_headw_absmax']:.4f} (0 would be the pre-T6 dead head)") + A(f" in the SCORE's unit (divide by {vmax:g}):") + A(f" D_model = (q_expert-q_other)/vmax = {D:.5f} the gap the head learned") + A(f" noise = q_std/vmax = {N:.5f} its own within-val s.d.") + A(f" S_cand = mean spread over the 128 candidates = {S:.5f}" + f" [bootstrap 95% {lo:.5f}, {hi:.5f}]") + A(f" RATIOS") + A(f" S_cand / D_model = {S / D:.3f} <- the 128 candidates span {100 * S / D:.1f}% of the") + A(f" only axis this head was ever fit to separate") + A(f" S_cand / noise = {S / N:.3f} <- and {100 * S / N:.1f}% of the head's own val s.d.") + A(f" FOR SCALE, same decisions, same candidates, DINO-WM's published read-out (also in [0,1]):") + A(f" S_cand(DINO-WM) = {Sd:.5f} = {Sd / S:.2f}x cfg(a); as a share of cfg(a)'s" + f" D_model, {100 * Sd / D:.1f}%") + A(f" file {rho_name}") + A("") + rows.append(dict(task=task, gamma=gamma, vmax=vmax, decisions=s["decisions"], + n_candidates=s["n_candidates"], q_auc=h["val/q_auc"], + q_expert=qe, q_other=qo, q_std=qsd, + q_headw_absmax=h["val/q_headw_absmax"], + D_model=D, noise=N, S_cand=S, S_cand_ci=[lo, hi], + S_cand_dinowm=Sd, ratio_D=S / D, ratio_noise=S / N, + health_file=os.path.relpath(hp, R), rho_file=rho_name)) + A("READING -- what this does and does not establish") + A(" * It does NOT rescue the cfg(a) column. The paired random-of-128 control still shows no") + A(" measurable benefit from the ordering (status/nb/td_ctl_pairs.txt):") + for _l in _ctl_pairs_prose(R): + A(_l) + A(" This says WHY, it does not say otherwise.") + A(" RUN-27 CORRECTION. This paragraph previously read `7/350 vs 7/350, Fisher p = 1.0000`.") + A(" That pooling was WITHDRAWN on 2026-09-24 (run 25): all cells run at exp.eval_seed = 0,") + A(" so 7 cells x 50 episodes are re-evaluations of 100 DISTINCT initial states, not 350") + A(" independent ones, and any interval on 350 is ~2x too narrow. The conclusion is") + A(" unchanged -- acting on the ordering is not distinguishable from ignoring it, and this") + A(" excludes a LARGE effect only -- but the statistic backing it is the sign test above.") + A(" * It is NOT the saturation hypothesis. Saturation would show as a clamped, tied score;") + A(" cfg(a) ties 5.7/128 on threading against DINO-WM's 48.5, and selecting on the unclamped") + A(" `logit` pre-image halved the ties and moved the success rate not at all") + A(" (status/nb/nb274_health.txt:20-21). The head has range; the CANDIDATES do not use it.") + A(" * It IS a property of the prescribed read-out meeting our reward. `_estimate_value` is") + A(" discounted learned reward + terminal Q; with a binary provenance reward every plausible") + A(" candidate is an expert-looking continuation, so all 128 sit on one side of the only") + A(" boundary val/q_auc = 1.0 certifies. A dense task reward would not have this shape.") + A(" * Honest caveat: D_model is measured on the VALIDATION expert/other split, not on the") + A(" candidate distribution, so it is an upper bound on the separation available among") + A(" candidates -- which makes S_cand/D_model an upper bound too. The true share is smaller.") + txt = "\n".join(out) + "\n" + open(os.path.join(NB, "td_dynrange.txt"), "w").write(txt) + json.dump(dict(rows=rows, built_by="scripts/nb/td_dynrange.py"), + open(os.path.join(NB, "td_dynrange.json"), "w"), indent=1) + sys.stdout.write(txt) + + +if __name__ == "__main__": + main() diff --git a/rsm_rise/scripts/nb/td_dynrange.sh b/rsm_rise/scripts/nb/td_dynrange.sh new file mode 100644 index 0000000000000000000000000000000000000000..54c4c77c657311049b5c39043e0d95e76d77a148 --- /dev/null +++ b/rsm_rise/scripts/nb/td_dynrange.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -uo pipefail +R=/proj/dmfexp/zwhong/rsm_rise +cd $R +python3 $R/scripts/nb/td_dynrange.py +echo "[td_dynrange] rc=$? $(date -u)" diff --git a/rsm_rise/scripts/nb/td_env_probe.sh b/rsm_rise/scripts/nb/td_env_probe.sh new file mode 100644 index 0000000000000000000000000000000000000000..83990974f6097a7432bd39b60d68ab1883c8a260 --- /dev/null +++ b/rsm_rise/scripts/nb/td_env_probe.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# gen_q#274 -- can TD-MPC2's world model be loaded INSIDE the RISE eval environment? +# +# WHY. Both TD-MPC2 configurations run in the eval process ($ROOT/env, python 3.10, torch 2.5.1): +# cfg(a) as a scorer the RSM planner calls, cfg(b) as a get_action replacement. Measured LSF +# 1881480 13:34Z, every attempt of both: +# ModuleNotFoundError: No module named 'tensordict' +# $ROOT/env has no tensordict; venv_tdmpc2 has 0.14.2 built against torch 2.14 and CANNOT be copied +# in (it ships compiled extensions bound to that torch). Same shape of problem as DF's +# rotary_embedding_torch, but NOT solvable the same way, so this probe measures rather than assumes. +# +# It tries, in order, tensordict versions that pair with torch 2.5, installed with --target into an +# ISOLATED directory (no shared environment is mutated), and for each one reports whether +# (i) it imports, (ii) upstream's WorldModel constructs, +# (iii) OUR v2 checkpoint loads into it and gives the same Q on a fixed input as venv_tdmpc2 does. +# (iii) is the one that matters: a version that imports but changes the numbers is not usable. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +OUT=$ROOT/status/nb/td_env_probe.txt +DEPS=$ROOT/code/tdmpc2_rise/_deps +CK=$ROOT/runs/threading_expert_play/wm/tdmpc2v2_g095/ckpt_s30000.pt +exec > >(tee $OUT) 2>&1 +echo "== $(date -u) host=$(hostname) ==" +source $ROOT/scripts/env.sh +python -c "import torch;print('eval env torch', torch.__version__)" + +# reference value from the env TD-MPC2 was trained in +echo "-- reference Q from venv_tdmpc2 (torch 2.14 / tensordict 0.14.2)" +$ROOT/venv_tdmpc2/bin/python - "$CK" <<'PY' +import sys, torch +sys.path.insert(0, "/proj/dmfexp/zwhong/rsm_rise/code/tdmpc2_rise") +from td_backend import TDMPC2Backend # the very object the scorer wraps +b = TDMPC2Backend(sys.argv[1], device="cpu") +g = torch.Generator().manual_seed(0) +z = torch.randn(4, b.d_z, generator=g) +a = torch.zeros(1, 4, 7) +with torch.no_grad(): + v = b._estimate_value(b.core.encode(z, None), a) +print("REF_Q", [round(float(x), 8) for x in v.flatten()[:4]]) +PY + +for V in 0.6.2 0.6.1 0.6.0 0.5.0; do + echo "== trying tensordict==$V into $DEPS/td$V" + rm -rf $DEPS/td$V; mkdir -p $DEPS/td$V + pip install --no-input --disable-pip-version-check --no-deps --target $DEPS/td$V "tensordict==$V" \ + > $DEPS/td$V/pip.log 2>&1 || { echo " pip FAILED (tail)"; tail -3 $DEPS/td$V/pip.log; continue; } + PYTHONPATH=$DEPS/td$V:$ROOT/code/tdmpc2_rise:$ROOT/code/tdmpc2/tdmpc2 python - "$CK" "$V" <<'PY' +import sys, torch, traceback +ck, V = sys.argv[1], sys.argv[2] +try: + import tensordict; print(f" import OK tensordict {tensordict.__version__} torch {torch.__version__}") +except Exception as e: + print(f" import FAILED: {type(e).__name__}: {e}"); sys.exit(0) +try: + from td_env_compat import install_state_dict_metadata_compat + install_state_dict_metadata_compat() # metadata-only; the numbers below are the real test + from td_backend import TDMPC2Backend + b = TDMPC2Backend(ck, device="cpu") + g = torch.Generator().manual_seed(0) + z = torch.randn(4, b.d_z, generator=g) + a = torch.zeros(1, 4, 7) + with torch.no_grad(): + v = b._estimate_value(b.core.encode(z, None), a) + print(" TRY_Q", [round(float(x), 8) for x in v.flatten()[:4]]) +except Exception as e: + print(f" load/forward FAILED: {type(e).__name__}: {e}"); traceback.print_exc() +PY +done +echo "== done $(date -u) ==" diff --git a/rsm_rise/scripts/nb/td_eval_payload.sh b/rsm_rise/scripts/nb/td_eval_payload.sh new file mode 100644 index 0000000000000000000000000000000000000000..43a5f1af936d026ec658bc4c15946c7d450fdbc2 --- /dev/null +++ b/rsm_rise/scripts/nb/td_eval_payload.sh @@ -0,0 +1,197 @@ +#!/usr/bin/env bash +# gen_q#274 TD-MPC2 eval cell -- BOTH configurations of the issue, one (task, mode, gamma, seed) per call. +# +# mode=score configuration (a), the SHARED-CANDIDATE column. The RISE proposer, plan_n=128, argmax, +# the same DINOv2 state and the same selection rule every value column gets; ONLY the +# function that ranks the 128 is swapped (eval.py's RR_TD_MODE=score block pre-populates +# `_planner_scorer`). #274 requires us to say plainly that this is close to DINO-WM plus a +# value head -- the scorer's describe() says it and so does the caption. +# mode=plan configuration (b), TD-MPC2's OWN MPPI/CEM planner with our RISE actor as the policy prior. +# It proposes its own actions, so the RSM planner is OFF and the candidate count is NOT 128: +# it is num_samples, and it is written into the cell name (Ntd) and the diag JSON. +# +# THE Q-HEAD GATE. Until 2026-09-23 11:56Z every TD-MPC2 world model we trained had a DETACHED Q +# ensemble (status/nb/diag_ensemble.txt, finding T6): `val/q_std == 0` means the terminal value is a +# constant and BOTH configurations degenerate (a -> a reward-sum ranker, b -> MPPI on reward alone). +# This script REFUSES such a checkpoint unless RR_TD_ALLOW_V1=1 is set, and a run made under that flag +# is written to a separate `td274smoke/` directory with -V1PLUMB in the cell name so a plumbing smoke +# can never be read as a score. +# +# usage: td_eval_payload.sh [rollouts] [extra eval_cell.sh args...] +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +TASK=$1; MODE=$2; GAMMA=$3; SEED=$4; ROLL=${5:-50}; shift 5 2>/dev/null || shift 4 +case "$TASK" in + threading_expert_play) ENVCFG=robomimic_threading_coverage ;; + mug_expert_suboptimal) ENVCFG=robomimic_mug ;; + *) echo "[td_eval] unknown task $TASK"; exit 2 ;; +esac +case "$MODE" in score|plan) ;; *) echo "[td_eval] mode must be score|plan, got $MODE"; exit 2 ;; esac + +# H = 1/(1-gamma) frames -- the SAME horizon family #273 sweeps, so these rows and the DINO-WM MPC rows +# are directly comparable. For mode=score H is the terminal-value horizon of the scored roll; for +# mode=plan it is the horizon of the terminal Q the MPPI objective ends on (the plan horizon Hp is its +# own, disclosed, number). +H=$(awk -v g="$GAMMA" 'BEGIN{printf "%d", int(1/(1-g)+0.5)}') +TAG=g$(echo "$GAMMA" | tr -d '.') +WM=$ROOT/runs/$TASK/wm/tdmpc2v2_$TAG +SUF=""; OUTD=$ROOT/runs/$TASK/eval_onactor/td274 +# RR_TD_SMOKE=1 -- a deliberately SHORT plumbing run (a handful of rollouts) on a HEALTHY v2 model. +# Without this, such a run would land in td274/ under the same cell name a real 50-rollout cell uses, +# where a later reader could not tell the two apart and a pooling script would merge them. Labelled +# -SMOKE in the name and written to td274smoke/, which no table reads. +if [ "${RR_TD_SMOKE:-0}" = "1" ]; then + SUF="$SUF-SMOKE"; OUTD=$ROOT/runs/$TASK/eval_onactor/td274smoke + echo "[td_eval] RR_TD_SMOKE=1: plumbing run, written to td274smoke/ and never pooled with a score." +fi +# RR_TD_SUF_EXTRA -- an extra, caller-supplied cell-name suffix. Default EMPTY, so every cell name +# and every filename produced before 2026-09-24 is byte-identical and every published number stays +# reproducible from its own file. +# +# Why it exists (run 21): a run whose POINT is a side-effect file -- td_dual_payload.sh, which rides +# an eval to compute the cfg(a)-vs-DINO-WM rank correlation -- was silently defeated by the +# skip-if-exists resume guard at the bottom of this script. An UNRELATED earlier smoke run had +# already written the same cell name into td274smoke/, so the eval exited 0 without running and the +# rho file was never produced (logs/lsf/rr_pack4_nb16td.slot3.1888056.out, 00:54:22Z). The guard is +# correct and must stay: it is what makes every payload resumable under preemption. The defect was +# that two DIFFERENT computations shared one name. A dual run costs a second read-out per decision +# and is not the same thing as a plain smoke, so it now says so in its name and collides with nothing. +if [ -n "${RR_TD_SUF_EXTRA:-}" ]; then + SUF="$SUF${RR_TD_SUF_EXTRA}" + echo "[td_eval] RR_TD_SUF_EXTRA=${RR_TD_SUF_EXTRA} -- distinct cell name; does not collide with a plain smoke." +fi +if [ ! -d "$WM" ]; then + if [ "${RR_TD_ALLOW_V1:-0}" = "1" ]; then + WM=$ROOT/runs/$TASK/wm/tdmpc2_$TAG; SUF="-V1PLUMB" + OUTD=$ROOT/runs/$TASK/eval_onactor/td274smoke + echo "[td_eval] WARNING: no v2 (post-T6-fix) world model; running the PRE-FIX checkpoint as a" + echo "[td_eval] PLUMBING SMOKE ONLY. Its Q head is a constant (finding T6) so this cell" + echo "[td_eval] measures the code path, NOT the method, and is written to td274smoke/." + else + echo "[td_eval] MISSING $WM (set RR_TD_ALLOW_V1=1 only for a labelled plumbing smoke)"; exit 2 + fi +fi +CK=$WM/ckpt_s30000.pt; [ -f "$CK" ] || CK=$WM/ckpt_last.pt +CKPT=$(ls $ROOT/runs/$TASK/policy/S0A_seed0/*/*/models/model_epoch_5000.pth 2>/dev/null | head -1) +FS=$ROOT/cache/$TASK/feat_stats.npz +for f in "$CK" "$CKPT" "$FS"; do [ -f "$f" ] || { echo "[td_eval] MISSING $f"; exit 2; }; done + +# --- preflight: the checkpoint's OWN gamma must be the cell's gamma, and its Q health is printed here +# so no number can be read without it. Cheap (one load, no env). +PRE=$($ROOT/venv_tdmpc2/bin/python - "$CK" "$WM/health.jsonl" "$GAMMA" <<'PY' +import json, sys, torch +ck, hj, want = sys.argv[1], sys.argv[2], float(sys.argv[3]) +sd = torch.load(ck, map_location="cpu", weights_only=False) +g, step = float(sd["gamma"]), int(sd.get("step", -1)) +qstd = qmax = None +try: + rows = [json.loads(l) for l in open(hj) if l.strip()] + for r in rows[::-1]: + if "val/q_std" in r: + qstd, qmax = r.get("val/q_std"), r.get("val/q_headw_absmax"); break +except FileNotFoundError: + pass +print(json.dumps({"gamma": g, "step": step, "cache": sd.get("cache", ""), + "q_std": qstd, "q_headw_absmax": qmax, "gamma_ok": abs(g - want) < 1e-9})) +PY +) +echo "[td_eval] checkpoint preflight: $PRE" +echo "$PRE" | grep -q '"gamma_ok": true' || { + echo "[td_eval] REFUSING: checkpoint gamma != cell gamma $GAMMA -- the H label would be a lie"; exit 3; } +QSTD=$(echo "$PRE" | $ROOT/venv_tdmpc2/bin/python -c 'import json,sys; print(json.load(sys.stdin)["q_std"])') +# "None" = the health file predates val/q_std (the pre-T6 trainer), which is exactly the case this +# gate exists for: unmeasurable is treated as dead, never as fine. +if [ "$QSTD" = "0" ] || [ "$QSTD" = "0.0" ] || [ "$QSTD" = "None" ] || [ -z "$QSTD" ]; then + if [ "${RR_TD_ALLOW_V1:-0}" = "1" ]; then + echo "[td_eval] val/q_std=$QSTD (dead or unmeasurable Q head, finding T6) -- allowed only as the" + echo "[td_eval] labelled plumbing smoke" + case "$SUF" in *V1PLUMB*) ;; *) SUF="$SUF-DEADQ"; OUTD=$ROOT/runs/$TASK/eval_onactor/td274smoke ;; esac + else + echo "[td_eval] REFUSING: val/q_std is $QSTD (0 = constant terminal value, T6; None = the" + echo "[td_eval] checkpoint's health file cannot show it). Nothing" + echo "[td_eval] TD-MPC2 may be quoted from this checkpoint."; exit 4 + fi +fi + +mkdir -p "$OUTD" +export RR_TD_CKPT=$CK RR_TD_FEAT_STATS=$FS RR_TD_SEED=$SEED +HY=() +if [ "$MODE" = "score" ]; then + export RR_TD_MODE=score RR_TD_CHUNK=8 RR_TD_ADIM=7 RR_TD_SCORE=${RR_TD_SCORE:-prob} \ + RR_TD_DEPTH=1 RR_TD_PARTICLES=1 + # RR_TD_RULE / RR_TD_SCORE are in the CELL NAME (owner blocker, 2026-09-23 19:45Z). Two cells + # differing only in the selection rule or the read-out scale are DIFFERENT MEASUREMENTS: + # rule=random -- the random-of-128 control on the same candidate distribution. It is the only + # thing that tells a 0.020 apart from a constant scorer picking candidate 0. + # score=logit -- the same scorer's monotone pre-image. The prob scale ties 49.7 of 128 on + # threading (status/nb/nb274_health.txt) while the logit scale ties 1.26, i.e. + # the ordering exists and the squashing is destroying it. Changing which scale + # a score is read on is a hyperparameter, not a new estimator. + RULE=${RR_TD_RULE:-argmax} + case "$RULE" in argmax|random) ;; *) echo "[td_eval] RR_TD_RULE must be argmax|random"; exit 2;; esac + SCTAG=""; [ "${RR_TD_SCORE:-prob}" != "prob" ] && SCTAG="-${RR_TD_SCORE}" + CELL="E1-TDMPC2-R$GAMMA-$H-tdq-128-$RULE$SCTAG-TD274a$SUF-es$SEED-sS0As0" + # the planner must be ON and at the SHARED candidate count, or eval.py's own guard refuses the cell + HY=(training.plan_n=128 training.plan_rule=$RULE) + # a control must not silently draw a different candidate distribution from the cell it controls: + # the proposer, its seed and its chunking are untouched above, only the pick among the 128 changes. +else + HP=${RR_TD_HP:-3}; NS=${RR_TD_SAMPLES:-512}; NE=${RR_TD_ELITES:-64}; IT=${RR_TD_ITERS:-6} + NPI=${RR_TD_PI_TRAJS:-24}; EX=${RR_TD_EXECUTE:-3} + # gen_q#274 run 31: WHICH PRIOR SEEDS MPPI is part of the cell's identity, so it goes in the cell + # NAME, not only in the JSON. Default rise_actor -> EMPTY tag, so every cell already landed keeps + # its byte-identical name and nothing is re-run. Measured reason this knob exists (LSF 1893275 + # slot0, 07:17Z): Hp=16 with the RISE actor as prior CANNOT RUN -- the actor's executed chunk is 8 + # frames, so cfg(b)-with-our-actor is structurally capped at Hp<=8 out of H=20. tdmpc2 = upstream + # TD-MPC2's own published prior; none = pure CEM. Both are the method's own ingredients, and a + # cell that used either must never be read as "the RISE actor as policy prior". + PRI=${RR_TD_PRIOR:-rise_actor} + case "$PRI" in rise_actor|tdmpc2|none) ;; *) echo "[td_eval] RR_TD_PRIOR must be rise_actor|tdmpc2|none"; exit 2;; esac + PRITAG=""; [ "$PRI" != "rise_actor" ] && PRITAG="-pri$PRI" + export RR_TD_MODE=plan RR_TD_HP=$HP RR_TD_SAMPLES=$NS RR_TD_ELITES=$NE RR_TD_ITERS=$IT \ + RR_TD_PI_TRAJS=$NPI RR_TD_EXECUTE=$EX RR_TD_PRIOR=$PRI + CELL="E1-TDMPC2-R$GAMMA-$H-plan-Ntd$NS-hp$HP-it$IT$PRITAG-TD274b$SUF-es$SEED-sS0As0" + # gen_q#274 run 10. cfg(b) PROPOSES its own actions, so like DF it must run with the cell's own + # ranked planner OFF. Left unset, plan_n came from the cell config (128): the harness then + # repeats the observation 128x, calls MPPI once per row, and the RISE critic argmaxes over the + # rows AFTERWARDS -- i.e. the row would be "TD-MPC2 re-ranked by our critic" printed as + # configuration (b), and 128x the planning cost. df_eval_payload.sh has carried plan_n=1 since + # 13:35Z for exactly this reason; td_policy.install records the bypass in the cell JSON. + HY=(training.plan_n=1) +fi +O=$OUTD/${CELL}-s${SEED}.json +if [ -s "$O" ]; then echo "[td_eval] $O exists -- skip"; exit 0; fi +export RR_TD_DIAG=$OUTD/${CELL}-s${SEED}.diag.json +echo "[td_eval] $(date -u) host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-?} cell=$CELL" +echo "[td_eval] mode=$MODE wm=$CK H=$H rollouts=$ROLL out=$O" +# RR_TD_PREFLIGHT_ONLY=1: everything above (arguments, gamma match, Q-head gate, cell name, env block, +# hydra overrides) with no env and no GPU, so the naming/gate logic is checkable on a CPU node. +if [ "${RR_TD_PREFLIGHT_ONLY:-0}" = "1" ]; then + echo "[td_eval] PREFLIGHT ONLY -- env vars: $(env | grep -E '^RR_TD_' | sort | tr '\n' ' ')" + echo "[td_eval] hydra: ${HY[*]:-}" + echo "[td_eval] PREFLIGHT OK"; exit 0 +fi +# EPISODE HORIZON = 400, the project default (scripts/eval_cell.sh, and what +# launch_dinowm_mpc.py passes for every DINO-WM MPC row). An earlier revision of this file used 150, +# which is NOT the protocol these rows are compared against: a shorter cap can only lose successes +# that arrive late, so it would have UNDERSTATED the baseline and broken the one comparison #274 asks +# for. Overridable via RR_EVAL_HORIZON for a deliberate cheap probe, and the value is in the cell JSON. +$ROOT/scripts/eval_cell.sh "$TASK" "$CKPT" "$ENVCFG" "$O" \ + exp.num_rollouts=$ROLL exp.rollout_horizon=${RR_EVAL_HORIZON:-400} exp.eval_seed=$SEED \ + exp.eval_cell=$CELL exp.eval_task=$TASK "${HY[@]}" "$@" +rc=$? +if [ -s "$O" ]; then + echo "[td_eval] JSON LANDED rc=$rc $O" +else + # gen_q#274 run 32, DEFECT 4 of scripts/pack_drain5.sh. rc=99 is eval_cell.sh's HOST-level claim + # ("this host cannot create an EGL framebuffer" / "3 consecutive read_pixels SIGABRTs having + # salvaged 0 episodes") and its request to be requeued elsewhere -- it is NOT a statement about the + # cell. Collapsing it to 1 here is what let one unfit host RETIRE 6 queue indices in 4 minutes on + # LSF 1894026. Propagate it verbatim so the payload and pack_drain5.sh can leave the index + # reclaimable. Any other failure still exits 1 and is a real cell failure. + if [ "$rc" = 99 ]; then + echo "[td_eval] NO JSON rc=99 -- HOST-LEVEL (eval_cell.sh requested a different host); propagating 99" + exit 99 + fi + echo "[td_eval] NO JSON rc=$rc"; exit 1 +fi diff --git a/rsm_rise/scripts/nb/td_eval_preflight.sh b/rsm_rise/scripts/nb/td_eval_preflight.sh new file mode 100644 index 0000000000000000000000000000000000000000..be319527c4157d1a4c86e578f764227ddb75a3f2 --- /dev/null +++ b/rsm_rise/scripts/nb/td_eval_preflight.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# gen_q#274 CPU check of scripts/nb/td_eval_payload.sh's argument / gamma / Q-head-gate / naming logic. +# No env, no GPU, no rollouts: RR_TD_PREFLIGHT_ONLY stops the payload right before eval_cell.sh. +# What must hold, and is asserted at the end: +# 1. a checkpoint whose gamma != the cell's gamma is REFUSED (exit 3) -- an H label can never be a lie; +# 2. a dead / unmeasurable Q head is REFUSED (exit 4) unless RR_TD_ALLOW_V1=1; +# 3. under RR_TD_ALLOW_V1 the cell name carries V1PLUMB/DEADQ and the output dir is td274smoke/. +set -uo pipefail +ROOT=/proj/dmfexp/zwhong/rsm_rise +OUT=$ROOT/status/nb/td_eval_preflight.txt +P=$ROOT/scripts/nb/td_eval_payload.sh +export MUJOCO_GL=disable +exec > "$OUT" 2>&1 +echo "=== gen_q#274 td_eval_payload preflight $(date -u +%FT%TZ) host=$(hostname) ===" +pass=0; fail=0 +chk() { # chk