diff --git a/.gitattributes b/.gitattributes index 2e87c7cd1d15409ee7dc9fb14822f24a4cf821da..f7c54285ecfc5eda2c61f0e8ec5b62d04196442c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -62,3 +62,7 @@ gen_q_rsm/misc/lewm/fig_cost_heatmap.png filter=lfs diff=lfs merge=lfs -text gen_q_rsm/misc/lewm/fig_horizon.png filter=lfs diff=lfs merge=lfs -text gen_q_rsm/misc/lewm/fig_mechanism.png filter=lfs diff=lfs merge=lfs -text gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/figures/fix_sweep.png filter=lfs diff=lfs merge=lfs -text +gen_q_rsm/ogbench_genq/figures/beta_recursion.gif filter=lfs diff=lfs merge=lfs -text +gen_q_rsm/ogbench_genq/figures/fig_actor.png filter=lfs diff=lfs merge=lfs -text +gen_q_rsm/ogbench_genq/figures/fig_occupancy.png filter=lfs diff=lfs merge=lfs -text +gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.png filter=lfs diff=lfs merge=lfs -text diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_joint1M_recnrE1.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_joint1M_recnrE1.json new file mode 100644 index 0000000000000000000000000000000000000000..7987281985387e35c3de79619e7ac55febc4996c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_joint1M_recnrE1.json @@ -0,0 +1,202 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 1, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 50000, + "rec_target": 4, + "rec_every": 1, + "rec_after": 100000, + "rec_free": true, + "rec_beta": 0.0, + "rec_max_depth": 6, + "rec_pess": 1, + "gamma_spectrum_lo": 0.0, + "gamma_spectrum_p": 0.5, + "success_rate": 0.488, + "best_sr": 0.49333333333333335, + "final_last_step": 0.488, + "final_best_ckpt": 0.41999999999999993, + "best_ckpt_periodic_sr": 0.5466666666666666, + "per_task": [ + 1.0, + 0.58, + 0.26, + 0.28, + 0.32 + ], + "curve": [ + [ + 25000, + 0.0 + ], + [ + 50000, + 0.04 + ], + [ + 75000, + 0.12 + ], + [ + 100000, + 0.14666666666666667 + ], + [ + 125000, + 0.18666666666666668 + ], + [ + 150000, + 0.21333333333333332 + ], + [ + 175000, + 0.21333333333333332 + ], + [ + 200000, + 0.2533333333333333 + ], + [ + 225000, + 0.22666666666666666 + ], + [ + 250000, + 0.27999999999999997 + ], + [ + 275000, + 0.2533333333333333 + ], + [ + 300000, + 0.29333333333333333 + ], + [ + 325000, + 0.26666666666666666 + ], + [ + 350000, + 0.31999999999999995 + ], + [ + 375000, + 0.33333333333333337 + ], + [ + 400000, + 0.3333333333333333 + ], + [ + 425000, + 0.3866666666666666 + ], + [ + 450000, + 0.30666666666666664 + ], + [ + 475000, + 0.30666666666666664 + ], + [ + 500000, + 0.4133333333333333 + ], + [ + 525000, + 0.31999999999999995 + ], + [ + 550000, + 0.44000000000000006 + ], + [ + 575000, + 0.4133333333333333 + ], + [ + 600000, + 0.4666666666666667 + ], + [ + 625000, + 0.37333333333333335 + ], + [ + 650000, + 0.4133333333333333 + ], + [ + 675000, + 0.3333333333333333 + ], + [ + 700000, + 0.42666666666666664 + ], + [ + 725000, + 0.4533333333333333 + ], + [ + 750000, + 0.4533333333333333 + ], + [ + 775000, + 0.49333333333333335 + ], + [ + 800000, + 0.39999999999999997 + ], + [ + 825000, + 0.38666666666666666 + ], + [ + 850000, + 0.3866666666666666 + ], + [ + 875000, + 0.4533333333333334 + ], + [ + 900000, + 0.4 + ], + [ + 925000, + 0.43999999999999995 + ], + [ + 950000, + 0.44000000000000006 + ], + [ + 975000, + 0.3866666666666666 + ], + [ + 1000000, + 0.4533333333333333 + ], + [ + 1000000, + 0.488 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 71094.5, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/ks1im40r" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_joint1Mst.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_joint1Mst.json new file mode 100644 index 0000000000000000000000000000000000000000..5be26244fad99e409320c729b9509b35ee52ed29 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_joint1Mst.json @@ -0,0 +1,193 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 1, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 10000, + "success_rate": 0.6559999999999999, + "best_sr": 0.6559999999999999, + "final_last_step": 0.6559999999999999, + "final_best_ckpt": 0.636, + "best_ckpt_periodic_sr": 0.6266666666666667, + "per_task": [ + 0.98, + 0.82, + 0.54, + 0.42, + 0.52 + ], + "curve": [ + [ + 25000, + 0.06666666666666667 + ], + [ + 50000, + 0.21333333333333332 + ], + [ + 75000, + 0.27999999999999997 + ], + [ + 100000, + 0.31999999999999995 + ], + [ + 125000, + 0.39999999999999997 + ], + [ + 150000, + 0.36 + ], + [ + 175000, + 0.39999999999999997 + ], + [ + 200000, + 0.3866666666666666 + ], + [ + 225000, + 0.4933333333333333 + ], + [ + 250000, + 0.3333333333333333 + ], + [ + 275000, + 0.44000000000000006 + ], + [ + 300000, + 0.3866666666666666 + ], + [ + 325000, + 0.3866666666666666 + ], + [ + 350000, + 0.5466666666666666 + ], + [ + 375000, + 0.4666666666666666 + ], + [ + 400000, + 0.48 + ], + [ + 425000, + 0.4666666666666667 + ], + [ + 450000, + 0.5333333333333333 + ], + [ + 475000, + 0.4666666666666666 + ], + [ + 500000, + 0.49333333333333335 + ], + [ + 525000, + 0.37333333333333335 + ], + [ + 550000, + 0.42666666666666675 + ], + [ + 575000, + 0.5733333333333334 + ], + [ + 600000, + 0.4933333333333333 + ], + [ + 625000, + 0.4666666666666666 + ], + [ + 650000, + 0.43999999999999995 + ], + [ + 675000, + 0.5066666666666667 + ], + [ + 700000, + 0.3733333333333333 + ], + [ + 725000, + 0.49333333333333335 + ], + [ + 750000, + 0.5066666666666666 + ], + [ + 775000, + 0.5733333333333334 + ], + [ + 800000, + 0.5066666666666666 + ], + [ + 825000, + 0.4 + ], + [ + 850000, + 0.3866666666666666 + ], + [ + 875000, + 0.6133333333333334 + ], + [ + 900000, + 0.5999999999999999 + ], + [ + 925000, + 0.4133333333333333 + ], + [ + 950000, + 0.4933333333333333 + ], + [ + 975000, + 0.48 + ], + [ + 1000000, + 0.6266666666666667 + ], + [ + 1000000, + 0.6559999999999999 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 26583.2, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/g1d1d1oe" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_recjoint_gmrt_500k.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_recjoint_gmrt_500k.json new file mode 100644 index 0000000000000000000000000000000000000000..06bdd4aadfb5df9a43785dac46d4a1ed5a5f6e77 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_recjoint_gmrt_500k.json @@ -0,0 +1,120 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 1, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 10000, + "rec_target": 4, + "rec_agg": "max", + "rec_after": null, + "rec_steps": 30, + "rec_eps": 0.5, + "rec_every": 2, + "rec_actor": false, + "success_rate": 0.62, + "best_sr": 0.6133333333333334, + "final_last_step": 0.596, + "final_best_ckpt": 0.62, + "best_ckpt_periodic_sr": 0.6133333333333334, + "per_task": [ + 1.0, + 0.62, + 0.46, + 0.48, + 0.54 + ], + "curve": [ + [ + 25000, + 0.18666666666666668 + ], + [ + 50000, + 0.27999999999999997 + ], + [ + 75000, + 0.29333333333333333 + ], + [ + 100000, + 0.5466666666666666 + ], + [ + 125000, + 0.42666666666666664 + ], + [ + 150000, + 0.48 + ], + [ + 175000, + 0.5466666666666666 + ], + [ + 200000, + 0.42666666666666664 + ], + [ + 225000, + 0.52 + ], + [ + 250000, + 0.5866666666666667 + ], + [ + 275000, + 0.42666666666666664 + ], + [ + 300000, + 0.4666666666666667 + ], + [ + 325000, + 0.5866666666666667 + ], + [ + 350000, + 0.5466666666666666 + ], + [ + 375000, + 0.6133333333333334 + ], + [ + 400000, + 0.5333333333333333 + ], + [ + 425000, + 0.5733333333333334 + ], + [ + 450000, + 0.6133333333333333 + ], + [ + 475000, + 0.5333333333333334 + ], + [ + 500000, + 0.4666666666666666 + ], + [ + 500000, + 0.596 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 51814.9, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/ooi8itm2" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_recjoint_gmst_500k.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_recjoint_gmst_500k.json new file mode 100644 index 0000000000000000000000000000000000000000..c43c5fe2a924e2a3025818155f8924b87985929b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/genq_joint_recjoint_gmst_500k.json @@ -0,0 +1,117 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 1, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 10000, + "rec_target": 4, + "rec_agg": "max", + "rec_after": null, + "rec_steps": 30, + "rec_eps": 0.5, + "rec_every": 2, + "rec_actor": false, + "success_rate": 0.616, + "best_sr": 0.6933333333333334, + "per_task": [ + 1.0, + 0.52, + 0.52, + 0.44, + 0.6 + ], + "curve": [ + [ + 25000, + 0.16 + ], + [ + 50000, + 0.18666666666666668 + ], + [ + 75000, + 0.22666666666666666 + ], + [ + 100000, + 0.27999999999999997 + ], + [ + 125000, + 0.3466666666666666 + ], + [ + 150000, + 0.3333333333333333 + ], + [ + 175000, + 0.5066666666666666 + ], + [ + 200000, + 0.43999999999999995 + ], + [ + 225000, + 0.42666666666666664 + ], + [ + 250000, + 0.3466666666666666 + ], + [ + 275000, + 0.6533333333333333 + ], + [ + 300000, + 0.5466666666666666 + ], + [ + 325000, + 0.5866666666666667 + ], + [ + 350000, + 0.6533333333333333 + ], + [ + 375000, + 0.6133333333333333 + ], + [ + 400000, + 0.6933333333333334 + ], + [ + 425000, + 0.6399999999999999 + ], + [ + 450000, + 0.6799999999999999 + ], + [ + 475000, + 0.6266666666666667 + ], + [ + 500000, + 0.5999999999999999 + ], + [ + 500000, + 0.616 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 52987.1, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/nb9i8w4j" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/rsm_seed1.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/rsm_seed1.json new file mode 100644 index 0000000000000000000000000000000000000000..30e0305b8b0aad1b79ef80f66bce0083c97f58d3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/1/rsm_seed1.json @@ -0,0 +1,156 @@ +{ + "method": "rsm", + "readout": "gl", + "env": "puzzle-3x3-play-v0", + "seed": 1, + "alpha": 1.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "off", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.9866666666666667, + "best_sr": 1.0, + "per_task": [ + 1.0, + 0.9333333333333333, + 1.0, + 1.0, + 1.0 + ], + "curve": [ + [ + 25000, + 0.026666666666666665 + ], + [ + 50000, + 0.16 + ], + [ + 75000, + 0.18666666666666668 + ], + [ + 100000, + 0.22666666666666666 + ], + [ + 125000, + 0.21333333333333332 + ], + [ + 150000, + 0.29333333333333333 + ], + [ + 175000, + 0.42666666666666664 + ], + [ + 200000, + 0.4533333333333333 + ], + [ + 225000, + 0.64 + ], + [ + 250000, + 0.5866666666666667 + ], + [ + 275000, + 0.6533333333333333 + ], + [ + 300000, + 0.7733333333333333 + ], + [ + 325000, + 0.5866666666666667 + ], + [ + 350000, + 0.6399999999999999 + ], + [ + 375000, + 0.72 + ], + [ + 400000, + 0.8 + ], + [ + 425000, + 0.7333333333333334 + ], + [ + 450000, + 0.8666666666666666 + ], + [ + 475000, + 0.8666666666666666 + ], + [ + 500000, + 0.8666666666666666 + ], + [ + 525000, + 0.9199999999999999 + ], + [ + 550000, + 0.9466666666666667 + ], + [ + 575000, + 0.9199999999999999 + ], + [ + 600000, + 0.8800000000000001 + ], + [ + 625000, + 0.9066666666666666 + ], + [ + 650000, + 0.9466666666666667 + ], + [ + 675000, + 0.9733333333333334 + ], + [ + 700000, + 1.0 + ], + [ + 725000, + 0.9333333333333332 + ], + [ + 750000, + 0.8933333333333333 + ], + [ + 775000, + 0.9733333333333334 + ], + [ + 800000, + 0.9866666666666667 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 30928.7, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/826rw9f0" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_b98s2_s500k.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_b98s2_s500k.json new file mode 100644 index 0000000000000000000000000000000000000000..5f41e563bb03bbb4daf77a16b121f580d120cf1b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_b98s2_s500k.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "actor_pkl": "best_ddpg2_4M_fourNW_B98_s2_puzzle_s500k_p853.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.868, + "per_task": [ + 1.0, + 0.82, + 0.86, + 0.82, + 0.84 + ] + } + }, + "wall_clock_sec": 91.9 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_b98s2_s650k.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_b98s2_s650k.json new file mode 100644 index 0000000000000000000000000000000000000000..84055d5e838179a52e1f5b379f98d6a6a3490460 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_b98s2_s650k.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "actor_pkl": "best_ddpg2_4M_fourNW_B98_s2_puzzle_s650k_p893.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.8640000000000001, + "per_task": [ + 1.0, + 0.74, + 0.72, + 0.88, + 0.98 + ] + } + }, + "wall_clock_sec": 87.5 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_fourNW_B98_s2_s775k.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_fourNW_B98_s2_s775k.json new file mode 100644 index 0000000000000000000000000000000000000000..eb3efede24e9a2336f67f6d783e55431ca2908c7 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_fourNW_B98_s2_s775k.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "actor_pkl": "best_ddpg2_4M_fourNW_B98_s2_s775k_p933.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.892, + "per_task": [ + 0.98, + 0.7, + 0.98, + 0.88, + 0.92 + ] + } + }, + "wall_clock_sec": 111.2 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_fourNW_seed2_s475k.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_fourNW_seed2_s475k.json new file mode 100644 index 0000000000000000000000000000000000000000..f63e98ff181077fe9a77ef65886d7b49fe99022a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/eval_plan_eval50_fourNW_seed2_s475k.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "actor_pkl": "best_ddpg2_4M_fourNW_seed2_s475k_p933.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.8640000000000001, + "per_task": [ + 1.0, + 0.78, + 0.82, + 0.8, + 0.92 + ] + } + }, + "wall_clock_sec": 123.1 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..758c4dd93a8e3ce6030e1417543a419f518891c4 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "success_rate": 0.004, + "best_sr": 0.026666666666666665, + "per_task": [ + 0.02, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.013333333333333332 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.013333333333333332 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.013333333333333332 + ], + [ + 300000, + 0.026666666666666665 + ], + [ + 300000, + 0.004 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 3680.1, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/xbght215" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..458282207f6ece771e2dea800d33009e17f3f99e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "actor_loss": "ddpgbc", + "alpha": 0.3, + "expectile": 0.9, + "success_rate": 0.8560000000000001, + "best_sr": 0.9333333333333333, + "per_task": [ + 1.0, + 0.94, + 0.68, + 0.8, + 0.86 + ], + "curve": [ + [ + 50000, + 0.17333333333333334 + ], + [ + 100000, + 0.18666666666666668 + ], + [ + 150000, + 0.29333333333333333 + ], + [ + 200000, + 0.4 + ], + [ + 250000, + 0.4533333333333333 + ], + [ + 300000, + 0.5466666666666666 + ], + [ + 350000, + 0.7733333333333333 + ], + [ + 400000, + 0.7466666666666667 + ], + [ + 450000, + 0.9333333333333333 + ], + [ + 500000, + 0.7866666666666667 + ], + [ + 500000, + 0.8560000000000001 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 4049.4, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/i7y1rxzk" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..f57dfbf770561e5f7c7c570b7b4ca03ad9a0edb5 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq.json @@ -0,0 +1,55 @@ +{ + "method": "gciql_genq", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 0.5, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_puzzle_3x3_play_v0.genqjax.npz", + "success_rate": 0.036, + "best_sr": 0.04, + "per_task": [ + 0.16, + 0.02, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.026666666666666665 + ], + [ + 100000, + 0.026666666666666665 + ], + [ + 150000, + 0.026666666666666665 + ], + [ + 200000, + 0.04 + ], + [ + 250000, + 0.04 + ], + [ + 300000, + 0.04 + ], + [ + 300000, + 0.036 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 14395.7, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/vtleh2vy" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..224640cde0e453fd0e9a0bdc0a82e8d02a56db7d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b09.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.15933294594287872, + "genq_npz": "m9_genq_rec_puzzle_3x3_play_v0_b09.genqjax.npz", + "success_rate": 0.016, + "best_sr": 0.04, + "per_task": [ + 0.06, + 0.02, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.013333333333333332 + ], + [ + 100000, + 0.013333333333333332 + ], + [ + 150000, + 0.04 + ], + [ + 200000, + 0.026666666666666665 + ], + [ + 250000, + 0.026666666666666665 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.016 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19559.4, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/0xbv3707" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..6ae965658d98293f3c42c9916e87e62c6cec0f94 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.15933294594287872, + "genq_npz": "m9_genq_rec_puzzle_3x3_play_v0_b095.genqjax.npz", + "success_rate": 0.044, + "best_sr": 0.06666666666666667, + "per_task": [ + 0.2, + 0.02, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.06666666666666667 + ], + [ + 100000, + 0.05333333333333333 + ], + [ + 150000, + 0.013333333333333332 + ], + [ + 200000, + 0.04 + ], + [ + 250000, + 0.04 + ], + [ + 300000, + 0.04 + ], + [ + 300000, + 0.044 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 11061.6, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/saq3zd5m" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_fast_ddpg2_4M_fourNW_B98_s2.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_fast_ddpg2_4M_fourNW_B98_s2.json new file mode 100644 index 0000000000000000000000000000000000000000..4884aec868441976d82b65f66a85002f7bd2a259 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_fast_ddpg2_4M_fourNW_B98_s2.json @@ -0,0 +1,191 @@ +{ + "method": "genq_joint_fast", + "extraction": "ddpg2", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "rt_eta": 0.5, + "pi_alpha": 0.0, + "occ_warmup": 50000, + "actor_ema_tau": 0.005, + "rec_target": 1, + "rec_every": 1, + "rec_after": 100000, + "rec_beta": 0.98, + "rec_prob": true, + "rec_mode": "prob", + "gamma_spectrum_lo": 0.95, + "gamma_spectrum_p": 0.5, + "data_parallel": false, + "n_devices": 1, + "success_rate": 0.8266666666666665, + "best_sr": 0.9466666666666667, + "per_task": [ + 1.0, + 0.6666666666666666, + 0.9333333333333333, + 0.6, + 0.9333333333333333 + ], + "curve": [ + [ + 25000, + 0.08 + ], + [ + 50000, + 0.14666666666666667 + ], + [ + 75000, + 0.1733333333333333 + ], + [ + 100000, + 0.26666666666666666 + ], + [ + 125000, + 0.2 + ], + [ + 150000, + 0.31999999999999995 + ], + [ + 175000, + 0.32 + ], + [ + 200000, + 0.42666666666666664 + ], + [ + 225000, + 0.5333333333333334 + ], + [ + 250000, + 0.5333333333333333 + ], + [ + 275000, + 0.5733333333333335 + ], + [ + 300000, + 0.5733333333333335 + ], + [ + 325000, + 0.5599999999999999 + ], + [ + 350000, + 0.5866666666666667 + ], + [ + 375000, + 0.6533333333333333 + ], + [ + 400000, + 0.6933333333333332 + ], + [ + 425000, + 0.6933333333333332 + ], + [ + 450000, + 0.68 + ], + [ + 475000, + 0.8133333333333332 + ], + [ + 500000, + 0.8533333333333333 + ], + [ + 525000, + 0.7466666666666667 + ], + [ + 550000, + 0.8400000000000001 + ], + [ + 575000, + 0.7866666666666666 + ], + [ + 600000, + 0.8800000000000001 + ], + [ + 625000, + 0.8133333333333332 + ], + [ + 650000, + 0.8933333333333333 + ], + [ + 675000, + 0.8933333333333333 + ], + [ + 700000, + 0.8666666666666668 + ], + [ + 725000, + 0.8 + ], + [ + 750000, + 0.9199999999999999 + ], + [ + 775000, + 0.9333333333333332 + ], + [ + 800000, + 0.9066666666666666 + ], + [ + 825000, + 0.8266666666666665 + ], + [ + 850000, + 0.9333333333333333 + ], + [ + 875000, + 0.9199999999999999 + ], + [ + 900000, + 0.9199999999999999 + ], + [ + 925000, + 0.9466666666666667 + ], + [ + 950000, + 0.76 + ], + [ + 975000, + 0.8266666666666665 + ] + ], + "train_steps": 4000000, + "wall_clock_sec": 79692.0, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/gd4k0jvk" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_fast_ddpg2_4M_fourNW_seed2.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_fast_ddpg2_4M_fourNW_seed2.json new file mode 100644 index 0000000000000000000000000000000000000000..f547a959d2847861cdb41d1af954f5b8e2611b7e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_fast_ddpg2_4M_fourNW_seed2.json @@ -0,0 +1,147 @@ +{ + "method": "genq_joint_fast", + "extraction": "ddpg2", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "rt_eta": 0.5, + "pi_alpha": 0.0, + "occ_warmup": 50000, + "actor_ema_tau": 0.005, + "rec_target": 1, + "rec_every": 1, + "rec_after": 100000, + "rec_beta": 0.95, + "rec_prob": true, + "rec_mode": "prob", + "gamma_spectrum_lo": 0.95, + "gamma_spectrum_p": 0.5, + "data_parallel": false, + "n_devices": 1, + "success_rate": 0.9199999999999999, + "best_sr": 0.9333333333333332, + "per_task": [ + 1.0, + 0.8, + 1.0, + 1.0, + 0.8 + ], + "curve": [ + [ + 25000, + 0.12 + ], + [ + 50000, + 0.16 + ], + [ + 75000, + 0.18666666666666668 + ], + [ + 100000, + 0.22666666666666666 + ], + [ + 125000, + 0.2 + ], + [ + 150000, + 0.3333333333333333 + ], + [ + 175000, + 0.3733333333333333 + ], + [ + 200000, + 0.38666666666666666 + ], + [ + 225000, + 0.52 + ], + [ + 250000, + 0.5466666666666666 + ], + [ + 275000, + 0.49333333333333335 + ], + [ + 300000, + 0.5333333333333333 + ], + [ + 325000, + 0.7066666666666668 + ], + [ + 350000, + 0.6266666666666666 + ], + [ + 375000, + 0.6666666666666666 + ], + [ + 400000, + 0.7866666666666667 + ], + [ + 425000, + 0.7866666666666666 + ], + [ + 450000, + 0.7066666666666667 + ], + [ + 475000, + 0.7466666666666667 + ], + [ + 500000, + 0.9066666666666666 + ], + [ + 525000, + 0.8933333333333333 + ], + [ + 550000, + 0.8666666666666668 + ], + [ + 575000, + 0.8533333333333333 + ], + [ + 600000, + 0.9333333333333332 + ], + [ + 625000, + 0.9199999999999999 + ], + [ + 650000, + 0.9199999999999999 + ], + [ + 675000, + 0.8800000000000001 + ], + [ + 700000, + 0.9199999999999999 + ] + ], + "train_steps": 4000000, + "wall_clock_sec": 53280.0, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/vnusv7vg" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1M_rec.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1M_rec.json new file mode 100644 index 0000000000000000000000000000000000000000..11a1592f164b2dd14d6f90aebcc2ed926ca42246 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1M_rec.json @@ -0,0 +1,50 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 50000, + "rec_target": 4, + "rec_every": 2, + "rec_after": 100000, + "rec_free": false, + "success_rate": 0.21333333333333332, + "best_sr": 0.21333333333333332, + "per_task": [ + 0.9333333333333333, + 0.0, + 0.0, + 0.0, + 0.13333333333333333 + ], + "curve": [ + [ + 25000, + 0.04 + ], + [ + 50000, + 0.0 + ], + [ + 75000, + 0.12 + ], + [ + 100000, + 0.05333333333333333 + ], + [ + 125000, + 0.21333333333333332 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 6197.8, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/c8pilrxh" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1M_recnr.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1M_recnr.json new file mode 100644 index 0000000000000000000000000000000000000000..de20cd260d32391eed863a8f9d68a0fdd113977b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1M_recnr.json @@ -0,0 +1,199 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 50000, + "rec_target": 4, + "rec_every": 2, + "rec_after": 100000, + "rec_free": true, + "rec_beta": 0.0, + "rec_max_depth": 6, + "success_rate": 0.4879999999999999, + "best_sr": 0.5866666666666667, + "final_last_step": 0.484, + "final_best_ckpt": 0.4879999999999999, + "best_ckpt_periodic_sr": 0.5866666666666667, + "per_task": [ + 1.0, + 0.44, + 0.38, + 0.32, + 0.3 + ], + "curve": [ + [ + 25000, + 0.013333333333333332 + ], + [ + 50000, + 0.13333333333333333 + ], + [ + 75000, + 0.18666666666666668 + ], + [ + 100000, + 0.2 + ], + [ + 125000, + 0.14666666666666667 + ], + [ + 150000, + 0.2 + ], + [ + 175000, + 0.21333333333333332 + ], + [ + 200000, + 0.22666666666666666 + ], + [ + 225000, + 0.30666666666666664 + ], + [ + 250000, + 0.22666666666666666 + ], + [ + 275000, + 0.27999999999999997 + ], + [ + 300000, + 0.3333333333333333 + ], + [ + 325000, + 0.29333333333333333 + ], + [ + 350000, + 0.31999999999999995 + ], + [ + 375000, + 0.30666666666666664 + ], + [ + 400000, + 0.36 + ], + [ + 425000, + 0.3733333333333333 + ], + [ + 450000, + 0.42666666666666664 + ], + [ + 475000, + 0.4 + ], + [ + 500000, + 0.43999999999999995 + ], + [ + 525000, + 0.49333333333333335 + ], + [ + 550000, + 0.37333333333333335 + ], + [ + 575000, + 0.39999999999999997 + ], + [ + 600000, + 0.42666666666666664 + ], + [ + 625000, + 0.3866666666666666 + ], + [ + 650000, + 0.43999999999999995 + ], + [ + 675000, + 0.4133333333333333 + ], + [ + 700000, + 0.43999999999999995 + ], + [ + 725000, + 0.43999999999999995 + ], + [ + 750000, + 0.49333333333333335 + ], + [ + 775000, + 0.4666666666666667 + ], + [ + 800000, + 0.4933333333333333 + ], + [ + 825000, + 0.4933333333333333 + ], + [ + 850000, + 0.48 + ], + [ + 875000, + 0.5066666666666666 + ], + [ + 900000, + 0.5866666666666667 + ], + [ + 925000, + 0.5733333333333333 + ], + [ + 950000, + 0.5066666666666666 + ], + [ + 975000, + 0.5733333333333334 + ], + [ + 1000000, + 0.5733333333333334 + ], + [ + 1000000, + 0.484 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 50294.5, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/p9kuegq2" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1Mst_s2.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1Mst_s2.json new file mode 100644 index 0000000000000000000000000000000000000000..a33471e58dc4554386c1aa0ae131ac3fb169d835 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1Mst_s2.json @@ -0,0 +1,193 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 10000, + "success_rate": 0.608, + "best_sr": 0.7066666666666667, + "final_last_step": 0.568, + "final_best_ckpt": 0.608, + "best_ckpt_periodic_sr": 0.7066666666666667, + "per_task": [ + 1.0, + 0.62, + 0.36, + 0.46, + 0.6 + ], + "curve": [ + [ + 25000, + 0.08 + ], + [ + 50000, + 0.17333333333333334 + ], + [ + 75000, + 0.27999999999999997 + ], + [ + 100000, + 0.3866666666666666 + ], + [ + 125000, + 0.36 + ], + [ + 150000, + 0.4133333333333334 + ], + [ + 175000, + 0.3733333333333333 + ], + [ + 200000, + 0.38666666666666666 + ], + [ + 225000, + 0.3333333333333333 + ], + [ + 250000, + 0.44000000000000006 + ], + [ + 275000, + 0.4133333333333333 + ], + [ + 300000, + 0.48 + ], + [ + 325000, + 0.31999999999999995 + ], + [ + 350000, + 0.3866666666666666 + ], + [ + 375000, + 0.4533333333333333 + ], + [ + 400000, + 0.3466666666666666 + ], + [ + 425000, + 0.4133333333333333 + ], + [ + 450000, + 0.48 + ], + [ + 475000, + 0.3733333333333333 + ], + [ + 500000, + 0.4533333333333333 + ], + [ + 525000, + 0.48 + ], + [ + 550000, + 0.6133333333333334 + ], + [ + 575000, + 0.5866666666666667 + ], + [ + 600000, + 0.5466666666666666 + ], + [ + 625000, + 0.5066666666666666 + ], + [ + 650000, + 0.4933333333333333 + ], + [ + 675000, + 0.7066666666666667 + ], + [ + 700000, + 0.5733333333333334 + ], + [ + 725000, + 0.52 + ], + [ + 750000, + 0.4933333333333333 + ], + [ + 775000, + 0.5466666666666666 + ], + [ + 800000, + 0.5866666666666667 + ], + [ + 825000, + 0.5066666666666667 + ], + [ + 850000, + 0.5866666666666667 + ], + [ + 875000, + 0.6133333333333333 + ], + [ + 900000, + 0.5066666666666666 + ], + [ + 925000, + 0.6266666666666667 + ], + [ + 950000, + 0.6133333333333333 + ], + [ + 975000, + 0.5733333333333334 + ], + [ + 1000000, + 0.5866666666666667 + ], + [ + 1000000, + 0.568 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 23431.5, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/dfxwygwx" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1Mst_s2e.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1Mst_s2e.json new file mode 100644 index 0000000000000000000000000000000000000000..48771c21a7cd6b99cf1d52c70496a5734c1166f6 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_joint1Mst_s2e.json @@ -0,0 +1,193 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 10000, + "success_rate": 0.6, + "best_sr": 0.68, + "final_last_step": 0.5599999999999999, + "final_best_ckpt": 0.6, + "best_ckpt_periodic_sr": 0.68, + "per_task": [ + 1.0, + 0.6, + 0.54, + 0.28, + 0.58 + ], + "curve": [ + [ + 25000, + 0.06666666666666667 + ], + [ + 50000, + 0.2533333333333333 + ], + [ + 75000, + 0.2533333333333333 + ], + [ + 100000, + 0.27999999999999997 + ], + [ + 125000, + 0.4666666666666666 + ], + [ + 150000, + 0.3333333333333333 + ], + [ + 175000, + 0.30666666666666664 + ], + [ + 200000, + 0.36 + ], + [ + 225000, + 0.3333333333333333 + ], + [ + 250000, + 0.27999999999999997 + ], + [ + 275000, + 0.42666666666666664 + ], + [ + 300000, + 0.30666666666666664 + ], + [ + 325000, + 0.39999999999999997 + ], + [ + 350000, + 0.4133333333333334 + ], + [ + 375000, + 0.4666666666666666 + ], + [ + 400000, + 0.36 + ], + [ + 425000, + 0.52 + ], + [ + 450000, + 0.49333333333333335 + ], + [ + 475000, + 0.4666666666666666 + ], + [ + 500000, + 0.4533333333333333 + ], + [ + 525000, + 0.5066666666666667 + ], + [ + 550000, + 0.5333333333333334 + ], + [ + 575000, + 0.5466666666666666 + ], + [ + 600000, + 0.52 + ], + [ + 625000, + 0.4533333333333333 + ], + [ + 650000, + 0.52 + ], + [ + 675000, + 0.5333333333333333 + ], + [ + 700000, + 0.52 + ], + [ + 725000, + 0.56 + ], + [ + 750000, + 0.48 + ], + [ + 775000, + 0.48 + ], + [ + 800000, + 0.5333333333333333 + ], + [ + 825000, + 0.6 + ], + [ + 850000, + 0.48 + ], + [ + 875000, + 0.5866666666666667 + ], + [ + 900000, + 0.64 + ], + [ + 925000, + 0.5466666666666666 + ], + [ + 950000, + 0.5866666666666667 + ], + [ + 975000, + 0.6133333333333334 + ], + [ + 1000000, + 0.68 + ], + [ + 1000000, + 0.5599999999999999 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 28333.8, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/affqbrje" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_recjoint_gmrt_500k.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_recjoint_gmrt_500k.json new file mode 100644 index 0000000000000000000000000000000000000000..ea423161963cdca1bacdaa353bffbe86517bc759 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_recjoint_gmrt_500k.json @@ -0,0 +1,120 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 10000, + "rec_target": 4, + "rec_agg": "max", + "rec_after": null, + "rec_steps": 30, + "rec_eps": 0.5, + "rec_every": 2, + "rec_actor": false, + "success_rate": 0.636, + "best_sr": 0.6933333333333334, + "final_last_step": 0.492, + "final_best_ckpt": 0.636, + "best_ckpt_periodic_sr": 0.6933333333333334, + "per_task": [ + 1.0, + 0.66, + 0.52, + 0.56, + 0.44 + ], + "curve": [ + [ + 25000, + 0.16 + ], + [ + 50000, + 0.29333333333333333 + ], + [ + 75000, + 0.3333333333333333 + ], + [ + 100000, + 0.36 + ], + [ + 125000, + 0.52 + ], + [ + 150000, + 0.5866666666666667 + ], + [ + 175000, + 0.56 + ], + [ + 200000, + 0.5333333333333333 + ], + [ + 225000, + 0.42666666666666675 + ], + [ + 250000, + 0.4666666666666667 + ], + [ + 275000, + 0.5733333333333334 + ], + [ + 300000, + 0.5466666666666666 + ], + [ + 325000, + 0.48 + ], + [ + 350000, + 0.6 + ], + [ + 375000, + 0.5466666666666666 + ], + [ + 400000, + 0.5733333333333334 + ], + [ + 425000, + 0.6933333333333334 + ], + [ + 450000, + 0.5733333333333333 + ], + [ + 475000, + 0.5333333333333333 + ], + [ + 500000, + 0.4666666666666667 + ], + [ + 500000, + 0.492 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 51973.5, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/iadaypy1" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_recjoint_gmst_500k.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_recjoint_gmst_500k.json new file mode 100644 index 0000000000000000000000000000000000000000..8df8e389dedeec5dbeee6908cedff82647c7445c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/genq_joint_recjoint_gmst_500k.json @@ -0,0 +1,117 @@ +{ + "method": "genq_joint", + "extraction": "r3", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "expectile": 0.9, + "rt_eta": 0.5, + "pi_alpha": 1.0, + "pi_horizon": 25, + "occ_warmup": 10000, + "rec_target": 4, + "rec_agg": "max", + "rec_after": null, + "rec_steps": 30, + "rec_eps": 0.5, + "rec_every": 2, + "rec_actor": false, + "success_rate": 0.7120000000000001, + "best_sr": 0.7333333333333333, + "per_task": [ + 1.0, + 0.66, + 0.66, + 0.68, + 0.56 + ], + "curve": [ + [ + 25000, + 0.14666666666666667 + ], + [ + 50000, + 0.18666666666666668 + ], + [ + 75000, + 0.30666666666666664 + ], + [ + 100000, + 0.29333333333333333 + ], + [ + 125000, + 0.4133333333333333 + ], + [ + 150000, + 0.5199999999999999 + ], + [ + 175000, + 0.4133333333333334 + ], + [ + 200000, + 0.4533333333333333 + ], + [ + 225000, + 0.52 + ], + [ + 250000, + 0.4666666666666666 + ], + [ + 275000, + 0.6133333333333333 + ], + [ + 300000, + 0.5066666666666667 + ], + [ + 325000, + 0.44000000000000006 + ], + [ + 350000, + 0.5866666666666667 + ], + [ + 375000, + 0.6133333333333333 + ], + [ + 400000, + 0.6266666666666666 + ], + [ + 425000, + 0.7333333333333333 + ], + [ + 450000, + 0.72 + ], + [ + 475000, + 0.6533333333333333 + ], + [ + 500000, + 0.6 + ], + [ + 500000, + 0.7120000000000001 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 53249.7, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/y890a3vz" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/rsm_seed2.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/rsm_seed2.json new file mode 100644 index 0000000000000000000000000000000000000000..2aa3017273341a71ba27b8a7119c00acbcc16a90 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/2/rsm_seed2.json @@ -0,0 +1,156 @@ +{ + "method": "rsm", + "readout": "gl", + "env": "puzzle-3x3-play-v0", + "seed": 2, + "alpha": 1.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "off", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.9466666666666667, + "best_sr": 0.9866666666666667, + "per_task": [ + 1.0, + 1.0, + 0.9333333333333333, + 0.8, + 1.0 + ], + "curve": [ + [ + 25000, + 0.026666666666666665 + ], + [ + 50000, + 0.16 + ], + [ + 75000, + 0.18666666666666668 + ], + [ + 100000, + 0.24 + ], + [ + 125000, + 0.2533333333333333 + ], + [ + 150000, + 0.27999999999999997 + ], + [ + 175000, + 0.4133333333333333 + ], + [ + 200000, + 0.44000000000000006 + ], + [ + 225000, + 0.56 + ], + [ + 250000, + 0.6533333333333333 + ], + [ + 275000, + 0.6 + ], + [ + 300000, + 0.7466666666666666 + ], + [ + 325000, + 0.7466666666666667 + ], + [ + 350000, + 0.76 + ], + [ + 375000, + 0.9333333333333333 + ], + [ + 400000, + 0.8266666666666668 + ], + [ + 425000, + 0.8266666666666665 + ], + [ + 450000, + 0.8533333333333333 + ], + [ + 475000, + 0.9066666666666666 + ], + [ + 500000, + 0.8933333333333333 + ], + [ + 525000, + 0.8933333333333333 + ], + [ + 550000, + 0.9466666666666667 + ], + [ + 575000, + 0.9200000000000002 + ], + [ + 600000, + 0.9066666666666666 + ], + [ + 625000, + 0.9466666666666667 + ], + [ + 650000, + 0.9600000000000002 + ], + [ + 675000, + 0.9466666666666667 + ], + [ + 700000, + 0.9733333333333334 + ], + [ + 725000, + 0.9466666666666667 + ], + [ + 750000, + 0.9866666666666667 + ], + [ + 775000, + 0.9466666666666667 + ], + [ + 800000, + 0.9466666666666667 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 30451.7, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/a8oixewt" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..9a1362d860b40d2f7e4bce69649ec3d54e2b6fa3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "puzzle-3x3-play-v0", + "seed": 3, + "success_rate": 0.004, + "best_sr": 0.026666666666666665, + "per_task": [ + 0.02, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.026666666666666665 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.013333333333333332 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.004 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 2451.4, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/ob7eq59e" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..dddaaa81ec0cdf492d37f7787f30bc5f3c9f773d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "puzzle-3x3-play-v0", + "seed": 3, + "actor_loss": "ddpgbc", + "alpha": 0.3, + "expectile": 0.9, + "success_rate": 0.696, + "best_sr": 0.696, + "per_task": [ + 1.0, + 0.86, + 0.34, + 0.52, + 0.76 + ], + "curve": [ + [ + 50000, + 0.14666666666666667 + ], + [ + 100000, + 0.17333333333333334 + ], + [ + 150000, + 0.3466666666666667 + ], + [ + 200000, + 0.42666666666666664 + ], + [ + 250000, + 0.52 + ], + [ + 300000, + 0.5333333333333333 + ], + [ + 350000, + 0.5866666666666667 + ], + [ + 400000, + 0.64 + ], + [ + 450000, + 0.6133333333333333 + ], + [ + 500000, + 0.6 + ], + [ + 500000, + 0.696 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 3234.9, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/zhkgzr8h" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..d414487a2cb72484ddab279e80f4738c3dda4bf1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq.json @@ -0,0 +1,51 @@ +{ + "method": "gciql_genq", + "env": "puzzle-3x3-play-v0", + "seed": 3, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 0.5, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_puzzle_3x3_play_v0.genqjax.npz", + "success_rate": 0.026666666666666665, + "best_sr": 0.05333333333333333, + "per_task": [ + 0.06666666666666667, + 0.06666666666666667, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.013333333333333332 + ], + [ + 100000, + 0.05333333333333333 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.013333333333333332 + ], + [ + 250000, + 0.04 + ], + [ + 300000, + 0.026666666666666665 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 20984.2, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/amt70koi" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..d1be56d8ecc8d373022fd934e181a0f289c8cdb9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b09.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-3x3-play-v0", + "seed": 3, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.18173280358314514, + "genq_npz": "m9_genq_rec_puzzle_3x3_play_v0_b09.genqjax.npz", + "success_rate": 0.052000000000000005, + "best_sr": 0.06666666666666667, + "per_task": [ + 0.18, + 0.08, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.06666666666666667 + ], + [ + 150000, + 0.026666666666666665 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.026666666666666665 + ], + [ + 300000, + 0.052000000000000005 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19692.6, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/wqb3gl8f" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..96e6766d58c993f2aff95260f275bc07182b71b8 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-3x3-play-v0", + "seed": 3, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.18175390362739563, + "genq_npz": "m9_genq_rec_puzzle_3x3_play_v0_b095.genqjax.npz", + "success_rate": 0.044, + "best_sr": 0.06666666666666667, + "per_task": [ + 0.18, + 0.0, + 0.02, + 0.02, + 0.0 + ], + "curve": [ + [ + 50000, + 0.013333333333333332 + ], + [ + 100000, + 0.06666666666666667 + ], + [ + 150000, + 0.026666666666666665 + ], + [ + 200000, + 0.026666666666666665 + ], + [ + 250000, + 0.026666666666666665 + ], + [ + 300000, + 0.026666666666666665 + ], + [ + 300000, + 0.044 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 11119.4, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/gh300b2v" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/3/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..32710e88a812ff9558ad74d187923b5f3970623c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "puzzle-3x3-play-v0", + "seed": 4, + "success_rate": 0.012, + "best_sr": 0.026666666666666665, + "per_task": [ + 0.04, + 0.0, + 0.02, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.026666666666666665 + ], + [ + 100000, + 0.013333333333333332 + ], + [ + 150000, + 0.026666666666666665 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.013333333333333332 + ], + [ + 300000, + 0.012 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 2274.7, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/gbkthdrx" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..d4122f2fa80ba44075df8825f14a4c832bf2daab --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "puzzle-3x3-play-v0", + "seed": 4, + "actor_loss": "ddpgbc", + "alpha": 0.3, + "expectile": 0.9, + "success_rate": 0.6880000000000001, + "best_sr": 0.6933333333333334, + "per_task": [ + 1.0, + 0.66, + 0.6, + 0.44, + 0.74 + ], + "curve": [ + [ + 50000, + 0.17333333333333334 + ], + [ + 100000, + 0.2 + ], + [ + 150000, + 0.27999999999999997 + ], + [ + 200000, + 0.38666666666666666 + ], + [ + 250000, + 0.48 + ], + [ + 300000, + 0.5866666666666667 + ], + [ + 350000, + 0.64 + ], + [ + 400000, + 0.6933333333333334 + ], + [ + 450000, + 0.68 + ], + [ + 500000, + 0.68 + ], + [ + 500000, + 0.6880000000000001 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 2994.4, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/0burclfj" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..529c701cd7f908ecc59d9d05e2beb4d2165c92b8 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq.json @@ -0,0 +1,51 @@ +{ + "method": "gciql_genq", + "env": "puzzle-3x3-play-v0", + "seed": 4, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 0.5, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_puzzle_3x3_play_v0.genqjax.npz", + "success_rate": 0.0, + "best_sr": 0.07999999999999999, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.04 + ], + [ + 100000, + 0.05333333333333333 + ], + [ + 150000, + 0.07999999999999999 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.013333333333333332 + ], + [ + 300000, + 0.0 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 20967.9, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/yo7vzo0s" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..6be5fc23c4830c53ab1f091a1061e6d200d70d37 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b09.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-3x3-play-v0", + "seed": 4, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.15925179421901703, + "genq_npz": "m9_genq_rec_puzzle_3x3_play_v0_b09.genqjax.npz", + "success_rate": 0.039999999999999994, + "best_sr": 0.039999999999999994, + "per_task": [ + 0.16, + 0.02, + 0.02, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.013333333333333332 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.013333333333333332 + ], + [ + 200000, + 0.026666666666666665 + ], + [ + 250000, + 0.013333333333333332 + ], + [ + 300000, + 0.026666666666666665 + ], + [ + 300000, + 0.039999999999999994 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19438.6, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/h8n5qium" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..25ee173a607b1ce8d00d80e38e788555fa3e9fea --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-3x3-play-v0", + "seed": 4, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.15901173651218414, + "genq_npz": "m9_genq_rec_puzzle_3x3_play_v0_b095.genqjax.npz", + "success_rate": 0.024, + "best_sr": 0.06666666666666668, + "per_task": [ + 0.1, + 0.0, + 0.02, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.013333333333333332 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.013333333333333332 + ], + [ + 200000, + 0.04 + ], + [ + 250000, + 0.06666666666666668 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.024 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 11175.0, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/itt47z3v" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-3x3-play-v0/results/4/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/figures/suc.png b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/figures/suc.png new file mode 100644 index 0000000000000000000000000000000000000000..a865211753190fb97f3c4ee9478888a7ce2c2f0f Binary files /dev/null and b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/figures/suc.png differ diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..e03e303b1041042e46f3ec40c9ba433a418cdd1e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "success_rate": 0.0, + "best_sr": 0.0, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.0 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 3879.0, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/vhbr95ir" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..93814c1d937b33327d60f59288033915e5ab20ac --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "success_rate": 0.21600000000000003, + "best_sr": 0.31999999999999995, + "per_task": [ + 0.56, + 0.0, + 0.26, + 0.02, + 0.24 + ], + "curve": [ + [ + 50000, + 0.14666666666666667 + ], + [ + 100000, + 0.2 + ], + [ + 150000, + 0.22666666666666666 + ], + [ + 200000, + 0.27999999999999997 + ], + [ + 250000, + 0.31999999999999995 + ], + [ + 300000, + 0.21333333333333332 + ], + [ + 350000, + 0.21333333333333332 + ], + [ + 400000, + 0.2533333333333333 + ], + [ + 450000, + 0.2533333333333333 + ], + [ + 500000, + 0.24 + ], + [ + 500000, + 0.21600000000000003 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 3897.1, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/a7ag1xb9" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..dda6d5ae29b64c20ef30bb3f00f1d7c7bef9dcf7 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq.json @@ -0,0 +1,51 @@ +{ + "method": "gciql_genq", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 0.5, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_puzzle_4x4_play_v0.genqjax.npz", + "success_rate": 0.013333333333333332, + "best_sr": 0.013333333333333332, + "per_task": [ + 0.06666666666666667, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.013333333333333332 + ], + [ + 200000, + 0.013333333333333332 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.013333333333333332 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 17016.6, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/v20ux7kz" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..0198e31fb962aa5ac1c0c0edc0fa2607547669c1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b09.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.18476414680480957, + "genq_npz": "m9_genq_rec_puzzle_4x4_play_v0_b09.genqjax.npz", + "success_rate": 0.004, + "best_sr": 0.026666666666666665, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.02, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.013333333333333332 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.026666666666666665 + ], + [ + 300000, + 0.004 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 35920.8, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/1fnctiba" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..0ab2de658e57bcc721abe1ce606eab3d0dcebdbb --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.18476414680480957, + "genq_npz": "m9_genq_rec_puzzle_4x4_play_v0_b095.genqjax.npz", + "success_rate": 0.008, + "best_sr": 0.008, + "per_task": [ + 0.02, + 0.0, + 0.02, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.008 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 20299.8, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/jr7xfnb9" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p400_read1.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p400_read1.json new file mode 100644 index 0000000000000000000000000000000000000000..2c2d503b8cfcb7517cad593fb56be4d9d0b7f482 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p400_read1.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "actor_pkl": "best_rsm_p4x4_s0_p400.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.304, + "per_task": [ + 0.72, + 0.0, + 0.4, + 0.18, + 0.22 + ] + } + }, + "wall_clock_sec": 114.7 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p400_read2.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p400_read2.json new file mode 100644 index 0000000000000000000000000000000000000000..935080f026460625caee2c10e1aad08fd6919f49 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p400_read2.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-4x4-play-v0", + "seed": 1, + "actor_pkl": "best_rsm_p4x4_s0_p400.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.33599999999999997, + "per_task": [ + 0.64, + 0.0, + 0.58, + 0.24, + 0.22 + ] + } + }, + "wall_clock_sec": 114.4 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p613_read1.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p613_read1.json new file mode 100644 index 0000000000000000000000000000000000000000..6aacfe4235413c7b7ca358ccd0776c92137230a2 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p613_read1.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "actor_pkl": "best_rsm_p4x4_s0_p613.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.512, + "per_task": [ + 0.92, + 0.08, + 0.64, + 0.44, + 0.48 + ] + } + }, + "wall_clock_sec": 115.5 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p613_read2.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p613_read2.json new file mode 100644 index 0000000000000000000000000000000000000000..893c7a722aa47e5ab344f243fc2eeedccc75489a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p613_read2.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-4x4-play-v0", + "seed": 1, + "actor_pkl": "best_rsm_p4x4_s0_p613.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.5840000000000001, + "per_task": [ + 0.9, + 0.18, + 0.8, + 0.56, + 0.48 + ] + } + }, + "wall_clock_sec": 115.1 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p680_read1.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p680_read1.json new file mode 100644 index 0000000000000000000000000000000000000000..5b591239674b49c231d0762049a453f9eb4b91cf --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p680_read1.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "actor_pkl": "best_rsm_p4x4_s0_p680.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.6519999999999999, + "per_task": [ + 0.92, + 0.24, + 0.72, + 0.62, + 0.76 + ] + } + }, + "wall_clock_sec": 111.7 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p680_read2.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p680_read2.json new file mode 100644 index 0000000000000000000000000000000000000000..cb77ee172e191a260296e7cde594e5f67aa02b8d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/official_rsm_p4x4_s0_p680_read2.json @@ -0,0 +1,29 @@ +{ + "method": "eval_plan", + "env": "puzzle-4x4-play-v0", + "seed": 1, + "actor_pkl": "best_rsm_p4x4_s0_p680.pkl", + "occ_npz": null, + "plan_k": [ + 1 + ], + "plan_sigma": 0.2, + "plan_pess": 1, + "plan_bc": 0.0, + "episodes": 50, + "n_orders": 16, + "read_gamma": 0.0, + "results": { + "k1": { + "success_rate": 0.6359999999999999, + "per_task": [ + 0.94, + 0.2, + 0.74, + 0.8, + 0.5 + ] + } + }, + "wall_clock_sec": 106.4 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/rsm.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/rsm.json new file mode 100644 index 0000000000000000000000000000000000000000..b09104235b1d16c40a471236b3a0d48257d9e534 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/0/rsm.json @@ -0,0 +1,193 @@ +{ + "method": "rsm", + "readout": "gl", + "env": "puzzle-4x4-play-v0", + "seed": 0, + "alpha": 1.0, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "off", + "gamma_spectrum_lo": 0.95, + "success_rate": 0.664, + "best_sr": 0.68, + "final_last_step": 0.652, + "final_best_ckpt": 0.664, + "best_ckpt_periodic_sr": 0.76, + "per_task": [ + 0.8, + 0.5, + 0.74, + 0.68, + 0.6 + ], + "curve": [ + [ + 25000, + 0.0 + ], + [ + 50000, + 0.013333333333333332 + ], + [ + 75000, + 0.05333333333333333 + ], + [ + 100000, + 0.09333333333333334 + ], + [ + 125000, + 0.13333333333333336 + ], + [ + 150000, + 0.05333333333333333 + ], + [ + 175000, + 0.2533333333333333 + ], + [ + 200000, + 0.26666666666666666 + ], + [ + 225000, + 0.3466666666666666 + ], + [ + 250000, + 0.29333333333333333 + ], + [ + 275000, + 0.3466666666666666 + ], + [ + 300000, + 0.30666666666666664 + ], + [ + 325000, + 0.2533333333333333 + ], + [ + 350000, + 0.37333333333333335 + ], + [ + 375000, + 0.6133333333333333 + ], + [ + 400000, + 0.5466666666666666 + ], + [ + 425000, + 0.4666666666666667 + ], + [ + 450000, + 0.5466666666666666 + ], + [ + 475000, + 0.5066666666666666 + ], + [ + 500000, + 0.4 + ], + [ + 525000, + 0.52 + ], + [ + 550000, + 0.6 + ], + [ + 575000, + 0.6266666666666666 + ], + [ + 600000, + 0.48 + ], + [ + 625000, + 0.5866666666666667 + ], + [ + 650000, + 0.48 + ], + [ + 675000, + 0.5199999999999999 + ], + [ + 700000, + 0.64 + ], + [ + 725000, + 0.5333333333333334 + ], + [ + 750000, + 0.49333333333333335 + ], + [ + 775000, + 0.68 + ], + [ + 800000, + 0.6133333333333334 + ], + [ + 825000, + 0.6133333333333334 + ], + [ + 850000, + 0.38666666666666666 + ], + [ + 875000, + 0.4666666666666667 + ], + [ + 900000, + 0.6133333333333334 + ], + [ + 925000, + 0.42666666666666664 + ], + [ + 950000, + 0.4933333333333333 + ], + [ + 975000, + 0.5333333333333334 + ], + [ + 1000000, + 0.6666666666666667 + ], + [ + 1000000, + 0.652 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 187997.4, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/bhpqmiv6" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..f62b3070c5ba60553969251f23aa750a15dc31a9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "puzzle-4x4-play-v0", + "seed": 1, + "success_rate": 0.004, + "best_sr": 0.013333333333333332, + "per_task": [ + 0.02, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.013333333333333332 + ], + [ + 300000, + 0.004 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 3440.5, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/bdyw0wr9" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..d5d5aab0244d4121b2254a263c0d089344a13964 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "puzzle-4x4-play-v0", + "seed": 1, + "actor_loss": "ddpgbc", + "alpha": 0.3, + "expectile": 0.9, + "success_rate": 0.12000000000000002, + "best_sr": 0.13333333333333336, + "per_task": [ + 0.14, + 0.0, + 0.34, + 0.06, + 0.06 + ], + "curve": [ + [ + 50000, + 0.06666666666666667 + ], + [ + 100000, + 0.09333333333333334 + ], + [ + 150000, + 0.07999999999999999 + ], + [ + 200000, + 0.13333333333333336 + ], + [ + 250000, + 0.09333333333333334 + ], + [ + 300000, + 0.05333333333333333 + ], + [ + 350000, + 0.06666666666666667 + ], + [ + 400000, + 0.10666666666666666 + ], + [ + 450000, + 0.07999999999999999 + ], + [ + 500000, + 0.12 + ], + [ + 500000, + 0.12000000000000002 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 4994.0, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/7dt9z6dk" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..481d3b2e04bf3c6f75f11f1231d1f96f51357a85 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq.json @@ -0,0 +1,55 @@ +{ + "method": "gciql_genq", + "env": "puzzle-4x4-play-v0", + "seed": 1, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 0.5, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_puzzle_4x4_play_v0.genqjax.npz", + "success_rate": 0.012, + "best_sr": 0.013333333333333332, + "per_task": [ + 0.04, + 0.0, + 0.0, + 0.02, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.013333333333333332 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.012 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 15467.0, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/6pp8yvnh" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..eda28b18de49ccfa28105000b1a02ecbf7d2c1d9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b09.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-4x4-play-v0", + "seed": 1, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.17200198769569397, + "genq_npz": "m9_genq_rec_puzzle_4x4_play_v0_b09.genqjax.npz", + "success_rate": 0.0, + "best_sr": 0.0, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.0 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 35735.2, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/hr3ibfzj" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..37e0c035dcafcb9687e54fb5a087520c576806b8 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-4x4-play-v0", + "seed": 1, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.17333774268627167, + "genq_npz": "m9_genq_rec_puzzle_4x4_play_v0_b095.genqjax.npz", + "success_rate": 0.008, + "best_sr": 0.013333333333333332, + "per_task": [ + 0.0, + 0.02, + 0.0, + 0.0, + 0.02 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.013333333333333332 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.013333333333333332 + ], + [ + 300000, + 0.013333333333333332 + ], + [ + 300000, + 0.008 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 11455.0, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/ekz41rzz" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/1/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..f82119ace451250e469df42082ea8ee51d1c0ada --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "puzzle-4x4-play-v0", + "seed": 2, + "success_rate": 0.0, + "best_sr": 0.013333333333333332, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.013333333333333332 + ], + [ + 150000, + 0.013333333333333332 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.013333333333333332 + ], + [ + 300000, + 0.0 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 3380.4, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/ylzjwn3f" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..b893fd480f4e09eaf5c34138f9b07abb1ba6e253 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "puzzle-4x4-play-v0", + "seed": 2, + "actor_loss": "ddpgbc", + "alpha": 0.3, + "expectile": 0.9, + "success_rate": 0.16399999999999998, + "best_sr": 0.21333333333333332, + "per_task": [ + 0.22, + 0.0, + 0.36, + 0.1, + 0.14 + ], + "curve": [ + [ + 50000, + 0.09333333333333334 + ], + [ + 100000, + 0.08 + ], + [ + 150000, + 0.10666666666666666 + ], + [ + 200000, + 0.04 + ], + [ + 250000, + 0.14666666666666667 + ], + [ + 300000, + 0.10666666666666666 + ], + [ + 350000, + 0.2 + ], + [ + 400000, + 0.09333333333333332 + ], + [ + 450000, + 0.21333333333333332 + ], + [ + 500000, + 0.18666666666666668 + ], + [ + 500000, + 0.16399999999999998 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 4783.1, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/vuieoije" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..0f1d755398f2472d21b258b450c21efdfad8de2d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq.json @@ -0,0 +1,55 @@ +{ + "method": "gciql_genq", + "env": "puzzle-4x4-play-v0", + "seed": 2, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 0.5, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_puzzle_4x4_play_v0.genqjax.npz", + "success_rate": 0.004, + "best_sr": 0.004, + "per_task": [ + 0.0, + 0.02, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.004 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 16041.5, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/iunufy4f" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..ec6dfb957c3596b6b20cab97fbf44bc872e0e81f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b09.json @@ -0,0 +1,61 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-4x4-play-v0", + "seed": 2, + "full_state": false, + "variant_tag": null, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.163155198097229, + "genq_npz": "m9_genq_rec_puzzle_4x4_play_v0_b09.genqjax.npz", + "success_rate": 0.0, + "best_sr": 0.013333333333333332, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.013333333333333332 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 250000, + 0.013333333333333332 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.0 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 35906.9, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/j5slh3vk" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..4d8740e576ec221fe8bf2173635cf7d80f62a1b9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "puzzle-4x4-play-v0", + "seed": 2, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.163155198097229, + "genq_npz": "m9_genq_rec_puzzle_4x4_play_v0_b095.genqjax.npz", + "success_rate": 0.004, + "best_sr": 0.013333333333333332, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.02, + 0.0 + ], + "curve": [ + [ + 50000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 200000, + 0.013333333333333332 + ], + [ + 250000, + 0.0 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.004 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19876.5, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/50un14xv" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/results/2/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/train_genq_joint.py b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/train_genq_joint.py new file mode 100644 index 0000000000000000000000000000000000000000..24bc069d204404fe7dd23be089bf47e2ecfc6090 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x4-play-v0/train_genq_joint.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python +"""JOINT Gen-Q policy iteration on puzzle-3x3-play-v0: occupancy + critic + V + actor in one +loop (no TD, no staging). See ogbench_genq/genq_joint.py.""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq.genq_joint import run_genq_joint + +ENV = "puzzle-4x4-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=500000) + ap.add_argument("--alpha", type=float, default=1.0) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--rt_eta", type=float, default=0.5) + ap.add_argument("--pi_alpha", type=float, default=1.0) + ap.add_argument("--pi_horizon", type=int, default=25) + ap.add_argument("--occ_warmup", type=int, default=50000) + ap.add_argument("--occ_tau", type=float, default=0.005) + ap.add_argument("--n_orders", type=int, default=16) + ap.add_argument("--extraction", default="r3", + choices=["r3", "gliql", "ddpg2", "awr2"]) + ap.add_argument("--gliql_alpha", type=float, default=3.0) + ap.add_argument("--awr_alpha", type=float, default=3.0, + help="awr2 temperature on the batch-std-normalized log-gl " + "advantage (forward-only actor loss; host path only)") + ap.add_argument("--occ_warmstart_npz", default=None) + ap.add_argument("--eval_interval", type=int, default=25000) + ap.add_argument("--variant_tag", default=None) + ap.add_argument("--save_agent", default=None) + ap.add_argument("--save_occ", default=None, + help="save the co-trained occupancy EMA as a warm-start-format " + "npz (input for eval_plan.py test-time planning)") + ap.add_argument("--rec_target", type=int, default=0, + help="RECURSIVE PREDICTION: M occupancy-sampled midpoints; r3 composes " + "critic targets, ddpg2 composes the actor loss through gl jumps") + ap.add_argument("--rec_every", type=int, default=2) + ap.add_argument("--rec_eps", type=float, default=0.5) + ap.add_argument("--rec_after", type=int, default=100000) + ap.add_argument("--rec_beta", type=float, default=0.0, + help="beta-recursive rule: stochastic recursion depth, continue " + "w.p. p=(gamma-beta)/(gamma*(1-beta)); 0 = fixed depth-1") + ap.add_argument("--rec_max_depth", type=int, default=6) + ap.add_argument("--rec_prob", action="store_true", + help="probabilistic beta-jump Q estimator (splitting identity, " + "expectation instead of max-certificates; needs rec_free+rec_beta)") + ap.add_argument("--rec_pess", type=int, default=1, + help="pessimism at generated midpoints: value = min over K " + "independent completion draws (1 = off)") + ap.add_argument("--gamma_spectrum_lo", type=float, default=0.0, + help="train the occupancy CONDITIONED on the discount, sampled " + "log-uniform-in-horizon in [lo, gamma] (0 = fixed gamma). " + "PI gl reads at task gamma; recursion hops at rec_beta.") + ap.add_argument("--gamma_spectrum_p", type=float, default=0.5) + ap.add_argument("--rec_free", action="store_true", + help="retrieval-free midpoints: full-state completion head, " + "live-actor midpoint actions (no eps-grid, no lookup)") + ap.add_argument("--readout", default="gl", choices=["gl", "sample"], + help="occupancy Q read-out for targets/hit terms (host path): gl = " + "exact teacher-forced likelihood; sample = de-hacked MC " + "hit-count over n_occ_ro ancestral draws") + ap.add_argument("--n_occ_ro", type=int, default=64) + ap.add_argument("--rec_actor", action="store_true", + help="r3: ALSO compose the actor-goal targets — the ddpgbc actor " + "differentiates the distilled critic at actor_goals, so " + "composition reaches the head the policy gradient reads " + "(retrieval-form cell: +0.13 final over value-goals-only)") + ap.add_argument("--actor_ema_tau", type=float, default=0.0, + help="Polyak EMA of the actor, evaluated alongside the live actor each " + "periodic eval (late-band stabilizer; best-ckpt picks the winner)") + ap.add_argument("--fast", action="store_true", + help="fused on-device train step + lax.scan (plain r3/ddpg2 only; " + "no rec_target/gliql)") + ap.add_argument("--steps_per_dispatch", type=int, default=100) + ap.add_argument("--data_parallel", action="store_true", + help="pmap the fused train step over all local devices (fast path " + "only): per-device batch = batch/D, grads pmean'd, global " + "batch semantics preserved") + ap.add_argument("--batch_size", type=int, default=0, + help="override PI batch size (fast path; 0 = reference 1024)") + ap.add_argument("--occ_batch", type=int, default=256) + ap.add_argument("--n_orders_pi", type=int, default=0, + help="order count for the differentiated actor-loss gl calls " + "(fast path; 0 = full n_orders). Large batch absorbs the " + "extra per-state read-out noise") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + assert not (a.data_parallel and not a.fast), "--data_parallel requires --fast" + if a.fast: + from ogbench_genq.genq_joint_fast import run_genq_joint_fast + assert a.extraction in ("r3", "ddpg2") + assert not (a.rec_target > 0 and not a.rec_free), \ + "fast recursion is retrieval-free only" + run_genq_joint_fast(ENV, seed=a.seed, train_steps=a.train_steps, alpha=a.alpha, + expectile=a.expectile, rt_eta=a.rt_eta, pi_alpha=a.pi_alpha, + pi_horizon=a.pi_horizon, occ_warmup=a.occ_warmup, + occ_tau=a.occ_tau, n_orders=a.n_orders, + extraction=a.extraction, + occ_warmstart_npz=a.occ_warmstart_npz, + eval_interval=a.eval_interval, variant_tag=a.variant_tag, + save_agent=a.save_agent, save_occ=a.save_occ, + n_orders_pi=a.n_orders_pi, + actor_ema_tau=a.actor_ema_tau, + steps_per_dispatch=a.steps_per_dispatch, + batch_size=a.batch_size, occ_batch=a.occ_batch, + rec_target=a.rec_target, rec_every=a.rec_every, + rec_after=a.rec_after, rec_beta=a.rec_beta, + rec_max_depth=a.rec_max_depth, rec_prob=a.rec_prob, + rec_actor=a.rec_actor, + gamma_spectrum_lo=a.gamma_spectrum_lo, + gamma_spectrum_p=a.gamma_spectrum_p, + data_parallel=a.data_parallel, + eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode) + raise SystemExit(0) + run_genq_joint(ENV, seed=a.seed, train_steps=a.train_steps, alpha=a.alpha, + expectile=a.expectile, rt_eta=a.rt_eta, pi_alpha=a.pi_alpha, + pi_horizon=a.pi_horizon, occ_warmup=a.occ_warmup, occ_tau=a.occ_tau, + n_orders=a.n_orders, extraction=a.extraction, + gliql_alpha=a.gliql_alpha, awr_alpha=a.awr_alpha, + occ_warmstart_npz=a.occ_warmstart_npz, + eval_interval=a.eval_interval, + variant_tag=a.variant_tag, save_agent=a.save_agent, + save_occ=a.save_occ, + actor_ema_tau=a.actor_ema_tau, + rec_target=a.rec_target, rec_every=a.rec_every, rec_eps=a.rec_eps, + rec_after=a.rec_after, rec_free=a.rec_free, + rec_beta=a.rec_beta, rec_max_depth=a.rec_max_depth, rec_pess=a.rec_pess, + rec_prob=a.rec_prob, rec_actor=a.rec_actor, + readout=a.readout, n_occ_ro=a.n_occ_ro, + gamma_spectrum_lo=a.gamma_spectrum_lo, gamma_spectrum_p=a.gamma_spectrum_p, + eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x5-play-v0/results/0/rsm_newcov.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x5-play-v0/results/0/rsm_newcov.json new file mode 100644 index 0000000000000000000000000000000000000000..ccab121abc21b4fda595958709eaa8c353bc3b15 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x5-play-v0/results/0/rsm_newcov.json @@ -0,0 +1,156 @@ +{ + "method": "rsm", + "readout": "gl", + "env": "puzzle-4x5-play-v0", + "seed": 0, + "alpha": 1.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "off", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.14666666666666667, + "best_sr": 0.18666666666666668, + "per_task": [ + 0.7333333333333333, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 25000, + 0.0 + ], + [ + 50000, + 0.013333333333333332 + ], + [ + 75000, + 0.026666666666666665 + ], + [ + 100000, + 0.08 + ], + [ + 125000, + 0.05333333333333333 + ], + [ + 150000, + 0.013333333333333332 + ], + [ + 175000, + 0.013333333333333332 + ], + [ + 200000, + 0.10666666666666666 + ], + [ + 225000, + 0.05333333333333333 + ], + [ + 250000, + 0.09333333333333334 + ], + [ + 275000, + 0.18666666666666668 + ], + [ + 300000, + 0.04 + ], + [ + 325000, + 0.05333333333333333 + ], + [ + 350000, + 0.12 + ], + [ + 375000, + 0.13333333333333333 + ], + [ + 400000, + 0.10666666666666666 + ], + [ + 425000, + 0.08 + ], + [ + 450000, + 0.14666666666666667 + ], + [ + 475000, + 0.09333333333333334 + ], + [ + 500000, + 0.12 + ], + [ + 525000, + 0.16 + ], + [ + 550000, + 0.06666666666666667 + ], + [ + 575000, + 0.08 + ], + [ + 600000, + 0.09333333333333334 + ], + [ + 625000, + 0.08 + ], + [ + 650000, + 0.09333333333333334 + ], + [ + 675000, + 0.09333333333333334 + ], + [ + 700000, + 0.04 + ], + [ + 725000, + 0.13333333333333333 + ], + [ + 750000, + 0.10666666666666666 + ], + [ + 775000, + 0.08 + ], + [ + 800000, + 0.14666666666666667 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 5174.6, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/njgxike2" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/puzzle-4x6-play-v0/results/0/rsm_newcov.json b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x6-play-v0/results/0/rsm_newcov.json new file mode 100644 index 0000000000000000000000000000000000000000..3d77acdd7808eddabdc69848f0a17482fdad63dc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/puzzle-4x6-play-v0/results/0/rsm_newcov.json @@ -0,0 +1,136 @@ +{ + "method": "rsm", + "readout": "gl", + "env": "puzzle-4x6-play-v0", + "seed": 0, + "alpha": 1.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "off", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.04, + "best_sr": 0.08, + "per_task": [ + 0.2, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 25000, + 0.0 + ], + [ + 50000, + 0.0 + ], + [ + 75000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 125000, + 0.013333333333333332 + ], + [ + 150000, + 0.0 + ], + [ + 175000, + 0.013333333333333332 + ], + [ + 200000, + 0.013333333333333332 + ], + [ + 225000, + 0.013333333333333332 + ], + [ + 250000, + 0.08 + ], + [ + 275000, + 0.04 + ], + [ + 300000, + 0.0 + ], + [ + 325000, + 0.05333333333333333 + ], + [ + 350000, + 0.013333333333333332 + ], + [ + 375000, + 0.0 + ], + [ + 400000, + 0.013333333333333332 + ], + [ + 425000, + 0.0 + ], + [ + 450000, + 0.026666666666666665 + ], + [ + 475000, + 0.013333333333333332 + ], + [ + 500000, + 0.026666666666666665 + ], + [ + 525000, + 0.026666666666666665 + ], + [ + 550000, + 0.013333333333333332 + ], + [ + 575000, + 0.04 + ], + [ + 600000, + 0.013333333333333332 + ], + [ + 625000, + 0.026666666666666665 + ], + [ + 650000, + 0.0 + ], + [ + 675000, + 0.04 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 32869.7, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/9c3nivd9" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/relaunch_b5_sequential.sh b/gen_q_rsm/ogbench_genq/experiments/relaunch_b5_sequential.sh new file mode 100644 index 0000000000000000000000000000000000000000..a441e5b12de4ea8465c455fe0d200905ebdd019a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/relaunch_b5_sequential.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# b5 relaunch. puzzle-4x5 + puzzle-4x6 OOM-crashed (job 278897, exit 1) when +# co-packed at MEM_FRACTION 0.42 each — wide bit-vectors (20 / 24 bits) have +# bigger activations than the 3x3 the 0.42 packing was sized for, and a spike +# blew past their shared budget. Run them SEQUENTIALLY on one GPU at full memory +# instead: no co-tenancy, still 1 GPU, resumes from --ckpt (resume_p45/p46.pkl, +# banked 00:13 / 01:10). Floor cells (0.187 / 0.080), breadth-only. +set -uo pipefail +cd /proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-ogbench-matrix +[ -f .env ] && set -a && . ./.env && set +a +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +mkdir -p ogbench_genq/experiments/logs +for cell in "puzzle-4x5-play-v0 resume_p45" "puzzle-4x6-play-v0 resume_p46"; do + set -- $cell; env=$1; ck=$2 + echo "[b5-seq] $env starting (resume ckpt/$ck.pkl)" + # --wandb_mode offline is REQUIRED: rsm.py defaults --wandb_mode=online and + # OVERRIDES the WANDB_MODE env var, so without this it hits the wandb-core + # service and can die on an intermittent ConnectionResetError (killed the + # first seq relaunch at step 800k). offline = local files, no service. + bash ogbench_genq/experiments/run_rsm.sh "$env" 0 \ + --train_steps 1000000 --variant_tag newcov --wandb_mode offline \ + --ckpt "ckpt/$ck.pkl" --ckpt_every 25000 \ + > "ogbench_genq/experiments/logs/seq_b5_${env}_s0.log" 2>&1 || true + echo "[b5-seq] $env done rc=$?" +done +echo "[b5-seq] ALL DONE" diff --git a/gen_q_rsm/ogbench_genq/experiments/rsm_rdec_logit.sh b/gen_q_rsm/ogbench_genq/experiments/rsm_rdec_logit.sh new file mode 100644 index 0000000000000000000000000000000000000000..17ba5082d460a64e69ca7e844e344402c00702c2 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/rsm_rdec_logit.sh @@ -0,0 +1,20 @@ +#!/bin/bash +set -uo pipefail +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF"; [ -f .env ] && set -a && . ./.env && set +a +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false XLA_PYTHON_CLIENT_MEM_FRACTION=0.6 +export MUJOCO_GL=egl WANDB_MODE=disabled PYTHONUNBUFFERED=1 RDEC_LOGIT=1 +PY=$REC/.ogbench_venv/bin/python +ENV=visual-cube-single-play-v0 +LAT=ckpt/valrew_smooth_s10_fast_latents.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_smooth_s10_fast.npz +RDEC=ckpt/rdec_smooth_s10_fast.npz +echo "[rdec-logit] host $(hostname); RAW-LOGIT read-out, reuse saved R_psi" +$PY -u ogbench_genq/rsm.py --env "$ENV" --latent_npz "$LAT" --pixel_encoder "$ENC" \ + --reward_decoder "$RDEC" --rdec_samples 8 \ + --recursion off --alpha 0.3 --train_steps 200000 --eval_interval 25000 \ + --ckpt ckpt/rsm_rdec_smooth_logit.pkl --ckpt_every 25000 \ + --variant_tag "rdec_smooth_logit_recoff" --wandb_mode disabled +echo "[rdec-logit] EXIT $?" diff --git a/gen_q_rsm/ogbench_genq/experiments/run_gcbc.sh b/gen_q_rsm/ogbench_genq/experiments/run_gcbc.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6bc23ea53d8bbdd897ea7b3029ea4f0acc9a234 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/run_gcbc.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# GCBC baseline: goal-conditioned behavior cloning (the floor). +# Usage: bash ogbench_genq/experiments/run_gcbc.sh [seed] +set -euo pipefail +ENV_ID=${1:?usage: run_gcbc.sh [seed]}; SEED=${2:-0} +cd "$(dirname "$0")/../.." +[ -f .env ] && set -a && source .env && set +a +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +# use the repo venv unless the caller provides PYTHON +PY=${PYTHON:-}; [ -z "$PY" ] && [ -x .ogbench_venv/bin/python ] && PY=.ogbench_venv/bin/python; PY=${PY:-python} +"$PY" -c "import sys; sys.path.insert(0, '.'); \ +from ogbench_genq._runner import run_gcbc; \ +run_gcbc('$ENV_ID', seed=$SEED)" diff --git a/gen_q_rsm/ogbench_genq/experiments/run_gciql.sh b/gen_q_rsm/ogbench_genq/experiments/run_gciql.sh new file mode 100644 index 0000000000000000000000000000000000000000..12465c4bad06bb245c595d45dfc6a66fef19d5b9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/run_gciql.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# GCIQL baseline: the reference-tuned TD agent (the bar RSM is measured against). +# Usage: bash ogbench_genq/experiments/run_gciql.sh [seed] [alpha] +# alpha = the DDPG+BC weight; use the env's published reference value +# (puzzle-3x3: 1.0, pointmaze: 0.003 — see $OGBENCH_IMPLS/hyperparameters.sh). +set -euo pipefail +ENV_ID=${1:?usage: run_gciql.sh [seed] [alpha]}; SEED=${2:-0}; ALPHA=${3:-1.0} +cd "$(dirname "$0")/../.." +[ -f .env ] && set -a && source .env && set +a +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +# use the repo venv unless the caller provides PYTHON +PY=${PYTHON:-}; [ -z "$PY" ] && [ -x .ogbench_venv/bin/python ] && PY=.ogbench_venv/bin/python; PY=${PY:-python} +"$PY" -c "import sys; sys.path.insert(0, '.'); \ +from ogbench_genq._runner import run_gciql; \ +run_gciql('$ENV_ID', seed=$SEED, actor_loss='ddpgbc', alpha=$ALPHA)" diff --git a/gen_q_rsm/ogbench_genq/experiments/run_recipe.sh b/gen_q_rsm/ogbench_genq/experiments/run_recipe.sh new file mode 100644 index 0000000000000000000000000000000000000000..206a07111cca15a852625afcd974ded2f10cf378 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/run_recipe.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Run THE single recipe (rsm_recipe.py) for one env. Self-locating: always runs +# the code of the checkout this script lives in (worktree-safe), reusing the +# symlinked .venv. Usage: run_recipe.sh [seed] [extra rsm_recipe flags...] +set -euo pipefail +ENV_ID=${1:?usage: run_recipe.sh [seed] [extra flags...]} +SEED=${2:-0} +shift $(( $# > 1 ? 2 : 1 )) +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$ROOT" +[ -f .env ] && { set -a; source .env; set +a; } +export OGBENCH_IMPLS="${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls}" +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION="${XLA_PYTHON_CLIENT_MEM_FRACTION:-0.85}" +export WANDB_MODE="${WANDB_MODE:-offline}" +export MUJOCO_GL="${MUJOCO_GL:-egl}" # headless rendering (visual eval; silences GLFW/X11) +export PYTHONUNBUFFERED=1 +PY="$ROOT/.ogbench_venv/bin/python" +mkdir -p ckpt +echo "[run_recipe] ROOT=$ROOT env=$ENV_ID seed=$SEED" +echo "[run_recipe] python=$PY" +exec "$PY" -m ogbench_genq.rsm_recipe --env "$ENV_ID" --seed "$SEED" \ + --ckpt "ckpt/recipe_${ENV_ID}_s${SEED}.pkl" "$@" diff --git a/gen_q_rsm/ogbench_genq/experiments/run_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/run_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..5224d208740530baefd08f364a9bf9b25c5473bc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/run_rsm.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# RSM (the method): occupancy diffusion + actor, no critic / TD / max. +# Usage: bash ogbench_genq/experiments/run_rsm.sh [seed] [extra rsm.py flags...] +# Example: bash ogbench_genq/experiments/run_rsm.sh puzzle-3x3-play-v0 0 +set -euo pipefail +ENV_ID=${1:?usage: run_rsm.sh [seed] [extra flags...]}; SEED=${2:-0}; shift $(( $# > 1 ? 2 : 1 )) +cd "$(dirname "$0")/../.." # repo root +[ -f .env ] && set -a && source .env && set +a +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +# use the repo venv unless the caller provides PYTHON +PY=${PYTHON:-}; [ -z "$PY" ] && [ -x .ogbench_venv/bin/python ] && PY=.ogbench_venv/bin/python; PY=${PY:-python} +mkdir -p ckpt +"$PY" ogbench_genq/rsm.py --env "$ENV_ID" --seed "$SEED" \ + --save_best "ckpt/best_rsm_${ENV_ID}_s${SEED}.pkl" "$@" diff --git a/gen_q_rsm/ogbench_genq/experiments/run_sweep.sh b/gen_q_rsm/ogbench_genq/experiments/run_sweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..46a84e63910c1aaba1d0a6daf5d430648ed0126e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/run_sweep.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Pack several RSM arms onto ONE GPU allocation (CLAUDE.md: never one bsub per cell). +# Usage: bash ogbench_genq/experiments/run_sweep.sh +# plan.txt: one arm per line, " [extra rsm.py flags...]"; +# blank lines and #-comments are skipped. Example plans: experiments/sweeps/. +# Each arm logs to logs/sweep___s.log; the script waits for +# all arms and exits non-zero if any arm failed. +set -uo pipefail +PLAN=${1:?usage: run_sweep.sh } +cd "$(dirname "$0")/../.." # repo root +mkdir -p logs +tag=$(basename "$PLAN" .txt) + +pids=(); names=() +while read -r env seed flags; do + case "$env" in ''|'#'*) continue;; esac + log="logs/sweep_${tag}_${env}_s${seed}.log" + echo "[run_sweep] $env seed=$seed $flags -> $log" + # shellcheck disable=SC2086 # flags are intentionally word-split + bash ogbench_genq/experiments/run_rsm.sh "$env" "$seed" $flags >"$log" 2>&1 & + pids+=($!); names+=("$env s$seed") +done < "$PLAN" + +fail=0 +for i in "${!pids[@]}"; do + if wait "${pids[$i]}"; then + echo "[run_sweep] DONE ${names[$i]}" + else + echo "[run_sweep] FAILED ${names[$i]} (see logs/)"; fail=1 + fi +done +exit $fail diff --git a/gen_q_rsm/ogbench_genq/experiments/run_sweep2.sh b/gen_q_rsm/ogbench_genq/experiments/run_sweep2.sh new file mode 100644 index 0000000000000000000000000000000000000000..9baa20b76a89b578db6e5cc8a1d3ee83b12e614f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/run_sweep2.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# run_sweep.sh with per-arm indexed log names, so one plan may repeat an env +# (e.g. an alpha scan). Supersedes run_sweep.sh once wave-1 jobs (which are +# executing that script) finish — bash reads scripts lazily, so the original +# must not be edited while running. +set -uo pipefail +PLAN=${1:?usage: run_sweep2.sh } +cd "$(dirname "$0")/../.." # repo root +mkdir -p logs +tag=$(basename "$PLAN" .txt) + +i=0; pids=(); names=() +while read -r env seed flags; do + case "$env" in ''|'#'*) continue;; esac + log="logs/sweep_${tag}_${i}_${env}_s${seed}.log" + echo "[run_sweep2] arm$i $env seed=$seed $flags -> $log" + # shellcheck disable=SC2086 # flags are intentionally word-split + bash ogbench_genq/experiments/run_rsm.sh "$env" "$seed" $flags >"$log" 2>&1 & + pids+=($!); names+=("arm$i $env"); i=$((i+1)) +done < "$PLAN" + +fail=0 +for j in "${!pids[@]}"; do + if wait "${pids[$j]}"; then echo "[run_sweep2] DONE ${names[$j]}" + else echo "[run_sweep2] FAILED ${names[$j]} (see logs/)"; fail=1; fi +done +exit $fail diff --git a/gen_q_rsm/ogbench_genq/experiments/run_visual_gciql.sh b/gen_q_rsm/ogbench_genq/experiments/run_visual_gciql.sh new file mode 100644 index 0000000000000000000000000000000000000000..953324a7aef24fb1a2a9ff3c6f66521f80a5150b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/run_visual_gciql.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Diagnostic: does a REWARD-SHAPED (index/hindsight reward) end-to-end encoder learn +# the cube from pixels? OGBench visual GCIQL (impala CNN, pixels only, index reward) +# on visual-cube-single-play. If SR>0 -> reward-shaping cracks the pixels and the +# joint RSM is worth building; if ~0 -> pixels are the wall for everyone. Fair: +# pixels only (matches RSM's fair diet + the WMs), no cube coordinate in training. +set -uo pipefail +cd /u/zwhong/ogbench_ref/impls +export OGBENCH_IMPLS=$HOME/ogbench_ref/impls +export MUJOCO_GL=egl WANDB_MODE=offline +export XLA_PYTHON_CLIENT_PREALLOCATE=false +PY=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion/.ogbench_venv/bin/python +SAVE=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/gciql_visual_cube +$PY main.py --env_name=visual-cube-single-play-v0 --train_steps=500000 \ + --eval_interval=100000 --eval_episodes=50 --agent=agents/gciql.py \ + --agent.alpha=1.0 --agent.batch_size=256 --agent.encoder=impala_small --agent.p_aug=0.5 \ + --save_dir="$SAVE" +echo "[visual-gciql] rc=$?" diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/figures/suc.png b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/figures/suc.png new file mode 100644 index 0000000000000000000000000000000000000000..17acea3a368d1ec66e4d0b962961bcd920930cfe Binary files /dev/null and b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/figures/suc.png differ diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..a46544086c23726e7c68ac2762108e94488a7433 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "scene-play-v0", + "seed": 0, + "success_rate": 0.02, + "best_sr": 0.14666666666666667, + "per_task": [ + 0.06, + 0.0, + 0.04, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.14666666666666667 + ], + [ + 100000, + 0.05333333333333333 + ], + [ + 150000, + 0.09333333333333332 + ], + [ + 200000, + 0.026666666666666665 + ], + [ + 250000, + 0.08 + ], + [ + 300000, + 0.026666666666666665 + ], + [ + 300000, + 0.02 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 4964.3, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/7pjctl1b" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..2d004b157bdd77197c41cd0f5650cc59d41aee37 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "scene-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "success_rate": 0.544, + "best_sr": 0.56, + "per_task": [ + 0.9, + 0.92, + 0.82, + 0.04, + 0.04 + ], + "curve": [ + [ + 50000, + 0.18666666666666668 + ], + [ + 100000, + 0.3466666666666667 + ], + [ + 150000, + 0.38666666666666666 + ], + [ + 200000, + 0.4533333333333334 + ], + [ + 250000, + 0.4666666666666667 + ], + [ + 300000, + 0.4533333333333333 + ], + [ + 350000, + 0.5066666666666667 + ], + [ + 400000, + 0.5333333333333334 + ], + [ + 450000, + 0.49333333333333335 + ], + [ + 500000, + 0.56 + ], + [ + 500000, + 0.544 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 4003.7, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/w9dun509" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..6d33ffb279e96849f302cf26540f2c5c2bb65290 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq.json @@ -0,0 +1,51 @@ +{ + "method": "gciql_genq", + "env": "scene-play-v0", + "seed": 0, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 1.0, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_scene_play_v0.genqjax.npz", + "success_rate": 0.27999999999999997, + "best_sr": 0.36, + "per_task": [ + 0.8, + 0.3333333333333333, + 0.13333333333333333, + 0.06666666666666667, + 0.06666666666666667 + ], + "curve": [ + [ + 50000, + 0.30666666666666664 + ], + [ + 100000, + 0.3466666666666667 + ], + [ + 150000, + 0.24 + ], + [ + 200000, + 0.36 + ], + [ + 250000, + 0.31999999999999995 + ], + [ + 300000, + 0.27999999999999997 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 17167.0, + "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/60pb4uis" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..c6991d10e2809e39c865c7d4342cfb4d7457e372 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b09.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "scene-play-v0", + "seed": 0, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.20899152755737305, + "genq_npz": "m9_genq_rec_scene_play_v0_b09.genqjax.npz", + "success_rate": 0.17200000000000001, + "best_sr": 0.22666666666666666, + "per_task": [ + 0.46, + 0.2, + 0.12, + 0.06, + 0.02 + ], + "curve": [ + [ + 50000, + 0.10666666666666666 + ], + [ + 100000, + 0.2 + ], + [ + 150000, + 0.21333333333333332 + ], + [ + 200000, + 0.14666666666666667 + ], + [ + 250000, + 0.22666666666666666 + ], + [ + 300000, + 0.14666666666666667 + ], + [ + 300000, + 0.17200000000000001 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19832.4, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/z0um2hrb" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..9e796448f8ab044e36375ea4b8890af76aaa3fbf --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "scene-play-v0", + "seed": 0, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.2087802141904831, + "genq_npz": "m9_genq_rec_scene_play_v0_b095.genqjax.npz", + "success_rate": 0.248, + "best_sr": 0.36, + "per_task": [ + 0.68, + 0.2, + 0.12, + 0.16, + 0.08 + ], + "curve": [ + [ + 50000, + 0.2 + ], + [ + 100000, + 0.3466666666666667 + ], + [ + 150000, + 0.3333333333333333 + ], + [ + 200000, + 0.29333333333333333 + ], + [ + 250000, + 0.13333333333333333 + ], + [ + 300000, + 0.36 + ], + [ + 300000, + 0.248 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19492.0, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/56sa4lyh" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm.json new file mode 100644 index 0000000000000000000000000000000000000000..ff791b00ab6b359c9e7fbe3ffcda2ff84a5a6ab0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm.json @@ -0,0 +1,193 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "scene-play-v0", + "seed": 0, + "alpha": 0.03, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "success_rate": 0.148, + "best_sr": 0.17333333333333334, + "final_last_step": 0.132, + "final_best_ckpt": 0.148, + "best_ckpt_periodic_sr": 0.17333333333333334, + "per_task": [ + 0.72, + 0.0, + 0.02, + 0.0, + 0.0 + ], + "curve": [ + [ + 25000, + 0.0 + ], + [ + 50000, + 0.0 + ], + [ + 75000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 125000, + 0.013333333333333332 + ], + [ + 150000, + 0.0 + ], + [ + 175000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 225000, + 0.0 + ], + [ + 250000, + 0.026666666666666665 + ], + [ + 275000, + 0.026666666666666665 + ], + [ + 300000, + 0.026666666666666665 + ], + [ + 325000, + 0.026666666666666665 + ], + [ + 350000, + 0.04 + ], + [ + 375000, + 0.08 + ], + [ + 400000, + 0.14666666666666667 + ], + [ + 425000, + 0.10666666666666666 + ], + [ + 450000, + 0.08 + ], + [ + 475000, + 0.09333333333333334 + ], + [ + 500000, + 0.08 + ], + [ + 525000, + 0.09333333333333334 + ], + [ + 550000, + 0.14666666666666667 + ], + [ + 575000, + 0.12 + ], + [ + 600000, + 0.16 + ], + [ + 625000, + 0.12 + ], + [ + 650000, + 0.08 + ], + [ + 675000, + 0.17333333333333334 + ], + [ + 700000, + 0.12 + ], + [ + 725000, + 0.16 + ], + [ + 750000, + 0.10666666666666666 + ], + [ + 775000, + 0.026666666666666665 + ], + [ + 800000, + 0.13333333333333333 + ], + [ + 825000, + 0.06666666666666667 + ], + [ + 850000, + 0.13333333333333333 + ], + [ + 875000, + 0.09333333333333334 + ], + [ + 900000, + 0.10666666666666666 + ], + [ + 925000, + 0.06666666666666667 + ], + [ + 950000, + 0.12 + ], + [ + 975000, + 0.10666666666666666 + ], + [ + 1000000, + 0.12 + ], + [ + 1000000, + 0.132 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 185477.3, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/cifeccbo" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a10.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a10.json new file mode 100644 index 0000000000000000000000000000000000000000..7d15a2ce793265cd5571176f74482e74fb69ec25 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a10.json @@ -0,0 +1,32 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "scene-play-v0", + "seed": 0, + "alpha": 10.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.18666666666666665, + "best_sr": 0.18666666666666665, + "per_task": [ + 0.7333333333333333, + 0.06666666666666667, + 0.0, + 0.13333333333333333, + 0.0 + ], + "curve": [ + [ + 25000, + 0.18666666666666665 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 7119.2, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/o10bxkoh" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a3.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a3.json new file mode 100644 index 0000000000000000000000000000000000000000..e1294b863061b9583d0e06e40a5d2c825c92ff43 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a3.json @@ -0,0 +1,52 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "scene-play-v0", + "seed": 0, + "alpha": 3.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.22666666666666666, + "best_sr": 0.44000000000000006, + "per_task": [ + 0.7333333333333333, + 0.13333333333333333, + 0.2, + 0.06666666666666667, + 0.0 + ], + "curve": [ + [ + 25000, + 0.26666666666666666 + ], + [ + 50000, + 0.37333333333333335 + ], + [ + 75000, + 0.4 + ], + [ + 100000, + 0.44000000000000006 + ], + [ + 125000, + 0.2 + ], + [ + 150000, + 0.22666666666666666 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 25034.4, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/z4vrmarx" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a30.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a30.json new file mode 100644 index 0000000000000000000000000000000000000000..55816f35ed1703f10540dc779dd3e8d3deef5016 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_a30.json @@ -0,0 +1,52 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "scene-play-v0", + "seed": 0, + "alpha": 30.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.026666666666666665, + "best_sr": 0.17333333333333334, + "per_task": [ + 0.13333333333333333, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 25000, + 0.17333333333333334 + ], + [ + 50000, + 0.17333333333333334 + ], + [ + 75000, + 0.10666666666666666 + ], + [ + 100000, + 0.16 + ], + [ + 125000, + 0.07999999999999999 + ], + [ + 150000, + 0.026666666666666665 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 26422.6, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/700c2jbb" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_reconA3.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_reconA3.json new file mode 100644 index 0000000000000000000000000000000000000000..5159f5b5deae86cc5f7111ac6f9a4ade0566fa66 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/0/rsm_reconA3.json @@ -0,0 +1,124 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "scene-play-v0", + "seed": 0, + "alpha": 3.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.09333333333333334, + "best_sr": 0.4533333333333334, + "per_task": [ + 0.4666666666666667, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 25000, + 0.24 + ], + [ + 50000, + 0.3466666666666667 + ], + [ + 75000, + 0.37333333333333335 + ], + [ + 100000, + 0.4533333333333334 + ], + [ + 125000, + 0.29333333333333333 + ], + [ + 150000, + 0.3066666666666667 + ], + [ + 175000, + 0.13333333333333333 + ], + [ + 200000, + 0.10666666666666666 + ], + [ + 225000, + 0.15999999999999998 + ], + [ + 250000, + 0.13333333333333333 + ], + [ + 275000, + 0.10666666666666666 + ], + [ + 300000, + 0.12 + ], + [ + 325000, + 0.06666666666666668 + ], + [ + 350000, + 0.16 + ], + [ + 375000, + 0.08 + ], + [ + 400000, + 0.07999999999999999 + ], + [ + 425000, + 0.026666666666666665 + ], + [ + 450000, + 0.06666666666666667 + ], + [ + 475000, + 0.09333333333333332 + ], + [ + 500000, + 0.09333333333333334 + ], + [ + 525000, + 0.09333333333333332 + ], + [ + 550000, + 0.09333333333333334 + ], + [ + 575000, + 0.06666666666666667 + ], + [ + 600000, + 0.09333333333333334 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 30765.3, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/x716y5lt" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..c9e45289d2b2f7538ba5d585fbba0c9f4eae46dd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "scene-play-v0", + "seed": 1, + "success_rate": 0.036000000000000004, + "best_sr": 0.10666666666666666, + "per_task": [ + 0.06, + 0.0, + 0.08, + 0.04, + 0.0 + ], + "curve": [ + [ + 50000, + 0.05333333333333333 + ], + [ + 100000, + 0.07999999999999999 + ], + [ + 150000, + 0.07999999999999999 + ], + [ + 200000, + 0.10666666666666666 + ], + [ + 250000, + 0.05333333333333333 + ], + [ + 300000, + 0.0 + ], + [ + 300000, + 0.036000000000000004 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 4111.4, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/kl8h1p6n" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..e97bde871ba4f1e8a922e49cb94eed791d740eed --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "scene-play-v0", + "seed": 1, + "actor_loss": "ddpgbc", + "alpha": 0.3, + "expectile": 0.9, + "success_rate": 0.5119999999999999, + "best_sr": 0.5466666666666666, + "per_task": [ + 0.94, + 0.82, + 0.8, + 0.0, + 0.0 + ], + "curve": [ + [ + 50000, + 0.14666666666666667 + ], + [ + 100000, + 0.17333333333333334 + ], + [ + 150000, + 0.32 + ], + [ + 200000, + 0.32 + ], + [ + 250000, + 0.5066666666666666 + ], + [ + 300000, + 0.4533333333333333 + ], + [ + 350000, + 0.4533333333333333 + ], + [ + 400000, + 0.5066666666666666 + ], + [ + 450000, + 0.43999999999999995 + ], + [ + 500000, + 0.5466666666666666 + ], + [ + 500000, + 0.5119999999999999 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 4772.0, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/ad0afjhd" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..d9874ae057f3ff3aca7d104e1576971a35c7a9ea --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq.json @@ -0,0 +1,55 @@ +{ + "method": "gciql_genq", + "env": "scene-play-v0", + "seed": 1, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 1.0, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_scene_play_v0.genqjax.npz", + "success_rate": 0.32, + "best_sr": 0.52, + "per_task": [ + 0.8, + 0.36, + 0.26, + 0.16, + 0.02 + ], + "curve": [ + [ + 50000, + 0.3866666666666666 + ], + [ + 100000, + 0.52 + ], + [ + 150000, + 0.30666666666666664 + ], + [ + 200000, + 0.4666666666666667 + ], + [ + 250000, + 0.29333333333333333 + ], + [ + 300000, + 0.3866666666666666 + ], + [ + 300000, + 0.32 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 15755.7, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/ulwawctv" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..58b7e3c184564822312c627736db684376f0f69f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b09.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "scene-play-v0", + "seed": 1, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.20098666846752167, + "genq_npz": "m9_genq_rec_scene_play_v0_b09.genqjax.npz", + "success_rate": 0.22800000000000004, + "best_sr": 0.27999999999999997, + "per_task": [ + 0.72, + 0.14, + 0.14, + 0.12, + 0.02 + ], + "curve": [ + [ + 50000, + 0.14666666666666667 + ], + [ + 100000, + 0.10666666666666666 + ], + [ + 150000, + 0.27999999999999997 + ], + [ + 200000, + 0.2 + ], + [ + 250000, + 0.18666666666666668 + ], + [ + 300000, + 0.2 + ], + [ + 300000, + 0.22800000000000004 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19957.2, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/dtb1gtw8" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..785db376236e78bbb5129355b59d0e572efd72fa --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "scene-play-v0", + "seed": 1, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.20082485675811768, + "genq_npz": "m9_genq_rec_scene_play_v0_b095.genqjax.npz", + "success_rate": 0.18, + "best_sr": 0.2533333333333333, + "per_task": [ + 0.58, + 0.2, + 0.1, + 0.0, + 0.02 + ], + "curve": [ + [ + 50000, + 0.17333333333333334 + ], + [ + 100000, + 0.24 + ], + [ + 150000, + 0.21333333333333332 + ], + [ + 200000, + 0.2 + ], + [ + 250000, + 0.2533333333333333 + ], + [ + 300000, + 0.16 + ], + [ + 300000, + 0.18 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19754.3, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/buw86kga" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/1/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gcbc.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gcbc.json new file mode 100644 index 0000000000000000000000000000000000000000..01634bcb89fb2813822f3351e7a8a72c8caf712d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gcbc.json @@ -0,0 +1,47 @@ +{ + "method": "gcbc", + "env": "scene-play-v0", + "seed": 2, + "success_rate": 0.048, + "best_sr": 0.2, + "per_task": [ + 0.16, + 0.02, + 0.0, + 0.06, + 0.0 + ], + "curve": [ + [ + 50000, + 0.15999999999999998 + ], + [ + 100000, + 0.2 + ], + [ + 150000, + 0.09333333333333334 + ], + [ + 200000, + 0.026666666666666665 + ], + [ + 250000, + 0.09333333333333334 + ], + [ + 300000, + 0.05333333333333333 + ], + [ + 300000, + 0.048 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 4186.1, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/qpt54qbq" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql.json new file mode 100644 index 0000000000000000000000000000000000000000..d4e6a1a9d53cfdc32b25125b05e22e612d8b8ae4 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql.json @@ -0,0 +1,66 @@ +{ + "method": "gciql", + "env": "scene-play-v0", + "seed": 2, + "actor_loss": "ddpgbc", + "alpha": 0.3, + "expectile": 0.9, + "success_rate": 0.476, + "best_sr": 0.6000000000000001, + "per_task": [ + 0.86, + 0.86, + 0.6, + 0.06, + 0.0 + ], + "curve": [ + [ + 50000, + 0.16 + ], + [ + 100000, + 0.21333333333333332 + ], + [ + 150000, + 0.22666666666666666 + ], + [ + 200000, + 0.3466666666666667 + ], + [ + 250000, + 0.39999999999999997 + ], + [ + 300000, + 0.4666666666666667 + ], + [ + 350000, + 0.4666666666666667 + ], + [ + 400000, + 0.6000000000000001 + ], + [ + 450000, + 0.52 + ], + [ + 500000, + 0.4666666666666667 + ], + [ + 500000, + 0.476 + ] + ], + "train_steps": 500000, + "wall_clock_sec": 4867.6, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/si7m0phu" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq.json new file mode 100644 index 0000000000000000000000000000000000000000..08d7e3c6e34ce5ba1be1eb5262a6f86922b1a149 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq.json @@ -0,0 +1,55 @@ +{ + "method": "gciql_genq", + "env": "scene-play-v0", + "seed": 2, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 64, + "sigma": 1.0, + "ensemble": true, + "latent": false, + "genq_npz": "m9_genq_scene_play_v0.genqjax.npz", + "success_rate": 0.28800000000000003, + "best_sr": 0.5466666666666666, + "per_task": [ + 0.78, + 0.34, + 0.3, + 0.02, + 0.0 + ], + "curve": [ + [ + 50000, + 0.3466666666666667 + ], + [ + 100000, + 0.4400000000000001 + ], + [ + 150000, + 0.42666666666666664 + ], + [ + 200000, + 0.5466666666666666 + ], + [ + 250000, + 0.31999999999999995 + ], + [ + 300000, + 0.24 + ], + [ + 300000, + 0.28800000000000003 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 14377.7, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/eywbkoze" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b09.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b09.json new file mode 100644 index 0000000000000000000000000000000000000000..bff705d3a1cdbf0d9b4654d5c805c0c4cee70566 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b09.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "scene-play-v0", + "seed": 2, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.9, + "gamma": 0.99, + "stop_prob": 0.09090909090909101, + "max_depth": 33, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.19500157237052917, + "genq_npz": "m9_genq_rec_scene_play_v0_b09.genqjax.npz", + "success_rate": 0.176, + "best_sr": 0.38666666666666666, + "per_task": [ + 0.48, + 0.2, + 0.08, + 0.08, + 0.04 + ], + "curve": [ + [ + 50000, + 0.2 + ], + [ + 100000, + 0.38666666666666666 + ], + [ + 150000, + 0.16 + ], + [ + 200000, + 0.24 + ], + [ + 250000, + 0.26666666666666666 + ], + [ + 300000, + 0.21333333333333332 + ], + [ + 300000, + 0.176 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19854.2, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/bmrhyd34" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b09.json.done b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b09.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b095.json b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b095.json new file mode 100644 index 0000000000000000000000000000000000000000..28d5a7171dcb0d73bb86703ad57e64273518daa8 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b095.json @@ -0,0 +1,59 @@ +{ + "method": "gciql_genq_rec", + "env": "scene-play-v0", + "seed": 2, + "actor_loss": "awr", + "alpha": 30.0, + "expectile": 0.9, + "n_occ": 16, + "sigma": 0.5, + "beta": 0.95, + "gamma": 0.99, + "stop_prob": 0.1919191919191919, + "max_depth": 16, + "steps_per_jump": 10, + "midpoint_bc_loss": 0.19712629914283752, + "genq_npz": "m9_genq_rec_scene_play_v0_b095.genqjax.npz", + "success_rate": 0.196, + "best_sr": 0.31999999999999995, + "per_task": [ + 0.56, + 0.1, + 0.18, + 0.12, + 0.02 + ], + "curve": [ + [ + 50000, + 0.26666666666666666 + ], + [ + 100000, + 0.30666666666666664 + ], + [ + 150000, + 0.31999999999999995 + ], + [ + 200000, + 0.26666666666666666 + ], + [ + 250000, + 0.27999999999999997 + ], + [ + 300000, + 0.2 + ], + [ + 300000, + 0.196 + ] + ], + "train_steps": 300000, + "wall_clock_sec": 19610.4, + "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/aczhi86p" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b095.json.done b/gen_q_rsm/ogbench_genq/experiments/scene-play-v0/results/2/gciql_genq_rec_b095.json.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/experiments/screen_visual_index_readers.sh b/gen_q_rsm/ogbench_genq/experiments/screen_visual_index_readers.sh new file mode 100644 index 0000000000000000000000000000000000000000..a42ff8b5c8e25573e977d603a6aaf97eb2f95abd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/screen_visual_index_readers.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Diagnose whether the current goal-return read-out double-discounts an already +# discounted visual occupancy. Training uses only frozen pixels-only latents +# and trajectory indices; cube coordinates are read by the existing trainer +# solely for its post-hoc diagnostic printout. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}_stateh256.npz +OCC=ckpt/rsm_${BASE}_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0.pkl +OUTDIR=ogbench_genq/experiments/visual-cube-single-play-v0 + +for delta in 0 2 8; do + reader=ckpt/rdec_${BASE}_indexd${delta}.npz + audit=$OUTDIR/occupancy_flow_stateh256_full_indexd${delta}_audit.json + if [ ! -s "$reader" ]; then + "$PY" -u ogbench_genq/genq/train_reward_decoder.py \ + --latents "$LAT" --out "$reader" \ + --target index --index_delta "$delta" --neg_gap 64 \ + --cross_neg_frac 0.5 --features symmetric --activation relu \ + --steps 20000 --batch 4096 --lr 1e-3 --seed 0 + fi + "$PY" -u ogbench_genq/genq/diagnose_visual_occupancy.py \ + --ckpt "$OCC" --latents "$LAT" --reward_decoder "$reader" \ + --out "$audit" --rows 256 --samples 32 --episodes 100 +done diff --git a/gen_q_rsm/ogbench_genq/experiments/shz16_metric.sh b/gen_q_rsm/ogbench_genq/experiments/shz16_metric.sh new file mode 100644 index 0000000000000000000000000000000000000000..8e611f7347d45e93cbb0ad0f15b55b32dabaee10 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/shz16_metric.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -uo pipefail +cd /proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +[ -f .env ] && set -a && . ./.env && set +a +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false XLA_PYTHON_CLIENT_MEM_FRACTION=0.5 +PY=.ogbench_venv/bin/python +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_shz16_t4.npz +OUT=ckpt/visual_cube_single_shz16t4_latents.npz +echo "[shz16] precompute latents (R2=0.77 fair encoder)" +$PY ogbench_genq/genq/precompute_pixel_latents.py --env visual-cube-single-play-v0 \ + --encoder "$ENC" --out "$OUT" 2>&1 | tail -3 +echo "[shz16] coordinate-free metric test on the R2=0.77 latent:" +$PY ogbench_genq/genq/learn_metric_coordfree.py "$OUT" 2>&1 | grep -vE "warn|libEGL|dri2|DISPLAY" | grep -E "spearman|infonce|metric" diff --git a/gen_q_rsm/ogbench_genq/experiments/smoke_fair_px_awr.sh b/gen_q_rsm/ogbench_genq/experiments/smoke_fair_px_awr.sh new file mode 100644 index 0000000000000000000000000000000000000000..80ccd24b330c9f208b6ccd97652ac7252c3cc86b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/smoke_fair_px_awr.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Fast render-free execution smoke for the strictly pixels-only classifier/AWR path. +# Reuses coordinate-free encoder/decoder artifacts only to test code; it does +# not reuse the ineligible proprioceptive occupancy checkpoint. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.5 +export MUJOCO_GL=egl +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +"$PY" -u ogbench_genq/rsm.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$REC/ckpt/visual_cube_single_recononly_latents.npz" \ + --pixel_encoder "$REC/ckpt/pixel_enc_visual_cube_single_play_v0_recononly.npz" \ + --reward_decoder ckpt/rdec_recon_index.npz --rdec_samples 2 \ + --drop_proprio --actor_loss awr --alpha 30 --expectile 0.7 --actor_after 50 \ + --recursion off --batch_size 64 --occ_batch 64 \ + --train_steps 100 --eval_interval 1000 \ + --eval_episodes 1 --eval_episodes_periodic 1 \ + --train_only \ + --ckpt ckpt/rsm_fair_px_awr_codesmoke.pkl --ckpt_every 100 \ + --variant_tag fair_px_awr_codesmoke --wandb_mode disabled diff --git a/gen_q_rsm/ogbench_genq/experiments/smoke_merged_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/smoke_merged_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed4d25e35c810b5ab853cdb218c91eee979213d3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/smoke_merged_rsm.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Post-merge smoke: does the combined (#63 state + #74 visual) rsm.py actually +# TRAIN on both goal spaces without crashing, and does the visual-recursion +# equivalence test still pass? A few hundred steps each — occ_loss finite, actor +# steps, eval + ckpt paths exercised. NOT a quality run. +set -uo pipefail +cd /proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-ogbench-matrix +[ -f .env ] && set -a && . ./.env && set +a +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false XLA_PYTHON_CLIENT_MEM_FRACTION=0.4 +export WANDB_MODE=disabled +PY=.ogbench_venv/bin/python +rc=0 + +echo "===== SMOKE 1/3: discrete (puzzle-3x3, gl read-out, off guard) =====" +$PY ogbench_genq/rsm.py --env puzzle-3x3-play-v0 --seed 0 \ + --train_steps 300 --eval_interval 300 --wandb_mode disabled 2>&1 \ + | grep -iE "step 300|occ/|occ_loss|Traceback|Error|nan" | tail -5 +[ ${PIPESTATUS[0]} -eq 0 ] && echo " [discrete] EXIT OK" || { echo " [discrete] FAILED"; rc=1; } + +echo "===== SMOKE 2/3: continuous (pointmaze-medium, ELBO read-out, tails guard) =====" +$PY ogbench_genq/rsm.py --env pointmaze-medium-navigate-v0 --seed 0 \ + --train_steps 300 --eval_interval 300 --wandb_mode disabled 2>&1 \ + | grep -iE "step 300|occ/|occ_loss|Traceback|Error|nan" | tail -5 +[ ${PIPESTATUS[0]} -eq 0 ] && echo " [continuous] EXIT OK" || { echo " [continuous] FAILED"; rc=1; } + +echo "===== SMOKE 3b: continuous + collaborator ELBO levers (main's --elbo_logspace/antithetic) =====" +$PY ogbench_genq/rsm.py --env pointmaze-medium-navigate-v0 --seed 0 \ + --train_steps 300 --eval_interval 300 --elbo_logspace --elbo_antithetic \ + --wandb_mode disabled 2>&1 \ + | grep -iE "step 300|occ_loss|Traceback|Error|nan" | tail -3 +[ ${PIPESTATUS[0]} -eq 0 ] && echo " [elbo-levers] EXIT OK" || { echo " [elbo-levers] FAILED"; rc=1; } + +echo "===== SMOKE 3/3: visual-recursion equivalence test =====" +$PY ogbench_genq/test_visual_recursion_equivalence.py 2>&1 | tail -8 +[ ${PIPESTATUS[0]} -eq 0 ] && echo " [equivalence] PASS" || { echo " [equivalence] FAIL"; rc=1; } + +echo "===== SMOKE RESULT: $([ $rc -eq 0 ] && echo ALL-PASS || echo FAILED) (rc=$rc) =====" +exit $rc diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_eval_fair_px_awr.sh b/gen_q_rsm/ogbench_genq/experiments/submit_eval_fair_px_awr.sh new file mode 100644 index 0000000000000000000000000000000000000000..e79f46183c3fbeaffe532ad8f1945295f6159ded --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_eval_fair_px_awr.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Submit a visual AWR evaluation to hosts with recently verified MuJoCo EGL. +# Usage: +# bash ogbench_genq/experiments/submit_eval_fair_px_awr.sh smoke +# bash ogbench_genq/experiments/submit_eval_fair_px_awr.sh full +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$CF" +mkdir -p bsub_out + +MODE=${1:-full} +case "$MODE" in + smoke) + JOB=fair_px_awr_eval_smoke + SCRIPT=ogbench_genq/experiments/eval_fair_px_awr_smoke.sh + ;; + full) + JOB=fair_px_awr_eval + SCRIPT=ogbench_genq/experiments/eval_fair_px_awr.sh + ;; + *) + echo "usage: $0 {smoke|full}" >&2 + exit 2 + ;; +esac + +# p1-r20-n4 is intentionally excluded: job 378203 trained successfully there +# but aborted at the first rollout on 2026-07-25. +GOOD_NODES="${GOOD_NODES:-p5-r05-n3 p6-r06-n3 p5-r06-n4 p1-r14-n3 p4-r25-n2 p1-r14-n2}" +bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared" \ + -m "$GOOD_NODES" \ + -n 1 -J "$JOB" \ + -o "./bsub_out/${JOB}.%J.out" \ + -e "./bsub_out/${JOB}.%J.err" \ + bash "$SCRIPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_fair_px_awr.sh b/gen_q_rsm/ogbench_genq/experiments/submit_fair_px_awr.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab1e322bf4e604421e5dc7708b53bfb61910dddd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_fair_px_awr.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# Submit the strictly pixels-only visual-cube retraining pipeline. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$CF" +mkdir -p bsub_out + +# Training never constructs the visual renderer, so it can use any scheduler +# host. The full-state checkpoint makes the long fit safe to preempt and resume. +bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -n 1 -J fair_px_awr \ + -o "./bsub_out/fair_px_awr.%J.out" \ + -e "./bsub_out/fair_px_awr.%J.err" \ + bash ogbench_genq/experiments/pack_fair_px_awr.sh diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_gciql_goal_latent_screen.sh b/gen_q_rsm/ogbench_genq/experiments/submit_gciql_goal_latent_screen.sh new file mode 100644 index 0000000000000000000000000000000000000000..49e77df09c62b9b66a84e10c403e973a9ac7bef0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_gciql_goal_latent_screen.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Submit the sequential GCIQL-matched latent screen on one preemptable GPU. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$CF" +mkdir -p bsub_out + +bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -n 1 -J gciql_goal_latent \ + -o "./bsub_out/gciql_goal_latent.%J.out" \ + -e "./bsub_out/gciql_goal_latent.%J.err" \ + bash ogbench_genq/experiments/gciql_goal_latent_screen.sh diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_gciql_goal_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/submit_gciql_goal_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..1585c300992a34efae1db3c360a7bf4b12c5d217 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_gciql_goal_rsm.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Submit shared preparation followed by frozen and joint RSM training arms. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$CF" +mkdir -p bsub_out + +if [ "$#" -ne 1 ]; then + echo "usage: $0 ENCODER_TAG" >&2 + exit 2 +fi + +ENC_TAG=$1 +SAFE_TAG=${ENC_TAG//[^A-Za-z0-9_-]/_} +PREP_JOB=gciql_rsm_prep_${SAFE_TAG} + +PREP_SUB=$(bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -n 1 -J "$PREP_JOB" \ + -o "./bsub_out/${PREP_JOB}.%J.out" \ + -e "./bsub_out/${PREP_JOB}.%J.err" \ + bash ogbench_genq/experiments/prepare_gciql_goal_rsm.sh "$ENC_TAG" 2>&1) +echo "$PREP_SUB" +PREP_ID=$(printf '%s\n' "$PREP_SUB" | sed -n 's/Job <\\([0-9][0-9]*\\)>.*/\\1/p') +[ -n "$PREP_ID" ] || { + echo "could not parse preparation job id" >&2 + exit 1 +} + +for MODE in frozen joint; do + JOB=gciql_rsm_${MODE}_${SAFE_TAG} + bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -n 1 -J "$JOB" -w "done($PREP_ID)" \ + -o "./bsub_out/${JOB}.%J.out" \ + -e "./bsub_out/${JOB}.%J.err" \ + bash ogbench_genq/experiments/train_gciql_goal_rsm.sh "$MODE" "$ENC_TAG" +done diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_fair_px_awr.sh b/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_fair_px_awr.sh new file mode 100644 index 0000000000000000000000000000000000000000..5fbc972d9b104c06940b55cbb00e0dfffb300893 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_fair_px_awr.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# Submit training or official evaluation for one screened goal-prediction encoder. +# +# Usage: +# bash ogbench_genq/experiments/submit_goalpred_fair_px_awr.sh train gpred_idx_z8_w003 +# bash ogbench_genq/experiments/submit_goalpred_fair_px_awr.sh eval gpred_idx_z8_w003 +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$CF" +mkdir -p bsub_out + +if [ "$#" -ne 2 ]; then + echo "usage: $0 {train|eval} ENCODER_TAG" >&2 + exit 2 +fi + +MODE=$1 +ENC_TAG=$2 +SAFE_TAG=${ENC_TAG//[^A-Za-z0-9_-]/_} + +case "$MODE" in + train) + JOB=gp_px_awr_${SAFE_TAG} + bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -n 1 -J "$JOB" \ + -o "./bsub_out/${JOB}.%J.out" \ + -e "./bsub_out/${JOB}.%J.err" \ + bash ogbench_genq/experiments/pack_goalpred_fair_px_awr.sh "$ENC_TAG" + ;; + eval) + JOB=gp_px_eval_${SAFE_TAG} + # p1-r20-n4 is excluded after its process-level EGL abort in job 378203. + GOOD_NODES="${GOOD_NODES:-p5-r05-n3 p6-r06-n3 p5-r06-n4 p1-r14-n3 p4-r25-n2 p1-r14-n2}" + bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared" \ + -m "$GOOD_NODES" \ + -n 1 -J "$JOB" \ + -o "./bsub_out/${JOB}.%J.out" \ + -e "./bsub_out/${JOB}.%J.err" \ + bash ogbench_genq/experiments/eval_goalpred_fair_px_awr.sh "$ENC_TAG" + ;; + *) + echo "usage: $0 {train|eval} ENCODER_TAG" >&2 + exit 2 + ;; +esac diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_index_encoder.sh b/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_index_encoder.sh new file mode 100644 index 0000000000000000000000000000000000000000..c7391a84673189f442c806772a8b605e32b01d9b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_index_encoder.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# Submit one audited pixels-only goal-proximity encoder fit. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$CF" +mkdir -p bsub_out + +if [ "$#" -lt 5 ] || [ "$#" -gt 6 ]; then + echo "usage: $0 TAG Z_DIM HIDDEN CHANNELS GOAL_WEIGHT [TRAIN_STEPS]" >&2 + exit 2 +fi + +TAG=$1 +SAFE_TAG=${TAG//[^A-Za-z0-9_-]/_} + +bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -n 1 -J "gp_enc_${SAFE_TAG}" \ + -o "./bsub_out/gp_enc_${SAFE_TAG}.%J.out" \ + -e "./bsub_out/gp_enc_${SAFE_TAG}.%J.err" \ + bash ogbench_genq/experiments/train_goalpred_index_encoder.sh "$@" diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_index_screen.sh b/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_index_screen.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec1b4285ecfd3da97083a180e0ac5e765f69bcd5 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_goalpred_index_screen.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# Submit the renderer-free pixels-only goal-prediction encoder screen. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$CF" +mkdir -p bsub_out + +bsub -q preemptable -G grp_preemptable \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -n 1 -J goalpred_idx_screen \ + -o "./bsub_out/goalpred_idx_screen.%J.out" \ + -e "./bsub_out/goalpred_idx_screen.%J.err" \ + bash ogbench_genq/experiments/goalpred_index_screen.sh diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_valrew_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/submit_valrew_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..de746854d52c8bb8bca2248884124ea1a8f9b702 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_valrew_rsm.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# Submit the value_reward RSM pack (precompute + 2 RSM arms) to ONE shared GPU. +# RSM evals render the visual env (EGL) -> exclude known bad render nodes. +# Usage: submit_valrew_rsm.sh [full|smoke] [queue] +set -euo pipefail +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$CF" +TAG=${1:?usage: submit_valrew_rsm.sh [full|smoke] [queue]} +MODE=${2:-full} +Q=${3:-normal} +if [ "$Q" = "normal" ]; then G=grp_runtime; else G=grp_preemptable; fi +mkdir -p bsub_out +# RSM eval renders via MuJoCo EGL, which core-dumps on SOME nodes (bad: p2-r28-n4, +# p3-r30-n4, p4-r26-n3, p6-r32-n1). Rather than whack-a-mole exclusions, TARGET the +# known-good render nodes with -m (job runs on the first available good host). +GOOD_NODES="${GOOD_NODES:-p5-r05-n3 p6-r06-n3 p5-r06-n4 p1-r14-n3 p1-r20-n4}" +bsub -q "$Q" -G "$G" \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -m "$GOOD_NODES" \ + -o "./bsub_out/rsm_valrew_${TAG}.%J.out" -e "./bsub_out/rsm_valrew_${TAG}.%J.err" \ + -n 4 -J "rsm_valrew_${TAG}" \ + bash ogbench_genq/experiments/pack_valrew_rsm.sh "$TAG" "$MODE" diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_visual_cube_resume.sh b/gen_q_rsm/ogbench_genq/experiments/submit_visual_cube_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..e29d4643d453e4a3f6425b518d1affcf78c65dbd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_visual_cube_resume.sh @@ -0,0 +1,10 @@ +#!/bin/bash +# Resubmit the visual-cube recursion OFF/ON pack on normal/grp_runtime (non-preemptable), +# with wandb FULLY disabled (WANDB_MODE=disabled — the flaky wandb-core service port-token +# timeout on busy nodes killed job 257833 even though it defaulted to offline; offline still +# spawns the service, disabled does not). Both arms resume from their existing --ckpt pkls +# (recoff ~500k, recon ~175k), so this is a clean continuation, not a restart. +set -uo pipefail +cd /proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +export WANDB_MODE=disabled +exec bash ogbench_genq/experiments/pack_visual_cube_recursion.sh full diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_visual_gcbc_control.sh b/gen_q_rsm/ogbench_genq/experiments/submit_visual_gcbc_control.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff79b01524dd782b8bc82c061997e6d009a347d4 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_visual_gcbc_control.sh @@ -0,0 +1,64 @@ +#!/bin/bash +# Safe preemptable submission wrapper for the pixels-only actor-input control. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +cd "$ROOT" + +DO_SUBMIT=0 +if [ "${1:-}" = "--submit" ]; then + DO_SUBMIT=1 +elif [ "$#" -ne 0 ]; then + echo "usage: $0 [--submit]" >&2 + exit 2 +fi + +PY=${PY:-/proj/inf-scaling/zwhong/projs/gen_q/.ogbench_venv/bin/python} +OUT_DIR=${OUT_DIR:-/proj/inf-scaling/zwhong/visual_gcbc_control_s0} +LOG_DIR=${LOG_DIR:-bsub_out/visual_gcbc_control} +JOB=${JOB:-visual_gcbc_control} +QUEUE=${QUEUE:-preemptable} +USER_GROUP=${USER_GROUP:-grp_preemptable} +TRAIN_STEPS=${TRAIN_STEPS:-300000} + +[ "$QUEUE:$USER_GROUP" = preemptable:grp_preemptable ] || { + echo "[visual-gcbc-submit] pinned to preemptable/grp_preemptable" >&2 + exit 2 +} +[ "$TRAIN_STEPS" = 300000 ] || { + echo "[visual-gcbc-submit] exact control requires 300000 steps" >&2 + exit 2 +} + +CMD=( + bsub + -q "$QUEUE" + -G "$USER_GROUP" + -J "$JOB" + -gpu "num=1:mode=shared:j_exclusive=yes" + -n 8 + -R "span[hosts=1]" + -o "$LOG_DIR/${JOB}.%J.out" + -e "$LOG_DIR/${JOB}.%J.err" + env + XLA_PYTHON_CLIENT_PREALLOCATE=false + XLA_PYTHON_CLIENT_MEM_FRACTION=0.90 + WANDB_MODE=disabled + "$PY" -u ogbench_genq/genq/train_visual_gcbc_control.py + --output_dir "$OUT_DIR" + --train_steps "$TRAIN_STEPS" + --seed 0 + --resume auto + --wandb_mode disabled +) + +printf '[visual-gcbc-submit] command=' +printf ' %q' "${CMD[@]}" +printf '\n' +echo "[visual-gcbc-submit] contract pixels_only=true actor_goal=uniform_future non_td=true reward=false coordinate=false simulator_state=false" +if [ "$DO_SUBMIT" = 1 ]; then + mkdir -p "$LOG_DIR" "$OUT_DIR" + "${CMD[@]}" +else + echo "[visual-gcbc-submit] dry-run only" +fi diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_fair_training.sh b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_fair_training.sh new file mode 100644 index 0000000000000000000000000000000000000000..028b3431d5074fe2988c9168f117f66320121e56 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_fair_training.sh @@ -0,0 +1,102 @@ +#!/bin/bash +# Scheduler wrapper for the packed fair visual RSM training screen. +# +# Safe default: print the exact preemptable bsub command(s). Pass --submit to +# mutate scheduler state. "all" means three GPU allocations, each containing +# multiple independently resumable cells. +# +# Usage: +# bash ogbench_genq/experiments/submit_visual_rsm_fair_training.sh \ +# {nonrec-primary|nonrec-secondary|recursion|all} [--submit] +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +cd "$ROOT" + +usage() { + echo "usage: $0 {nonrec-primary|nonrec-secondary|recursion|all} [--submit]" >&2 + exit 2 +} + +REQUEST=${1:-} +case "$REQUEST" in + nonrec-primary|nonrec-secondary|recursion|all) ;; + *) usage ;; +esac +shift + +DO_SUBMIT=0 +while [ "$#" -gt 0 ]; do + case "$1" in + --submit) DO_SUBMIT=1 ;; + *) usage ;; + esac + shift +done + +PACK_SCRIPT=ogbench_genq/experiments/pack_visual_rsm_fair_training.sh +[ -r "$PACK_SCRIPT" ] || { + echo "[visual-rsm-submit] missing packed launcher: $PACK_SCRIPT" >&2 + exit 1 +} + +QUEUE=${QUEUE:-preemptable} +USER_GROUP=${USER_GROUP:-grp_preemptable} +case "$QUEUE:$USER_GROUP" in + preemptable:grp_preemptable) ;; + *) + echo "[visual-rsm-submit] fair training wrapper is pinned to preemptable/grp_preemptable" >&2 + exit 2 + ;; +esac + +if [ "$REQUEST" = all ]; then + PACKS=(nonrec-primary nonrec-secondary recursion) +else + PACKS=("$REQUEST") +fi + +submit_one() { + local pack=$1 + local job cores + case "$pack" in + nonrec-primary) job=vrsm_nr_primary; cores=${PRIMARY_CORES:-16} ;; + nonrec-secondary) job=vrsm_nr_secondary; cores=${SECONDARY_CORES:-8} ;; + recursion) job=vrsm_recursion; cores=${RECURSION_CORES:-12} ;; + *) return 2 ;; + esac + + local out_dir=bsub_out/visual_rsm_fair/scheduler + local cmd=( + bsub + -q "$QUEUE" + -G "$USER_GROUP" + -J "$job" + # The cells are local background processes, not LSF parallel tasks. Request + # one GPU per host (the LSF default) while reserving enough CPU slots for + # the packed processes. "/task" here would multiply the GPU request by + # "$cores" and make the larger packs impossible to schedule. + -gpu "num=1:mode=shared:j_exclusive=yes" + -n "$cores" + -R "span[hosts=1]" + -o "$out_dir/${job}.%J.out" + -e "$out_dir/${job}.%J.err" + bash "$PACK_SCRIPT" "$pack" + ) + + printf '[visual-rsm-submit] command=' + printf ' %q' "${cmd[@]}" + printf '\n' + if [ "$DO_SUBMIT" = 1 ]; then + mkdir -p "$out_dir" + "${cmd[@]}" + fi +} + +for pack in "${PACKS[@]}"; do + submit_one "$pack" +done + +if [ "$DO_SUBMIT" = 0 ]; then + echo "[visual-rsm-submit] dry-run only; pass --submit to create jobs" +fi diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_occupancy_recipe_ablation.sh b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_occupancy_recipe_ablation.sh new file mode 100644 index 0000000000000000000000000000000000000000..4aa0f9acd891a259c7e66b3fd99ccadb85e900f2 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_occupancy_recipe_ablation.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Dry-run-first preemptable scheduler wrapper for the occupancy recipe ablation. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +cd "$ROOT" + +case "${1:-}" in + "") DO_SUBMIT=0 ;; + --submit) DO_SUBMIT=1 ;; + *) + echo "usage: $0 [--submit]" >&2 + exit 2 + ;; +esac +[ "$#" -le 1 ] || { + echo "usage: $0 [--submit]" >&2 + exit 2 +} + +PACK=ogbench_genq/experiments/pack_visual_rsm_occupancy_recipe_ablation.sh +PACK_DRY_RUN=1 bash "$PACK" --dry-run + +JOB=${JOB:-vrsm_occ_recipe} +OUT_DIR=${OUT_DIR:-bsub_out/visual_rsm_occupancy_recipe/scheduler} +COMMAND=( + bsub + -q preemptable + -G grp_preemptable + -J "$JOB" + -gpu "num=1:mode=shared:j_exclusive=yes" + -n 8 + -R "span[hosts=1]" + -o "$OUT_DIR/${JOB}.%J.out" + -e "$OUT_DIR/${JOB}.%J.err" + env + PACK_DRY_RUN=0 + bash "$PACK" + --execute +) +printf '[visual-rsm-occ-recipe-submit] command=' +printf ' %q' "${COMMAND[@]}" +printf '\n' +if [ "$DO_SUBMIT" = 1 ]; then + mkdir -p "$OUT_DIR" + "${COMMAND[@]}" +else + echo "[visual-rsm-occ-recipe-submit] dry-run only; no submission" +fi diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_onehop_30k_eval.sh b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_onehop_30k_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..a46d11210b6a3da757af87d5ad596e4b4f24b578 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_onehop_30k_eval.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Scheduler-safe wrapper for the non-resumable official 30k RSM rollouts. +set -euo pipefail + +ROOT=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +cd "$ROOT" + +DO_SUBMIT=0 +if [ "${1:-}" = "--submit" ]; then + DO_SUBMIT=1 +elif [ "$#" -ne 0 ]; then + echo "usage: $0 [--submit]" >&2 + exit 2 +fi + +OUT_DIR=bsub_out/visual_rsm_onehop_v2/official_step30000/scheduler +mkdir -p "$OUT_DIR" +CMD=( + bsub + -q preemptable + -G grp_preemptable + -J vrsm_30k_official + -gpu "num=1:mode=shared:j_exclusive=yes" + -n 6 + -R "span[hosts=1]" + -m "p5-r06-n4" + -o "$OUT_DIR/vrsm_30k_official.%J.out" + -e "$OUT_DIR/vrsm_30k_official.%J.err" + bash ogbench_genq/experiments/pack_visual_rsm_onehop_30k_eval.sh +) +printf '[visual-rsm-30k-submit] command=' +printf ' %q' "${CMD[@]}" +printf '\n' +if [ "$DO_SUBMIT" = 1 ]; then + "${CMD[@]}" +else + echo "[visual-rsm-30k-submit] dry-run only; target host p5-r06-n4 passed fresh EGL jobs 419013 and 420976" +fi diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_onehop_v2.sh b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_onehop_v2.sh new file mode 100644 index 0000000000000000000000000000000000000000..2734552fc9e2c1d7540619869ab9d4a5de7c5eeb --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_onehop_v2.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# Safe scheduler wrapper for the compact one-hop visual RSM v2 screen. +# The default is a dry run; --submit is the only scheduler-mutating path. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +cd "$ROOT" + +usage() { + echo "usage: $0 [--submit]" >&2 + exit 2 +} + +DO_SUBMIT=0 +while [ "$#" -gt 0 ]; do + case "$1" in + --submit) DO_SUBMIT=1 ;; + *) usage ;; + esac + shift +done + +PACK_SCRIPT=ogbench_genq/experiments/pack_visual_rsm_onehop_v2.sh +[ -r "$PACK_SCRIPT" ] || { + echo "[visual-rsm-onehop-v2-submit] missing packed launcher: $PACK_SCRIPT" >&2 + exit 1 +} + +QUEUE=${QUEUE:-preemptable} +USER_GROUP=${USER_GROUP:-grp_preemptable} +[ "$QUEUE:$USER_GROUP" = preemptable:grp_preemptable ] || { + echo "[visual-rsm-onehop-v2-submit] wrapper is pinned to preemptable/grp_preemptable" >&2 + exit 2 +} + +JOB=${JOB:-vrsm_onehop_v2} +CORES=${CORES:-8} +OUT_DIR=${OUT_DIR:-bsub_out/visual_rsm_onehop_v2/scheduler} +CMD=( + bsub + -q "$QUEUE" + -G "$USER_GROUP" + -J "$JOB" + -gpu "num=1:mode=shared:j_exclusive=yes" + -n "$CORES" + -R "span[hosts=1]" + -o "$OUT_DIR/${JOB}.%J.out" + -e "$OUT_DIR/${JOB}.%J.err" + bash "$PACK_SCRIPT" +) + +printf '[visual-rsm-onehop-v2-submit] command=' +printf ' %q' "${CMD[@]}" +printf '\n' +if [ "$DO_SUBMIT" = 1 ]; then + mkdir -p "$OUT_DIR" + "${CMD[@]}" +else + echo "[visual-rsm-onehop-v2-submit] dry-run only; exactly one preemptable GPU allocation; pass --submit to create it" +fi diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_recursion_continuation.sh b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_recursion_continuation.sh new file mode 100644 index 0000000000000000000000000000000000000000..a0ac734ae85492555346a76a314a51994ba60835 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_recursion_continuation.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# Scheduler wrapper for gate-passing visual RSM recursive continuations. +# It validates and dry-runs the exact selected cells before printing a pinned +# preemptable command. Nothing is submitted unless --submit is explicit. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +cd "$ROOT" + +usage() { + echo "usage: CELL_FILTER=cell[,cell...] GATE_DIR=/abs/gates $0 [--submit]" >&2 + exit 2 +} + +DO_SUBMIT=0 +while [ "$#" -gt 0 ]; do + case "$1" in + --submit) DO_SUBMIT=1 ;; + *) usage ;; + esac + shift +done + +PACK_SCRIPT=ogbench_genq/experiments/pack_visual_rsm_recursion_continuation.sh +[ -r "$PACK_SCRIPT" ] || { + echo "[visual-rsm-rec-cont-submit] missing pack script: $PACK_SCRIPT" >&2 + exit 1 +} + +# This is a real provenance preflight, not merely a static command preview. +# It fails before bsub construction if any selected cell lacks a passing, +# cell-matched gate or immutable source checkpoint. +PACK_DRY_RUN=1 bash "$PACK_SCRIPT" --dry-run + +QUEUE=${QUEUE:-preemptable} +USER_GROUP=${USER_GROUP:-grp_preemptable} +[ "$QUEUE:$USER_GROUP" = preemptable:grp_preemptable ] || { + echo "[visual-rsm-rec-cont-submit] wrapper is pinned to preemptable/grp_preemptable" >&2 + exit 2 +} + +JOB=${JOB:-vrsm_gate_cont100k} +case "$JOB" in + *[!A-Za-z0-9._-]*|'') + echo "[visual-rsm-rec-cont-submit] JOB contains unsafe characters" >&2 + exit 2 + ;; +esac +CORES=${CORES:-12} +OUT_DIR=${OUT_DIR:-bsub_out/visual_rsm_recursion_continuation/scheduler} +CMD=( + bsub + -q "$QUEUE" + -G "$USER_GROUP" + -J "$JOB" + -gpu "num=1:mode=shared:j_exclusive=yes" + -n "$CORES" + -R "span[hosts=1]" + -o "$OUT_DIR/${JOB}.%J.out" + -e "$OUT_DIR/${JOB}.%J.err" + env + "PACK_DRY_RUN=0" + "CELL_FILTER=$CELL_FILTER" + "GATE_DIR=$GATE_DIR" + bash "$PACK_SCRIPT" +) + +printf '[visual-rsm-rec-cont-submit] command=' +printf ' %q' "${CMD[@]}" +printf '\n' +if [ "$DO_SUBMIT" = 1 ]; then + mkdir -p "$OUT_DIR" + "${CMD[@]}" +else + echo "[visual-rsm-rec-cont-submit] dry-run only; no submission; one preemptable GPU allocation would continue only the explicitly selected gate-passing cells to step 100000" +fi diff --git a/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_recursion_sweep.sh b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_recursion_sweep.sh new file mode 100644 index 0000000000000000000000000000000000000000..29cbb9e05a94c181efc0bfca37e418ab054e6803 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/submit_visual_rsm_recursion_sweep.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# Safe scheduler wrapper for the hidden-state one-hop visual RSM gamma/beta +# calibration. The default is a scheduler-free dry run. This phase stops at +# step 50k while composition remains inactive; a separate continuation will +# require a checkpoint-specific passing gate. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +cd "$ROOT" + +usage() { + echo "usage: $0 [--submit]" >&2 + exit 2 +} + +DO_SUBMIT=0 +while [ "$#" -gt 0 ]; do + case "$1" in + --submit) DO_SUBMIT=1 ;; + *) usage ;; + esac + shift +done + +PACK_SCRIPT=ogbench_genq/experiments/pack_visual_rsm_recursion_sweep.sh +CONTRACT_SOURCE=ogbench_genq/genq/visual_recursion_sweep_contract.py +REC=${REC:-/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion} +PY=${PY:-$REC/.ogbench_venv/bin/python} +for required in "$PACK_SCRIPT" "$CONTRACT_SOURCE"; do + [ -r "$required" ] || { + echo "[visual-rsm-rec-submit] missing required file: $required" >&2 + exit 1 + } +done + +QUEUE=${QUEUE:-preemptable} +USER_GROUP=${USER_GROUP:-grp_preemptable} +[ "$QUEUE:$USER_GROUP" = preemptable:grp_preemptable ] || { + echo "[visual-rsm-rec-submit] wrapper is pinned to preemptable/grp_preemptable" >&2 + exit 2 +} + +JOB=${JOB:-vrsm_h1_gb_cal} +CORES=${CORES:-12} +OUT_DIR=${OUT_DIR:-bsub_out/visual_rsm_recursion_sweep/scheduler} +CMD=( + bsub + -q "$QUEUE" + -G "$USER_GROUP" + -J "$JOB" + -gpu "num=1:mode=shared:j_exclusive=yes" + -n "$CORES" + -R "span[hosts=1]" + -o "$OUT_DIR/${JOB}.%J.out" + -e "$OUT_DIR/${JOB}.%J.err" +) +CMD+=(env PACK_DRY_RUN=0 bash "$PACK_SCRIPT") + +printf '[visual-rsm-rec-submit] command=' +printf ' %q' "${CMD[@]}" +printf '\n' +if [ "$DO_SUBMIT" = 1 ]; then + mkdir -p "$OUT_DIR" + "${CMD[@]}" +else + echo "[visual-rsm-rec-submit] dry-run only; exactly one preemptable GPU allocation; composition remains inactive through the 50k calibration checkpoint" +fi diff --git a/gen_q_rsm/ogbench_genq/experiments/sweep_visual_action_contrast.sh b/gen_q_rsm/ogbench_genq/experiments/sweep_visual_action_contrast.sh new file mode 100644 index 0000000000000000000000000000000000000000..71b36332979c6a6885acd5f497143c0f545c5392 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweep_visual_action_contrast.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Reward-free action-identification screen on the selected flow occupancy. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +TRAIN=ogbench_genq/genq/train_visual_occupancy_sweep.py +LAT=ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret.npz +RDEC=ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz +OUTDIR=ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep +CKDIR=ckpt/visual_occupancy_sweep + +run_arm() { + local tag=$1 + shift + "$PY" -u "$TRAIN" \ + --latents "$LAT" --reward_decoder "$RDEC" \ + --variant "$tag" --out "$OUTDIR/${tag}.json" --ckpt "$CKDIR/${tag}.pkl" \ + --model flow --target absolute --arch mlp --sampler stratified \ + --hidden 256 --layers 4 --steps 50000 --batch 2048 \ + --eval_rows 256 --eval_samples 32 "$@" +} + +run_arm flow_abs_mlp_h256_l4_acshuf_w01 \ + --action_contrast_weight 0.1 --action_negative shuffle +run_arm flow_abs_mlp_h256_l4_acshuf_w05 \ + --action_contrast_weight 0.5 --action_negative shuffle +run_arm flow_abs_mlp_h256_l4_aclocal_w01 \ + --action_contrast_weight 0.1 --action_negative local +run_arm flow_abs_mlp_h256_l4_aclocal_w05 \ + --action_contrast_weight 0.5 --action_negative local diff --git a/gen_q_rsm/ogbench_genq/experiments/sweep_visual_action_contrast_robustness.sh b/gen_q_rsm/ogbench_genq/experiments/sweep_visual_action_contrast_robustness.sh new file mode 100644 index 0000000000000000000000000000000000000000..198bf1106fb3204fdbb734b19078b2356be0081a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweep_visual_action_contrast_robustness.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Robustness screen for the selected local action-contrastive flow recipe: +# two independent data/model seeds and two local-negative radii. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +TRAIN=ogbench_genq/genq/train_visual_occupancy_sweep.py +LAT=ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret.npz +RDEC=ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz +OUTDIR=ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep +CKDIR=ckpt/visual_occupancy_sweep + +run_arm() { + local tag=$1 + shift + "$PY" -u "$TRAIN" \ + --latents "$LAT" --reward_decoder "$RDEC" \ + --variant "$tag" --out "$OUTDIR/${tag}.json" --ckpt "$CKDIR/${tag}.pkl" \ + --model flow --target absolute --arch mlp --sampler stratified \ + --hidden 256 --layers 4 --steps 50000 --batch 2048 \ + --eval_rows 256 --eval_samples 32 \ + --action_contrast_weight 0.5 --action_negative local "$@" +} + +run_arm flow_abs_mlp_h256_l4_aclocal_w05_s1 --seed 1 +run_arm flow_abs_mlp_h256_l4_aclocal_w05_s2 --seed 2 +run_arm flow_abs_mlp_h256_l4_aclocal_w05_sigma01 \ + --seed 0 --action_negative_sigma 0.1 +run_arm flow_abs_mlp_h256_l4_aclocal_w05_sigma06 \ + --seed 0 --action_negative_sigma 0.6 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweep_visual_horizon_priority.sh b/gen_q_rsm/ogbench_genq/experiments/sweep_visual_horizon_priority.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd23979fc6ada6c1918eff7cef3a66a491d6df7a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweep_visual_horizon_priority.sh @@ -0,0 +1,101 @@ +#!/bin/bash +# Fair pixels-only discount-prioritization screen for visual RSM occupancy. +# +# One preemptable H100 runs five small flow-matching cells concurrently. Every +# cell uses the same rich frozen pixel state, compact future/goal latent, +# explicit discount encoding, and reward-free local action-contrast loss. +# There is no actor, TD/bootstrap target, coordinate/proprio input, or reward +# label in occupancy training. Readers are loaded only for held-out evaluation. +set -euo pipefail + +WT=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$WT" + +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.18 +export PYTHONUNBUFFERED=1 +export WANDB_MODE=disabled + +PY=$REC/.ogbench_venv/bin/python +TRAIN=ogbench_genq/genq/train_visual_occupancy_sweep.py +LAT=ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz +INDEX_RDEC=ckpt/rdec_fair_px_gpred_gciql_z8_w003_index_d8_symrelu_s0.npz +RETURN_RDEC=ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz +OUTDIR=ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority +CKDIR=ckpt/visual_occupancy_horizon_priority +mkdir -p "$OUTDIR" "$CKDIR" + +for artifact in "$LAT" "$RETURN_RDEC"; do + [ -f "$artifact" ] || { + echo "[horizon-priority] missing artifact: $artifact" >&2 + exit 1 + } +done + +# Immediate at-goal/index reader on the exact same frozen z used as the +# occupancy target. The older GCIQL-return reader is retained only as a +# diagnostic because integrating it over occupancy double-counts horizon. +if [ ! -s "$INDEX_RDEC" ]; then + "$PY" -u ogbench_genq/genq/train_reward_decoder.py \ + --latents "$LAT" --out "$INDEX_RDEC" \ + --target index --index_delta 8 --neg_gap 64 --cross_neg_frac 0.5 \ + --features symmetric --activation relu --steps 20000 --seed 0 +fi + +run_arm() { + local tag=$1 + shift + local out=$OUTDIR/${tag}.json + local ck=$CKDIR/${tag}.pkl + if [ -s "$out" ] && [ -s "$ck" ]; then + echo "[horizon-priority] skip complete $tag" + return + fi + echo "[horizon-priority] start $tag" + "$PY" -u "$TRAIN" \ + --latents "$LAT" \ + --reward_decoder "$INDEX_RDEC" --require_index_reader \ + --diagnostic_reward_decoder "$RETURN_RDEC" \ + --variant "$tag" --out "$out" --ckpt "$ck" \ + --state_key state_h \ + --model flow --target absolute --arch mlp --sampler stratified \ + --hidden 256 --layers 4 --steps 50000 --batch 2048 \ + --eval_rows 128 --eval_samples 16 --sample_steps 25 \ + --action_contrast_weight 0.5 --action_contrast_margin 0.1 \ + --action_negative local --action_negative_sigma 0.3 \ + --gamma_horizons 2,4,8,16,32,64 \ + --gamma_eval_horizons 2,4,8,16,32,64,100 \ + --seed 0 "$@" + echo "[horizon-priority] done $tag" +} + +# Same architecture/data/optimization; only the training-discount proposal +# differs. All spectra reserve exactly half of each batch for task gamma=0.99. +run_arm stateh_ac_gfixed \ + --gamma_sampler fixed & +p1=$! +run_arm stateh_ac_glegacy_logh10_100 \ + --gamma_sampler legacy_log_uniform --spectrum_lo 0.90 \ + --gamma_task_fraction 0.5 & +p2=$! +run_arm stateh_ac_gstrat_h2_64 \ + --gamma_sampler stratified_bins --gamma_task_fraction 0.5 & +p3=$! +run_arm stateh_ac_gshortiw_h2_64 \ + --gamma_sampler short_iw --gamma_task_fraction 0.5 \ + --short_priority_power 1.0 & +p4=$! +run_arm stateh_ac_gactionprio_h2_64 \ + --gamma_sampler action_priority --gamma_task_fraction 0.5 & +p5=$! + +status=0 +for pid in "$p1" "$p2" "$p3" "$p4" "$p5"; do + wait "$pid" || status=1 +done +if [ "$status" -ne 0 ]; then + echo "[horizon-priority] at least one arm failed" >&2 + exit "$status" +fi +echo "[horizon-priority] all arms complete" diff --git a/gen_q_rsm/ogbench_genq/experiments/sweep_visual_occupancy.sh b/gen_q_rsm/ogbench_genq/experiments/sweep_visual_occupancy.sh new file mode 100644 index 0000000000000000000000000000000000000000..60198271495f7a90d8829f9c67d070d140618bbc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweep_visual_occupancy.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# One-GPU, sequential occupancy-only screen with an episode-held-out audit. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +TRAIN=ogbench_genq/genq/train_visual_occupancy_sweep.py +LAT=ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret.npz +RDEC=ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz +OUTDIR=ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep +CKDIR=ckpt/visual_occupancy_sweep +mkdir -p "$OUTDIR" "$CKDIR" + +run_arm() { + local tag=$1 + shift + local out=$OUTDIR/${tag}.json + local ck=$CKDIR/${tag}.pkl + if [ -s "$out" ] && [ -s "$ck" ]; then + echo "[occ-sweep] skip complete $tag" + return + fi + echo "[occ-sweep] start $tag" + "$PY" -u "$TRAIN" \ + --latents "$LAT" --reward_decoder "$RDEC" \ + --variant "$tag" --out "$out" --ckpt "$ck" \ + --steps 50000 --batch 2048 --eval_rows 256 --eval_samples 32 \ + "$@" + echo "[occ-sweep] done $tag" +} + +# Controlled architecture/target comparisons. +run_arm diff_abs_mlp_h256_l3 \ + --model diffusion --target absolute --arch mlp --sampler stratified \ + --hidden 256 --layers 3 +run_arm diff_delta_mlp_h256_l3 \ + --model diffusion --target delta --arch mlp --sampler stratified \ + --hidden 256 --layers 3 +run_arm flow_abs_mlp_h256_l4 \ + --model flow --target absolute --arch mlp --sampler stratified \ + --hidden 256 --layers 4 +run_arm flow_delta_mlp_h256_l4 \ + --model flow --target delta --arch mlp --sampler stratified \ + --hidden 256 --layers 4 + +# Conditioning and horizon-recipe comparisons. +run_arm flow_delta_res_h256_l4 \ + --model flow --target delta --arch residual --sampler stratified \ + --hidden 256 --layers 4 +run_arm flow_delta_res_h256_l4_spec90 \ + --model flow --target delta --arch residual --sampler stratified \ + --spectrum_lo 0.90 --hidden 256 --layers 4 +run_arm flow_delta_res_h512_l4_spec90 \ + --model flow --target delta --arch residual --sampler stratified \ + --spectrum_lo 0.90 --hidden 512 --layers 4 +run_arm flow_delta_res_h256_l4_spec90_direct \ + --model flow --target delta --arch residual --sampler direct \ + --spectrum_lo 0.90 --hidden 256 --layers 4 + +echo "[occ-sweep] all arms complete" diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_humanoidmaze.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_humanoidmaze.txt new file mode 100644 index 0000000000000000000000000000000000000000..2bb7f10360989f01308ce0d1a09b42306756e58b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_humanoidmaze.txt @@ -0,0 +1,11 @@ +# issue #61 — humanoidmaze-medium-navigate below bar (RSM 0.184 vs official GCIQL 0.27). +# HYPOTHESIS: the horizon is the lever. Official GCIQL uses discount 0.995 for +# humanoidmaze; rsm.py hardcoded GAMMA=0.99 (now a --gamma flag, equivalence-gated). +# The existing S2b a1 arm IS the gamma=0.99/alpha=1 baseline (~0.18) — not repeated here. +# These three arms isolate gamma (0.995 vs the 0.99 control) and alpha (1 vs 3). +# a1_g995 : gamma=0.995, alpha=1 — the gamma hypothesis at the TD-rule alpha (TD 0.1 -> RSM ~1) +# a3_g995 : gamma=0.995, alpha=3 — gamma hypothesis, one alpha notch up +# a3_g99 : gamma=0.99, alpha=3 — the gamma CONTROL (isolates alpha at the old horizon) +humanoidmaze-medium-navigate-v0 0 --train_steps 1000000 --gamma 0.995 --alpha 1.0 --variant_tag a1_g995 --save_best ckpt/best_rsm_humanoid_a1_g995.pkl +humanoidmaze-medium-navigate-v0 0 --train_steps 1000000 --gamma 0.995 --alpha 3.0 --variant_tag a3_g995 --save_best ckpt/best_rsm_humanoid_a3_g995.pkl +humanoidmaze-medium-navigate-v0 0 --train_steps 1000000 --gamma 0.99 --alpha 3.0 --variant_tag a3_g99 --save_best ckpt/best_rsm_humanoid_a3_g99.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_humanoidmaze_ei50k.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_humanoidmaze_ei50k.txt new file mode 100644 index 0000000000000000000000000000000000000000..989b2f13b32bdf50e8cb4f300c5286537256b6bf --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_humanoidmaze_ei50k.txt @@ -0,0 +1,13 @@ +# issue #61 — humanoidmaze gamma sweep, RELAUNCH with --eval_interval 50000. +# Rationale: humanoidmaze periodic evals are ~2.5-3h each on the shared GPU +# (long 1000-step locomotion episodes), so the original --eval_interval 25000 +# pack spent most of its runtime evaluating and kept getting preempted before +# banking 50k+. Halving the eval count lets it reach later banks between +# preemptions. eval_interval is downstream of training RNG (does NOT touch +# the gamma-equivalence / gamma-comparison). 25k banks are snapshotted under +# results/0/snapshots_ei25k/ (a1_g995 0.24, a3_g995 0.107, a3_g99 0.08). +# Same three arms; a1_g995 (gamma=0.995, alpha=1, the TD-rule alpha) is the +# standout so far and the arm to watch for clearing the 0.27 bar. +humanoidmaze-medium-navigate-v0 0 --train_steps 1000000 --eval_interval 50000 --gamma 0.995 --alpha 1.0 --variant_tag a1_g995 --save_best ckpt/best_rsm_humanoid_a1_g995.pkl +humanoidmaze-medium-navigate-v0 0 --train_steps 1000000 --eval_interval 50000 --gamma 0.995 --alpha 3.0 --variant_tag a3_g995 --save_best ckpt/best_rsm_humanoid_a3_g995.pkl +humanoidmaze-medium-navigate-v0 0 --train_steps 1000000 --eval_interval 50000 --gamma 0.99 --alpha 3.0 --variant_tag a3_g99 --save_best ckpt/best_rsm_humanoid_a3_g99.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_scene_antmaze.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_scene_antmaze.txt new file mode 100644 index 0000000000000000000000000000000000000000..c45094d719520c7ce80d744a4c34aa54b5e8733b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_scene_antmaze.txt @@ -0,0 +1,15 @@ +# issue #61 — two below/marginal cells packed on one GPU allocation. +# +# scene-play (RSM ~0.23 vs official GCIQL 0.51): bracket the current alpha=10 bank. +# a3 : alpha=3 — below the current setting +# a30 : alpha=30 — above it +# If BOTH alpha arms stall well below 0.51, the mixed-alphabet 7-dim target +# (binary button bits + continuous cube/drawer/window under the continuous +# ELBO path) is the likely bottleneck, not alpha — a diagnostic, not fixed here. +scene-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag a3 --save_best ckpt/best_rsm_scene_a3.pkl +scene-play-v0 0 --train_steps 1000000 --alpha 30.0 --variant_tag a30 --save_best ckpt/best_rsm_scene_a30.pkl +# +# antmaze-medium (RSM ~0.69 vs official GCIQL 0.71, MARGINAL): shorter hops. +# The existing alpha=3 arm keeps running longer (not relaunched here); this +# adds one shorter-hop arm to close the small gap. +antmaze-medium-navigate-v0 0 --train_steps 1000000 --alpha 3.0 --rec_beta 0.95 --variant_tag a3_b95 --save_best ckpt/best_rsm_antmaze_a3_b95.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/antmaze_a3_b95.json b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/antmaze_a3_b95.json new file mode 100644 index 0000000000000000000000000000000000000000..3980c93e6966e455d92cfaa0e74f373f1d5ac5a1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/antmaze_a3_b95.json @@ -0,0 +1,52 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "antmaze-medium-navigate-v0", + "seed": 0, + "alpha": 3.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.95, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.5866666666666667, + "best_sr": 0.5866666666666667, + "per_task": [ + 0.6666666666666666, + 0.6, + 0.4, + 0.5333333333333333, + 0.7333333333333333 + ], + "curve": [ + [ + 25000, + 0.3866666666666667 + ], + [ + 50000, + 0.4533333333333333 + ], + [ + 75000, + 0.5733333333333333 + ], + [ + 100000, + 0.5466666666666666 + ], + [ + 125000, + 0.48 + ], + [ + 150000, + 0.5866666666666667 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 25723.5, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/ff3t6ycp" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a1_g995_ei50k.json b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a1_g995_ei50k.json new file mode 100644 index 0000000000000000000000000000000000000000..c92cb52f15cfce81f539c35bec97d5b1bb0f2440 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a1_g995_ei50k.json @@ -0,0 +1,32 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "humanoidmaze-medium-navigate-v0", + "seed": 0, + "alpha": 1.0, + "gamma": 0.995, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.21333333333333332, + "best_sr": 0.21333333333333332, + "per_task": [ + 0.4, + 0.4, + 0.06666666666666667, + 0.0, + 0.2 + ], + "curve": [ + [ + 50000, + 0.21333333333333332 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 10202.2, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/ije7uysp" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a3_g99.json b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a3_g99.json new file mode 100644 index 0000000000000000000000000000000000000000..6d730c88dddb5baa75e67d642f94167ec877cac7 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a3_g99.json @@ -0,0 +1,32 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "humanoidmaze-medium-navigate-v0", + "seed": 0, + "alpha": 3.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.05333333333333333, + "best_sr": 0.05333333333333333, + "per_task": [ + 0.06666666666666667, + 0.13333333333333333, + 0.0, + 0.0, + 0.06666666666666667 + ], + "curve": [ + [ + 50000, + 0.05333333333333333 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 10423.2, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/sd33nr9p" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a3_g995.json b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a3_g995.json new file mode 100644 index 0000000000000000000000000000000000000000..2943ffd0632d2be20337d0733da8c0e842b8eafc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/humanoidmaze_a3_g995.json @@ -0,0 +1,32 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "humanoidmaze-medium-navigate-v0", + "seed": 0, + "alpha": 3.0, + "gamma": 0.995, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.06666666666666668, + "best_sr": 0.06666666666666668, + "per_task": [ + 0.0, + 0.0, + 0.2, + 0.0, + 0.13333333333333333 + ], + "curve": [ + [ + 50000, + 0.06666666666666668 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 10527.5, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/xfdrqb5y" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/scene_a3.json b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/scene_a3.json new file mode 100644 index 0000000000000000000000000000000000000000..e1294b863061b9583d0e06e40a5d2c825c92ff43 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/scene_a3.json @@ -0,0 +1,52 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "scene-play-v0", + "seed": 0, + "alpha": 3.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.22666666666666666, + "best_sr": 0.44000000000000006, + "per_task": [ + 0.7333333333333333, + 0.13333333333333333, + 0.2, + 0.06666666666666667, + 0.0 + ], + "curve": [ + [ + 25000, + 0.26666666666666666 + ], + [ + 50000, + 0.37333333333333335 + ], + [ + 75000, + 0.4 + ], + [ + 100000, + 0.44000000000000006 + ], + [ + 125000, + 0.2 + ], + [ + 150000, + 0.22666666666666666 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 25034.4, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/z4vrmarx" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/scene_a30.json b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/scene_a30.json new file mode 100644 index 0000000000000000000000000000000000000000..55816f35ed1703f10540dc779dd3e8d3deef5016 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/gamma_sweep_curves/scene_a30.json @@ -0,0 +1,52 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "scene-play-v0", + "seed": 0, + "alpha": 30.0, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": false, + "success_rate": 0.026666666666666665, + "best_sr": 0.17333333333333334, + "per_task": [ + 0.13333333333333333, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 25000, + 0.17333333333333334 + ], + [ + 50000, + 0.17333333333333334 + ], + [ + 75000, + 0.10666666666666666 + ], + [ + 100000, + 0.16 + ], + [ + 125000, + 0.07999999999999999 + ], + [ + 150000, + 0.026666666666666665 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 26422.6, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/700c2jbb" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_def_loco.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_def_loco.txt new file mode 100644 index 0000000000000000000000000000000000000000..f4d313d3542cbfaa09fbba08cb66231b56065d37 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_def_loco.txt @@ -0,0 +1,2 @@ +# antmaze-teleport (deferred; resumed after quota reclaim). antmaze family alpha=3. +antmaze-teleport-navigate-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_am_teleport.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_def_manip.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_def_manip.txt new file mode 100644 index 0000000000000000000000000000000000000000..7384fb9274e18e03c8b3aa81d976fa47d63164b1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_def_manip.txt @@ -0,0 +1,2 @@ +# cube-quadruple (deferred; resumed after quota reclaim). cube family alpha=3. +cube-quadruple-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_cube_quad_a3.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_giants.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_giants.txt new file mode 100644 index 0000000000000000000000000000000000000000..3611ec10fcad7a5d88b33bf82cc67938e983ff4d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_giants.txt @@ -0,0 +1,5 @@ +# New OGBench coverage — long-horizon giants + humanoidmaze-large. gamma=0.995 (long horizon). +# humanoidmaze wins at DEFAULT alpha=0.03 (measured: medium best 0.507 at 0.03 vs 0.28 at alpha=1; the 10x rule over-anchors it). +pointmaze-giant-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --save_best ckpt/best_rsm_pm_giant.pkl +humanoidmaze-large-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --save_best ckpt/best_rsm_hm_large.pkl +humanoidmaze-giant-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --save_best ckpt/best_rsm_hm_giant.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_hm.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_hm.txt new file mode 100644 index 0000000000000000000000000000000000000000..e480bbc3316cf1775820e38142e45b8e87bf9d16 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_hm.txt @@ -0,0 +1,3 @@ +# humanoidmaze large/giant (long-horizon, gamma=0.995, default alpha=0.03 — 10x rule over-anchors humanoidmaze). Datasets already in /u/zwhong. +humanoidmaze-large-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --save_best ckpt/best_rsm_hm_large.pkl +humanoidmaze-giant-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --save_best ckpt/best_rsm_hm_giant.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_loco_short.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_loco_short.txt new file mode 100644 index 0000000000000000000000000000000000000000..0d7f0c34bf228a1f73c17d36e61e1088a5c9adb0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_loco_short.txt @@ -0,0 +1,6 @@ +# New OGBench coverage — teleport mazes + antsoccer ARENA (the paper antsoccer cell; we only had medium). +# antsoccer is hard (medium ~0.04 at both alphas); bracket arena with alpha 1.0 and 0.3. +pointmaze-teleport-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --variant_tag newcov_a003 --save_best ckpt/best_rsm_pm_teleport.pkl +antmaze-teleport-navigate-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_am_teleport.pkl +antsoccer-arena-navigate-v0 0 --train_steps 1000000 --alpha 1.0 --variant_tag newcov_a1 --save_best ckpt/best_rsm_asoc_arena_a1.pkl +antsoccer-arena-navigate-v0 0 --train_steps 1000000 --alpha 0.3 --variant_tag newcov_a03 --save_best ckpt/best_rsm_asoc_arena_a03.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_manip.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_manip.txt new file mode 100644 index 0000000000000000000000000000000000000000..c994c13ce772b2a39075f8b51243b10df4a43d09 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_manip.txt @@ -0,0 +1,3 @@ +# New OGBench coverage — manipulation. cube family alpha=3 (proven: single 0.924). +cube-triple-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_cube_triple_a3.pkl +cube-quadruple-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_cube_quad_a3.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_puzzle.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_puzzle.txt new file mode 100644 index 0000000000000000000000000000000000000000..de420bd1b6240e3b66370503dc706579ef0708bc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_puzzle.txt @@ -0,0 +1,3 @@ +# New OGBench coverage — puzzle 4x5/4x6 (discrete goals; auto alpha=1.0, beta=0.98, exact gl read-out). +puzzle-4x5-play-v0 0 --train_steps 1000000 --variant_tag newcov --save_best ckpt/best_rsm_puzzle_4x5.pkl +puzzle-4x6-play-v0 0 --train_steps 1000000 --variant_tag newcov --save_best ckpt/best_rsm_puzzle_4x6.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_A.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_A.txt new file mode 100644 index 0000000000000000000000000000000000000000..40ea8d6b3d75e2465290041b5fa667742a55f949 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_A.txt @@ -0,0 +1,4 @@ +# Ready-A: puzzle 4x5/4x6 (discrete auto alpha=1.0) + cube-triple (alpha=3). Datasets complete. +puzzle-4x5-play-v0 0 --train_steps 1000000 --variant_tag newcov --save_best ckpt/best_rsm_puzzle_4x5.pkl +puzzle-4x6-play-v0 0 --train_steps 1000000 --variant_tag newcov --save_best ckpt/best_rsm_puzzle_4x6.pkl +cube-triple-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_cube_triple_a3.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_B.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_B.txt new file mode 100644 index 0000000000000000000000000000000000000000..205297dbb21eb0c0668d26e0980538adfca728fc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_B.txt @@ -0,0 +1,4 @@ +# Ready-B: cube-quadruple (alpha=3) + antmaze-teleport (alpha=3) + pointmaze-teleport (alpha=0.03). Datasets complete. +cube-quadruple-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_cube_quad_a3.pkl +antmaze-teleport-navigate-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_am_teleport.pkl +pointmaze-teleport-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --variant_tag newcov_a003 --save_best ckpt/best_rsm_pm_teleport.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_C.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_C.txt new file mode 100644 index 0000000000000000000000000000000000000000..57a41a7e7b548fa1e634b254c33b5ffe16af91ab --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_C.txt @@ -0,0 +1,4 @@ +# Ready-C: antsoccer-arena bracket (alpha 1.0 & 0.3) + pointmaze-giant (alpha=0.03, gamma=0.995 long-horizon). Datasets complete. +antsoccer-arena-navigate-v0 0 --train_steps 1000000 --alpha 1.0 --variant_tag newcov_a1 --save_best ckpt/best_rsm_asoc_arena_a1.pkl +antsoccer-arena-navigate-v0 0 --train_steps 1000000 --alpha 0.3 --variant_tag newcov_a03 --save_best ckpt/best_rsm_asoc_arena_a03.pkl +pointmaze-giant-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --save_best ckpt/best_rsm_pm_giant.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_loco.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_loco.txt new file mode 100644 index 0000000000000000000000000000000000000000..5b38d1d02be124078d585f48907f8be5cc55b5cf --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_loco.txt @@ -0,0 +1,4 @@ +# teleport pointmaze + antsoccer-arena bracket (antmaze-teleport data not yet downloaded). +pointmaze-teleport-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --variant_tag newcov_a003 --save_best ckpt/best_rsm_pm_teleport.pkl +antsoccer-arena-navigate-v0 0 --train_steps 1000000 --alpha 1.0 --variant_tag newcov_a1 --save_best ckpt/best_rsm_asoc_arena_a1.pkl +antsoccer-arena-navigate-v0 0 --train_steps 1000000 --alpha 0.3 --variant_tag newcov_a03 --save_best ckpt/best_rsm_asoc_arena_a03.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_manip.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_manip.txt new file mode 100644 index 0000000000000000000000000000000000000000..947e1993cc7b116762bd3802570b33e5ab104936 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/newcov_ready_manip.txt @@ -0,0 +1,2 @@ +# cube-triple only (cube-quadruple data not yet downloaded; giant prefetch quota-paused). +cube-triple-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --save_best ckpt/best_rsm_cube_triple_a3.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b1.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b1.txt new file mode 100644 index 0000000000000000000000000000000000000000..0971b9d1b33001d5b379a68ac8e5779299718577 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b1.txt @@ -0,0 +1 @@ +humanoidmaze-large-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --ckpt ckpt/resume_hml.pkl --ckpt_every 25000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b2.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b2.txt new file mode 100644 index 0000000000000000000000000000000000000000..d5ab8155cfcab8b3e2b93cb2bcd6a321015676df --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b2.txt @@ -0,0 +1 @@ +humanoidmaze-giant-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --ckpt ckpt/resume_hmg.pkl --ckpt_every 25000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b3.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b3.txt new file mode 100644 index 0000000000000000000000000000000000000000..a2181e2ca7c55b9960c8c54c8598d1237cc17979 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b3.txt @@ -0,0 +1,2 @@ +pointmaze-giant-navigate-v0 0 --train_steps 1000000 --alpha 0.03 --gamma 0.995 --variant_tag newcov_g995 --ckpt ckpt/resume_pmg.pkl --ckpt_every 25000 +antmaze-teleport-navigate-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --ckpt ckpt/resume_amt.pkl --ckpt_every 25000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b4.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b4.txt new file mode 100644 index 0000000000000000000000000000000000000000..404a47fc0af71944514b33da4869b9e5ddb1cc25 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b4.txt @@ -0,0 +1,2 @@ +cube-triple-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --ckpt ckpt/resume_ct.pkl --ckpt_every 25000 +cube-quadruple-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag newcov_a3 --ckpt ckpt/resume_cq.pkl --ckpt_every 25000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b5.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b5.txt new file mode 100644 index 0000000000000000000000000000000000000000..b1f50dfc107815a0c44711285fd5f112ffa80621 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b5.txt @@ -0,0 +1,2 @@ +puzzle-4x5-play-v0 0 --train_steps 1000000 --variant_tag newcov --ckpt ckpt/resume_p45.pkl --ckpt_every 25000 +puzzle-4x6-play-v0 0 --train_steps 1000000 --variant_tag newcov --ckpt ckpt/resume_p46.pkl --ckpt_every 25000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b6.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b6.txt new file mode 100644 index 0000000000000000000000000000000000000000..023ee12b3973391ca0494cff0723835e50f38bc0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b6.txt @@ -0,0 +1,3 @@ +scene-play-v0 0 --train_steps 1000000 --alpha 3.0 --recursion on --rec_guard tails --rec_beta 0.98 --rec_after 100000 --variant_tag reconA3 --ckpt ckpt/resume_scene_reconA3.pkl --ckpt_every 25000 +puzzle-3x3-play-v0 1 --train_steps 1000000 --variant_tag seed1 --ckpt ckpt/resume_puz3_s1.pkl --ckpt_every 25000 +puzzle-3x3-play-v0 2 --train_steps 1000000 --variant_tag seed2 --ckpt ckpt/resume_puz3_s2.pkl --ckpt_every 25000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b7.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b7.txt new file mode 100644 index 0000000000000000000000000000000000000000..42eb8382d69f96f53630ade85a7b1d85216df096 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b7.txt @@ -0,0 +1,3 @@ +antmaze-medium-navigate-v0 1 --train_steps 1000000 --alpha 3.0 --variant_tag a3_s1 --ckpt ckpt/resume_amed_s1.pkl --ckpt_every 25000 +antmaze-medium-navigate-v0 2 --train_steps 1000000 --alpha 3.0 --variant_tag a3_s2 --ckpt ckpt/resume_amed_s2.pkl --ckpt_every 25000 +antsoccer-arena-navigate-v0 1 --train_steps 1000000 --alpha 0.3 --variant_tag a03_s1 --ckpt ckpt/resume_asoc_s1.pkl --ckpt_every 25000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b8.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b8.txt new file mode 100644 index 0000000000000000000000000000000000000000..57d4d12ab05d57ab42327f987f9af3310d235847 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/pack8/b8.txt @@ -0,0 +1,3 @@ +antsoccer-arena-navigate-v0 2 --train_steps 1000000 --alpha 0.3 --variant_tag a03_s2 --ckpt ckpt/resume_asoc_s2.pkl --ckpt_every 25000 +pointmaze-teleport-navigate-v0 1 --train_steps 1000000 --alpha 0.03 --variant_tag s1 --ckpt ckpt/resume_pmt_s1.pkl --ckpt_every 25000 +pointmaze-teleport-navigate-v0 2 --train_steps 1000000 --alpha 0.03 --variant_tag s2 --ckpt ckpt/resume_pmt_s2.pkl --ckpt_every 25000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/s2_alpha_wave1.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/s2_alpha_wave1.txt new file mode 100644 index 0000000000000000000000000000000000000000..dbe1d05954ef6499c8a59c72893e01e64b407e32 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/s2_alpha_wave1.txt @@ -0,0 +1,9 @@ +# S2 alpha scan for wave-1 cells below/without signal at ~300k (issue #61). +# Rationale: TD-reference alphas are cube/scene 1.0, antsoccer 0.1 — the +# ~10x-TD rule predicts RSM alpha ~10 (manip) / ~1 (antsoccer); the S1 +# default 0.03 was calibrated on pointmaze (TD ref 0.003) and is far under- +# anchored here. S1 arms keep running as the low-alpha end of the scan. +cube-single-play-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag a3 --save_best ckpt/best_rsm_cube_a3.pkl +cube-single-play-v0 0 --train_steps 1000000 --alpha 10.0 --variant_tag a10 --save_best ckpt/best_rsm_cube_a10.pkl +antsoccer-medium-navigate-v0 0 --train_steps 1000000 --alpha 1.0 --variant_tag a1 --save_best ckpt/best_rsm_antsoccer_a1.pkl +scene-play-v0 0 --train_steps 1000000 --alpha 10.0 --variant_tag a10 --save_best ckpt/best_rsm_scene_a10.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/s2b_alpha_mazes.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/s2b_alpha_mazes.txt new file mode 100644 index 0000000000000000000000000000000000000000..a19ea7bab8cc09aaf9cb2c29005fe0963234bdaa --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/s2b_alpha_mazes.txt @@ -0,0 +1,5 @@ +# S2b: apply the 10x-TD alpha rule to the maze cells running 100x/30x under- +# anchored in S1 (issue #61; motivated by cube's instant 0.907 at alpha=3). +# TD refs: antmaze 0.3 -> RSM 3; humanoidmaze 0.1 -> RSM 1. +antmaze-medium-navigate-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag a3 --save_best ckpt/best_rsm_antmaze_a3.pkl +humanoidmaze-medium-navigate-v0 0 --train_steps 1000000 --alpha 1.0 --variant_tag a1 --save_best ckpt/best_rsm_humanoid_a1.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/tier2_wave1_locomotion.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/tier2_wave1_locomotion.txt new file mode 100644 index 0000000000000000000000000000000000000000..b23dbeac963c69bb8cd22b06f77eac47d239ee80 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/tier2_wave1_locomotion.txt @@ -0,0 +1,5 @@ +# Wave 1 / S1 recipe-transfer probes — locomotion families (issue #61). +# Pure rsm.py defaults (unified recipe), 1 seed, 1M-step probe budget. +antmaze-medium-navigate-v0 0 --train_steps 1000000 +humanoidmaze-medium-navigate-v0 0 --train_steps 1000000 +antsoccer-medium-navigate-v0 0 --train_steps 1000000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/tier2_wave1_manip.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/tier2_wave1_manip.txt new file mode 100644 index 0000000000000000000000000000000000000000..d59eb3a94af2e152172212942c87fd3449837053 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/tier2_wave1_manip.txt @@ -0,0 +1,7 @@ +# Wave 1 / S1 recipe-transfer probes — manipulation families (issue #61). +# Pure rsm.py defaults (unified recipe), 1 seed, 1M-step probe budget. +# puzzle-4x4 runs the discrete path with 16 bits; scene runs the mixed +# 7-dim target under the continuous path (see issue #61 open decisions). +cube-single-play-v0 0 --train_steps 1000000 +scene-play-v0 0 --train_steps 1000000 +puzzle-4x4-play-v0 0 --train_steps 1000000 diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/w3_giant_longhorizon.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/w3_giant_longhorizon.txt new file mode 100644 index 0000000000000000000000000000000000000000..f9367b39d5aa3954891e01a4bb037f62830112f0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/w3_giant_longhorizon.txt @@ -0,0 +1,6 @@ +# Wave-3 giant mazes — the long-horizon frontier (#61 + long-horizon improvement). +# Giants use official discount 0.995; test whether gamma=0.995 lifts RSM on long +# horizons (unlike medium humanoidmaze where gamma was neutral). alpha per 10x rule. +# antmaze-giant: CompPlan reports 0.29 (planner+repertoire); alpha 0.3->3. +antmaze-giant-navigate-v0 0 --train_steps 2000000 --gamma 0.995 --alpha 3.0 --variant_tag g995_a3 --save_best ckpt/best_rsm_antmaze_giant_g995_a3.pkl +antmaze-giant-navigate-v0 0 --train_steps 2000000 --gamma 0.99 --alpha 3.0 --variant_tag g99_a3 --save_best ckpt/best_rsm_antmaze_giant_g99_a3.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/sweeps/w3a_mazes_cached.txt b/gen_q_rsm/ogbench_genq/experiments/sweeps/w3a_mazes_cached.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a86c7325ff2986ea2613f08f60f6c8a1f72263d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/sweeps/w3a_mazes_cached.txt @@ -0,0 +1,4 @@ +# Wave-3a large mazes, part 1 (cached datasets) — alpha rule from day one (#61). +# CompPlan published: antmaze-large 0.90 (planner + policy repertoire). +antmaze-large-navigate-v0 0 --train_steps 1000000 --alpha 3.0 --variant_tag a3 --save_best ckpt/best_rsm_antmaze_lg_a3.pkl +pointmaze-large-navigate-v0 0 --train_steps 1000000 --variant_tag s1 --save_best ckpt/best_rsm_pointmaze_lg.pkl diff --git a/gen_q_rsm/ogbench_genq/experiments/train_gciql_goal_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/train_gciql_goal_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..657c07454e261e46c5540b4702fd6b4375d61ad8 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_gciql_goal_rsm.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# Fit one fair pixels-only RSM arm: frozen latent or jointly trained adapter. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" +[ -f .env ] && set -a && . ./.env && set +a + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export MUJOCO_GL=egl +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +if [ "$#" -ne 2 ]; then + echo "usage: $0 {frozen|joint} ENCODER_TAG" >&2 + exit 2 +fi + +MODE=$1 +ENC_TAG=$2 +case "$MODE" in + frozen) LATENT_ARGS=(--latent_update frozen) ;; + joint) + LATENT_ARGS=( + --latent_update adapter + --latent_lr 3e-5 + --latent_hidden 64 + --latent_goal_weight 0.1 + --latent_anchor_weight 0.01 + ) + ;; + *) + echo "usage: $0 {frozen|joint} ENCODER_TAG" >&2 + exit 2 + ;; +esac + +PY=$REC/.ogbench_venv/bin/python +ENV=visual-cube-single-play-v0 +BASE=fair_px_${ENC_TAG}_gciqlret +TAG=${BASE}_${MODE}_awr_s0 +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_${ENC_TAG}.npz +LAT=ckpt/latents_${BASE}.npz +RDEC=ckpt/rdec_${BASE}.npz +SMOKE_CKPT=ckpt/rsm_${TAG}_smoke.pkl +FULL_CKPT=ckpt/rsm_${TAG}.pkl + +for artifact in "$ENC" "$LAT" "$RDEC"; do + [ -f "$artifact" ] || { + echo "[gciql-rsm-$MODE] FATAL artifact missing: $artifact" >&2 + exit 1 + } +done + +COMMON=( + --env "$ENV" + --latent_npz "$LAT" + --pixel_encoder "$ENC" + --drop_proprio + --reward_decoder "$RDEC" + --rdec_samples 4 + --actor_loss awr + --alpha 30 + --expectile 0.7 + --recursion off + --wandb_mode disabled + "${LATENT_ARGS[@]}" +) + +echo "[gciql-rsm-$MODE] exact-path smoke" +"$PY" -u ogbench_genq/rsm.py "${COMMON[@]}" \ + --rdec_samples 2 --actor_after 50 \ + --batch_size 64 --occ_batch 64 \ + --train_steps 100 --eval_interval 1000 \ + --eval_episodes 1 --eval_episodes_periodic 1 \ + --train_only \ + --ckpt "$SMOKE_CKPT" --ckpt_every 100 \ + --variant_tag "${TAG}_smoke" + +echo "[gciql-rsm-$MODE] full resumable occupancy + AWR fit" +"$PY" -u ogbench_genq/rsm.py "${COMMON[@]}" \ + --actor_after 100000 \ + --batch_size 1024 --occ_batch 2048 \ + --train_steps 1000000 --eval_interval 100000 \ + --eval_episodes 50 --eval_episodes_periodic 3 \ + --train_only \ + --ckpt "$FULL_CKPT" --ckpt_every 10000 \ + --variant_tag "$TAG" + +echo "[gciql-rsm-$MODE] DONE tag=$TAG" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_gciql_matched_extraction.sh b/gen_q_rsm/ogbench_genq/experiments/train_gciql_matched_extraction.sh new file mode 100644 index 0000000000000000000000000000000000000000..eb4121844b82cae48f98e00968a0a3e3552ef1b3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_gciql_matched_extraction.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Fresh visual GCIQL DDPG+BC actor on the already-trained frozen occupancy. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz +RDEC=ckpt/rdec_${BASE}.npz +SOURCE=ckpt/rsm_${BASE}_frozen_awr_s0.pkl +TAG=${BASE}_frozen_gciql_ddpgbc_raw_s0 +CKPT=ckpt/rsm_${TAG}.pkl + +for artifact in "$LAT" "$ENC" "$RDEC" "$SOURCE"; do + [ -f "$artifact" ] || { + echo "[gciql-extract] missing artifact: $artifact" >&2 + exit 1 + } +done + +"$PY" -u ogbench_genq/rsm.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio \ + --reward_decoder "$RDEC" --rdec_samples 4 \ + --actor_loss ddpgbc --alpha 1.0 --expectile 0.9 \ + --actor_q_transform raw \ + --recursion off --batch_size 256 --occ_batch 2048 \ + --init_occupancy_ckpt "$SOURCE" --freeze_occupancy \ + --train_steps 500000 --eval_interval 100000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --variant_tag "$TAG" --wandb_mode disabled + +echo "[gciql-extract] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_goalpred_index_encoder.sh b/gen_q_rsm/ogbench_genq/experiments/train_goalpred_index_encoder.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b8a5168743ee1824e7db8f73149acd978d8555a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_goalpred_index_encoder.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# Train one audited pixels-only goal-proximity encoder selected by a screen. +# +# Usage: +# bash ogbench_genq/experiments/train_goalpred_index_encoder.sh \ +# TAG Z_DIM HIDDEN CHANNELS GOAL_WEIGHT [TRAIN_STEPS] +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" +[ -f .env ] && set -a && . ./.env && set +a + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +if [ "$#" -lt 5 ] || [ "$#" -gt 6 ]; then + echo "usage: $0 TAG Z_DIM HIDDEN CHANNELS GOAL_WEIGHT [TRAIN_STEPS]" >&2 + exit 2 +fi + +TAG=$1 +Z_DIM=$2 +HIDDEN=$3 +CHANNELS=$4 +GOAL_WEIGHT=$5 +TRAIN_STEPS=${6:-25000} +PY=$REC/.ogbench_venv/bin/python +OUT=ckpt/pixel_enc_visual_cube_single_play_v0_${TAG}.npz +mkdir -p ckpt bsub_out + +if [ -f "$OUT" ]; then + echo "[goalpred-selected] already exists: $OUT" + exit 0 +fi + +echo "[goalpred-selected] host=$(hostname) tag=$TAG z=$Z_DIM hidden=$HIDDEN " +echo "[goalpred-selected] channels=$CHANNELS weight=$GOAL_WEIGHT steps=$TRAIN_STEPS" +"$PY" -u ogbench_genq/genq/train_latent_variants_jax.py \ + --env visual-cube-single-play-v0 --variant "$TAG" \ + --w_reward 0 --w_recon 1 --w_consistency 0 \ + --w_tempcon 0 --w_stepsto 0 --w_goalcls 0 \ + --w_goalcls_bin "$GOAL_WEIGHT" \ + --goalcls_target index --goalcls_features symmetric \ + --goalcls_index_delta 8 --goalcls_neg_gap 64 \ + --goalcls_cross_neg_frac 0.5 \ + --goalcls_after 5000 --goalcls_ramp 5000 \ + --z_dim "$Z_DIM" --hidden "$HIDDEN" --channels "$CHANNELS" \ + --batch_size 256 --lr 3e-4 \ + --train_steps "$TRAIN_STEPS" --eval_every 5000 \ + --out "$OUT" + +echo "[goalpred-selected] DONE $OUT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_extraction.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_extraction.sh new file mode 100644 index 0000000000000000000000000000000000000000..3b98991cfdb951328d6d38bb75429beeba964589 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_extraction.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Fresh matched GCIQL actor on the completed, frozen action-contrastive flow +# occupancy. This isolates policy extraction from occupancy nonstationarity. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz +RDEC=ckpt/rdec_${BASE}.npz +SOURCE=ckpt/rsm_${BASE}_flow_abs_h256l4_aclocal05_gciqlraw_s0.pkl +TAG=${TAG:-${BASE}_flow_abs_h256l4_aclocal05_frozenextract_gciqlraw_s0} +CKPT=${CKPT:-ckpt/rsm_${TAG}.pkl} +ACTOR_AFTER=${ACTOR_AFTER:-0} + +for artifact in "$LAT" "$ENC" "$RDEC" "$SOURCE"; do + [ -f "$artifact" ] || { + echo "[visual-flow-action-extract] missing artifact: $artifact" >&2 + exit 1 + } +done + +"$PY" -u ogbench_genq/rsm.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio \ + --reward_decoder "$RDEC" --rdec_samples 4 \ + --occupancy_model flow --occ_hidden 256 --occ_layers 4 --flow_steps 25 \ + --occ_action_contrast_weight 0.5 --occ_action_contrast_margin 0.1 \ + --occ_action_negative local --occ_action_negative_sigma 0.3 \ + --actor_loss ddpgbc --actor_q_transform raw \ + --alpha 1.0 --expectile 0.9 --actor_after "$ACTOR_AFTER" \ + --recursion off --batch_size 256 --occ_batch 2048 \ + --init_occupancy_ckpt "$SOURCE" --freeze_occupancy \ + --train_steps 500000 --eval_interval 100000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --variant_tag "$TAG" --wandb_mode disabled + +echo "[visual-flow-action-extract] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_joint_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_joint_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c25bfac4c34d457d9f174d807514a18b8d1581e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_joint_rsm.sh @@ -0,0 +1,48 @@ +#!/bin/bash +# Fair pixels-only RSM: jointly adapt the goal-predictive latent while fitting +# the action-contrastive conditional-flow occupancy and matched GCIQL actor. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz +RDEC=ckpt/rdec_${BASE}.npz +TAG=${BASE}_flow_abs_h256l4_aclocal05_joint_gciqlraw_s0 +CKPT=ckpt/rsm_${TAG}.pkl + +for artifact in "$LAT" "$ENC" "$RDEC"; do + [ -f "$artifact" ] || { + echo "[visual-flow-action-contrast-joint] missing artifact: $artifact" >&2 + exit 1 + } +done + +"$PY" -u ogbench_genq/rsm.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio \ + --reward_decoder "$RDEC" --rdec_samples 4 \ + --latent_update adapter --latent_hidden 64 --latent_lr 3e-5 \ + --latent_goal_weight 0.1 --latent_anchor_weight 0.01 \ + --occupancy_model flow --occ_hidden 256 --occ_layers 4 --flow_steps 25 \ + --occ_action_contrast_weight 0.5 --occ_action_contrast_margin 0.1 \ + --occ_action_negative local --occ_action_negative_sigma 0.3 \ + --actor_loss ddpgbc --actor_q_transform raw \ + --alpha 1.0 --expectile 0.9 \ + --recursion off --batch_size 256 --occ_batch 2048 \ + --train_steps 500000 --eval_interval 100000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --variant_tag "$TAG" --wandb_mode disabled + +echo "[visual-flow-action-contrast-joint] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..fa1cc032bf2eb2850c719f2317ef662c48166f05 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_action_contrast_rsm.sh @@ -0,0 +1,46 @@ +#!/bin/bash +# Fair pixels-only RSM: calibrated conditional-flow occupancy with a +# reward-free local action-identification loss and matched GCIQL extraction. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz +RDEC=ckpt/rdec_${BASE}.npz +TAG=${BASE}_flow_abs_h256l4_aclocal05_gciqlraw_s0 +CKPT=ckpt/rsm_${TAG}.pkl + +for artifact in "$LAT" "$ENC" "$RDEC"; do + [ -f "$artifact" ] || { + echo "[visual-flow-action-contrast] missing artifact: $artifact" >&2 + exit 1 + } +done + +"$PY" -u ogbench_genq/rsm.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio \ + --reward_decoder "$RDEC" --rdec_samples 4 \ + --occupancy_model flow --occ_hidden 256 --occ_layers 4 --flow_steps 25 \ + --occ_action_contrast_weight 0.5 --occ_action_contrast_margin 0.1 \ + --occ_action_negative local --occ_action_negative_sigma 0.3 \ + --actor_loss ddpgbc --actor_q_transform raw \ + --alpha 1.0 --expectile 0.9 \ + --recursion off --batch_size 256 --occ_batch 2048 \ + --train_steps 500000 --eval_interval 100000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --variant_tag "$TAG" --wandb_mode disabled + +echo "[visual-flow-action-contrast] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_bc_probe.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_bc_probe.sh new file mode 100644 index 0000000000000000000000000000000000000000..2938eca66464585b5769a170b19d35dbccc2552c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_bc_probe.sh @@ -0,0 +1,41 @@ +#!/bin/bash +# Diagnostic control: fit only the matched GCIQL behavior-cloning term for +# 100k steps on the final frozen occupancy/state representation. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz +RDEC=ckpt/rdec_${BASE}.npz +SOURCE=ckpt/rsm_${BASE}_flow_abs_h256l4_aclocal05_gciqlraw_s0.pkl +TAG=${BASE}_flow_abs_h256l4_aclocal05_bcprobe100k_s0 +CKPT=ckpt/rsm_${TAG}.pkl + +"$PY" -u ogbench_genq/rsm.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio \ + --reward_decoder "$RDEC" --rdec_samples 4 \ + --occupancy_model flow --occ_hidden 256 --occ_layers 4 --flow_steps 25 \ + --occ_action_contrast_weight 0.5 --occ_action_contrast_margin 0.1 \ + --occ_action_negative local --occ_action_negative_sigma 0.3 \ + --actor_loss ddpgbc --actor_q_transform raw \ + --alpha 1.0 --expectile 0.9 --actor_after 100001 \ + --recursion off --batch_size 256 --occ_batch 2048 \ + --init_occupancy_ckpt "$SOURCE" --freeze_occupancy \ + --train_steps 100000 --eval_interval 100000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --variant_tag "$TAG" --wandb_mode disabled + +echo "[visual-flow-bc-probe] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..154114b9d9cd0462f3813c61ee267522bdb46745 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_rsm.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# Evidence-backed fair visual RSM: frozen latent + conditional flow occupancy +# + the reference visual GCIQL DDPG+BC extraction recipe. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz +RDEC=ckpt/rdec_${BASE}.npz +TAG=${BASE}_flow_abs_h256l4_gciqlraw_s0 +CKPT=ckpt/rsm_${TAG}.pkl + +for artifact in "$LAT" "$ENC" "$RDEC"; do + [ -f "$artifact" ] || { + echo "[visual-flow-rsm] missing artifact: $artifact" >&2 + exit 1 + } +done + +"$PY" -u ogbench_genq/rsm.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio \ + --reward_decoder "$RDEC" --rdec_samples 4 \ + --occupancy_model flow --occ_hidden 256 --occ_layers 4 --flow_steps 25 \ + --actor_loss ddpgbc --actor_q_transform raw \ + --alpha 1.0 --expectile 0.9 \ + --recursion off --batch_size 256 --occ_batch 2048 \ + --train_steps 500000 --eval_interval 100000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --variant_tag "$TAG" --wandb_mode disabled + +echo "[visual-flow-rsm] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_statehidden_rsm.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_statehidden_rsm.sh new file mode 100644 index 0000000000000000000000000000000000000000..a32927f7ae491f8b5db34400c720fe4bf3750215 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_flow_statehidden_rsm.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Fair pixels-only RSM with a rich image state and compact goal/reward latent. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +PY=$REC/.ogbench_venv/bin/python +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}_stateh256.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz +RDEC=ckpt/rdec_${BASE}.npz +TAG=${BASE}_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0 +CKPT=ckpt/rsm_${TAG}.pkl + +for artifact in "$LAT" "$ENC" "$RDEC"; do + [ -f "$artifact" ] || { + echo "[visual-flow-statehidden] missing artifact: $artifact" >&2 + exit 1 + } +done + +"$PY" -u ogbench_genq/rsm.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio \ + --reward_decoder "$RDEC" --rdec_samples 4 \ + --occupancy_model flow --occ_hidden 256 --occ_layers 4 --flow_steps 25 \ + --occ_action_contrast_weight 0.5 --occ_action_contrast_margin 0.1 \ + --occ_action_negative local --occ_action_negative_sigma 0.3 \ + --actor_loss ddpgbc --actor_q_transform raw \ + --alpha 1.0 --expectile 0.9 \ + --recursion off --batch_size 256 --occ_batch 2048 \ + --train_steps 500000 --eval_interval 100000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --variant_tag "$TAG" --wandb_mode disabled + +echo "[visual-flow-statehidden] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_gciql_control.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_gciql_control.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d32d0e3961ff7c482fbf8166f03ca46bbbe9d5d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_gciql_control.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# Exact fair visual GCIQL diagnostic control. Training is render-free. +set -euo pipefail + +ROOT=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-gciql-audit +PY=/proj/inf-scaling/zwhong/projs/gen_q/.ogbench_venv/bin/python +OUT=${OUT:-$ROOT/ckpt/gciql_visual_control_s0} +TASK_TMP=${TASK_TMP:-/proj/inf-scaling/zwhong/tmp_visual_gciql_control} + +cd "$ROOT" +mkdir -p "$TASK_TMP" "$TASK_TMP/wandb-cache" "$TASK_TMP/wandb-data" +export OGBENCH_IMPLS=/u/zwhong/ogbench_ref/impls +export WANDB_MODE=offline +export WANDB_CACHE_DIR="$TASK_TMP/wandb-cache" +export WANDB_DATA_DIR="$TASK_TMP/wandb-data" +export TMPDIR="$TASK_TMP" +export XLA_PYTHON_CLIENT_PREALLOCATE=false + +"$PY" -m ogbench_genq.genq.train_visual_gciql_control \ + --output_dir "$OUT" \ + --train_steps "${TRAIN_STEPS:-300000}" \ + --seed "${SEED:-0}" \ + --checkpoint_interval "${CHECKPOINT_INTERVAL:-10000}" \ + --export_interval "${EXPORT_INTERVAL:-100000}" \ + --log_interval "${LOG_INTERVAL:-1000}" \ + --resume "${RESUME:-auto}" \ + --wandb_mode offline diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_rich_gcbc.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_rich_gcbc.sh new file mode 100644 index 0000000000000000000000000000000000000000..998533ee5ae320d965f2d57bcffab329e189bab6 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_rich_gcbc.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# Strict pixels-only GCBC representation gate: h_state, h_goal -> action. +set -euo pipefail + +WT=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-rich-goal +VENV=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion/.ogbench_venv +cd "$WT" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=0.70 +export PYTHONUNBUFFERED=1 + +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}_stateh256.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz +TAG=${BASE}_stateh256_goalh256_gcbc_s0 +CKPT=ckpt/${TAG}.pkl +OUT=ogbench_genq/experiments/visual-cube-single-play-v0/results/0/${TAG}_train.json + +"$VENV/bin/python" -u ogbench_genq/genq/train_visual_rich_gcbc.py \ + --env visual-cube-single-play-v0 \ + --latent_npz "$LAT" --pixel_encoder "$ENC" \ + --train_steps 300000 --batch_size 1024 --lr 3e-4 \ + --ckpt "$CKPT" --ckpt_every 10000 --out "$OUT" --train_only diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_index_distill.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_index_distill.sh new file mode 100644 index 0000000000000000000000000000000000000000..bc1b4a194ee505c1eb28f0a555ae85b3d80664f0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_index_distill.sh @@ -0,0 +1,229 @@ +#!/bin/bash +# Fair visual-cube RSM with a discount-conditioned flow occupancy and a +# supervised index-reward occupancy-Q policy extractor. This contains no +# Bellman/TD target: the scalar scorer is regressed directly onto +# E_{z'~p_theta(.|s,a,gamma,g)}[R_index(z',g)] while p_theta and the actor are +# updated in the same fused training loop. +set -euo pipefail + +CF=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree +REC=/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=${XLA_PYTHON_CLIENT_MEM_FRACTION:-0.90} +export WANDB_MODE=${WANDB_MODE:-disabled} +export PYTHONUNBUFFERED=1 + +PY=${PY:-$REC/.ogbench_venv/bin/python} +ENV=visual-cube-single-play-v0 +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}_stateh256.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz + +MODE=${MODE:-ddpgbc_distill} +LATENT_UPDATE=${LATENT_UPDATE:-frozen} +READER_DELTA=${READER_DELTA:-2} +READER_TAG=${READER_TAG:-indexd${READER_DELTA}} +SEED=${SEED:-0} +TRAIN_STEPS=${TRAIN_STEPS:-150000} +RDEC_SAMPLES=${RDEC_SAMPLES:-16} +FLOW_STEPS=${FLOW_STEPS:-25} +OCC_HIDDEN=${OCC_HIDDEN:-256} +OCC_LAYERS=${OCC_LAYERS:-4} +OCC_ACTION_CONTRAST_WEIGHT=${OCC_ACTION_CONTRAST_WEIGHT:-0.5} +OCC_ACTION_CONTRAST_MARGIN=${OCC_ACTION_CONTRAST_MARGIN:-0.1} +OCC_ACTION_NEGATIVE=${OCC_ACTION_NEGATIVE:-local} +OCC_ACTION_NEGATIVE_SIGMA=${OCC_ACTION_NEGATIVE_SIGMA:-0.3} +OCC_ACTION_NEGATIVE_K=${OCC_ACTION_NEGATIVE_K:-2} +GAMMA_SAMPLER=${GAMMA_SAMPLER:-stratified_bins} +GAMMA_HORIZONS=${GAMMA_HORIZONS:-2,4,8,16,32,64} +GAMMA_TASK_FRACTION=${GAMMA_TASK_FRACTION:-0.5} +GAMMA_LO=${GAMMA_LO:-} +ACTOR_AFTER=${ACTOR_AFTER:-50000} +DISTILL_ACTOR_GOALS=${DISTILL_ACTOR_GOALS:-1} +DISTILL_ACTOR_ACTIONS=${DISTILL_ACTOR_ACTIONS:-} +DISTILL_ACTOR_ACTION_K=${DISTILL_ACTOR_ACTION_K:-2} +DISTILL_ACTOR_ACTION_SIGMA=${DISTILL_ACTOR_ACTION_SIGMA:-0.3} +DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT=${DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT:-1.0} +LATENT_HIDDEN=${LATENT_HIDDEN:-64} +LATENT_LR=${LATENT_LR:-3e-5} +LATENT_GOAL_WEIGHT=${LATENT_GOAL_WEIGHT:-0.1} +LATENT_ANCHOR_WEIGHT=${LATENT_ANCHOR_WEIGHT:-0.01} +ARCHIVE_EVERY=${ARCHIVE_EVERY:-25000} + +TASK_FRAC_TAG=${GAMMA_TASK_FRACTION//./p} +case "$GAMMA_SAMPLER" in + stratified_bins) + GAMMA_LO=${GAMMA_LO:-0.50} + HORIZON_TAG=${GAMMA_HORIZONS//,/-} + GAMMA_RECIPE_TAG=strath${HORIZON_TAG}tf${TASK_FRAC_TAG} + ;; + legacy_log_uniform) + GAMMA_LO=${GAMMA_LO:-0.90} + GAMMA_LO_TAG=${GAMMA_LO//./p} + GAMMA_RECIPE_TAG=legacylo${GAMMA_LO_TAG}tf${TASK_FRAC_TAG} + ;; + *) + echo "[visual-index-distill] unsupported GAMMA_SAMPLER=$GAMMA_SAMPLER" >&2 + exit 2 + ;; +esac + +case "$MODE" in + ddpgbc_distill) + ALPHA=${ALPHA:-1.0} + EXPECTILE=${EXPECTILE:-0.9} + DISTILL_ACTOR_ACTIONS=${DISTILL_ACTOR_ACTIONS:-1} + MODE_TAG=ddpg + ;; + awr_distill) + ALPHA=${ALPHA:-10.0} + EXPECTILE=${EXPECTILE:-0.9} + DISTILL_ACTOR_ACTIONS=${DISTILL_ACTOR_ACTIONS:-0} + MODE_TAG=awr + ;; + *) + echo "[visual-index-distill] unsupported MODE=$MODE" >&2 + exit 2 + ;; +esac + +case "$LATENT_UPDATE" in + frozen) + LATENT_TAG=frozen + LATENT_ARGS=(--latent_update frozen) + ;; + rich_adapter) + LATENT_LR_TAG=${LATENT_LR//./p} + LATENT_GOAL_TAG=${LATENT_GOAL_WEIGHT//./p} + LATENT_ANCHOR_TAG=${LATENT_ANCHOR_WEIGHT//./p} + LATENT_TAG=richadapt_h${LATENT_HIDDEN}_lr${LATENT_LR_TAG}_gw${LATENT_GOAL_TAG}_aw${LATENT_ANCHOR_TAG} + LATENT_ARGS=( + --latent_update rich_adapter + --latent_hidden "$LATENT_HIDDEN" --latent_lr "$LATENT_LR" + --latent_goal_weight "$LATENT_GOAL_WEIGHT" + --latent_anchor_weight "$LATENT_ANCHOR_WEIGHT" + ) + ;; + *) + echo "[visual-index-distill] unsupported LATENT_UPDATE=$LATENT_UPDATE" >&2 + exit 2 + ;; +esac + +case "$READER_TAG" in + *[!A-Za-z0-9._-]*|'') + echo "[visual-index-distill] READER_TAG must use only A-Z, a-z, 0-9, dot, underscore, or hyphen" >&2 + exit 2 + ;; +esac +RDEC=${RDEC:-ckpt/rdec_${BASE}_${READER_TAG}.npz} +ACTOR_GOAL_TAG=ag${DISTILL_ACTOR_GOALS} +case "$DISTILL_ACTOR_ACTIONS" in + 1) + if [ "$MODE" != ddpgbc_distill ]; then + echo "[visual-index-distill] actor-action scorer support applies only to ddpgbc_distill" >&2 + exit 2 + fi + AA_SIGMA_TAG=${DISTILL_ACTOR_ACTION_SIGMA//./p} + AA_PAIR_TAG=${DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT//./p} + ACTOR_ACTION_TAG=aa1k${DISTILL_ACTOR_ACTION_K}s${AA_SIGMA_TAG}pw${AA_PAIR_TAG} + ;; + 0) + ACTOR_ACTION_TAG=aa0 + ;; + *) + echo "[visual-index-distill] DISTILL_ACTOR_ACTIONS must be 0 or 1" >&2 + exit 2 + ;; +esac +AC_WEIGHT_TAG=${OCC_ACTION_CONTRAST_WEIGHT//./p} +AC_MARGIN_TAG=${OCC_ACTION_CONTRAST_MARGIN//./p} +AC_SIGMA_TAG=${OCC_ACTION_NEGATIVE_SIGMA//./p} +if [ "$OCC_ACTION_NEGATIVE" = actor_local ]; then + AC_NEGATIVE_TAG=actorlocalk${OCC_ACTION_NEGATIVE_K}s${AC_SIGMA_TAG} +else + AC_NEGATIVE_TAG=${OCC_ACTION_NEGATIVE}${AC_SIGMA_TAG} +fi +DEFAULT_TAG=${BASE}_stateh256_goalh256_flow${FLOW_STEPS}_h${OCC_HIDDEN}l${OCC_LAYERS}_acw${AC_WEIGHT_TAG}m${AC_MARGIN_TAG}_${AC_NEGATIVE_TAG}_${READER_TAG}_${LATENT_TAG}_${MODE_TAG}_a${ALPHA}_e${EXPECTILE}_${ACTOR_GOAL_TAG}_${ACTOR_ACTION_TAG}_${GAMMA_RECIPE_TAG}_m${RDEC_SAMPLES}_warm${ACTOR_AFTER}_s${SEED} +TAG=${TAG:-$DEFAULT_TAG} +CKPT=${CKPT:-ckpt/rsm_${TAG}.pkl} + +for artifact in "$LAT" "$ENC" "$RDEC"; do + [ -s "$artifact" ] || { + echo "[visual-index-distill] missing artifact: $artifact" >&2 + exit 1 + } +done + +EXTRA_ARGS=() +if [ "$DISTILL_ACTOR_GOALS" = 1 ]; then + EXTRA_ARGS+=(--distill_actor_goals) +elif [ "$DISTILL_ACTOR_GOALS" = 0 ]; then + EXTRA_ARGS+=(--no_distill_actor_goals) +elif [ "$DISTILL_ACTOR_GOALS" != 0 ]; then + echo "[visual-index-distill] DISTILL_ACTOR_GOALS must be 0 or 1" >&2 + exit 2 +fi +if [ "$DISTILL_ACTOR_ACTIONS" = 1 ]; then + EXTRA_ARGS+=(--distill_actor_actions) +else + EXTRA_ARGS+=(--no_distill_actor_actions) +fi +EXTRA_ARGS+=( + --distill_actor_action_k "$DISTILL_ACTOR_ACTION_K" + --distill_actor_action_sigma "$DISTILL_ACTOR_ACTION_SIGMA" + --distill_actor_action_pairwise_weight \ + "$DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT" +) + +echo "[visual-index-distill] train tag=$TAG checkpoint=$CKPT reader_tag=$READER_TAG reader=$RDEC" +"$PY" -u ogbench_genq/rsm.py \ + --env "$ENV" --seed "$SEED" \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio --goal_hidden \ + --reward_decoder "$RDEC" --rdec_samples "$RDEC_SAMPLES" \ + "${LATENT_ARGS[@]}" \ + --occupancy_model flow --occ_hidden "$OCC_HIDDEN" \ + --occ_layers "$OCC_LAYERS" --flow_steps "$FLOW_STEPS" \ + --occ_action_contrast_weight "$OCC_ACTION_CONTRAST_WEIGHT" \ + --occ_action_contrast_margin "$OCC_ACTION_CONTRAST_MARGIN" \ + --occ_action_negative "$OCC_ACTION_NEGATIVE" \ + --occ_action_negative_sigma "$OCC_ACTION_NEGATIVE_SIGMA" \ + --occ_action_negative_k "$OCC_ACTION_NEGATIVE_K" \ + --actor_loss "$MODE" --actor_q_transform raw \ + --alpha "$ALPHA" --expectile "$EXPECTILE" --actor_after "$ACTOR_AFTER" \ + "${EXTRA_ARGS[@]}" \ + --gamma 0.99 --gamma_spectrum_lo "$GAMMA_LO" \ + --gamma_sampler "$GAMMA_SAMPLER" \ + --gamma_task_fraction "$GAMMA_TASK_FRACTION" \ + --gamma_horizons "$GAMMA_HORIZONS" \ + --recursion off --batch_size 256 --occ_batch 2048 \ + --train_steps "$TRAIN_STEPS" --eval_interval 50000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --ckpt_archive_every "$ARCHIVE_EVERY" \ + --variant_tag "$TAG" --wandb_mode "$WANDB_MODE" + +if [ "${AUDIT_ARCHIVES:-1}" = 1 ]; then + CKPT_STEM=${CKPT%.pkl} + for ((STEP=ARCHIVE_EVERY; STEP<=TRAIN_STEPS; STEP+=ARCHIVE_EVERY)); do + ARCHIVE=${CKPT_STEM}_step${STEP}.pkl + AUDIT=ogbench_genq/experiments/visual-cube-single-play-v0/${TAG}_step${STEP}_distill_audit.json + [ -s "$ARCHIVE" ] || { + echo "[visual-index-distill] missing archived checkpoint: $ARCHIVE" >&2 + exit 1 + } + echo "[visual-index-distill] audit step=$STEP -> $AUDIT" + "$PY" -u ogbench_genq/genq/diagnose_visual_distilled_policy.py \ + --ckpt "$ARCHIVE" --require_index_delta "$READER_DELTA" \ + --rows 128 --samples 16 --episodes 100 --horizons 10,25,50,100 \ + --out "$AUDIT" + done +elif [ "${AUDIT_ARCHIVES:-1}" != 0 ]; then + echo "[visual-index-distill] AUDIT_ARCHIVES must be 0 or 1" >&2 + exit 2 +fi + +echo "[visual-index-distill] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_occupancy_recursion.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_occupancy_recursion.sh new file mode 100644 index 0000000000000000000000000000000000000000..25b4eb0519b559fcf05fb199524c207148ffdc52 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_occupancy_recursion.sh @@ -0,0 +1,280 @@ +#!/bin/bash +# Fair pixels-only visual Recursive Successor Model (RSM) recursion. +# +# The occupancy is a discount-conditioned flow over frozen encoder futures: +# hidden (primary): p(h_future | h_state, action, h_goal, discount) +# compact (control): p(z_future | z_state, action, z_goal, discount) +# A beta-conditioned sample is already the next recursive state. No +# completion/forward model, temporal-difference target, proprioception, cube +# coordinate, or reward label enters the occupancy fit. At termination only, +# hidden samples pass through the frozen encoder fc_1 to compact z and the +# frozen local index-reward reader. +set -euo pipefail + +CF=${CF:-/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree} +REC=${REC:-/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion} +cd "$CF" + +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=${XLA_PYTHON_CLIENT_MEM_FRACTION:-0.90} +export WANDB_MODE=${WANDB_MODE:-disabled} +export PYTHONUNBUFFERED=1 + +PY=${PY:-$REC/.ogbench_venv/bin/python} +ENV=visual-cube-single-play-v0 +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=ckpt/latents_${BASE}_stateh256.npz +ENC=ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz + +MODE=${MODE:-ddpgbc_distill} +REC_STATE=${REC_STATE:-hidden} +READER_DELTA=${READER_DELTA:-2} +READER_TAG=${READER_TAG:-indexd${READER_DELTA}} +SEED=${SEED:-0} +TRAIN_STEPS=${TRAIN_STEPS:-150000} +RDEC_SAMPLES=${RDEC_SAMPLES:-16} +FLOW_STEPS=${FLOW_STEPS:-25} +OCC_LAYERS=${OCC_LAYERS:-4} +OCC_ACTION_CONTRAST_WEIGHT=${OCC_ACTION_CONTRAST_WEIGHT:-0.5} +OCC_ACTION_CONTRAST_MARGIN=${OCC_ACTION_CONTRAST_MARGIN:-0.1} +OCC_ACTION_NEGATIVE=${OCC_ACTION_NEGATIVE:-local} +OCC_ACTION_NEGATIVE_SIGMA=${OCC_ACTION_NEGATIVE_SIGMA:-0.3} +OCC_ACTION_NEGATIVE_K=${OCC_ACTION_NEGATIVE_K:-2} +OCC_ACTOR_GOAL_FRACTION=${OCC_ACTOR_GOAL_FRACTION:-0.0} +OCC_READER_METRIC_WEIGHT=${OCC_READER_METRIC_WEIGHT:-0.0} +GAMMA=${GAMMA:-0.99} +BETA=${BETA:-0.98} +REC_DEPTH=${REC_DEPTH:-12} +REC_AFTER=${REC_AFTER:-50000} +REC_GUARD=${REC_GUARD:-ema} +BETA_SAMPLE_PROB=${BETA_SAMPLE_PROB:-0.25} +GAMMA_SAMPLER=${GAMMA_SAMPLER:-stratified_bins} +GAMMA_HORIZONS=${GAMMA_HORIZONS:-2,4,8,16,32,64} +GAMMA_TASK_FRACTION=${GAMMA_TASK_FRACTION:-0.5} +GAMMA_LO=${GAMMA_LO:-} +ALPHA=${ALPHA:-1.0} +EXPECTILE=${EXPECTILE:-0.9} +ACTOR_AFTER=${ACTOR_AFTER:-50000} +DISTILL_ACTOR_GOALS=${DISTILL_ACTOR_GOALS:-1} +DISTILL_ACTOR_ACTIONS=${DISTILL_ACTOR_ACTIONS:-} +DISTILL_ACTOR_ACTION_K=${DISTILL_ACTOR_ACTION_K:-2} +DISTILL_ACTOR_ACTION_SIGMA=${DISTILL_ACTOR_ACTION_SIGMA:-0.3} +DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT=${DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT:-1.0} +ARCHIVE_EVERY=${ARCHIVE_EVERY:-25000} +RESUME_CKPT=${RESUME_CKPT:-} +RESUME_CKPT_SHA256=${RESUME_CKPT_SHA256:-} +RDEC_SHA256=${RDEC_SHA256:-} + +TASK_FRAC_TAG=${GAMMA_TASK_FRACTION//./p} +case "$GAMMA_SAMPLER" in + stratified_bins) + GAMMA_LO=${GAMMA_LO:-0.50} + HORIZON_TAG=${GAMMA_HORIZONS//,/-} + GAMMA_RECIPE_TAG=strath${HORIZON_TAG}tf${TASK_FRAC_TAG} + ;; + legacy_log_uniform) + GAMMA_LO=${GAMMA_LO:-0.90} + GAMMA_LO_TAG=${GAMMA_LO//./p} + GAMMA_RECIPE_TAG=legacylo${GAMMA_LO_TAG}tf${TASK_FRAC_TAG} + ;; + *) + echo "[visual-occ-rec] unsupported GAMMA_SAMPLER=$GAMMA_SAMPLER" >&2 + exit 2 + ;; +esac + +case "$MODE" in + ddpgbc_distill) + MODE_TAG=distill + DISTILL_ACTOR_ACTIONS=${DISTILL_ACTOR_ACTIONS:-1} + case "$DISTILL_ACTOR_GOALS" in + 1) + DISTILL_ARGS=(--distill_actor_goals) + ACTOR_GOAL_TAG=ag1 + ;; + 0) + DISTILL_ARGS=(--no_distill_actor_goals) + ACTOR_GOAL_TAG=ag0 + ;; + *) + echo "[visual-occ-rec] DISTILL_ACTOR_GOALS must be 0 or 1" >&2 + exit 2 + ;; + esac + ;; + ddpgbc) + MODE_TAG=direct + DISTILL_ACTOR_ACTIONS=${DISTILL_ACTOR_ACTIONS:-0} + DISTILL_ARGS=() + ACTOR_GOAL_TAG=ag0 + ;; + *) + echo "[visual-occ-rec] MODE must be ddpgbc_distill or ddpgbc" >&2 + exit 2 + ;; +esac + +case "$DISTILL_ACTOR_ACTIONS" in + 1) + if [ "$MODE" != ddpgbc_distill ] || [ "$DISTILL_ACTOR_GOALS" != 1 ]; then + echo "[visual-occ-rec] actor-action scorer support requires ddpgbc_distill and DISTILL_ACTOR_GOALS=1" >&2 + exit 2 + fi + AA_SIGMA_TAG=${DISTILL_ACTOR_ACTION_SIGMA//./p} + AA_PAIR_TAG=${DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT//./p} + ACTION_SUPPORT_TAG=as1k${DISTILL_ACTOR_ACTION_K}s${AA_SIGMA_TAG}pw${AA_PAIR_TAG} + DISTILL_ARGS+=( + --distill_actor_actions + --distill_actor_action_k "$DISTILL_ACTOR_ACTION_K" + --distill_actor_action_sigma "$DISTILL_ACTOR_ACTION_SIGMA" + --distill_actor_action_pairwise_weight \ + "$DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT" + ) + ;; + 0) + ACTION_SUPPORT_TAG=as0 + if [ "$MODE" = ddpgbc_distill ]; then + DISTILL_ARGS+=(--no_distill_actor_actions) + fi + ;; + *) + echo "[visual-occ-rec] DISTILL_ACTOR_ACTIONS must be 0 or 1" >&2 + exit 2 + ;; +esac + +case "$REC_STATE" in + hidden) + STATE_TAG=h256 + GOAL_ARGS=(--goal_hidden) + OCC_HIDDEN=${OCC_HIDDEN:-512} + ;; + compact) + STATE_TAG=z8 + GOAL_ARGS=() + OCC_HIDDEN=${OCC_HIDDEN:-256} + ;; + *) + echo "[visual-occ-rec] REC_STATE must be hidden or compact" >&2 + exit 2 + ;; +esac + +case "$READER_TAG" in + *[!A-Za-z0-9._-]*|'') + echo "[visual-occ-rec] READER_TAG must use only A-Z, a-z, 0-9, dot, underscore, or hyphen" >&2 + exit 2 + ;; +esac +RDEC=${RDEC:-ckpt/rdec_${BASE}_${READER_TAG}.npz} +BETA_MASS_TAG=${BETA_SAMPLE_PROB//./p} +AC_WEIGHT_TAG=${OCC_ACTION_CONTRAST_WEIGHT//./p} +AC_MARGIN_TAG=${OCC_ACTION_CONTRAST_MARGIN//./p} +AC_SIGMA_TAG=${OCC_ACTION_NEGATIVE_SIGMA//./p} +OCC_ACTOR_GOAL_TAG=${OCC_ACTOR_GOAL_FRACTION//./p} +OCC_READER_METRIC_TAG=${OCC_READER_METRIC_WEIGHT//./p} +if [ "$OCC_ACTION_NEGATIVE" = actor_local ]; then + AC_NEGATIVE_TAG=actorlocalk${OCC_ACTION_NEGATIVE_K}s${AC_SIGMA_TAG} +else + AC_NEGATIVE_TAG=${OCC_ACTION_NEGATIVE}${AC_SIGMA_TAG} +fi +DEFAULT_TAG=${BASE}_flow${FLOW_STEPS}_${STATE_TAG}_oh${OCC_HIDDEN}l${OCC_LAYERS}_acw${AC_WEIGHT_TAG}m${AC_MARGIN_TAG}_${AC_NEGATIVE_TAG}_og${OCC_ACTOR_GOAL_TAG}_rm${OCC_READER_METRIC_TAG}_${READER_TAG}_occ-rec_g${GAMMA}_b${BETA}_bm${BETA_MASS_TAG}_d${REC_DEPTH}_ra${REC_AFTER}_rg${REC_GUARD}_${MODE_TAG}_a${ALPHA}_e${EXPECTILE}_aa${ACTOR_AFTER}_${ACTOR_GOAL_TAG}_${ACTION_SUPPORT_TAG}_${GAMMA_RECIPE_TAG}_m${RDEC_SAMPLES}_s${SEED} +TAG=${TAG:-$DEFAULT_TAG} +CKPT=${CKPT:-ckpt/rsm_${TAG}.pkl} + +for artifact in "$LAT" "$ENC" "$RDEC"; do + [ -s "$artifact" ] || { + echo "[visual-occ-rec] missing artifact: $artifact" >&2 + exit 1 + } +done + +RESUME_ARGS=() +if [ -n "$RESUME_CKPT" ] || [ -n "$RESUME_CKPT_SHA256" ]; then + [ -n "$RESUME_CKPT" ] && [ -n "$RESUME_CKPT_SHA256" ] || { + echo "[visual-occ-rec] RESUME_CKPT and RESUME_CKPT_SHA256 must be set together" >&2 + exit 2 + } + case "$RESUME_CKPT" in + /*_step50000.pkl) ;; + *) + echo "[visual-occ-rec] gated resume source must be an absolute *_step50000.pkl archive" >&2 + exit 2 + ;; + esac + [[ "$RESUME_CKPT_SHA256" =~ ^[0-9a-f]{64}$ ]] || { + echo "[visual-occ-rec] RESUME_CKPT_SHA256 must be a lowercase SHA-256 digest" >&2 + exit 2 + } + [ -f "$RESUME_CKPT" ] || { + echo "[visual-occ-rec] gated resume source does not exist: $RESUME_CKPT" >&2 + exit 1 + } + ACTUAL_RESUME_SHA256=$(sha256sum "$RESUME_CKPT") + ACTUAL_RESUME_SHA256=${ACTUAL_RESUME_SHA256%% *} + [ "$ACTUAL_RESUME_SHA256" = "$RESUME_CKPT_SHA256" ] || { + echo "[visual-occ-rec] gated resume source checksum mismatch: expected=$RESUME_CKPT_SHA256 actual=$ACTUAL_RESUME_SHA256" >&2 + exit 1 + } + SOURCE_REAL=$(realpath "$RESUME_CKPT") + DESTINATION_REAL=$(realpath -m "$CKPT") + [ "$SOURCE_REAL" != "$DESTINATION_REAL" ] || { + echo "[visual-occ-rec] resume source and destination checkpoint must be distinct" >&2 + exit 2 + } + RESUME_ARGS=( + --resume_ckpt "$RESUME_CKPT" + --resume_ckpt_sha256 "$RESUME_CKPT_SHA256" + ) +fi + +if [ -n "$RDEC_SHA256" ]; then + ACTUAL_RDEC_SHA256=$(sha256sum "$RDEC") + ACTUAL_RDEC_SHA256=${ACTUAL_RDEC_SHA256%% *} + [ "$ACTUAL_RDEC_SHA256" = "$RDEC_SHA256" ] || { + echo "[visual-occ-rec] reward reader checksum mismatch: expected=$RDEC_SHA256 actual=$ACTUAL_RDEC_SHA256 path=$RDEC" >&2 + exit 1 + } +fi + +echo "[visual-occ-rec] TRAIN-ONLY proposal; no scheduler submission in this script" +echo "[visual-occ-rec] tag=$TAG checkpoint=$CKPT state=$REC_STATE mode=$MODE reader_tag=$READER_TAG reader=$RDEC" +echo "[visual-occ-rec] occupancy_actor_goal_fraction=$OCC_ACTOR_GOAL_FRACTION reader_metric_weight=$OCC_READER_METRIC_WEIGHT" +if [ -n "$RESUME_CKPT" ]; then + echo "[visual-occ-rec] immutable_resume_source=$RESUME_CKPT source_sha256=$RESUME_CKPT_SHA256 destination=$CKPT" +fi +"$PY" -u ogbench_genq/rsm.py \ + --env "$ENV" --seed "$SEED" \ + --latent_npz "$LAT" --pixel_encoder "$ENC" --drop_proprio \ + "${GOAL_ARGS[@]}" --latent_update frozen \ + --reward_decoder "$RDEC" --rdec_samples "$RDEC_SAMPLES" \ + --occupancy_model flow --occ_hidden "$OCC_HIDDEN" --occ_layers "$OCC_LAYERS" \ + --flow_steps "$FLOW_STEPS" \ + --occ_action_contrast_weight "$OCC_ACTION_CONTRAST_WEIGHT" \ + --occ_action_contrast_margin "$OCC_ACTION_CONTRAST_MARGIN" \ + --occ_action_negative "$OCC_ACTION_NEGATIVE" \ + --occ_action_negative_sigma "$OCC_ACTION_NEGATIVE_SIGMA" \ + --occ_action_negative_k "$OCC_ACTION_NEGATIVE_K" \ + --occ_actor_goal_fraction "$OCC_ACTOR_GOAL_FRACTION" \ + --occ_reader_metric_weight "$OCC_READER_METRIC_WEIGHT" \ + --actor_loss "$MODE" --actor_q_transform raw \ + --alpha "$ALPHA" --expectile "$EXPECTILE" --actor_after "$ACTOR_AFTER" \ + "${DISTILL_ARGS[@]}" \ + --gamma "$GAMMA" --gamma_spectrum_lo "$GAMMA_LO" \ + --gamma_sampler "$GAMMA_SAMPLER" \ + --gamma_task_fraction "$GAMMA_TASK_FRACTION" \ + --gamma_horizons "$GAMMA_HORIZONS" \ + --recursion occupancy --recursion_state "$REC_STATE" \ + --rec_beta "$BETA" --rec_beta_sample_prob "$BETA_SAMPLE_PROB" \ + --rec_after "$REC_AFTER" --rec_max_depth "$REC_DEPTH" \ + --rec_guard "$REC_GUARD" \ + --batch_size 256 --occ_batch 2048 \ + --train_steps "$TRAIN_STEPS" --eval_interval 50000 \ + --eval_episodes 50 --eval_episodes_periodic 3 --train_only \ + --ckpt "$CKPT" --ckpt_every 10000 \ + --ckpt_archive_every "$ARCHIVE_EVERY" \ + "${RESUME_ARGS[@]}" \ + --variant_tag "$TAG" --wandb_mode "$WANDB_MODE" + +echo "[visual-occ-rec] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_pixel_actor.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_pixel_actor.sh new file mode 100644 index 0000000000000000000000000000000000000000..145a67d8e98cb4901f1d2e4d5126d207efedcc57 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_pixel_actor.sh @@ -0,0 +1,394 @@ +#!/bin/bash +# One-hop visual Recursive Successor Model (RSM) with a final trainable pixel +# actor and a reward-predictive latent occupancy. +# +# The actor is the exact visual GCIQL IMPALA-small architecture, but its Q +# signal is a direct Monte-Carlo expectation under a discount-conditioned flow +# occupancy and frozen index-reward reader. There is no Bellman target, +# temporal-difference bootstrap, coordinate, proprioception, simulator state, +# forward model, or image reconstruction. Occupancy and actor update in the +# same fused step. LATENT_UPDATE=frozen and LATENT_UPDATE=joint are the two +# intended representation arms. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +cd "$ROOT" + +DRY_RUN=0 +if [ "${1:-}" = "--dry-run" ]; then + DRY_RUN=1 + shift +fi +if [ "$#" -ne 0 ]; then + echo "usage: $0 [--dry-run]" >&2 + exit 2 +fi + +PY=${PY:-/proj/inf-scaling/zwhong/projs/gen_q/.ogbench_venv/bin/python} +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=${XLA_PYTHON_CLIENT_MEM_FRACTION:-0.90} +export WANDB_MODE=${WANDB_MODE:-disabled} +export PYTHONUNBUFFERED=1 + +ENV=visual-cube-single-play-v0 +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +LAT=${LAT:-$ROOT/ckpt/latents_${BASE}_stateh256.npz} +ENC=${ENC:-$ROOT/ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz} +PIXEL_DATASET=${PIXEL_DATASET:-/proj/inf-scaling/zwhong/.ogbench/data/visual-cube-single-play-v0.npz} +LAT_SHA256=${LAT_SHA256:-8b19aa38a9df797fdbef230506e18357efa6622b6fe6b2b011e8af5f90908f2d} +ENC_SHA256=${ENC_SHA256:-c81cfa6048673706a3842e58d36cc2ecff999e51d2a897dd8ba099c8447e39b2} +PIXEL_DATASET_SHA256=${PIXEL_DATASET_SHA256:-8de92b80f0c11d32b8621a98c473006313771a32da11a333b5d473db197d95c0} +READER_TAG=${READER_TAG:-indexd4_diagmetric} +RDEC=${RDEC:-$ROOT/ckpt/rdec_${BASE}_${READER_TAG}.npz} +RDEC_SHA256=${RDEC_SHA256:-9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7} + +SEED=${SEED:-0} +TRAIN_STEPS=${TRAIN_STEPS:-150000} +LATENT_UPDATE=${LATENT_UPDATE:-frozen} +GOAL_HIDDEN=${GOAL_HIDDEN:-1} +OCC_TARGET_SPACE=${OCC_TARGET_SPACE:-absolute_future} +LATENT_HIDDEN=${LATENT_HIDDEN:-64} +LATENT_LR=${LATENT_LR:-3e-5} +LATENT_GOAL_WEIGHT=${LATENT_GOAL_WEIGHT:-0.1} +LATENT_ANCHOR_WEIGHT=${LATENT_ANCHOR_WEIGHT:-0.01} +PIXEL_ACTOR_P_AUG=${PIXEL_ACTOR_P_AUG:-0.5} +PIXEL_ACTOR_INIT_CKPT=${PIXEL_ACTOR_INIT_CKPT:-} +PIXEL_ACTOR_INIT_CKPT_SHA256=${PIXEL_ACTOR_INIT_CKPT_SHA256:-} +INIT_OCCUPANCY_CKPT=${INIT_OCCUPANCY_CKPT:-} +INIT_OCCUPANCY_CKPT_SHA256=${INIT_OCCUPANCY_CKPT_SHA256:-} + +FLOW_STEPS=${FLOW_STEPS:-25} +if [ "$OCC_TARGET_SPACE" = goal_relative_reader_metric ]; then + OCC_HIDDEN=${OCC_HIDDEN:-256} + OCC_LAYERS=${OCC_LAYERS:-4} +else + OCC_HIDDEN=${OCC_HIDDEN:-512} + OCC_LAYERS=${OCC_LAYERS:-4} +fi +OCC_ACTION_CONTRAST_WEIGHT=${OCC_ACTION_CONTRAST_WEIGHT:-0.5} +OCC_ACTION_CONTRAST_MARGIN=${OCC_ACTION_CONTRAST_MARGIN:-0.1} +OCC_ACTION_NEGATIVE_SIGMA=${OCC_ACTION_NEGATIVE_SIGMA:-0.3} +OCC_ACTION_NEGATIVE_K=${OCC_ACTION_NEGATIVE_K:-2} +OCC_ACTOR_GOAL_FRACTION=${OCC_ACTOR_GOAL_FRACTION:-0.5} +OCC_READER_METRIC_WEIGHT=${OCC_READER_METRIC_WEIGHT:-0.0} +OCC_READER_HIT_WEIGHT=${OCC_READER_HIT_WEIGHT:-0.0} +RDEC_SAMPLES=${RDEC_SAMPLES:-16} + +ALPHA=${ALPHA:-1.0} +EXPECTILE=${EXPECTILE:-0.9} +DISTILL_SCORER_INPUT=${DISTILL_SCORER_INPUT:-latent} +DISTILL_ACTOR_ACTIONS=${DISTILL_ACTOR_ACTIONS:-1} +DISTILL_ACTOR_ACTION_K=${DISTILL_ACTOR_ACTION_K:-2} +DISTILL_ACTOR_ACTION_SIGMA=${DISTILL_ACTOR_ACTION_SIGMA:-0.3} +DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT=${DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT:-1.0} +if [ "$OCC_TARGET_SPACE" = goal_relative_reader_metric ]; then + DISTILL_EMPIRICAL_INDEX_WEIGHT=${DISTILL_EMPIRICAL_INDEX_WEIGHT:-1.0} +else + DISTILL_EMPIRICAL_INDEX_WEIGHT=${DISTILL_EMPIRICAL_INDEX_WEIGHT:-0.0} +fi +if [ -z "${ACTOR_AFTER+x}" ]; then + if [ -n "$PIXEL_ACTOR_INIT_CKPT" ]; then + ACTOR_AFTER=0 + else + ACTOR_AFTER=50000 + fi +fi + +case "$DISTILL_SCORER_INPUT" in + latent) + SCORER_TAG=latentscorer + SCORER_ARGS=(--distill_scorer_input latent) + ;; + pixels) + [ "$DISTILL_EMPIRICAL_INDEX_WEIGHT" = 1.0 ] || { + echo "[visual-pixel-rsm] pixel scorer requires DISTILL_EMPIRICAL_INDEX_WEIGHT=1.0" >&2 + exit 2 + } + SCORER_TAG=pixelscorer + SCORER_ARGS=(--distill_scorer_input pixels) + ;; + *) + echo "[visual-pixel-rsm] DISTILL_SCORER_INPUT must be latent or pixels" >&2 + exit 2 + ;; +esac + +case "$DISTILL_ACTOR_ACTIONS" in + 1) + SCORER_SUPPORT_TAG=occsupport + SCORER_SUPPORT_ARGS=(--distill_actor_actions) + ;; + 0) + SCORER_SUPPORT_TAG=behavioronly + SCORER_SUPPORT_ARGS=(--no_distill_actor_actions) + ;; + *) + echo "[visual-pixel-rsm] DISTILL_ACTOR_ACTIONS must be 0 or 1" >&2 + exit 2 + ;; +esac + +GAMMA=${GAMMA:-0.99} +BETA=${BETA:-0.98} +REWARD_METRIC_AUX_ALLOCATION=${REWARD_METRIC_AUX_ALLOCATION:-uniform} +if [ "$OCC_TARGET_SPACE" = goal_relative_reader_metric ]; then + GAMMA_LO=${GAMMA_LO:-0.875} + GAMMA_TASK_FRACTION=${GAMMA_TASK_FRACTION:-0.5} + REC_BETA_SAMPLE_PROB=${REC_BETA_SAMPLE_PROB:-0.25} + GAMMA_HORIZONS=${GAMMA_HORIZONS:-8,16,32,64} + GAMMA_SAMPLER=${GAMMA_SAMPLER:-reward_metric_endpoints} +else + GAMMA_LO=${GAMMA_LO:-0.50} + GAMMA_TASK_FRACTION=${GAMMA_TASK_FRACTION:-0.5} + REC_BETA_SAMPLE_PROB=${REC_BETA_SAMPLE_PROB:-0.25} + GAMMA_HORIZONS=${GAMMA_HORIZONS:-2,4,8,16,32,50,64} + GAMMA_SAMPLER=${GAMMA_SAMPLER:-stratified_bins} +fi +CKPT_EVERY=${CKPT_EVERY:-10000} +ARCHIVE_EVERY=${ARCHIVE_EVERY:-25000} + +case "$LATENT_UPDATE" in + frozen) + LATENT_TAG=frozen + LATENT_ARGS=(--latent_update frozen) + ;; + joint|rich_adapter) + LATENT_TAG=joint + LATENT_ARGS=( + --latent_update rich_adapter + --latent_hidden "$LATENT_HIDDEN" + --latent_lr "$LATENT_LR" + --latent_goal_weight "$LATENT_GOAL_WEIGHT" + --latent_anchor_weight "$LATENT_ANCHOR_WEIGHT" + ) + ;; + *) + echo "[visual-pixel-rsm] LATENT_UPDATE must be frozen or joint" >&2 + exit 2 + ;; +esac + +case "$GOAL_HIDDEN" in + 1) + FUTURE_TAG=h256 + GOAL_ARGS=(--goal_hidden) + ;; + 0) + [ "$LATENT_UPDATE" = frozen ] || { + echo "[visual-pixel-rsm] compact z8 future requires LATENT_UPDATE=frozen" >&2 + exit 2 + } + FUTURE_TAG=z8 + GOAL_ARGS=() + ;; + *) + echo "[visual-pixel-rsm] GOAL_HIDDEN must be 0 or 1" >&2 + exit 2 + ;; +esac + +case "$OCC_TARGET_SPACE" in + absolute_future) + TARGET_TAG=abs + TARGET_ARGS=(--occ_target_space absolute_future) + ;; + goal_relative_reader_metric) + [ "$LATENT_UPDATE" = frozen ] || { + echo "[visual-pixel-rsm] reward-metric target requires LATENT_UPDATE=frozen" >&2 + exit 2 + } + [ "$GOAL_HIDDEN" = 1 ] || { + echo "[visual-pixel-rsm] reward-metric target requires GOAL_HIDDEN=1" >&2 + exit 2 + } + [ "$OCC_HIDDEN" = 256 ] && [ "$OCC_LAYERS" = 4 ] || { + echo "[visual-pixel-rsm] reward-metric target requires OCC_HIDDEN=256 OCC_LAYERS=4" >&2 + exit 2 + } + [ "$GAMMA" = 0.99 ] && [ "$BETA" = 0.98 ] || { + echo "[visual-pixel-rsm] reward-metric target requires GAMMA=0.99 BETA=0.98" >&2 + exit 2 + } + [ "$GAMMA_SAMPLER" = reward_metric_endpoints ] && \ + [ "$GAMMA_HORIZONS" = 8,16,32,64 ] || { + echo "[visual-pixel-rsm] reward-metric target requires its exact endpoint sampler" >&2 + exit 2 + } + case "$REWARD_METRIC_AUX_ALLOCATION" in + uniform|sqrt_h) + ;; + *) + echo "[visual-pixel-rsm] REWARD_METRIC_AUX_ALLOCATION must be uniform or sqrt_h" >&2 + exit 2 + ;; + esac + TARGET_TAG=metricu_${REWARD_METRIC_AUX_ALLOCATION} + TARGET_ARGS=( + --occ_target_space goal_relative_reader_metric + --reward_metric_aux_allocation "$REWARD_METRIC_AUX_ALLOCATION" + ) + ;; + *) + echo "[visual-pixel-rsm] OCC_TARGET_SPACE must be absolute_future or goal_relative_reader_metric" >&2 + exit 2 + ;; +esac + +INIT_ARGS=() +INIT_TAG=fresh +if [ -n "$PIXEL_ACTOR_INIT_CKPT" ] || \ + [ -n "$PIXEL_ACTOR_INIT_CKPT_SHA256" ]; then + [ -n "$PIXEL_ACTOR_INIT_CKPT" ] && \ + [ -n "$PIXEL_ACTOR_INIT_CKPT_SHA256" ] || { + echo "[visual-pixel-rsm] pixel init path and SHA-256 must be set together" >&2 + exit 2 + } + [[ "$PIXEL_ACTOR_INIT_CKPT_SHA256" =~ ^[0-9a-f]{64}$ ]] || { + echo "[visual-pixel-rsm] pixel init SHA-256 must be lowercase hex" >&2 + exit 2 + } + [ -s "$PIXEL_ACTOR_INIT_CKPT" ] || { + echo "[visual-pixel-rsm] missing pixel init: $PIXEL_ACTOR_INIT_CKPT" >&2 + exit 1 + } + ACTUAL_INIT_SHA=$(sha256sum "$PIXEL_ACTOR_INIT_CKPT") + ACTUAL_INIT_SHA=${ACTUAL_INIT_SHA%% *} + [ "$ACTUAL_INIT_SHA" = "$PIXEL_ACTOR_INIT_CKPT_SHA256" ] || { + echo "[visual-pixel-rsm] pixel init checksum mismatch" >&2 + exit 1 + } + INIT_ARGS=( + --pixel_actor_init_ckpt "$PIXEL_ACTOR_INIT_CKPT" + --pixel_actor_init_ckpt_sha256 "$PIXEL_ACTOR_INIT_CKPT_SHA256" + ) + INIT_TAG=gcbc +fi + +OCC_INIT_ARGS=() +OCC_INIT_TAG=occfresh +if [ -n "$INIT_OCCUPANCY_CKPT" ] || \ + [ -n "$INIT_OCCUPANCY_CKPT_SHA256" ]; then + [ "$LATENT_UPDATE" = frozen ] || { + echo "[visual-pixel-rsm] occupancy transplant requires LATENT_UPDATE=frozen" >&2 + exit 2 + } + [ -n "$INIT_OCCUPANCY_CKPT" ] && \ + [ -n "$INIT_OCCUPANCY_CKPT_SHA256" ] || { + echo "[visual-pixel-rsm] occupancy init path and SHA-256 must be set together" >&2 + exit 2 + } + [[ "$INIT_OCCUPANCY_CKPT_SHA256" =~ ^[0-9a-f]{64}$ ]] || { + echo "[visual-pixel-rsm] occupancy init SHA-256 must be lowercase hex" >&2 + exit 2 + } + OCC_INIT_ARGS=( + --init_occupancy_ckpt "$INIT_OCCUPANCY_CKPT" + --init_occupancy_ckpt_sha256 "$INIT_OCCUPANCY_CKPT_SHA256" + ) + OCC_INIT_TAG=occinit +fi + +verify_sha256() { + local label=$1 + local path=$2 + local expected=$3 + [ -s "$path" ] || { + echo "[visual-pixel-rsm] missing $label artifact: $path" >&2 + exit 1 + } + local actual + actual=$(sha256sum "$path") + actual=${actual%% *} + [ "$actual" = "$expected" ] || { + echo "[visual-pixel-rsm] $label checksum mismatch: expected=$expected actual=$actual" >&2 + exit 1 + } +} +verify_sha256 latent "$LAT" "$LAT_SHA256" +verify_sha256 encoder "$ENC" "$ENC_SHA256" +verify_sha256 pixel-dataset "$PIXEL_DATASET" "$PIXEL_DATASET_SHA256" +verify_sha256 reward-reader "$RDEC" "$RDEC_SHA256" +if [ -n "$INIT_OCCUPANCY_CKPT" ]; then + verify_sha256 occupancy-init \ + "$INIT_OCCUPANCY_CKPT" "$INIT_OCCUPANCY_CKPT_SHA256" +fi + +DEFAULT_TAG=${BASE}_pixelactor_${SCORER_TAG}_${SCORER_SUPPORT_TAG}_${INIT_TAG}_${OCC_INIT_TAG}_${LATENT_TAG}_${FUTURE_TAG}_${TARGET_TAG}_flowh${OCC_HIDDEN}l${OCC_LAYERS}_og${OCC_ACTOR_GOAL_FRACTION}_rm${OCC_READER_METRIC_WEIGHT}_rh${OCC_READER_HIT_WEIGHT}_ei${DISTILL_EMPIRICAL_INDEX_WEIGHT}_gs${GAMMA_SAMPLER}_gt${GAMMA_TASK_FRACTION}_bp${REC_BETA_SAMPLE_PROB}_g${GAMMA}_b${BETA}_s${SEED} +TAG=${TAG:-$DEFAULT_TAG} +case "$TAG" in + *[!A-Za-z0-9._-]*|'') + echo "[visual-pixel-rsm] TAG contains unsafe characters" >&2 + exit 2 + ;; +esac +CKPT=${CKPT:-$ROOT/ckpt/rsm_${TAG}.pkl} + +COMMAND=( + "$PY" -u ogbench_genq/rsm.py + --env "$ENV" --seed "$SEED" + --latent_npz "$LAT" --pixel_encoder "$ENC" + --latent_npz_sha256 "$LAT_SHA256" + --pixel_encoder_sha256 "$ENC_SHA256" + --pixel_dataset "$PIXEL_DATASET" + --pixel_dataset_sha256 "$PIXEL_DATASET_SHA256" + --drop_proprio + "${GOAL_ARGS[@]}" + --actor_input pixels --pixel_actor_p_aug "$PIXEL_ACTOR_P_AUG" + "${INIT_ARGS[@]}" + "${OCC_INIT_ARGS[@]}" + "${LATENT_ARGS[@]}" + --reward_decoder "$RDEC" --rdec_samples "$RDEC_SAMPLES" + --occupancy_model flow --occ_hidden "$OCC_HIDDEN" + --occ_layers "$OCC_LAYERS" --flow_steps "$FLOW_STEPS" + "${TARGET_ARGS[@]}" + --occ_action_contrast_weight "$OCC_ACTION_CONTRAST_WEIGHT" + --occ_action_contrast_margin "$OCC_ACTION_CONTRAST_MARGIN" + --occ_action_negative actor_local + --occ_action_negative_sigma "$OCC_ACTION_NEGATIVE_SIGMA" + --occ_action_negative_k "$OCC_ACTION_NEGATIVE_K" + --occ_actor_goal_fraction "$OCC_ACTOR_GOAL_FRACTION" + --occ_reader_metric_weight "$OCC_READER_METRIC_WEIGHT" + --occ_reader_hit_weight "$OCC_READER_HIT_WEIGHT" + --actor_loss ddpgbc_distill --actor_q_transform raw + --alpha "$ALPHA" --expectile "$EXPECTILE" + --actor_after "$ACTOR_AFTER" + --distill_actor_goals + "${SCORER_ARGS[@]}" + "${SCORER_SUPPORT_ARGS[@]}" + --distill_actor_action_k "$DISTILL_ACTOR_ACTION_K" + --distill_actor_action_sigma "$DISTILL_ACTOR_ACTION_SIGMA" + --distill_actor_action_pairwise_weight + "$DISTILL_ACTOR_ACTION_PAIRWISE_WEIGHT" + --distill_empirical_index_weight "$DISTILL_EMPIRICAL_INDEX_WEIGHT" + --gamma "$GAMMA" --rec_beta "$BETA" + --rec_beta_sample_prob "$REC_BETA_SAMPLE_PROB" + --gamma_spectrum_lo "$GAMMA_LO" + --gamma_sampler "$GAMMA_SAMPLER" + --gamma_task_fraction "$GAMMA_TASK_FRACTION" + --gamma_horizons "$GAMMA_HORIZONS" + --recursion off + --batch_size 256 --occ_batch 2048 + --train_steps "$TRAIN_STEPS" --eval_interval 50000 + --eval_episodes 50 --eval_episodes_periodic 3 --train_only + --ckpt "$CKPT" --ckpt_every "$CKPT_EVERY" + --ckpt_archive_every "$ARCHIVE_EVERY" + --variant_tag "$TAG" --wandb_mode "$WANDB_MODE" +) + +echo "[visual-pixel-rsm] one-hop joint actor+occupancy; no TD; pixels-only" +printf '[visual-pixel-rsm] latent_update=%s future=%s target=%s scorer=%s scorer_support=%s init=%s gamma_sampler=%s task_fraction=%s beta_fraction=%s metric_aux=%s endpoint_hit_weight=%s empirical_index_weight=%s tag=%s checkpoint=%s\n' \ + "$LATENT_TAG" "$FUTURE_TAG" "$OCC_TARGET_SPACE" "$DISTILL_SCORER_INPUT" \ + "$SCORER_SUPPORT_TAG" "$INIT_TAG" "$GAMMA_SAMPLER" \ + "$GAMMA_TASK_FRACTION" "$REC_BETA_SAMPLE_PROB" "$REWARD_METRIC_AUX_ALLOCATION" \ + "$OCC_READER_HIT_WEIGHT" "$DISTILL_EMPIRICAL_INDEX_WEIGHT" "$TAG" "$CKPT" +printf '[visual-pixel-rsm] command=' +printf ' %q' "${COMMAND[@]}" +printf '\n' +if [ "$DRY_RUN" = 1 ]; then + echo "[visual-pixel-rsm] dry-run complete; no training or submission" + exit 0 +fi + +"${COMMAND[@]}" +echo "[visual-pixel-rsm] complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_pixel_scorer.sh b/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_pixel_scorer.sh new file mode 100644 index 0000000000000000000000000000000000000000..024d4fa6ceb32f6dc4b62e1f66b2ca7f1bf7e35b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/train_visual_rsm_pixel_scorer.sh @@ -0,0 +1,406 @@ +#!/bin/bash +# Strict pixels-only raw-pixel scorer extraction for visual-cube. +# +# This launcher intentionally exposes only the scientific axes in the matched +# screen: frozen versus jointly adapted reward-predictive latent, behavior-only +# versus occupancy-supported scorer supervision, and DDPG+BC versus AWR policy +# extraction. Recorded-action Q labels are finite-trajectory empirical index +# returns. The discount-conditioned flow occupancy, supervised scorer, and +# pixel actor remain trainable in one fused step. There is no Bellman target, +# TD bootstrap, recursive composition, coordinate, proprioception, simulator +# state, forward model, or reward-array input. +set -euo pipefail + +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +cd "$ROOT" + +DRY_RUN=0 +if [ "${1:-}" = "--dry-run" ]; then + DRY_RUN=1 + shift +fi +if [ "$#" -ne 0 ]; then + echo "usage: $0 [--dry-run]" >&2 + exit 2 +fi + +PREFIX="[visual-pixel-scorer]" +RSM_IMPL="$ROOT/ogbench_genq/rsm.py" +PINNED_PIXEL_SCORER_COMMIT=2683ed1094d23f3ace7be0ef94ee71e942f1f640 + +fail_usage() { + echo "$PREFIX $*" >&2 + exit 2 +} + +fail_contract() { + echo "$PREFIX $*" >&2 + exit 1 +} + +# Refuse to run from source that predates the corrected schema-13 pixel scorer. +command -v git >/dev/null 2>&1 || fail_contract "git is required" +command -v rg >/dev/null 2>&1 || fail_contract "rg is required" +command -v sha256sum >/dev/null 2>&1 || \ + fail_contract "sha256sum is required" +[ -r "$RSM_IMPL" ] || fail_contract "missing implementation: $RSM_IMPL" +git -C "$ROOT" cat-file -e \ + "${PINNED_PIXEL_SCORER_COMMIT}^{commit}" 2>/dev/null || \ + fail_contract "missing pinned pixel-scorer source commit" +git -C "$ROOT" merge-base --is-ancestor \ + "$PINNED_PIXEL_SCORER_COMMIT" HEAD || \ + fail_contract \ + "HEAD must descend from corrected pixel-scorer commit $PINNED_PIXEL_SCORER_COMMIT" +for literal in \ + 'def validate_visual_pixel_scorer_run_contract(' \ + 'recorded-action label is empirical by contract' \ + 'the raw-pixel scorer, occupancy, and actor must be jointly' \ + '"distill_empirical_index_uses_td_or_bootstrap": False' \ + 'critic_ema, new_critic_params)'; do + rg -Fq -- "$literal" "$RSM_IMPL" || \ + fail_contract "implementation contract is missing: $literal" +done + +PY=${PY:-/proj/inf-scaling/zwhong/projs/gen_q/.ogbench_venv/bin/python} +[ -x "$PY" ] || fail_contract "Python executable is missing: $PY" +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +[ -d "$OGBENCH_IMPLS" ] || \ + fail_contract "OGBENCH_IMPLS is missing: $OGBENCH_IMPLS" +export XLA_PYTHON_CLIENT_PREALLOCATE=false +export XLA_PYTHON_CLIENT_MEM_FRACTION=${XLA_PYTHON_CLIENT_MEM_FRACTION:-0.90} +export WANDB_MODE=disabled +export PYTHONUNBUFFERED=1 + +ENV=visual-cube-single-play-v0 +BASE=fair_px_gpred_gciql_z8_w003_gciqlret +ARTIFACT_ROOT=${ARTIFACT_ROOT:-/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree} +LAT=${LAT:-$ARTIFACT_ROOT/ckpt/latents_${BASE}_stateh256.npz} +ENC=${ENC:-$ARTIFACT_ROOT/ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz} +RDEC=${RDEC:-$ARTIFACT_ROOT/ckpt/rdec_${BASE}_indexd4_diagmetric.npz} +PIXEL_DATASET=${PIXEL_DATASET:-/proj/inf-scaling/zwhong/.ogbench/data/visual-cube-single-play-v0.npz} +PIXEL_ACTOR_INIT_CKPT=${PIXEL_ACTOR_INIT_CKPT:-/proj/inf-scaling/zwhong/visual_gcbc_control_s0/params_300000.pkl} + +readonly LAT_SHA256=8b19aa38a9df797fdbef230506e18357efa6622b6fe6b2b011e8af5f90908f2d +readonly ENC_SHA256=c81cfa6048673706a3842e58d36cc2ecff999e51d2a897dd8ba099c8447e39b2 +readonly RDEC_SHA256=9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7 +readonly PIXEL_DATASET_SHA256=8de92b80f0c11d32b8621a98c473006313771a32da11a333b5d473db197d95c0 +readonly PIXEL_ACTOR_INIT_CKPT_SHA256=95ee8d65769dc1da91d06de38801d588ca6446ff8a73fea340af752d5627f89b +readonly PROTECTED_OCCUPANCY_CKPT=/proj/inf-scaling/zwhong/visual_rsm_protected_frozen_s0/rsm_fair_visual_rsm_protected_frozen_hit025_jointtrain50k_h256_s0_step50000.pkl +readonly PROTECTED_OCCUPANCY_CKPT_SHA256=ebd13c6963c3b8905cd1bf4fde4f618095e955c791292d507ce6c5280f919279 + +LATENT_UPDATE=${LATENT_UPDATE:-frozen} +SUPPORT_MODE=${SUPPORT_MODE:-behavior} +ACTOR_LOSS=${ACTOR_LOSS:-ddpgbc_distill} +SEED=${SEED:-0} +TRAIN_STEPS=${TRAIN_STEPS:-50000} +INIT_OCCUPANCY_CKPT=${INIT_OCCUPANCY_CKPT:-} +INIT_OCCUPANCY_CKPT_SHA256=${INIT_OCCUPANCY_CKPT_SHA256:-} + +[[ "$SEED" =~ ^[0-9]+$ ]] || fail_usage "SEED must be a nonnegative integer" +[[ "$TRAIN_STEPS" =~ ^[1-9][0-9]*$ ]] || \ + fail_usage "TRAIN_STEPS must be a positive integer" + +case "$LATENT_UPDATE" in + frozen) + LATENT_TAG=frozen + LATENT_ARGS=(--latent_update frozen) + ;; + joint) + LATENT_TAG=joint + LATENT_ARGS=( + --latent_update rich_adapter + --latent_hidden 64 + --latent_lr 3e-5 + --latent_goal_weight 0.1 + --latent_anchor_weight 0.01 + ) + ;; + *) + fail_usage "LATENT_UPDATE must be frozen or joint" + ;; +esac + +case "$ACTOR_LOSS" in + ddpgbc_distill) + ACTOR_TAG=ddpgbc + ALPHA=1.0 + ;; + awr_distill) + ACTOR_TAG=awr + ALPHA=10.0 + ;; + *) + fail_usage \ + "ACTOR_LOSS must be ddpgbc_distill or awr_distill" + ;; +esac + +case "$SUPPORT_MODE" in + behavior) + SUPPORT_TAG=behavior + SUPPORT_ARGS=(--no_distill_actor_actions) + ;; + occupancy) + [ "$ACTOR_LOSS" = ddpgbc_distill ] || \ + fail_usage "SUPPORT_MODE=occupancy is incompatible with awr_distill" + SUPPORT_TAG=occupancy + SUPPORT_ARGS=( + --distill_actor_actions + --distill_actor_action_k 2 + --distill_actor_action_sigma 0.3 + --distill_actor_action_pairwise_weight 1.0 + ) + ;; + *) + fail_usage "SUPPORT_MODE must be behavior or occupancy" + ;; +esac + +verify_sha256() { + local label=$1 + local path=$2 + local expected=$3 + [ -s "$path" ] || fail_contract "missing $label artifact: $path" + local actual + actual=$(sha256sum "$path") + actual=${actual%% *} + [ "$actual" = "$expected" ] || \ + fail_contract \ + "$label checksum mismatch: expected=$expected actual=$actual path=$path" +} + +verify_sha256 latent "$LAT" "$LAT_SHA256" +verify_sha256 encoder "$ENC" "$ENC_SHA256" +verify_sha256 reward-reader "$RDEC" "$RDEC_SHA256" +verify_sha256 pixel-dataset "$PIXEL_DATASET" "$PIXEL_DATASET_SHA256" +verify_sha256 strict-non-td-gcbc \ + "$PIXEL_ACTOR_INIT_CKPT" "$PIXEL_ACTOR_INIT_CKPT_SHA256" + +# The protected occupancy checkpoint was normalized over gamma_lo=0.5. +# Fresh arms deliberately use the shortest requested horizon, 1-1/8=0.875. +# Only the exact protected frozen checkpoint may select the wider encoding. +OCCUPANCY_INIT_ARGS=() +OCCUPANCY_INIT_TAG=fresh +EXPECTED_GAMMA_LO=0.875 +OCC_READER_HIT_WEIGHT=0.25 +if [ -n "$INIT_OCCUPANCY_CKPT" ]; then + [ "$LATENT_UPDATE" = frozen ] || \ + fail_usage "INIT_OCCUPANCY_CKPT requires LATENT_UPDATE=frozen" + [ "$SUPPORT_MODE" = occupancy ] || \ + fail_usage "INIT_OCCUPANCY_CKPT is restricted to SUPPORT_MODE=occupancy" + [ "$SEED" = 0 ] || \ + fail_usage "the pinned protected occupancy checkpoint requires SEED=0" + [ -s "$INIT_OCCUPANCY_CKPT" ] || \ + fail_contract \ + "missing protected occupancy checkpoint: $INIT_OCCUPANCY_CKPT" + ACTUAL_INIT_REAL=$(realpath "$INIT_OCCUPANCY_CKPT") + PROTECTED_INIT_REAL=$(realpath "$PROTECTED_OCCUPANCY_CKPT") + [ "$ACTUAL_INIT_REAL" = "$PROTECTED_INIT_REAL" ] || \ + fail_usage \ + "INIT_OCCUPANCY_CKPT must be the pinned protected step-50000 checkpoint" + if [ -n "$INIT_OCCUPANCY_CKPT_SHA256" ] && \ + [ "$INIT_OCCUPANCY_CKPT_SHA256" != \ + "$PROTECTED_OCCUPANCY_CKPT_SHA256" ]; then + fail_usage "INIT_OCCUPANCY_CKPT_SHA256 does not match the pinned digest" + fi + verify_sha256 protected-occupancy-init \ + "$ACTUAL_INIT_REAL" "$PROTECTED_OCCUPANCY_CKPT_SHA256" + INIT_OCCUPANCY_CKPT="$ACTUAL_INIT_REAL" + INIT_OCCUPANCY_CKPT_SHA256="$PROTECTED_OCCUPANCY_CKPT_SHA256" + OCCUPANCY_INIT_ARGS=( + --init_occupancy_ckpt "$INIT_OCCUPANCY_CKPT" + --init_occupancy_ckpt_sha256 "$INIT_OCCUPANCY_CKPT_SHA256" + ) + OCCUPANCY_INIT_TAG=protected50k + EXPECTED_GAMMA_LO=0.5 + # Selective occupancy loading checks the loss/normalizer contract as well + # as shapes. The immutable source and fresh recipe both use this protected + # endpoint-reader weight while continuing to update the occupancy. +elif [ -n "$INIT_OCCUPANCY_CKPT_SHA256" ]; then + fail_usage \ + "INIT_OCCUPANCY_CKPT_SHA256 requires INIT_OCCUPANCY_CKPT" +fi +if [ -n "${GAMMA_LO+x}" ] && [ "$GAMMA_LO" != "$EXPECTED_GAMMA_LO" ]; then + fail_usage \ + "GAMMA_LO must be $EXPECTED_GAMMA_LO for occupancy init $OCCUPANCY_INIT_TAG" +fi +GAMMA_LO=$EXPECTED_GAMMA_LO + +LAT=$(realpath "$LAT") +ENC=$(realpath "$ENC") +RDEC=$(realpath "$RDEC") +PIXEL_DATASET=$(realpath "$PIXEL_DATASET") +PIXEL_ACTOR_INIT_CKPT=$(realpath "$PIXEL_ACTOR_INIT_CKPT") + +DEFAULT_TAG=${BASE}_pixel_scorer_${LATENT_TAG}_${SUPPORT_TAG}_${ACTOR_TAG}_${OCCUPANCY_INIT_TAG}_protected_g099_b098_glo${GAMMA_LO}_rh${OCC_READER_HIT_WEIGHT}_h8-16-32-64_flowh512l4_m64_warm10k_s${SEED} +TAG=${TAG:-$DEFAULT_TAG} +case "$TAG" in + *[!A-Za-z0-9._-]*|'') + fail_usage \ + "TAG must use only A-Z, a-z, 0-9, dot, underscore, or hyphen" + ;; +esac + +OUTPUT_ROOT=${OUTPUT_ROOT:-/proj/inf-scaling/zwhong/visual_rsm_pixel_scorer} +CKPT=${CKPT:-$OUTPUT_ROOT/rsm_${TAG}.pkl} +CKPT=$(realpath -m "$CKPT") +case "$CKPT" in + /proj/inf-scaling/zwhong/*.pkl) ;; + *) + fail_usage \ + "CKPT must be an absolute .pkl path under /proj/inf-scaling/zwhong" + ;; +esac +for protected_input in \ + "$LAT" "$ENC" "$RDEC" "$PIXEL_DATASET" "$PIXEL_ACTOR_INIT_CKPT" \ + "${INIT_OCCUPANCY_CKPT:-}"; do + [ -z "$protected_input" ] || [ "$CKPT" != "$protected_input" ] || \ + fail_usage "CKPT must not overwrite an immutable input artifact" +done + +COMMAND=( + "$PY" -u ogbench_genq/rsm.py + --env "$ENV" + --seed "$SEED" + --latent_npz "$LAT" + --latent_npz_sha256 "$LAT_SHA256" + --pixel_encoder "$ENC" + --pixel_encoder_sha256 "$ENC_SHA256" + --pixel_dataset "$PIXEL_DATASET" + --pixel_dataset_sha256 "$PIXEL_DATASET_SHA256" + --drop_proprio + --goal_hidden + --actor_input pixels + --pixel_actor_p_aug 0.5 + --pixel_actor_init_ckpt "$PIXEL_ACTOR_INIT_CKPT" + --pixel_actor_init_ckpt_sha256 "$PIXEL_ACTOR_INIT_CKPT_SHA256" + "${LATENT_ARGS[@]}" + "${OCCUPANCY_INIT_ARGS[@]}" + --reward_decoder "$RDEC" + --rdec_samples 64 + --occupancy_model flow + --occ_hidden 512 + --occ_layers 4 + --flow_steps 25 + --occ_action_contrast_weight 0.0 + --occ_actor_goal_fraction 0.50 + --occ_reader_metric_weight 0.0 + --occ_reader_hit_weight "$OCC_READER_HIT_WEIGHT" + --actor_loss "$ACTOR_LOSS" + --actor_q_transform raw + --alpha "$ALPHA" + --expectile 0.9 + --actor_after 10000 + --distill_actor_goals + "${SUPPORT_ARGS[@]}" + --distill_empirical_index_weight 1.0 + --distill_scorer_input pixels + --gamma 0.99 + --rec_beta 0.98 + --rec_beta_sample_prob 0.30 + --gamma_spectrum_lo "$GAMMA_LO" + --gamma_sampler protected_endpoints + --gamma_task_fraction 0.60 + --gamma_horizons 8,16,32,64 + --recursion off + --batch_size 256 + --occ_batch 2048 + --train_steps "$TRAIN_STEPS" + --eval_interval 50000 + --eval_episodes 50 + --eval_episodes_periodic 3 + --train_only + --ckpt "$CKPT" + --ckpt_every 1000 + --ckpt_archive_every 10000 + --variant_tag "$TAG" + --wandb_mode disabled +) + +require_flag() { + local requested=$1 + local count=0 + local arg + for arg in "${COMMAND[@]}"; do + [ "$arg" != "$requested" ] || count=$((count + 1)) + done + [ "$count" -eq 1 ] || \ + fail_contract "command must contain $requested exactly once; count=$count" +} + +require_pair() { + local requested=$1 + local expected=$2 + local count=0 + local index + for ((index=0; index<${#COMMAND[@]}; index++)); do + if [ "${COMMAND[$index]}" = "$requested" ]; then + count=$((count + 1)) + [ "$((index + 1))" -lt "${#COMMAND[@]}" ] && \ + [ "${COMMAND[$((index + 1))]}" = "$expected" ] || \ + fail_contract \ + "command requires $requested $expected" + fi + done + [ "$count" -eq 1 ] || \ + fail_contract \ + "command must contain $requested exactly once; count=$count" +} + +reject_flag() { + local forbidden=$1 + local arg + for arg in "${COMMAND[@]}"; do + [ "$arg" != "$forbidden" ] || \ + fail_contract "forbidden command option present: $forbidden" + done +} + +# Audit the final argv, not merely the defaults above. +require_flag --drop_proprio +require_flag --goal_hidden +require_flag --distill_actor_goals +require_flag --train_only +require_pair --actor_input pixels +require_pair --pixel_actor_p_aug 0.5 +require_pair --distill_empirical_index_weight 1.0 +require_pair --distill_scorer_input pixels +require_pair --gamma 0.99 +require_pair --rec_beta 0.98 +require_pair --gamma_spectrum_lo "$GAMMA_LO" +require_pair --gamma_sampler protected_endpoints +require_pair --gamma_horizons 8,16,32,64 +require_pair --occupancy_model flow +require_pair --occ_hidden 512 +require_pair --occ_layers 4 +require_pair --occ_reader_hit_weight "$OCC_READER_HIT_WEIGHT" +require_pair --batch_size 256 +require_pair --occ_batch 2048 +require_pair --rdec_samples 64 +require_pair --actor_after 10000 +require_pair --recursion off +reject_flag --freeze_occupancy +reject_flag --coordinates +reject_flag --proprio + +printf '%s source_head=%s schema=13 corrected_source=%s\n' \ + "$PREFIX" "$(git -C "$ROOT" rev-parse HEAD)" \ + "$PINNED_PIXEL_SCORER_COMMIT" +printf '%s latent_update=%s support_mode=%s actor_loss=%s occupancy_init=%s gamma_lo=%s\n' \ + "$PREFIX" "$LATENT_UPDATE" "$SUPPORT_MODE" "$ACTOR_LOSS" \ + "$OCCUPANCY_INIT_TAG" "$GAMMA_LO" +printf '%s pixels_only=true drop_proprio=true td=false bootstrap=false recursion=false discount_conditioned=true joint_occupancy_scorer_actor=true\n' \ + "$PREFIX" +printf '%s tag=%s checkpoint=%s\n' "$PREFIX" "$TAG" "$CKPT" +printf '%s command=' "$PREFIX" +printf ' %q' "${COMMAND[@]}" +printf '\n' + +if [ "$DRY_RUN" = 1 ]; then + echo "$PREFIX dry-run complete; no training or submission" + exit 0 +fi + +mkdir -p "$(dirname "$CKPT")" +"${COMMAND[@]}" +echo "$PREFIX complete $CKPT" diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/0/rsm_step100000_official.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/0/rsm_step100000_official.json new file mode 100644 index 0000000000000000000000000000000000000000..d7dfa8fb36890822f8884945f89f72b1f681fd44 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/0/rsm_step100000_official.json @@ -0,0 +1,419 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-noisy-v0", + "seed": 0, + "actor_loss": "ddpgbc_distill", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "distill_actor_goals": true, + "distill_goal_loss_reduction": "mean_value_and_actor_goals", + "distill_actor_actions": true, + "distill_actor_action_local_k": 2, + "distill_actor_action_sigma": 0.3, + "distill_actor_action_pairwise_weight": 1.0, + "distill_actor_action_pointwise_weight": 1.0, + "distill_actor_action_candidate_count": 3, + "distill_actor_action_pairwise_candidate_count": 4, + "distill_actor_action_common_random_numbers": true, + "distill_actor_action_policy": "stop_gradient_current_actor_mode_plus_local_gaussian", + "distill_actor_action_target_source": "behavior_reference_convex_blend_of_empirical_and_occupancy;actor_mode_and_local_candidates_occupancy_only", + "distill_actor_action_composed_occupancy": false, + "distill_actor_action_support_start_step": 0, + "actor_q_gradient_start_step": 0, + "distill_actor_action_loss_reduction": "normalized_point_and_pairwise_then_mean_with_existing_support", + "distill_actor_action_updates_occupancy": false, + "distill_empirical_index_weight": 1.0, + "distill_empirical_index_enabled": true, + "distill_empirical_index_target_source": "observed_same_trajectory_absorbing_first_passage_geometric_successor_compact_z_through_frozen_index_reader", + "distill_empirical_index_samples": 4, + "distill_empirical_index_horizon": "finite_trajectory_truncated_geometric_absorbing_first_passage_explicit_task_discount", + "distill_empirical_index_blend_formula": "(1-weight)*ema_occupancy_reader_expectation+weight*recorded_successor_reader_expectation", + "distill_empirical_index_behavior_action_only": true, + "distill_empirical_index_counterfactual_action_source": "discount_conditioned_ema_occupancy", + "distill_empirical_index_uses_reward_arrays": false, + "distill_empirical_index_uses_coordinates": false, + "distill_empirical_index_uses_td_or_bootstrap": false, + "distill_empirical_index_recorded_action_uses_occupancy": null, + "distill_empirical_index_counterfactual_uses_empirical": null, + "policy_extraction": "supervised_occupancy_q_distillation_ddpgbc", + "uses_td_or_bootstrap": false, + "occupancy_supervision": "monte_carlo_geometric_futures", + "occupancy_uses_reward_labels": false, + "occupancy_uses_simulator_coordinates": false, + "uses_completion_or_forward_model": false, + "critic_target_source": "convex_blend_of_empirical_recorded_successor_index_expectation_and_ema_occupancy_within_4_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "occupancy_gradient_updates_actor": false, + "gamma": 0.99, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "off", + "rec_max_depth": 10, + "rec_continuation_probability": 0.0, + "rec_cap_mass": 0.0, + "rec_beta_sample_prob": 0.25, + "recursion_state": null, + "recursion_intermediate_actor": null, + "offpolicy_zero_horizon_boundary_approximation": false, + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.875, + "gamma_sampler": "reward_metric_endpoints", + "gamma_task_fraction": 0.5, + "gamma_horizons": [ + 8.0, + 16.0, + 32.0, + 64.0 + ], + "gamma_aux_discounts": [ + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "gamma_batch_allocation": "exact_configurable_task_beta_remaining_aux_sqrt_h_then_shuffle", + "gamma_task_rows_per_occ_batch": 1024, + "gamma_beta_rows_per_occ_batch": 512, + "gamma_aux_rows_per_occ_batch": [ + 71, + 100, + 141, + 200 + ], + "gamma_sampling_importance_weighted": false, + "gamma_normalization": "fixed_fourier_identity", + "gamma_encoding_lo": 0.875, + "gamma_encoding_hi": 0.99, + "condition_normalizer_probe_size": 20000, + "condition_normalizer_seed": 0, + "condition_normalizer_goal_sampler": "exact_mixture_actor_uniform_future_0.5_plus_gciql_value_goals_20_current_50_trajectory_30_random", + "occupancy_actor_goal_fraction": 0.5, + "occupancy_actor_goal_rows_per_batch": 1024, + "condition_normalizer_actor_goal_rows": 10000, + "protected_endpoint_sampler": false, + "protected_endpoint_task_fraction": null, + "protected_endpoint_beta_fraction": null, + "protected_endpoint_aux_fraction": null, + "protected_endpoint_aux_allocation": null, + "protected_endpoint_overrides_legacy_fraction_flags": null, + "protected_endpoint_requested_horizons": null, + "protected_endpoint_excluded_beta_horizons": null, + "protected_endpoint_goal_source_fraction": null, + "protected_endpoint_actor_rows_by_discount": null, + "protected_endpoint_value_rows_by_discount": null, + "protected_endpoint_cross_stratification": null, + "protected_endpoint_normalizer_discount_rows": null, + "protected_endpoint_normalizer_actor_rows_by_discount": null, + "protected_endpoint_normalizer_value_rows_by_discount": null, + "reward_metric_endpoint_sampler": true, + "reward_metric_endpoint_task_fraction": 0.5, + "reward_metric_endpoint_beta_fraction": 0.25, + "reward_metric_endpoint_aux_fraction": 0.25, + "reward_metric_endpoint_aux_allocation": "deterministic_largest_remainder_sqrt_h", + "reward_metric_endpoint_horizons": [ + 8.0, + 16.0, + 32.0, + 64.0 + ], + "reward_metric_endpoint_normalizer_discount_rows": [ + 10000, + 5000, + 690, + 976, + 1381, + 1953 + ], + "occ_reader_metric_weight": 0.0, + "occ_reader_metric_enabled": false, + "occ_reader_metric_model": null, + "occ_reader_metric_target": null, + "occ_reader_metric_projection": null, + "occ_reader_metric_formula": null, + "occ_reader_metric_normalization": null, + "occ_reader_metric_pullback_trace": null, + "occ_reader_metric_loss_reduction": "base_flow_mse_only", + "occ_reader_metric_scale": null, + "occ_reader_metric_weights": null, + "occ_reader_metric_uses_index_relabeling": false, + "occ_reader_metric_uses_reward_arrays": false, + "occ_reader_metric_uses_coordinates": false, + "occ_reader_metric_uses_td_or_bootstrap": false, + "occ_reader_geometry_enabled": false, + "occ_reader_hit_weight": 0.0, + "occ_reader_hit_enabled": false, + "occ_reader_hit_formula": null, + "occ_reader_hit_reader_error_formula": null, + "occ_reader_hit_reader_error_normalization": null, + "occ_reader_hit_mask": null, + "occ_reader_hit_empty_endpoint_mean": null, + "occ_reader_hit_importance_weighted": false, + "occ_reader_hit_endpoint_weights": null, + "occ_reader_hit_base_mle_formula": null, + "occ_reader_hit_total_loss_formula": null, + "occ_reader_hit_take_hit_probability": null, + "occ_reader_hit_target_source": null, + "occ_reader_hit_action_contrast_weights_changed": false, + "occ_reader_hit_uses_index_relabeling": false, + "occ_reader_hit_uses_reward_arrays": false, + "occ_reader_hit_uses_coordinates": false, + "occ_reader_hit_uses_td_or_bootstrap": false, + "occupancy_target_space": "goal_relative_reader_metric", + "occupancy_target_formula": "u_i=sqrt(reader_weight_i)/reader_scale_i*(z_future_i-z_goal_i)", + "occupancy_target_decoder": "z_future_i=z_goal_i+u_i*reader_scale_i/sqrt(reader_weight_i)", + "occupancy_target_invertible": true, + "occupancy_target_reader_frozen": true, + "occupancy_target_reader_model": "diag_metric", + "occupancy_target_reader_target": "index", + "occupancy_target_reader_index_delta": 4, + "occupancy_target_metric_scale": [ + 0.18116597831249237, + 0.1270117163658142, + 0.14198869466781616, + 0.1489657461643219, + 0.15169529616832733, + 0.09334456920623779, + 0.10062896460294724, + 0.1354714035987854 + ], + "occupancy_target_metric_weight": [ + 2.0791609287261963, + 2.331886053085327, + 2.1686906814575195, + 2.732884407043457, + 1.1076571941375732, + 0.3223981261253357, + 0.4262296259403229, + 1.8870292901992798 + ], + "occupancy_target_metric_diagonal": [ + 7.959163188934326, + 12.022917747497559, + 10.371582984924316, + 11.0974760055542, + 6.93794059753418, + 6.082850933074951, + 6.487820625305176, + 10.140087127685547 + ], + "occupancy_target_metric_inverse_diagonal": [ + 0.1256413459777832, + 0.08317448198795319, + 0.09641730040311813, + 0.09011057764291763, + 0.144134983420372, + 0.16439659893512726, + 0.15413495898246765, + 0.09861848503351212 + ], + "occupancy_target_goal_feature": "compact_reward_predictive_z", + "occupancy_decoded_future_feature": "compact_reward_predictive_z", + "occupancy_target_uses_index_relabeling": true, + "occupancy_target_uses_reward_arrays": false, + "occupancy_target_uses_coordinates": false, + "occupancy_target_uses_td_or_bootstrap": false, + "occupancy_model": "flow", + "occupancy_learning_rate": 0.0003, + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.0, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "shuffle", + "occ_action_negative_sigma": 0.3, + "occ_action_negative_local_k": 0, + "occ_action_negative_candidate_count": 0, + "occ_action_negative_policy": null, + "occ_action_negative_actor_source": null, + "occ_action_negative_support_start_step": null, + "occ_action_negative_actions_stop_gradient": false, + "occ_action_negative_common_random_numbers": false, + "occ_action_negative_updates_actor": false, + "occ_action_negative_counterfactual_target": false, + "occ_action_negative_interpretation": null, + "latent": true, + "drop_proprio": true, + "goal_hidden": true, + "state_feature": "encoder_hidden", + "actor_goal_feature": "raw_rgb_pixels", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "goal_relative_reader_metric_u", + "reward_goal_feature": "compact_reward_predictive_z", + "occupancy_future_dim": 8, + "reward_reader_dim": 8, + "occupancy_target_standardization": "identity_in_frozen_reader_metric_coordinates", + "frozen_encoder_fc1_reward_projection": false, + "occupancy_active_future_dims": 8, + "occupancy_constant_future_dims": 0, + "constant_future_masking": false, + "recursive_state_support_projection": null, + "fc1_cached_z_max_abs": null, + "fc1_cached_z_mean_abs": null, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "latent_aux_target": null, + "latent_index_delta": null, + "latent_index_neg_gap": null, + "latent_reader_model": null, + "latent_index_negative_contract": null, + "readout_kind": "classifier", + "reward_decoder_model": "diag_metric", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 4, + "reward_decoder_features": "concat", + "reward_decoder_logit": false, + "rdec_samples": 4, + "actor_input": "pixels", + "actor_state_feature": "raw_rgb_pixels", + "final_actor_consumes_pixels": true, + "policy_observation": "rendered_pixels_only", + "actor_architecture": "GCActor_IMPALA_small_early_fusion_MLP_512x3", + "actor_encoder": "impala_small", + "actor_encoder_trainable": true, + "actor_encoder_initialization": "fresh_jointly_trainable", + "actor_pixel_augmentation_probability": 0.5, + "actor_training_augmentation": "batch_probability_shared_per_row_edge_padded_random_crop", + "actor_goal_relabeling": "uniform_future_same_trajectory", + "actor_pixel_state_shape": [ + 64, + 64, + 3 + ], + "actor_pixel_goal_shape": [ + 64, + 64, + 3 + ], + "actor_goal_dim_semantics": "latent_supervised_scorer_goal_width", + "actor_transition_sampling": "uniform_over_dataset_valid_indices", + "pixel_actor_dataset": { + "dataset_keys": [ + "actions", + "observations", + "terminals", + "valids" + ], + "excluded_keys": [ + "button_states", + "coordinates", + "qpos", + "qvel", + "rewards" + ], + "observation_shape": [ + 64, + 64, + 3 + ], + "observation_dtype": "uint8", + "action_shape": [ + 5 + ], + "row_count": 1001000, + "valid_transition_count": 1000000, + "actions_match_latent_cache": true, + "source_terminals_match_latent_cache": true, + "compact_terminals_match_reconstructed": true, + "terminal_alignment_contract": "latent_source_endpoints_equal_pixel_valids_zero_and_compact_terminals_equal_source_plus_shifted_source", + "path": "/proj/dmfexp/zwhong/.ogbench/data/visual-cube-single-noisy-v0.npz", + "sha256": "3f46dd366dc0415584a2138b9fa86cc1c0369e120f2e5b1c29b94af4247a226a" + }, + "pixel_dataset_device_transport": "dynamic_jit_dispatch_argument_not_xla_constant", + "pixel_actor_init": null, + "pixel_artifact_provenance": { + "latent_npz": { + "path": "/proj/dmfexp/zwhong/projs/gen_q/.claude/worktrees/ogbench-pixel-validation/ckpt/vallat_visual_cube_single_noisy_v0.npz", + "sha256": "c4aed2b417f66cc6d12173a4c4749f6bcf297214d5a1d6cb3dc08aac8eaf04ce" + }, + "pixel_encoder": { + "path": "/proj/dmfexp/zwhong/projs/gen_q/.claude/worktrees/ogbench-pixel-validation/ckpt/valenc_visual_cube_single_noisy_v0.npz", + "sha256": "3d8a1bc222b6ee54ff1867e01193ee00f0a2a8aa6c047d5735746c5cc669dfb2" + }, + "pixel_dataset": { + "path": "/proj/dmfexp/zwhong/.ogbench/data/visual-cube-single-noisy-v0.npz", + "sha256": "3f46dd366dc0415584a2138b9fa86cc1c0369e120f2e5b1c29b94af4247a226a" + } + }, + "occupancy_consumes_raw_pixels": false, + "raw_pixels_update_actor_only": true, + "occupancy_state_for_pixel_actor": "encoder_hidden", + "occupancy_goal_for_pixel_actor": "encoder_hidden", + "supervised_scalar_scorer_state_for_pixel_actor": "encoder_hidden", + "pixel_actor_occupancy_discount_required": true, + "pixel_actor_recursion_supported": false, + "pixel_actor_generated_midpoint_policy": null, + "pixel_actor_uses_image_or_world_model_reconstruction": false, + "completion_or_world_model_carrier_instantiated": false, + "pixel_actor_and_occupancy_same_fused_step": true, + "distill_scorer_input": "latent", + "supervised_scalar_scorer_input": "encoder_hidden", + "supervised_scalar_scorer_goal_input": "raw_rgb_pixels", + "supervised_scalar_scorer_architecture": "GCValue_twin_MLP_512x3", + "supervised_scalar_scorer_encoder": null, + "supervised_scalar_scorer_encoder_trainable": false, + "supervised_scalar_scorer_ensemble_size": 2, + "supervised_scalar_scorer_target_update_source": null, + "supervised_scalar_scorer_target_update_timing": null, + "supervised_scalar_scorer_target_update_tau": null, + "supervised_scalar_scorer_recorded_action_target_source": null, + "supervised_scalar_scorer_recorded_action_uses_occupancy": null, + "supervised_scalar_scorer_counterfactual_target_source": null, + "supervised_scalar_scorer_counterfactual_uses_empirical": null, + "supervised_scalar_scorer_target_discount": null, + "supervised_scalar_scorer_receives_discount_feature": null, + "supervised_scalar_scorer_training_augmentation": null, + "supervised_scalar_scorer_uses_proprio": null, + "supervised_scalar_scorer_uses_coordinates": null, + "supervised_scalar_scorer_uses_reward_arrays": null, + "supervised_scalar_scorer_uses_td_or_bootstrap": null, + "supervised_expectile_value_input": null, + "supervised_expectile_value_architecture": null, + "supervised_expectile_value_target_source": null, + "supervised_expectile_value_target_discount": null, + "supervised_expectile_value_uses_next_state": null, + "supervised_expectile_value_uses_td_or_bootstrap": null, + "supervised_expectile_value_uses_reward_arrays": null, + "pixel_scorer_policy_extraction": null, + "pixel_scorer_actor_advantage_source": null, + "pixel_scorer_actor_weight_formula": null, + "pixel_scorer_actor_uses_dataset_actions_only": null, + "pixel_scorer_supervision_regime": null, + "pixel_scorer_and_occupancy_same_fused_step": false, + "pixel_scorer_and_actor_same_fused_step": false, + "pixel_scorer_gradient_updates_occupancy": false, + "occupancy_gradient_updates_pixel_scorer": false, + "reader_metric_pixel_scorer_combined": false, + "reader_metric_pixel_scorer_update_semantics": null, + "eval_episodes_periodic": 15, + "success_rate": 0.8960000000000001, + "best_sr": 0.8960000000000001, + "eval_only": true, + "eval_actor": "ema", + "checkpoint_step": 100000, + "checkpoint_path": "/proj/dmfexp/zwhong/projs/gen_q/.claude/worktrees/unified-rsm-recipe/ckpt/recipe_visual-cube-single-noisy-v0_s0_step100000.pkl", + "per_task": [ + 1.0, + 0.94, + 0.64, + 0.96, + 0.94 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 1211.8, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/0s8gc4o4" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/0/rsm_step60000.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/0/rsm_step60000.json new file mode 100644 index 0000000000000000000000000000000000000000..b55666d7ab4323aab2175acf57724deeb5e5096d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/0/rsm_step60000.json @@ -0,0 +1,419 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-noisy-v0", + "seed": 0, + "actor_loss": "ddpgbc_distill", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "distill_actor_goals": true, + "distill_goal_loss_reduction": "mean_value_and_actor_goals", + "distill_actor_actions": true, + "distill_actor_action_local_k": 2, + "distill_actor_action_sigma": 0.3, + "distill_actor_action_pairwise_weight": 1.0, + "distill_actor_action_pointwise_weight": 1.0, + "distill_actor_action_candidate_count": 3, + "distill_actor_action_pairwise_candidate_count": 4, + "distill_actor_action_common_random_numbers": true, + "distill_actor_action_policy": "stop_gradient_current_actor_mode_plus_local_gaussian", + "distill_actor_action_target_source": "behavior_reference_convex_blend_of_empirical_and_occupancy;actor_mode_and_local_candidates_occupancy_only", + "distill_actor_action_composed_occupancy": false, + "distill_actor_action_support_start_step": 0, + "actor_q_gradient_start_step": 0, + "distill_actor_action_loss_reduction": "normalized_point_and_pairwise_then_mean_with_existing_support", + "distill_actor_action_updates_occupancy": false, + "distill_empirical_index_weight": 1.0, + "distill_empirical_index_enabled": true, + "distill_empirical_index_target_source": "observed_same_trajectory_absorbing_first_passage_geometric_successor_compact_z_through_frozen_index_reader", + "distill_empirical_index_samples": 4, + "distill_empirical_index_horizon": "finite_trajectory_truncated_geometric_absorbing_first_passage_explicit_task_discount", + "distill_empirical_index_blend_formula": "(1-weight)*ema_occupancy_reader_expectation+weight*recorded_successor_reader_expectation", + "distill_empirical_index_behavior_action_only": true, + "distill_empirical_index_counterfactual_action_source": "discount_conditioned_ema_occupancy", + "distill_empirical_index_uses_reward_arrays": false, + "distill_empirical_index_uses_coordinates": false, + "distill_empirical_index_uses_td_or_bootstrap": false, + "distill_empirical_index_recorded_action_uses_occupancy": null, + "distill_empirical_index_counterfactual_uses_empirical": null, + "policy_extraction": "supervised_occupancy_q_distillation_ddpgbc", + "uses_td_or_bootstrap": false, + "occupancy_supervision": "monte_carlo_geometric_futures", + "occupancy_uses_reward_labels": false, + "occupancy_uses_simulator_coordinates": false, + "uses_completion_or_forward_model": false, + "critic_target_source": "convex_blend_of_empirical_recorded_successor_index_expectation_and_ema_occupancy_within_4_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "occupancy_gradient_updates_actor": false, + "gamma": 0.99, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "off", + "rec_max_depth": 10, + "rec_continuation_probability": 0.0, + "rec_cap_mass": 0.0, + "rec_beta_sample_prob": 0.25, + "recursion_state": null, + "recursion_intermediate_actor": null, + "offpolicy_zero_horizon_boundary_approximation": false, + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.875, + "gamma_sampler": "reward_metric_endpoints", + "gamma_task_fraction": 0.5, + "gamma_horizons": [ + 8.0, + 16.0, + 32.0, + 64.0 + ], + "gamma_aux_discounts": [ + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "gamma_batch_allocation": "exact_configurable_task_beta_remaining_aux_sqrt_h_then_shuffle", + "gamma_task_rows_per_occ_batch": 1024, + "gamma_beta_rows_per_occ_batch": 512, + "gamma_aux_rows_per_occ_batch": [ + 71, + 100, + 141, + 200 + ], + "gamma_sampling_importance_weighted": false, + "gamma_normalization": "fixed_fourier_identity", + "gamma_encoding_lo": 0.875, + "gamma_encoding_hi": 0.99, + "condition_normalizer_probe_size": 20000, + "condition_normalizer_seed": 0, + "condition_normalizer_goal_sampler": "exact_mixture_actor_uniform_future_0.5_plus_gciql_value_goals_20_current_50_trajectory_30_random", + "occupancy_actor_goal_fraction": 0.5, + "occupancy_actor_goal_rows_per_batch": 1024, + "condition_normalizer_actor_goal_rows": 10000, + "protected_endpoint_sampler": false, + "protected_endpoint_task_fraction": null, + "protected_endpoint_beta_fraction": null, + "protected_endpoint_aux_fraction": null, + "protected_endpoint_aux_allocation": null, + "protected_endpoint_overrides_legacy_fraction_flags": null, + "protected_endpoint_requested_horizons": null, + "protected_endpoint_excluded_beta_horizons": null, + "protected_endpoint_goal_source_fraction": null, + "protected_endpoint_actor_rows_by_discount": null, + "protected_endpoint_value_rows_by_discount": null, + "protected_endpoint_cross_stratification": null, + "protected_endpoint_normalizer_discount_rows": null, + "protected_endpoint_normalizer_actor_rows_by_discount": null, + "protected_endpoint_normalizer_value_rows_by_discount": null, + "reward_metric_endpoint_sampler": true, + "reward_metric_endpoint_task_fraction": 0.5, + "reward_metric_endpoint_beta_fraction": 0.25, + "reward_metric_endpoint_aux_fraction": 0.25, + "reward_metric_endpoint_aux_allocation": "deterministic_largest_remainder_sqrt_h", + "reward_metric_endpoint_horizons": [ + 8.0, + 16.0, + 32.0, + 64.0 + ], + "reward_metric_endpoint_normalizer_discount_rows": [ + 10000, + 5000, + 690, + 976, + 1381, + 1953 + ], + "occ_reader_metric_weight": 0.0, + "occ_reader_metric_enabled": false, + "occ_reader_metric_model": null, + "occ_reader_metric_target": null, + "occ_reader_metric_projection": null, + "occ_reader_metric_formula": null, + "occ_reader_metric_normalization": null, + "occ_reader_metric_pullback_trace": null, + "occ_reader_metric_loss_reduction": "base_flow_mse_only", + "occ_reader_metric_scale": null, + "occ_reader_metric_weights": null, + "occ_reader_metric_uses_index_relabeling": false, + "occ_reader_metric_uses_reward_arrays": false, + "occ_reader_metric_uses_coordinates": false, + "occ_reader_metric_uses_td_or_bootstrap": false, + "occ_reader_geometry_enabled": false, + "occ_reader_hit_weight": 0.0, + "occ_reader_hit_enabled": false, + "occ_reader_hit_formula": null, + "occ_reader_hit_reader_error_formula": null, + "occ_reader_hit_reader_error_normalization": null, + "occ_reader_hit_mask": null, + "occ_reader_hit_empty_endpoint_mean": null, + "occ_reader_hit_importance_weighted": false, + "occ_reader_hit_endpoint_weights": null, + "occ_reader_hit_base_mle_formula": null, + "occ_reader_hit_total_loss_formula": null, + "occ_reader_hit_take_hit_probability": null, + "occ_reader_hit_target_source": null, + "occ_reader_hit_action_contrast_weights_changed": false, + "occ_reader_hit_uses_index_relabeling": false, + "occ_reader_hit_uses_reward_arrays": false, + "occ_reader_hit_uses_coordinates": false, + "occ_reader_hit_uses_td_or_bootstrap": false, + "occupancy_target_space": "goal_relative_reader_metric", + "occupancy_target_formula": "u_i=sqrt(reader_weight_i)/reader_scale_i*(z_future_i-z_goal_i)", + "occupancy_target_decoder": "z_future_i=z_goal_i+u_i*reader_scale_i/sqrt(reader_weight_i)", + "occupancy_target_invertible": true, + "occupancy_target_reader_frozen": true, + "occupancy_target_reader_model": "diag_metric", + "occupancy_target_reader_target": "index", + "occupancy_target_reader_index_delta": 4, + "occupancy_target_metric_scale": [ + 0.18116597831249237, + 0.1270117163658142, + 0.14198869466781616, + 0.1489657461643219, + 0.15169529616832733, + 0.09334456920623779, + 0.10062896460294724, + 0.1354714035987854 + ], + "occupancy_target_metric_weight": [ + 2.0791609287261963, + 2.331886053085327, + 2.1686906814575195, + 2.732884407043457, + 1.1076571941375732, + 0.3223981261253357, + 0.4262296259403229, + 1.8870292901992798 + ], + "occupancy_target_metric_diagonal": [ + 7.959163188934326, + 12.022917747497559, + 10.371582984924316, + 11.0974760055542, + 6.93794059753418, + 6.082850933074951, + 6.487820625305176, + 10.140087127685547 + ], + "occupancy_target_metric_inverse_diagonal": [ + 0.1256413459777832, + 0.08317448198795319, + 0.09641730040311813, + 0.09011057764291763, + 0.144134983420372, + 0.16439659893512726, + 0.15413495898246765, + 0.09861848503351212 + ], + "occupancy_target_goal_feature": "compact_reward_predictive_z", + "occupancy_decoded_future_feature": "compact_reward_predictive_z", + "occupancy_target_uses_index_relabeling": true, + "occupancy_target_uses_reward_arrays": false, + "occupancy_target_uses_coordinates": false, + "occupancy_target_uses_td_or_bootstrap": false, + "occupancy_model": "flow", + "occupancy_learning_rate": 0.0003, + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.0, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "shuffle", + "occ_action_negative_sigma": 0.3, + "occ_action_negative_local_k": 0, + "occ_action_negative_candidate_count": 0, + "occ_action_negative_policy": null, + "occ_action_negative_actor_source": null, + "occ_action_negative_support_start_step": null, + "occ_action_negative_actions_stop_gradient": false, + "occ_action_negative_common_random_numbers": false, + "occ_action_negative_updates_actor": false, + "occ_action_negative_counterfactual_target": false, + "occ_action_negative_interpretation": null, + "latent": true, + "drop_proprio": true, + "goal_hidden": true, + "state_feature": "encoder_hidden", + "actor_goal_feature": "raw_rgb_pixels", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "goal_relative_reader_metric_u", + "reward_goal_feature": "compact_reward_predictive_z", + "occupancy_future_dim": 8, + "reward_reader_dim": 8, + "occupancy_target_standardization": "identity_in_frozen_reader_metric_coordinates", + "frozen_encoder_fc1_reward_projection": false, + "occupancy_active_future_dims": 8, + "occupancy_constant_future_dims": 0, + "constant_future_masking": false, + "recursive_state_support_projection": null, + "fc1_cached_z_max_abs": null, + "fc1_cached_z_mean_abs": null, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "latent_aux_target": null, + "latent_index_delta": null, + "latent_index_neg_gap": null, + "latent_reader_model": null, + "latent_index_negative_contract": null, + "readout_kind": "classifier", + "reward_decoder_model": "diag_metric", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 4, + "reward_decoder_features": "concat", + "reward_decoder_logit": false, + "rdec_samples": 4, + "actor_input": "pixels", + "actor_state_feature": "raw_rgb_pixels", + "final_actor_consumes_pixels": true, + "policy_observation": "rendered_pixels_only", + "actor_architecture": "GCActor_IMPALA_small_early_fusion_MLP_512x3", + "actor_encoder": "impala_small", + "actor_encoder_trainable": true, + "actor_encoder_initialization": "fresh_jointly_trainable", + "actor_pixel_augmentation_probability": 0.5, + "actor_training_augmentation": "batch_probability_shared_per_row_edge_padded_random_crop", + "actor_goal_relabeling": "uniform_future_same_trajectory", + "actor_pixel_state_shape": [ + 64, + 64, + 3 + ], + "actor_pixel_goal_shape": [ + 64, + 64, + 3 + ], + "actor_goal_dim_semantics": "latent_supervised_scorer_goal_width", + "actor_transition_sampling": "uniform_over_dataset_valid_indices", + "pixel_actor_dataset": { + "dataset_keys": [ + "actions", + "observations", + "terminals", + "valids" + ], + "excluded_keys": [ + "button_states", + "coordinates", + "qpos", + "qvel", + "rewards" + ], + "observation_shape": [ + 64, + 64, + 3 + ], + "observation_dtype": "uint8", + "action_shape": [ + 5 + ], + "row_count": 1001000, + "valid_transition_count": 1000000, + "actions_match_latent_cache": true, + "source_terminals_match_latent_cache": true, + "compact_terminals_match_reconstructed": true, + "terminal_alignment_contract": "latent_source_endpoints_equal_pixel_valids_zero_and_compact_terminals_equal_source_plus_shifted_source", + "path": "/proj/dmfexp/zwhong/.ogbench/data/visual-cube-single-noisy-v0.npz", + "sha256": "3f46dd366dc0415584a2138b9fa86cc1c0369e120f2e5b1c29b94af4247a226a" + }, + "pixel_dataset_device_transport": "dynamic_jit_dispatch_argument_not_xla_constant", + "pixel_actor_init": null, + "pixel_artifact_provenance": { + "latent_npz": { + "path": "/proj/dmfexp/zwhong/projs/gen_q/.claude/worktrees/ogbench-pixel-validation/ckpt/vallat_visual_cube_single_noisy_v0.npz", + "sha256": "c4aed2b417f66cc6d12173a4c4749f6bcf297214d5a1d6cb3dc08aac8eaf04ce" + }, + "pixel_encoder": { + "path": "/proj/dmfexp/zwhong/projs/gen_q/.claude/worktrees/ogbench-pixel-validation/ckpt/valenc_visual_cube_single_noisy_v0.npz", + "sha256": "3d8a1bc222b6ee54ff1867e01193ee00f0a2a8aa6c047d5735746c5cc669dfb2" + }, + "pixel_dataset": { + "path": "/proj/dmfexp/zwhong/.ogbench/data/visual-cube-single-noisy-v0.npz", + "sha256": "3f46dd366dc0415584a2138b9fa86cc1c0369e120f2e5b1c29b94af4247a226a" + } + }, + "occupancy_consumes_raw_pixels": false, + "raw_pixels_update_actor_only": true, + "occupancy_state_for_pixel_actor": "encoder_hidden", + "occupancy_goal_for_pixel_actor": "encoder_hidden", + "supervised_scalar_scorer_state_for_pixel_actor": "encoder_hidden", + "pixel_actor_occupancy_discount_required": true, + "pixel_actor_recursion_supported": false, + "pixel_actor_generated_midpoint_policy": null, + "pixel_actor_uses_image_or_world_model_reconstruction": false, + "completion_or_world_model_carrier_instantiated": false, + "pixel_actor_and_occupancy_same_fused_step": true, + "distill_scorer_input": "latent", + "supervised_scalar_scorer_input": "encoder_hidden", + "supervised_scalar_scorer_goal_input": "raw_rgb_pixels", + "supervised_scalar_scorer_architecture": "GCValue_twin_MLP_512x3", + "supervised_scalar_scorer_encoder": null, + "supervised_scalar_scorer_encoder_trainable": false, + "supervised_scalar_scorer_ensemble_size": 2, + "supervised_scalar_scorer_target_update_source": null, + "supervised_scalar_scorer_target_update_timing": null, + "supervised_scalar_scorer_target_update_tau": null, + "supervised_scalar_scorer_recorded_action_target_source": null, + "supervised_scalar_scorer_recorded_action_uses_occupancy": null, + "supervised_scalar_scorer_counterfactual_target_source": null, + "supervised_scalar_scorer_counterfactual_uses_empirical": null, + "supervised_scalar_scorer_target_discount": null, + "supervised_scalar_scorer_receives_discount_feature": null, + "supervised_scalar_scorer_training_augmentation": null, + "supervised_scalar_scorer_uses_proprio": null, + "supervised_scalar_scorer_uses_coordinates": null, + "supervised_scalar_scorer_uses_reward_arrays": null, + "supervised_scalar_scorer_uses_td_or_bootstrap": null, + "supervised_expectile_value_input": null, + "supervised_expectile_value_architecture": null, + "supervised_expectile_value_target_source": null, + "supervised_expectile_value_target_discount": null, + "supervised_expectile_value_uses_next_state": null, + "supervised_expectile_value_uses_td_or_bootstrap": null, + "supervised_expectile_value_uses_reward_arrays": null, + "pixel_scorer_policy_extraction": null, + "pixel_scorer_actor_advantage_source": null, + "pixel_scorer_actor_weight_formula": null, + "pixel_scorer_actor_uses_dataset_actions_only": null, + "pixel_scorer_supervision_regime": null, + "pixel_scorer_and_occupancy_same_fused_step": false, + "pixel_scorer_and_actor_same_fused_step": false, + "pixel_scorer_gradient_updates_occupancy": false, + "occupancy_gradient_updates_pixel_scorer": false, + "reader_metric_pixel_scorer_combined": false, + "reader_metric_pixel_scorer_update_semantics": null, + "eval_episodes_periodic": 15, + "success_rate": 0.908, + "best_sr": 0.908, + "eval_only": true, + "eval_actor": "ema", + "checkpoint_step": 60000, + "checkpoint_path": "/proj/dmfexp/zwhong/projs/gen_q/.claude/worktrees/unified-rsm-recipe/ckpt/recipe_visual-cube-single-noisy-v0_s0_step60000.pkl", + "per_task": [ + 0.94, + 0.96, + 0.8, + 0.92, + 0.92 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 870.5, + "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/obi6gctm" +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/gciql_control_noisy_300000.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/gciql_control_noisy_300000.json new file mode 100644 index 0000000000000000000000000000000000000000..e69e979fde9fd728e561972e8404146b0cb33be3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-noisy-v0/results/gciql_control_noisy_300000.json @@ -0,0 +1,105 @@ +{ + "method": "GCIQL", + "env": "visual-cube-single-noisy-v0", + "checkpoint": "/proj/dmfexp/zwhong/projs/gen_q/.claude/worktrees/ogbench-pixel-validation/ckpt/valgciql_visual_cube_single_noisy_v0_s0/params_300000.pkl", + "checkpoint_step": 300000, + "episodes_per_task": 50, + "total_episodes": 250, + "success_rate": 0.404, + "per_task": [ + 0.28, + 0.8, + 0.16, + 0.34, + 0.44 + ], + "task_results": { + "task1_horizontal": 0.28, + "task2_vertical1": 0.8, + "task3_vertical2": 0.16, + "task4_diagonal1": 0.34, + "task5_diagonal2": 0.44 + }, + "pixels_only": true, + "drop_proprio": true, + "simulator_state_used": false, + "coordinate_used": false, + "policy_observation": "rendered_pixels_only", + "run_meta": { + "method": "GCIQL", + "purpose": "diagnostic_control_only", + "env": "visual-cube-single-noisy-v0", + "seed": 0, + "pixels_only": true, + "drop_proprio": true, + "simulator_state_used": false, + "coordinate_used": false, + "observation_shape": [ + 64, + 64, + 3 + ], + "observation_dtype": "uint8", + "action_shape": [ + 5 + ], + "dataset_keys": [ + "actions", + "observations", + "terminals", + "valids" + ], + "excluded_keys": [ + "button_states", + "coordinates", + "qpos", + "qvel" + ], + "reference_root": "/u/zwhong/ogbench_ref/impls", + "reference_sha256": "fe6a895a228506596712f2cf1571c5ffdcd15eb43c0ab31a24e9752f53b738ed", + "config": { + "actor_geom_sample": false, + "actor_hidden_dims": [ + 512, + 512, + 512 + ], + "actor_loss": "ddpgbc", + "actor_p_curgoal": 0.0, + "actor_p_randomgoal": 0.0, + "actor_p_trajgoal": 1.0, + "agent_name": "gciql", + "alpha": 1.0, + "batch_size": 256, + "const_std": true, + "dataset_class": "GCDataset", + "discount": 0.99, + "discrete": false, + "encoder": "impala_small", + "expectile": 0.9, + "frame_stack": null, + "gc_negative": true, + "layer_norm": true, + "lr": 0.0003, + "p_aug": 0.5, + "tau": 0.005, + "value_geom_sample": true, + "value_hidden_dims": [ + 512, + 512, + 512 + ], + "value_p_curgoal": 0.2, + "value_p_randomgoal": 0.3, + "value_p_trajgoal": 0.5 + }, + "train_steps": 300000, + "network_input_contract": { + "critic": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels], then dataset action", + "value": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels]", + "actor": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels]", + "training_augmentation": "with probability 0.5, one shared random-crop offset per row is applied to observation, next observation, value goal, and actor goal" + }, + "rsm_consumes_td_outputs": false + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/VISUAL_OCCUPANCY_RESULTS.md b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/VISUAL_OCCUPANCY_RESULTS.md new file mode 100644 index 0000000000000000000000000000000000000000..309663a1f8e5279942e28e78955fac512c161300 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/VISUAL_OCCUPANCY_RESULTS.md @@ -0,0 +1,171 @@ +# Fair visual occupancy screen + +Date: 2026-07-26. All training inputs are pixels-only frozen latents, actions, +episode boundaries, and relabeled goal latents. No proprioception, cube +coordinates, or reward enters occupancy training. Metrics use 100 held-out +episodes. The frozen GCIQL-style goal-return reader is diagnostic only. + +Each arm trains for 50,000 updates with batch 2,048. `data best / 8` is the +fraction of rows where the recorded action outranks seven local Gaussian +perturbations; chance is 0.125. + +| arm | reward rho | normalized MAE | mean RMSE | variance ratio | action shuffle | local Q span | data best / 8 | +|---|---:|---:|---:|---:|---:|---:|---:| +| diffusion, absolute, MLP 256x3 | 0.4356 | 0.7308 | 1.4761 | 29.459 | 0.0540 | 0.1163 | 0.0977 | +| diffusion, delta, MLP 256x3 | 0.4520 | 0.7335 | 3.4679 | 83.390 | 0.0586 | 0.1393 | 0.1016 | +| flow, absolute, MLP 256x4 | **0.5366** | 0.5094 | 0.4291 | 1.055 | 0.0667 | 0.1097 | **0.0938** | +| flow, delta, MLP 256x4 | 0.5321 | **0.5015** | **0.4272** | 1.044 | 0.0682 | 0.1041 | 0.0742 | +| flow, delta, residual 256x4 | 0.5304 | 0.5053 | 0.4279 | 1.047 | 0.0703 | 0.1114 | 0.0625 | +| flow, delta, residual 256x4, gamma 0.90--0.99 | 0.5342 | 0.5049 | 0.4279 | **1.038** | 0.0709 | 0.1049 | 0.0586 | +| previous + direct sampler | 0.5258 | 0.5072 | 0.4275 | 1.051 | 0.0688 | 0.1047 | 0.0586 | +| flow, delta, residual 512x4, gamma 0.90--0.99 | 0.5284 | 0.5074 | 0.4281 | 1.053 | **0.0738** | **0.1141** | 0.0859 | + +## Decision + +Advance conditional flow matching with the absolute latent target and the +plain 256x4 MLP. It has the best reward-ranking correlation, calibrated mean, +near-correct variance, the simplest architecture, and the least-bad recorded +action ranking among the flow arms. Delta targets, residual FiLM blocks, +doubling width, discount-spectrum training, and removing exact stratification +did not yield a meaningful control-quality gain. + +The family-level result is strong for distribution fit but exposes the next +gate: every arm ranks the recorded action below chance among local candidates. +Therefore the selected flow should be paired with the exact GCIQL DDPG+BC +extraction control and strong behavior anchoring; occupancy likelihood alone +does not establish trustworthy counterfactual action rankings. + +## Policy-extraction control + +The exact visual GCIQL DDPG+BC recipe (raw normalized value objective, alpha +1.0, batch 256, 512x3 actor, uniform future actor goals) was trained on the +frozen 1M-step diffusion occupancy. Both its 250k checkpoint and completed +500k exponential-moving-average actor scored **0/250** official episodes, +with per-task success `[0, 0, 0, 0, 0]`. Matching policy extraction therefore +does not rescue the old occupancy and strengthens the action-ranking +diagnosis. + +The selected flow occupancy was then trained jointly with the same matched +actor. Both its 110k checkpoint and completed 500k exponential-moving-average +actor scored **0/250**, with per-task success `[0, 0, 0, 0, 0]`. The full +checkpoint audit confirms that this is not ordinary generative underfitting: +reward Spearman is 0.619, normalized MAE is 0.519, latent variance is 1.080 +times empirical variance, and mean error is 0.407 latent standard deviations. +However, the recorded action is best among eight local candidates only 0.109 +of the time, below 0.125 chance. Thus fixing distribution calibration alone is +insufficient: the unresolved gate is counterfactual action identification +from offline occupancy likelihood. + +## Reward-free action-identification objective + +The next screen adds no reward or coordinate supervision to the occupancy. +For the same observed future, flow time, and base noise, it requires the +recorded action to have lower flow-matching error than a negative action: + +`MLE + weight * softplus(margin + error(data action) - error(negative action))`. + +This isolates the property needed by policy improvement: nearby actions must +induce distinguishable conditional future distributions. The architecture and +all other training settings remain the selected absolute-target 256x4 MLP. + +| negative / weight | reward rho | normalized MAE | mean RMSE | variance ratio | action shuffle | local Q span | data best / 8 | +|---|---:|---:|---:|---:|---:|---:|---:| +| shuffled / 0.1 | 0.5347 | 0.5089 | 0.4289 | 1.054 | 0.0869 | 0.1409 | 0.1094 | +| shuffled / 0.5 | **0.5390** | 0.5132 | 0.4305 | **1.051** | **0.1803** | 0.2592 | 0.2227 | +| local Gaussian / 0.1 | 0.5407 | **0.5078** | **0.4289** | 1.056 | 0.0732 | 0.2176 | 0.1602 | +| local Gaussian / 0.5 | 0.5155 | 0.5219 | 0.4322 | 1.051 | 0.1477 | **0.2621** | **0.4453** | + +The local-negative 0.5 arm is the first occupancy to clear the held-out +action-identification gate, reaching 44.5% recorded-action top-1 accuracy +against 12.5% chance while retaining calibrated variance. It is advanced to +matched GCIQL DDPG+BC policy training in both frozen-latent and jointly adapted +goal-predictive-latent arms. The shuffled-negative 0.5 arm is a useful +secondary candidate because it has the best reward correlation and +global-action sensitivity, but the local arm directly matches the actor's +local policy-improvement geometry. + +This result is robust across data/model seeds: with local-negative standard +deviation 0.3, top-1 rates are 0.445, 0.523, and 0.523 (mean 0.497). The +corresponding reward correlations are 0.515, 0.450, and 0.649, and variance +ratios remain 1.051--1.131. A radius sweep confirms that the scale matters: +standard deviation 0.1 falls to 0.098 top-1 and 0.6 reaches 0.406, selecting +0.3 as the best tested local counterfactual scale. + +## Latent control-sufficiency probe + +A diagnostic-only linear ridge fit uses 200,000 rows from the first 900 +episodes and 100,000 rows from the held-out final 100 episodes. Its target is +the one-step latent delta; it is not part of RSM training. Current latent alone +explains 0.5% of delta variance, action alone explains 21.7%, and latent plus +action explains 22.2%. Thus the 8D reward-predictive code does contain a +substantial immediate action effect. The leading remaining explanation is +temporal dilution: with discount 0.99, the first action controls only about 1% +of direct occupancy mass, allowing maximum-likelihood fitting to model future +marginals accurately while neglecting the small conditional action effect. + +## Full action-contrastive RSM audits + +The co-trained frozen-latent actor remains **0/250** at 500k steps. Its +occupancy itself passes the measured gates: reward Spearman 0.626, normalized +MAE 0.516, variance ratio 1.078, and recorded-action top-1 0.465. The policy +failure is instead a nonstationary extraction failure. The +exponential-moving-average actor is 0.994 L2 from the data action, yet the +final occupancy scores it 0.197 lower than the data action and prefers it on +only 18.0% of audited states. + +Joint goal-predictive latent adaptation improves the final occupancy slightly: +reward Spearman 0.633, normalized MAE 0.522, variance ratio 1.081, and +recorded-action top-1 0.551. Its co-trained actor has the same stale-policy +signature: 0.942 L2 from data, 0.144 lower predicted return than data, and only +24.6% model preference. The 170k joint and 190k frozen intermediate actors are +both **0/250**, so this is not explained by selecting only the final actor. + +The next controlled arm therefore freezes the completed action-contrastive +occupancy and initializes a fresh matched GCIQL DDPG+BC actor. This preserves +the successful occupancy while removing the moving-objective confound. + +That staged actor also scores **0/250** at both 110k and 500k. At 110k it is +1.050 L2 from data actions, and the frozen occupancy scores its actions 0.199 +below data. A 100k behavior-cloning warm start followed by 50k occupancy +updates gives essentially the same offline alignment and **0/250**. + +A pure 100k behavior-cloning probe identifies the representation bottleneck. +On the held-out episode slice it reduces action L2 only from 0.876 for the zero +action to 0.770; its predicted action RMS is 0.180 versus 0.435 in the data. +Unlike the occupancy-gradient actors, its final actions are nearly neutral +under the occupancy (only 0.025 below data), showing that the severe +off-support drift is caused by occupancy gradients but that the compact 8D +state is already insufficient for strong behavior cloning. + +The next architecture separates roles without changing pixel inputs: the +selected encoder's 256D hidden image feature conditions the actor and +occupancy, while its bit-identical 8D goal-predictive code remains the future +target, goal input, and classifier reward space. This is strictly pixels-only +and introduces no proprioception, coordinate, temporal-difference, forward, +or world-model training. + +At 100k updates, the rich-state arm preserves occupancy quality (reward +Spearman 0.633, normalized MAE 0.506, variance ratio 1.044, recorded-action +top-1 0.492) and produces the first aligned improved actor: action L2 falls to +0.810, the occupancy scores actor actions 0.048 above data on average, and +prefers them on 68.8% of audited states. This is qualitatively different from +every compact-state arm, whose actor actions score substantially below data. +The five-episode-per-task smoke rollout is still **0/25**, so the offline +alignment improvement is not yet evidence of control success. + +At 270k updates, reward Spearman is 0.637, normalized MAE is 0.499, variance +ratio is 1.045, and recorded-action top-1 is 0.539. Actor action L2 improves to +0.764, but its predicted advantage over the data action shrinks to 0.007 and +the occupancy prefers it on exactly half of audited states. + +The completed 500k audit uses 256 rows and 32 samples per condition. Reward +Spearman is 0.629, normalized MAE is 0.515, variance ratio is 1.080, and +recorded-action top-1 remains 0.523. Actor action L2 improves further to 0.718, +but predicted advantage is effectively zero (-0.001) and model preference is +0.480. Rich visual state therefore fixes much of the representation and +off-support actor problem, while longer training converges toward behavior +support rather than producing a useful policy-improvement direction. The +official evaluations confirm that this offline improvement is insufficient: +both the 100k and completed 500k exponential-moving-average actors score +**0/250**, with per-task success `[0, 0, 0, 0, 0]`. The independent final +five-episode-per-task smoke evaluation also scores **0/25**. diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step100000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step100000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..c13e1906e51db5b0b11bce1b50530bdaa09af86c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step100000_distill_audit.json @@ -0,0 +1,616 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step100000.pkl", + "checkpoint_step": 100000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "awr_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 30.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.2820026180321888, + "scorer_mean": 0.10075131381563551, + "bias": -0.18125130421655328, + "mae": 0.18689703381490702, + "rmse": 0.2607339164240141, + "normalized_mae_by_direct_sd": 0.6927214330200736, + "pearson": 0.7560592977236541, + "spearman": 0.7344636971250685 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.2820026180321888, + "scorer_mean": 0.103508880813024, + "bias": -0.17849373721916478, + "mae": 0.18433401305295277, + "rmse": 0.2560439196395929, + "normalized_mae_by_direct_sd": 0.683221766926713, + "pearson": 0.7715893171572638, + "spearman": 0.7421832082036256 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.1241100049381551, + "scorer_mean": 0.0735461600366989, + "bias": -0.05056384490145621, + "mae": 0.11458437649130981, + "rmse": 0.18693027176420593, + "normalized_mae_by_direct_sd": 0.5244311807918222, + "pearson": 0.570112535836581, + "spearman": 0.4544611584179113 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.1241100049381551, + "scorer_mean": 0.07449197542109687, + "bias": -0.04961802951705824, + "mae": 0.11522147009931759, + "rmse": 0.18796598980817975, + "normalized_mae_by_direct_sd": 0.5273470386369602, + "pearson": 0.5643903488915272, + "spearman": 0.4768713681768811 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.31470761091446275, + "scorer_mean": 0.11602180825866526, + "bias": -0.1986858026557975, + "mae": 0.20315451733580903, + "rmse": 0.27073369411957376, + "normalized_mae_by_direct_sd": 0.7419538516603388, + "pearson": 0.777697760372764, + "spearman": 0.7576948386358433 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.31470761091446275, + "scorer_mean": 0.11855826482496923, + "bias": -0.19614934608949353, + "mae": 0.20081619866136224, + "rmse": 0.26645949401929836, + "normalized_mae_by_direct_sd": 0.7334139256490096, + "pearson": 0.7893045362236594, + "spearman": 0.7649755378805217 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.2890625, + "pairwise_agreement": 0.6607142857142857, + "per_row_spearman_mean": 0.392844016609098, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.2961459755897522, + "scorer_span_mean": 0.12019869685173035, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.1484375 + }, + "ema": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.66796875, + "per_row_spearman_mean": 0.41515315599524405, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.2961459755897522, + "scorer_span_mean": 0.12569230794906616, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.1796875 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.2820026180321888, + "std": 0.26980114214178086, + "min": 3.204291559842524e-27, + "median": 0.18748292326927185, + "p90": 0.7234555780887603, + "p99": 0.9996642166376114, + "max": 0.9999817609786987 + }, + "direct_q_actor": { + "mean": 0.3474126037967367, + "std": 0.27388344130848136, + "min": 4.0460096509058424e-26, + "median": 0.24999315291643143, + "p90": 0.8114505171775818, + "p99": 0.999722660779953, + "max": 0.9999840259552002 + }, + "direct_q_actor_minus_data": { + "mean": 0.06540998608973661, + "std": 0.14865690599787287, + "min": -0.3022588789463043, + "median": 0.000830870121717453, + "p90": 0.30357177257537843, + "p99": 0.6059955924749377, + "max": 0.6231763362884521 + }, + "direct_prefers_actor_rate": 0.6640625, + "live_scorer_q_data": { + "mean": 0.10075131381563551, + "std": 0.14115546297862763, + "min": -0.007534824311733246, + "median": 0.0428678784519434, + "p90": 0.27996349036693574, + "p99": 0.7456466120481503, + "max": 0.8501173853874207 + }, + "live_scorer_q_actor": { + "mean": 0.131292302701695, + "std": 0.15339244715451422, + "min": -0.007202550768852234, + "median": 0.06414064764976501, + "p90": 0.33079456388950346, + "p99": 0.7549668496847161, + "max": 0.8670576214790344 + }, + "live_scorer_actor_minus_data": { + "mean": 0.03054098859865917, + "std": 0.06029749108079663, + "min": -0.032609567046165466, + "median": 0.008343445137143135, + "p90": 0.09814797639846799, + "p99": 0.2656308728456498, + "max": 0.37175634503364563 + }, + "live_scorer_prefers_actor_rate": 0.71875, + "ema_scorer_q_data": { + "mean": 0.103508880813024, + "std": 0.14303788970986403, + "min": -0.002313557080924511, + "median": 0.04239821992814541, + "p90": 0.2823339462280272, + "p99": 0.7179811465740213, + "max": 0.859086275100708 + }, + "ema_scorer_q_actor": { + "mean": 0.13360764883691445, + "std": 0.15681525807431584, + "min": -0.004450688138604164, + "median": 0.0628542359918356, + "p90": 0.3541781812906265, + "p99": 0.7142417222261432, + "max": 0.8806636333465576 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8622932703001425, + "std": 0.5255191716222996, + "min": 0.11630839109420776, + "median": 0.7590244114398956, + "p90": 1.666007387638092, + "p99": 2.1337288308143623, + "max": 2.183091163635254 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.8625331223011017, + "std": 1.1670889944239904, + "min": 0.2772526144981384, + "median": 1.6330367922782898, + "p90": 3.5806500911712638, + "p99": 5.089768390655518, + "max": 5.385341167449951 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0, + "actor_row_outside_dataset_p01_p99_rate": 0.0, + "actor_action_saturation_fraction": 0.0 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.012728347443044186, + "absolute_median": 0.006756956689059734, + "absolute_p95": 0.041957590728998184, + "absolute_max": 0.2652689814567566 + }, + "live_data_actions": { + "absolute_mean": 0.009486792609095573, + "absolute_median": 0.006914176046848297, + "absolute_p95": 0.030394606292247772, + "absolute_max": 0.04844602942466736 + }, + "live_actor_actions": { + "absolute_mean": 0.010007049888372421, + "absolute_median": 0.00588969886302948, + "absolute_p95": 0.0365031361579895, + "absolute_max": 0.06610029935836792 + }, + "ema_all_candidates": { + "absolute_mean": 0.010780387558043003, + "absolute_median": 0.005687604658305645, + "absolute_p95": 0.04036524519324303, + "absolute_max": 0.2379322499036789 + }, + "ema_data_actions": { + "absolute_mean": 0.00689982995390892, + "absolute_median": 0.005215594545006752, + "absolute_p95": 0.020432965829968452, + "absolute_max": 0.04230162501335144 + }, + "ema_actor_actions": { + "absolute_mean": 0.00772211654111743, + "absolute_median": 0.005425814539194107, + "absolute_p95": 0.027533501386642456, + "absolute_max": 0.0438077449798584 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.12845668239060615, + "std": 0.14252088159083287, + "min": 0.0008123519364744425, + "median": 0.07055115327239037, + "p90": 0.2907227933406829, + "p99": 0.7142423969507226, + "max": 0.8557425141334534 + }, + "live_data_q_minus_value": { + "mean": -0.027705368396709673, + "std": 0.04626447934890257, + "min": -0.21597906947135925, + "median": -0.015593410469591618, + "p90": 0.009776168316602704, + "p99": 0.05835036143660548, + "max": 0.10228058695793152 + }, + "awr": { + "alpha": 30.0, + "expectile": 0.9, + "adv_norm": false, + "actor_after": 0, + "actor_after_reached": true, + "value": { + "mean": 0.12845668239060615, + "std": 0.14252088159083287, + "min": 0.0008123519364744425, + "median": 0.07055115327239037, + "p90": 0.2907227933406829, + "p99": 0.7142423969507226, + "max": 0.8557425141334534 + }, + "advantage_q_live_min_minus_value": { + "mean": -0.027705368396709673, + "std": 0.04626447934890257, + "min": -0.21597906947135925, + "median": -0.015593410469591618, + "p90": 0.009776168316602704, + "p99": 0.05835036143660548, + "max": 0.10228058695793152 + }, + "transformed_advantage": { + "mean": -0.027705368396709673, + "std": 0.04626447934890257, + "min": -0.21597906947135925, + "median": -0.015593410469591618, + "p90": 0.009776168316602704, + "p99": 0.05835036143660548, + "max": 0.10228058695793152 + }, + "raw_weight": { + "mean": 0.895073892694537, + "std": 2.000265695037232, + "min": 0.0015347741772921753, + "median": 0.626377344465704, + "p90": 1.340923377095343, + "p99": 5.773750761806012, + "max": 21.507840630308124 + }, + "effective_weight": { + "mean": 0.895073892694537, + "std": 2.000265695037232, + "min": 0.0015347741772921753, + "median": 0.626377344465704, + "p90": 1.340923377095343, + "p99": 5.773750761806012, + "max": 21.507840630308124 + }, + "normalized_effective_sample_size": 0.16683060182068174, + "top_10pct_weight_mass": 0.46118929743656484, + "fraction_at_clip_100": 0.0 + } + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.09370437264442444, + "direct_q_actor_mean": 0.1275523602962494, + "direct_q_actor_minus_data_mean": 0.03384798765182495, + "direct_prefers_actor_rate": 0.6171875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03529390630195417, + "scorer_mean": 0.0735461600366989, + "bias": 0.03825225373474473, + "mae": 0.07211145861453208, + "rmse": 0.12407468521247533, + "normalized_mae_by_direct_sd": 0.5256818754995856, + "pearson": 0.6303274583516164, + "spearman": 0.4432036426697973 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03529390630195417, + "scorer_mean": 0.07449197542109687, + "bias": 0.0391980691191427, + "mae": 0.07344898646446348, + "rmse": 0.1266051702528734, + "normalized_mae_by_direct_sd": 0.5354322558440371, + "pearson": 0.6276506550815711, + "spearman": 0.45122050186111634 + }, + "live_local_ranking": { + "top1_agreement": 0.3046875, + "pairwise_agreement": 0.5803571428571429, + "per_row_spearman_mean": 0.25491207800046967, + "per_row_spearman_median": 0.3214285714285715, + "direct_span_mean": 0.10243667662143707, + "scorer_span_mean": 0.12019869685173035, + "direct_data_action_best_rate": 0.2421875, + "scorer_data_action_best_rate": 0.1484375 + }, + "ema_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.58203125, + "per_row_spearman_mean": 0.2638295433233805, + "per_row_spearman_median": 0.3214285714285715, + "direct_span_mean": 0.10243667662143707, + "scorer_span_mean": 0.12569230794906616, + "direct_data_action_best_rate": 0.2421875, + "scorer_data_action_best_rate": 0.1796875 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14225266873836517, + "direct_q_actor_mean": 0.19868676364421844, + "direct_q_actor_minus_data_mean": 0.056434083729982376, + "direct_prefers_actor_rate": 0.640625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05618584867763253, + "scorer_mean": 0.0735461600366989, + "bias": 0.017360311359066367, + "mae": 0.07630681196079775, + "rmse": 0.13345553366131452, + "normalized_mae_by_direct_sd": 0.4665071779086624, + "pearson": 0.6256466926466302, + "spearman": 0.5090350214260677 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05618584867763253, + "scorer_mean": 0.07449197542109687, + "bias": 0.018306126743464338, + "mae": 0.07757465497599622, + "rmse": 0.13503357812661687, + "normalized_mae_by_direct_sd": 0.4742582272822794, + "pearson": 0.6241439436077506, + "spearman": 0.5132337005527516 + }, + "live_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.6138392857142857, + "per_row_spearman_mean": 0.33251768255427383, + "per_row_spearman_median": 0.4285714285714286, + "direct_span_mean": 0.15630754828453064, + "scorer_span_mean": 0.12019869685173035, + "direct_data_action_best_rate": 0.421875, + "scorer_data_action_best_rate": 0.1484375 + }, + "ema_local_ranking": { + "top1_agreement": 0.2421875, + "pairwise_agreement": 0.6160714285714286, + "per_row_spearman_mean": 0.33570988285221703, + "per_row_spearman_median": 0.4047619047619048, + "direct_span_mean": 0.15630754828453064, + "scorer_span_mean": 0.12569230794906616, + "direct_data_action_best_rate": 0.421875, + "scorer_data_action_best_rate": 0.1796875 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.2132057249546051, + "direct_q_actor_mean": 0.2763068675994873, + "direct_q_actor_minus_data_mean": 0.0631011500954628, + "direct_prefers_actor_rate": 0.6640625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08834830471546198, + "scorer_mean": 0.0735461600366989, + "bias": -0.014802144678763082, + "mae": 0.08914240920695646, + "rmse": 0.15490956863053082, + "normalized_mae_by_direct_sd": 0.46283483602722736, + "pearson": 0.6082824610985084, + "spearman": 0.50937600706075 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08834830471546198, + "scorer_mean": 0.07449197542109687, + "bias": -0.01385632929436511, + "mae": 0.0900789750800155, + "rmse": 0.1562382400113366, + "normalized_mae_by_direct_sd": 0.4676975642857783, + "pearson": 0.6037400748112494, + "spearman": 0.5249220381166791 + }, + "live_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.6305803571428571, + "per_row_spearman_mean": 0.3475168104910075, + "per_row_spearman_median": 0.4047619047619048, + "direct_span_mean": 0.22966605424880981, + "scorer_span_mean": 0.12019869685173035, + "direct_data_action_best_rate": 0.4921875, + "scorer_data_action_best_rate": 0.1484375 + }, + "ema_local_ranking": { + "top1_agreement": 0.2421875, + "pairwise_agreement": 0.634765625, + "per_row_spearman_mean": 0.35862687063253973, + "per_row_spearman_median": 0.41666666666666674, + "direct_span_mean": 0.22966605424880981, + "scorer_span_mean": 0.12569230794906616, + "direct_data_action_best_rate": 0.4921875, + "scorer_data_action_best_rate": 0.1796875 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.28200262784957886, + "direct_q_actor_mean": 0.3474126160144806, + "direct_q_actor_minus_data_mean": 0.06540998816490173, + "direct_prefers_actor_rate": 0.6640625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1241100049381551, + "scorer_mean": 0.0735461600366989, + "bias": -0.05056384490145621, + "mae": 0.11458437649130981, + "rmse": 0.18693027176420593, + "normalized_mae_by_direct_sd": 0.5244311807918222, + "pearson": 0.570112535836581, + "spearman": 0.4544611584179113 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1241100049381551, + "scorer_mean": 0.07449197542109687, + "bias": -0.04961802951705824, + "mae": 0.11522147009931759, + "rmse": 0.18796598980817975, + "normalized_mae_by_direct_sd": 0.5273470386369602, + "pearson": 0.5643903488915272, + "spearman": 0.4768713681768811 + }, + "live_local_ranking": { + "top1_agreement": 0.2890625, + "pairwise_agreement": 0.6607142857142857, + "per_row_spearman_mean": 0.392844016609098, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.2961459755897522, + "scorer_span_mean": 0.12019869685173035, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.1484375 + }, + "ema_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.66796875, + "per_row_spearman_mean": 0.41515315599524405, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.2961459755897522, + "scorer_span_mean": 0.12569230794906616, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.1796875 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step150000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step150000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..be7f5322f656344ef4cac5abf0b9cc3042175bae --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step150000_distill_audit.json @@ -0,0 +1,616 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step150000.pkl", + "checkpoint_step": 150000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "awr_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 30.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.2865538729252221, + "scorer_mean": 0.08686007240976323, + "bias": -0.19969380051545893, + "mae": 0.20457058912367931, + "rmse": 0.2852621612313912, + "normalized_mae_by_direct_sd": 0.763720128604577, + "pearson": 0.687917422405223, + "spearman": 0.6756260300311299 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.2865538729252221, + "scorer_mean": 0.07657499774359167, + "bias": -0.2099788751816305, + "mae": 0.2132460383568031, + "rmse": 0.2928528295675878, + "normalized_mae_by_direct_sd": 0.7961080453251868, + "pearson": 0.6837009632281962, + "spearman": 0.6603586797289873 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.11963254564285229, + "scorer_mean": 0.061063963176820835, + "bias": -0.05856858246603146, + "mae": 0.11712168306307794, + "rmse": 0.1941940627267824, + "normalized_mae_by_direct_sd": 0.5503391595064403, + "pearson": 0.5020969738215632, + "spearman": 0.48392397759468214 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.11963254564285229, + "scorer_mean": 0.05165571572888439, + "bias": -0.0679768299139679, + "mae": 0.11773800194209037, + "rmse": 0.19898667049441202, + "normalized_mae_by_direct_sd": 0.5532351596747523, + "pearson": 0.49066548932224213, + "spearman": 0.485817262505946 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.3111906758742735, + "scorer_mean": 0.09914325642785116, + "bias": -0.21204741944642236, + "mae": 0.21637701724718128, + "rmse": 0.2924622729835591, + "normalized_mae_by_direct_sd": 0.7956138338240211, + "pearson": 0.7071492555110233, + "spearman": 0.6878903009646018 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.3111906758742735, + "scorer_mean": 0.08746073550173605, + "bias": -0.22372994037253746, + "mae": 0.22662367956742302, + "rmse": 0.30168004151816, + "normalized_mae_by_direct_sd": 0.8332906000361862, + "pearson": 0.7022221020245198, + "spearman": 0.6762647123670985 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.6635044642857143, + "per_row_spearman_mean": 0.41242079747196925, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.300764262676239, + "scorer_span_mean": 0.11814907193183899, + "direct_data_action_best_rate": 0.5390625, + "scorer_data_action_best_rate": 0.1875 + }, + "ema": { + "top1_agreement": 0.2109375, + "pairwise_agreement": 0.6648995535714286, + "per_row_spearman_mean": 0.42304172557275355, + "per_row_spearman_median": 0.48809523809523814, + "direct_span_mean": 0.300764262676239, + "scorer_span_mean": 0.11416040360927582, + "direct_data_action_best_rate": 0.5390625, + "scorer_data_action_best_rate": 0.15625 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.2865538729252221, + "std": 0.2678606749536093, + "min": 4.833443788705453e-28, + "median": 0.18754350394010544, + "p90": 0.7078142106533049, + "p99": 0.9995381557941437, + "max": 0.9999915361404419 + }, + "direct_q_actor": { + "mean": 0.3358274788233249, + "std": 0.27379511875871343, + "min": 8.084694720602988e-28, + "median": 0.2499871775507927, + "p90": 0.7850374281406403, + "p99": 0.9996113002300262, + "max": 0.9999905824661255 + }, + "direct_q_actor_minus_data": { + "mean": 0.04927360554579356, + "std": 0.14652718725228775, + "min": -0.3572063446044922, + "median": 1.516193151473999e-06, + "p90": 0.19510970115661622, + "p99": 0.5824409008026128, + "max": 0.686365008354187 + }, + "direct_prefers_actor_rate": 0.578125, + "live_scorer_q_data": { + "mean": 0.08686007240976323, + "std": 0.12342596033861584, + "min": 0.0015082755126059055, + "median": 0.040825244039297104, + "p90": 0.22603311687707897, + "p99": 0.6011823344230661, + "max": 0.9011477828025818 + }, + "live_scorer_q_actor": { + "mean": 0.11142644044593908, + "std": 0.1396866604320095, + "min": 0.007766252383589745, + "median": 0.050045980140566826, + "p90": 0.28647992908954617, + "p99": 0.6157555472850802, + "max": 0.8897801041603088 + }, + "live_scorer_actor_minus_data": { + "mean": 0.02456636814167723, + "std": 0.05644558394307213, + "min": -0.0367809534072876, + "median": 0.005328205414116383, + "p90": 0.08394905179738998, + "p99": 0.2658462864160538, + "max": 0.3333999812602997 + }, + "live_scorer_prefers_actor_rate": 0.65625, + "ema_scorer_q_data": { + "mean": 0.07657499774359167, + "std": 0.12430357183312575, + "min": -0.011265140026807785, + "median": 0.029940711334347725, + "p90": 0.21403443366289135, + "p99": 0.615018711388112, + "max": 0.9060869216918945 + }, + "ema_scorer_q_actor": { + "mean": 0.09834647325988044, + "std": 0.1386379724401739, + "min": 0.0006211441941559315, + "median": 0.03696790710091591, + "p90": 0.2656980693340301, + "p99": 0.6069304126501088, + "max": 0.8969261050224304 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8352241460816003, + "std": 0.505336471619448, + "min": 0.12410113960504532, + "median": 0.7487596869468689, + "p90": 1.6089723110198975, + "p99": 2.0612474071979525, + "max": 2.5446338653564453 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.812349389307201, + "std": 1.14408068740502, + "min": 0.32704949378967285, + "median": 1.6633870005607605, + "p90": 3.4312955856323244, + "p99": 4.7370176601409915, + "max": 6.886641979217529 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0, + "actor_row_outside_dataset_p01_p99_rate": 0.0, + "actor_action_saturation_fraction": 0.003125 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.011454088613390923, + "absolute_median": 0.00562738161534071, + "absolute_p95": 0.04476272687315941, + "absolute_max": 0.23234236240386963 + }, + "live_data_actions": { + "absolute_mean": 0.008522242307662964, + "absolute_median": 0.00553828664124012, + "absolute_p95": 0.02667435072362423, + "absolute_max": 0.051507771015167236 + }, + "live_actor_actions": { + "absolute_mean": 0.0077868918888270855, + "absolute_median": 0.004823768511414528, + "absolute_p95": 0.02920965477824211, + "absolute_max": 0.05539789795875549 + }, + "ema_all_candidates": { + "absolute_mean": 0.009835845790803432, + "absolute_median": 0.004762646742165089, + "absolute_p95": 0.03747015818953514, + "absolute_max": 0.18758100271224976 + }, + "ema_data_actions": { + "absolute_mean": 0.006599645595997572, + "absolute_median": 0.004199218936264515, + "absolute_p95": 0.019913554191589355, + "absolute_max": 0.04827722907066345 + }, + "ema_actor_actions": { + "absolute_mean": 0.0066076116636395454, + "absolute_median": 0.003741302527487278, + "absolute_p95": 0.023733850568532944, + "absolute_max": 0.061178058385849 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.1020951813479769, + "std": 0.13150459927904942, + "min": 0.007805970497429371, + "median": 0.045586636289954185, + "p90": 0.2596320778131484, + "p99": 0.6758572989702234, + "max": 0.8938297629356384 + }, + "live_data_q_minus_value": { + "mean": -0.015235108960041543, + "std": 0.04391406026866484, + "min": -0.24250155687332153, + "median": -0.004774318542331457, + "p90": 0.01452156277373433, + "p99": 0.05276506587862971, + "max": 0.1357637345790863 + }, + "awr": { + "alpha": 30.0, + "expectile": 0.9, + "adv_norm": false, + "actor_after": 0, + "actor_after_reached": true, + "value": { + "mean": 0.1020951813479769, + "std": 0.13150459927904942, + "min": 0.007805970497429371, + "median": 0.045586636289954185, + "p90": 0.2596320778131484, + "p99": 0.6758572989702234, + "max": 0.8938297629356384 + }, + "advantage_q_live_min_minus_value": { + "mean": -0.015235108960041543, + "std": 0.04391406026866484, + "min": -0.24250155687332153, + "median": -0.004774318542331457, + "p90": 0.01452156277373433, + "p99": 0.05276506587862971, + "max": 0.1357637345790863 + }, + "transformed_advantage": { + "mean": -0.015235108960041543, + "std": 0.04391406026866484, + "min": -0.24250155687332153, + "median": -0.004774318542331457, + "p90": 0.01452156277373433, + "p99": 0.05276506587862971, + "max": 0.1357637345790863 + }, + "raw_weight": { + "mean": 1.3848140196438812, + "std": 5.140844967605866, + "min": 0.0006926076883092403, + "median": 0.8665793694736783, + "p90": 1.5460244777441434, + "p99": 4.8899040549640524, + "max": 58.72774167829785 + }, + "effective_weight": { + "mean": 1.3848140196438812, + "std": 5.140844967605866, + "min": 0.0006926076883092403, + "median": 0.8665793694736783, + "p90": 1.5460244777441434, + "p99": 4.8899040549640524, + "max": 58.72774167829785 + }, + "normalized_effective_sample_size": 0.06765364009432942, + "top_10pct_weight_mass": 0.5043959740290187, + "fraction_at_clip_100": 0.0 + } + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.09649728238582611, + "direct_q_actor_mean": 0.12549960613250732, + "direct_q_actor_minus_data_mean": 0.029002320021390915, + "direct_prefers_actor_rate": 0.5859375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03369105428868947, + "scorer_mean": 0.061063963176820835, + "bias": 0.027372908888131365, + "mae": 0.06836312119892769, + "rmse": 0.11940292407430042, + "normalized_mae_by_direct_sd": 0.5277342852279662, + "pearson": 0.589820447345613, + "spearman": 0.38561237842691126 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03369105428868947, + "scorer_mean": 0.05165571572888439, + "bias": 0.017964661440194922, + "mae": 0.062057466291184415, + "rmse": 0.11856916370980822, + "normalized_mae_by_direct_sd": 0.4790573051944052, + "pearson": 0.5879567148545258, + "spearman": 0.3906416175778001 + }, + "live_local_ranking": { + "top1_agreement": 0.203125, + "pairwise_agreement": 0.5934709821428571, + "per_row_spearman_mean": 0.28413400675007094, + "per_row_spearman_median": 0.3333333333333334, + "direct_span_mean": 0.10348570346832275, + "scorer_span_mean": 0.11814907193183899, + "direct_data_action_best_rate": 0.265625, + "scorer_data_action_best_rate": 0.1875 + }, + "ema_local_ranking": { + "top1_agreement": 0.1640625, + "pairwise_agreement": 0.5970982142857143, + "per_row_spearman_mean": 0.2965892502098148, + "per_row_spearman_median": 0.4238703101205346, + "direct_span_mean": 0.10348570346832275, + "scorer_span_mean": 0.11416040360927582, + "direct_data_action_best_rate": 0.265625, + "scorer_data_action_best_rate": 0.15625 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14449983835220337, + "direct_q_actor_mean": 0.18837910890579224, + "direct_q_actor_minus_data_mean": 0.04387926682829857, + "direct_prefers_actor_rate": 0.5625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05467708274223962, + "scorer_mean": 0.061063963176820835, + "bias": 0.006386880434581217, + "mae": 0.0770608095114195, + "rmse": 0.13810441915224875, + "normalized_mae_by_direct_sd": 0.48409150101800097, + "pearson": 0.5550154536470457, + "spearman": 0.49472292664511536 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05467708274223962, + "scorer_mean": 0.05165571572888439, + "bias": -0.0030213670133552306, + "mae": 0.0723013515771514, + "rmse": 0.13928646956401006, + "normalized_mae_by_direct_sd": 0.4541928644731765, + "pearson": 0.5493496795893164, + "spearman": 0.5045847721108797 + }, + "live_local_ranking": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.6188616071428571, + "per_row_spearman_mean": 0.3469070745824504, + "per_row_spearman_median": 0.4285714285714286, + "direct_span_mean": 0.15682876110076904, + "scorer_span_mean": 0.11814907193183899, + "direct_data_action_best_rate": 0.4296875, + "scorer_data_action_best_rate": 0.1875 + }, + "ema_local_ranking": { + "top1_agreement": 0.1875, + "pairwise_agreement": 0.6233258928571429, + "per_row_spearman_mean": 0.35978224580007023, + "per_row_spearman_median": 0.4358465727396672, + "direct_span_mean": 0.15682876110076904, + "scorer_span_mean": 0.11416040360927582, + "direct_data_action_best_rate": 0.4296875, + "scorer_data_action_best_rate": 0.15625 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.2174343764781952, + "direct_q_actor_mean": 0.2610592842102051, + "direct_q_actor_minus_data_mean": 0.043624892830848694, + "direct_prefers_actor_rate": 0.625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08337876411529715, + "scorer_mean": 0.061063963176820835, + "bias": -0.02231480093847632, + "mae": 0.09142469572497411, + "rmse": 0.16169980822479973, + "normalized_mae_by_direct_sd": 0.48813435569954616, + "pearson": 0.5373214896961119, + "spearman": 0.5244751777148524 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08337876411529715, + "scorer_mean": 0.05165571572888439, + "bias": -0.03172304838641277, + "mae": 0.08941007300661735, + "rmse": 0.1647689651226017, + "normalized_mae_by_direct_sd": 0.4773778904490514, + "pearson": 0.5289025305383369, + "spearman": 0.5341707060136845 + }, + "live_local_ranking": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.6501116071428571, + "per_row_spearman_mean": 0.3995855652395002, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.232048898935318, + "scorer_span_mean": 0.11814907193183899, + "direct_data_action_best_rate": 0.5234375, + "scorer_data_action_best_rate": 0.1875 + }, + "ema_local_ranking": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.6495535714285714, + "per_row_spearman_mean": 0.4023246296079277, + "per_row_spearman_median": 0.4537394659539954, + "direct_span_mean": 0.232048898935318, + "scorer_span_mean": 0.11416040360927582, + "direct_data_action_best_rate": 0.5234375, + "scorer_data_action_best_rate": 0.15625 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.28655385971069336, + "direct_q_actor_mean": 0.33582746982574463, + "direct_q_actor_minus_data_mean": 0.04927360638976097, + "direct_prefers_actor_rate": 0.578125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11963254564285229, + "scorer_mean": 0.061063963176820835, + "bias": -0.05856858246603146, + "mae": 0.11712168306307794, + "rmse": 0.1941940627267824, + "normalized_mae_by_direct_sd": 0.5503391595064403, + "pearson": 0.5020969738215632, + "spearman": 0.48392397759468214 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11963254564285229, + "scorer_mean": 0.05165571572888439, + "bias": -0.0679768299139679, + "mae": 0.11773800194209037, + "rmse": 0.19898667049441202, + "normalized_mae_by_direct_sd": 0.5532351596747523, + "pearson": 0.49066548932224213, + "spearman": 0.485817262505946 + }, + "live_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.6635044642857143, + "per_row_spearman_mean": 0.41242079747196925, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.300764262676239, + "scorer_span_mean": 0.11814907193183899, + "direct_data_action_best_rate": 0.5390625, + "scorer_data_action_best_rate": 0.1875 + }, + "ema_local_ranking": { + "top1_agreement": 0.2109375, + "pairwise_agreement": 0.6648995535714286, + "per_row_spearman_mean": 0.42304172557275355, + "per_row_spearman_median": 0.48809523809523814, + "direct_span_mean": 0.300764262676239, + "scorer_span_mean": 0.11416040360927582, + "direct_data_action_best_rate": 0.5390625, + "scorer_data_action_best_rate": 0.15625 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step200000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step200000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..e4c6ff415dc77c1127bd5b9c7c4aba20068c46fd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step200000_distill_audit.json @@ -0,0 +1,616 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step200000.pkl", + "checkpoint_step": 200000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "awr_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 30.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.28002160628758765, + "scorer_mean": 0.05921450475580059, + "bias": -0.22080710153178706, + "mae": 0.22379248927089457, + "rmse": 0.3087915533197118, + "normalized_mae_by_direct_sd": 0.8492375514524452, + "pearson": 0.6031975566102966, + "spearman": 0.5796966267868772 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.28002160628758765, + "scorer_mean": 0.05431514132214943, + "bias": -0.22570646496543822, + "mae": 0.22795070334510925, + "rmse": 0.3133984886407374, + "normalized_mae_by_direct_sd": 0.865016952943112, + "pearson": 0.5975226188165054, + "spearman": 0.5634593072750389 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.11642616477331239, + "scorer_mean": 0.04386880273978022, + "bias": -0.07255736203353216, + "mae": 0.11241727107588768, + "rmse": 0.20014983502614492, + "normalized_mae_by_direct_sd": 0.5304220777015493, + "pearson": 0.4762656749618411, + "spearman": 0.3477875615049297 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.11642616477331239, + "scorer_mean": 0.0384227882268533, + "bias": -0.07800337654645909, + "mae": 0.1126862251921373, + "rmse": 0.20253936806499923, + "normalized_mae_by_direct_sd": 0.5316910926828078, + "pearson": 0.4724299252577018, + "spearman": 0.34534097096084565 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.291794964091346, + "scorer_mean": 0.0657042127349996, + "bias": -0.22609075135634632, + "mae": 0.22997439687522708, + "rmse": 0.31086695417334487, + "normalized_mae_by_direct_sd": 0.8563674153982677, + "pearson": 0.6446357794707894, + "spearman": 0.5923446069510793 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.291794964091346, + "scorer_mean": 0.060803120490163565, + "bias": -0.23099184360118236, + "mae": 0.23408663675015778, + "rmse": 0.315786294034386, + "normalized_mae_by_direct_sd": 0.8716803731928814, + "pearson": 0.6375164148304578, + "spearman": 0.5752289881889876 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.21875, + "pairwise_agreement": 0.6498325892857143, + "per_row_spearman_mean": 0.3804778550018489, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.2960486114025116, + "scorer_span_mean": 0.08091944456100464, + "direct_data_action_best_rate": 0.578125, + "scorer_data_action_best_rate": 0.1875 + }, + "ema": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.6517857142857143, + "per_row_spearman_mean": 0.38754630738280127, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.2960486114025116, + "scorer_span_mean": 0.08376403898000717, + "direct_data_action_best_rate": 0.578125, + "scorer_data_action_best_rate": 0.1640625 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.28002160628758765, + "std": 0.2635216599738716, + "min": 6.565427387682045e-27, + "median": 0.1874629110097885, + "p90": 0.6876471996307371, + "p99": 0.9988578927516938, + "max": 0.9999879002571106 + }, + "direct_q_actor": { + "mean": 0.30356832189510424, + "std": 0.27297154019916453, + "min": 6.924058197077919e-30, + "median": 0.18917091190814972, + "p90": 0.7557162046432495, + "p99": 0.9966431319713593, + "max": 0.9999857544898987 + }, + "direct_q_actor_minus_data": { + "mean": 0.023546715401533882, + "std": 0.15935166678721016, + "min": -0.5670496821403503, + "median": 1.043081283569336e-07, + "p90": 0.23065243065357208, + "p99": 0.48401451438665416, + "max": 0.5942410230636597 + }, + "direct_prefers_actor_rate": 0.5234375, + "live_scorer_q_data": { + "mean": 0.05921450475580059, + "std": 0.10976546368292785, + "min": -0.007160518318414688, + "median": 0.021309386007487774, + "p90": 0.1549581363797187, + "p99": 0.5244097080826762, + "max": 0.8894213438034058 + }, + "live_scorer_q_actor": { + "mean": 0.07219392071419861, + "std": 0.11973065960067147, + "min": -0.004956567659974098, + "median": 0.023494779132306576, + "p90": 0.20218355357646942, + "p99": 0.5077748373150827, + "max": 0.8795022368431091 + }, + "live_scorer_actor_minus_data": { + "mean": 0.012979416002053767, + "std": 0.04049937983893096, + "min": -0.04845564812421799, + "median": 0.0014334642328321934, + "p90": 0.041331204026937476, + "p99": 0.21856937244534513, + "max": 0.26904988288879395 + }, + "live_scorer_prefers_actor_rate": 0.5859375, + "ema_scorer_q_data": { + "mean": 0.05431514132214943, + "std": 0.10622306944415656, + "min": -0.012682991102337837, + "median": 0.01770982053130865, + "p90": 0.14919520169496536, + "p99": 0.5348412817716603, + "max": 0.8434261679649353 + }, + "ema_scorer_q_actor": { + "mean": 0.0672910996581777, + "std": 0.11629644871879818, + "min": -0.0062987785786390305, + "median": 0.019468214362859726, + "p90": 0.17272701263427734, + "p99": 0.517529973983765, + "max": 0.8336825370788574 + }, + "l2_to_paired_behavior_action": { + "mean": 0.7816154133761302, + "std": 0.4472392843439103, + "min": 0.1456451117992401, + "median": 0.7161473035812378, + "p90": 1.4390713095664978, + "p99": 1.8080932545661927, + "max": 1.8718479871749878 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.726375215454027, + "std": 1.0292379414817363, + "min": 0.3437073528766632, + "median": 1.5038211941719055, + "p90": 3.263487911224365, + "p99": 4.441263155937195, + "max": 4.751340866088867 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0, + "actor_row_outside_dataset_p01_p99_rate": 0.0, + "actor_action_saturation_fraction": 0.003125 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.0087553970515728, + "absolute_median": 0.004180085379630327, + "absolute_p95": 0.03075643628835678, + "absolute_max": 0.22869959473609924 + }, + "live_data_actions": { + "absolute_mean": 0.006085504777729511, + "absolute_median": 0.0037659183144569397, + "absolute_p95": 0.024324240162968636, + "absolute_max": 0.03927719593048096 + }, + "live_actor_actions": { + "absolute_mean": 0.0065323589369654655, + "absolute_median": 0.003815758042037487, + "absolute_p95": 0.023711638525128365, + "absolute_max": 0.06092458963394165 + }, + "ema_all_candidates": { + "absolute_mean": 0.00861428678035736, + "absolute_median": 0.00389846321195364, + "absolute_p95": 0.03280702605843544, + "absolute_max": 0.20321330428123474 + }, + "ema_data_actions": { + "absolute_mean": 0.005161764100193977, + "absolute_median": 0.002897520549595356, + "absolute_p95": 0.01974446140229702, + "absolute_max": 0.03522735834121704 + }, + "ema_actor_actions": { + "absolute_mean": 0.005942364223301411, + "absolute_median": 0.0032368628308176994, + "absolute_p95": 0.02045494318008423, + "absolute_max": 0.063696950674057 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.07501171718467958, + "std": 0.11447008614428823, + "min": 0.0003528534434735775, + "median": 0.030688954517245293, + "p90": 0.16502062678337096, + "p99": 0.5675791382789617, + "max": 0.8681108951568604 + }, + "live_data_q_minus_value": { + "mean": -0.01579721246889676, + "std": 0.03416355278268893, + "min": -0.19532495737075806, + "median": -0.007986467331647873, + "p90": 0.0071481436491012545, + "p99": 0.028509626090526603, + "max": 0.11552250385284424 + }, + "awr": { + "alpha": 30.0, + "expectile": 0.9, + "adv_norm": false, + "actor_after": 0, + "actor_after_reached": true, + "value": { + "mean": 0.07501171718467958, + "std": 0.11447008614428823, + "min": 0.0003528534434735775, + "median": 0.030688954517245293, + "p90": 0.16502062678337096, + "p99": 0.5675791382789617, + "max": 0.8681108951568604 + }, + "advantage_q_live_min_minus_value": { + "mean": -0.01579721246889676, + "std": 0.03416355278268893, + "min": -0.19532495737075806, + "median": -0.007986467331647873, + "p90": 0.0071481436491012545, + "p99": 0.028509626090526603, + "max": 0.11552250385284424 + }, + "transformed_advantage": { + "mean": -0.01579721246889676, + "std": 0.03416355278268893, + "min": -0.19532495737075806, + "median": -0.007986467331647873, + "p90": 0.0071481436491012545, + "p99": 0.028509626090526603, + "max": 0.11552250385284424 + }, + "raw_weight": { + "mean": 1.0244135113904753, + "std": 2.7807411082153846, + "min": 0.0028519598900337085, + "median": 0.7869519410869246, + "p90": 1.239303634185089, + "p99": 2.3584899236382353, + "max": 31.998054868259388 + }, + "effective_weight": { + "mean": 1.0244135113904753, + "std": 2.7807411082153846, + "min": 0.0028519598900337085, + "median": 0.7869519410869246, + "p90": 1.239303634185089, + "p99": 2.3584899236382353, + "max": 31.998054868259388 + }, + "normalized_effective_sample_size": 0.11949780413171901, + "top_10pct_weight_mass": 0.3961037053854681, + "fraction_at_clip_100": 0.0 + } + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.08962523937225342, + "direct_q_actor_mean": 0.10761632770299911, + "direct_q_actor_minus_data_mean": 0.0179910808801651, + "direct_prefers_actor_rate": 0.53125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.032646919369217445, + "scorer_mean": 0.04386880273978022, + "bias": 0.011221883370562782, + "mae": 0.05281205766854664, + "rmse": 0.10580539119845181, + "normalized_mae_by_direct_sd": 0.4145082961097039, + "pearson": 0.613810827812308, + "spearman": 0.3284325813560183 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.032646919369217445, + "scorer_mean": 0.0384227882268533, + "bias": 0.005775868857635862, + "mae": 0.05079723546525812, + "rmse": 0.10586433704449005, + "normalized_mae_by_direct_sd": 0.39869447337076297, + "pearson": 0.6050511486810548, + "spearman": 0.2860132020315609 + }, + "live_local_ranking": { + "top1_agreement": 0.203125, + "pairwise_agreement": 0.5834263392857143, + "per_row_spearman_mean": 0.27952258048664996, + "per_row_spearman_median": 0.38565620506589715, + "direct_span_mean": 0.0963648110628128, + "scorer_span_mean": 0.08091944456100464, + "direct_data_action_best_rate": 0.2734375, + "scorer_data_action_best_rate": 0.1875 + }, + "ema_local_ranking": { + "top1_agreement": 0.2578125, + "pairwise_agreement": 0.5862165178571429, + "per_row_spearman_mean": 0.28796474667216554, + "per_row_spearman_median": 0.4047619047619048, + "direct_span_mean": 0.0963648110628128, + "scorer_span_mean": 0.08376403898000717, + "direct_data_action_best_rate": 0.2734375, + "scorer_data_action_best_rate": 0.1640625 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14297911524772644, + "direct_q_actor_mean": 0.1677234172821045, + "direct_q_actor_minus_data_mean": 0.024744313210248947, + "direct_prefers_actor_rate": 0.5, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.054120881908437765, + "scorer_mean": 0.04386880273978022, + "bias": -0.010252079168657542, + "mae": 0.06466564619908223, + "rmse": 0.13239831726814336, + "normalized_mae_by_direct_sd": 0.41155949490654087, + "pearson": 0.5589882710970371, + "spearman": 0.4065153712047447 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.054120881908437765, + "scorer_mean": 0.0384227882268533, + "bias": -0.015698093681584462, + "mae": 0.06331119595796583, + "rmse": 0.1335334183594706, + "normalized_mae_by_direct_sd": 0.4029392012904567, + "pearson": 0.5515185219801858, + "spearman": 0.3748503060069937 + }, + "live_local_ranking": { + "top1_agreement": 0.2109375, + "pairwise_agreement": 0.611328125, + "per_row_spearman_mean": 0.336396761607419, + "per_row_spearman_median": 0.41666666666666674, + "direct_span_mean": 0.15364468097686768, + "scorer_span_mean": 0.08091944456100464, + "direct_data_action_best_rate": 0.421875, + "scorer_data_action_best_rate": 0.1875 + }, + "ema_local_ranking": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.6127232142857143, + "per_row_spearman_mean": 0.33145655202798213, + "per_row_spearman_median": 0.40975971788251575, + "direct_span_mean": 0.15364468097686768, + "scorer_span_mean": 0.08376403898000717, + "direct_data_action_best_rate": 0.421875, + "scorer_data_action_best_rate": 0.1640625 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.20906727015972137, + "direct_q_actor_mean": 0.2387549877166748, + "direct_q_actor_minus_data_mean": 0.02968772128224373, + "direct_prefers_actor_rate": 0.5859375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08154986420458304, + "scorer_mean": 0.04386880273978022, + "bias": -0.03768106146480284, + "mae": 0.08365486464237967, + "rmse": 0.16407165488889178, + "normalized_mae_by_direct_sd": 0.45071372793569126, + "pearson": 0.5148593487226673, + "spearman": 0.39893017296293876 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08154986420458304, + "scorer_mean": 0.0384227882268533, + "bias": -0.04312707597772975, + "mae": 0.08324127329746481, + "rmse": 0.16578405775259744, + "normalized_mae_by_direct_sd": 0.44848539013722116, + "pearson": 0.5103126620178369, + "spearman": 0.37902503760632084 + }, + "live_local_ranking": { + "top1_agreement": 0.2109375, + "pairwise_agreement": 0.6467633928571429, + "per_row_spearman_mean": 0.3887266055436509, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.22181379795074463, + "scorer_span_mean": 0.08091944456100464, + "direct_data_action_best_rate": 0.546875, + "scorer_data_action_best_rate": 0.1875 + }, + "ema_local_ranking": { + "top1_agreement": 0.21875, + "pairwise_agreement": 0.6467633928571429, + "per_row_spearman_mean": 0.3873903062172815, + "per_row_spearman_median": 0.4285714285714286, + "direct_span_mean": 0.22181379795074463, + "scorer_span_mean": 0.08376403898000717, + "direct_data_action_best_rate": 0.546875, + "scorer_data_action_best_rate": 0.1640625 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.280021607875824, + "direct_q_actor_mean": 0.3035683035850525, + "direct_q_actor_minus_data_mean": 0.023546714335680008, + "direct_prefers_actor_rate": 0.5234375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11642616477331239, + "scorer_mean": 0.04386880273978022, + "bias": -0.07255736203353216, + "mae": 0.11241727107588768, + "rmse": 0.20014983502614492, + "normalized_mae_by_direct_sd": 0.5304220777015493, + "pearson": 0.4762656749618411, + "spearman": 0.3477875615049297 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11642616477331239, + "scorer_mean": 0.0384227882268533, + "bias": -0.07800337654645909, + "mae": 0.1126862251921373, + "rmse": 0.20253936806499923, + "normalized_mae_by_direct_sd": 0.5316910926828078, + "pearson": 0.4724299252577018, + "spearman": 0.34534097096084565 + }, + "live_local_ranking": { + "top1_agreement": 0.21875, + "pairwise_agreement": 0.6498325892857143, + "per_row_spearman_mean": 0.3804778550018489, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.2960486114025116, + "scorer_span_mean": 0.08091944456100464, + "direct_data_action_best_rate": 0.578125, + "scorer_data_action_best_rate": 0.1875 + }, + "ema_local_ranking": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.6517857142857143, + "per_row_spearman_mean": 0.38754630738280127, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.2960486114025116, + "scorer_span_mean": 0.08376403898000717, + "direct_data_action_best_rate": 0.578125, + "scorer_data_action_best_rate": 0.1640625 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step250000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step250000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..bed96306a4e94d562b18ba4a33321fcdac84a749 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step250000_distill_audit.json @@ -0,0 +1,616 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step250000.pkl", + "checkpoint_step": 250000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "awr_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 30.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.2870678951238088, + "scorer_mean": 0.025325704220449552, + "bias": -0.26174219090335926, + "mae": 0.26209976314729827, + "rmse": 0.3596963599325074, + "normalized_mae_by_direct_sd": 0.9771034973424858, + "pearson": 0.42890346225283904, + "spearman": 0.39541750595129094 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.2870678951238088, + "scorer_mean": 0.026159792323596776, + "bias": -0.26090810280021204, + "mae": 0.26131965483927244, + "rmse": 0.35875451375078143, + "normalized_mae_by_direct_sd": 0.9741952667247816, + "pearson": 0.4226172116148973, + "spearman": 0.4167105383629372 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.11484912494692395, + "scorer_mean": 0.021100139909322024, + "bias": -0.09374898503760193, + "mae": 0.11465358328321146, + "rmse": 0.2240798462132796, + "normalized_mae_by_direct_sd": 0.5333617362928097, + "pearson": 0.323045481446322, + "spearman": 0.28226059683235993 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.11484912494692395, + "scorer_mean": 0.021203223061093013, + "bias": -0.09364590188583094, + "mae": 0.11445372124914208, + "rmse": 0.22375804520616194, + "normalized_mae_by_direct_sd": 0.5324319898474069, + "pearson": 0.32612424112100297, + "spearman": 0.28641644930931176 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.28710259840185626, + "scorer_mean": 0.027346063649019925, + "bias": -0.25975653475283633, + "mae": 0.2605301917340107, + "rmse": 0.3588703775270684, + "normalized_mae_by_direct_sd": 0.9519399390471632, + "pearson": 0.48442598832878675, + "spearman": 0.41112883382925147 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.28710259840185626, + "scorer_mean": 0.027991368569928454, + "bias": -0.2591112298319278, + "mae": 0.2599780481181877, + "rmse": 0.3580415129055612, + "normalized_mae_by_direct_sd": 0.9499224854979467, + "pearson": 0.47611829807128786, + "spearman": 0.4147924296177614 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.1640625, + "pairwise_agreement": 0.6110491071428571, + "per_row_spearman_mean": 0.30935826353985985, + "per_row_spearman_median": 0.3333333333333334, + "direct_span_mean": 0.3019973337650299, + "scorer_span_mean": 0.030042335391044617, + "direct_data_action_best_rate": 0.6328125, + "scorer_data_action_best_rate": 0.1171875 + }, + "ema": { + "top1_agreement": 0.15625, + "pairwise_agreement": 0.6177455357142857, + "per_row_spearman_mean": 0.32118507835919824, + "per_row_spearman_median": 0.3214285714285715, + "direct_span_mean": 0.3019973337650299, + "scorer_span_mean": 0.031582191586494446, + "direct_data_action_best_rate": 0.6328125, + "scorer_data_action_best_rate": 0.140625 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.2870678951238088, + "std": 0.26824155666227173, + "min": 3.631080832562443e-26, + "median": 0.1874963790178299, + "p90": 0.7589047491550446, + "p99": 0.9944361525774003, + "max": 0.9999871850013733 + }, + "direct_q_actor": { + "mean": 0.2871373016799037, + "std": 0.2790191915527298, + "min": 3.580858434439855e-26, + "median": 0.18748749792575836, + "p90": 0.758570384979248, + "p99": 0.999983816742897, + "max": 0.9999898672103882 + }, + "direct_q_actor_minus_data": { + "mean": 6.940626506500786e-05, + "std": 0.15493176094794342, + "min": -0.7010788917541504, + "median": -4.7741952613478134e-08, + "p90": 0.1253027617931366, + "p99": 0.48320256680250195, + "max": 0.5398802757263184 + }, + "direct_prefers_actor_rate": 0.46875, + "live_scorer_q_data": { + "mean": 0.025325704220449552, + "std": 0.06862339234664933, + "min": -0.007051954045891762, + "median": 0.004490390419960022, + "p90": 0.06536563262343405, + "p99": 0.2861271063983445, + "max": 0.6178602576255798 + }, + "live_scorer_q_actor": { + "mean": 0.029366423077590298, + "std": 0.07014860034647873, + "min": -0.008993787690997124, + "median": 0.004531241953372955, + "p90": 0.08542378023266792, + "p99": 0.33941416621208204, + "max": 0.5069844722747803 + }, + "live_scorer_actor_minus_data": { + "mean": 0.004040718842588831, + "std": 0.026321105456151087, + "min": -0.11087578535079956, + "median": -3.355834633111954e-05, + "p90": 0.009918322600424273, + "p99": 0.1267744402587418, + "max": 0.20998115837574005 + }, + "live_scorer_prefers_actor_rate": 0.484375, + "ema_scorer_q_data": { + "mean": 0.026159792323596776, + "std": 0.0742545080582888, + "min": -0.004063636064529419, + "median": 0.004276322200894356, + "p90": 0.06586140915751457, + "p99": 0.26795676678419167, + "max": 0.7127763628959656 + }, + "ema_scorer_q_actor": { + "mean": 0.029822944816260133, + "std": 0.07438230817771878, + "min": -0.007264770567417145, + "median": 0.004293328151106834, + "p90": 0.0797113999724388, + "p99": 0.329476975798607, + "max": 0.6120713353157043 + }, + "l2_to_paired_behavior_action": { + "mean": 0.7427303550066426, + "std": 0.4194321942111449, + "min": 0.1128467321395874, + "median": 0.6758656203746796, + "p90": 1.3354299902915954, + "p99": 1.8339078462123872, + "max": 1.9922962188720703 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.6677554142661393, + "std": 1.0033051809302151, + "min": 0.24284449219703674, + "median": 1.4415764212608337, + "p90": 3.0854817152023313, + "p99": 4.841299533843995, + "max": 5.252277374267578 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0, + "actor_row_outside_dataset_p01_p99_rate": 0.0, + "actor_action_saturation_fraction": 0.003125 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.006176340859383345, + "absolute_median": 0.0025399019941687584, + "absolute_p95": 0.022317437455058098, + "absolute_max": 0.21955648064613342 + }, + "live_data_actions": { + "absolute_mean": 0.0053131612949073315, + "absolute_median": 0.002483401447534561, + "absolute_p95": 0.014998054131865501, + "absolute_max": 0.15160393714904785 + }, + "live_actor_actions": { + "absolute_mean": 0.00575262401252985, + "absolute_median": 0.0024167299270629883, + "absolute_p95": 0.017744816839694977, + "absolute_max": 0.17257261276245117 + }, + "ema_all_candidates": { + "absolute_mean": 0.0053580403327941895, + "absolute_median": 0.0024308254942297935, + "absolute_p95": 0.019595051184296608, + "absolute_max": 0.12881049513816833 + }, + "ema_data_actions": { + "absolute_mean": 0.004238794092088938, + "absolute_median": 0.002247910015285015, + "absolute_p95": 0.01449232455343008, + "absolute_max": 0.05358171463012695 + }, + "ema_actor_actions": { + "absolute_mean": 0.004358525387942791, + "absolute_median": 0.002258480526506901, + "absolute_p95": 0.01286657340824604, + "absolute_max": 0.04909813404083252 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.03666839955985779, + "std": 0.08296668276768546, + "min": 0.0008363630622625351, + "median": 0.009404757991433144, + "p90": 0.08734795898199081, + "p99": 0.35687720417976404, + "max": 0.7341529726982117 + }, + "live_data_q_minus_value": { + "mean": -0.011342695324856322, + "std": 0.02547471816762618, + "min": -0.17295177280902863, + "median": -0.004201301373541355, + "p90": 0.0009359320625662803, + "p99": 0.01968504704535011, + "max": 0.02487943321466446 + }, + "awr": { + "alpha": 30.0, + "expectile": 0.9, + "adv_norm": false, + "actor_after": 0, + "actor_after_reached": true, + "value": { + "mean": 0.03666839955985779, + "std": 0.08296668276768546, + "min": 0.0008363630622625351, + "median": 0.009404757991433144, + "p90": 0.08734795898199081, + "p99": 0.35687720417976404, + "max": 0.7341529726982117 + }, + "advantage_q_live_min_minus_value": { + "mean": -0.011342695324856322, + "std": 0.02547471816762618, + "min": -0.17295177280902863, + "median": -0.004201301373541355, + "p90": 0.0009359320625662803, + "p99": 0.01968504704535011, + "max": 0.02487943321466446 + }, + "transformed_advantage": { + "mean": -0.011342695324856322, + "std": 0.02547471816762618, + "min": -0.17295177280902863, + "median": -0.004201301373541355, + "p90": 0.0009359320625662803, + "p99": 0.01968504704535011, + "max": 0.02487943321466446 + }, + "raw_weight": { + "mean": 0.8201327015553883, + "std": 0.29319525784950295, + "min": 0.005580073485213847, + "median": 0.8815804359544435, + "p90": 1.0284759162262385, + "p99": 1.8158182808550174, + "max": 2.109356682820399 + }, + "effective_weight": { + "mean": 0.8201327015553883, + "std": 0.29319525784950295, + "min": 0.005580073485213847, + "median": 0.8815804359544435, + "p90": 1.0284759162262385, + "p99": 1.8158182808550174, + "max": 2.109356682820399 + }, + "normalized_effective_sample_size": 0.8866786182934856, + "top_10pct_weight_mass": 0.15521274826207848, + "fraction_at_clip_100": 0.0 + } + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.0919741541147232, + "direct_q_actor_mean": 0.09760376065969467, + "direct_q_actor_minus_data_mean": 0.005629600957036018, + "direct_prefers_actor_rate": 0.46875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.030855193211095918, + "scorer_mean": 0.021100139909322024, + "bias": -0.009755053301773892, + "mae": 0.03970672451043861, + "rmse": 0.1083569944824701, + "normalized_mae_by_direct_sd": 0.31826507956833333, + "pearson": 0.5018236676464402, + "spearman": 0.17986212901469717 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.030855193211095918, + "scorer_mean": 0.021203223061093013, + "bias": -0.009651970150002902, + "mae": 0.03925016785876945, + "rmse": 0.10804048957097714, + "normalized_mae_by_direct_sd": 0.31460559768302354, + "pearson": 0.5075789114247986, + "spearman": 0.18020623325498344 + }, + "live_local_ranking": { + "top1_agreement": 0.1484375, + "pairwise_agreement": 0.5571986607142857, + "per_row_spearman_mean": 0.27306444977929584, + "per_row_spearman_median": 0.29761904761904767, + "direct_span_mean": 0.09770897030830383, + "scorer_span_mean": 0.030042335391044617, + "direct_data_action_best_rate": 0.34375, + "scorer_data_action_best_rate": 0.1171875 + }, + "ema_local_ranking": { + "top1_agreement": 0.1875, + "pairwise_agreement": 0.560546875, + "per_row_spearman_mean": 0.2784517138091898, + "per_row_spearman_median": 0.27380952380952384, + "direct_span_mean": 0.09770897030830383, + "scorer_span_mean": 0.031582191586494446, + "direct_data_action_best_rate": 0.34375, + "scorer_data_action_best_rate": 0.140625 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14348287880420685, + "direct_q_actor_mean": 0.15775996446609497, + "direct_q_actor_minus_data_mean": 0.014277095906436443, + "direct_prefers_actor_rate": 0.546875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05262075625323642, + "scorer_mean": 0.021100139909322024, + "bias": -0.0315206163439144, + "mae": 0.05790263536815503, + "rmse": 0.1465163348356638, + "normalized_mae_by_direct_sd": 0.3673695200448843, + "pearson": 0.4197015836015168, + "spearman": 0.25822769719934185 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05262075625323642, + "scorer_mean": 0.021203223061093013, + "bias": -0.03141753319214341, + "mae": 0.05748982270006198, + "rmse": 0.1461475836665395, + "normalized_mae_by_direct_sd": 0.364750385513588, + "pearson": 0.4242914439252695, + "spearman": 0.2539241829752143 + }, + "live_local_ranking": { + "top1_agreement": 0.1484375, + "pairwise_agreement": 0.5948660714285714, + "per_row_spearman_mean": 0.3168113417657232, + "per_row_spearman_median": 0.3690476190476191, + "direct_span_mean": 0.15737734735012054, + "scorer_span_mean": 0.030042335391044617, + "direct_data_action_best_rate": 0.453125, + "scorer_data_action_best_rate": 0.1171875 + }, + "ema_local_ranking": { + "top1_agreement": 0.171875, + "pairwise_agreement": 0.5982142857142857, + "per_row_spearman_mean": 0.3245774206764499, + "per_row_spearman_median": 0.36248445849047095, + "direct_span_mean": 0.15737734735012054, + "scorer_span_mean": 0.031582191586494446, + "direct_data_action_best_rate": 0.453125, + "scorer_data_action_best_rate": 0.140625 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.20845884084701538, + "direct_q_actor_mean": 0.21538972854614258, + "direct_q_actor_minus_data_mean": 0.0069308956153690815, + "direct_prefers_actor_rate": 0.5, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.07923142326785668, + "scorer_mean": 0.021100139909322024, + "bias": -0.05813128335853463, + "mae": 0.08136925481170122, + "rmse": 0.18396330617416953, + "normalized_mae_by_direct_sd": 0.435402175283156, + "pearson": 0.3579012197590088, + "spearman": 0.2829429518690144 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.07923142326785668, + "scorer_mean": 0.021203223061093013, + "bias": -0.05802820020676364, + "mae": 0.08105718723656358, + "rmse": 0.1836173448123901, + "normalized_mae_by_direct_sd": 0.4337323197417147, + "pearson": 0.36203354689425915, + "spearman": 0.2843909387402593 + }, + "live_local_ranking": { + "top1_agreement": 0.1953125, + "pairwise_agreement": 0.6121651785714286, + "per_row_spearman_mean": 0.32398311350891595, + "per_row_spearman_median": 0.38095238095238104, + "direct_span_mean": 0.22444778680801392, + "scorer_span_mean": 0.030042335391044617, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.1171875 + }, + "ema_local_ranking": { + "top1_agreement": 0.1953125, + "pairwise_agreement": 0.6213727678571429, + "per_row_spearman_mean": 0.34310889322287186, + "per_row_spearman_median": 0.4047619047619048, + "direct_span_mean": 0.22444778680801392, + "scorer_span_mean": 0.031582191586494446, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.140625 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.28706789016723633, + "direct_q_actor_mean": 0.28713732957839966, + "direct_q_actor_minus_data_mean": 6.94057671353221e-05, + "direct_prefers_actor_rate": 0.46875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11484912494692395, + "scorer_mean": 0.021100139909322024, + "bias": -0.09374898503760193, + "mae": 0.11465358328321146, + "rmse": 0.2240798462132796, + "normalized_mae_by_direct_sd": 0.5333617362928097, + "pearson": 0.323045481446322, + "spearman": 0.28226059683235993 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11484912494692395, + "scorer_mean": 0.021203223061093013, + "bias": -0.09364590188583094, + "mae": 0.11445372124914208, + "rmse": 0.22375804520616194, + "normalized_mae_by_direct_sd": 0.5324319898474069, + "pearson": 0.32612424112100297, + "spearman": 0.28641644930931176 + }, + "live_local_ranking": { + "top1_agreement": 0.1640625, + "pairwise_agreement": 0.6110491071428571, + "per_row_spearman_mean": 0.30935826353985985, + "per_row_spearman_median": 0.3333333333333334, + "direct_span_mean": 0.3019973337650299, + "scorer_span_mean": 0.030042335391044617, + "direct_data_action_best_rate": 0.6328125, + "scorer_data_action_best_rate": 0.1171875 + }, + "ema_local_ranking": { + "top1_agreement": 0.15625, + "pairwise_agreement": 0.6177455357142857, + "per_row_spearman_mean": 0.32118507835919824, + "per_row_spearman_median": 0.3214285714285715, + "direct_span_mean": 0.3019973337650299, + "scorer_span_mean": 0.031582191586494446, + "direct_data_action_best_rate": 0.6328125, + "scorer_data_action_best_rate": 0.140625 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step300000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step300000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..7e5b140638bdcafc0c344af59a1ce8946a2ff635 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step300000_distill_audit.json @@ -0,0 +1,616 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step300000.pkl", + "checkpoint_step": 300000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "awr_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 30.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.28808089951699345, + "scorer_mean": 0.013213283091317862, + "bias": -0.2748676164256756, + "mae": 0.2748676164256756, + "rmse": 0.37826986811797103, + "normalized_mae_by_direct_sd": 1.0055919335772407, + "pearson": 0.3437880465708729, + "spearman": 0.35271127082951836 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.28808089951699345, + "scorer_mean": 0.014439224993111566, + "bias": -0.2736416745238819, + "mae": 0.2737059362179204, + "rmse": 0.3778716477939901, + "normalized_mae_by_direct_sd": 1.0013419740457918, + "pearson": 0.3441977328813656, + "spearman": 0.34508331807361287 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.11570492204821439, + "scorer_mean": 0.011163711395056453, + "bias": -0.10454121065315794, + "mae": 0.11413545533593929, + "rmse": 0.23116634833864835, + "normalized_mae_by_direct_sd": 0.527402783255339, + "pearson": 0.31709857027790234, + "spearman": 0.2606299153764098 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.11570492204821439, + "scorer_mean": 0.012680185205681482, + "bias": -0.10302473684253291, + "mae": 0.11411583621594512, + "rmse": 0.2311793724418095, + "normalized_mae_by_direct_sd": 0.527312126250822, + "pearson": 0.3074958644561003, + "spearman": 0.2594479933842485 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.2788346109190341, + "scorer_mean": 0.01422666321741417, + "bias": -0.26460794770161994, + "mae": 0.26468246692007047, + "rmse": 0.37028573400903847, + "normalized_mae_by_direct_sd": 0.9617636717808897, + "pearson": 0.3912214061643242, + "spearman": 0.38636630235751884 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.2788346109190341, + "scorer_mean": 0.015468481527932454, + "bias": -0.26336612939110166, + "mae": 0.26357596632638874, + "rmse": 0.36999096644595897, + "normalized_mae_by_direct_sd": 0.9577430349544677, + "pearson": 0.3924459654708869, + "spearman": 0.38549439230945287 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.1015625, + "pairwise_agreement": 0.5784040178571429, + "per_row_spearman_mean": 0.2113531423387312, + "per_row_spearman_median": 0.2142857142857143, + "direct_span_mean": 0.3053022027015686, + "scorer_span_mean": 0.01770695298910141, + "direct_data_action_best_rate": 0.59375, + "scorer_data_action_best_rate": 0.0703125 + }, + "ema": { + "top1_agreement": 0.171875, + "pairwise_agreement": 0.5870535714285714, + "per_row_spearman_mean": 0.2303793349054636, + "per_row_spearman_median": 0.261904761904762, + "direct_span_mean": 0.3053022027015686, + "scorer_span_mean": 0.017521098256111145, + "direct_data_action_best_rate": 0.59375, + "scorer_data_action_best_rate": 0.109375 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.28808089951699345, + "std": 0.2733391222102148, + "min": 8.698711038787777e-28, + "median": 0.18747911602258682, + "p90": 0.7451012313365936, + "p99": 0.9999766939878464, + "max": 0.9999873042106628 + }, + "direct_q_actor": { + "mean": 0.26958832232107477, + "std": 0.2767501743173974, + "min": 1.5925998503740083e-26, + "median": 0.18745093047618866, + "p90": 0.7498875379562377, + "p99": 0.9999700564146042, + "max": 0.9999784827232361 + }, + "direct_q_actor_minus_data": { + "mean": -0.018492577495542836, + "std": 0.16586935856955085, + "min": -0.8937643766403198, + "median": -1.2367963790893555e-06, + "p90": 0.12495342567563057, + "p99": 0.4154882040619852, + "max": 0.5598609447479248 + }, + "direct_prefers_actor_rate": 0.4296875, + "live_scorer_q_data": { + "mean": 0.013213283091317862, + "std": 0.05332459644743191, + "min": -0.0059183016419410706, + "median": -0.0006361100822687149, + "p90": 0.03979216255247592, + "p99": 0.1317169177532197, + "max": 0.5487213730812073 + }, + "live_scorer_q_actor": { + "mean": 0.015240043343510479, + "std": 0.05339371184699387, + "min": -0.005005724728107452, + "median": -0.0007827021181583405, + "p90": 0.046476998925209026, + "p99": 0.23133516564965287, + "max": 0.4825512766838074 + }, + "live_scorer_actor_minus_data": { + "mean": 0.002026760223088786, + "std": 0.018992466270313736, + "min": -0.0661700963973999, + "median": 2.4672597646713257e-05, + "p90": 0.0024857375770807257, + "p99": 0.08046739012002962, + "max": 0.16313683986663818 + }, + "live_scorer_prefers_actor_rate": 0.5234375, + "ema_scorer_q_data": { + "mean": 0.014439224993111566, + "std": 0.04886660239956151, + "min": -0.0030442029237747192, + "median": 0.0007169824093580246, + "p90": 0.04055032171308992, + "p99": 0.11615707024931914, + "max": 0.49623242020606995 + }, + "ema_scorer_q_actor": { + "mean": 0.016497738062753342, + "std": 0.04950110760862936, + "min": -0.002743314951658249, + "median": 0.0005697924643754959, + "p90": 0.0524806637316942, + "p99": 0.23365421205759096, + "max": 0.42982321977615356 + }, + "l2_to_paired_behavior_action": { + "mean": 0.7138626928790472, + "std": 0.41481939523027206, + "min": 0.10199645906686783, + "median": 0.6183694005012512, + "p90": 1.2878018021583557, + "p99": 1.7069569158554083, + "max": 1.9590495824813843 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.6265121491160244, + "std": 0.9749773084532478, + "min": 0.2634098529815674, + "median": 1.3467726707458496, + "p90": 2.967310070991516, + "p99": 4.5378753852844245, + "max": 4.774380207061768 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0, + "actor_row_outside_dataset_p01_p99_rate": 0.0, + "actor_action_saturation_fraction": 0.0078125 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.0037269543390721083, + "absolute_median": 0.001679869368672371, + "absolute_p95": 0.011993934400379658, + "absolute_max": 0.11271464824676514 + }, + "live_data_actions": { + "absolute_mean": 0.00314324744977057, + "absolute_median": 0.0014435090124607086, + "absolute_p95": 0.009946887381374836, + "absolute_max": 0.04948568344116211 + }, + "live_actor_actions": { + "absolute_mean": 0.0031130153220146894, + "absolute_median": 0.0014549121260643005, + "absolute_p95": 0.009483863599598408, + "absolute_max": 0.05286937952041626 + }, + "ema_all_candidates": { + "absolute_mean": 0.003356342203915119, + "absolute_median": 0.0014750836417078972, + "absolute_p95": 0.010990423150360584, + "absolute_max": 0.10042348504066467 + }, + "ema_data_actions": { + "absolute_mean": 0.002928843256086111, + "absolute_median": 0.0013320697471499443, + "absolute_p95": 0.009123518131673336, + "absolute_max": 0.05826810002326965 + }, + "ema_actor_actions": { + "absolute_mean": 0.0029415658209472895, + "absolute_median": 0.0014178240671753883, + "absolute_p95": 0.0105724623426795, + "absolute_max": 0.055256783962249756 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.021227007651759777, + "std": 0.051687470576649915, + "min": -0.0006099473685026169, + "median": 0.003807893954217434, + "p90": 0.06451352685689926, + "p99": 0.24076467499136978, + "max": 0.44336584210395813 + }, + "live_data_q_minus_value": { + "mean": -0.008013724444026593, + "std": 0.023086415760767198, + "min": -0.18249806761741638, + "median": -0.0040310584008693695, + "p90": -0.0021384237334132195, + "p99": 0.03825666092336192, + "max": 0.10535553097724915 + }, + "awr": { + "alpha": 30.0, + "expectile": 0.9, + "adv_norm": false, + "actor_after": 0, + "actor_after_reached": true, + "value": { + "mean": 0.021227007651759777, + "std": 0.051687470576649915, + "min": -0.0006099473685026169, + "median": 0.003807893954217434, + "p90": 0.06451352685689926, + "p99": 0.24076467499136978, + "max": 0.44336584210395813 + }, + "advantage_q_live_min_minus_value": { + "mean": -0.008013724444026593, + "std": 0.023086415760767198, + "min": -0.18249806761741638, + "median": -0.0040310584008693695, + "p90": -0.0021384237334132195, + "p99": 0.03825666092336192, + "max": 0.10535553097724915 + }, + "transformed_advantage": { + "mean": -0.008013724444026593, + "std": 0.023086415760767198, + "min": -0.18249806761741638, + "median": -0.0040310584008693695, + "p90": -0.0021384237334132195, + "p99": 0.03825666092336192, + "max": 0.10535553097724915 + }, + "raw_weight": { + "mean": 1.0264821108132203, + "std": 2.0338149254272295, + "min": 0.004190470721451266, + "median": 0.8860944752345294, + "p90": 0.9378621303500355, + "p99": 3.4541272638043106, + "max": 23.586298913270983 + }, + "effective_weight": { + "mean": 1.0264821108132203, + "std": 2.0338149254272295, + "min": 0.004190470721451266, + "median": 0.8860944752345294, + "p90": 0.9378621303500355, + "p99": 3.4541272638043106, + "max": 23.586298913270983 + }, + "normalized_effective_sample_size": 0.2030157190315814, + "top_10pct_weight_mass": 0.29950077262934305, + "fraction_at_clip_100": 0.0 + } + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.09388919919729233, + "direct_q_actor_mean": 0.09578805416822433, + "direct_q_actor_minus_data_mean": 0.0018988479860126972, + "direct_prefers_actor_rate": 0.4453125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.031700421501714544, + "scorer_mean": 0.011163711395056453, + "bias": -0.020536710106658095, + "mae": 0.035231282826700544, + "rmse": 0.11235910215927288, + "normalized_mae_by_direct_sd": 0.275543284452731, + "pearson": 0.5224370221826948, + "spearman": 0.21070419974451485 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.031700421501714544, + "scorer_mean": 0.012680185205681482, + "bias": -0.019020236296033062, + "mae": 0.0357953938631026, + "rmse": 0.11364375288285522, + "normalized_mae_by_direct_sd": 0.27995518760513216, + "pearson": 0.5027168524461776, + "spearman": 0.191938931748893 + }, + "live_local_ranking": { + "top1_agreement": 0.1484375, + "pairwise_agreement": 0.5290178571428571, + "per_row_spearman_mean": 0.15492692514591017, + "per_row_spearman_median": 0.13242232598785475, + "direct_span_mean": 0.10198243707418442, + "scorer_span_mean": 0.01770695298910141, + "direct_data_action_best_rate": 0.3046875, + "scorer_data_action_best_rate": 0.0703125 + }, + "ema_local_ranking": { + "top1_agreement": 0.1640625, + "pairwise_agreement": 0.5131138392857143, + "per_row_spearman_mean": 0.12596862967758243, + "per_row_spearman_median": 0.17211893398390554, + "direct_span_mean": 0.10198243707418442, + "scorer_span_mean": 0.017521098256111145, + "direct_data_action_best_rate": 0.3046875, + "scorer_data_action_best_rate": 0.109375 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14508457481861115, + "direct_q_actor_mean": 0.1459423303604126, + "direct_q_actor_minus_data_mean": 0.0008577585685998201, + "direct_prefers_actor_rate": 0.515625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05282124716285187, + "scorer_mean": 0.011163711395056453, + "bias": -0.04165753576779542, + "mae": 0.05459614301239715, + "rmse": 0.15101462842275207, + "normalized_mae_by_direct_sd": 0.3443122728923695, + "pearson": 0.4165997159946756, + "spearman": 0.2571120049607816 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05282124716285187, + "scorer_mean": 0.012680185205681482, + "bias": -0.04014106195717039, + "mae": 0.05490639377186448, + "rmse": 0.15170595231276662, + "normalized_mae_by_direct_sd": 0.3462688789503198, + "pearson": 0.40155265811715135, + "spearman": 0.24849120782371034 + }, + "live_local_ranking": { + "top1_agreement": 0.1640625, + "pairwise_agreement": 0.5479910714285714, + "per_row_spearman_mean": 0.18173631998855827, + "per_row_spearman_median": 0.23067693607961265, + "direct_span_mean": 0.15814626216888428, + "scorer_span_mean": 0.01770695298910141, + "direct_data_action_best_rate": 0.46875, + "scorer_data_action_best_rate": 0.0703125 + }, + "ema_local_ranking": { + "top1_agreement": 0.1953125, + "pairwise_agreement": 0.5560825892857143, + "per_row_spearman_mean": 0.19980585692218172, + "per_row_spearman_median": 0.23881024523894495, + "direct_span_mean": 0.15814626216888428, + "scorer_span_mean": 0.017521098256111145, + "direct_data_action_best_rate": 0.46875, + "scorer_data_action_best_rate": 0.109375 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.2124292254447937, + "direct_q_actor_mean": 0.20856286585330963, + "direct_q_actor_minus_data_mean": -0.003866365645080805, + "direct_prefers_actor_rate": 0.484375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08101550511290495, + "scorer_mean": 0.011163711395056453, + "bias": -0.0698517937178485, + "mae": 0.0807766100416193, + "rmse": 0.19008491565424673, + "normalized_mae_by_direct_sd": 0.42911994833248124, + "pearson": 0.3567540392644088, + "spearman": 0.29467255604623555 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08101550511290495, + "scorer_mean": 0.012680185205681482, + "bias": -0.06833531990722347, + "mae": 0.08088976864285366, + "rmse": 0.19039198960329837, + "normalized_mae_by_direct_sd": 0.42972109528690333, + "pearson": 0.3448688009813023, + "spearman": 0.28608216356686933 + }, + "live_local_ranking": { + "top1_agreement": 0.1640625, + "pairwise_agreement": 0.5803571428571429, + "per_row_spearman_mean": 0.22120210105053173, + "per_row_spearman_median": 0.29248892488192957, + "direct_span_mean": 0.23021697998046875, + "scorer_span_mean": 0.01770695298910141, + "direct_data_action_best_rate": 0.578125, + "scorer_data_action_best_rate": 0.0703125 + }, + "ema_local_ranking": { + "top1_agreement": 0.171875, + "pairwise_agreement": 0.5823102678571429, + "per_row_spearman_mean": 0.22807706421896723, + "per_row_spearman_median": 0.261904761904762, + "direct_span_mean": 0.23021697998046875, + "scorer_span_mean": 0.017521098256111145, + "direct_data_action_best_rate": 0.578125, + "scorer_data_action_best_rate": 0.109375 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.2880809009075165, + "direct_q_actor_mean": 0.26958832144737244, + "direct_q_actor_minus_data_mean": -0.018492579460144043, + "direct_prefers_actor_rate": 0.4296875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11570492204821439, + "scorer_mean": 0.011163711395056453, + "bias": -0.10454121065315794, + "mae": 0.11413545533593929, + "rmse": 0.23116634833864835, + "normalized_mae_by_direct_sd": 0.527402783255339, + "pearson": 0.31709857027790234, + "spearman": 0.2606299153764098 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11570492204821439, + "scorer_mean": 0.012680185205681482, + "bias": -0.10302473684253291, + "mae": 0.11411583621594512, + "rmse": 0.2311793724418095, + "normalized_mae_by_direct_sd": 0.527312126250822, + "pearson": 0.3074958644561003, + "spearman": 0.2594479933842485 + }, + "live_local_ranking": { + "top1_agreement": 0.1015625, + "pairwise_agreement": 0.5784040178571429, + "per_row_spearman_mean": 0.2113531423387312, + "per_row_spearman_median": 0.2142857142857143, + "direct_span_mean": 0.3053022027015686, + "scorer_span_mean": 0.01770695298910141, + "direct_data_action_best_rate": 0.59375, + "scorer_data_action_best_rate": 0.0703125 + }, + "ema_local_ranking": { + "top1_agreement": 0.171875, + "pairwise_agreement": 0.5870535714285714, + "per_row_spearman_mean": 0.2303793349054636, + "per_row_spearman_median": 0.261904761904762, + "direct_span_mean": 0.3053022027015686, + "scorer_span_mean": 0.017521098256111145, + "direct_data_action_best_rate": 0.59375, + "scorer_data_action_best_rate": 0.109375 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step50000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step50000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..f6879b59387a16d57805c0638abf82a93c8d83ea --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step50000_distill_audit.json @@ -0,0 +1,633 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step50000.pkl", + "checkpoint_step": 50000, + "actor_source": "ema", + "rows": 256, + "samples_per_condition": 32, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "awr_distill", + "distill_actor_goals": false, + "distill_goal_loss_reduction": null, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 30.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "discount_sampling": { + "gamma_sampler": null, + "gamma_task_fraction": null, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": null, + "gamma_task_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": null, + "gamma_normalization": null, + "gamma_encoding_lo": null, + "gamma_encoding_hi": null, + "condition_normalizer_probe_size": null, + "condition_normalizer_seed": null, + "condition_normalizer_goal_sampler": null + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 256, + "direct_mean": 0.3119226427827755, + "scorer_mean": 0.19158621783685703, + "bias": -0.12033642494591845, + "mae": 0.13139322943285947, + "rmse": 0.16782327335551653, + "normalized_mae_by_direct_sd": 0.46726720533966454, + "pearson": 0.9093638232680296, + "spearman": 0.7469322213321125 + }, + "ema_data_actions": { + "n": 256, + "direct_mean": 0.3119226427827755, + "scorer_mean": 0.19980120092577636, + "bias": -0.11212144185699913, + "mae": 0.12609319381610362, + "rmse": 0.1637445338650299, + "normalized_mae_by_direct_sd": 0.4484189523396294, + "pearson": 0.9054910825276331, + "spearman": 0.7324881265735865 + }, + "live_local_candidates": { + "n": 2048, + "direct_mean": 0.14976976254637675, + "scorer_mean": 0.15250343549249123, + "bias": 0.002733672946114466, + "mae": 0.12188466207330606, + "rmse": 0.20147412437582887, + "normalized_mae_by_direct_sd": 0.4972856366872283, + "pearson": 0.6573415932698077, + "spearman": 0.4857427976596699 + }, + "ema_local_candidates": { + "n": 2048, + "direct_mean": 0.14976976254637675, + "scorer_mean": 0.16027074173643996, + "bias": 0.010500979190063191, + "mae": 0.1228174599396286, + "rmse": 0.20330565149028, + "normalized_mae_by_direct_sd": 0.5010914230180441, + "pearson": 0.6526770890933677, + "spearman": 0.48356478772281614 + }, + "live_data_and_actor": { + "n": 512, + "direct_mean": 0.34360678371844244, + "scorer_mean": 0.2147078727545022, + "bias": -0.12889891096394024, + "mae": 0.1403943375428156, + "rmse": 0.1752407388234102, + "normalized_mae_by_direct_sd": 0.5019799572847957, + "pearson": 0.9056665203131713, + "spearman": 0.7725073957725362 + }, + "ema_data_and_actor": { + "n": 512, + "direct_mean": 0.34360678371844244, + "scorer_mean": 0.2220650671504245, + "bias": -0.12154171656801793, + "mae": 0.1347389166768238, + "rmse": 0.17087276036330637, + "normalized_mae_by_direct_sd": 0.4817589998414634, + "pearson": 0.9033507992617464, + "spearman": 0.7627695093899132 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.34765625, + "pairwise_agreement": 0.73046875, + "per_row_spearman_mean": 0.5692784976517002, + "per_row_spearman_median": 0.6666666666666669, + "direct_span_mean": 0.33074700832366943, + "scorer_span_mean": 0.1874675154685974, + "direct_data_action_best_rate": 0.4765625, + "scorer_data_action_best_rate": 0.203125 + }, + "ema": { + "top1_agreement": 0.35546875, + "pairwise_agreement": 0.7315848214285714, + "per_row_spearman_mean": 0.5769550601459128, + "per_row_spearman_median": 0.6904761904761906, + "direct_span_mean": 0.33074700832366943, + "scorer_span_mean": 0.18637865781784058, + "direct_data_action_best_rate": 0.4765625, + "scorer_data_action_best_rate": 0.2265625 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.3119226427827755, + "std": 0.28119505912542586, + "min": 1.3053948350716382e-05, + "median": 0.18763402849435806, + "p90": 0.8417142629623413, + "p99": 0.9999415278434753, + "max": 0.9999874830245972 + }, + "direct_q_actor": { + "mean": 0.3752909246541094, + "std": 0.27452627093632354, + "min": 0.02528040111064911, + "median": 0.28123368322849274, + "p90": 0.8743646144866943, + "p99": 0.9999536365270615, + "max": 0.9999911785125732 + }, + "direct_q_actor_minus_data": { + "mean": 0.0633682817715453, + "std": 0.12001129210855302, + "min": -0.12813597917556763, + "median": 0.010267160832881927, + "p90": 0.21859413385391235, + "p99": 0.4718669325113296, + "max": 0.6262004375457764 + }, + "direct_prefers_actor_rate": 0.703125, + "live_scorer_q_data": { + "mean": 0.19158621783685703, + "std": 0.255881628525501, + "min": -0.02504822239279747, + "median": 0.07950485870242119, + "p90": 0.6609019637107849, + "p99": 0.9399995207786559, + "max": 0.9645777940750122 + }, + "live_scorer_q_actor": { + "mean": 0.23782952767214738, + "std": 0.2600558979229075, + "min": 0.006112665869295597, + "median": 0.12922796607017517, + "p90": 0.7010642290115356, + "p99": 0.9540509611368178, + "max": 0.9673798680305481 + }, + "live_scorer_actor_minus_data": { + "mean": 0.04624330990554881, + "std": 0.08374502560331515, + "min": -0.05892280861735344, + "median": 0.0110321044921875, + "p90": 0.15638692677021027, + "p99": 0.3448625817894931, + "max": 0.4296361207962036 + }, + "live_scorer_prefers_actor_rate": 0.703125, + "ema_scorer_q_data": { + "mean": 0.19980120092577636, + "std": 0.2558619910041077, + "min": -0.011490401811897755, + "median": 0.09042150899767876, + "p90": 0.6455915868282318, + "p99": 0.956664529442787, + "max": 0.9817212820053101 + }, + "ema_scorer_q_actor": { + "mean": 0.24432893337507267, + "std": 0.2594528161745902, + "min": 0.01985310949385166, + "median": 0.13199370354413986, + "p90": 0.7005268633365631, + "p99": 0.9725218772888182, + "max": 0.9818398952484131 + }, + "l2_to_paired_behavior_action": { + "mean": 0.781577638030285, + "std": 0.5421521665882958, + "min": 0.06468643248081207, + "median": 0.5849258303642273, + "p90": 1.6105594635009766, + "p99": 2.1910820603370653, + "max": 2.522270441055298 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.776018617209047, + "std": 1.1790025960427748, + "min": 0.19187122583389282, + "median": 1.4281506538391113, + "p90": 3.485261917114258, + "p99": 5.3456937789916985, + "max": 5.96953010559082 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0, + "actor_row_outside_dataset_p01_p99_rate": 0.0, + "actor_action_saturation_fraction": 0.0015625 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.015390485525131226, + "absolute_median": 0.008631192147731781, + "absolute_p95": 0.05253710225224495, + "absolute_max": 0.46649450063705444 + }, + "live_data_actions": { + "absolute_mean": 0.012019801884889603, + "absolute_median": 0.008191904984414577, + "absolute_p95": 0.0376700684428215, + "absolute_max": 0.08749598264694214 + }, + "live_actor_actions": { + "absolute_mean": 0.010575879365205765, + "absolute_median": 0.00721152126789093, + "absolute_p95": 0.032757148146629333, + "absolute_max": 0.0917167067527771 + }, + "ema_all_candidates": { + "absolute_mean": 0.013727807439863682, + "absolute_median": 0.007293662056326866, + "absolute_p95": 0.04509451612830162, + "absolute_max": 0.5004090070724487 + }, + "ema_data_actions": { + "absolute_mean": 0.009321398101747036, + "absolute_median": 0.006193496286869049, + "absolute_p95": 0.029317229986190796, + "absolute_max": 0.060370028018951416 + }, + "ema_actor_actions": { + "absolute_mean": 0.00914139486849308, + "absolute_median": 0.00623738206923008, + "absolute_p95": 0.02705281972885132, + "absolute_max": 0.053123682737350464 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.2405185825409717, + "std": 0.25531976145897994, + "min": 0.02294798381626606, + "median": 0.1325121521949768, + "p90": 0.6990163922309875, + "p99": 0.9765274584293364, + "max": 0.9853175282478333 + }, + "live_data_q_minus_value": { + "mean": -0.048932364807114936, + "std": 0.06545854274705008, + "min": -0.37876105308532715, + "median": -0.03376848250627518, + "p90": 0.004053004086017609, + "p99": 0.0743888363242147, + "max": 0.11910313367843628 + }, + "awr": { + "alpha": 30.0, + "expectile": 0.9, + "adv_norm": false, + "actor_after": 0, + "actor_after_reached": true, + "value": { + "mean": 0.2405185825409717, + "std": 0.25531976145897994, + "min": 0.02294798381626606, + "median": 0.1325121521949768, + "p90": 0.6990163922309875, + "p99": 0.9765274584293364, + "max": 0.9853175282478333 + }, + "advantage_q_live_min_minus_value": { + "mean": -0.048932364807114936, + "std": 0.06545854274705008, + "min": -0.37876105308532715, + "median": -0.03376848250627518, + "p90": 0.004053004086017609, + "p99": 0.0743888363242147, + "max": 0.11910313367843628 + }, + "transformed_advantage": { + "mean": -0.048932364807114936, + "std": 0.06545854274705008, + "min": -0.37876105308532715, + "median": -0.03376848250627518, + "p90": 0.004053004086017609, + "p99": 0.0743888363242147, + "max": 0.11910313367843628 + }, + "raw_weight": { + "mean": 0.7973777949025129, + "std": 2.6879445063539795, + "min": 1.1619438660862474e-05, + "median": 0.3631116188215592, + "p90": 1.1292972475810572, + "p99": 9.771738480229601, + "max": 35.62664778537816 + }, + "effective_weight": { + "mean": 0.7973777949025129, + "std": 2.6879445063539795, + "min": 1.1619438660862474e-05, + "median": 0.3631116188215592, + "p90": 1.1292972475810572, + "p99": 9.771738480229601, + "max": 35.62664778537816 + }, + "normalized_effective_sample_size": 0.08088320986187275, + "top_10pct_weight_mass": 0.5861398153840275, + "fraction_at_clip_100": 0.0 + } + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.12686121463775635, + "direct_q_actor_mean": 0.15479174256324768, + "direct_q_actor_minus_data_mean": 0.027930524200201035, + "direct_prefers_actor_rate": 0.63671875, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.06171698666417165, + "scorer_mean": 0.15250343549249123, + "bias": 0.09078644882831959, + "mae": 0.1122387324355835, + "rmse": 0.19362019419327553, + "normalized_mae_by_direct_sd": 0.5845284639761043, + "pearson": 0.7111435980665565, + "spearman": 0.574764245268659 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.06171698666417165, + "scorer_mean": 0.16027074173643996, + "bias": 0.09855375507226831, + "mae": 0.11806020359088984, + "rmse": 0.19680114759052322, + "normalized_mae_by_direct_sd": 0.614846122761545, + "pearson": 0.7147980378489769, + "spearman": 0.5662968970876904 + }, + "live_local_ranking": { + "top1_agreement": 0.34375, + "pairwise_agreement": 0.6491350446428571, + "per_row_spearman_mean": 0.43143918696066763, + "per_row_spearman_median": 0.523809523809524, + "direct_span_mean": 0.13833990693092346, + "scorer_span_mean": 0.1874675154685974, + "direct_data_action_best_rate": 0.265625, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.34375, + "pairwise_agreement": 0.6522042410714286, + "per_row_spearman_mean": 0.43913763863816957, + "per_row_spearman_median": 0.5543807947822272, + "direct_span_mean": 0.13833990693092346, + "scorer_span_mean": 0.18637865781784058, + "direct_data_action_best_rate": 0.265625, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.17621095478534698, + "direct_q_actor_mean": 0.2284141331911087, + "direct_q_actor_minus_data_mean": 0.05220317840576172, + "direct_prefers_actor_rate": 0.69921875, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.08521270100558465, + "scorer_mean": 0.15250343549249123, + "bias": 0.06729073448690658, + "mae": 0.1019475486246651, + "rmse": 0.18448117088741198, + "normalized_mae_by_direct_sd": 0.47904203367714093, + "pearson": 0.7210281852803648, + "spearman": 0.5813966992621487 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.08521270100558465, + "scorer_mean": 0.16027074173643996, + "bias": 0.0750580407308553, + "mae": 0.10665638136240534, + "rmse": 0.18776731057744991, + "normalized_mae_by_direct_sd": 0.5011684000426274, + "pearson": 0.7207910082982251, + "spearman": 0.5753730912213094 + }, + "live_local_ranking": { + "top1_agreement": 0.41015625, + "pairwise_agreement": 0.7098214285714286, + "per_row_spearman_mean": 0.5411060851830225, + "per_row_spearman_median": 0.6512036595592681, + "direct_span_mean": 0.19298851490020752, + "scorer_span_mean": 0.1874675154685974, + "direct_data_action_best_rate": 0.390625, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.41015625, + "pairwise_agreement": 0.7106584821428571, + "per_row_spearman_mean": 0.5464501717656879, + "per_row_spearman_median": 0.6428571428571429, + "direct_span_mean": 0.19298851490020752, + "scorer_span_mean": 0.18637865781784058, + "direct_data_action_best_rate": 0.390625, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.24388742446899414, + "direct_q_actor_mean": 0.304334819316864, + "direct_q_actor_minus_data_mean": 0.06044737249612808, + "direct_prefers_actor_rate": 0.703125, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.117058243598544, + "scorer_mean": 0.15250343549249123, + "bias": 0.035445191893947244, + "mae": 0.10429753181366519, + "rmse": 0.18748913756039998, + "normalized_mae_by_direct_sd": 0.4498372469042687, + "pearson": 0.6982092231835115, + "spearman": 0.5207255354200577 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.117058243598544, + "scorer_mean": 0.16027074173643996, + "bias": 0.04321249813789597, + "mae": 0.10679099730806847, + "rmse": 0.19032721009124037, + "normalized_mae_by_direct_sd": 0.4605916112094286, + "pearson": 0.6948501745003948, + "spearman": 0.5203120570515174 + }, + "live_local_ranking": { + "top1_agreement": 0.39453125, + "pairwise_agreement": 0.7373046875, + "per_row_spearman_mean": 0.5849945919531577, + "per_row_spearman_median": 0.7023809523809526, + "direct_span_mean": 0.2638808488845825, + "scorer_span_mean": 0.1874675154685974, + "direct_data_action_best_rate": 0.47265625, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.38671875, + "pairwise_agreement": 0.7395368303571429, + "per_row_spearman_mean": 0.5947539334203324, + "per_row_spearman_median": 0.6904761904761906, + "direct_span_mean": 0.2638808488845825, + "scorer_span_mean": 0.18637865781784058, + "direct_data_action_best_rate": 0.47265625, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.31192266941070557, + "direct_q_actor_mean": 0.3752909302711487, + "direct_q_actor_minus_data_mean": 0.06336827576160431, + "direct_prefers_actor_rate": 0.703125, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.14976976254637675, + "scorer_mean": 0.15250343549249123, + "bias": 0.002733672946114466, + "mae": 0.12188466207330606, + "rmse": 0.20147412437582887, + "normalized_mae_by_direct_sd": 0.4972856366872283, + "pearson": 0.6573415932698077, + "spearman": 0.4857427976596699 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.14976976254637675, + "scorer_mean": 0.16027074173643996, + "bias": 0.010500979190063191, + "mae": 0.1228174599396286, + "rmse": 0.20330565149028, + "normalized_mae_by_direct_sd": 0.5010914230180441, + "pearson": 0.6526770890933677, + "spearman": 0.48356478772281614 + }, + "live_local_ranking": { + "top1_agreement": 0.34765625, + "pairwise_agreement": 0.73046875, + "per_row_spearman_mean": 0.5692784976517002, + "per_row_spearman_median": 0.6666666666666669, + "direct_span_mean": 0.33074700832366943, + "scorer_span_mean": 0.1874675154685974, + "direct_data_action_best_rate": 0.4765625, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.35546875, + "pairwise_agreement": 0.7315848214285714, + "per_row_spearman_mean": 0.5769550601459128, + "per_row_spearman_median": 0.6904761904761906, + "direct_span_mean": 0.33074700832366943, + "scorer_span_mean": 0.18637865781784058, + "direct_data_action_best_rate": 0.4765625, + "scorer_data_action_best_rate": 0.2265625 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step100000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step100000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..4e3462eac95e5ee04d49b795efce56b3ab88f947 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step100000_distill_audit.json @@ -0,0 +1,562 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step100000.pkl", + "checkpoint_step": 100000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.28199791221242804, + "scorer_mean": 0.16977236848651955, + "bias": -0.11222554372590851, + "mae": 0.1348914619592321, + "rmse": 0.18447287029456286, + "normalized_mae_by_direct_sd": 0.5072778285310083, + "pearson": 0.8402432605616316, + "spearman": 0.7689239608130379 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.28199791221242804, + "scorer_mean": 0.17480625316966325, + "bias": -0.10719165904276481, + "mae": 0.13284221421225054, + "rmse": 0.18088943113129138, + "normalized_mae_by_direct_sd": 0.4995713515449034, + "pearson": 0.8405388501997327, + "spearman": 0.7681571598608313 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.12439922499920059, + "scorer_mean": 0.11786234574378796, + "bias": -0.006536879255412619, + "mae": 0.12191299110212511, + "rmse": 0.18530635236664367, + "normalized_mae_by_direct_sd": 0.5554076739035378, + "pearson": 0.6049753950058847, + "spearman": 0.5337695818580531 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.12439922499920059, + "scorer_mean": 0.1152366324902232, + "bias": -0.009162592508977373, + "mae": 0.12506350670023508, + "rmse": 0.1918014018413439, + "normalized_mae_by_direct_sd": 0.5697607016171904, + "pearson": 0.593239281778617, + "spearman": 0.5324902123793307 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.2862926113169817, + "scorer_mean": 0.20107568451112456, + "bias": -0.08521692680585717, + "mae": 0.13801342803310374, + "rmse": 0.18463661142995155, + "normalized_mae_by_direct_sd": 0.508767328016694, + "pearson": 0.7975698079883037, + "spearman": 0.68710374227512 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.2862926113169817, + "scorer_mean": 0.20790690528519917, + "bias": -0.07838570603178256, + "mae": 0.13665334109702937, + "rmse": 0.18407653729364598, + "normalized_mae_by_direct_sd": 0.5037535564859196, + "pearson": 0.7893277147757533, + "spearman": 0.6819795719844357 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.685546875, + "per_row_spearman_mean": 0.46788160114678845, + "per_row_spearman_median": 0.5671564572639016, + "direct_span_mean": 0.29672861099243164, + "scorer_span_mean": 0.2095155119895935, + "direct_data_action_best_rate": 0.5390625, + "scorer_data_action_best_rate": 0.203125 + }, + "ema": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.6849888392857143, + "per_row_spearman_mean": 0.4698238340237163, + "per_row_spearman_median": 0.5952380952380953, + "direct_span_mean": 0.29672861099243164, + "scorer_span_mean": 0.23438796401023865, + "direct_data_action_best_rate": 0.5390625, + "scorer_data_action_best_rate": 0.2109375 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.28199791221242804, + "std": 0.26591239429851526, + "min": 9.334989181199738e-28, + "median": 0.18748963624238968, + "p90": 0.74899263381958, + "p99": 0.9998159170150757, + "max": 0.9999809265136719 + }, + "direct_q_actor": { + "mean": 0.2905873104215354, + "std": 0.27645755671429567, + "min": 1.5044791418992872e-36, + "median": 0.18749190866947174, + "p90": 0.7499599397182465, + "p99": 0.9999175930023193, + "max": 0.9999584555625916 + }, + "direct_q_actor_minus_data": { + "mean": 0.008589398241505331, + "std": 0.18732855627779377, + "min": -0.9273035526275635, + "median": 4.9173831939697266e-06, + "p90": 0.1966136962175368, + "p99": 0.4832456937432292, + "max": 0.6196208000183105 + }, + "direct_prefers_actor_rate": 0.59375, + "live_scorer_q_data": { + "mean": 0.16977236848651955, + "std": 0.1979807343699232, + "min": 0.0001169710885733366, + "median": 0.090999536216259, + "p90": 0.40848519504070274, + "p99": 0.9120436394214634, + "max": 0.955824613571167 + }, + "live_scorer_q_actor": { + "mean": 0.23237900053572957, + "std": 0.21530043626220335, + "min": 0.00198621628805995, + "median": 0.1482035592198372, + "p90": 0.5625851690769195, + "p99": 0.9354161620140077, + "max": 0.9613955020904541 + }, + "live_scorer_actor_minus_data": { + "mean": 0.06260663216380635, + "std": 0.09162132383487533, + "min": -0.04038120061159134, + "median": 0.0318505484610796, + "p90": 0.16879415065050116, + "p99": 0.4365151396393777, + "max": 0.4830976128578186 + }, + "live_scorer_prefers_actor_rate": 0.8359375, + "ema_scorer_q_data": { + "mean": 0.17480625316966325, + "std": 0.20164378277390624, + "min": 0.0018758522346615791, + "median": 0.09325002133846283, + "p90": 0.4731350809335708, + "p99": 0.9086320751905446, + "max": 0.9512017369270325 + }, + "ema_scorer_q_actor": { + "mean": 0.2410075574007351, + "std": 0.22179570427176662, + "min": 0.010159306228160858, + "median": 0.15536180138587952, + "p90": 0.6005290985107421, + "p99": 0.9342111676931384, + "max": 0.9634042978286743 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8364607974654064, + "std": 0.434764788302483, + "min": 0.1104883998632431, + "median": 0.7326920926570892, + "p90": 1.4628453254699707, + "p99": 2.1119702899456034, + "max": 2.238661766052246 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.978736404213123, + "std": 1.0741162215892806, + "min": 0.24963440001010895, + "median": 1.777086853981018, + "p90": 3.453198099136352, + "p99": 5.071358661651612, + "max": 5.4412522315979 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0015625, + "actor_row_outside_dataset_p01_p99_rate": 0.0078125, + "actor_action_saturation_fraction": 0.0078125 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.015518509782850742, + "absolute_median": 0.00789511390030384, + "absolute_p95": 0.05657337233424187, + "absolute_max": 0.2331264466047287 + }, + "live_data_actions": { + "absolute_mean": 0.009966805577278137, + "absolute_median": 0.006270613521337509, + "absolute_p95": 0.03032112494111061, + "absolute_max": 0.0735321044921875 + }, + "live_actor_actions": { + "absolute_mean": 0.011641187593340874, + "absolute_median": 0.008889064192771912, + "absolute_p95": 0.034871362149715424, + "absolute_max": 0.08586382865905762 + }, + "ema_all_candidates": { + "absolute_mean": 0.015287118032574654, + "absolute_median": 0.008013598620891571, + "absolute_p95": 0.05424942821264267, + "absolute_max": 0.30343490839004517 + }, + "ema_data_actions": { + "absolute_mean": 0.009269317612051964, + "absolute_median": 0.005389750003814697, + "absolute_p95": 0.032689694315195084, + "absolute_max": 0.06607693433761597 + }, + "ema_actor_actions": { + "absolute_mean": 0.009830877184867859, + "absolute_median": 0.0070463791489601135, + "absolute_p95": 0.03531115502119064, + "absolute_max": 0.05605071783065796 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.2251188445079606, + "std": 0.2012460281206327, + "min": 0.03250766173005104, + "median": 0.15174608677625656, + "p90": 0.5163416266441345, + "p99": 0.9182382661104205, + "max": 0.9428394436836243 + }, + "live_data_q_minus_value": { + "mean": -0.05534647592867259, + "std": 0.07240458894932313, + "min": -0.3885103166103363, + "median": -0.03179075941443443, + "p90": 0.0029149137437343587, + "p99": 0.05183758050203341, + "max": 0.08446431159973145 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.09207825362682343, + "direct_q_actor_mean": 0.09929060935974121, + "direct_q_actor_minus_data_mean": 0.007212342694401741, + "direct_prefers_actor_rate": 0.6171875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03393679968139882, + "scorer_mean": 0.11786234574378796, + "bias": 0.08392554606238914, + "mae": 0.11602955501090048, + "rmse": 0.1786989488770477, + "normalized_mae_by_direct_sd": 0.8552089810098714, + "pearson": 0.5918926330253155, + "spearman": 0.5154258137730797 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03393679968139882, + "scorer_mean": 0.1152366324902232, + "bias": 0.08129983280882438, + "mae": 0.12019633582602862, + "rmse": 0.18577906876558758, + "normalized_mae_by_direct_sd": 0.8859207110915945, + "pearson": 0.5813233767313902, + "spearman": 0.5121522086738635 + }, + "live_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.6099330357142857, + "per_row_spearman_mean": 0.35897350666643446, + "per_row_spearman_median": 0.45804698456621806, + "direct_span_mean": 0.10017929971218109, + "scorer_span_mean": 0.2095155119895935, + "direct_data_action_best_rate": 0.296875, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.2578125, + "pairwise_agreement": 0.60546875, + "per_row_spearman_mean": 0.34774988728855405, + "per_row_spearman_median": 0.43250360452170666, + "direct_span_mean": 0.10017929971218109, + "scorer_span_mean": 0.23438796401023865, + "direct_data_action_best_rate": 0.296875, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14684759080410004, + "direct_q_actor_mean": 0.16718687117099762, + "direct_q_actor_minus_data_mean": 0.020339282229542732, + "direct_prefers_actor_rate": 0.578125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05760464522050723, + "scorer_mean": 0.11786234574378796, + "bias": 0.06025770052328073, + "mae": 0.10830813816131471, + "rmse": 0.1685205330998411, + "normalized_mae_by_direct_sd": 0.6538552744525296, + "pearson": 0.6271905248301353, + "spearman": 0.5796732430118325 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05760464522050723, + "scorer_mean": 0.1152366324902232, + "bias": 0.057631987269715974, + "mae": 0.11175740420868405, + "rmse": 0.17575546051339286, + "normalized_mae_by_direct_sd": 0.6746784631468397, + "pearson": 0.6145719388236645, + "spearman": 0.5776097799456489 + }, + "live_local_ranking": { + "top1_agreement": 0.3046875, + "pairwise_agreement": 0.6487165178571429, + "per_row_spearman_mean": 0.42579997106445455, + "per_row_spearman_median": 0.5952380952380953, + "direct_span_mean": 0.16212327778339386, + "scorer_span_mean": 0.2095155119895935, + "direct_data_action_best_rate": 0.3828125, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.642578125, + "per_row_spearman_mean": 0.4196939326743611, + "per_row_spearman_median": 0.5774384021375943, + "direct_span_mean": 0.16212327778339386, + "scorer_span_mean": 0.23438796401023865, + "direct_data_action_best_rate": 0.3828125, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.2073219120502472, + "direct_q_actor_mean": 0.22918447852134705, + "direct_q_actor_minus_data_mean": 0.021862562745809555, + "direct_prefers_actor_rate": 0.5859375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08734987337211841, + "scorer_mean": 0.11786234574378796, + "bias": 0.030512472371669534, + "mae": 0.1063409878309933, + "rmse": 0.16847511123545714, + "normalized_mae_by_direct_sd": 0.5506288887434635, + "pearson": 0.633683033359814, + "spearman": 0.5937601668594136 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08734987337211841, + "scorer_mean": 0.1152366324902232, + "bias": 0.027886759118104777, + "mae": 0.11038856600124959, + "rmse": 0.17557258462457703, + "normalized_mae_by_direct_sd": 0.5715870678562305, + "pearson": 0.6206700890006374, + "spearman": 0.5901604962293223 + }, + "live_local_ranking": { + "top1_agreement": 0.3203125, + "pairwise_agreement": 0.697265625, + "per_row_spearman_mean": 0.5062251578034157, + "per_row_spearman_median": 0.6309523809523809, + "direct_span_mean": 0.22597551345825195, + "scorer_span_mean": 0.2095155119895935, + "direct_data_action_best_rate": 0.5234375, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.34375, + "pairwise_agreement": 0.6964285714285714, + "per_row_spearman_mean": 0.5107987911271717, + "per_row_spearman_median": 0.6666666666666669, + "direct_span_mean": 0.22597551345825195, + "scorer_span_mean": 0.23438796401023865, + "direct_data_action_best_rate": 0.5234375, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.2819979190826416, + "direct_q_actor_mean": 0.29058730602264404, + "direct_q_actor_minus_data_mean": 0.008589396253228188, + "direct_prefers_actor_rate": 0.59375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.12439922499920059, + "scorer_mean": 0.11786234574378796, + "bias": -0.006536879255412619, + "mae": 0.12191299110212511, + "rmse": 0.18530635236664367, + "normalized_mae_by_direct_sd": 0.5554076739035378, + "pearson": 0.6049753950058847, + "spearman": 0.5337695818580531 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.12439922499920059, + "scorer_mean": 0.1152366324902232, + "bias": -0.009162592508977373, + "mae": 0.12506350670023508, + "rmse": 0.1918014018413439, + "normalized_mae_by_direct_sd": 0.5697607016171904, + "pearson": 0.593239281778617, + "spearman": 0.5324902123793307 + }, + "live_local_ranking": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.685546875, + "per_row_spearman_mean": 0.46788160114678845, + "per_row_spearman_median": 0.5671564572639016, + "direct_span_mean": 0.29672861099243164, + "scorer_span_mean": 0.2095155119895935, + "direct_data_action_best_rate": 0.5390625, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.6849888392857143, + "per_row_spearman_mean": 0.4698238340237163, + "per_row_spearman_median": 0.5952380952380953, + "direct_span_mean": 0.29672861099243164, + "scorer_span_mean": 0.23438796401023865, + "direct_data_action_best_rate": 0.5390625, + "scorer_data_action_best_rate": 0.2109375 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step150000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step150000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..f249f48c0b0646de3d1549a3e5c059cf0e46032c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step150000_distill_audit.json @@ -0,0 +1,562 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step150000.pkl", + "checkpoint_step": 150000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.2862490482290314, + "scorer_mean": 0.16081704100361094, + "bias": -0.12543200722542047, + "mae": 0.14211663053026036, + "rmse": 0.20093288081752808, + "normalized_mae_by_direct_sd": 0.5442239055496783, + "pearson": 0.811243763554221, + "spearman": 0.7368499359091741 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.2862490482290314, + "scorer_mean": 0.1485050672745274, + "bias": -0.13774398095450402, + "mae": 0.15140838495096154, + "rmse": 0.20831417593641555, + "normalized_mae_by_direct_sd": 0.5798059121127015, + "pearson": 0.8135947093830455, + "spearman": 0.7356482329243728 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.11965321073277418, + "scorer_mean": 0.11027039622695156, + "bias": -0.009382814505822621, + "mae": 0.12429085046701918, + "rmse": 0.18360677289591443, + "normalized_mae_by_direct_sd": 0.5762781059193208, + "pearson": 0.580359958366001, + "spearman": 0.4812779422425689 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.11965321073277418, + "scorer_mean": 0.09588667092930336, + "bias": -0.02376653980347082, + "mae": 0.12318624787482363, + "rmse": 0.18642737769041096, + "normalized_mae_by_direct_sd": 0.5711565842044708, + "pearson": 0.57866102540094, + "spearman": 0.4859060547071124 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.27646137181188607, + "scorer_mean": 0.19807364526059246, + "bias": -0.0783877265512936, + "mae": 0.15296052607111707, + "rmse": 0.20491355507183315, + "normalized_mae_by_direct_sd": 0.5622504733858538, + "pearson": 0.7181115454647604, + "spearman": 0.5627074273289081 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.27646137181188607, + "scorer_mean": 0.18279048421209154, + "bias": -0.09367088759979451, + "mae": 0.15807441535792097, + "rmse": 0.2092196699339081, + "normalized_mae_by_direct_sd": 0.5810480464996616, + "pearson": 0.7262079375304965, + "spearman": 0.5666363870450902 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.6743861607142857, + "per_row_spearman_mean": 0.4405033373632119, + "per_row_spearman_median": 0.5000000000000001, + "direct_span_mean": 0.30157047510147095, + "scorer_span_mean": 0.21043705940246582, + "direct_data_action_best_rate": 0.5, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.677734375, + "per_row_spearman_mean": 0.45286437568915017, + "per_row_spearman_median": 0.523809523809524, + "direct_span_mean": 0.30157047510147095, + "scorer_span_mean": 0.21530310809612274, + "direct_data_action_best_rate": 0.5, + "scorer_data_action_best_rate": 0.2265625 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.2862490482290314, + "std": 0.26113632473883963, + "min": 8.909525256430348e-29, + "median": 0.1874924600124359, + "p90": 0.7509812712669373, + "p99": 0.9983986848592759, + "max": 0.9999918937683105 + }, + "direct_q_actor": { + "mean": 0.26667369539474073, + "std": 0.28220414396185683, + "min": 0.0, + "median": 0.18743785470724106, + "p90": 0.7510169684886933, + "p99": 0.9988233810663223, + "max": 0.9999864101409912 + }, + "direct_q_actor_minus_data": { + "mean": -0.01957535335509849, + "std": 0.20342470789680794, + "min": -0.937649130821228, + "median": 2.5298566019849034e-10, + "p90": 0.18708776235580443, + "p99": 0.566976957321167, + "max": 0.6246435642242432 + }, + "direct_prefers_actor_rate": 0.515625, + "live_scorer_q_data": { + "mean": 0.16081704100361094, + "std": 0.17541652938178368, + "min": 0.01056649349629879, + "median": 0.0913303755223751, + "p90": 0.4062551736831665, + "p99": 0.82914697110653, + "max": 0.9578145146369934 + }, + "live_scorer_q_actor": { + "mean": 0.23533024951757398, + "std": 0.2068037741967674, + "min": 0.007999543100595474, + "median": 0.15603122860193253, + "p90": 0.5651581346988678, + "p99": 0.865620299577713, + "max": 0.9884002804756165 + }, + "live_scorer_actor_minus_data": { + "mean": 0.07451320842665154, + "std": 0.1022648090798066, + "min": -0.03224344551563263, + "median": 0.047575756907463074, + "p90": 0.17798282355070114, + "p99": 0.4723100244998934, + "max": 0.555863618850708 + }, + "live_scorer_prefers_actor_rate": 0.8359375, + "ema_scorer_q_data": { + "mean": 0.1485050672745274, + "std": 0.1754713723825523, + "min": -0.003370247781276703, + "median": 0.07875746488571167, + "p90": 0.39470194280147547, + "p99": 0.8321257555484781, + "max": 0.9477723836898804 + }, + "ema_scorer_q_actor": { + "mean": 0.2170759011496557, + "std": 0.20371617503374545, + "min": -0.0023661069571971893, + "median": 0.1280769407749176, + "p90": 0.5181831061840058, + "p99": 0.8574922305345538, + "max": 0.9732773900032043 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8377034498844296, + "std": 0.440889609140423, + "min": 0.1652621328830719, + "median": 0.7623181343078613, + "p90": 1.498947775363922, + "p99": 1.9622367036342627, + "max": 2.3216745853424072 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 2.0224650828167796, + "std": 1.1030358829114544, + "min": 0.4358205199241638, + "median": 1.8362366557121277, + "p90": 3.5949352502822873, + "p99": 4.984833579063417, + "max": 5.820572376251221 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.003125, + "actor_row_outside_dataset_p01_p99_rate": 0.015625, + "actor_action_saturation_fraction": 0.0078125 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.014633084647357464, + "absolute_median": 0.008204713463783264, + "absolute_p95": 0.050367459654808044, + "absolute_max": 0.242282435297966 + }, + "live_data_actions": { + "absolute_mean": 0.0102421585470438, + "absolute_median": 0.005888506770133972, + "absolute_p95": 0.0309627465903759, + "absolute_max": 0.0696481466293335 + }, + "live_actor_actions": { + "absolute_mean": 0.011564329266548157, + "absolute_median": 0.007846318185329437, + "absolute_p95": 0.034703776240348816, + "absolute_max": 0.05235224962234497 + }, + "ema_all_candidates": { + "absolute_mean": 0.013673007488250732, + "absolute_median": 0.007909806445240974, + "absolute_p95": 0.04673246294260025, + "absolute_max": 0.18584120273590088 + }, + "ema_data_actions": { + "absolute_mean": 0.008609754964709282, + "absolute_median": 0.006452590227127075, + "absolute_p95": 0.024033907800912857, + "absolute_max": 0.05218607187271118 + }, + "ema_actor_actions": { + "absolute_mean": 0.010057397186756134, + "absolute_median": 0.006747454404830933, + "absolute_p95": 0.029875457286834717, + "absolute_max": 0.05629384517669678 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.19772562793514226, + "std": 0.17842433775429128, + "min": 0.02462697960436344, + "median": 0.125780388712883, + "p90": 0.44298778772354125, + "p99": 0.8767548125982291, + "max": 0.9542702436447144 + }, + "live_data_q_minus_value": { + "mean": -0.03690858719346579, + "std": 0.06896805194343791, + "min": -0.35699230432510376, + "median": -0.0161801278591156, + "p90": 0.018030526489019393, + "p99": 0.06989710696041594, + "max": 0.12082186341285706 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.09268108010292053, + "direct_q_actor_mean": 0.097837895154953, + "direct_q_actor_minus_data_mean": 0.005156807601451874, + "direct_prefers_actor_rate": 0.5703125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03398218771492982, + "scorer_mean": 0.11027039622695156, + "bias": 0.07628820851202174, + "mae": 0.1119683680030777, + "rmse": 0.16320994171048803, + "normalized_mae_by_direct_sd": 0.8421014567750527, + "pearson": 0.6023945331474373, + "spearman": 0.4094327483825928 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03398218771492982, + "scorer_mean": 0.09588667092930336, + "bias": 0.06190448321437354, + "mae": 0.10384009677347092, + "rmse": 0.15975708827335733, + "normalized_mae_by_direct_sd": 0.780969646375472, + "pearson": 0.6007145669641135, + "spearman": 0.40086762254712494 + }, + "live_local_ranking": { + "top1_agreement": 0.328125, + "pairwise_agreement": 0.5968191964285714, + "per_row_spearman_mean": 0.32085457832049014, + "per_row_spearman_median": 0.3928571428571429, + "direct_span_mean": 0.09835733473300934, + "scorer_span_mean": 0.21043705940246582, + "direct_data_action_best_rate": 0.2421875, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema_local_ranking": { + "top1_agreement": 0.359375, + "pairwise_agreement": 0.5973772321428571, + "per_row_spearman_mean": 0.3220945116068261, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.09835733473300934, + "scorer_span_mean": 0.21530310809612274, + "direct_data_action_best_rate": 0.2421875, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14204367995262146, + "direct_q_actor_mean": 0.15088731050491333, + "direct_q_actor_minus_data_mean": 0.008843615651130676, + "direct_prefers_actor_rate": 0.5625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05463633548922433, + "scorer_mean": 0.11027039622695156, + "bias": 0.055634060737727226, + "mae": 0.10791472645273917, + "rmse": 0.160368270601709, + "normalized_mae_by_direct_sd": 0.6713844328630724, + "pearson": 0.6094066551861911, + "spearman": 0.5108723052355191 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05463633548922433, + "scorer_mean": 0.09588667092930336, + "bias": 0.04125033544007903, + "mae": 0.10058801928935648, + "rmse": 0.15851071136500194, + "normalized_mae_by_direct_sd": 0.6258018020643392, + "pearson": 0.6068133132175063, + "spearman": 0.5041060663069316 + }, + "live_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.6283482142857143, + "per_row_spearman_mean": 0.37996200253782164, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.15564781427383423, + "scorer_span_mean": 0.21043705940246582, + "direct_data_action_best_rate": 0.3984375, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema_local_ranking": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6196986607142857, + "per_row_spearman_mean": 0.36147467691957424, + "per_row_spearman_median": 0.44047619047619047, + "direct_span_mean": 0.15564781427383423, + "scorer_span_mean": 0.21530310809612274, + "direct_data_action_best_rate": 0.3984375, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.21105818450450897, + "direct_q_actor_mean": 0.21200919151306152, + "direct_q_actor_minus_data_mean": 0.0009510163217782974, + "direct_prefers_actor_rate": 0.546875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08295073640267901, + "scorer_mean": 0.11027039622695156, + "bias": 0.02731965982427255, + "mae": 0.10720561595953071, + "rmse": 0.16456294618590805, + "normalized_mae_by_direct_sd": 0.5691739929931932, + "pearson": 0.6085570219605821, + "spearman": 0.5267254960907977 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.08295073640267901, + "scorer_mean": 0.09588667092930336, + "bias": 0.012935934526624355, + "mae": 0.10265665851479164, + "rmse": 0.16501391774299917, + "normalized_mae_by_direct_sd": 0.545022755675965, + "pearson": 0.6054866059004562, + "spearman": 0.5262826802887652 + }, + "live_local_ranking": { + "top1_agreement": 0.2578125, + "pairwise_agreement": 0.6665736607142857, + "per_row_spearman_mean": 0.42834388286674796, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.22630907595157623, + "scorer_span_mean": 0.21043705940246582, + "direct_data_action_best_rate": 0.546875, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema_local_ranking": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.6665736607142857, + "per_row_spearman_mean": 0.4306543996703326, + "per_row_spearman_median": 0.5000000000000001, + "direct_span_mean": 0.22630907595157623, + "scorer_span_mean": 0.21530310809612274, + "direct_data_action_best_rate": 0.546875, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.286249041557312, + "direct_q_actor_mean": 0.2666737139225006, + "direct_q_actor_minus_data_mean": -0.01957535371184349, + "direct_prefers_actor_rate": 0.515625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11965321073277418, + "scorer_mean": 0.11027039622695156, + "bias": -0.009382814505822621, + "mae": 0.12429085046701918, + "rmse": 0.18360677289591443, + "normalized_mae_by_direct_sd": 0.5762781059193208, + "pearson": 0.580359958366001, + "spearman": 0.4812779422425689 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11965321073277418, + "scorer_mean": 0.09588667092930336, + "bias": -0.02376653980347082, + "mae": 0.12318624787482363, + "rmse": 0.18642737769041096, + "normalized_mae_by_direct_sd": 0.5711565842044708, + "pearson": 0.57866102540094, + "spearman": 0.4859060547071124 + }, + "live_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.6743861607142857, + "per_row_spearman_mean": 0.4405033373632119, + "per_row_spearman_median": 0.5000000000000001, + "direct_span_mean": 0.30157047510147095, + "scorer_span_mean": 0.21043705940246582, + "direct_data_action_best_rate": 0.5, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.677734375, + "per_row_spearman_mean": 0.45286437568915017, + "per_row_spearman_median": 0.523809523809524, + "direct_span_mean": 0.30157047510147095, + "scorer_span_mean": 0.21530310809612274, + "direct_data_action_best_rate": 0.5, + "scorer_data_action_best_rate": 0.2265625 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step200000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step200000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..35647fb4b60fcca510c431e20cbe26540924074f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step200000_distill_audit.json @@ -0,0 +1,562 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step200000.pkl", + "checkpoint_step": 200000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.2845038562040597, + "scorer_mean": 0.1265437479596585, + "bias": -0.15796010824440115, + "mae": 0.1716534942715971, + "rmse": 0.23518438260245342, + "normalized_mae_by_direct_sd": 0.6414714744609763, + "pearson": 0.7745575755678666, + "spearman": 0.6928676066654459 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.2845038562040597, + "scorer_mean": 0.13146435511589516, + "bias": -0.1530395010881645, + "mae": 0.16648803452565092, + "rmse": 0.23305255888621346, + "normalized_mae_by_direct_sd": 0.6221680801807633, + "pearson": 0.7694911534849259, + "spearman": 0.6961579838857351 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.11650485405705877, + "scorer_mean": 0.08532449623362481, + "bias": -0.031180357823433952, + "mae": 0.12097651230358877, + "rmse": 0.18914257284390848, + "normalized_mae_by_direct_sd": 0.5514569327737174, + "pearson": 0.5673589224501114, + "spearman": 0.4256833027534782 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.11650485405705877, + "scorer_mean": 0.08932945863398345, + "bias": -0.027175395423075323, + "mae": 0.12244709588627975, + "rmse": 0.19122469532498884, + "normalized_mae_by_direct_sd": 0.5581604117917193, + "pearson": 0.5601687085841879, + "spearman": 0.4217462374892041 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.26811828956450906, + "scorer_mean": 0.15751851264576544, + "bias": -0.11059977691874362, + "mae": 0.17363961516834758, + "rmse": 0.22978447349734063, + "normalized_mae_by_direct_sd": 0.6282601772758419, + "pearson": 0.6854288315336484, + "spearman": 0.49384584573128854 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.26811828956450906, + "scorer_mean": 0.16370218924203073, + "bias": -0.10441610032247833, + "mae": 0.17120315539924352, + "rmse": 0.2294295212799511, + "normalized_mae_by_direct_sd": 0.6194446161207524, + "pearson": 0.6736780550187491, + "spearman": 0.49373497940032035 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.3203125, + "pairwise_agreement": 0.6824776785714286, + "per_row_spearman_mean": 0.45986521244639994, + "per_row_spearman_median": 0.5357142857142858, + "direct_span_mean": 0.29665476083755493, + "scorer_span_mean": 0.17309322953224182, + "direct_data_action_best_rate": 0.6015625, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.67578125, + "per_row_spearman_mean": 0.44804219501839654, + "per_row_spearman_median": 0.48809523809523814, + "direct_span_mean": 0.29665476083755493, + "scorer_span_mean": 0.18196187913417816, + "direct_data_action_best_rate": 0.6015625, + "scorer_data_action_best_rate": 0.15625 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.2845038562040597, + "std": 0.2675933398532433, + "min": 3.669734323583493e-29, + "median": 0.18749310076236725, + "p90": 0.7019600391387938, + "p99": 0.9996308767795563, + "max": 0.9999824166297913 + }, + "direct_q_actor": { + "mean": 0.25173272292495846, + "std": 0.2839551335858529, + "min": 0.0, + "median": 0.12594901025295258, + "p90": 0.7042101263999939, + "p99": 0.9933797836303712, + "max": 0.9999707937240601 + }, + "direct_q_actor_minus_data": { + "mean": -0.03277113341476648, + "std": 0.23092473166425384, + "min": -0.9973827004432678, + "median": -5.569308996200562e-07, + "p90": 0.18748067915439606, + "p99": 0.5761489653587342, + "max": 0.6446354985237122 + }, + "direct_prefers_actor_rate": 0.4140625, + "live_scorer_q_data": { + "mean": 0.1265437479596585, + "std": 0.16587220757574042, + "min": -0.013763613998889923, + "median": 0.06939370930194855, + "p90": 0.3754079967737198, + "p99": 0.779000433683396, + "max": 0.9662199020385742 + }, + "live_scorer_q_actor": { + "mean": 0.18849327733187238, + "std": 0.19019696832426777, + "min": -0.0030800364911556244, + "median": 0.11061075702309608, + "p90": 0.46845314800739274, + "p99": 0.771570736765862, + "max": 0.9735816717147827 + }, + "live_scorer_actor_minus_data": { + "mean": 0.061949529277626425, + "std": 0.08819340557209383, + "min": -0.019251840189099312, + "median": 0.029241293668746948, + "p90": 0.15920259207487106, + "p99": 0.4140073171257973, + "max": 0.44311827421188354 + }, + "live_scorer_prefers_actor_rate": 0.828125, + "ema_scorer_q_data": { + "mean": 0.13146435511589516, + "std": 0.16485671474183866, + "min": -0.005903569981455803, + "median": 0.07077410072088242, + "p90": 0.3628881812095642, + "p99": 0.7884879237413412, + "max": 0.9683502316474915 + }, + "ema_scorer_q_actor": { + "mean": 0.1959400233681663, + "std": 0.19271809197198247, + "min": 0.004632548429071903, + "median": 0.11338233575224876, + "p90": 0.5029196918010712, + "p99": 0.7905860209465032, + "max": 0.9723404049873352 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8193167424760759, + "std": 0.4588340506168547, + "min": 0.11566413938999176, + "median": 0.7610881924629211, + "p90": 1.4895597696304321, + "p99": 1.9860563766956334, + "max": 2.376089334487915 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.9748654081486166, + "std": 1.1333206660753032, + "min": 0.24882087111473083, + "median": 1.8485347628593445, + "p90": 3.732298684120178, + "p99": 4.771498365402222, + "max": 5.97876501083374 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0015625, + "actor_row_outside_dataset_p01_p99_rate": 0.0078125, + "actor_action_saturation_fraction": 0.0109375 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.013473186641931534, + "absolute_median": 0.007023181766271591, + "absolute_p95": 0.04469048231840134, + "absolute_max": 0.3146290183067322 + }, + "live_data_actions": { + "absolute_mean": 0.008431239984929562, + "absolute_median": 0.005049123428761959, + "absolute_p95": 0.02456454373896122, + "absolute_max": 0.06343069672584534 + }, + "live_actor_actions": { + "absolute_mean": 0.010186033323407173, + "absolute_median": 0.006970718502998352, + "absolute_p95": 0.029642432928085327, + "absolute_max": 0.051746636629104614 + }, + "ema_all_candidates": { + "absolute_mean": 0.013152068480849266, + "absolute_median": 0.007225729525089264, + "absolute_p95": 0.04306764900684357, + "absolute_max": 0.2651989161968231 + }, + "ema_data_actions": { + "absolute_mean": 0.00900859385728836, + "absolute_median": 0.0062726084142923355, + "absolute_p95": 0.030039135366678238, + "absolute_max": 0.05150771141052246 + }, + "ema_actor_actions": { + "absolute_mean": 0.009695000015199184, + "absolute_median": 0.006101023405790329, + "absolute_p95": 0.029383361339569092, + "absolute_max": 0.0476401150226593 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.16769802068301942, + "std": 0.16908187139839348, + "min": 0.004427011124789715, + "median": 0.09669522941112518, + "p90": 0.409021446108818, + "p99": 0.7733451879024511, + "max": 0.9749568104743958 + }, + "live_data_q_minus_value": { + "mean": -0.04115427257056581, + "std": 0.06615795806848723, + "min": -0.3370082676410675, + "median": -0.0271303653717041, + "p90": 0.008972159773111341, + "p99": 0.07899669334292422, + "max": 0.17355209589004517 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.08855926990509033, + "direct_q_actor_mean": 0.08121328055858612, + "direct_q_actor_minus_data_mean": -0.007345985155552626, + "direct_prefers_actor_rate": 0.5390625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03343891829517591, + "scorer_mean": 0.08532449623362481, + "bias": 0.051885577938448904, + "mae": 0.09117603371885954, + "rmse": 0.15044123880764473, + "normalized_mae_by_direct_sd": 0.6707373205535212, + "pearson": 0.5976426408186323, + "spearman": 0.40245922169420234 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03343891829517591, + "scorer_mean": 0.08932945863398345, + "bias": 0.05589054033880754, + "mae": 0.0973920327359656, + "rmse": 0.15743144229854014, + "normalized_mae_by_direct_sd": 0.7164653738065618, + "pearson": 0.5802013436950981, + "spearman": 0.3751784416338793 + }, + "live_local_ranking": { + "top1_agreement": 0.328125, + "pairwise_agreement": 0.5834263392857143, + "per_row_spearman_mean": 0.347114351812686, + "per_row_spearman_median": 0.4097929892358346, + "direct_span_mean": 0.092277392745018, + "scorer_span_mean": 0.17309322953224182, + "direct_data_action_best_rate": 0.3515625, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema_local_ranking": { + "top1_agreement": 0.3046875, + "pairwise_agreement": 0.5842633928571429, + "per_row_spearman_mean": 0.34642858281417654, + "per_row_spearman_median": 0.4157811205454009, + "direct_span_mean": 0.092277392745018, + "scorer_span_mean": 0.18196187913417816, + "direct_data_action_best_rate": 0.3515625, + "scorer_data_action_best_rate": 0.15625 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14042700827121735, + "direct_q_actor_mean": 0.14210054278373718, + "direct_q_actor_minus_data_mean": 0.0016735382378101349, + "direct_prefers_actor_rate": 0.4921875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05398538011161132, + "scorer_mean": 0.08532449623362481, + "bias": 0.0313391161220135, + "mae": 0.0905513656617458, + "rmse": 0.15109812335249603, + "normalized_mae_by_direct_sd": 0.5537986117118777, + "pearson": 0.6103727080023151, + "spearman": 0.45300603780597903 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05398538011161132, + "scorer_mean": 0.08932945863398345, + "bias": 0.03534407852237213, + "mae": 0.09537108503858133, + "rmse": 0.15701660885736998, + "normalized_mae_by_direct_sd": 0.5832752946997739, + "pearson": 0.5956194471513055, + "spearman": 0.4330458956272651 + }, + "live_local_ranking": { + "top1_agreement": 0.2890625, + "pairwise_agreement": 0.6219308035714286, + "per_row_spearman_mean": 0.40060124988360635, + "per_row_spearman_median": 0.43386323069913424, + "direct_span_mean": 0.15045194327831268, + "scorer_span_mean": 0.17309322953224182, + "direct_data_action_best_rate": 0.4921875, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema_local_ranking": { + "top1_agreement": 0.2890625, + "pairwise_agreement": 0.6194196428571429, + "per_row_spearman_mean": 0.3925808701035412, + "per_row_spearman_median": 0.45796674351575284, + "direct_span_mean": 0.15045194327831268, + "scorer_span_mean": 0.18196187913417816, + "direct_data_action_best_rate": 0.4921875, + "scorer_data_action_best_rate": 0.15625 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.2151774764060974, + "direct_q_actor_mean": 0.200926274061203, + "direct_q_actor_minus_data_mean": -0.0142512246966362, + "direct_prefers_actor_rate": 0.484375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.0823615777527349, + "scorer_mean": 0.08532449623362481, + "bias": 0.0029629184808899287, + "mae": 0.09901013938002345, + "rmse": 0.16517205180082137, + "normalized_mae_by_direct_sd": 0.5152316980656906, + "pearson": 0.5918870346489727, + "spearman": 0.45376995768458506 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.0823615777527349, + "scorer_mean": 0.08932945863398345, + "bias": 0.0069678808812485655, + "mae": 0.10185173103876699, + "rmse": 0.16910161527260478, + "normalized_mae_by_direct_sd": 0.5300188512270883, + "pearson": 0.5815338213992773, + "spearman": 0.443737985489402 + }, + "live_local_ranking": { + "top1_agreement": 0.328125, + "pairwise_agreement": 0.6713169642857143, + "per_row_spearman_mean": 0.46771695671439073, + "per_row_spearman_median": 0.5476190476190477, + "direct_span_mean": 0.2236517369747162, + "scorer_span_mean": 0.17309322953224182, + "direct_data_action_best_rate": 0.546875, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema_local_ranking": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6671316964285714, + "per_row_spearman_mean": 0.45684519120933587, + "per_row_spearman_median": 0.5476190476190477, + "direct_span_mean": 0.2236517369747162, + "scorer_span_mean": 0.18196187913417816, + "direct_data_action_best_rate": 0.546875, + "scorer_data_action_best_rate": 0.15625 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.28450384736061096, + "direct_q_actor_mean": 0.2517327070236206, + "direct_q_actor_minus_data_mean": -0.03277113288640976, + "direct_prefers_actor_rate": 0.4140625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11650485405705877, + "scorer_mean": 0.08532449623362481, + "bias": -0.031180357823433952, + "mae": 0.12097651230358877, + "rmse": 0.18914257284390848, + "normalized_mae_by_direct_sd": 0.5514569327737174, + "pearson": 0.5673589224501114, + "spearman": 0.4256833027534782 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11650485405705877, + "scorer_mean": 0.08932945863398345, + "bias": -0.027175395423075323, + "mae": 0.12244709588627975, + "rmse": 0.19122469532498884, + "normalized_mae_by_direct_sd": 0.5581604117917193, + "pearson": 0.5601687085841879, + "spearman": 0.4217462374892041 + }, + "live_local_ranking": { + "top1_agreement": 0.3203125, + "pairwise_agreement": 0.6824776785714286, + "per_row_spearman_mean": 0.45986521244639994, + "per_row_spearman_median": 0.5357142857142858, + "direct_span_mean": 0.29665476083755493, + "scorer_span_mean": 0.17309322953224182, + "direct_data_action_best_rate": 0.6015625, + "scorer_data_action_best_rate": 0.1796875 + }, + "ema_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.67578125, + "per_row_spearman_mean": 0.44804219501839654, + "per_row_spearman_median": 0.48809523809523814, + "direct_span_mean": 0.29665476083755493, + "scorer_span_mean": 0.18196187913417816, + "direct_data_action_best_rate": 0.6015625, + "scorer_data_action_best_rate": 0.15625 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step250000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step250000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..5d6f57dd1513df363e6695d02a4e9f6673d4f0e9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step250000_distill_audit.json @@ -0,0 +1,562 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step250000.pkl", + "checkpoint_step": 250000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.2827785127545353, + "scorer_mean": 0.0842952307939413, + "bias": -0.198483281960594, + "mae": 0.20460797789864854, + "rmse": 0.29420348666226703, + "normalized_mae_by_direct_sd": 0.7453855979461653, + "pearson": 0.6298587708204396, + "spearman": 0.6204621406335835 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.2827785127545353, + "scorer_mean": 0.09094435891165631, + "bias": -0.191834153842879, + "mae": 0.1990391600676817, + "rmse": 0.28731335761774357, + "normalized_mae_by_direct_sd": 0.725098429032133, + "pearson": 0.6436218750921453, + "spearman": 0.6240271928218274 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.11313404640899413, + "scorer_mean": 0.055345181535813026, + "bias": -0.05778886487318111, + "mae": 0.11976384979432857, + "rmse": 0.20721492057914664, + "normalized_mae_by_direct_sd": 0.5511418383343463, + "pearson": 0.4502025708805814, + "spearman": 0.38471536174830934 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.11313404640899413, + "scorer_mean": 0.05880865768449439, + "bias": -0.054325388724499754, + "mae": 0.1206596864702716, + "rmse": 0.20580238662697156, + "normalized_mae_by_direct_sd": 0.5552643934565678, + "pearson": 0.46084361443121075, + "spearman": 0.3791117482277603 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.26358500927629935, + "scorer_mean": 0.11229549599738675, + "bias": -0.1512895132789126, + "mae": 0.20200456360937202, + "rmse": 0.28075765955398435, + "normalized_mae_by_direct_sd": 0.7294085973306271, + "pearson": 0.5222149536360418, + "spearman": 0.4009942206454566 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.26358500927629935, + "scorer_mean": 0.11778513651006506, + "bias": -0.1457998727662343, + "mae": 0.19766906021437902, + "rmse": 0.2755068272660634, + "normalized_mae_by_direct_sd": 0.7137537359078959, + "pearson": 0.5376754396015517, + "spearman": 0.39600666628519104 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.3046875, + "pairwise_agreement": 0.6746651785714286, + "per_row_spearman_mean": 0.45887788606236357, + "per_row_spearman_median": 0.5595238095238095, + "direct_span_mean": 0.3014201521873474, + "scorer_span_mean": 0.1313614547252655, + "direct_data_action_best_rate": 0.5625, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.6771763392857143, + "per_row_spearman_mean": 0.46384540385303696, + "per_row_spearman_median": 0.5714285714285715, + "direct_span_mean": 0.3014201521873474, + "scorer_span_mean": 0.14083099365234375, + "direct_data_action_best_rate": 0.5625, + "scorer_data_action_best_rate": 0.1796875 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.2827785127545353, + "std": 0.2744995053062806, + "min": 6.676650829009504e-29, + "median": 0.18745915591716766, + "p90": 0.7322130739688872, + "p99": 0.9972100520133973, + "max": 0.9999833106994629 + }, + "direct_q_actor": { + "mean": 0.24439150579806346, + "std": 0.2780432121326543, + "min": 0.0, + "median": 0.13377998769283295, + "p90": 0.6906696081161499, + "p99": 0.9985536187887192, + "max": 0.99997878074646 + }, + "direct_q_actor_minus_data": { + "mean": -0.038387006985643825, + "std": 0.23093537912987097, + "min": -0.9073760509490967, + "median": -3.3527612686157227e-07, + "p90": 0.13971345871686927, + "p99": 0.6193716073036194, + "max": 0.8123411536216736 + }, + "direct_prefers_actor_rate": 0.4375, + "live_scorer_q_data": { + "mean": 0.0842952307939413, + "std": 0.13162729572328521, + "min": -0.018330834805965424, + "median": 0.038722362369298935, + "p90": 0.24369750320911407, + "p99": 0.5980569922924042, + "max": 0.9435042142868042 + }, + "live_scorer_q_actor": { + "mean": 0.1402957612008322, + "std": 0.17449928939661832, + "min": -0.006056873127818108, + "median": 0.06346972845494747, + "p90": 0.3719696760177612, + "p99": 0.6721935749053958, + "max": 0.9659061431884766 + }, + "live_scorer_actor_minus_data": { + "mean": 0.056000530312303454, + "std": 0.09202366724066875, + "min": -0.027089416980743408, + "median": 0.019362840801477432, + "p90": 0.18558105826377866, + "p99": 0.4192570310831072, + "max": 0.47193408012390137 + }, + "live_scorer_prefers_actor_rate": 0.8046875, + "ema_scorer_q_data": { + "mean": 0.09094435891165631, + "std": 0.13652034876483157, + "min": -0.014414185658097267, + "median": 0.04123394936323166, + "p90": 0.25361326336860657, + "p99": 0.6211798989772798, + "max": 0.964000403881073 + }, + "ema_scorer_q_actor": { + "mean": 0.1446259141084738, + "std": 0.176309893532448, + "min": 0.000787561759352684, + "median": 0.06700734049081802, + "p90": 0.3766717195510864, + "p99": 0.6831206977367403, + "max": 0.9855639338493347 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8213771391892806, + "std": 0.4644622842820997, + "min": 0.15192735195159912, + "median": 0.7236697375774384, + "p90": 1.4391685366630553, + "p99": 2.0096606731414797, + "max": 2.34358811378479 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.9753935576882213, + "std": 1.1518208511202408, + "min": 0.35803306102752686, + "median": 1.7675701975822449, + "p90": 3.574965238571167, + "p99": 4.947695345878602, + "max": 5.94183874130249 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0046875, + "actor_row_outside_dataset_p01_p99_rate": 0.0234375, + "actor_action_saturation_fraction": 0.009375 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.012784499675035477, + "absolute_median": 0.006265201605856419, + "absolute_p95": 0.042120855301618576, + "absolute_max": 0.34764373302459717 + }, + "live_data_actions": { + "absolute_mean": 0.008336849510669708, + "absolute_median": 0.005153177306056023, + "absolute_p95": 0.0207871925085783, + "absolute_max": 0.08492786437273026 + }, + "live_actor_actions": { + "absolute_mean": 0.00984569825232029, + "absolute_median": 0.006008462980389595, + "absolute_p95": 0.03737123683094978, + "absolute_max": 0.06047731637954712 + }, + "ema_all_candidates": { + "absolute_mean": 0.012313740327954292, + "absolute_median": 0.0056767538189888, + "absolute_p95": 0.042463477700948715, + "absolute_max": 0.3832424283027649 + }, + "ema_data_actions": { + "absolute_mean": 0.007138485554605722, + "absolute_median": 0.004797397181391716, + "absolute_p95": 0.017373593524098396, + "absolute_max": 0.10123194009065628 + }, + "ema_actor_actions": { + "absolute_mean": 0.009489503689110279, + "absolute_median": 0.005454300902783871, + "absolute_p95": 0.0263761468231678, + "absolute_max": 0.06374441087245941 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.12278213496028911, + "std": 0.14726490132151446, + "min": -0.0031387675553560257, + "median": 0.06568943336606026, + "p90": 0.3046911805868149, + "p99": 0.6572800785303116, + "max": 0.9384984374046326 + }, + "live_data_q_minus_value": { + "mean": -0.03848690416634781, + "std": 0.05615339747813789, + "min": -0.3202109932899475, + "median": -0.02258317358791828, + "p90": -0.0007960168644785893, + "p99": 0.05273718662559995, + "max": 0.08681148290634155 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.09007972478866577, + "direct_q_actor_mean": 0.08111175894737244, + "direct_q_actor_minus_data_mean": -0.00896796677261591, + "direct_prefers_actor_rate": 0.484375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03225779334264549, + "scorer_mean": 0.055345181535813026, + "bias": 0.023087388193167538, + "mae": 0.07161746303983922, + "rmse": 0.13520737517862974, + "normalized_mae_by_direct_sd": 0.5501648353310782, + "pearson": 0.5236313073529169, + "spearman": 0.28244426374421217 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03225779334264549, + "scorer_mean": 0.05880865768449439, + "bias": 0.026550864341848904, + "mae": 0.07430881862985347, + "rmse": 0.13782458871468864, + "normalized_mae_by_direct_sd": 0.5708398095922286, + "pearson": 0.5301815645478519, + "spearman": 0.2661773362747967 + }, + "live_local_ranking": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.5767299107142857, + "per_row_spearman_mean": 0.32165960403318195, + "per_row_spearman_median": 0.37603676035837497, + "direct_span_mean": 0.095769964158535, + "scorer_span_mean": 0.1313614547252655, + "direct_data_action_best_rate": 0.3125, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_local_ranking": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.5892857142857143, + "per_row_spearman_mean": 0.3557026415227922, + "per_row_spearman_median": 0.4204822389962949, + "direct_span_mean": 0.095769964158535, + "scorer_span_mean": 0.14083099365234375, + "direct_data_action_best_rate": 0.3125, + "scorer_data_action_best_rate": 0.1796875 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.14169719815254211, + "direct_q_actor_mean": 0.13273736834526062, + "direct_q_actor_minus_data_mean": -0.008959848433732986, + "direct_prefers_actor_rate": 0.5, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05165940522575762, + "scorer_mean": 0.055345181535813026, + "bias": 0.003685776310055406, + "mae": 0.08053887769908445, + "rmse": 0.15218163897655138, + "normalized_mae_by_direct_sd": 0.5088934005666816, + "pearson": 0.4908675448950487, + "spearman": 0.36812879144801086 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05165940522575762, + "scorer_mean": 0.05880865768449439, + "bias": 0.007149252458736772, + "mae": 0.08279584706450038, + "rmse": 0.15282224953341894, + "normalized_mae_by_direct_sd": 0.5231542997517021, + "pearson": 0.502392493542907, + "spearman": 0.3530259174549509 + }, + "live_local_ranking": { + "top1_agreement": 0.203125, + "pairwise_agreement": 0.6104910714285714, + "per_row_spearman_mean": 0.3809805629513199, + "per_row_spearman_median": 0.5000000000000001, + "direct_span_mean": 0.15359263122081757, + "scorer_span_mean": 0.1313614547252655, + "direct_data_action_best_rate": 0.4375, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_local_ranking": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.6199776785714286, + "per_row_spearman_mean": 0.40635969062690347, + "per_row_spearman_median": 0.5313706708352453, + "direct_span_mean": 0.15359263122081757, + "scorer_span_mean": 0.14083099365234375, + "direct_data_action_best_rate": 0.4375, + "scorer_data_action_best_rate": 0.1796875 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.21177329123020172, + "direct_q_actor_mean": 0.1849423497915268, + "direct_q_actor_minus_data_mean": -0.02683095447719097, + "direct_prefers_actor_rate": 0.4296875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.07835852323114828, + "scorer_mean": 0.055345181535813026, + "bias": -0.023013341695335247, + "mae": 0.09432419643608736, + "rmse": 0.1756023551219884, + "normalized_mae_by_direct_sd": 0.505566125762509, + "pearson": 0.4654807956122376, + "spearman": 0.38686898827455707 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.07835852323114828, + "scorer_mean": 0.05880865768449439, + "bias": -0.01954986554665388, + "mae": 0.09606566183678242, + "rmse": 0.17495563909472694, + "normalized_mae_by_direct_sd": 0.5149001667514023, + "pearson": 0.4778432533236357, + "spearman": 0.3783079964942753 + }, + "live_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.66015625, + "per_row_spearman_mean": 0.4501574855477223, + "per_row_spearman_median": 0.5714285714285715, + "direct_span_mean": 0.22727099061012268, + "scorer_span_mean": 0.1313614547252655, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_local_ranking": { + "top1_agreement": 0.2421875, + "pairwise_agreement": 0.6685267857142857, + "per_row_spearman_mean": 0.47153288324845954, + "per_row_spearman_median": 0.5784843075988457, + "direct_span_mean": 0.22727099061012268, + "scorer_span_mean": 0.14083099365234375, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.1796875 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.2827785015106201, + "direct_q_actor_mean": 0.24439150094985962, + "direct_q_actor_minus_data_mean": -0.038387004286050797, + "direct_prefers_actor_rate": 0.4375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11313404640899413, + "scorer_mean": 0.055345181535813026, + "bias": -0.05778886487318111, + "mae": 0.11976384979432857, + "rmse": 0.20721492057914664, + "normalized_mae_by_direct_sd": 0.5511418383343463, + "pearson": 0.4502025708805814, + "spearman": 0.38471536174830934 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11313404640899413, + "scorer_mean": 0.05880865768449439, + "bias": -0.054325388724499754, + "mae": 0.1206596864702716, + "rmse": 0.20580238662697156, + "normalized_mae_by_direct_sd": 0.5552643934565678, + "pearson": 0.46084361443121075, + "spearman": 0.3791117482277603 + }, + "live_local_ranking": { + "top1_agreement": 0.3046875, + "pairwise_agreement": 0.6746651785714286, + "per_row_spearman_mean": 0.45887788606236357, + "per_row_spearman_median": 0.5595238095238095, + "direct_span_mean": 0.3014201521873474, + "scorer_span_mean": 0.1313614547252655, + "direct_data_action_best_rate": 0.5625, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_local_ranking": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.6771763392857143, + "per_row_spearman_mean": 0.46384540385303696, + "per_row_spearman_median": 0.5714285714285715, + "direct_span_mean": 0.3014201521873474, + "scorer_span_mean": 0.14083099365234375, + "direct_data_action_best_rate": 0.5625, + "scorer_data_action_best_rate": 0.1796875 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step300000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step300000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..7e39fadbde94f13b027bc375ab42b1048f3b0be1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step300000_distill_audit.json @@ -0,0 +1,562 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step300000.pkl", + "checkpoint_step": 300000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.28659560872856255, + "scorer_mean": 0.0747198596218368, + "bias": -0.21187574910672574, + "mae": 0.2171523864387749, + "rmse": 0.30667981985591836, + "normalized_mae_by_direct_sd": 0.806781865046493, + "pearson": 0.5797253936586617, + "spearman": 0.5333844533968137 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.28659560872856255, + "scorer_mean": 0.07736949487298261, + "bias": -0.20922611385557993, + "mae": 0.21510786135095677, + "rmse": 0.3054994602054238, + "normalized_mae_by_direct_sd": 0.7991858823795038, + "pearson": 0.5740737114960549, + "spearman": 0.5292128273210034 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.11154547305817411, + "scorer_mean": 0.04732836313996813, + "bias": -0.06421710991820598, + "mae": 0.1204554991438633, + "rmse": 0.20891875762175752, + "normalized_mae_by_direct_sd": 0.5581846977098148, + "pearson": 0.42511593044441537, + "spearman": 0.3426601483723595 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.11154547305817411, + "scorer_mean": 0.0525094696549786, + "bias": -0.059036003403195515, + "mae": 0.12029597549062185, + "rmse": 0.20730176789561053, + "normalized_mae_by_direct_sd": 0.557445473159711, + "pearson": 0.4232378106511196, + "spearman": 0.341668853233505 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.2537071694387132, + "scorer_mean": 0.09892020916595357, + "bias": -0.1547869602727596, + "mae": 0.21034584972149456, + "rmse": 0.2902688017586356, + "normalized_mae_by_direct_sd": 0.7898456767510219, + "pearson": 0.4143195902176924, + "spearman": 0.2827165924592942 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.2537071694387132, + "scorer_mean": 0.10286023980734171, + "bias": -0.15084692963137145, + "mae": 0.21026904849350017, + "rmse": 0.2901154040529515, + "normalized_mae_by_direct_sd": 0.789557289231226, + "pearson": 0.40126808010498866, + "spearman": 0.2710941830748878 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.6648995535714286, + "per_row_spearman_mean": 0.4605388453193498, + "per_row_spearman_median": 0.5476190476190477, + "direct_span_mean": 0.30397653579711914, + "scorer_span_mean": 0.12110266834497452, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.2109375 + }, + "ema": { + "top1_agreement": 0.265625, + "pairwise_agreement": 0.6632254464285714, + "per_row_spearman_mean": 0.45062659755362244, + "per_row_spearman_median": 0.523809523809524, + "direct_span_mean": 0.30397653579711914, + "scorer_span_mean": 0.11495013535022736, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.234375 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.28659560872856255, + "std": 0.26915873527506834, + "min": 3.2224334828809115e-29, + "median": 0.18748383224010468, + "p90": 0.7087082803249357, + "p99": 0.9979284608364105, + "max": 0.9999907612800598 + }, + "direct_q_actor": { + "mean": 0.2208187301488638, + "std": 0.2592972618857768, + "min": 0.0, + "median": 0.12502017617225647, + "p90": 0.6317775189876556, + "p99": 0.9911027467250825, + "max": 0.99998939037323 + }, + "direct_q_actor_minus_data": { + "mean": -0.06577687812188573, + "std": 0.2570592232781715, + "min": -0.9755803942680359, + "median": -4.558265209197998e-05, + "p90": 0.12704859301447866, + "p99": 0.6072036069631579, + "max": 0.8110612630844116 + }, + "direct_prefers_actor_rate": 0.375, + "live_scorer_q_data": { + "mean": 0.0747198596218368, + "std": 0.12343969517272092, + "min": -0.020524516701698303, + "median": 0.027896001935005188, + "p90": 0.21692586541175843, + "p99": 0.4860995802283287, + "max": 0.8790364861488342 + }, + "live_scorer_q_actor": { + "mean": 0.12312055871007033, + "std": 0.1685535585672559, + "min": -0.006640944629907608, + "median": 0.04622301273047924, + "p90": 0.3220406502485275, + "p99": 0.7081871604919442, + "max": 0.9201131463050842 + }, + "live_scorer_actor_minus_data": { + "mean": 0.04840069879719522, + "std": 0.0888906849154681, + "min": -0.015283115208148956, + "median": 0.006979560479521751, + "p90": 0.18096963614225386, + "p99": 0.3942903095483783, + "max": 0.4647418260574341 + }, + "live_scorer_prefers_actor_rate": 0.7421875, + "ema_scorer_q_data": { + "mean": 0.07736949487298261, + "std": 0.1231574610197669, + "min": -0.012443196028470993, + "median": 0.028522842563688755, + "p90": 0.21744235008955, + "p99": 0.4894923102855684, + "max": 0.8707940578460693 + }, + "ema_scorer_q_actor": { + "mean": 0.1283509847417008, + "std": 0.16990870218051254, + "min": -0.003491334617137909, + "median": 0.05242600291967392, + "p90": 0.3457366406917572, + "p99": 0.719676524400712, + "max": 0.9061127305030823 + }, + "l2_to_paired_behavior_action": { + "mean": 0.815387831418775, + "std": 0.4611716052141833, + "min": 0.16681085526943207, + "median": 0.7280645966529846, + "p90": 1.4119237303733825, + "p99": 1.983996950387955, + "max": 2.1663401126861572 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.9984567137435079, + "std": 1.162187863495862, + "min": 0.4315647780895233, + "median": 1.8198999762535095, + "p90": 3.7325297594070435, + "p99": 4.8931043910980225, + "max": 5.042513847351074 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0046875, + "actor_row_outside_dataset_p01_p99_rate": 0.0234375, + "actor_action_saturation_fraction": 0.0125 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.012447246350347996, + "absolute_median": 0.005419889464974403, + "absolute_p95": 0.04744625836610794, + "absolute_max": 0.2924770712852478 + }, + "live_data_actions": { + "absolute_mean": 0.0074082897044718266, + "absolute_median": 0.004822752438485622, + "absolute_p95": 0.022413339465856552, + "absolute_max": 0.06496655941009521 + }, + "live_actor_actions": { + "absolute_mean": 0.010028824210166931, + "absolute_median": 0.00509130023419857, + "absolute_p95": 0.04002918675541878, + "absolute_max": 0.05942288041114807 + }, + "ema_all_candidates": { + "absolute_mean": 0.011542589403688908, + "absolute_median": 0.0052201393991708755, + "absolute_p95": 0.04220892861485481, + "absolute_max": 0.2748197615146637 + }, + "ema_data_actions": { + "absolute_mean": 0.0071154069155454636, + "absolute_median": 0.004440500400960445, + "absolute_p95": 0.023952148854732513, + "absolute_max": 0.058413416147232056 + }, + "ema_actor_actions": { + "absolute_mean": 0.009059812873601913, + "absolute_median": 0.004554759711027145, + "absolute_p95": 0.033785026520490646, + "absolute_max": 0.06931096315383911 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.09712794100050814, + "std": 0.13181209127960922, + "min": -0.006601078435778618, + "median": 0.04595935717225075, + "p90": 0.2463591337203979, + "p99": 0.608825070858002, + "max": 0.8238841891288757 + }, + "live_data_q_minus_value": { + "mean": -0.022408081364119425, + "std": 0.0527587646584617, + "min": -0.2976597547531128, + "median": -0.007623524405062199, + "p90": 0.006497564166784283, + "p99": 0.07452422074973587, + "max": 0.17476886510849 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.09099577367305756, + "direct_q_actor_mean": 0.06849465519189835, + "direct_q_actor_minus_data_mean": -0.022501114755868912, + "direct_prefers_actor_rate": 0.46875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03264463720050374, + "scorer_mean": 0.04732836313996813, + "bias": 0.014683725939464386, + "mae": 0.06809442492694642, + "rmse": 0.12791176748873279, + "normalized_mae_by_direct_sd": 0.5330224914870714, + "pearson": 0.5092429153847354, + "spearman": 0.2146248055030212 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.03264463720050374, + "scorer_mean": 0.0525094696549786, + "bias": 0.019864832454474853, + "mae": 0.06948361814283976, + "rmse": 0.12753911425069367, + "normalized_mae_by_direct_sd": 0.543896674357208, + "pearson": 0.5103344472732535, + "spearman": 0.21740049522164842 + }, + "live_local_ranking": { + "top1_agreement": 0.21875, + "pairwise_agreement": 0.5703125, + "per_row_spearman_mean": 0.32907516471426124, + "per_row_spearman_median": 0.3333333333333334, + "direct_span_mean": 0.09638936817646027, + "scorer_span_mean": 0.12110266834497452, + "direct_data_action_best_rate": 0.3515625, + "scorer_data_action_best_rate": 0.2109375 + }, + "ema_local_ranking": { + "top1_agreement": 0.2109375, + "pairwise_agreement": 0.5666852678571429, + "per_row_spearman_mean": 0.32045306851759625, + "per_row_spearman_median": 0.30952380952380953, + "direct_span_mean": 0.09638936817646027, + "scorer_span_mean": 0.11495013535022736, + "direct_data_action_best_rate": 0.3515625, + "scorer_data_action_best_rate": 0.234375 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.1434316635131836, + "direct_q_actor_mean": 0.1086609810590744, + "direct_q_actor_minus_data_mean": -0.03477068617939949, + "direct_prefers_actor_rate": 0.4140625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05226644272096606, + "scorer_mean": 0.04732836313996813, + "bias": -0.004938079580997932, + "mae": 0.07862483481257529, + "rmse": 0.14956617301221578, + "normalized_mae_by_direct_sd": 0.5008274525904662, + "pearson": 0.4669765029384303, + "spearman": 0.2898925396830376 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.05226644272096606, + "scorer_mean": 0.0525094696549786, + "bias": 0.0002430269340125378, + "mae": 0.07977062290111393, + "rmse": 0.14879005748730353, + "normalized_mae_by_direct_sd": 0.5081259369810437, + "pearson": 0.46697226751822535, + "spearman": 0.29048586451280933 + }, + "live_local_ranking": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.6141183035714286, + "per_row_spearman_mean": 0.3988160794326941, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.1570030301809311, + "scorer_span_mean": 0.12110266834497452, + "direct_data_action_best_rate": 0.4765625, + "scorer_data_action_best_rate": 0.2109375 + }, + "ema_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.609375, + "per_row_spearman_mean": 0.3905364298714342, + "per_row_spearman_median": 0.4285714285714286, + "direct_span_mean": 0.1570030301809311, + "scorer_span_mean": 0.11495013535022736, + "direct_data_action_best_rate": 0.4765625, + "scorer_data_action_best_rate": 0.234375 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.21553805470466614, + "direct_q_actor_mean": 0.16339240968227386, + "direct_q_actor_minus_data_mean": -0.05214564502239227, + "direct_prefers_actor_rate": 0.421875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.07996436227822507, + "scorer_mean": 0.04732836313996813, + "bias": -0.03263599913825694, + "mae": 0.09593941003825922, + "rmse": 0.1796179288326054, + "normalized_mae_by_direct_sd": 0.5046679288974263, + "pearson": 0.4396003839267128, + "spearman": 0.33444778372153905 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.07996436227822507, + "scorer_mean": 0.0525094696549786, + "bias": -0.02745489262324647, + "mae": 0.09625862279179598, + "rmse": 0.17839449001828667, + "normalized_mae_by_direct_sd": 0.5063470765922141, + "pearson": 0.43873605457136733, + "spearman": 0.3363106251482771 + }, + "live_local_ranking": { + "top1_agreement": 0.265625, + "pairwise_agreement": 0.6576450892857143, + "per_row_spearman_mean": 0.458615286312588, + "per_row_spearman_median": 0.5282615638564785, + "direct_span_mean": 0.23266756534576416, + "scorer_span_mean": 0.12110266834497452, + "direct_data_action_best_rate": 0.578125, + "scorer_data_action_best_rate": 0.2109375 + }, + "ema_local_ranking": { + "top1_agreement": 0.3046875, + "pairwise_agreement": 0.6540178571428571, + "per_row_spearman_mean": 0.44736951097148214, + "per_row_spearman_median": 0.5074896463113507, + "direct_span_mean": 0.23266756534576416, + "scorer_span_mean": 0.11495013535022736, + "direct_data_action_best_rate": 0.578125, + "scorer_data_action_best_rate": 0.234375 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.2865956127643585, + "direct_q_actor_mean": 0.22081872820854187, + "direct_q_actor_minus_data_mean": -0.06577688455581665, + "direct_prefers_actor_rate": 0.375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11154547305817411, + "scorer_mean": 0.04732836313996813, + "bias": -0.06421710991820598, + "mae": 0.1204554991438633, + "rmse": 0.20891875762175752, + "normalized_mae_by_direct_sd": 0.5581846977098148, + "pearson": 0.42511593044441537, + "spearman": 0.3426601483723595 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11154547305817411, + "scorer_mean": 0.0525094696549786, + "bias": -0.059036003403195515, + "mae": 0.12029597549062185, + "rmse": 0.20730176789561053, + "normalized_mae_by_direct_sd": 0.557445473159711, + "pearson": 0.4232378106511196, + "spearman": 0.341668853233505 + }, + "live_local_ranking": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.6648995535714286, + "per_row_spearman_mean": 0.4605388453193498, + "per_row_spearman_median": 0.5476190476190477, + "direct_span_mean": 0.30397653579711914, + "scorer_span_mean": 0.12110266834497452, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.2109375 + }, + "ema_local_ranking": { + "top1_agreement": 0.265625, + "pairwise_agreement": 0.6632254464285714, + "per_row_spearman_mean": 0.45062659755362244, + "per_row_spearman_median": 0.523809523809524, + "direct_span_mean": 0.30397653579711914, + "scorer_span_mean": 0.11495013535022736, + "direct_data_action_best_rate": 0.5546875, + "scorer_data_action_best_rate": 0.234375 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step50000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step50000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..ce6fcf3ef8e855977a49be3c052928ef3dd050d9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step50000_distill_audit.json @@ -0,0 +1,579 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0_step50000.pkl", + "checkpoint_step": 50000, + "actor_source": "ema", + "rows": 256, + "samples_per_condition": 32, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 2, + "reader_reward_semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd2.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 2, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "distill_goal_loss_reduction": null, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "discount_sampling": { + "gamma_sampler": null, + "gamma_task_fraction": null, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": null, + "gamma_task_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": null, + "gamma_normalization": null, + "gamma_encoding_lo": null, + "gamma_encoding_hi": null, + "condition_normalizer_probe_size": null, + "condition_normalizer_seed": null, + "condition_normalizer_goal_sampler": null + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 2, + "semantics": "within_2_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 256, + "direct_mean": 0.3092021683728916, + "scorer_mean": 0.23349530537871033, + "bias": -0.07570686299418128, + "mae": 0.10408060660252261, + "rmse": 0.13610311732534752, + "normalized_mae_by_direct_sd": 0.3711726211799435, + "pearson": 0.9161721262568219, + "spearman": 0.7513182364385442 + }, + "ema_data_actions": { + "n": 256, + "direct_mean": 0.3092021683728916, + "scorer_mean": 0.23878245289051847, + "bias": -0.07041971548237314, + "mae": 0.10112613732640341, + "rmse": 0.1345773306913105, + "normalized_mae_by_direct_sd": 0.36063638257402636, + "pearson": 0.9139621480623301, + "spearman": 0.746594615472648 + }, + "live_local_candidates": { + "n": 2048, + "direct_mean": 0.1494942563437896, + "scorer_mean": 0.18644086708093255, + "bias": 0.03694661073714296, + "mae": 0.12693181190656055, + "rmse": 0.2105981988048738, + "normalized_mae_by_direct_sd": 0.5180460463138187, + "pearson": 0.6605664993880145, + "spearman": 0.4961520673149966 + }, + "ema_local_candidates": { + "n": 2048, + "direct_mean": 0.1494942563437896, + "scorer_mean": 0.19227304426954106, + "bias": 0.042778787925751474, + "mae": 0.12862863133018748, + "rmse": 0.21425130627705494, + "normalized_mae_by_direct_sd": 0.5249712652996275, + "pearson": 0.6555894291947229, + "spearman": 0.49990513205356174 + }, + "live_data_and_actor": { + "n": 512, + "direct_mean": 0.32235246945776863, + "scorer_mean": 0.26630151479503184, + "bias": -0.056050954662736824, + "mae": 0.1124789876733989, + "rmse": 0.14881342936401132, + "normalized_mae_by_direct_sd": 0.39564161559196714, + "pearson": 0.8783548678438315, + "spearman": 0.6919645539362103 + }, + "ema_data_and_actor": { + "n": 512, + "direct_mean": 0.32235246945776863, + "scorer_mean": 0.27153794773312256, + "bias": -0.050814521724646095, + "mae": 0.11005815309351916, + "rmse": 0.14684647082722563, + "normalized_mae_by_direct_sd": 0.38712639933623766, + "pearson": 0.8788566814410217, + "spearman": 0.6892720528490175 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.3671875, + "pairwise_agreement": 0.7279575892857143, + "per_row_spearman_mean": 0.566868139028254, + "per_row_spearman_median": 0.6666666666666669, + "direct_span_mean": 0.3277672529220581, + "scorer_span_mean": 0.2227562516927719, + "direct_data_action_best_rate": 0.48828125, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema": { + "top1_agreement": 0.390625, + "pairwise_agreement": 0.732421875, + "per_row_spearman_mean": 0.5755785792267054, + "per_row_spearman_median": 0.6865615798833741, + "direct_span_mean": 0.3277672529220581, + "scorer_span_mean": 0.2216266393661499, + "direct_data_action_best_rate": 0.48828125, + "scorer_data_action_best_rate": 0.2265625 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.3092021683728916, + "std": 0.28041024758683536, + "min": 1.720239015412517e-05, + "median": 0.1879964917898178, + "p90": 0.8492140471935272, + "p99": 0.9999474942684173, + "max": 0.9999900460243225 + }, + "direct_q_actor": { + "mean": 0.3355027705426457, + "std": 0.28752683893175873, + "min": 5.640490787113539e-13, + "median": 0.2483741044998169, + "p90": 0.8719860315322876, + "p99": 0.9999503910541534, + "max": 0.999988853931427 + }, + "direct_q_actor_minus_data": { + "mean": 0.026300602054107003, + "std": 0.1587438078287725, + "min": -0.7524793744087219, + "median": 0.005104660987854004, + "p90": 0.17729059606790543, + "p99": 0.4408586919307708, + "max": 0.5926143527030945 + }, + "direct_prefers_actor_rate": 0.609375, + "live_scorer_q_data": { + "mean": 0.23349530537871033, + "std": 0.2696443357950348, + "min": 0.0020993039943277836, + "median": 0.12101457267999649, + "p90": 0.7620754837989807, + "p99": 0.971706810593605, + "max": 0.985450267791748 + }, + "live_scorer_q_actor": { + "mean": 0.29910772421135334, + "std": 0.27212283828230394, + "min": 0.012600274756550789, + "median": 0.18521125614643097, + "p90": 0.8278063833713531, + "p99": 0.9827062368392944, + "max": 0.9945909380912781 + }, + "live_scorer_actor_minus_data": { + "mean": 0.06561241887720826, + "std": 0.09393957008841204, + "min": -0.09483128786087036, + "median": 0.031235452741384506, + "p90": 0.18801913410425186, + "p99": 0.3901860162615772, + "max": 0.5004268288612366 + }, + "live_scorer_prefers_actor_rate": 0.80859375, + "ema_scorer_q_data": { + "mean": 0.23878245289051847, + "std": 0.270563142441904, + "min": 0.002280249958857894, + "median": 0.12447983026504517, + "p90": 0.7563703656196594, + "p99": 0.9831093728542328, + "max": 0.9864024519920349 + }, + "ema_scorer_q_actor": { + "mean": 0.30429344257572666, + "std": 0.2735989678446467, + "min": 0.026391975581645966, + "median": 0.18470694869756699, + "p90": 0.8337101340293884, + "p99": 0.9919324785470962, + "max": 0.9975534677505493 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8038612141972408, + "std": 0.4277894220745863, + "min": 0.12727659940719604, + "median": 0.697952389717102, + "p90": 1.4067867994308472, + "p99": 1.9630281269550318, + "max": 1.996232032775879 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.9176858821883798, + "std": 1.033512752059501, + "min": 0.337926983833313, + "median": 1.7398570775985718, + "p90": 3.512453317642212, + "p99": 4.776695704460143, + "max": 5.59034538269043 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.00078125, + "actor_row_outside_dataset_p01_p99_rate": 0.00390625, + "actor_action_saturation_fraction": 0.00390625 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.015869151800870895, + "absolute_median": 0.009087517857551575, + "absolute_p95": 0.050998155027627945, + "absolute_max": 0.45051538944244385 + }, + "live_data_actions": { + "absolute_mean": 0.01118161529302597, + "absolute_median": 0.007648255676031113, + "absolute_p95": 0.03075682744383812, + "absolute_max": 0.11212480068206787 + }, + "live_actor_actions": { + "absolute_mean": 0.012172703631222248, + "absolute_median": 0.007462538778781891, + "absolute_p95": 0.036941178143024445, + "absolute_max": 0.07120078802108765 + }, + "ema_all_candidates": { + "absolute_mean": 0.014200806617736816, + "absolute_median": 0.008752565830945969, + "absolute_p95": 0.04210358113050461, + "absolute_max": 0.3926272392272949 + }, + "ema_data_actions": { + "absolute_mean": 0.00990969780832529, + "absolute_median": 0.00742693617939949, + "absolute_p95": 0.026726804673671722, + "absolute_max": 0.06556737422943115 + }, + "ema_actor_actions": { + "absolute_mean": 0.010883577167987823, + "absolute_median": 0.007796041667461395, + "absolute_p95": 0.031257521361112595, + "absolute_max": 0.0721426010131836 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.2871283179119928, + "std": 0.26771863304086724, + "min": 0.03241754695773125, + "median": 0.1774793192744255, + "p90": 0.8516786694526672, + "p99": 0.9947030067443847, + "max": 1.0042790174484253 + }, + "live_data_q_minus_value": { + "mean": -0.053633012452337425, + "std": 0.07512165014099458, + "min": -0.4550950527191162, + "median": -0.033449795097112656, + "p90": 0.007459864020347595, + "p99": 0.08622300177812547, + "max": 0.1231488287448883 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.12487342953681946, + "direct_q_actor_mean": 0.14670510590076447, + "direct_q_actor_minus_data_mean": 0.02183167263865471, + "direct_prefers_actor_rate": 0.6015625, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.05969936983635339, + "scorer_mean": 0.18644086708093255, + "bias": 0.12674149724457914, + "mae": 0.14433331265870358, + "rmse": 0.2248861463957992, + "normalized_mae_by_direct_sd": 0.760597755324508, + "pearson": 0.6938124369212465, + "spearman": 0.5947997776214813 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.05969936983635339, + "scorer_mean": 0.19227304426954106, + "bias": 0.13257367443318765, + "mae": 0.14945193899369652, + "rmse": 0.22898031342783376, + "normalized_mae_by_direct_sd": 0.7875715400248329, + "pearson": 0.6963358932266033, + "spearman": 0.5906063095654043 + }, + "live_local_ranking": { + "top1_agreement": 0.33984375, + "pairwise_agreement": 0.6626674107142857, + "per_row_spearman_mean": 0.4680256991780551, + "per_row_spearman_median": 0.5476190476190477, + "direct_span_mean": 0.1353311538696289, + "scorer_span_mean": 0.2227562516927719, + "direct_data_action_best_rate": 0.328125, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema_local_ranking": { + "top1_agreement": 0.375, + "pairwise_agreement": 0.6632254464285714, + "per_row_spearman_mean": 0.4700645546078029, + "per_row_spearman_median": 0.5714285714285715, + "direct_span_mean": 0.1353311538696289, + "scorer_span_mean": 0.2216266393661499, + "direct_data_action_best_rate": 0.328125, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.17523539066314697, + "direct_q_actor_mean": 0.2104628086090088, + "direct_q_actor_minus_data_mean": 0.035227395594120026, + "direct_prefers_actor_rate": 0.6484375, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.08359674688887855, + "scorer_mean": 0.18644086708093255, + "bias": 0.102844120192054, + "mae": 0.12765983773558698, + "rmse": 0.21028764483712636, + "normalized_mae_by_direct_sd": 0.6011380536603879, + "pearson": 0.7109962935019978, + "spearman": 0.6105731478052655 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.08359674688887855, + "scorer_mean": 0.19227304426954106, + "bias": 0.1086762973806625, + "mae": 0.13245969632876056, + "rmse": 0.21463936994913824, + "normalized_mae_by_direct_sd": 0.6237401319939179, + "pearson": 0.7099871823221073, + "spearman": 0.6090086173586594 + }, + "live_local_ranking": { + "top1_agreement": 0.3984375, + "pairwise_agreement": 0.7049386160714286, + "per_row_spearman_mean": 0.5400515525754419, + "per_row_spearman_median": 0.6190476190476191, + "direct_span_mean": 0.1918327808380127, + "scorer_span_mean": 0.2227562516927719, + "direct_data_action_best_rate": 0.39453125, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema_local_ranking": { + "top1_agreement": 0.40234375, + "pairwise_agreement": 0.7074497767857143, + "per_row_spearman_mean": 0.5496117982436926, + "per_row_spearman_median": 0.6666666666666669, + "direct_span_mean": 0.1918327808380127, + "scorer_span_mean": 0.2216266393661499, + "direct_data_action_best_rate": 0.39453125, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.2412349283695221, + "direct_q_actor_mean": 0.2741597294807434, + "direct_q_actor_minus_data_mean": 0.03292477875947952, + "direct_prefers_actor_rate": 0.65234375, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.11494308599056205, + "scorer_mean": 0.18644086708093255, + "bias": 0.0714977810903705, + "mae": 0.11713881482021621, + "rmse": 0.20436854291460063, + "normalized_mae_by_direct_sd": 0.5080074981047665, + "pearson": 0.6974268536618031, + "spearman": 0.5507954978192341 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.11494308599056205, + "scorer_mean": 0.19227304426954106, + "bias": 0.07732995827897901, + "mae": 0.12056637419603683, + "rmse": 0.20865098594743076, + "normalized_mae_by_direct_sd": 0.522872134269889, + "pearson": 0.6937334484456771, + "spearman": 0.5535258704132351 + }, + "live_local_ranking": { + "top1_agreement": 0.3828125, + "pairwise_agreement": 0.7321428571428571, + "per_row_spearman_mean": 0.5810906067447745, + "per_row_spearman_median": 0.6904761904761906, + "direct_span_mean": 0.26015323400497437, + "scorer_span_mean": 0.2227562516927719, + "direct_data_action_best_rate": 0.45703125, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema_local_ranking": { + "top1_agreement": 0.38671875, + "pairwise_agreement": 0.7342354910714286, + "per_row_spearman_mean": 0.592354410362668, + "per_row_spearman_median": 0.7142857142857144, + "direct_span_mean": 0.26015323400497437, + "scorer_span_mean": 0.2216266393661499, + "direct_data_action_best_rate": 0.45703125, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.3092021346092224, + "direct_q_actor_mean": 0.3355027437210083, + "direct_q_actor_minus_data_mean": 0.026300601661205292, + "direct_prefers_actor_rate": 0.609375, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.1494942563437896, + "scorer_mean": 0.18644086708093255, + "bias": 0.03694661073714296, + "mae": 0.12693181190656055, + "rmse": 0.2105981988048738, + "normalized_mae_by_direct_sd": 0.5180460463138187, + "pearson": 0.6605664993880145, + "spearman": 0.4961520673149966 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.1494942563437896, + "scorer_mean": 0.19227304426954106, + "bias": 0.042778787925751474, + "mae": 0.12862863133018748, + "rmse": 0.21425130627705494, + "normalized_mae_by_direct_sd": 0.5249712652996275, + "pearson": 0.6555894291947229, + "spearman": 0.49990513205356174 + }, + "live_local_ranking": { + "top1_agreement": 0.3671875, + "pairwise_agreement": 0.7279575892857143, + "per_row_spearman_mean": 0.566868139028254, + "per_row_spearman_median": 0.6666666666666669, + "direct_span_mean": 0.3277672529220581, + "scorer_span_mean": 0.2227562516927719, + "direct_data_action_best_rate": 0.48828125, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema_local_ranking": { + "top1_agreement": 0.390625, + "pairwise_agreement": 0.732421875, + "per_row_spearman_mean": 0.5755785792267054, + "per_row_spearman_median": 0.6865615798833741, + "direct_span_mean": 0.3277672529220581, + "scorer_span_mean": 0.2216266393661499, + "direct_data_action_best_rate": 0.48828125, + "scorer_data_action_best_rate": 0.2265625 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step100000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step100000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..76caeff617f3210ad61900bf388b187f9a091a3b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step100000_distill_audit.json @@ -0,0 +1,579 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step100000.pkl", + "checkpoint_step": 100000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 8, + "reader_reward_semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd8.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 8, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "distill_goal_loss_reduction": null, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "discount_sampling": { + "gamma_sampler": null, + "gamma_task_fraction": null, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": null, + "gamma_task_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": null, + "gamma_normalization": null, + "gamma_encoding_lo": null, + "gamma_encoding_hi": null, + "condition_normalizer_probe_size": null, + "condition_normalizer_seed": null, + "condition_normalizer_goal_sampler": null + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 8, + "semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.3377530433859312, + "scorer_mean": 0.1989026500195905, + "bias": -0.1388503933663407, + "mae": 0.15490590186931225, + "rmse": 0.20707661906117622, + "normalized_mae_by_direct_sd": 0.5285657541697939, + "pearson": 0.8587565180853789, + "spearman": 0.7843286485991575 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.3377530433859312, + "scorer_mean": 0.20226238963186915, + "bias": -0.13549065375406205, + "mae": 0.15139049384237008, + "rmse": 0.2026345576648331, + "normalized_mae_by_direct_sd": 0.5165705734016469, + "pearson": 0.8612309619996817, + "spearman": 0.786554660318623 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.1930818191822685, + "scorer_mean": 0.1571047606275897, + "bias": -0.03597705855467878, + "mae": 0.12890674125063392, + "rmse": 0.18493389228722512, + "normalized_mae_by_direct_sd": 0.5043103931051226, + "pearson": 0.7127794992177284, + "spearman": 0.5688691684250053 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.1930818191822685, + "scorer_mean": 0.15203012389247306, + "bias": -0.04105169528979544, + "mae": 0.1300306589397725, + "rmse": 0.1898898156557207, + "normalized_mae_by_direct_sd": 0.5087073964435689, + "pearson": 0.7058848954277731, + "spearman": 0.57589369054431 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.35207929869172305, + "scorer_mean": 0.23932195414454327, + "bias": -0.11275734454717978, + "mae": 0.15433665590283552, + "rmse": 0.2025075672604832, + "normalized_mae_by_direct_sd": 0.5258791581306794, + "pearson": 0.8195903582406907, + "spearman": 0.7523081654840924 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.35207929869172305, + "scorer_mean": 0.24378941215672967, + "bias": -0.10828988653499338, + "mae": 0.15010340068895955, + "rmse": 0.19849019670019835, + "normalized_mae_by_direct_sd": 0.511454971763528, + "pearson": 0.824046399268743, + "spearman": 0.7575410563057906 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.6607142857142857, + "per_row_spearman_mean": 0.40662202380952384, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.32928308844566345, + "scorer_span_mean": 0.18516230583190918, + "direct_data_action_best_rate": 0.4453125, + "scorer_data_action_best_rate": 0.1640625 + }, + "ema": { + "top1_agreement": 0.328125, + "pairwise_agreement": 0.6724330357142857, + "per_row_spearman_mean": 0.4332217261904763, + "per_row_spearman_median": 0.5357142857142858, + "direct_span_mean": 0.32928308844566345, + "scorer_span_mean": 0.20878753066062927, + "direct_data_action_best_rate": 0.4453125, + "scorer_data_action_best_rate": 0.2109375 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.3377530433859312, + "std": 0.29306836594553765, + "min": 3.332515266887305e-14, + "median": 0.24278827011585236, + "p90": 0.8695351183414459, + "p99": 0.9999612635374069, + "max": 0.9999897480010986 + }, + "direct_q_actor": { + "mean": 0.3664055539975149, + "std": 0.2931981118185135, + "min": 9.191183231171962e-11, + "median": 0.3056449592113495, + "p90": 0.8734715461730955, + "p99": 0.9999543803930283, + "max": 0.9999876618385315 + }, + "direct_q_actor_minus_data": { + "mean": 0.02865251050522035, + "std": 0.18749510674354194, + "min": -0.8054213523864746, + "median": 9.655952453613281e-05, + "p90": 0.23649487197399136, + "p99": 0.5316494452953339, + "max": 0.6040411591529846 + }, + "direct_prefers_actor_rate": 0.5703125, + "live_scorer_q_data": { + "mean": 0.1989026500195905, + "std": 0.21923649704798162, + "min": 0.005651670973747969, + "median": 0.10749885439872742, + "p90": 0.4757424950599668, + "p99": 0.9270322585105897, + "max": 0.9417256116867065 + }, + "live_scorer_q_actor": { + "mean": 0.27974125826949603, + "std": 0.24513176693131727, + "min": 0.005526184570044279, + "median": 0.18117519468069077, + "p90": 0.6968926250934601, + "p99": 0.9174303472042084, + "max": 0.95237797498703 + }, + "live_scorer_actor_minus_data": { + "mean": 0.08083860811893828, + "std": 0.11220620025788987, + "min": -0.038574524223804474, + "median": 0.03916569799184799, + "p90": 0.21943617612123487, + "p99": 0.48263812839984893, + "max": 0.5841256380081177 + }, + "live_scorer_prefers_actor_rate": 0.8125, + "ema_scorer_q_data": { + "mean": 0.20226238963186915, + "std": 0.22960672733510212, + "min": -0.0012113444972783327, + "median": 0.10363089293241501, + "p90": 0.515126323699951, + "p99": 0.941387494802475, + "max": 0.9667474031448364 + }, + "ema_scorer_q_actor": { + "mean": 0.2853164346815902, + "std": 0.2568169347923458, + "min": 0.008620062842965126, + "median": 0.1762526035308838, + "p90": 0.7260408341884612, + "p99": 0.9505975145101548, + "max": 0.9580432772636414 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8541208053356968, + "std": 0.44281553569598736, + "min": 0.12292288988828659, + "median": 0.732541024684906, + "p90": 1.478962254524231, + "p99": 2.0808887946605688, + "max": 2.2945828437805176 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 2.0540247585158795, + "std": 1.1039114016825593, + "min": 0.3923834562301636, + "median": 1.898736834526062, + "p90": 3.4322368144989013, + "p99": 5.070367641448975, + "max": 5.685698986053467 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0015625, + "actor_row_outside_dataset_p01_p99_rate": 0.0078125, + "actor_action_saturation_fraction": 0.0015625 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.016085578128695488, + "absolute_median": 0.008382752537727356, + "absolute_p95": 0.05713687092065811, + "absolute_max": 0.2533000111579895 + }, + "live_data_actions": { + "absolute_mean": 0.01071219053119421, + "absolute_median": 0.007202891632914543, + "absolute_p95": 0.033429890871047974, + "absolute_max": 0.0741204023361206 + }, + "live_actor_actions": { + "absolute_mean": 0.010749137960374355, + "absolute_median": 0.008020116947591305, + "absolute_p95": 0.036963291466236115, + "absolute_max": 0.07983553409576416 + }, + "ema_all_candidates": { + "absolute_mean": 0.015820354223251343, + "absolute_median": 0.008173777721822262, + "absolute_p95": 0.05884215235710144, + "absolute_max": 0.30748921632766724 + }, + "ema_data_actions": { + "absolute_mean": 0.008711425587534904, + "absolute_median": 0.006584241986274719, + "absolute_p95": 0.025472957640886307, + "absolute_max": 0.049344390630722046 + }, + "ema_actor_actions": { + "absolute_mean": 0.00892963819205761, + "absolute_median": 0.006828334182500839, + "absolute_p95": 0.025440718978643417, + "absolute_max": 0.04966306686401367 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.2536031997879036, + "std": 0.23375879804236052, + "min": 0.023611392825841904, + "median": 0.16951338946819305, + "p90": 0.572990822792053, + "p99": 0.9448409694433213, + "max": 0.979137122631073 + }, + "live_data_q_minus_value": { + "mean": -0.05470054945908487, + "std": 0.07872956732683926, + "min": -0.3872585892677307, + "median": -0.0304873026907444, + "p90": 0.012621974945068358, + "p99": 0.040872951969504384, + "max": 0.18192028999328613 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.16896575689315796, + "direct_q_actor_mean": 0.20057857036590576, + "direct_q_actor_minus_data_mean": 0.0316128209233284, + "direct_prefers_actor_rate": 0.625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1070573322786457, + "scorer_mean": 0.1571047606275897, + "bias": 0.050047428348944024, + "mae": 0.13034868245799525, + "rmse": 0.19088381346361308, + "normalized_mae_by_direct_sd": 0.5424952234629887, + "pearson": 0.6726896957347162, + "spearman": 0.5244510724914376 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1070573322786457, + "scorer_mean": 0.15203012389247306, + "bias": 0.04497279161382736, + "mae": 0.13035961477814995, + "rmse": 0.19428261418039422, + "normalized_mae_by_direct_sd": 0.5425407224381487, + "pearson": 0.6663642642941913, + "spearman": 0.505190635790241 + }, + "live_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.5733816964285714, + "per_row_spearman_mean": 0.18675567560040282, + "per_row_spearman_median": 0.28571428571428575, + "direct_span_mean": 0.2132662683725357, + "scorer_span_mean": 0.18516230583190918, + "direct_data_action_best_rate": 0.1953125, + "scorer_data_action_best_rate": 0.1640625 + }, + "ema_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.5795200892857143, + "per_row_spearman_mean": 0.20217455265329934, + "per_row_spearman_median": 0.30952380952380953, + "direct_span_mean": 0.2132662683725357, + "scorer_span_mean": 0.20878753066062927, + "direct_data_action_best_rate": 0.1953125, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.20937249064445496, + "direct_q_actor_mean": 0.24642550945281982, + "direct_q_actor_minus_data_mean": 0.03705301880836487, + "direct_prefers_actor_rate": 0.6484375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.12348566840366737, + "scorer_mean": 0.1571047606275897, + "bias": 0.03361909222392234, + "mae": 0.11534808471566547, + "rmse": 0.17302312773095546, + "normalized_mae_by_direct_sd": 0.48384656689690725, + "pearson": 0.7202292065105949, + "spearman": 0.5720925441873123 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.12348566840366737, + "scorer_mean": 0.15203012389247306, + "bias": 0.028544455488805687, + "mae": 0.1156350273035467, + "rmse": 0.17714268301399422, + "normalized_mae_by_direct_sd": 0.48505019491019485, + "pearson": 0.7121597531454262, + "spearman": 0.5631825717474579 + }, + "live_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.6104910714285714, + "per_row_spearman_mean": 0.2849900723570301, + "per_row_spearman_median": 0.38095238095238104, + "direct_span_mean": 0.24298524856567383, + "scorer_span_mean": 0.18516230583190918, + "direct_data_action_best_rate": 0.296875, + "scorer_data_action_best_rate": 0.1640625 + }, + "ema_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.6160714285714286, + "per_row_spearman_mean": 0.303726720351579, + "per_row_spearman_median": 0.38095238095238104, + "direct_span_mean": 0.24298524856567383, + "scorer_span_mean": 0.20878753066062927, + "direct_data_action_best_rate": 0.296875, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.27021172642707825, + "direct_q_actor_mean": 0.308868408203125, + "direct_q_actor_minus_data_mean": 0.03865668177604675, + "direct_prefers_actor_rate": 0.6171875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.15329323045314303, + "scorer_mean": 0.1571047606275897, + "bias": 0.0038115301744466867, + "mae": 0.11347711290615389, + "rmse": 0.17071378134630283, + "normalized_mae_by_direct_sd": 0.461852495299886, + "pearson": 0.7299835834548599, + "spearman": 0.5820225775159145 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.15329323045314303, + "scorer_mean": 0.15203012389247306, + "bias": -0.0012631065606699679, + "mae": 0.11462530823746292, + "rmse": 0.17534426489289862, + "normalized_mae_by_direct_sd": 0.46652565683242614, + "pearson": 0.7219877201472454, + "spearman": 0.5817214880909806 + }, + "live_local_ranking": { + "top1_agreement": 0.2421875, + "pairwise_agreement": 0.6481584821428571, + "per_row_spearman_mean": 0.3831845238095239, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.2859613299369812, + "scorer_span_mean": 0.18516230583190918, + "direct_data_action_best_rate": 0.4140625, + "scorer_data_action_best_rate": 0.1640625 + }, + "ema_local_ranking": { + "top1_agreement": 0.2890625, + "pairwise_agreement": 0.6615513392857143, + "per_row_spearman_mean": 0.40829613095238093, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.2859613299369812, + "scorer_span_mean": 0.20878753066062927, + "direct_data_action_best_rate": 0.4140625, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.3377530574798584, + "direct_q_actor_mean": 0.36640554666519165, + "direct_q_actor_minus_data_mean": 0.028652509674429893, + "direct_prefers_actor_rate": 0.5703125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1930818191822685, + "scorer_mean": 0.1571047606275897, + "bias": -0.03597705855467878, + "mae": 0.12890674125063392, + "rmse": 0.18493389228722512, + "normalized_mae_by_direct_sd": 0.5043103931051226, + "pearson": 0.7127794992177284, + "spearman": 0.5688691684250053 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1930818191822685, + "scorer_mean": 0.15203012389247306, + "bias": -0.04105169528979544, + "mae": 0.1300306589397725, + "rmse": 0.1898898156557207, + "normalized_mae_by_direct_sd": 0.5087073964435689, + "pearson": 0.7058848954277731, + "spearman": 0.57589369054431 + }, + "live_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.6607142857142857, + "per_row_spearman_mean": 0.40662202380952384, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.32928308844566345, + "scorer_span_mean": 0.18516230583190918, + "direct_data_action_best_rate": 0.4453125, + "scorer_data_action_best_rate": 0.1640625 + }, + "ema_local_ranking": { + "top1_agreement": 0.328125, + "pairwise_agreement": 0.6724330357142857, + "per_row_spearman_mean": 0.4332217261904763, + "per_row_spearman_median": 0.5357142857142858, + "direct_span_mean": 0.32928308844566345, + "scorer_span_mean": 0.20878753066062927, + "direct_data_action_best_rate": 0.4453125, + "scorer_data_action_best_rate": 0.2109375 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step150000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step150000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..76b25743040ef0f0f4a17358f8eacbeaa91c1127 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step150000_distill_audit.json @@ -0,0 +1,579 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step150000.pkl", + "checkpoint_step": 150000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 8, + "reader_reward_semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd8.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 8, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "distill_goal_loss_reduction": null, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "discount_sampling": { + "gamma_sampler": null, + "gamma_task_fraction": null, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": null, + "gamma_task_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": null, + "gamma_normalization": null, + "gamma_encoding_lo": null, + "gamma_encoding_hi": null, + "condition_normalizer_probe_size": null, + "condition_normalizer_seed": null, + "condition_normalizer_goal_sampler": null + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 8, + "semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.3415754329665105, + "scorer_mean": 0.18220770024345256, + "bias": -0.15936773272305788, + "mae": 0.17746516489814906, + "rmse": 0.2372267038262804, + "normalized_mae_by_direct_sd": 0.601170503178487, + "pearson": 0.8118276890995797, + "spearman": 0.7282033968137703 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.3415754329665105, + "scorer_mean": 0.17691748948709574, + "bias": -0.1646579434794147, + "mae": 0.1810715296111995, + "rmse": 0.24134551906581547, + "normalized_mae_by_direct_sd": 0.6133872111190789, + "pearson": 0.8122415755341812, + "spearman": 0.7304580205090642 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.18512854663042327, + "scorer_mean": 0.1325945928110741, + "bias": -0.05253395381934915, + "mae": 0.140519903961161, + "rmse": 0.19969786422811536, + "normalized_mae_by_direct_sd": 0.5628796777902134, + "pearson": 0.652927568182066, + "spearman": 0.45383327149345537 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.18512854663042327, + "scorer_mean": 0.1308655433840613, + "bias": -0.05426300324636195, + "mae": 0.13995999305276424, + "rmse": 0.19962237931320806, + "normalized_mae_by_direct_sd": 0.5606368462565632, + "pearson": 0.6508725042068575, + "spearman": 0.45568581914741435 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.3356010282603121, + "scorer_mean": 0.22740191632328788, + "bias": -0.10819911193702417, + "mae": 0.18032780530320897, + "rmse": 0.23707879743107244, + "normalized_mae_by_direct_sd": 0.6132263138725164, + "pearson": 0.7007344428882191, + "spearman": 0.6011115243762873 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.3356010282603121, + "scorer_mean": 0.21949845451308647, + "bias": -0.11610257374722557, + "mae": 0.18365188428852425, + "rmse": 0.24013354729641026, + "normalized_mae_by_direct_sd": 0.6245302428465231, + "pearson": 0.7017989090270658, + "spearman": 0.6005636301213091 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6721540178571429, + "per_row_spearman_mean": 0.42671130952380953, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.34869056940078735, + "scorer_span_mean": 0.20389419794082642, + "direct_data_action_best_rate": 0.4296875, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6729910714285714, + "per_row_spearman_mean": 0.42819940476190477, + "per_row_spearman_median": 0.4761904761904763, + "direct_span_mean": 0.34869056940078735, + "scorer_span_mean": 0.1894809603691101, + "direct_data_action_best_rate": 0.4296875, + "scorer_data_action_best_rate": 0.2265625 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.3415754329665105, + "std": 0.29519938845944976, + "min": 3.362764168686472e-14, + "median": 0.24286987632513046, + "p90": 0.848922091722488, + "p99": 0.9999090558290482, + "max": 0.9999772310256958 + }, + "direct_q_actor": { + "mean": 0.32962662355411365, + "std": 0.2928024068515969, + "min": 2.717184810485662e-10, + "median": 0.2530638575553894, + "p90": 0.7855446696281432, + "p99": 0.9995691680908203, + "max": 0.9999765157699585 + }, + "direct_q_actor_minus_data": { + "mean": -0.011948809500881384, + "std": 0.23581458690322904, + "min": -0.9958708882331848, + "median": 2.5406479835510254e-06, + "p90": 0.21987022757530209, + "p99": 0.5552741098403935, + "max": 0.6227979063987732 + }, + "direct_prefers_actor_rate": 0.5234375, + "live_scorer_q_data": { + "mean": 0.18220770024345256, + "std": 0.2054695286966049, + "min": 0.00492490641772747, + "median": 0.09742750599980354, + "p90": 0.47611840665340405, + "p99": 0.9052026140689854, + "max": 0.9421457052230835 + }, + "live_scorer_q_actor": { + "mean": 0.2725961324031232, + "std": 0.2403677924149092, + "min": 0.011200904846191406, + "median": 0.17899050563573837, + "p90": 0.6449570298194884, + "p99": 0.9193749821186067, + "max": 0.9418999552726746 + }, + "live_scorer_actor_minus_data": { + "mean": 0.09038843157759402, + "std": 0.11798166485501828, + "min": -0.06036970019340515, + "median": 0.04494093731045723, + "p90": 0.23409475684165953, + "p99": 0.4699437096714975, + "max": 0.5303030014038086 + }, + "live_scorer_prefers_actor_rate": 0.828125, + "ema_scorer_q_data": { + "mean": 0.17691748948709574, + "std": 0.2012513061435564, + "min": 0.002766504418104887, + "median": 0.09573601931333542, + "p90": 0.4609960407018659, + "p99": 0.9075882619619372, + "max": 0.9459314942359924 + }, + "ema_scorer_q_actor": { + "mean": 0.2620794195390772, + "std": 0.23658152753478545, + "min": 0.01305960863828659, + "median": 0.1644895151257515, + "p90": 0.642978686094284, + "p99": 0.9027919894456865, + "max": 0.9329928159713745 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8495990728260949, + "std": 0.43627299585404705, + "min": 0.18032975494861603, + "median": 0.7361533641815186, + "p90": 1.5310102701187134, + "p99": 1.9998995125293733, + "max": 2.3144516944885254 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 2.0692117360886186, + "std": 1.0888163764024175, + "min": 0.44891539216041565, + "median": 1.891869843006134, + "p90": 3.589652419090271, + "p99": 4.996139173507692, + "max": 5.765572547912598 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0015625, + "actor_row_outside_dataset_p01_p99_rate": 0.0078125, + "actor_action_saturation_fraction": 0.0046875 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.016481023281812668, + "absolute_median": 0.008969553746283054, + "absolute_p95": 0.059253156185150146, + "absolute_max": 0.23755550384521484 + }, + "live_data_actions": { + "absolute_mean": 0.011113722808659077, + "absolute_median": 0.007578130811452866, + "absolute_p95": 0.03430263698101044, + "absolute_max": 0.07364168763160706 + }, + "live_actor_actions": { + "absolute_mean": 0.012890230864286423, + "absolute_median": 0.008040517568588257, + "absolute_p95": 0.04188554733991623, + "absolute_max": 0.09030038118362427 + }, + "ema_all_candidates": { + "absolute_mean": 0.01538822054862976, + "absolute_median": 0.008322913199663162, + "absolute_p95": 0.05310184508562088, + "absolute_max": 0.2017202079296112 + }, + "ema_data_actions": { + "absolute_mean": 0.009301668964326382, + "absolute_median": 0.005847247317433357, + "absolute_p95": 0.02810651808977127, + "absolute_max": 0.057520270347595215 + }, + "ema_actor_actions": { + "absolute_mean": 0.011531217023730278, + "absolute_median": 0.007187061011791229, + "absolute_p95": 0.037432003766298294, + "absolute_max": 0.07192015647888184 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.23519480956019834, + "std": 0.20476754531530486, + "min": 0.03864182531833649, + "median": 0.14923930913209915, + "p90": 0.5536246359348297, + "p99": 0.8906120038032534, + "max": 0.9492670297622681 + }, + "live_data_q_minus_value": { + "mean": -0.052987109156674705, + "std": 0.07287382394692307, + "min": -0.3803294599056244, + "median": -0.03213026933372021, + "p90": -0.0006552249193191675, + "p99": 0.06051947556436074, + "max": 0.12499922513961792 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.16687139868736267, + "direct_q_actor_mean": 0.16693547368049622, + "direct_q_actor_minus_data_mean": 6.407639011740685e-05, + "direct_prefers_actor_rate": 0.5859375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.09670052071177879, + "scorer_mean": 0.1325945928110741, + "bias": 0.035894072099295314, + "mae": 0.12463040624928903, + "rmse": 0.18379505914494404, + "normalized_mae_by_direct_sd": 0.5628200744425793, + "pearson": 0.6383037130633897, + "spearman": 0.4086741797063756 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.09670052071177879, + "scorer_mean": 0.1308655433840613, + "bias": 0.03416502267228252, + "mae": 0.12144570487478856, + "rmse": 0.1809556962546064, + "normalized_mae_by_direct_sd": 0.5484382400362267, + "pearson": 0.641059599084452, + "spearman": 0.42214874103786876 + }, + "live_local_ranking": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.5672433035714286, + "per_row_spearman_mean": 0.16259395204448143, + "per_row_spearman_median": 0.27380952380952384, + "direct_span_mean": 0.20828647911548615, + "scorer_span_mean": 0.20389419794082642, + "direct_data_action_best_rate": 0.21875, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.5630580357142857, + "per_row_spearman_mean": 0.15204406225678044, + "per_row_spearman_median": 0.19047619047619052, + "direct_span_mean": 0.20828647911548615, + "scorer_span_mean": 0.1894809603691101, + "direct_data_action_best_rate": 0.21875, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.21165552735328674, + "direct_q_actor_mean": 0.21088287234306335, + "direct_q_actor_minus_data_mean": -0.0007726633921265602, + "direct_prefers_actor_rate": 0.59375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11581462540709161, + "scorer_mean": 0.1325945928110741, + "bias": 0.016779967403982493, + "mae": 0.11733548139115912, + "rmse": 0.1757586252277088, + "normalized_mae_by_direct_sd": 0.5197516995212128, + "pearson": 0.6683276456718406, + "spearman": 0.45356818257636455 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11581462540709161, + "scorer_mean": 0.1308655433840613, + "bias": 0.015050917976969697, + "mae": 0.1146106856086023, + "rmse": 0.17345706856896267, + "normalized_mae_by_direct_sd": 0.5076818872015196, + "pearson": 0.6704650133495345, + "spearman": 0.46769133487474895 + }, + "live_local_ranking": { + "top1_agreement": 0.2890625, + "pairwise_agreement": 0.60546875, + "per_row_spearman_mean": 0.2834081255880076, + "per_row_spearman_median": 0.38095238095238104, + "direct_span_mean": 0.24885138869285583, + "scorer_span_mean": 0.20389419794082642, + "direct_data_action_best_rate": 0.3125, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.3046875, + "pairwise_agreement": 0.6046316964285714, + "per_row_spearman_mean": 0.27266998949822063, + "per_row_spearman_median": 0.3214285714285715, + "direct_span_mean": 0.24885138869285583, + "scorer_span_mean": 0.1894809603691101, + "direct_data_action_best_rate": 0.3125, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.27428919076919556, + "direct_q_actor_mean": 0.26938149333000183, + "direct_q_actor_minus_data_mean": -0.0049076564610004425, + "direct_prefers_actor_rate": 0.5859375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1461854610204859, + "scorer_mean": 0.1325945928110741, + "bias": -0.013590868209411822, + "mae": 0.12129572961728805, + "rmse": 0.179253359599306, + "normalized_mae_by_direct_sd": 0.514831458238168, + "pearson": 0.6744210821140074, + "spearman": 0.45117552392532717 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1461854610204859, + "scorer_mean": 0.1308655433840613, + "bias": -0.015319917636424618, + "mae": 0.1199197130497045, + "rmse": 0.1782415923642171, + "normalized_mae_by_direct_sd": 0.508991049690529, + "pearson": 0.6738507354218446, + "spearman": 0.46070922144338744 + }, + "live_local_ranking": { + "top1_agreement": 0.2890625, + "pairwise_agreement": 0.6375558035714286, + "per_row_spearman_mean": 0.34040178571428575, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.2963426113128662, + "scorer_span_mean": 0.20389419794082642, + "direct_data_action_best_rate": 0.3984375, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.63671875, + "per_row_spearman_mean": 0.33444940476190477, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.2963426113128662, + "scorer_span_mean": 0.1894809603691101, + "direct_data_action_best_rate": 0.3984375, + "scorer_data_action_best_rate": 0.2265625 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.3415754437446594, + "direct_q_actor_mean": 0.3296266198158264, + "direct_q_actor_minus_data_mean": -0.011948810890316963, + "direct_prefers_actor_rate": 0.5234375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.18512854663042327, + "scorer_mean": 0.1325945928110741, + "bias": -0.05253395381934915, + "mae": 0.140519903961161, + "rmse": 0.19969786422811536, + "normalized_mae_by_direct_sd": 0.5628796777902134, + "pearson": 0.652927568182066, + "spearman": 0.45383327149345537 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.18512854663042327, + "scorer_mean": 0.1308655433840613, + "bias": -0.05426300324636195, + "mae": 0.13995999305276424, + "rmse": 0.19962237931320806, + "normalized_mae_by_direct_sd": 0.5606368462565632, + "pearson": 0.6508725042068575, + "spearman": 0.45568581914741435 + }, + "live_local_ranking": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6721540178571429, + "per_row_spearman_mean": 0.42671130952380953, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.34869056940078735, + "scorer_span_mean": 0.20389419794082642, + "direct_data_action_best_rate": 0.4296875, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6729910714285714, + "per_row_spearman_mean": 0.42819940476190477, + "per_row_spearman_median": 0.4761904761904763, + "direct_span_mean": 0.34869056940078735, + "scorer_span_mean": 0.1894809603691101, + "direct_data_action_best_rate": 0.4296875, + "scorer_data_action_best_rate": 0.2265625 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step200000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step200000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..00f4f096ccf3db5311786e7f9b435fb60887078a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step200000_distill_audit.json @@ -0,0 +1,579 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step200000.pkl", + "checkpoint_step": 200000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 8, + "reader_reward_semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd8.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 8, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "distill_goal_loss_reduction": null, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "discount_sampling": { + "gamma_sampler": null, + "gamma_task_fraction": null, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": null, + "gamma_task_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": null, + "gamma_normalization": null, + "gamma_encoding_lo": null, + "gamma_encoding_hi": null, + "condition_normalizer_probe_size": null, + "condition_normalizer_seed": null, + "condition_normalizer_goal_sampler": null + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 8, + "semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.34161798019528966, + "scorer_mean": 0.13710474447725574, + "bias": -0.20451323571803393, + "mae": 0.21521217411552246, + "rmse": 0.28955682035535485, + "normalized_mae_by_direct_sd": 0.7377101050702431, + "pearson": 0.7228593439167765, + "spearman": 0.6729078923274125 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.34161798019528966, + "scorer_mean": 0.14569498402124736, + "bias": -0.1959229961740423, + "mae": 0.20727850392538133, + "rmse": 0.28251785356509124, + "normalized_mae_by_direct_sd": 0.7105148560393031, + "pearson": 0.7247865117872953, + "spearman": 0.6788534609045962 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.19730951414862796, + "scorer_mean": 0.10429593667959125, + "bias": -0.09301357746903671, + "mae": 0.1538195943424507, + "rmse": 0.22660243245226835, + "normalized_mae_by_direct_sd": 0.6080464155492475, + "pearson": 0.5817777943511165, + "spearman": 0.4008836892503769 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.19730951414862796, + "scorer_mean": 0.11137255729227036, + "bias": -0.0859369568563576, + "mae": 0.15206787041445569, + "rmse": 0.2245535681179651, + "normalized_mae_by_direct_sd": 0.6011218786591169, + "pearson": 0.5817591012913891, + "spearman": 0.4107527358858471 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.3261758281693493, + "scorer_mean": 0.17346722190995933, + "bias": -0.15270860625939, + "mae": 0.2117254632365575, + "rmse": 0.2758410789896542, + "normalized_mae_by_direct_sd": 0.7431572579210016, + "pearson": 0.5995208587343445, + "spearman": 0.5268461032272831 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.3261758281693493, + "scorer_mean": 0.18444835723130382, + "bias": -0.14172747093804552, + "mae": 0.20628078906188874, + "rmse": 0.2712737055515472, + "normalized_mae_by_direct_sd": 0.7240464288876541, + "pearson": 0.5974028715985747, + "spearman": 0.5271715495536735 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.359375, + "pairwise_agreement": 0.6682477678571429, + "per_row_spearman_mean": 0.4281449421633643, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.32801389694213867, + "scorer_span_mean": 0.1402977705001831, + "direct_data_action_best_rate": 0.4375, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema": { + "top1_agreement": 0.3359375, + "pairwise_agreement": 0.6640625, + "per_row_spearman_mean": 0.4142920826525816, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.32801389694213867, + "scorer_span_mean": 0.14779308438301086, + "direct_data_action_best_rate": 0.4375, + "scorer_data_action_best_rate": 0.2578125 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.34161798019528966, + "std": 0.2917300069991998, + "min": 2.4625624889945685e-12, + "median": 0.23322897404432297, + "p90": 0.8706679999828337, + "p99": 0.99985400557518, + "max": 0.9999707937240601 + }, + "direct_q_actor": { + "mean": 0.310733676143409, + "std": 0.27704267226744433, + "min": 7.680542833676807e-12, + "median": 0.24269255250692368, + "p90": 0.7248552203178406, + "p99": 0.9995801132917405, + "max": 0.999962568283081 + }, + "direct_q_actor_minus_data": { + "mean": -0.030884303734701867, + "std": 0.23899229327547647, + "min": -0.9990149140357971, + "median": -0.0001470819115638733, + "p90": 0.19963998794555657, + "p99": 0.5017321491241457, + "max": 0.590365469455719 + }, + "direct_prefers_actor_rate": 0.4453125, + "live_scorer_q_data": { + "mean": 0.13710474447725574, + "std": 0.17371303655433862, + "min": -0.026126643642783165, + "median": 0.06042575091123581, + "p90": 0.33354058563709255, + "p99": 0.8156680607795715, + "max": 0.8608192801475525 + }, + "live_scorer_q_actor": { + "mean": 0.20982969934266293, + "std": 0.21467596821283935, + "min": -0.01082484982907772, + "median": 0.12140105292201042, + "p90": 0.5601419746875762, + "p99": 0.8259533715248109, + "max": 0.8539735674858093 + }, + "live_scorer_actor_minus_data": { + "mean": 0.07272495501820231, + "std": 0.10898631763821326, + "min": -0.03751473128795624, + "median": 0.022200576961040497, + "p90": 0.22115916907787322, + "p99": 0.4510882776975632, + "max": 0.49965572357177734 + }, + "live_scorer_prefers_actor_rate": 0.8359375, + "ema_scorer_q_data": { + "mean": 0.14569498402124736, + "std": 0.1793198851100947, + "min": -0.017604907974600792, + "median": 0.0629386231303215, + "p90": 0.36047901511192315, + "p99": 0.8485927557945253, + "max": 0.8713944554328918 + }, + "ema_scorer_q_actor": { + "mean": 0.22320173044136027, + "std": 0.2235077856725528, + "min": 0.005558038130402565, + "median": 0.12747610732913017, + "p90": 0.5611657738685608, + "p99": 0.843518701195717, + "max": 0.867315948009491 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8309981370111927, + "std": 0.4517028178828547, + "min": 0.15613718330860138, + "median": 0.7700386047363281, + "p90": 1.5463478446006773, + "p99": 1.9595801794528962, + "max": 2.0281076431274414 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 2.013641196070239, + "std": 1.1359119734272949, + "min": 0.37035825848579407, + "median": 1.8667065501213074, + "p90": 3.686782312393188, + "p99": 4.865524563789369, + "max": 5.042852401733398 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0015625, + "actor_row_outside_dataset_p01_p99_rate": 0.0078125, + "actor_action_saturation_fraction": 0.009375 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.014945990405976772, + "absolute_median": 0.008266538381576538, + "absolute_p95": 0.04829595983028412, + "absolute_max": 0.35157543420791626 + }, + "live_data_actions": { + "absolute_mean": 0.011011932045221329, + "absolute_median": 0.006919353734701872, + "absolute_p95": 0.0369916670024395, + "absolute_max": 0.09610521793365479 + }, + "live_actor_actions": { + "absolute_mean": 0.013361452147364616, + "absolute_median": 0.008708098903298378, + "absolute_p95": 0.03875550627708435, + "absolute_max": 0.09300786256790161 + }, + "ema_all_candidates": { + "absolute_mean": 0.013746514916419983, + "absolute_median": 0.008001890033483505, + "absolute_p95": 0.04336317256093025, + "absolute_max": 0.2993212342262268 + }, + "ema_data_actions": { + "absolute_mean": 0.00948538538068533, + "absolute_median": 0.00702504301443696, + "absolute_p95": 0.029030805453658104, + "absolute_max": 0.05862325429916382 + }, + "ema_actor_actions": { + "absolute_mean": 0.01172276958823204, + "absolute_median": 0.007294967770576477, + "absolute_p95": 0.03581981733441353, + "absolute_max": 0.06735503673553467 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.18477067147614434, + "std": 0.18888067992540672, + "min": -0.011998649686574936, + "median": 0.11264724284410477, + "p90": 0.42997033596038814, + "p99": 0.8505900669097902, + "max": 0.8816092014312744 + }, + "live_data_q_minus_value": { + "mean": -0.047665927042544354, + "std": 0.07324384761521974, + "min": -0.33363208174705505, + "median": -0.027378320693969727, + "p90": 0.0037471078336238717, + "p99": 0.06899525374174134, + "max": 0.19488897919654846 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.1690741628408432, + "direct_q_actor_mean": 0.15631699562072754, + "direct_q_actor_minus_data_mean": -0.01275715883821249, + "direct_prefers_actor_rate": 0.53125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.10376990621254333, + "scorer_mean": 0.10429593667959125, + "bias": 0.0005260304670479197, + "mae": 0.11608859925089583, + "rmse": 0.18936048895583965, + "normalized_mae_by_direct_sd": 0.504944659093509, + "pearson": 0.5838892568726791, + "spearman": 0.396361958761676 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.10376990621254333, + "scorer_mean": 0.11137255729227036, + "bias": 0.007602651079727028, + "mae": 0.11928424261517284, + "rmse": 0.19142978151269177, + "normalized_mae_by_direct_sd": 0.5188445860421653, + "pearson": 0.5814269192112732, + "spearman": 0.4020347822608081 + }, + "live_local_ranking": { + "top1_agreement": 0.2265625, + "pairwise_agreement": 0.5594308035714286, + "per_row_spearman_mean": 0.14846600607761953, + "per_row_spearman_median": 0.22619047619047625, + "direct_span_mean": 0.19919756054878235, + "scorer_span_mean": 0.1402977705001831, + "direct_data_action_best_rate": 0.2421875, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.203125, + "pairwise_agreement": 0.5647321428571429, + "per_row_spearman_mean": 0.15330231560142907, + "per_row_spearman_median": 0.2380952380952381, + "direct_span_mean": 0.19919756054878235, + "scorer_span_mean": 0.14779308438301086, + "direct_data_action_best_rate": 0.2421875, + "scorer_data_action_best_rate": 0.2578125 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.21088340878486633, + "direct_q_actor_mean": 0.19125889241695404, + "direct_q_actor_minus_data_mean": -0.019624512642621994, + "direct_prefers_actor_rate": 0.5234375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.12392975418260024, + "scorer_mean": 0.10429593667959125, + "bias": -0.01963381750300899, + "mae": 0.11809512890776785, + "rmse": 0.19033764682155588, + "normalized_mae_by_direct_sd": 0.5052541194926626, + "pearson": 0.5973620542325045, + "spearman": 0.41558470093224925 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.12392975418260024, + "scorer_mean": 0.11137255729227036, + "bias": -0.012557196890329884, + "mae": 0.12087949053349686, + "rmse": 0.19165262395834604, + "normalized_mae_by_direct_sd": 0.5171666360762687, + "pearson": 0.593952161266549, + "spearman": 0.4218386963273782 + }, + "live_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.5931919642857143, + "per_row_spearman_mean": 0.23328015534600738, + "per_row_spearman_median": 0.3333333333333334, + "direct_span_mean": 0.23701563477516174, + "scorer_span_mean": 0.1402977705001831, + "direct_data_action_best_rate": 0.34375, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.5968191964285714, + "per_row_spearman_mean": 0.2377444410602931, + "per_row_spearman_median": 0.3214285714285715, + "direct_span_mean": 0.23701563477516174, + "scorer_span_mean": 0.14779308438301086, + "direct_data_action_best_rate": 0.34375, + "scorer_data_action_best_rate": 0.2578125 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.27371785044670105, + "direct_q_actor_mean": 0.24647949635982513, + "direct_q_actor_minus_data_mean": -0.027238372713327408, + "direct_prefers_actor_rate": 0.46875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1572066354094011, + "scorer_mean": 0.10429593667959125, + "bias": -0.05291069872980986, + "mae": 0.1301712971760887, + "rmse": 0.2040130938063376, + "normalized_mae_by_direct_sd": 0.534037375405829, + "pearson": 0.5950742246167414, + "spearman": 0.41633570783563406 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.1572066354094011, + "scorer_mean": 0.11137255729227036, + "bias": -0.04583407811713074, + "mae": 0.13004652186393517, + "rmse": 0.20357399734697046, + "normalized_mae_by_direct_sd": 0.533525475458118, + "pearson": 0.5933301641050684, + "spearman": 0.42489854534725696 + }, + "live_local_ranking": { + "top1_agreement": 0.34375, + "pairwise_agreement": 0.6448102678571429, + "per_row_spearman_mean": 0.36402529761904767, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.28506672382354736, + "scorer_span_mean": 0.1402977705001831, + "direct_data_action_best_rate": 0.4453125, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.6372767857142857, + "per_row_spearman_mean": 0.3422619047619048, + "per_row_spearman_median": 0.4285714285714286, + "direct_span_mean": 0.28506672382354736, + "scorer_span_mean": 0.14779308438301086, + "direct_data_action_best_rate": 0.4453125, + "scorer_data_action_best_rate": 0.2578125 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.34161800146102905, + "direct_q_actor_mean": 0.3107336759567261, + "direct_q_actor_minus_data_mean": -0.030884305015206337, + "direct_prefers_actor_rate": 0.4453125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.19730951414862796, + "scorer_mean": 0.10429593667959125, + "bias": -0.09301357746903671, + "mae": 0.1538195943424507, + "rmse": 0.22660243245226835, + "normalized_mae_by_direct_sd": 0.6080464155492475, + "pearson": 0.5817777943511165, + "spearman": 0.4008836892503769 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.19730951414862796, + "scorer_mean": 0.11137255729227036, + "bias": -0.0859369568563576, + "mae": 0.15206787041445569, + "rmse": 0.2245535681179651, + "normalized_mae_by_direct_sd": 0.6011218786591169, + "pearson": 0.5817591012913891, + "spearman": 0.4107527358858471 + }, + "live_local_ranking": { + "top1_agreement": 0.359375, + "pairwise_agreement": 0.6682477678571429, + "per_row_spearman_mean": 0.4281449421633643, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.32801389694213867, + "scorer_span_mean": 0.1402977705001831, + "direct_data_action_best_rate": 0.4375, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.3359375, + "pairwise_agreement": 0.6640625, + "per_row_spearman_mean": 0.4142920826525816, + "per_row_spearman_median": 0.4761904761904762, + "direct_span_mean": 0.32801389694213867, + "scorer_span_mean": 0.14779308438301086, + "direct_data_action_best_rate": 0.4375, + "scorer_data_action_best_rate": 0.2578125 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step250000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step250000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..cc418d6e96647a05ae9064f63983180496ca7389 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step250000_distill_audit.json @@ -0,0 +1,579 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step250000.pkl", + "checkpoint_step": 250000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 8, + "reader_reward_semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd8.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 8, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "distill_goal_loss_reduction": null, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "discount_sampling": { + "gamma_sampler": null, + "gamma_task_fraction": null, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": null, + "gamma_task_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": null, + "gamma_normalization": null, + "gamma_encoding_lo": null, + "gamma_encoding_hi": null, + "condition_normalizer_probe_size": null, + "condition_normalizer_seed": null, + "condition_normalizer_goal_sampler": null + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 8, + "semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.34088459664283316, + "scorer_mean": 0.0911822800480877, + "bias": -0.24970231659474545, + "mae": 0.25446551758566177, + "rmse": 0.354203544979659, + "normalized_mae_by_direct_sd": 0.8630380160960338, + "pearson": 0.5259045254264394, + "spearman": 0.5636502014283098 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.34088459664283316, + "scorer_mean": 0.09057656584627694, + "bias": -0.2503080307965562, + "mae": 0.2546940875077694, + "rmse": 0.3539567106441664, + "normalized_mae_by_direct_sd": 0.8638132273466056, + "pearson": 0.5310947108427323, + "spearman": 0.553201107855704 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.18399105125451737, + "scorer_mean": 0.07157691177417291, + "bias": -0.11241413948034445, + "mae": 0.14922702824930204, + "rmse": 0.24107190053454688, + "normalized_mae_by_direct_sd": 0.6092414621816481, + "pearson": 0.49532048002919926, + "spearman": 0.4108346036585366 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.18399105125451737, + "scorer_mean": 0.06988915177953459, + "bias": -0.11410189947498278, + "mae": 0.1504722791680108, + "rmse": 0.2413905454743378, + "normalized_mae_by_direct_sd": 0.6143253836360761, + "pearson": 0.49957573376607867, + "spearman": 0.40475053197196187 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.3268713927930291, + "scorer_mean": 0.11783824419399025, + "bias": -0.2090331485990389, + "mae": 0.24431094660824623, + "rmse": 0.3329623497712453, + "normalized_mae_by_direct_sd": 0.8446174506766017, + "pearson": 0.45969969875799327, + "spearman": 0.444129091325246 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.3268713927930291, + "scorer_mean": 0.11726512591485516, + "bias": -0.209606266878174, + "mae": 0.2445544781988865, + "rmse": 0.33266066704088004, + "normalized_mae_by_direct_sd": 0.8454593737836151, + "pearson": 0.46504739896120606, + "spearman": 0.43602297436484316 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6473214285714286, + "per_row_spearman_mean": 0.38318452380952384, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.3288787603378296, + "scorer_span_mean": 0.09463333338499069, + "direct_data_action_best_rate": 0.484375, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6556919642857143, + "per_row_spearman_mean": 0.39843750000000006, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.3288787603378296, + "scorer_span_mean": 0.09753569215536118, + "direct_data_action_best_rate": 0.484375, + "scorer_data_action_best_rate": 0.203125 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.34088459664283316, + "std": 0.2948485615230956, + "min": 4.571068246139731e-10, + "median": 0.24557504057884216, + "p90": 0.8778291702270506, + "p99": 0.9998813843727112, + "max": 0.9999734163284302 + }, + "direct_q_actor": { + "mean": 0.31285818894322515, + "std": 0.2828604574987113, + "min": 9.448670144907023e-12, + "median": 0.24985815584659576, + "p90": 0.8582024335861206, + "p99": 0.9996031701564789, + "max": 0.9999773502349854 + }, + "direct_q_actor_minus_data": { + "mean": -0.028026408047012116, + "std": 0.2223739076807483, + "min": -0.9348463416099548, + "median": 2.5704503059387207e-07, + "p90": 0.14554533809423434, + "p99": 0.4982900190353394, + "max": 0.5184412002563477 + }, + "direct_prefers_actor_rate": 0.5234375, + "live_scorer_q_data": { + "mean": 0.0911822800480877, + "std": 0.14031384466112445, + "min": -0.00594547763466835, + "median": 0.03480774722993374, + "p90": 0.2552896201610565, + "p99": 0.7229980444908142, + "max": 0.7360705137252808 + }, + "live_scorer_q_actor": { + "mean": 0.1444942083398928, + "std": 0.18680336616281842, + "min": -0.002525772899389267, + "median": 0.04970601387321949, + "p90": 0.38698796927928925, + "p99": 0.7173751723766327, + "max": 0.754378080368042 + }, + "live_scorer_actor_minus_data": { + "mean": 0.05331192829180509, + "std": 0.09621961227216966, + "min": -0.030095547437667847, + "median": 0.01035505160689354, + "p90": 0.1583419173955917, + "p99": 0.3661846637725831, + "max": 0.4659245014190674 + }, + "live_scorer_prefers_actor_rate": 0.828125, + "ema_scorer_q_data": { + "mean": 0.09057656584627694, + "std": 0.14186895345922443, + "min": -0.010863278061151505, + "median": 0.033172132447361946, + "p90": 0.26606501936912536, + "p99": 0.6923414713144302, + "max": 0.7884755730628967 + }, + "ema_scorer_q_actor": { + "mean": 0.1439536859834334, + "std": 0.18768882017101532, + "min": -0.006058013066649437, + "median": 0.05043163150548935, + "p90": 0.4106298267841339, + "p99": 0.6869123589992523, + "max": 0.8040815591812134 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8127424807753414, + "std": 0.45390853545709464, + "min": 0.14273273944854736, + "median": 0.7360799312591553, + "p90": 1.4997653126716612, + "p99": 1.8729588329792024, + "max": 1.9040786027908325 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.976681545842439, + "std": 1.139696870906537, + "min": 0.3448893129825592, + "median": 1.8387603163719177, + "p90": 3.782288837432861, + "p99": 4.480678677558899, + "max": 4.948713302612305 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.009375, + "actor_row_outside_dataset_p01_p99_rate": 0.046875, + "actor_action_saturation_fraction": 0.0109375 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.01241430826485157, + "absolute_median": 0.005878831259906292, + "absolute_p95": 0.04109213501214981, + "absolute_max": 0.35051149129867554 + }, + "live_data_actions": { + "absolute_mean": 0.008609852753579617, + "absolute_median": 0.005166187882423401, + "absolute_p95": 0.030949056148529053, + "absolute_max": 0.0939645767211914 + }, + "live_actor_actions": { + "absolute_mean": 0.010912524536252022, + "absolute_median": 0.004967689514160156, + "absolute_p95": 0.04316803440451622, + "absolute_max": 0.11293864250183105 + }, + "ema_all_candidates": { + "absolute_mean": 0.011495462618768215, + "absolute_median": 0.005520541220903397, + "absolute_p95": 0.03766658157110214, + "absolute_max": 0.3350030481815338 + }, + "ema_data_actions": { + "absolute_mean": 0.007436218671500683, + "absolute_median": 0.004576750099658966, + "absolute_p95": 0.02182113192975521, + "absolute_max": 0.07983985543251038 + }, + "ema_actor_actions": { + "absolute_mean": 0.009494708850979805, + "absolute_median": 0.0047506894916296005, + "absolute_p95": 0.035119615495204926, + "absolute_max": 0.0625336766242981 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.1146184699391597, + "std": 0.1558078717278582, + "min": -0.00584424939006567, + "median": 0.04897874779999256, + "p90": 0.30530521571636193, + "p99": 0.7159558928012849, + "max": 0.8164204359054565 + }, + "live_data_q_minus_value": { + "mean": -0.02343618997838348, + "std": 0.05655995685042416, + "min": -0.296689510345459, + "median": -0.005826752632856369, + "p90": 0.009089571237564084, + "p99": 0.025533589869737645, + "max": 0.15012669563293457 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.16837865114212036, + "direct_q_actor_mean": 0.16208219528198242, + "direct_q_actor_minus_data_mean": -0.0062964316457509995, + "direct_prefers_actor_rate": 0.53125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.09456302452122732, + "scorer_mean": 0.07157691177417291, + "bias": -0.022986112747054404, + "mae": 0.105752204054398, + "rmse": 0.19727892119951299, + "normalized_mae_by_direct_sd": 0.4902106167777821, + "pearson": 0.45351326175938833, + "spearman": 0.35206062670466426 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.09456302452122732, + "scorer_mean": 0.06988915177953459, + "bias": -0.02467387274169273, + "mae": 0.10578225216046677, + "rmse": 0.19655263485772242, + "normalized_mae_by_direct_sd": 0.49034990371502074, + "pearson": 0.4621808478468066, + "spearman": 0.3387489546533409 + }, + "live_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.5516183035714286, + "per_row_spearman_mean": 0.138745046690589, + "per_row_spearman_median": 0.19047619047619052, + "direct_span_mean": 0.1940511018037796, + "scorer_span_mean": 0.09463333338499069, + "direct_data_action_best_rate": 0.2265625, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_local_ranking": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.5471540178571429, + "per_row_spearman_mean": 0.13204861811916044, + "per_row_spearman_median": 0.2023809523809524, + "direct_span_mean": 0.1940511018037796, + "scorer_span_mean": 0.09753569215536118, + "direct_data_action_best_rate": 0.2265625, + "scorer_data_action_best_rate": 0.203125 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.2127648890018463, + "direct_q_actor_mean": 0.19727104902267456, + "direct_q_actor_minus_data_mean": -0.015493838116526604, + "direct_prefers_actor_rate": 0.5078125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11502385650727404, + "scorer_mean": 0.07157691177417291, + "bias": -0.04344694473310113, + "mae": 0.11155256969570643, + "rmse": 0.20353801788121495, + "normalized_mae_by_direct_sd": 0.4990846976948028, + "pearson": 0.4751809506612406, + "spearman": 0.38619023805239655 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.11502385650727404, + "scorer_mean": 0.06988915177953459, + "bias": -0.04513470472773946, + "mae": 0.11212653992329269, + "rmse": 0.20336858199413962, + "normalized_mae_by_direct_sd": 0.5016526327795984, + "pearson": 0.480617949593474, + "spearman": 0.37433203536924003 + }, + "live_local_ranking": { + "top1_agreement": 0.28125, + "pairwise_agreement": 0.5862165178571429, + "per_row_spearman_mean": 0.22546988974333146, + "per_row_spearman_median": 0.28571428571428575, + "direct_span_mean": 0.2307216078042984, + "scorer_span_mean": 0.09463333338499069, + "direct_data_action_best_rate": 0.3359375, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_local_ranking": { + "top1_agreement": 0.25, + "pairwise_agreement": 0.5823102678571429, + "per_row_spearman_mean": 0.21300709212428387, + "per_row_spearman_median": 0.29761904761904767, + "direct_span_mean": 0.2307216078042984, + "scorer_span_mean": 0.09753569215536118, + "direct_data_action_best_rate": 0.3359375, + "scorer_data_action_best_rate": 0.203125 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.27154994010925293, + "direct_q_actor_mean": 0.2507014572620392, + "direct_q_actor_minus_data_mean": -0.02084849216043949, + "direct_prefers_actor_rate": 0.5078125, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.14389736308082807, + "scorer_mean": 0.07157691177417291, + "bias": -0.07232045130665514, + "mae": 0.12380239303129334, + "rmse": 0.21613122937101123, + "normalized_mae_by_direct_sd": 0.5319712817635711, + "pearson": 0.4921827011790467, + "spearman": 0.394650753701452 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.14389736308082807, + "scorer_mean": 0.06988915177953459, + "bias": -0.07400821130129347, + "mae": 0.12485073109828088, + "rmse": 0.21615406823624764, + "normalized_mae_by_direct_sd": 0.536475926072635, + "pearson": 0.49719893844932317, + "spearman": 0.38766835347972245 + }, + "live_local_ranking": { + "top1_agreement": 0.296875, + "pairwise_agreement": 0.6183035714285714, + "per_row_spearman_mean": 0.30003720238095244, + "per_row_spearman_median": 0.38095238095238104, + "direct_span_mean": 0.280690997838974, + "scorer_span_mean": 0.09463333338499069, + "direct_data_action_best_rate": 0.484375, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_local_ranking": { + "top1_agreement": 0.2890625, + "pairwise_agreement": 0.6183035714285714, + "per_row_spearman_mean": 0.3030133928571429, + "per_row_spearman_median": 0.38095238095238104, + "direct_span_mean": 0.280690997838974, + "scorer_span_mean": 0.09753569215536118, + "direct_data_action_best_rate": 0.484375, + "scorer_data_action_best_rate": 0.203125 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.34088459610939026, + "direct_q_actor_mean": 0.3128581643104553, + "direct_q_actor_minus_data_mean": -0.028026413172483444, + "direct_prefers_actor_rate": 0.5234375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.18399105125451737, + "scorer_mean": 0.07157691177417291, + "bias": -0.11241413948034445, + "mae": 0.14922702824930204, + "rmse": 0.24107190053454688, + "normalized_mae_by_direct_sd": 0.6092414621816481, + "pearson": 0.49532048002919926, + "spearman": 0.4108346036585366 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.18399105125451737, + "scorer_mean": 0.06988915177953459, + "bias": -0.11410189947498278, + "mae": 0.1504722791680108, + "rmse": 0.2413905454743378, + "normalized_mae_by_direct_sd": 0.6143253836360761, + "pearson": 0.49957573376607867, + "spearman": 0.40475053197196187 + }, + "live_local_ranking": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6473214285714286, + "per_row_spearman_mean": 0.38318452380952384, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.3288787603378296, + "scorer_span_mean": 0.09463333338499069, + "direct_data_action_best_rate": 0.484375, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_local_ranking": { + "top1_agreement": 0.3125, + "pairwise_agreement": 0.6556919642857143, + "per_row_spearman_mean": 0.39843750000000006, + "per_row_spearman_median": 0.4523809523809524, + "direct_span_mean": 0.3288787603378296, + "scorer_span_mean": 0.09753569215536118, + "direct_data_action_best_rate": 0.484375, + "scorer_data_action_best_rate": 0.203125 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step300000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step300000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..30751b6f49b38c739370f6b5b9aa5190df7ae486 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step300000_distill_audit.json @@ -0,0 +1,579 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step300000.pkl", + "checkpoint_step": 300000, + "actor_source": "ema", + "rows": 128, + "samples_per_condition": 16, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 8, + "reader_reward_semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd8.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 8, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "distill_goal_loss_reduction": null, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "discount_sampling": { + "gamma_sampler": null, + "gamma_task_fraction": null, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": null, + "gamma_task_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": null, + "gamma_normalization": null, + "gamma_encoding_lo": null, + "gamma_encoding_hi": null, + "condition_normalizer_probe_size": null, + "condition_normalizer_seed": null, + "condition_normalizer_goal_sampler": null + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 8, + "semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 128, + "direct_mean": 0.3489060644119548, + "scorer_mean": 0.05339203050243668, + "bias": -0.29551403390951814, + "mae": 0.2974844704753945, + "rmse": 0.40212107997910534, + "normalized_mae_by_direct_sd": 1.003275360195652, + "pearson": 0.39334170955121517, + "spearman": 0.48774262955502656 + }, + "ema_data_actions": { + "n": 128, + "direct_mean": 0.3489060644119548, + "scorer_mean": 0.057901168416719884, + "bias": -0.29100489599523494, + "mae": 0.29410206130664385, + "rmse": 0.3999114771341001, + "normalized_mae_by_direct_sd": 0.9918680831311235, + "pearson": 0.37978459398295655, + "spearman": 0.48214612708295185 + }, + "live_local_candidates": { + "n": 1024, + "direct_mean": 0.178330061259512, + "scorer_mean": 0.043770855075308646, + "bias": -0.13455920618420336, + "mae": 0.15816380794245327, + "rmse": 0.2631701821336238, + "normalized_mae_by_direct_sd": 0.6454820569373977, + "pearson": 0.38628463538026253, + "spearman": 0.3511798936950147 + }, + "ema_local_candidates": { + "n": 1024, + "direct_mean": 0.178330061259512, + "scorer_mean": 0.04817181458565756, + "bias": -0.13015824667385445, + "mae": 0.1565956378329591, + "rmse": 0.2617125548370201, + "normalized_mae_by_direct_sd": 0.6390822004779961, + "pearson": 0.3782388098517268, + "spearman": 0.34788371271725915 + }, + "live_data_and_actor": { + "n": 256, + "direct_mean": 0.31154853295533336, + "scorer_mean": 0.07349635528953513, + "bias": -0.23805217766579823, + "mae": 0.27192095371266595, + "rmse": 0.3671398632544195, + "normalized_mae_by_direct_sd": 0.9550362810824058, + "pearson": 0.27531221145547696, + "spearman": 0.3021050297550926 + }, + "ema_data_and_actor": { + "n": 256, + "direct_mean": 0.31154853295533336, + "scorer_mean": 0.07962534914258868, + "bias": -0.23192318381274468, + "mae": 0.2695910461754176, + "rmse": 0.3657832025100508, + "normalized_mae_by_direct_sd": 0.9468532183236941, + "pearson": 0.25730843922663443, + "spearman": 0.29953436140993356 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.6180245535714286, + "per_row_spearman_mean": 0.29873511904761907, + "per_row_spearman_median": 0.34523809523809534, + "direct_span_mean": 0.3407477140426636, + "scorer_span_mean": 0.049731671810150146, + "direct_data_action_best_rate": 0.5234375, + "scorer_data_action_best_rate": 0.203125 + }, + "ema": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.6277901785714286, + "per_row_spearman_mean": 0.32235863095238093, + "per_row_spearman_median": 0.3690476190476191, + "direct_span_mean": 0.3407477140426636, + "scorer_span_mean": 0.051986344158649445, + "direct_data_action_best_rate": 0.5234375, + "scorer_data_action_best_rate": 0.2109375 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.3489060644119548, + "std": 0.296513282671849, + "min": 2.9801074802326966e-12, + "median": 0.24988670647144318, + "p90": 0.8992651522159576, + "p99": 0.9997618007659912, + "max": 0.9999721646308899 + }, + "direct_q_actor": { + "mean": 0.2741910014987119, + "std": 0.26725131532129764, + "min": 1.624965023649949e-10, + "median": 0.19544100016355515, + "p90": 0.6873228311538695, + "p99": 0.9989396518468857, + "max": 0.9999719858169556 + }, + "direct_q_actor_minus_data": { + "mean": -0.07471506363559785, + "std": 0.22316315293850608, + "min": -0.9895874857902527, + "median": -0.0006805360317230225, + "p90": 0.11356731280684466, + "p99": 0.40486600756645263, + "max": 0.5075370669364929 + }, + "direct_prefers_actor_rate": 0.3984375, + "live_scorer_q_data": { + "mean": 0.05339203050243668, + "std": 0.10918176173744797, + "min": -0.012463772669434547, + "median": 0.009364048950374126, + "p90": 0.20395632088184354, + "p99": 0.5293664592504503, + "max": 0.5736454129219055 + }, + "live_scorer_q_actor": { + "mean": 0.09360068007663358, + "std": 0.15394265159108703, + "min": -0.007882462814450264, + "median": 0.011224848218262196, + "p90": 0.34032711386680603, + "p99": 0.6043933790922166, + "max": 0.6572972536087036 + }, + "live_scorer_actor_minus_data": { + "mean": 0.04020864947233349, + "std": 0.08081358533895829, + "min": -0.013631267473101616, + "median": 0.0017679929733276367, + "p90": 0.15090751051902768, + "p99": 0.30893851190805444, + "max": 0.37546849250793457 + }, + "live_scorer_prefers_actor_rate": 0.6875, + "ema_scorer_q_data": { + "mean": 0.057901168416719884, + "std": 0.11006355806343984, + "min": -0.00913705863058567, + "median": 0.01398930512368679, + "p90": 0.20319714248180382, + "p99": 0.5198104476928714, + "max": 0.566053569316864 + }, + "ema_scorer_q_actor": { + "mean": 0.10134952986845747, + "std": 0.15978438129733163, + "min": -0.005641782656311989, + "median": 0.015131688676774502, + "p90": 0.3667437195777893, + "p99": 0.6171233063936236, + "max": 0.6970574855804443 + }, + "l2_to_paired_behavior_action": { + "mean": 0.8138979725772515, + "std": 0.46754862773470407, + "min": 0.1331055611371994, + "median": 0.7725922465324402, + "p90": 1.4881714701652526, + "p99": 1.9114012205600743, + "max": 1.9748263359069824 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.9915614847559482, + "std": 1.2083601964689676, + "min": 0.3343343734741211, + "median": 1.7550012469291687, + "p90": 3.923093342781067, + "p99": 4.671707286834717, + "max": 4.798822402954102 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0109375, + "actor_row_outside_dataset_p01_p99_rate": 0.0546875, + "actor_action_saturation_fraction": 0.009375 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.008087178692221642, + "absolute_median": 0.003250506706535816, + "absolute_p95": 0.030428733676671982, + "absolute_max": 0.1526646614074707 + }, + "live_data_actions": { + "absolute_mean": 0.005852041766047478, + "absolute_median": 0.002635597251355648, + "absolute_p95": 0.019520336762070656, + "absolute_max": 0.1526646614074707 + }, + "live_actor_actions": { + "absolute_mean": 0.009441938251256943, + "absolute_median": 0.003449997864663601, + "absolute_p95": 0.03643845021724701, + "absolute_max": 0.13570690155029297 + }, + "ema_all_candidates": { + "absolute_mean": 0.00763047905638814, + "absolute_median": 0.0033089127391576767, + "absolute_p95": 0.027918757870793343, + "absolute_max": 0.14402300119400024 + }, + "ema_data_actions": { + "absolute_mean": 0.005439857020974159, + "absolute_median": 0.0026660189032554626, + "absolute_p95": 0.015848198905587196, + "absolute_max": 0.13197314739227295 + }, + "ema_actor_actions": { + "absolute_mean": 0.008624745532870293, + "absolute_median": 0.0031760912388563156, + "absolute_p95": 0.033355627208948135, + "absolute_max": 0.11651945114135742 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.07392481243005022, + "std": 0.12138455848640833, + "min": -0.0031504668295383453, + "median": 0.01680772751569748, + "p90": 0.24166905283927914, + "p99": 0.5256924396753312, + "max": 0.6168763637542725 + }, + "live_data_q_minus_value": { + "mean": -0.020532782014925033, + "std": 0.048355432915412895, + "min": -0.3020634055137634, + "median": -0.006755053997039795, + "p90": -0.0004907714203000092, + "p99": 0.07132269173860573, + "max": 0.08746159076690674 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.1717618703842163, + "direct_q_actor_mean": 0.1433088779449463, + "direct_q_actor_minus_data_mean": -0.028452999889850616, + "direct_prefers_actor_rate": 0.4765625, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.0916566221093072, + "scorer_mean": 0.043770855075308646, + "bias": -0.04788576703399855, + "mae": 0.0999801176111561, + "rmse": 0.20576384379349105, + "normalized_mae_by_direct_sd": 0.4682650116526934, + "pearson": 0.3672628177991053, + "spearman": 0.32114237062792295 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.0916566221093072, + "scorer_mean": 0.04817181458565756, + "bias": -0.04348480752364964, + "mae": 0.10041753477459223, + "rmse": 0.20591349685294472, + "normalized_mae_by_direct_sd": 0.47031369051032507, + "pearson": 0.35634222270369087, + "spearman": 0.3121561110858698 + }, + "live_local_ranking": { + "top1_agreement": 0.21875, + "pairwise_agreement": 0.5323660714285714, + "per_row_spearman_mean": 0.0781596266259196, + "per_row_spearman_median": 0.035714285714285726, + "direct_span_mean": 0.20613370835781097, + "scorer_span_mean": 0.049731671810150146, + "direct_data_action_best_rate": 0.1875, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.1953125, + "pairwise_agreement": 0.5267857142857143, + "per_row_spearman_mean": 0.06151994013969447, + "per_row_spearman_median": 0.011904761904761908, + "direct_span_mean": 0.20613370835781097, + "scorer_span_mean": 0.051986344158649445, + "direct_data_action_best_rate": 0.1875, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.2160206139087677, + "direct_q_actor_mean": 0.1718326210975647, + "direct_q_actor_minus_data_mean": -0.0441880002617836, + "direct_prefers_actor_rate": 0.4921875, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.10984784110648468, + "scorer_mean": 0.043770855075308646, + "bias": -0.06607698603117604, + "mae": 0.10802155880866884, + "rmse": 0.21614754009259737, + "normalized_mae_by_direct_sd": 0.4885511206402023, + "pearson": 0.37643019634558256, + "spearman": 0.3494352463519272 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.10984784110648468, + "scorer_mean": 0.04817181458565756, + "bias": -0.061676026520827126, + "mae": 0.10815349621587086, + "rmse": 0.21606430795240916, + "normalized_mae_by_direct_sd": 0.4891478364148476, + "pearson": 0.36457499932765053, + "spearman": 0.3437298355653345 + }, + "live_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.5823102678571429, + "per_row_spearman_mean": 0.19917545285547628, + "per_row_spearman_median": 0.30952380952380953, + "direct_span_mean": 0.24217729270458221, + "scorer_span_mean": 0.049731671810150146, + "direct_data_action_best_rate": 0.328125, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.5828683035714286, + "per_row_spearman_mean": 0.21015015523642863, + "per_row_spearman_median": 0.30952380952380953, + "direct_span_mean": 0.24217729270458221, + "scorer_span_mean": 0.051986344158649445, + "direct_data_action_best_rate": 0.328125, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.2826796770095825, + "direct_q_actor_mean": 0.2187110185623169, + "direct_q_actor_minus_data_mean": -0.06396865844726562, + "direct_prefers_actor_rate": 0.3984375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.14193123804198243, + "scorer_mean": 0.043770855075308646, + "bias": -0.09816038296667379, + "mae": 0.12906494112013367, + "rmse": 0.23840111232753347, + "normalized_mae_by_direct_sd": 0.54995070641797, + "pearson": 0.38241324556547507, + "spearman": 0.3613102380015735 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.14193123804198243, + "scorer_mean": 0.04817181458565756, + "bias": -0.09375942345632488, + "mae": 0.12826047391314774, + "rmse": 0.2376910826458947, + "normalized_mae_by_direct_sd": 0.5465228405317554, + "pearson": 0.37173686418492025, + "spearman": 0.35548366980187396 + }, + "live_local_ranking": { + "top1_agreement": 0.2734375, + "pairwise_agreement": 0.6023995535714286, + "per_row_spearman_mean": 0.2574404761904763, + "per_row_spearman_median": 0.3333333333333334, + "direct_span_mean": 0.2949602007865906, + "scorer_span_mean": 0.049731671810150146, + "direct_data_action_best_rate": 0.4375, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.2578125, + "pairwise_agreement": 0.6104910714285714, + "per_row_spearman_mean": 0.27808779761904767, + "per_row_spearman_median": 0.3333333333333334, + "direct_span_mean": 0.2949602007865906, + "scorer_span_mean": 0.051986344158649445, + "direct_data_action_best_rate": 0.4375, + "scorer_data_action_best_rate": 0.2109375 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.3489060699939728, + "direct_q_actor_mean": 0.2741909921169281, + "direct_q_actor_minus_data_mean": -0.07471507042646408, + "direct_prefers_actor_rate": 0.3984375, + "live_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.178330061259512, + "scorer_mean": 0.043770855075308646, + "bias": -0.13455920618420336, + "mae": 0.15816380794245327, + "rmse": 0.2631701821336238, + "normalized_mae_by_direct_sd": 0.6454820569373977, + "pearson": 0.38628463538026253, + "spearman": 0.3511798936950147 + }, + "ema_scorer_fidelity_local": { + "n": 1024, + "direct_mean": 0.178330061259512, + "scorer_mean": 0.04817181458565756, + "bias": -0.13015824667385445, + "mae": 0.1565956378329591, + "rmse": 0.2617125548370201, + "normalized_mae_by_direct_sd": 0.6390822004779961, + "pearson": 0.3782388098517268, + "spearman": 0.34788371271725915 + }, + "live_local_ranking": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.6180245535714286, + "per_row_spearman_mean": 0.29873511904761907, + "per_row_spearman_median": 0.34523809523809534, + "direct_span_mean": 0.3407477140426636, + "scorer_span_mean": 0.049731671810150146, + "direct_data_action_best_rate": 0.5234375, + "scorer_data_action_best_rate": 0.203125 + }, + "ema_local_ranking": { + "top1_agreement": 0.234375, + "pairwise_agreement": 0.6277901785714286, + "per_row_spearman_mean": 0.32235863095238093, + "per_row_spearman_median": 0.3690476190476191, + "direct_span_mean": 0.3407477140426636, + "scorer_span_mean": 0.051986344158649445, + "direct_data_action_best_rate": 0.5234375, + "scorer_data_action_best_rate": 0.2109375 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step50000_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step50000_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..b49162edf8cd8829752714fe661e3e6ee4f47ca7 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step50000_distill_audit.json @@ -0,0 +1,579 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0_step50000.pkl", + "checkpoint_step": 50000, + "actor_source": "ema", + "rows": 256, + "samples_per_condition": 32, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.9, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_index_delta": 8, + "reader_reward_semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd8.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "target": "index", + "index_delta": 8, + "neg_gap": 64, + "zdim": 8, + "features": "symmetric", + "activation": "relu" + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": false, + "distill_goal_loss_reduction": null, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "discount_sampling": { + "gamma_sampler": null, + "gamma_task_fraction": null, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": null, + "gamma_task_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": null, + "gamma_normalization": null, + "gamma_encoding_lo": null, + "gamma_encoding_hi": null, + "condition_normalizer_probe_size": null, + "condition_normalizer_seed": null, + "condition_normalizer_goal_sampler": null + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 8, + "semantics": "within_8_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 256, + "direct_mean": 0.36387066127645085, + "scorer_mean": 0.2586955005899654, + "bias": -0.10517516068648547, + "mae": 0.1231964751787018, + "rmse": 0.15850256558792733, + "normalized_mae_by_direct_sd": 0.4053962086605586, + "pearson": 0.921331838156013, + "spearman": 0.7590180819409474 + }, + "ema_data_actions": { + "n": 256, + "direct_mean": 0.36387066127645085, + "scorer_mean": 0.2690678357248544, + "bias": -0.09480282555159647, + "mae": 0.11395986909337807, + "rmse": 0.14728809779966984, + "normalized_mae_by_direct_sd": 0.3750017912679364, + "pearson": 0.9293530267532514, + "spearman": 0.7571648260471502 + }, + "live_local_candidates": { + "n": 2048, + "direct_mean": 0.2186252640514172, + "scorer_mean": 0.2148354619924362, + "bias": -0.0037898020589809886, + "mae": 0.12240174572647897, + "rmse": 0.19198591295466919, + "normalized_mae_by_direct_sd": 0.4352621137447488, + "pearson": 0.7636991200282557, + "spearman": 0.6050820978152778 + }, + "ema_local_candidates": { + "n": 2048, + "direct_mean": 0.2186252640514172, + "scorer_mean": 0.2252645003187581, + "bias": 0.006639236267340927, + "mae": 0.12042228955606565, + "rmse": 0.1899013067198937, + "normalized_mae_by_direct_sd": 0.4282231432489808, + "pearson": 0.7697987633393706, + "spearman": 0.6016057571272142 + }, + "live_data_and_actor": { + "n": 512, + "direct_mean": 0.38529578628640593, + "scorer_mean": 0.29718392942959326, + "bias": -0.08811185685681266, + "mae": 0.12545365784262685, + "rmse": 0.16292466953758708, + "normalized_mae_by_direct_sd": 0.41590897238379915, + "pearson": 0.8944232220342561, + "spearman": 0.7364086303893079 + }, + "ema_data_and_actor": { + "n": 512, + "direct_mean": 0.38529578628640593, + "scorer_mean": 0.30657711530329834, + "bias": -0.07871867098310759, + "mae": 0.11936467340910895, + "rmse": 0.15662548347085514, + "normalized_mae_by_direct_sd": 0.39572252822461657, + "pearson": 0.8974308412510219, + "spearman": 0.7338023625926431 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.40234375, + "pairwise_agreement": 0.7272600446428571, + "per_row_spearman_mean": 0.5555245535714286, + "per_row_spearman_median": 0.6428571428571429, + "direct_span_mean": 0.35724225640296936, + "scorer_span_mean": 0.2171582281589508, + "direct_data_action_best_rate": 0.421875, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema": { + "top1_agreement": 0.41015625, + "pairwise_agreement": 0.7265625, + "per_row_spearman_mean": 0.557012648809524, + "per_row_spearman_median": 0.6666666666666669, + "direct_span_mean": 0.35724225640296936, + "scorer_span_mean": 0.20847108960151672, + "direct_data_action_best_rate": 0.421875, + "scorer_data_action_best_rate": 0.23828125 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.36387066127645085, + "std": 0.30389153264591867, + "min": 0.010678986087441444, + "median": 0.23558281362056732, + "p90": 0.9738315939903259, + "p99": 0.9999533057212829, + "max": 0.9999760985374451 + }, + "direct_q_actor": { + "mean": 0.406720911296361, + "std": 0.2978287783072632, + "min": 0.0015359255485236645, + "median": 0.3041057586669922, + "p90": 0.9716579020023346, + "p99": 0.9999553084373474, + "max": 0.9999760985374451 + }, + "direct_q_actor_minus_data": { + "mean": 0.042850249956245534, + "std": 0.16590487180931027, + "min": -0.7874962687492371, + "median": 0.007718682289123535, + "p90": 0.2128821238875389, + "p99": 0.4921078711748117, + "max": 0.5563926100730896 + }, + "direct_prefers_actor_rate": 0.66015625, + "live_scorer_q_data": { + "mean": 0.2586955005899654, + "std": 0.2901217256188668, + "min": -0.009775086306035519, + "median": 0.13304453343153, + "p90": 0.868994951248169, + "p99": 0.9934433162212372, + "max": 1.0028671026229858 + }, + "live_scorer_q_actor": { + "mean": 0.33567235826922115, + "std": 0.2926885030208624, + "min": -0.02050996944308281, + "median": 0.21264522522687912, + "p90": 0.9027016162872314, + "p99": 0.9976329386234284, + "max": 1.00079345703125 + }, + "live_scorer_actor_minus_data": { + "mean": 0.07697685759922024, + "std": 0.11353110938668605, + "min": -0.1031309962272644, + "median": 0.027688629925251007, + "p90": 0.24408307671546936, + "p99": 0.45604184120893454, + "max": 0.5892854928970337 + }, + "live_scorer_prefers_actor_rate": 0.83203125, + "ema_scorer_q_data": { + "mean": 0.2690678357248544, + "std": 0.293313877562677, + "min": 0.0041978443041443825, + "median": 0.13684657961130142, + "p90": 0.873836874961853, + "p99": 0.994936466217041, + "max": 1.0032892227172852 + }, + "ema_scorer_q_actor": { + "mean": 0.3440863948817423, + "std": 0.2934104696894025, + "min": -0.006177104078233242, + "median": 0.22085995227098465, + "p90": 0.9104140102863312, + "p99": 0.9965578466653824, + "max": 1.0000332593917847 + }, + "l2_to_paired_behavior_action": { + "mean": 0.7945480089983903, + "std": 0.4338120946984107, + "min": 0.17307889461517334, + "median": 0.6603717505931854, + "p90": 1.4282400012016296, + "p99": 1.9311587035655975, + "max": 2.148599624633789 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.8876057103043422, + "std": 1.0450434191023785, + "min": 0.3626897633075714, + "median": 1.6777581572532654, + "p90": 3.5482434034347534, + "p99": 4.729136157035826, + "max": 5.63210391998291 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.00078125, + "actor_row_outside_dataset_p01_p99_rate": 0.00390625, + "actor_action_saturation_fraction": 0.00234375 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.016876015812158585, + "absolute_median": 0.009616438299417496, + "absolute_p95": 0.05698470026254654, + "absolute_max": 0.29813116788864136 + }, + "live_data_actions": { + "absolute_mean": 0.012442640960216522, + "absolute_median": 0.00796981155872345, + "absolute_p95": 0.039562322199344635, + "absolute_max": 0.09870940446853638 + }, + "live_actor_actions": { + "absolute_mean": 0.011751118116080761, + "absolute_median": 0.007983427494764328, + "absolute_p95": 0.035848960280418396, + "absolute_max": 0.07999950647354126 + }, + "ema_all_candidates": { + "absolute_mean": 0.014752047136425972, + "absolute_median": 0.008893456310033798, + "absolute_p95": 0.04845299571752548, + "absolute_max": 0.29424017667770386 + }, + "ema_data_actions": { + "absolute_mean": 0.010095896199345589, + "absolute_median": 0.007425691932439804, + "absolute_p95": 0.029049750417470932, + "absolute_max": 0.08490985631942749 + }, + "ema_actor_actions": { + "absolute_mean": 0.010672531090676785, + "absolute_median": 0.007829360663890839, + "absolute_p95": 0.032272011041641235, + "absolute_max": 0.07486671209335327 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.32185474153084215, + "std": 0.28261359832276545, + "min": 0.038800448179244995, + "median": 0.19519199430942535, + "p90": 0.8980719447135925, + "p99": 1.0037774980068206, + "max": 1.0085960626602173 + }, + "live_data_q_minus_value": { + "mean": -0.06315924068621825, + "std": 0.08890461831260392, + "min": -0.5413473844528198, + "median": -0.03951198607683182, + "p90": 0.010954461991786957, + "p99": 0.08159490823745721, + "max": 0.10217344760894775 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.19572705030441284, + "direct_q_actor_mean": 0.22664996981620789, + "direct_q_actor_minus_data_mean": 0.03092290088534355, + "direct_prefers_actor_rate": 0.6328125, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.12974728574685548, + "scorer_mean": 0.2148354619924362, + "bias": 0.08508817624558071, + "mae": 0.12985372948991347, + "rmse": 0.1991360989648495, + "normalized_mae_by_direct_sd": 0.4661789408938266, + "pearson": 0.7900331477122394, + "spearman": 0.5949861410227159 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.12974728574685548, + "scorer_mean": 0.2252645003187581, + "bias": 0.09551721457190263, + "mae": 0.13372044064143923, + "rmse": 0.201291653318807, + "normalized_mae_by_direct_sd": 0.4800605545867213, + "pearson": 0.7973772278925764, + "spearman": 0.5900906306348754 + }, + "live_local_ranking": { + "top1_agreement": 0.33203125, + "pairwise_agreement": 0.6392299107142857, + "per_row_spearman_mean": 0.3404017857142858, + "per_row_spearman_median": 0.4285714285714286, + "direct_span_mean": 0.21610766649246216, + "scorer_span_mean": 0.2171582281589508, + "direct_data_action_best_rate": 0.1640625, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema_local_ranking": { + "top1_agreement": 0.3046875, + "pairwise_agreement": 0.6371372767857143, + "per_row_spearman_mean": 0.3394717261904762, + "per_row_spearman_median": 0.4642857142857143, + "direct_span_mean": 0.21610766649246216, + "scorer_span_mean": 0.20847108960151672, + "direct_data_action_best_rate": 0.1640625, + "scorer_data_action_best_rate": 0.23828125 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.23836040496826172, + "direct_q_actor_mean": 0.28375017642974854, + "direct_q_actor_minus_data_mean": 0.045389771461486816, + "direct_prefers_actor_rate": 0.65234375, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.15269093104065176, + "scorer_mean": 0.2148354619924362, + "bias": 0.06214453095178443, + "mae": 0.11649646707256678, + "rmse": 0.18747429824639367, + "normalized_mae_by_direct_sd": 0.41624752534044623, + "pearson": 0.7983510997029518, + "spearman": 0.6267411605880941 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.15269093104065176, + "scorer_mean": 0.2252645003187581, + "bias": 0.07257356927810635, + "mae": 0.11846605602530676, + "rmse": 0.1882190240933748, + "normalized_mae_by_direct_sd": 0.423284962166794, + "pearson": 0.8062893406347922, + "spearman": 0.6220217400580323 + }, + "live_local_ranking": { + "top1_agreement": 0.3828125, + "pairwise_agreement": 0.681640625, + "per_row_spearman_mean": 0.45070684523809534, + "per_row_spearman_median": 0.5476190476190477, + "direct_span_mean": 0.25727811455726624, + "scorer_span_mean": 0.2171582281589508, + "direct_data_action_best_rate": 0.28125, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema_local_ranking": { + "top1_agreement": 0.375, + "pairwise_agreement": 0.6840122767857143, + "per_row_spearman_mean": 0.45824032738095244, + "per_row_spearman_median": 0.5714285714285715, + "direct_span_mean": 0.25727811455726624, + "scorer_span_mean": 0.20847108960151672, + "direct_data_action_best_rate": 0.28125, + "scorer_data_action_best_rate": 0.23828125 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.2987349331378937, + "direct_q_actor_mean": 0.3454936146736145, + "direct_q_actor_minus_data_mean": 0.04675869643688202, + "direct_prefers_actor_rate": 0.65625, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.1833244713682377, + "scorer_mean": 0.2148354619924362, + "bias": 0.0315109906241985, + "mae": 0.10964991242821295, + "rmse": 0.18326966163189076, + "normalized_mae_by_direct_sd": 0.390673986652563, + "pearson": 0.7905321773036486, + "spearman": 0.6231357734862325 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.1833244713682377, + "scorer_mean": 0.2252645003187581, + "bias": 0.04194002895052042, + "mae": 0.10951450646643278, + "rmse": 0.18253950826409143, + "normalized_mae_by_direct_sd": 0.3901915458942102, + "pearson": 0.7978785659073506, + "spearman": 0.6182649464121335 + }, + "live_local_ranking": { + "top1_agreement": 0.37890625, + "pairwise_agreement": 0.7135881696428571, + "per_row_spearman_mean": 0.5281808035714287, + "per_row_spearman_median": 0.6190476190476191, + "direct_span_mean": 0.3025400638580322, + "scorer_span_mean": 0.2171582281589508, + "direct_data_action_best_rate": 0.3984375, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema_local_ranking": { + "top1_agreement": 0.39453125, + "pairwise_agreement": 0.7159598214285714, + "per_row_spearman_mean": 0.533482142857143, + "per_row_spearman_median": 0.6309523809523809, + "direct_span_mean": 0.3025400638580322, + "scorer_span_mean": 0.20847108960151672, + "direct_data_action_best_rate": 0.3984375, + "scorer_data_action_best_rate": 0.23828125 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.36387065052986145, + "direct_q_actor_mean": 0.40672093629837036, + "direct_q_actor_minus_data_mean": 0.042850248515605927, + "direct_prefers_actor_rate": 0.66015625, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.2186252640514172, + "scorer_mean": 0.2148354619924362, + "bias": -0.0037898020589809886, + "mae": 0.12240174572647897, + "rmse": 0.19198591295466919, + "normalized_mae_by_direct_sd": 0.4352621137447488, + "pearson": 0.7636991200282557, + "spearman": 0.6050820978152778 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.2186252640514172, + "scorer_mean": 0.2252645003187581, + "bias": 0.006639236267340927, + "mae": 0.12042228955606565, + "rmse": 0.1899013067198937, + "normalized_mae_by_direct_sd": 0.4282231432489808, + "pearson": 0.7697987633393706, + "spearman": 0.6016057571272142 + }, + "live_local_ranking": { + "top1_agreement": 0.40234375, + "pairwise_agreement": 0.7272600446428571, + "per_row_spearman_mean": 0.5555245535714286, + "per_row_spearman_median": 0.6428571428571429, + "direct_span_mean": 0.35724225640296936, + "scorer_span_mean": 0.2171582281589508, + "direct_data_action_best_rate": 0.421875, + "scorer_data_action_best_rate": 0.1953125 + }, + "ema_local_ranking": { + "top1_agreement": 0.41015625, + "pairwise_agreement": 0.7265625, + "per_row_spearman_mean": 0.557012648809524, + "per_row_spearman_median": 0.6666666666666669, + "direct_span_mean": 0.35724225640296936, + "scorer_span_mean": 0.20847108960151672, + "direct_data_action_best_rate": 0.421875, + "scorer_data_action_best_rate": 0.23828125 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_visual_rsm_onehop_v2_frozen_local_step30000_official_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_visual_rsm_onehop_v2_frozen_local_step30000_official_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..39c815b061d9ae463650725b8666d5a553111bb2 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_visual_rsm_onehop_v2_frozen_local_step30000_official_distill_audit.json @@ -0,0 +1,756 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_visual_rsm_onehop_v2_frozen_local_s0_step30000_manual.pkl", + "checkpoint_step": 30000, + "actor_source": "ema", + "rows": 256, + "samples_per_condition": 32, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.5, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_model": "diag_metric", + "reader_index_delta": 4, + "reader_reward_semantics": "within_4_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true, + "actor_action_scorer_support": true, + "actor_query_occupancy_support": false + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd4_diagmetric.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd4_diagmetric.npz", + "reader_model": "diag_metric", + "target": "index", + "index_delta": 4, + "neg_gap": 64, + "features": "concat", + "activation": "tanh", + "zdim": 8, + "pixels_only_latents": true, + "frozen_encoder": true, + "uses_coordinates_for_training": false, + "uses_coordinates_for_diagnostics": false, + "uses_reward_arrays": false, + "uses_td_or_bootstrap": false, + "label_source": "trajectory_index_positive_and_far_negative_relabeling", + "metric_formula": "bias-sum(weight*((future-goal)/scale)^2)", + "metric_scale": [ + 0.1212734580039978, + 0.11785601824522018, + 0.14360646903514862, + 0.12027847766876221, + 0.1290542036294937, + 0.11801266670227051, + 0.13187457621097565, + 0.15636976063251495 + ], + "metric_weight": [ + 0.8197049498558044, + 0.5192811489105225, + 2.501105308532715, + 2.897911310195923, + 2.5396385192871094, + 0.5441544055938721, + 1.0393574237823486, + 0.5873745083808899 + ], + "metric_scale_min": 0.11785601824522018, + "metric_scale_max": 0.15636976063251495, + "metric_weight_min": 0.5192811489105225, + "metric_weight_max": 2.897911310195923, + "metric_weight_sum": 11.448527336120605, + "metric_bias": 3.7990050315856934, + "metric_weight_nonnegative": true + } + }, + "representation_roles": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": true, + "distill_goal_loss_reduction": "mean_value_and_actor_goals", + "distill_actor_actions": true, + "distill_actor_action_local_k": 2, + "distill_actor_action_sigma": 0.3, + "distill_actor_action_pairwise_weight": 1.0, + "distill_actor_action_support_start_step": 0, + "distill_actor_action_composed_occupancy": false, + "actor_q_gradient_start_step": 0, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "occupancy_gradient_updates_actor": false, + "critic_target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "actor_query_anti_exploitation": { + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "occ_action_negative_local_k": 0, + "occ_action_negative_candidate_count": 1, + "occ_action_negative_policy": "behavior_action_plus_local_gaussian", + "occ_action_negative_actor_source": null, + "occ_action_negative_support_start_step": null, + "occ_action_negative_actions_stop_gradient": false, + "occ_action_negative_common_random_numbers": true, + "occ_action_negative_updates_actor": false, + "occ_action_negative_counterfactual_target": false, + "occ_action_negative_interpretation": null + }, + "discount_sampling": { + "gamma_sampler": "stratified_bins", + "gamma_task_fraction": 0.5, + "gamma_horizons": [ + 2.0, + 4.0, + 8.0, + 16.0, + 32.0, + 64.0 + ], + "gamma_aux_discounts": [ + 0.5, + 0.75, + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "gamma_batch_allocation": "exact_task_count_balanced_aux_bins_then_shuffle", + "gamma_task_rows_per_occ_batch": 1024, + "gamma_aux_rows_per_occ_batch": [ + 171, + 171, + 171, + 171, + 170, + 170 + ], + "gamma_sampling_importance_weighted": false, + "gamma_normalization": "fixed_fourier_identity", + "gamma_encoding_lo": 0.5, + "gamma_encoding_hi": 0.99, + "condition_normalizer_probe_size": 20000, + "condition_normalizer_seed": 0, + "condition_normalizer_goal_sampler": "gciql_value_goals_20_current_50_trajectory_30_random" + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 4, + "semantics": "within_4_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 256, + "direct_mean": 0.384300730990617, + "scorer_mean": 0.36942839913535863, + "bias": -0.01487233185525838, + "mae": 0.06159361401023489, + "rmse": 0.08252390763764507, + "normalized_mae_by_direct_sd": 0.2033017169099751, + "pearson": 0.9634410810963201, + "spearman": 0.886131694895857 + }, + "ema_data_actions": { + "n": 256, + "direct_mean": 0.384300730990617, + "scorer_mean": 0.37149436916661216, + "bias": -0.012806361824004853, + "mae": 0.06130408244735008, + "rmse": 0.08236012728474423, + "normalized_mae_by_direct_sd": 0.20234606160739244, + "pearson": 0.9636743522175655, + "spearman": 0.8857161249713891 + }, + "live_local_candidates": { + "n": 2048, + "direct_mean": 0.23557749984322088, + "scorer_mean": 0.23521066697526294, + "bias": -0.000366832867957953, + "mae": 0.05652310661389292, + "rmse": 0.0827530491957965, + "normalized_mae_by_direct_sd": 0.1875242180013539, + "pearson": 0.9615959230735938, + "spearman": 0.9212433033048043 + }, + "ema_local_candidates": { + "n": 2048, + "direct_mean": 0.23557749984322088, + "scorer_mean": 0.23707928686604873, + "bias": 0.0015017870228278417, + "mae": 0.056204303180320436, + "rmse": 0.08415653629713594, + "normalized_mae_by_direct_sd": 0.18646653790982595, + "pearson": 0.9609137327575373, + "spearman": 0.9202007493669092 + }, + "live_data_and_actor": { + "n": 512, + "direct_mean": 0.41902076623910034, + "scorer_mean": 0.4065363074769266, + "bias": -0.012484458762173745, + "mae": 0.06130013994015826, + "rmse": 0.08156799420824858, + "normalized_mae_by_direct_sd": 0.2066166493574304, + "pearson": 0.9624363937079948, + "spearman": 0.9023791105904029 + }, + "ema_data_and_actor": { + "n": 512, + "direct_mean": 0.41902076623910034, + "scorer_mean": 0.40934461386859766, + "bias": -0.009676152370502678, + "mae": 0.061531761250535055, + "rmse": 0.08213766707706094, + "normalized_mae_by_direct_sd": 0.20739734609183508, + "pearson": 0.9621140749845896, + "spearman": 0.9004579263512663 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.62109375, + "pairwise_agreement": 0.8874162946428571, + "per_row_spearman_mean": 0.8715587797619049, + "per_row_spearman_median": 0.9285714285714287, + "direct_span_mean": 0.3928883373737335, + "scorer_span_mean": 0.3870161771774292, + "direct_data_action_best_rate": 0.43359375, + "scorer_data_action_best_rate": 0.3984375 + }, + "ema": { + "top1_agreement": 0.6328125, + "pairwise_agreement": 0.8907645089285714, + "per_row_spearman_mean": 0.8770461309523812, + "per_row_spearman_median": 0.9285714285714287, + "direct_span_mean": 0.3928883373737335, + "scorer_span_mean": 0.3924858570098877, + "direct_data_action_best_rate": 0.43359375, + "scorer_data_action_best_rate": 0.37109375 + } + }, + "actor_action_scorer_support": { + "enabled": true, + "scorer_support_start_step": 0, + "actor_q_gradient_start_step": 0, + "scorer_support_active_at_checkpoint": true, + "actor_q_gradient_active_at_checkpoint": true, + "mode_action_count": 1, + "local_action_k": 2, + "local_action_sigma": 0.3, + "pointwise_weight": 1.0, + "pairwise_weight": 1.0, + "pointwise_candidate_count": 3, + "pairwise_candidate_count_including_behavior": 4, + "behavior_action_is_pairwise_reference": true, + "common_occupancy_random_numbers": true, + "target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "composed_occupancy_target": false, + "actor_actions_are_stop_gradient_targets": true, + "updates_occupancy": false, + "loss_reduction": "normalized_point_and_pairwise_then_mean_with_existing_support", + "diagnostic_uses_common_occupancy_noise": true, + "live_point_fidelity_mode_and_local": { + "n": 768, + "direct_mean": 0.3082533077663905, + "scorer_mean": 0.306290613608932, + "bias": -0.0019626941574584673, + "mae": 0.055576637822086494, + "rmse": 0.08027104991109678, + "normalized_mae_by_direct_sd": 0.17948421897344183, + "pearson": 0.9658427087572207, + "spearman": 0.9477478571961419 + }, + "ema_point_fidelity_mode_and_local": { + "n": 768, + "direct_mean": 0.3082533077663905, + "scorer_mean": 0.3101053378773031, + "bias": 0.0018520301109126458, + "mae": 0.055322240191035175, + "rmse": 0.08217131583471245, + "normalized_mae_by_direct_sd": 0.1786626442631452, + "pearson": 0.9644303249893303, + "spearman": 0.9448207343559001 + }, + "live_pairwise_gap_fidelity_with_behavior": { + "n": 1536, + "direct_mean": -0.03545987725217047, + "scorer_mean": -0.038124622839556345, + "bias": -0.0026647455873858705, + "mae": 0.05158156772125738, + "rmse": 0.0789983944518549, + "normalized_mae_by_direct_sd": 0.16756321898593263, + "pearson": 0.9671770039644828, + "spearman": 0.9501066989821111, + "candidate_count": 4, + "pair_count_per_row": 6, + "sign_agreement": 0.8815104166666666 + }, + "ema_pairwise_gap_fidelity_with_behavior": { + "n": 1536, + "direct_mean": -0.03545987725217047, + "scorer_mean": -0.039106812328933906, + "bias": -0.0036469350767634316, + "mae": 0.050271985252788885, + "rmse": 0.07924407174888753, + "normalized_mae_by_direct_sd": 0.16330902773819952, + "pearson": 0.9670338603224736, + "spearman": 0.9521523709943012, + "candidate_count": 4, + "pair_count_per_row": 6, + "sign_agreement": 0.888671875 + }, + "live_ranking_with_behavior": { + "top1_agreement": 0.72265625, + "pairwise_agreement": 0.8815104166666666, + "per_row_spearman_mean": 0.8187500000000001, + "per_row_spearman_median": 1.0, + "direct_span_mean": 0.34155264496803284, + "scorer_span_mean": 0.3224559426307678, + "direct_data_action_best_rate": 0.24609375, + "scorer_data_action_best_rate": 0.2265625 + }, + "ema_ranking_with_behavior": { + "top1_agreement": 0.7421875, + "pairwise_agreement": 0.888671875, + "per_row_spearman_mean": 0.825, + "per_row_spearman_median": 1.0, + "direct_span_mean": 0.34155264496803284, + "scorer_span_mean": 0.3231669068336487, + "direct_data_action_best_rate": 0.24609375, + "scorer_data_action_best_rate": 0.23046875 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.384300730990617, + "std": 0.302966521613339, + "min": 0.0007175614591687918, + "median": 0.2749662548303604, + "p90": 0.9686248898506165, + "p99": 0.977967095375061, + "max": 0.9779970645904541 + }, + "direct_q_actor": { + "mean": 0.45374080148758367, + "std": 0.2860852305818994, + "min": 0.0021347366273403168, + "median": 0.3605159670114517, + "p90": 0.9691325426101685, + "p99": 0.9779715210199356, + "max": 0.9780240058898926 + }, + "direct_q_actor_minus_data": { + "mean": 0.06944007043057354, + "std": 0.12958944332974076, + "min": -0.09779311716556549, + "median": 0.012606784701347351, + "p90": 0.25970685482025146, + "p99": 0.5166109919548034, + "max": 0.5758033394813538 + }, + "direct_prefers_actor_rate": 0.70703125, + "live_scorer_q_data": { + "mean": 0.36942839913535863, + "std": 0.2924357863147188, + "min": 0.015160247683525085, + "median": 0.2435142770409584, + "p90": 0.9437465965747833, + "p99": 0.9706222444772721, + "max": 0.9742982983589172 + }, + "live_scorer_q_actor": { + "mean": 0.44364421581849456, + "std": 0.27964779107170734, + "min": 0.0556928813457489, + "median": 0.32708021998405457, + "p90": 0.9495288133621216, + "p99": 0.9748481273651123, + "max": 0.9785963892936707 + }, + "live_scorer_actor_minus_data": { + "mean": 0.07421581685775891, + "std": 0.12618979779744632, + "min": -0.0988997220993042, + "median": 0.023633524775505066, + "p90": 0.25691795349121094, + "p99": 0.5166853189468381, + "max": 0.5407355427742004 + }, + "live_scorer_prefers_actor_rate": 0.74609375, + "ema_scorer_q_data": { + "mean": 0.37149436916661216, + "std": 0.30043094088481426, + "min": 0.016442717984318733, + "median": 0.2421635240316391, + "p90": 0.9599260687828064, + "p99": 0.9816369354724884, + "max": 0.9828675389289856 + }, + "ema_scorer_q_actor": { + "mean": 0.44719485857058316, + "std": 0.28637785016718625, + "min": 0.04466511309146881, + "median": 0.3282202184200287, + "p90": 0.9604792594909668, + "p99": 0.9807649850845337, + "max": 0.9810390472412109 + }, + "l2_to_paired_behavior_action": { + "mean": 0.7768782324274071, + "std": 0.44303343368027265, + "min": 0.10657510161399841, + "median": 0.6511367857456207, + "p90": 1.3976738452911377, + "p99": 1.9586100995540618, + "max": 2.1060988903045654 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.7687605107203126, + "std": 1.0576752292296332, + "min": 0.2583566904067993, + "median": 1.4613836407661438, + "p90": 3.5013105869293213, + "p99": 4.789583063125607, + "max": 5.509342670440674 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.00078125, + "actor_row_outside_dataset_p01_p99_rate": 0.00390625, + "actor_action_saturation_fraction": 0.0015625 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.018743712455034256, + "absolute_median": 0.012604158371686935, + "absolute_p95": 0.05886533856391907, + "absolute_max": 0.17206227779388428 + }, + "live_data_actions": { + "absolute_mean": 0.01151733286678791, + "absolute_median": 0.00825788825750351, + "absolute_p95": 0.034421153366565704, + "absolute_max": 0.055215030908584595 + }, + "live_actor_actions": { + "absolute_mean": 0.009759129956364632, + "absolute_median": 0.007270969450473785, + "absolute_p95": 0.027013644576072693, + "absolute_max": 0.06296831369400024 + }, + "ema_all_candidates": { + "absolute_mean": 0.01553204096853733, + "absolute_median": 0.010676153004169464, + "absolute_p95": 0.04883582517504692, + "absolute_max": 0.13900414109230042 + }, + "ema_data_actions": { + "absolute_mean": 0.008661666885018349, + "absolute_median": 0.006147786974906921, + "absolute_p95": 0.02391199953854084, + "absolute_max": 0.050779879093170166 + }, + "ema_actor_actions": { + "absolute_mean": 0.007631178945302963, + "absolute_median": 0.005172990262508392, + "absolute_p95": 0.020781487226486206, + "absolute_max": 0.0643465518951416 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.4220840862253681, + "std": 0.28109458788045644, + "min": 0.054468244314193726, + "median": 0.3007110357284546, + "p90": 0.9607892334461212, + "p99": 0.9812664598226547, + "max": 0.9846104383468628 + }, + "live_data_q_minus_value": { + "mean": -0.05265568703180179, + "std": 0.10381480773323272, + "min": -0.5004607439041138, + "median": -0.021543920040130615, + "p90": 0.025319695472717285, + "p99": 0.13873328343033664, + "max": 0.21288639307022095 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.21576783061027527, + "direct_q_actor_mean": 0.2531784474849701, + "direct_q_actor_minus_data_mean": 0.03741063177585602, + "direct_prefers_actor_rate": 0.64453125, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.14282475642468384, + "scorer_mean": 0.23521066697526294, + "bias": 0.09238591055057911, + "mae": 0.11599968678520402, + "rmse": 0.15978324301920893, + "normalized_mae_by_direct_sd": 0.37607101584507346, + "pearson": 0.9071228808524684, + "spearman": 0.7373273902216954 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.14282475642468384, + "scorer_mean": 0.23707928686604873, + "bias": 0.0942545304413649, + "mae": 0.11342512305162818, + "rmse": 0.1599257856134883, + "normalized_mae_by_direct_sd": 0.3677242795264091, + "pearson": 0.9102838118794195, + "spearman": 0.742868138280274 + }, + "live_local_ranking": { + "top1_agreement": 0.4765625, + "pairwise_agreement": 0.8017578125, + "per_row_spearman_mean": 0.7117745535714287, + "per_row_spearman_median": 0.8333333333333335, + "direct_span_mean": 0.22143639624118805, + "scorer_span_mean": 0.3870161771774292, + "direct_data_action_best_rate": 0.31640625, + "scorer_data_action_best_rate": 0.3984375 + }, + "ema_local_ranking": { + "top1_agreement": 0.48046875, + "pairwise_agreement": 0.8051060267857143, + "per_row_spearman_mean": 0.7146577380952381, + "per_row_spearman_median": 0.8333333333333335, + "direct_span_mean": 0.22143639624118805, + "scorer_span_mean": 0.3924858570098877, + "direct_data_action_best_rate": 0.31640625, + "scorer_data_action_best_rate": 0.37109375 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.25725072622299194, + "direct_q_actor_mean": 0.32384905219078064, + "direct_q_actor_minus_data_mean": 0.0665983036160469, + "direct_prefers_actor_rate": 0.69921875, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.15950269514325227, + "scorer_mean": 0.23521066697526294, + "bias": 0.07570797183201067, + "mae": 0.0928790549250014, + "rmse": 0.12728656212242517, + "normalized_mae_by_direct_sd": 0.3118366304286966, + "pearson": 0.9399710078838912, + "spearman": 0.8754173544421502 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.15950269514325227, + "scorer_mean": 0.23707928686604873, + "bias": 0.07757659172279646, + "mae": 0.09228173679206061, + "rmse": 0.12903801953444813, + "normalized_mae_by_direct_sd": 0.3098311656441914, + "pearson": 0.9406266319745711, + "spearman": 0.8749560018080943 + }, + "live_local_ranking": { + "top1_agreement": 0.59375, + "pairwise_agreement": 0.8572823660714286, + "per_row_spearman_mean": 0.8222656250000001, + "per_row_spearman_median": 0.880952380952381, + "direct_span_mean": 0.273723840713501, + "scorer_span_mean": 0.3870161771774292, + "direct_data_action_best_rate": 0.41015625, + "scorer_data_action_best_rate": 0.3984375 + }, + "ema_local_ranking": { + "top1_agreement": 0.59375, + "pairwise_agreement": 0.8595145089285714, + "per_row_spearman_mean": 0.8271019345238098, + "per_row_spearman_median": 0.880952380952381, + "direct_span_mean": 0.273723840713501, + "scorer_span_mean": 0.3924858570098877, + "direct_data_action_best_rate": 0.41015625, + "scorer_data_action_best_rate": 0.37109375 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.3220760226249695, + "direct_q_actor_mean": 0.3963397741317749, + "direct_q_actor_minus_data_mean": 0.07426374405622482, + "direct_prefers_actor_rate": 0.69140625, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.19356297067198722, + "scorer_mean": 0.23521066697526294, + "bias": 0.04164769630327573, + "mae": 0.06581637995589656, + "rmse": 0.0955965802373732, + "normalized_mae_by_direct_sd": 0.22515758303898448, + "pearson": 0.9565945219230647, + "spearman": 0.9154097351135413 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.19356297067198722, + "scorer_mean": 0.23707928686604873, + "bias": 0.043516316194061516, + "mae": 0.06653232704529982, + "rmse": 0.0987659366353636, + "normalized_mae_by_direct_sd": 0.2276068352819953, + "pearson": 0.9556203998390038, + "spearman": 0.9135258446495873 + }, + "live_local_ranking": { + "top1_agreement": 0.63671875, + "pairwise_agreement": 0.8836495535714286, + "per_row_spearman_mean": 0.8602120535714288, + "per_row_spearman_median": 0.9047619047619048, + "direct_span_mean": 0.3387961983680725, + "scorer_span_mean": 0.3870161771774292, + "direct_data_action_best_rate": 0.44921875, + "scorer_data_action_best_rate": 0.3984375 + }, + "ema_local_ranking": { + "top1_agreement": 0.64453125, + "pairwise_agreement": 0.8895089285714286, + "per_row_spearman_mean": 0.8715587797619049, + "per_row_spearman_median": 0.9285714285714287, + "direct_span_mean": 0.3387961983680725, + "scorer_span_mean": 0.3924858570098877, + "direct_data_action_best_rate": 0.44921875, + "scorer_data_action_best_rate": 0.37109375 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.38430073857307434, + "direct_q_actor_mean": 0.45374077558517456, + "direct_q_actor_minus_data_mean": 0.0694400742650032, + "direct_prefers_actor_rate": 0.70703125, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.23557749984322088, + "scorer_mean": 0.23521066697526294, + "bias": -0.000366832867957953, + "mae": 0.05652310661389292, + "rmse": 0.0827530491957965, + "normalized_mae_by_direct_sd": 0.1875242180013539, + "pearson": 0.9615959230735938, + "spearman": 0.9212433033048043 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.23557749984322088, + "scorer_mean": 0.23707928686604873, + "bias": 0.0015017870228278417, + "mae": 0.056204303180320436, + "rmse": 0.08415653629713594, + "normalized_mae_by_direct_sd": 0.18646653790982595, + "pearson": 0.9609137327575373, + "spearman": 0.9202007493669092 + }, + "live_local_ranking": { + "top1_agreement": 0.62109375, + "pairwise_agreement": 0.8874162946428571, + "per_row_spearman_mean": 0.8715587797619049, + "per_row_spearman_median": 0.9285714285714287, + "direct_span_mean": 0.3928883373737335, + "scorer_span_mean": 0.3870161771774292, + "direct_data_action_best_rate": 0.43359375, + "scorer_data_action_best_rate": 0.3984375 + }, + "ema_local_ranking": { + "top1_agreement": 0.6328125, + "pairwise_agreement": 0.8907645089285714, + "per_row_spearman_mean": 0.8770461309523812, + "per_row_spearman_median": 0.9285714285714287, + "direct_span_mean": 0.3928883373737335, + "scorer_span_mean": 0.3924858570098877, + "direct_data_action_best_rate": 0.43359375, + "scorer_data_action_best_rate": 0.37109375 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_visual_rsm_onehop_v2_rich_adapter_actor_local_step30000_official_distill_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_visual_rsm_onehop_v2_rich_adapter_actor_local_step30000_official_distill_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..99922e227937f2b4d1e1e4526e4a22072940919a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/fair_visual_rsm_onehop_v2_rich_adapter_actor_local_step30000_official_distill_audit.json @@ -0,0 +1,756 @@ +{ + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_visual_rsm_onehop_v2_rich_adapter_actor_local_s0_step30000_manual.pkl", + "checkpoint_step": 30000, + "actor_source": "ema", + "rows": 256, + "samples_per_condition": 32, + "episodes_requested": 100, + "episodes_used": 100, + "seed": 0, + "fairness": { + "drop_proprio": true, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "discount_support": [ + 0.5, + 0.99 + ], + "uses_td_or_bootstrap": false, + "reader_target": "index", + "reader_model": "diag_metric", + "reader_index_delta": 4, + "reader_reward_semantics": "within_4_trajectory_steps_index_reward", + "strict_instant_reward_reader": false, + "recursion": "off", + "goal_roles_separate": true, + "actor_action_scorer_support": true, + "actor_query_occupancy_support": true + }, + "artifact_contract": { + "latent": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "reward_reader": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd4_diagmetric.npz", + "latent_arrays_available": [ + "actions", + "encoder_npz", + "proprio", + "proprio19", + "sigma_z", + "state_h", + "state_h_dim", + "terminals", + "z", + "z_dim" + ], + "latent_arrays_read": [ + "z", + "state_h", + "actions", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd4_diagmetric.npz", + "reader_model": "diag_metric", + "target": "index", + "index_delta": 4, + "neg_gap": 64, + "features": "concat", + "activation": "tanh", + "zdim": 8, + "pixels_only_latents": true, + "frozen_encoder": true, + "uses_coordinates_for_training": false, + "uses_coordinates_for_diagnostics": false, + "uses_reward_arrays": false, + "uses_td_or_bootstrap": false, + "label_source": "trajectory_index_positive_and_far_negative_relabeling", + "metric_formula": "bias-sum(weight*((future-goal)/scale)^2)", + "metric_scale": [ + 0.1212734580039978, + 0.11785601824522018, + 0.14360646903514862, + 0.12027847766876221, + 0.1290542036294937, + 0.11801266670227051, + 0.13187457621097565, + 0.15636976063251495 + ], + "metric_weight": [ + 0.8197049498558044, + 0.5192811489105225, + 2.501105308532715, + 2.897911310195923, + 2.5396385192871094, + 0.5441544055938721, + 1.0393574237823486, + 0.5873745083808899 + ], + "metric_scale_min": 0.11785601824522018, + "metric_scale_max": 0.15636976063251495, + "metric_weight_min": 0.5192811489105225, + "metric_weight_max": 2.897911310195923, + "metric_weight_sum": 11.448527336120605, + "metric_bias": 3.7990050315856934, + "metric_weight_nonnegative": true + } + }, + "representation_roles": { + "latent_update": "rich_adapter", + "state_feature": "joint_encoder_hidden_adapter", + "actor_goal_feature": "joint_encoder_hidden_adapter", + "occupancy_goal_feature": "joint_encoder_hidden_adapter", + "future_feature": "frozen_compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8 + }, + "policy_extraction": { + "actor_loss": "ddpgbc_distill", + "distill_actor_goals": true, + "distill_goal_loss_reduction": "mean_value_and_actor_goals", + "distill_actor_actions": true, + "distill_actor_action_local_k": 2, + "distill_actor_action_sigma": 0.3, + "distill_actor_action_pairwise_weight": 1.0, + "distill_actor_action_support_start_step": 0, + "distill_actor_action_composed_occupancy": false, + "actor_q_gradient_start_step": 0, + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_occupancy_uses_detached_live_preupdate_actor_queries", + "occupancy_training_policy": "offline_behavior_futures_with_detached_live_actor_query_negatives", + "actor_gradient_updates_occupancy": false, + "occupancy_gradient_updates_actor": false, + "critic_target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "uses_td_or_bootstrap": false, + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false + }, + "occupancy": { + "model": "flow", + "hidden": 256, + "layers": 4, + "sample_steps": 25, + "normalization": { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": true, + "condition_dim": 525, + "target_dim": 8 + }, + "actor_query_anti_exploitation": { + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "actor_local", + "occ_action_negative_sigma": 0.3, + "occ_action_negative_local_k": 2, + "occ_action_negative_candidate_count": 3, + "occ_action_negative_policy": "stop_gradient_live_preupdate_actor_mode_plus_local_gaussian", + "occ_action_negative_actor_source": "live_preupdate_actor", + "occ_action_negative_support_start_step": 0, + "occ_action_negative_actions_stop_gradient": true, + "occ_action_negative_common_random_numbers": true, + "occ_action_negative_updates_actor": false, + "occ_action_negative_counterfactual_target": false, + "occ_action_negative_interpretation": "anti_exploitation_likelihood_ranking_not_counterfactual_occupancy" + }, + "discount_sampling": { + "gamma_sampler": "stratified_bins", + "gamma_task_fraction": 0.5, + "gamma_horizons": [ + 2.0, + 4.0, + 8.0, + 16.0, + 32.0, + 64.0 + ], + "gamma_aux_discounts": [ + 0.5, + 0.75, + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "gamma_batch_allocation": "exact_task_count_balanced_aux_bins_then_shuffle", + "gamma_task_rows_per_occ_batch": 1024, + "gamma_aux_rows_per_occ_batch": [ + 171, + 171, + 171, + 171, + 170, + 170 + ], + "gamma_sampling_importance_weighted": false, + "gamma_normalization": "fixed_fourier_identity", + "gamma_encoding_lo": 0.5, + "gamma_encoding_hi": 0.99, + "condition_normalizer_probe_size": 20000, + "condition_normalizer_seed": 0, + "condition_normalizer_goal_sampler": "gciql_value_goals_20_current_50_trajectory_30_random" + } + }, + "integrated_reward_target": { + "target": "index", + "index_delta": 4, + "semantics": "within_4_trajectory_steps_index_reward", + "strict_instant_reward": false, + "checkpoint_declared_critic_target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "checkpoint_target_label_exact": true, + "all_direct_q_and_fidelity_metrics_use_this_target": true + }, + "task_gamma_scalar_fidelity": { + "gamma": 0.99, + "live_data_actions": { + "n": 256, + "direct_mean": 0.37983292062261853, + "scorer_mean": 0.36873028723493917, + "bias": -0.011102633387679361, + "mae": 0.05641838252205389, + "rmse": 0.07397059660226339, + "normalized_mae_by_direct_sd": 0.1855974037414315, + "pearson": 0.9707051188173373, + "spearman": 0.8903446154726479 + }, + "ema_data_actions": { + "n": 256, + "direct_mean": 0.37983292062261853, + "scorer_mean": 0.37625108266365714, + "bias": -0.003581837958961387, + "mae": 0.05386623131499846, + "rmse": 0.07057737129780477, + "normalized_mae_by_direct_sd": 0.1772016891390164, + "pearson": 0.9727694105032075, + "spearman": 0.9038295376516364 + }, + "live_local_candidates": { + "n": 2048, + "direct_mean": 0.25553794674954416, + "scorer_mean": 0.23741448145977984, + "bias": -0.018123465289764364, + "mae": 0.06380529938075286, + "rmse": 0.09556143746892916, + "normalized_mae_by_direct_sd": 0.2165966546222651, + "pearson": 0.9479303403137276, + "spearman": 0.9073487560090436 + }, + "ema_local_candidates": { + "n": 2048, + "direct_mean": 0.25553794674954416, + "scorer_mean": 0.24363968531594082, + "bias": -0.011898261433603376, + "mae": 0.05968301245275491, + "rmse": 0.08920842731283013, + "normalized_mae_by_direct_sd": 0.20260293362004395, + "pearson": 0.9540668985851585, + "spearman": 0.9198848800645484 + }, + "live_data_and_actor": { + "n": 512, + "direct_mean": 0.42419427015860833, + "scorer_mean": 0.4167850242192799, + "bias": -0.007409245939328457, + "mae": 0.058575346848243726, + "rmse": 0.07632147939151979, + "normalized_mae_by_direct_sd": 0.19189775233044767, + "pearson": 0.968587314936117, + "spearman": 0.9200847974674129 + }, + "ema_data_and_actor": { + "n": 512, + "direct_mean": 0.42419427015860833, + "scorer_mean": 0.4253259944234742, + "bias": 0.001131724264865852, + "mae": 0.055283309386737756, + "rmse": 0.07156775606591381, + "normalized_mae_by_direct_sd": 0.18111276131558746, + "pearson": 0.9721680317272864, + "spearman": 0.9276822728911319 + } + }, + "task_gamma_local_action_ranking": { + "candidate_count": 8, + "sigma": 0.3, + "common_base_noise": true, + "live": { + "top1_agreement": 0.51171875, + "pairwise_agreement": 0.8376116071428571, + "per_row_spearman_mean": 0.7857142857142858, + "per_row_spearman_median": 0.8333333333333335, + "direct_span_mean": 0.4006754755973816, + "scorer_span_mean": 0.41087377071380615, + "direct_data_action_best_rate": 0.21484375, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema": { + "top1_agreement": 0.5234375, + "pairwise_agreement": 0.8462611607142857, + "per_row_spearman_mean": 0.8012462797619049, + "per_row_spearman_median": 0.880952380952381, + "direct_span_mean": 0.4006754755973816, + "scorer_span_mean": 0.4158039093017578, + "direct_data_action_best_rate": 0.21484375, + "scorer_data_action_best_rate": 0.24609375 + } + }, + "actor_action_scorer_support": { + "enabled": true, + "scorer_support_start_step": 0, + "actor_q_gradient_start_step": 0, + "scorer_support_active_at_checkpoint": true, + "actor_q_gradient_active_at_checkpoint": true, + "mode_action_count": 1, + "local_action_k": 2, + "local_action_sigma": 0.3, + "pointwise_weight": 1.0, + "pairwise_weight": 1.0, + "pointwise_candidate_count": 3, + "pairwise_candidate_count_including_behavior": 4, + "behavior_action_is_pairwise_reference": true, + "common_occupancy_random_numbers": true, + "target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "composed_occupancy_target": false, + "actor_actions_are_stop_gradient_targets": true, + "updates_occupancy": false, + "loss_reduction": "normalized_point_and_pairwise_then_mean_with_existing_support", + "diagnostic_uses_common_occupancy_noise": true, + "live_point_fidelity_mode_and_local": { + "n": 768, + "direct_mean": 0.3130126874496298, + "scorer_mean": 0.30398837761989245, + "bias": -0.009024309829737334, + "mae": 0.05990924203384454, + "rmse": 0.08666624584309594, + "normalized_mae_by_direct_sd": 0.18863375906877825, + "pearson": 0.9625424160796312, + "spearman": 0.9455815823136771 + }, + "ema_point_fidelity_mode_and_local": { + "n": 768, + "direct_mean": 0.3130126874496298, + "scorer_mean": 0.3106726052265003, + "bias": -0.0023400822231294904, + "mae": 0.053672338690550346, + "rmse": 0.07798927026243418, + "normalized_mae_by_direct_sd": 0.16899587879098105, + "pearson": 0.969507328807858, + "spearman": 0.9593431790130259 + }, + "live_pairwise_gap_fidelity_with_behavior": { + "n": 1536, + "direct_mean": -0.040315450367908484, + "scorer_mean": -0.04599627712855181, + "bias": -0.005680826760643325, + "mae": 0.06340837319421087, + "rmse": 0.09455597027646227, + "normalized_mae_by_direct_sd": 0.18953315558337433, + "pearson": 0.9593776215332802, + "spearman": 0.9297142227604008, + "candidate_count": 4, + "pair_count_per_row": 6, + "sign_agreement": 0.85546875 + }, + "ema_pairwise_gap_fidelity_with_behavior": { + "n": 1536, + "direct_mean": -0.040315450367908484, + "scorer_mean": -0.04666763625922007, + "bias": -0.006352185891311579, + "mae": 0.05688180469053458, + "rmse": 0.08308153172179997, + "normalized_mae_by_direct_sd": 0.17002467332277335, + "pearson": 0.9688966099312827, + "spearman": 0.9375319249235472, + "candidate_count": 4, + "pair_count_per_row": 6, + "sign_agreement": 0.873046875 + }, + "live_ranking_with_behavior": { + "top1_agreement": 0.6171875, + "pairwise_agreement": 0.85546875, + "per_row_spearman_mean": 0.78046875, + "per_row_spearman_median": 0.7999999999999999, + "direct_span_mean": 0.39137372374534607, + "scorer_span_mean": 0.3774196207523346, + "direct_data_action_best_rate": 0.171875, + "scorer_data_action_best_rate": 0.18359375 + }, + "ema_ranking_with_behavior": { + "top1_agreement": 0.66015625, + "pairwise_agreement": 0.873046875, + "per_row_spearman_mean": 0.8109375000000001, + "per_row_spearman_median": 0.7999999999999999, + "direct_span_mean": 0.39137372374534607, + "scorer_span_mean": 0.38331687450408936, + "direct_data_action_best_rate": 0.171875, + "scorer_data_action_best_rate": 0.16796875 + } + }, + "data_actor": { + "direct_q_data": { + "mean": 0.37983292062261853, + "std": 0.30398260635506635, + "min": 2.0046179997734725e-05, + "median": 0.2680739462375641, + "p90": 0.970133900642395, + "p99": 0.9777199327945709, + "max": 0.977852463722229 + }, + "direct_q_actor": { + "mean": 0.46855561969459814, + "std": 0.30000777665626566, + "min": 0.0016363938339054585, + "median": 0.3629930913448334, + "p90": 0.966686338186264, + "p99": 0.9777261167764664, + "max": 0.9778235554695129 + }, + "direct_q_actor_minus_data": { + "mean": 0.08872269885614514, + "std": 0.16328528253737387, + "min": -0.25739067792892456, + "median": 0.03469979017972946, + "p90": 0.32466521859169006, + "p99": 0.6799175828695296, + "max": 0.7901487946510315 + }, + "direct_prefers_actor_rate": 0.7265625, + "live_scorer_q_data": { + "mean": 0.36873028723493917, + "std": 0.29138014582095095, + "min": 0.030451303347945213, + "median": 0.24097371846437454, + "p90": 0.9480657875537872, + "p99": 0.9776388674974441, + "max": 0.9839156866073608 + }, + "live_scorer_q_actor": { + "mean": 0.4648397612036206, + "std": 0.2861716482504426, + "min": 0.04845993220806122, + "median": 0.34243856370449066, + "p90": 0.946240246295929, + "p99": 0.9709739714860917, + "max": 0.9854825735092163 + }, + "live_scorer_actor_minus_data": { + "mean": 0.09610947425244376, + "std": 0.15901360396148212, + "min": -0.13747954368591309, + "median": 0.02945314347743988, + "p90": 0.322332501411438, + "p99": 0.6358369976282114, + "max": 0.7944713234901428 + }, + "live_scorer_prefers_actor_rate": 0.765625, + "ema_scorer_q_data": { + "mean": 0.37625108266365714, + "std": 0.29778980023036805, + "min": 0.03260113671422005, + "median": 0.2430511638522148, + "p90": 0.9625537693500519, + "p99": 0.9901623427867889, + "max": 0.9953986406326294 + }, + "ema_scorer_q_actor": { + "mean": 0.4744009061832912, + "std": 0.29266423916200396, + "min": 0.045489974319934845, + "median": 0.3511228412389755, + "p90": 0.9598506093025208, + "p99": 0.9795815140008927, + "max": 0.9836684465408325 + }, + "l2_to_paired_behavior_action": { + "mean": 0.7793687375669833, + "std": 0.5021362655789572, + "min": 0.10929640382528305, + "median": 0.5905367434024811, + "p90": 1.5283021926879883, + "p99": 2.054663431644439, + "max": 2.190791130065918 + }, + "l2_to_paired_behavior_action_normalized_by_action_sd": { + "mean": 1.7843543872004375, + "std": 1.118932166499248, + "min": 0.26040369272232056, + "median": 1.4592862725257874, + "p90": 3.4933738708496094, + "p99": 4.922114443778984, + "max": 5.420678615570068 + }, + "actor_component_outside_dataset_p01_p99_fraction": 0.0, + "actor_row_outside_dataset_p01_p99_rate": 0.0, + "actor_action_saturation_fraction": 0.0 + }, + "scorer_ensemble_gap": { + "live_all_candidates": { + "absolute_mean": 0.02390223555266857, + "absolute_median": 0.01651293784379959, + "absolute_p95": 0.06988490372896194, + "absolute_max": 0.28812694549560547 + }, + "live_data_actions": { + "absolute_mean": 0.013213828206062317, + "absolute_median": 0.010885298252105713, + "absolute_p95": 0.03641146048903465, + "absolute_max": 0.05936795473098755 + }, + "live_actor_actions": { + "absolute_mean": 0.015492617152631283, + "absolute_median": 0.012137949466705322, + "absolute_p95": 0.03848923742771149, + "absolute_max": 0.06664979457855225 + }, + "ema_all_candidates": { + "absolute_mean": 0.02023119293153286, + "absolute_median": 0.01300022006034851, + "absolute_p95": 0.06308216601610184, + "absolute_max": 0.21887162327766418 + }, + "ema_data_actions": { + "absolute_mean": 0.01031363382935524, + "absolute_median": 0.007596738636493683, + "absolute_p95": 0.02985517680644989, + "absolute_max": 0.06345635652542114 + }, + "ema_actor_actions": { + "absolute_mean": 0.011327680200338364, + "absolute_median": 0.00829104334115982, + "absolute_p95": 0.0335918664932251, + "absolute_max": 0.060495197772979736 + } + }, + "value_and_advantage": { + "value": { + "mean": 0.43542627032729797, + "std": 0.27914537339656886, + "min": 0.040218107402324677, + "median": 0.32261282205581665, + "p90": 0.963189423084259, + "p99": 0.9860063403844833, + "max": 0.9928609728813171 + }, + "live_data_q_minus_value": { + "mean": -0.0666959831432905, + "std": 0.11322391210104976, + "min": -0.6565437316894531, + "median": -0.03108527511358261, + "p90": 0.017854750156402588, + "p99": 0.12862777709960901, + "max": 0.2439993917942047 + }, + "awr": null + }, + "per_horizon": [ + { + "gamma": 0.8999999761581421, + "effective_horizon": 9.999998092651367, + "is_task_gamma": false, + "direct_q_data_mean": 0.217890202999115, + "direct_q_actor_mean": 0.26873818039894104, + "direct_q_actor_minus_data_mean": 0.05084796994924545, + "direct_prefers_actor_rate": 0.71875, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.14972280811969474, + "scorer_mean": 0.23741448145977984, + "bias": 0.0876916733400851, + "mae": 0.12734142677349167, + "rmse": 0.1691068661379281, + "normalized_mae_by_direct_sd": 0.4140072708629155, + "pearson": 0.8828563880114784, + "spearman": 0.7080941649825371 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.14972280811969474, + "scorer_mean": 0.24363968531594082, + "bias": 0.09391687719624608, + "mae": 0.12600304841185506, + "rmse": 0.16983124592948137, + "normalized_mae_by_direct_sd": 0.40965598953269483, + "pearson": 0.8888893660969611, + "spearman": 0.726637216302685 + }, + "live_local_ranking": { + "top1_agreement": 0.3515625, + "pairwise_agreement": 0.7286551339285714, + "per_row_spearman_mean": 0.5484561011904763, + "per_row_spearman_median": 0.7142857142857144, + "direct_span_mean": 0.22552499175071716, + "scorer_span_mean": 0.41087377071380615, + "direct_data_action_best_rate": 0.13671875, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.3515625, + "pairwise_agreement": 0.7375837053571429, + "per_row_spearman_mean": 0.5597098214285715, + "per_row_spearman_median": 0.7380952380952381, + "direct_span_mean": 0.22552499175071716, + "scorer_span_mean": 0.4158039093017578, + "direct_data_action_best_rate": 0.13671875, + "scorer_data_action_best_rate": 0.24609375 + } + }, + { + "gamma": 0.9599999785423279, + "effective_horizon": 24.99998664855957, + "is_task_gamma": false, + "direct_q_data_mean": 0.26146912574768066, + "direct_q_actor_mean": 0.34794044494628906, + "direct_q_actor_minus_data_mean": 0.08647136390209198, + "direct_prefers_actor_rate": 0.7109375, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.17540873268810175, + "scorer_mean": 0.23741448145977984, + "bias": 0.062005748771678096, + "mae": 0.1010971465391927, + "rmse": 0.13406466393866764, + "normalized_mae_by_direct_sd": 0.3331222998547597, + "pearson": 0.9201184832098611, + "spearman": 0.8463137533736308 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.17540873268810175, + "scorer_mean": 0.24363968531594082, + "bias": 0.06823095262783908, + "mae": 0.09954514158402475, + "rmse": 0.13351072876842263, + "normalized_mae_by_direct_sd": 0.32800833296499093, + "pearson": 0.9259141569502792, + "spearman": 0.8642048629098774 + }, + "live_local_ranking": { + "top1_agreement": 0.45703125, + "pairwise_agreement": 0.8098493303571429, + "per_row_spearman_mean": 0.7329799107142858, + "per_row_spearman_median": 0.8095238095238096, + "direct_span_mean": 0.2820832133293152, + "scorer_span_mean": 0.41087377071380615, + "direct_data_action_best_rate": 0.21484375, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.453125, + "pairwise_agreement": 0.8118024553571429, + "per_row_spearman_mean": 0.7372581845238095, + "per_row_spearman_median": 0.8095238095238096, + "direct_span_mean": 0.2820832133293152, + "scorer_span_mean": 0.4158039093017578, + "direct_data_action_best_rate": 0.21484375, + "scorer_data_action_best_rate": 0.24609375 + } + }, + { + "gamma": 0.9800000190734863, + "effective_horizon": 50.00004959106445, + "is_task_gamma": false, + "direct_q_data_mean": 0.3283321261405945, + "direct_q_actor_mean": 0.4193977117538452, + "direct_q_actor_minus_data_mean": 0.09106562286615372, + "direct_prefers_actor_rate": 0.703125, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.21950629774629984, + "scorer_mean": 0.23741448145977984, + "bias": 0.017908183713480005, + "mae": 0.06924153433511299, + "rmse": 0.10093488771078546, + "normalized_mae_by_direct_sd": 0.23236947017829782, + "pearson": 0.9428566149685672, + "spearman": 0.8978649055151418 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.21950629774629984, + "scorer_mean": 0.24363968531594082, + "bias": 0.024133387569640993, + "mae": 0.06641704025327058, + "rmse": 0.0970247570076002, + "normalized_mae_by_direct_sd": 0.22289067685544928, + "pearson": 0.9490406464780069, + "spearman": 0.913272446764397 + }, + "live_local_ranking": { + "top1_agreement": 0.53125, + "pairwise_agreement": 0.8364955357142857, + "per_row_spearman_mean": 0.7878534226190478, + "per_row_spearman_median": 0.8333333333333335, + "direct_span_mean": 0.3507345914840698, + "scorer_span_mean": 0.41087377071380615, + "direct_data_action_best_rate": 0.20703125, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.53125, + "pairwise_agreement": 0.8434709821428571, + "per_row_spearman_mean": 0.8003162202380955, + "per_row_spearman_median": 0.8571428571428572, + "direct_span_mean": 0.3507345914840698, + "scorer_span_mean": 0.4158039093017578, + "direct_data_action_best_rate": 0.20703125, + "scorer_data_action_best_rate": 0.24609375 + } + }, + { + "gamma": 0.9900000095367432, + "effective_horizon": 100.0000991821289, + "is_task_gamma": true, + "direct_q_data_mean": 0.379832923412323, + "direct_q_actor_mean": 0.46855562925338745, + "direct_q_actor_minus_data_mean": 0.08872269839048386, + "direct_prefers_actor_rate": 0.7265625, + "live_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.25553794674954416, + "scorer_mean": 0.23741448145977984, + "bias": -0.018123465289764364, + "mae": 0.06380529938075286, + "rmse": 0.09556143746892916, + "normalized_mae_by_direct_sd": 0.2165966546222651, + "pearson": 0.9479303403137276, + "spearman": 0.9073487560090436 + }, + "ema_scorer_fidelity_local": { + "n": 2048, + "direct_mean": 0.25553794674954416, + "scorer_mean": 0.24363968531594082, + "bias": -0.011898261433603376, + "mae": 0.05968301245275491, + "rmse": 0.08920842731283013, + "normalized_mae_by_direct_sd": 0.20260293362004395, + "pearson": 0.9540668985851585, + "spearman": 0.9198848800645484 + }, + "live_local_ranking": { + "top1_agreement": 0.51171875, + "pairwise_agreement": 0.8376116071428571, + "per_row_spearman_mean": 0.7857142857142858, + "per_row_spearman_median": 0.8333333333333335, + "direct_span_mean": 0.4006754755973816, + "scorer_span_mean": 0.41087377071380615, + "direct_data_action_best_rate": 0.21484375, + "scorer_data_action_best_rate": 0.2578125 + }, + "ema_local_ranking": { + "top1_agreement": 0.5234375, + "pairwise_agreement": 0.8462611607142857, + "per_row_spearman_mean": 0.8012462797619049, + "per_row_spearman_median": 0.880952380952381, + "direct_span_mean": 0.4006754755973816, + "scorer_span_mean": 0.4158039093017578, + "direct_data_action_best_rate": 0.21484375, + "scorer_data_action_best_rate": 0.24609375 + } + } + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/gciql_action_audit_300000.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/gciql_action_audit_300000.json new file mode 100644 index 0000000000000000000000000000000000000000..c49262ec4a2525dd59908314329650976e72597b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/gciql_action_audit_300000.json @@ -0,0 +1,140 @@ +{ + "method": "GCIQL", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-gciql-audit/ckpt/gciql_visual_control_s0/params_300000.pkl", + "checkpoint_step": 300000, + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "episodes": 100, + "pixels_only": true, + "drop_proprio": true, + "simulator_state_used": false, + "coordinate_used": false, + "dataset_keys": [ + "actions", + "observations", + "terminals", + "valids" + ], + "network_input_contract": { + "critic": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels], then dataset action", + "value": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels]", + "actor": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels]", + "training_augmentation": "with probability 0.5, one shared random-crop offset per row is applied to observation, next observation, value goal, and actor goal" + }, + "rsm_consumes_td_outputs": false, + "local_candidate_contract": { + "count": 8, + "action_sigma": 0.3, + "candidate_0": "recorded_dataset_action", + "other_candidates": "clipped_local_gaussian_perturbations", + "random_seed": 918 + }, + "online_critic_action_signal": { + "data_action_best_of_8_rate": 0.0234375, + "data_action_top2_of_8_rate": 0.11328125, + "data_action_rank_mean": 4.5703125, + "local_candidate_q_span_mean": 2.2796926498413086, + "q_action_gradient_norm_mean": 2.187547206878662, + "q_action_gradient_norm_median": 1.2897014617919922 + }, + "target_critic_action_signal": { + "data_action_best_of_8_rate": 0.0234375, + "data_action_top2_of_8_rate": 0.1171875, + "data_action_rank_mean": 4.62890625, + "local_candidate_q_span_mean": 2.15986967086792 + }, + "actor_signal": { + "data_action_l2_mean": 0.42123571038246155, + "online_q_data_mean": -26.69803237915039, + "online_q_actor_mean": -26.360393524169922, + "online_q_actor_minus_data_mean": 0.3376407325267792, + "online_prefers_actor_rate": 0.6171875, + "target_q_actor_minus_data_mean": 0.343755304813385, + "target_prefers_actor_rate": 0.59765625, + "action_saturation_fraction": 0.01015625 + }, + "value_mechanism": { + "value_mean": -25.907968521118164, + "target_q_data_mean": -26.609811782836914, + "target_q_minus_value_mean": -0.7018430233001709, + "online_target_q_spearman_data_actions": 0.9992189288166626, + "online_target_local_ranking_agreement": 0.89453125 + }, + "run_meta": { + "method": "GCIQL", + "purpose": "diagnostic_control_only", + "env": "visual-cube-single-play-v0", + "seed": 0, + "pixels_only": true, + "drop_proprio": true, + "simulator_state_used": false, + "coordinate_used": false, + "observation_shape": [ + 64, + 64, + 3 + ], + "observation_dtype": "uint8", + "action_shape": [ + 5 + ], + "dataset_keys": [ + "actions", + "observations", + "terminals", + "valids" + ], + "excluded_keys": [ + "button_states", + "coordinates", + "qpos", + "qvel" + ], + "reference_root": "/u/zwhong/ogbench_ref/impls", + "reference_sha256": "fe6a895a228506596712f2cf1571c5ffdcd15eb43c0ab31a24e9752f53b738ed", + "config": { + "actor_geom_sample": false, + "actor_hidden_dims": [ + 512, + 512, + 512 + ], + "actor_loss": "ddpgbc", + "actor_p_curgoal": 0.0, + "actor_p_randomgoal": 0.0, + "actor_p_trajgoal": 1.0, + "agent_name": "gciql", + "alpha": 1.0, + "batch_size": 256, + "const_std": true, + "dataset_class": "GCDataset", + "discount": 0.99, + "discrete": false, + "encoder": "impala_small", + "expectile": 0.9, + "frame_stack": null, + "gc_negative": true, + "layer_norm": true, + "lr": 0.0003, + "p_aug": 0.5, + "tau": 0.005, + "value_geom_sample": true, + "value_hidden_dims": [ + 512, + 512, + 512 + ], + "value_p_curgoal": 0.2, + "value_p_randomgoal": 0.3, + "value_p_trajgoal": 0.5 + }, + "train_steps": 300000, + "network_input_contract": { + "critic": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels], then dataset action", + "value": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels]", + "actor": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels]", + "training_augmentation": "with probability 0.5, one shared random-crop offset per row is applied to observation, next observation, value goal, and actor goal" + }, + "rsm_consumes_td_outputs": false + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_extract_mid110k_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_extract_mid110k_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..8ffd261ae9aaa5a3b01da5401090830c7877228a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_extract_mid110k_audit.json @@ -0,0 +1,53 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 128, + "samples_per_condition": 16, + "occupancy_model": "flow", + "latent_update": "frozen", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4847579002380371, + "empirical_std": 0.2912124693393707, + "model_mean": 0.46367567777633667, + "mae": 0.14469848573207855, + "normalized_mae": 0.4968828637741163, + "spearman": 0.6162504577916132 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.4042850434780121, + "variance_rmse_in_latent_var": 0.4479582905769348, + "model_variance_ratio": 1.0415881872177124 + }, + "denoising": { + "mse": 0.6357626914978027, + "action_shuffle_delta": 20.167280197143555, + "state_shuffle_delta": 30.132898330688477, + "goal_shuffle_delta": 0.16783292591571808 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.1870632767677307, + "q_common_noise_zero_abs_delta": 0.12032337486743927, + "local_candidate_q_span_mean": 0.2863316535949707, + "data_action_best_of_8_rate": 0.4765625, + "q_action_gradient_norm_mean": 0.1575874388217926, + "q_action_gradient_norm_median": 0.03941946476697922 + }, + "actor_signal": { + "data_action_l2_mean": 1.0495938062667847, + "model_q_data_mean": 0.46367567777633667, + "model_q_actor_mean": 0.26468634605407715, + "model_q_actor_minus_data_mean": -0.19898933172225952, + "model_prefers_actor_rate": 0.1484375, + "action_saturation_fraction": 0.003125 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.22170358896255493 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_frozen_full_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_frozen_full_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..a2f8124efae665c3fee8de34c0fe5df7a22f5b87 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_frozen_full_audit.json @@ -0,0 +1,53 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "samples_per_condition": 32, + "occupancy_model": "flow", + "latent_update": "frozen", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4814140200614929, + "empirical_std": 0.28829479217529297, + "model_mean": 0.4709320366382599, + "mae": 0.14885789155960083, + "normalized_mae": 0.5163391625509843, + "spearman": 0.6261937800411992 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.40559205412864685, + "variance_rmse_in_latent_var": 0.42146536707878113, + "model_variance_ratio": 1.0780537128448486 + }, + "denoising": { + "mse": 0.7000459432601929, + "action_shuffle_delta": 21.886821746826172, + "state_shuffle_delta": 19.675844192504883, + "goal_shuffle_delta": 0.2514641284942627 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.17753660678863525, + "q_common_noise_zero_abs_delta": 0.1076216995716095, + "local_candidate_q_span_mean": 0.30343925952911377, + "data_action_best_of_8_rate": 0.46484375, + "q_action_gradient_norm_mean": 0.2062821388244629, + "q_action_gradient_norm_median": 0.0414898544549942 + }, + "actor_signal": { + "data_action_l2_mean": 0.9941911697387695, + "model_q_data_mean": 0.4709320366382599, + "model_q_actor_mean": 0.27431797981262207, + "model_q_actor_minus_data_mean": -0.19661404192447662, + "model_prefers_actor_rate": 0.1796875, + "action_saturation_fraction": 0.0140625 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.2287832796573639 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_joint_full_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_joint_full_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..4b1e78f56be92ced3ea01bf6fde5358cea1c670f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_joint_full_audit.json @@ -0,0 +1,53 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "samples_per_condition": 32, + "occupancy_model": "flow", + "latent_update": "adapter", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4851498603820801, + "empirical_std": 0.28149309754371643, + "model_mean": 0.473422646522522, + "mae": 0.1470436453819275, + "normalized_mae": 0.5223703411025605, + "spearman": 0.6332405870908674 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.3778528869152069, + "variance_rmse_in_latent_var": 0.36249563097953796, + "model_variance_ratio": 1.0814200639724731 + }, + "denoising": { + "mse": 0.6462150812149048, + "action_shuffle_delta": 18.984643936157227, + "state_shuffle_delta": 14.7400541305542, + "goal_shuffle_delta": 0.24789007008075714 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.1725793331861496, + "q_common_noise_zero_abs_delta": 0.11107288300991058, + "local_candidate_q_span_mean": 0.29095694422721863, + "data_action_best_of_8_rate": 0.55078125, + "q_action_gradient_norm_mean": 0.2290668487548828, + "q_action_gradient_norm_median": 0.04175649583339691 + }, + "actor_signal": { + "data_action_l2_mean": 0.9419808387756348, + "model_q_data_mean": 0.473422646522522, + "model_q_actor_mean": 0.3296498656272888, + "model_q_actor_minus_data_mean": -0.14377281069755554, + "model_prefers_actor_rate": 0.24609375, + "action_saturation_fraction": 0.00234375 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.21762433648109436 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_warmbc_mid150k_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_warmbc_mid150k_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..e8ea0234ab45a804fe22d9393499e5a70c6fe632 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_aclocal_warmbc_mid150k_audit.json @@ -0,0 +1,53 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 128, + "samples_per_condition": 16, + "occupancy_model": "flow", + "latent_update": "frozen", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4847579002380371, + "empirical_std": 0.2912124693393707, + "model_mean": 0.46367567777633667, + "mae": 0.14469847083091736, + "normalized_mae": 0.4968828126047373, + "spearman": 0.6162504577916132 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.4042850434780121, + "variance_rmse_in_latent_var": 0.4479582905769348, + "model_variance_ratio": 1.0415881872177124 + }, + "denoising": { + "mse": 0.6357626914978027, + "action_shuffle_delta": 20.167280197143555, + "state_shuffle_delta": 30.132898330688477, + "goal_shuffle_delta": 0.16783292591571808 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.1870632767677307, + "q_common_noise_zero_abs_delta": 0.12032338231801987, + "local_candidate_q_span_mean": 0.2863316535949707, + "data_action_best_of_8_rate": 0.4765625, + "q_action_gradient_norm_mean": 0.157586932182312, + "q_action_gradient_norm_median": 0.03941946476697922 + }, + "actor_signal": { + "data_action_l2_mean": 1.0407981872558594, + "model_q_data_mean": 0.46367567777633667, + "model_q_actor_mean": 0.26006752252578735, + "model_q_actor_minus_data_mean": -0.20360814034938812, + "model_prefers_actor_rate": 0.171875, + "action_saturation_fraction": 0.0109375 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.22170358896255493 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_bc_probe100k_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_bc_probe100k_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..3803cf7a99e51a57d8a38e56e94a61b805590ce4 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_bc_probe100k_audit.json @@ -0,0 +1,53 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 128, + "samples_per_condition": 16, + "occupancy_model": "flow", + "latent_update": "frozen", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4847579002380371, + "empirical_std": 0.2912124693393707, + "model_mean": 0.46367567777633667, + "mae": 0.14469847083091736, + "normalized_mae": 0.4968828126047373, + "spearman": 0.6162504577916132 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.4042850434780121, + "variance_rmse_in_latent_var": 0.4479582905769348, + "model_variance_ratio": 1.0415881872177124 + }, + "denoising": { + "mse": 0.6357626914978027, + "action_shuffle_delta": 20.167280197143555, + "state_shuffle_delta": 30.132898330688477, + "goal_shuffle_delta": 0.16783292591571808 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.1870632767677307, + "q_common_noise_zero_abs_delta": 0.12032338231801987, + "local_candidate_q_span_mean": 0.2863316535949707, + "data_action_best_of_8_rate": 0.4765625, + "q_action_gradient_norm_mean": 0.1575874388217926, + "q_action_gradient_norm_median": 0.03941946476697922 + }, + "actor_signal": { + "data_action_l2_mean": 0.770279049873352, + "model_q_data_mean": 0.46367567777633667, + "model_q_actor_mean": 0.4387998580932617, + "model_q_actor_minus_data_mean": -0.0248758215457201, + "model_prefers_actor_rate": 0.4609375, + "action_saturation_fraction": 0.0015625 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.22170358896255493 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_full_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_full_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..bfb63356c757da5862cd492b23e265375b741147 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_full_audit.json @@ -0,0 +1,53 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "samples_per_condition": 32, + "occupancy_model": "flow", + "latent_update": "frozen", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4814140200614929, + "empirical_std": 0.28829479217529297, + "model_mean": 0.4763268828392029, + "mae": 0.1496191918849945, + "normalized_mae": 0.5189798634795352, + "spearman": 0.6194037537193865 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.407265305519104, + "variance_rmse_in_latent_var": 0.42325520515441895, + "model_variance_ratio": 1.0800105333328247 + }, + "denoising": { + "mse": 0.6759840250015259, + "action_shuffle_delta": 0.033768512308597565, + "state_shuffle_delta": 0.27616116404533386, + "goal_shuffle_delta": 0.2609386444091797 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.08018031716346741, + "q_common_noise_zero_abs_delta": 0.06837301701307297, + "local_candidate_q_span_mean": 0.11918501555919647, + "data_action_best_of_8_rate": 0.109375, + "q_action_gradient_norm_mean": 0.2706668972969055, + "q_action_gradient_norm_median": 0.02049640193581581 + }, + "actor_signal": { + "data_action_l2_mean": 0.7210788726806641, + "model_q_data_mean": 0.4763268828392029, + "model_q_actor_mean": 0.4782681167125702, + "model_q_actor_minus_data_mean": 0.0019412182737141848, + "model_prefers_actor_rate": 0.4140625, + "action_saturation_fraction": 0.0015625 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.19749264419078827 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..3eb322f0f2dd10ab4b9ee34c35621ed8f954295f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_audit.json @@ -0,0 +1,54 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "samples_per_condition": 32, + "occupancy_model": "flow", + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4814140200614929, + "empirical_std": 0.28829479217529297, + "model_mean": 0.4700940251350403, + "mae": 0.14852944016456604, + "normalized_mae": 0.5151998724772493, + "spearman": 0.6292350938429846 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.40496277809143066, + "variance_rmse_in_latent_var": 0.4192798435688019, + "model_variance_ratio": 1.0797797441482544 + }, + "denoising": { + "mse": 0.6751123070716858, + "action_shuffle_delta": 69.30569458007812, + "state_shuffle_delta": 56.32301330566406, + "goal_shuffle_delta": 0.2619513273239136 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.21481665968894958, + "q_common_noise_zero_abs_delta": 0.1360364407300949, + "local_candidate_q_span_mean": 0.3506094813346863, + "data_action_best_of_8_rate": 0.5234375, + "q_action_gradient_norm_mean": 0.15607278048992157, + "q_action_gradient_norm_median": 0.03971715271472931 + }, + "actor_signal": { + "data_action_l2_mean": 0.7176102995872498, + "model_q_data_mean": 0.4700940251350403, + "model_q_actor_mean": 0.4690322279930115, + "model_q_actor_minus_data_mean": -0.0010618618689477444, + "model_prefers_actor_rate": 0.48046875, + "action_saturation_fraction": 0.00390625 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.24217037856578827 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd0_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd0_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..34a994bfc0b3e8e0ca4e41d43cb8857ed150974a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd0_audit.json @@ -0,0 +1,54 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "samples_per_condition": 32, + "occupancy_model": "flow", + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "index", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.25500649213790894, + "empirical_std": 0.2836539149284363, + "model_mean": 0.2557432949542999, + "mae": 0.1763424277305603, + "normalized_mae": 0.621681628385246, + "spearman": 0.4595609680038218 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.40496277809143066, + "variance_rmse_in_latent_var": 0.4192798435688019, + "model_variance_ratio": 1.0797797441482544 + }, + "denoising": { + "mse": 0.6751123666763306, + "action_shuffle_delta": 69.30580139160156, + "state_shuffle_delta": 56.32298278808594, + "goal_shuffle_delta": 0.2619512677192688 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.20036360621452332, + "q_common_noise_zero_abs_delta": 0.13604524731636047, + "local_candidate_q_span_mean": 0.26998311281204224, + "data_action_best_of_8_rate": 0.62109375, + "q_action_gradient_norm_mean": 0.0789109542965889, + "q_action_gradient_norm_median": 0.0 + }, + "actor_signal": { + "data_action_l2_mean": 0.7176102995872498, + "model_q_data_mean": 0.2557432949542999, + "model_q_actor_mean": 0.23716461658477783, + "model_q_actor_minus_data_mean": -0.0185786671936512, + "model_prefers_actor_rate": 0.43359375, + "action_saturation_fraction": 0.00390625 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.22171112895011902 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd2_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd2_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..1f5f1b201218f0b146d59aaa2d640e31fdd7a2ae --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd2_audit.json @@ -0,0 +1,54 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "samples_per_condition": 32, + "occupancy_model": "flow", + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "index", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.3085985779762268, + "empirical_std": 0.32113927602767944, + "model_mean": 0.31910574436187744, + "mae": 0.17210450768470764, + "normalized_mae": 0.535918589010812, + "spearman": 0.5208850709544518 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.40496277809143066, + "variance_rmse_in_latent_var": 0.4192798435688019, + "model_variance_ratio": 1.0797797441482544 + }, + "denoising": { + "mse": 0.6751123070716858, + "action_shuffle_delta": 69.30569458007812, + "state_shuffle_delta": 56.32301330566406, + "goal_shuffle_delta": 0.2619513273239136 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.2459564357995987, + "q_common_noise_zero_abs_delta": 0.1577751487493515, + "local_candidate_q_span_mean": 0.33987683057785034, + "data_action_best_of_8_rate": 0.6015625, + "q_action_gradient_norm_mean": 0.1157371997833252, + "q_action_gradient_norm_median": 7.068594186421251e-06 + }, + "actor_signal": { + "data_action_l2_mean": 0.7176102995872498, + "model_q_data_mean": 0.31910574436187744, + "model_q_actor_mean": 0.30643725395202637, + "model_q_actor_minus_data_mean": -0.012668488547205925, + "model_prefers_actor_rate": 0.4921875, + "action_saturation_fraction": 0.00390625 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.27400776743888855 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd8_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd8_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..d240cd05179fef23e8314c81d3a8544e4580e766 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_full_indexd8_audit.json @@ -0,0 +1,54 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "samples_per_condition": 32, + "occupancy_model": "flow", + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "index", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.372464120388031, + "empirical_std": 0.356330007314682, + "model_mean": 0.3750288784503937, + "mae": 0.17771583795547485, + "normalized_mae": 0.49873946708768346, + "spearman": 0.5844543945983062 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.40496277809143066, + "variance_rmse_in_latent_var": 0.4192798435688019, + "model_variance_ratio": 1.0797797441482544 + }, + "denoising": { + "mse": 0.6751123070716858, + "action_shuffle_delta": 69.30569458007812, + "state_shuffle_delta": 56.32301330566406, + "goal_shuffle_delta": 0.2619513273239136 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.2809426188468933, + "q_common_noise_zero_abs_delta": 0.18068286776542664, + "local_candidate_q_span_mean": 0.39669227600097656, + "data_action_best_of_8_rate": 0.6015625, + "q_action_gradient_norm_mean": 0.09453046321868896, + "q_action_gradient_norm_median": 0.00010037090396508574 + }, + "actor_signal": { + "data_action_l2_mean": 0.7176102995872498, + "model_q_data_mean": 0.3750288784503937, + "model_q_actor_mean": 0.36078619956970215, + "model_q_actor_minus_data_mean": -0.014242655597627163, + "model_prefers_actor_rate": 0.4921875, + "action_saturation_fraction": 0.00390625 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.31091344356536865 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_mid100k_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_mid100k_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..66367d804f78eeacfa07efa2f708d2995b1ec761 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_mid100k_audit.json @@ -0,0 +1,54 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 128, + "samples_per_condition": 16, + "occupancy_model": "flow", + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4847579002380371, + "empirical_std": 0.2912124693393707, + "model_mean": 0.44630008935928345, + "mae": 0.1473379135131836, + "normalized_mae": 0.5059464446952654, + "spearman": 0.6332116370628089 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.4026086926460266, + "variance_rmse_in_latent_var": 0.4491363763809204, + "model_variance_ratio": 1.0442503690719604 + }, + "denoising": { + "mse": 0.6403612494468689, + "action_shuffle_delta": 8.411270141601562, + "state_shuffle_delta": 9.734107971191406, + "goal_shuffle_delta": 0.18234670162200928 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.1790192723274231, + "q_common_noise_zero_abs_delta": 0.1165817379951477, + "local_candidate_q_span_mean": 0.2921898365020752, + "data_action_best_of_8_rate": 0.4921875, + "q_action_gradient_norm_mean": 0.14603285491466522, + "q_action_gradient_norm_median": 0.05856893211603165 + }, + "actor_signal": { + "data_action_l2_mean": 0.8104262351989746, + "model_q_data_mean": 0.44630008935928345, + "model_q_actor_mean": 0.4938385486602783, + "model_q_actor_minus_data_mean": 0.04753847420215607, + "model_prefers_actor_rate": 0.6875, + "action_saturation_fraction": 0.0 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.20659248530864716 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_mid270k_audit.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_mid270k_audit.json new file mode 100644 index 0000000000000000000000000000000000000000..6915305789290422b588d937d2aac0b9943a4240 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_flow_stateh256_mid270k_audit.json @@ -0,0 +1,54 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 128, + "samples_per_condition": 16, + "occupancy_model": "flow", + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "model_hidden": 256, + "model_layers": 4, + "sample_steps": 25, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.4847579002380371, + "empirical_std": 0.2912124693393707, + "model_mean": 0.4558680057525635, + "mae": 0.1453244984149933, + "normalized_mae": 0.49903254055250035, + "spearman": 0.6366908533235671 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.40700727701187134, + "variance_rmse_in_latent_var": 0.44477543234825134, + "model_variance_ratio": 1.0448026657104492 + }, + "denoising": { + "mse": 0.6328076124191284, + "action_shuffle_delta": 19.710542678833008, + "state_shuffle_delta": 21.992721557617188, + "goal_shuffle_delta": 0.1695517599582672 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.1927044540643692, + "q_common_noise_zero_abs_delta": 0.14613433182239532, + "local_candidate_q_span_mean": 0.3014281988143921, + "data_action_best_of_8_rate": 0.5390625, + "q_action_gradient_norm_mean": 0.27296707034111023, + "q_action_gradient_norm_median": 0.04405594617128372 + }, + "actor_signal": { + "data_action_l2_mean": 0.7640133500099182, + "model_q_data_mean": 0.4558680057525635, + "model_q_actor_mean": 0.462573766708374, + "model_q_actor_minus_data_mean": 0.006705732084810734, + "model_prefers_actor_rate": 0.5, + "action_saturation_fraction": 0.0 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.22342999279499054 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gactionprio_h2_64.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gactionprio_h2_64.json new file mode 100644 index 0000000000000000000000000000000000000000..49967e0fd2686aebb5354f40c7c13516bfc17f9c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gactionprio_h2_64.json @@ -0,0 +1,381 @@ +{ + "variant": "stateh_ac_gactionprio_h2_64", + "fairness": { + "drop_proprio": true, + "pixels_only": true, + "uses_coordinates": false, + "occupancy_uses_reward_labels": false, + "discount_conditioned": true, + "discount_encoding": "log_horizon_fourier_k4", + "occupancy_definition": "(1-gamma)*sum_{k>=0} gamma^k P(z_{t+k}|s_t,a_t,g)", + "shifted_occupancy": false, + "occupancy_state_condition_feature": "frozen_pixel_encoder_fc0_hidden", + "occupancy_goal_condition_feature": "frozen_pixel_encoder_reward_latent_z", + "occupancy_future_target_feature": "frozen_pixel_encoder_reward_latent_z", + "reward_reader_goal_feature": "frozen_pixel_encoder_reward_latent_z", + "objective": "flow_matching_plus_reward_free_action_contrast_no_td", + "uses_td_or_bootstrap": false, + "uses_world_model_rollout": false, + "external_action_proposer": false + }, + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "future_sampler": "stratified", + "gamma_sampler": "action_priority", + "gamma_support": { + "kind": "task_plus_discrete_auxiliary", + "task_fraction": 0.5, + "aux_horizons": [ + 2.0, + 4.0, + 8.0, + 16.0, + 32.0, + 64.0 + ], + "aux_gammas": [ + 0.5, + 0.75, + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "aux_proposal_probabilities": [ + 0.3839520059992501, + 0.2879640044994376, + 0.1679790026246719, + 0.08998875140607424, + 0.046494188226471694, + 0.023622047244094488 + ], + "importance_weighted": false, + "importance_target": null + }, + "gamma_proposal_probe": { + "rows": 32768, + "task_branch_fraction": 0.5, + "gamma_weight_task_min": 1.0, + "gamma_weight_task_max": 1.0, + "gamma_weight_all_mean": 1.0, + "gamma_weight_all_max": 1.0, + "sampled_horizon_quantiles": { + "p10": 2.0, + "p50": 82.0000476837613, + "p90": 100.00009536752259 + }, + "zero_offset_fraction": 0.29876708984375, + "offset_support": "unshifted_k_ge_0", + "aux_bin_counts": { + "H2": 6248, + "H4": 4778, + "H8": 2761, + "H16": 1470, + "H32": 759, + "H64": 368 + } + }, + "state_key": "state_h", + "state_dim": 256, + "goal_key": "z", + "goal_dim": 8, + "future_target_key": "z", + "future_target_dim": 8, + "reward_reader_goal_key": "z", + "reward_reader_goal_dim": 8, + "discount_conditioned": true, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 443.56, + "final_loss": 0.5299828052520752 + }, + "readers": { + "primary_policy_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_index_d8_symrelu_s0.npz", + "target": "index", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "diagnostic_return_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz", + "target": "gciql", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "readers_used_during_occupancy_training": false + }, + "task_gamma_key": "H100_g0.990000", + "heldout_reward_expectation": { + "empirical_mean": 0.34922701120376587, + "empirical_std": 0.34182673692703247, + "model_mean": 0.3393210768699646, + "mae": 0.14734715223312378, + "normalized_mae": 0.431058007801704, + "spearman": 0.6390599249221754 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4146563708782196, + "variance_rmse_in_latent_var": 0.463854044675827, + "model_variance_ratio": 1.0603389739990234 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.1917804777622223, + "local_candidate_q_span_mean": 0.3432060480117798, + "data_action_best_of_8_rate": 0.40625 + }, + "per_horizon": { + "H2_g0.500000": { + "horizon": 2.0, + "gamma": 0.5, + "primary_reward_expectation": { + "empirical_mean": 0.1505288928747177, + "empirical_std": 0.3439146876335144, + "model_mean": 0.14913643896579742, + "mae": 0.0032808282412588596, + "normalized_mae": 0.009539657244168085, + "spearman": 0.9350384334789019 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.29565542936325073, + "empirical_std": 0.25984257459640503, + "model_mean": 0.2940714955329895, + "mae": 0.005632626824080944, + "normalized_mae": 0.021677074408724985, + "spearman": 0.996618064457059 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.05278884619474411, + "variance_rmse_in_latent_var": 0.03092404082417488, + "model_variance_ratio": 0.7978648543357849 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.07274352014064789, + "local_candidate_q_span_mean": 0.16950762271881104, + "data_action_best_of_8_rate": 0.125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.08324544131755829, + "local_candidate_q_span_mean": 0.18621695041656494, + "data_action_best_of_8_rate": 0.078125 + } + }, + "H4_g0.750000": { + "horizon": 4.0, + "gamma": 0.75, + "primary_reward_expectation": { + "empirical_mean": 0.15416553616523743, + "empirical_std": 0.34448885917663574, + "model_mean": 0.15167178213596344, + "mae": 0.00691357534378767, + "normalized_mae": 0.020069082525083208, + "spearman": 0.846527214741797 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.3020879626274109, + "empirical_std": 0.2645036578178406, + "model_mean": 0.2975878119468689, + "mae": 0.012013183906674385, + "normalized_mae": 0.04541783658412645, + "spearman": 0.9896539095403772 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.10162858664989471, + "variance_rmse_in_latent_var": 0.09169501811265945, + "model_variance_ratio": 0.8728771209716797 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.07839210331439972, + "local_candidate_q_span_mean": 0.17496509850025177, + "data_action_best_of_8_rate": 0.1328125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.08476823568344116, + "local_candidate_q_span_mean": 0.192500501871109, + "data_action_best_of_8_rate": 0.1328125 + } + }, + "H8_g0.875000": { + "horizon": 8.0, + "gamma": 0.875, + "primary_reward_expectation": { + "empirical_mean": 0.16398364305496216, + "empirical_std": 0.3444366157054901, + "model_mean": 0.1597917377948761, + "mae": 0.015558524057269096, + "normalized_mae": 0.04517093522534313, + "spearman": 0.7251876945614356 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.31232064962387085, + "empirical_std": 0.27165499329566956, + "model_mean": 0.3032492399215698, + "mae": 0.02116183564066887, + "normalized_mae": 0.07789967481892117, + "spearman": 0.9682292620399193 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.1687813401222229, + "variance_rmse_in_latent_var": 0.20065446197986603, + "model_variance_ratio": 0.9147034287452698 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.09069012105464935, + "local_candidate_q_span_mean": 0.1888008713722229, + "data_action_best_of_8_rate": 0.1953125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.09073378890752792, + "local_candidate_q_span_mean": 0.20016199350357056, + "data_action_best_of_8_rate": 0.15625 + } + }, + "H16_g0.937500": { + "horizon": 16.0, + "gamma": 0.9375, + "primary_reward_expectation": { + "empirical_mean": 0.1852213740348816, + "empirical_std": 0.3457781672477722, + "model_mean": 0.18555906414985657, + "mae": 0.039114899933338165, + "normalized_mae": 0.11312136982121787, + "spearman": 0.6664530305804797 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.32881981134414673, + "empirical_std": 0.28073397278785706, + "model_mean": 0.319291889667511, + "mae": 0.03478575497865677, + "normalized_mae": 0.12391002995901536, + "spearman": 0.9020211499725324 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.2549900412559509, + "variance_rmse_in_latent_var": 0.3149431347846985, + "model_variance_ratio": 1.021128535270691 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.11053827404975891, + "local_candidate_q_span_mean": 0.2137175053358078, + "data_action_best_of_8_rate": 0.2109375 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.10230153799057007, + "local_candidate_q_span_mean": 0.20764397084712982, + "data_action_best_of_8_rate": 0.21875 + } + }, + "H32_g0.968750": { + "horizon": 32.0, + "gamma": 0.96875, + "primary_reward_expectation": { + "empirical_mean": 0.2248375117778778, + "empirical_std": 0.348341166973114, + "model_mean": 0.23098456859588623, + "mae": 0.07814140617847443, + "normalized_mae": 0.22432435091573774, + "spearman": 0.5918787767808094 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.36093538999557495, + "empirical_std": 0.28592631220817566, + "model_mean": 0.34810125827789307, + "mae": 0.0675056129693985, + "normalized_mae": 0.23609444142464714, + "spearman": 0.7914530305804797 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.34259581565856934, + "variance_rmse_in_latent_var": 0.3896466791629791, + "model_variance_ratio": 1.0710893869400024 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.13708241283893585, + "local_candidate_q_span_mean": 0.2551926076412201, + "data_action_best_of_8_rate": 0.3125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.1173040047287941, + "local_candidate_q_span_mean": 0.2217109203338623, + "data_action_best_of_8_rate": 0.2734375 + } + }, + "H64_g0.984375": { + "horizon": 64.0, + "gamma": 0.984375, + "primary_reward_expectation": { + "empirical_mean": 0.2933652698993683, + "empirical_std": 0.3458337187767029, + "model_mean": 0.29732489585876465, + "mae": 0.12648794054985046, + "normalized_mae": 0.365747854192092, + "spearman": 0.5955926112433619 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.4175015687942505, + "empirical_std": 0.28455883264541626, + "model_mean": 0.39171507954597473, + "mae": 0.1083209216594696, + "normalized_mae": 0.3806626582364653, + "spearman": 0.6628765336019043 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.40290337800979614, + "variance_rmse_in_latent_var": 0.4436827600002289, + "model_variance_ratio": 1.0621860027313232 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.17301982641220093, + "local_candidate_q_span_mean": 0.30666211247444153, + "data_action_best_of_8_rate": 0.40625 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.14132629334926605, + "local_candidate_q_span_mean": 0.25324875116348267, + "data_action_best_of_8_rate": 0.375 + } + }, + "H100_g0.990000": { + "horizon": 100.0, + "gamma": 0.9900000095367432, + "primary_reward_expectation": { + "empirical_mean": 0.34922701120376587, + "empirical_std": 0.34182673692703247, + "model_mean": 0.3393210768699646, + "mae": 0.14734715223312378, + "normalized_mae": 0.431058007801704, + "spearman": 0.6390599249221754 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.4634796380996704, + "empirical_std": 0.28095051646232605, + "model_mean": 0.41958749294281006, + "mae": 0.13221028447151184, + "normalized_mae": 0.4705821015610787, + "spearman": 0.6535204175059512 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.4146563708782196, + "variance_rmse_in_latent_var": 0.463854044675827, + "model_variance_ratio": 1.0603389739990234 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.1917804777622223, + "local_candidate_q_span_mean": 0.3432060480117798, + "data_action_best_of_8_rate": 0.40625 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.15257740020751953, + "local_candidate_q_span_mean": 0.2730233371257782, + "data_action_best_of_8_rate": 0.421875 + } + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gfixed.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gfixed.json new file mode 100644 index 0000000000000000000000000000000000000000..d8724348dd6e5c3600ebc70c4c51c0b2c409bd9f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gfixed.json @@ -0,0 +1,356 @@ +{ + "variant": "stateh_ac_gfixed", + "fairness": { + "drop_proprio": true, + "pixels_only": true, + "uses_coordinates": false, + "occupancy_uses_reward_labels": false, + "discount_conditioned": true, + "discount_encoding": "log_horizon_fourier_k4", + "occupancy_definition": "(1-gamma)*sum_{k>=0} gamma^k P(z_{t+k}|s_t,a_t,g)", + "shifted_occupancy": false, + "occupancy_state_condition_feature": "frozen_pixel_encoder_fc0_hidden", + "occupancy_goal_condition_feature": "frozen_pixel_encoder_reward_latent_z", + "occupancy_future_target_feature": "frozen_pixel_encoder_reward_latent_z", + "reward_reader_goal_feature": "frozen_pixel_encoder_reward_latent_z", + "objective": "flow_matching_plus_reward_free_action_contrast_no_td", + "uses_td_or_bootstrap": false, + "uses_world_model_rollout": false, + "external_action_proposer": false + }, + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "future_sampler": "stratified", + "gamma_sampler": "fixed", + "gamma_support": { + "kind": "point_mass", + "horizons": [ + 100.0 + ], + "gammas": [ + 0.99 + ], + "proposal_probabilities": [ + 1.0 + ], + "importance_weighted": false + }, + "gamma_proposal_probe": { + "rows": 32768, + "task_branch_fraction": 1.0, + "gamma_weight_task_min": 1.0, + "gamma_weight_task_max": 1.0, + "gamma_weight_all_mean": 1.0, + "gamma_weight_all_max": 1.0, + "sampled_horizon_quantiles": { + "p10": 100.00009536752259, + "p50": 100.00009536752259, + "p90": 100.00009536752259 + }, + "zero_offset_fraction": 0.22515869140625, + "offset_support": "unshifted_k_ge_0" + }, + "state_key": "state_h", + "state_dim": 256, + "goal_key": "z", + "goal_dim": 8, + "future_target_key": "z", + "future_target_dim": 8, + "reward_reader_goal_key": "z", + "reward_reader_goal_dim": 8, + "discount_conditioned": true, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 391.07, + "final_loss": 0.7137764692306519 + }, + "readers": { + "primary_policy_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_index_d8_symrelu_s0.npz", + "target": "index", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "diagnostic_return_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz", + "target": "gciql", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "readers_used_during_occupancy_training": false + }, + "task_gamma_key": "H100_g0.990000", + "heldout_reward_expectation": { + "empirical_mean": 0.34922701120376587, + "empirical_std": 0.34182673692703247, + "model_mean": 0.33625495433807373, + "mae": 0.14780008792877197, + "normalized_mae": 0.43238305247117603, + "spearman": 0.6210401025453213 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4105582535266876, + "variance_rmse_in_latent_var": 0.45037516951560974, + "model_variance_ratio": 1.058014154434204 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.1747567355632782, + "local_candidate_q_span_mean": 0.3481898605823517, + "data_action_best_of_8_rate": 0.2265625 + }, + "per_horizon": { + "H2_g0.500000": { + "horizon": 2.0, + "gamma": 0.5, + "primary_reward_expectation": { + "empirical_mean": 0.1505288928747177, + "empirical_std": 0.3439146876335144, + "model_mean": 0.31088897585868835, + "mae": 0.16885924339294434, + "normalized_mae": 0.49099166003891553, + "spearman": 0.627234611525306 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.29565542936325073, + "empirical_std": 0.25984257459640503, + "model_mean": 0.38960975408554077, + "mae": 0.11179781705141068, + "normalized_mae": 0.4302521140927666, + "spearman": 0.7159403039736312 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.7654973268508911, + "variance_rmse_in_latent_var": 0.7070160508155823, + "model_variance_ratio": 34.651798248291016 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.1753215193748474, + "local_candidate_q_span_mean": 0.3222527503967285, + "data_action_best_of_8_rate": 0.2421875 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.14863541722297668, + "local_candidate_q_span_mean": 0.2529706656932831, + "data_action_best_of_8_rate": 0.2578125 + } + }, + "H4_g0.750000": { + "horizon": 4.0, + "gamma": 0.75, + "primary_reward_expectation": { + "empirical_mean": 0.15416553616523743, + "empirical_std": 0.34448885917663574, + "model_mean": 0.16876666247844696, + "mae": 0.154923677444458, + "normalized_mae": 0.44972042873822315, + "spearman": 0.489526310156364 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.3020879626274109, + "empirical_std": 0.2645036578178406, + "model_mean": 0.2781772017478943, + "mae": 0.12094700336456299, + "normalized_mae": 0.4572602298296277, + "spearman": 0.6086282274308734 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.9383209943771362, + "variance_rmse_in_latent_var": 0.6987665891647339, + "model_variance_ratio": 10.04837703704834 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.11814578622579575, + "local_candidate_q_span_mean": 0.2238978147506714, + "data_action_best_of_8_rate": 0.1640625 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.08609765022993088, + "local_candidate_q_span_mean": 0.16562287509441376, + "data_action_best_of_8_rate": 0.1484375 + } + }, + "H8_g0.875000": { + "horizon": 8.0, + "gamma": 0.875, + "primary_reward_expectation": { + "empirical_mean": 0.16398364305496216, + "empirical_std": 0.3444366157054901, + "model_mean": 0.15617682039737701, + "mae": 0.16285422444343567, + "normalized_mae": 0.4728133334775414, + "spearman": 0.40547747665262773 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.31232064962387085, + "empirical_std": 0.27165499329566956, + "model_mean": 0.2691868245601654, + "mae": 0.13707029819488525, + "normalized_mae": 0.5045749262031706, + "spearman": 0.5842107672587438 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 1.0040149688720703, + "variance_rmse_in_latent_var": 0.6666678786277771, + "model_variance_ratio": 4.3084259033203125 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.10216915607452393, + "local_candidate_q_span_mean": 0.2089024931192398, + "data_action_best_of_8_rate": 0.1796875 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.07729823887348175, + "local_candidate_q_span_mean": 0.15960457921028137, + "data_action_best_of_8_rate": 0.1875 + } + }, + "H16_g0.937500": { + "horizon": 16.0, + "gamma": 0.9375, + "primary_reward_expectation": { + "empirical_mean": 0.1852213740348816, + "empirical_std": 0.3457781672477722, + "model_mean": 0.2858734726905823, + "mae": 0.12932395935058594, + "normalized_mae": 0.3740084586020639, + "spearman": 0.6113635323200878 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.32881981134414673, + "empirical_std": 0.28073397278785706, + "model_mean": 0.36694878339767456, + "mae": 0.09971189498901367, + "normalized_mae": 0.355182858700052, + "spearman": 0.7674018036989562 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.5613945126533508, + "variance_rmse_in_latent_var": 0.5946481227874756, + "model_variance_ratio": 2.2176296710968018 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.166763037443161, + "local_candidate_q_span_mean": 0.3097233772277832, + "data_action_best_of_8_rate": 0.203125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.13626760244369507, + "local_candidate_q_span_mean": 0.23886749148368835, + "data_action_best_of_8_rate": 0.2734375 + } + }, + "H32_g0.968750": { + "horizon": 32.0, + "gamma": 0.96875, + "primary_reward_expectation": { + "empirical_mean": 0.2248375117778778, + "empirical_std": 0.348341166973114, + "model_mean": 0.1660037487745285, + "mae": 0.16709491610527039, + "normalized_mae": 0.47968753609350817, + "spearman": 0.4431022248672403 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.36093538999557495, + "empirical_std": 0.28592631220817566, + "model_mean": 0.27905476093292236, + "mae": 0.14617513120174408, + "normalized_mae": 0.51123357648637, + "spearman": 0.598745650979674 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.6835168600082397, + "variance_rmse_in_latent_var": 0.54340660572052, + "model_variance_ratio": 1.6731102466583252 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.1129818931221962, + "local_candidate_q_span_mean": 0.22046233713626862, + "data_action_best_of_8_rate": 0.1796875 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.08304683119058609, + "local_candidate_q_span_mean": 0.15832604467868805, + "data_action_best_of_8_rate": 0.140625 + } + }, + "H64_g0.984375": { + "horizon": 64.0, + "gamma": 0.984375, + "primary_reward_expectation": { + "empirical_mean": 0.2933652698993683, + "empirical_std": 0.3458337187767029, + "model_mean": 0.20400212705135345, + "mae": 0.18654125928878784, + "normalized_mae": 0.5393958112257798, + "spearman": 0.476080388207288 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.4175015687942505, + "empirical_std": 0.28455883264541626, + "model_mean": 0.30266672372817993, + "mae": 0.1718638390302658, + "normalized_mae": 0.6039659265977602, + "spearman": 0.5047953671488737 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.559726893901825, + "variance_rmse_in_latent_var": 0.4822166860103607, + "model_variance_ratio": 1.2633565664291382 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.12852001190185547, + "local_candidate_q_span_mean": 0.24496708810329437, + "data_action_best_of_8_rate": 0.1875 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.09705246984958649, + "local_candidate_q_span_mean": 0.18087324500083923, + "data_action_best_of_8_rate": 0.21875 + } + }, + "H100_g0.990000": { + "horizon": 100.0, + "gamma": 0.9900000095367432, + "primary_reward_expectation": { + "empirical_mean": 0.34922701120376587, + "empirical_std": 0.34182673692703247, + "model_mean": 0.33625495433807373, + "mae": 0.14780008792877197, + "normalized_mae": 0.43238305247117603, + "spearman": 0.6210401025453213 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.4634796380996704, + "empirical_std": 0.28095051646232605, + "model_mean": 0.4298475384712219, + "mae": 0.1264476329088211, + "normalized_mae": 0.45007083276096077, + "spearman": 0.650739333455411 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.4105582535266876, + "variance_rmse_in_latent_var": 0.45037516951560974, + "model_variance_ratio": 1.058014154434204 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.1747567355632782, + "local_candidate_q_span_mean": 0.3481898605823517, + "data_action_best_of_8_rate": 0.2265625 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.1564963161945343, + "local_candidate_q_span_mean": 0.28597354888916016, + "data_action_best_of_8_rate": 0.3046875 + } + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_glegacy_logh10_100.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_glegacy_logh10_100.json new file mode 100644 index 0000000000000000000000000000000000000000..ebfa41ce1b447108a744abddd1f5ef4f16d3238d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_glegacy_logh10_100.json @@ -0,0 +1,352 @@ +{ + "variant": "stateh_ac_glegacy_logh10_100", + "fairness": { + "drop_proprio": true, + "pixels_only": true, + "uses_coordinates": false, + "occupancy_uses_reward_labels": false, + "discount_conditioned": true, + "discount_encoding": "log_horizon_fourier_k4", + "occupancy_definition": "(1-gamma)*sum_{k>=0} gamma^k P(z_{t+k}|s_t,a_t,g)", + "shifted_occupancy": false, + "occupancy_state_condition_feature": "frozen_pixel_encoder_fc0_hidden", + "occupancy_goal_condition_feature": "frozen_pixel_encoder_reward_latent_z", + "occupancy_future_target_feature": "frozen_pixel_encoder_reward_latent_z", + "reward_reader_goal_feature": "frozen_pixel_encoder_reward_latent_z", + "objective": "flow_matching_plus_reward_free_action_contrast_no_td", + "uses_td_or_bootstrap": false, + "uses_world_model_rollout": false, + "external_action_proposer": false + }, + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "future_sampler": "stratified", + "gamma_sampler": "legacy_log_uniform", + "gamma_support": { + "kind": "task_plus_continuous_log_uniform_horizon", + "task_fraction": 0.5, + "aux_horizon_range": [ + 10.000000000000002, + 100.0 + ], + "importance_weighted": false + }, + "gamma_proposal_probe": { + "rows": 32768, + "task_branch_fraction": 0.5, + "gamma_weight_task_min": 1.0, + "gamma_weight_task_max": 1.0, + "gamma_weight_all_mean": 1.0, + "gamma_weight_all_max": 1.0, + "sampled_horizon_quantiles": { + "p10": 15.79015748099713, + "p50": 99.98430509475489, + "p90": 100.00009536752259 + }, + "zero_offset_fraction": 0.231964111328125, + "offset_support": "unshifted_k_ge_0" + }, + "state_key": "state_h", + "state_dim": 256, + "goal_key": "z", + "goal_dim": 8, + "future_target_key": "z", + "future_target_dim": 8, + "reward_reader_goal_key": "z", + "reward_reader_goal_dim": 8, + "discount_conditioned": true, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 443.13, + "final_loss": 0.6555050015449524 + }, + "readers": { + "primary_policy_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_index_d8_symrelu_s0.npz", + "target": "index", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "diagnostic_return_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz", + "target": "gciql", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "readers_used_during_occupancy_training": false + }, + "task_gamma_key": "H100_g0.990000", + "heldout_reward_expectation": { + "empirical_mean": 0.34922701120376587, + "empirical_std": 0.34182673692703247, + "model_mean": 0.33879321813583374, + "mae": 0.1459082067012787, + "normalized_mae": 0.4268484320827857, + "spearman": 0.6432830525544772 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.41233566403388977, + "variance_rmse_in_latent_var": 0.4572445750236511, + "model_variance_ratio": 1.0620123147964478 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.2004842758178711, + "local_candidate_q_span_mean": 0.35160142183303833, + "data_action_best_of_8_rate": 0.375 + }, + "per_horizon": { + "H2_g0.500000": { + "horizon": 2.0, + "gamma": 0.5, + "primary_reward_expectation": { + "empirical_mean": 0.1505288928747177, + "empirical_std": 0.3439146876335144, + "model_mean": 0.2568797767162323, + "mae": 0.10876840353012085, + "normalized_mae": 0.31626565378338145, + "spearman": 0.6949588199385383 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.29565542936325073, + "empirical_std": 0.25984257459640503, + "model_mean": 0.35737505555152893, + "mae": 0.0739419236779213, + "normalized_mae": 0.2845643128065908, + "spearman": 0.7904287218458158 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.6200646758079529, + "variance_rmse_in_latent_var": 0.5959770679473877, + "model_variance_ratio": 27.059383392333984 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.15597155690193176, + "local_candidate_q_span_mean": 0.27788037061691284, + "data_action_best_of_8_rate": 0.390625 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.12228822708129883, + "local_candidate_q_span_mean": 0.24459043145179749, + "data_action_best_of_8_rate": 0.3046875 + } + }, + "H4_g0.750000": { + "horizon": 4.0, + "gamma": 0.75, + "primary_reward_expectation": { + "empirical_mean": 0.15416553616523743, + "empirical_std": 0.34448885917663574, + "model_mean": 0.20793630182743073, + "mae": 0.05837279558181763, + "normalized_mae": 0.16944755694374178, + "spearman": 0.753497746991705 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.3020879626274109, + "empirical_std": 0.2645036578178406, + "model_mean": 0.3328873813152313, + "mae": 0.04040655493736267, + "normalized_mae": 0.15276369056941366, + "spearman": 0.8921500183116645 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.42245444655418396, + "variance_rmse_in_latent_var": 0.4120502769947052, + "model_variance_ratio": 4.881392478942871 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.12102017551660538, + "local_candidate_q_span_mean": 0.22814327478408813, + "data_action_best_of_8_rate": 0.234375 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.10947440564632416, + "local_candidate_q_span_mean": 0.22780051827430725, + "data_action_best_of_8_rate": 0.25 + } + }, + "H8_g0.875000": { + "horizon": 8.0, + "gamma": 0.875, + "primary_reward_expectation": { + "empirical_mean": 0.16398364305496216, + "empirical_std": 0.3444366157054901, + "model_mean": 0.17088159918785095, + "mae": 0.02368861809372902, + "normalized_mae": 0.06877497052747704, + "spearman": 0.7383320362570958 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.31232064962387085, + "empirical_std": 0.27165499329566956, + "model_mean": 0.31441283226013184, + "mae": 0.021252941340208054, + "normalized_mae": 0.07823504763292288, + "spearman": 0.9657228529573338 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.1945888102054596, + "variance_rmse_in_latent_var": 0.20684069395065308, + "model_variance_ratio": 1.1678781509399414 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.10370229184627533, + "local_candidate_q_span_mean": 0.1945350468158722, + "data_action_best_of_8_rate": 0.140625 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.10155822336673737, + "local_candidate_q_span_mean": 0.21938303112983704, + "data_action_best_of_8_rate": 0.171875 + } + }, + "H16_g0.937500": { + "horizon": 16.0, + "gamma": 0.9375, + "primary_reward_expectation": { + "empirical_mean": 0.1852213740348816, + "empirical_std": 0.3457781672477722, + "model_mean": 0.19702869653701782, + "mae": 0.041504524648189545, + "normalized_mae": 0.12003223042838587, + "spearman": 0.6590425288408716 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.32881981134414673, + "empirical_std": 0.28073397278785706, + "model_mean": 0.3299303948879242, + "mae": 0.03325765207409859, + "normalized_mae": 0.11846678812624677, + "spearman": 0.9122814045046694 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.2553221881389618, + "variance_rmse_in_latent_var": 0.3076637089252472, + "model_variance_ratio": 1.0024458169937134 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.11642727255821228, + "local_candidate_q_span_mean": 0.22116078436374664, + "data_action_best_of_8_rate": 0.1953125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.11156242340803146, + "local_candidate_q_span_mean": 0.2287149727344513, + "data_action_best_of_8_rate": 0.1953125 + } + }, + "H32_g0.968750": { + "horizon": 32.0, + "gamma": 0.96875, + "primary_reward_expectation": { + "empirical_mean": 0.2248375117778778, + "empirical_std": 0.348341166973114, + "model_mean": 0.2374127209186554, + "mae": 0.07656723260879517, + "normalized_mae": 0.21980529397119705, + "spearman": 0.5870433528657754 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.36093538999557495, + "empirical_std": 0.28592631220817566, + "model_mean": 0.35783177614212036, + "mae": 0.06591176986694336, + "normalized_mae": 0.2305201272240894, + "spearman": 0.7872928492950009 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.337777316570282, + "variance_rmse_in_latent_var": 0.38457542657852173, + "model_variance_ratio": 1.045487880706787 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.14369167387485504, + "local_candidate_q_span_mean": 0.2633611857891083, + "data_action_best_of_8_rate": 0.25 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.12475582957267761, + "local_candidate_q_span_mean": 0.24461635947227478, + "data_action_best_of_8_rate": 0.2578125 + } + }, + "H64_g0.984375": { + "horizon": 64.0, + "gamma": 0.984375, + "primary_reward_expectation": { + "empirical_mean": 0.2933652698993683, + "empirical_std": 0.3458337187767029, + "model_mean": 0.30334892868995667, + "mae": 0.12085136771202087, + "normalized_mae": 0.34944934848892484, + "spearman": 0.6252460629921259 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.4175015687942505, + "empirical_std": 0.28455883264541626, + "model_mean": 0.4009268581867218, + "mae": 0.10244569182395935, + "normalized_mae": 0.36001585637517397, + "spearman": 0.6871566562900567 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.3962457478046417, + "variance_rmse_in_latent_var": 0.43808427453041077, + "model_variance_ratio": 1.044101595878601 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.17982429265975952, + "local_candidate_q_span_mean": 0.319602370262146, + "data_action_best_of_8_rate": 0.3671875 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.1458255797624588, + "local_candidate_q_span_mean": 0.2752276659011841, + "data_action_best_of_8_rate": 0.359375 + } + }, + "H100_g0.990000": { + "horizon": 100.0, + "gamma": 0.9900000095367432, + "primary_reward_expectation": { + "empirical_mean": 0.34922701120376587, + "empirical_std": 0.34182673692703247, + "model_mean": 0.33879321813583374, + "mae": 0.1459082067012787, + "normalized_mae": 0.4268484320827857, + "spearman": 0.6432830525544772 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.4634796380996704, + "empirical_std": 0.28095051646232605, + "model_mean": 0.42642590403556824, + "mae": 0.1276271641254425, + "normalized_mae": 0.4542691920716103, + "spearman": 0.6708249404870903 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.41233566403388977, + "variance_rmse_in_latent_var": 0.4572445750236511, + "model_variance_ratio": 1.0620123147964478 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.2004842758178711, + "local_candidate_q_span_mean": 0.35160142183303833, + "data_action_best_of_8_rate": 0.375 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.15511062741279602, + "local_candidate_q_span_mean": 0.29430413246154785, + "data_action_best_of_8_rate": 0.3828125 + } + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gshortiw_h2_64.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gshortiw_h2_64.json new file mode 100644 index 0000000000000000000000000000000000000000..3308799a8423f99712a8b7bdda03759cf3dbdf5d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gshortiw_h2_64.json @@ -0,0 +1,389 @@ +{ + "variant": "stateh_ac_gshortiw_h2_64", + "fairness": { + "drop_proprio": true, + "pixels_only": true, + "uses_coordinates": false, + "occupancy_uses_reward_labels": false, + "discount_conditioned": true, + "discount_encoding": "log_horizon_fourier_k4", + "occupancy_definition": "(1-gamma)*sum_{k>=0} gamma^k P(z_{t+k}|s_t,a_t,g)", + "shifted_occupancy": false, + "occupancy_state_condition_feature": "frozen_pixel_encoder_fc0_hidden", + "occupancy_goal_condition_feature": "frozen_pixel_encoder_reward_latent_z", + "occupancy_future_target_feature": "frozen_pixel_encoder_reward_latent_z", + "reward_reader_goal_feature": "frozen_pixel_encoder_reward_latent_z", + "objective": "flow_matching_plus_reward_free_action_contrast_no_td", + "uses_td_or_bootstrap": false, + "uses_world_model_rollout": false, + "external_action_proposer": false + }, + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "future_sampler": "stratified", + "gamma_sampler": "short_iw", + "gamma_support": { + "kind": "task_plus_discrete_auxiliary", + "task_fraction": 0.5, + "aux_horizons": [ + 2.0, + 4.0, + 8.0, + 16.0, + 32.0, + 64.0 + ], + "aux_gammas": [ + 0.5, + 0.75, + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "aux_proposal_probabilities": [ + 0.5079365079365079, + 0.25396825396825395, + 0.12698412698412698, + 0.06349206349206349, + 0.031746031746031744, + 0.015873015873015872 + ], + "importance_weighted": true, + "importance_target": "uniform_auxiliary_bins" + }, + "gamma_proposal_probe": { + "rows": 32768, + "task_branch_fraction": 0.5, + "gamma_weight_task_min": 1.0, + "gamma_weight_task_max": 1.0, + "gamma_weight_all_mean": 0.993769645690918, + "gamma_weight_all_max": 10.499999046325684, + "sampled_horizon_quantiles": { + "p10": 2.0, + "p50": 82.0000476837613, + "p90": 100.00009536752259 + }, + "zero_offset_fraction": 0.310394287109375, + "offset_support": "unshifted_k_ge_0", + "aux_bin_counts": { + "H2": 8262, + "H4": 4238, + "H8": 2095, + "H16": 1034, + "H32": 515, + "H64": 240 + }, + "importance_weighted_aux_bin_mass": { + "H2": 0.16755223274230957, + "H4": 0.17189212143421173, + "H8": 0.16994525492191315, + "H16": 0.16775502264499664, + "H32": 0.16710606217384338, + "H64": 0.1557493507862091 + } + }, + "state_key": "state_h", + "state_dim": 256, + "goal_key": "z", + "goal_dim": 8, + "future_target_key": "z", + "future_target_dim": 8, + "reward_reader_goal_key": "z", + "reward_reader_goal_dim": 8, + "discount_conditioned": true, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 446.81, + "final_loss": 0.5894385576248169 + }, + "readers": { + "primary_policy_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_index_d8_symrelu_s0.npz", + "target": "index", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "diagnostic_return_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz", + "target": "gciql", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "readers_used_during_occupancy_training": false + }, + "task_gamma_key": "H100_g0.990000", + "heldout_reward_expectation": { + "empirical_mean": 0.34922516345977783, + "empirical_std": 0.3418257534503937, + "model_mean": 0.3401782512664795, + "mae": 0.14154976606369019, + "normalized_mae": 0.4140991854325924, + "spearman": 0.6336179271195751 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4173930883407593, + "variance_rmse_in_latent_var": 0.4608377516269684, + "model_variance_ratio": 1.0617963075637817 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.1877017319202423, + "local_candidate_q_span_mean": 0.3408706784248352, + "data_action_best_of_8_rate": 0.328125 + }, + "per_horizon": { + "H2_g0.500000": { + "horizon": 2.0, + "gamma": 0.5, + "primary_reward_expectation": { + "empirical_mean": 0.1505262553691864, + "empirical_std": 0.3439119756221771, + "model_mean": 0.14837008714675903, + "mae": 0.003612884785979986, + "normalized_mae": 0.010505260188872032, + "spearman": 0.9312740588144236 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.2956721782684326, + "empirical_std": 0.2598372995853424, + "model_mean": 0.2948698401451111, + "mae": 0.00642991391941905, + "normalized_mae": 0.024745923428546, + "spearman": 0.9960172129646585 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.060109831392765045, + "variance_rmse_in_latent_var": 0.03575676307082176, + "model_variance_ratio": 0.9154831767082214 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.07860149443149567, + "local_candidate_q_span_mean": 0.18584556877613068, + "data_action_best_of_8_rate": 0.09375 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.09611685574054718, + "local_candidate_q_span_mean": 0.2032480388879776, + "data_action_best_of_8_rate": 0.15625 + } + }, + "H4_g0.750000": { + "horizon": 4.0, + "gamma": 0.75, + "primary_reward_expectation": { + "empirical_mean": 0.15416258573532104, + "empirical_std": 0.34448641538619995, + "model_mean": 0.15223079919815063, + "mae": 0.0064821308478713036, + "normalized_mae": 0.018816796710558987, + "spearman": 0.8431774324112147 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.30210447311401367, + "empirical_std": 0.2644978165626526, + "model_mean": 0.2990531921386719, + "mae": 0.012314219027757645, + "normalized_mae": 0.04655697800378904, + "spearman": 0.9873935634499176 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.10477057844400406, + "variance_rmse_in_latent_var": 0.09611082822084427, + "model_variance_ratio": 0.9220783710479736 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.07567335665225983, + "local_candidate_q_span_mean": 0.18592578172683716, + "data_action_best_of_8_rate": 0.0546875 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.09549642354249954, + "local_candidate_q_span_mean": 0.2055339366197586, + "data_action_best_of_8_rate": 0.171875 + } + }, + "H8_g0.875000": { + "horizon": 8.0, + "gamma": 0.875, + "primary_reward_expectation": { + "empirical_mean": 0.16398070752620697, + "empirical_std": 0.34443414211273193, + "model_mean": 0.1615140587091446, + "mae": 0.016056597232818604, + "normalized_mae": 0.04661732177399342, + "spearman": 0.7431274034059696 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.3123367130756378, + "empirical_std": 0.27164915204048157, + "model_mean": 0.3054022789001465, + "mae": 0.01955779269337654, + "normalized_mae": 0.07199651663356567, + "spearman": 0.9661291430140999 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.16897505521774292, + "variance_rmse_in_latent_var": 0.1967983990907669, + "model_variance_ratio": 0.8904042840003967 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.0787656381726265, + "local_candidate_q_span_mean": 0.19570311903953552, + "data_action_best_of_8_rate": 0.0859375 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.09630809724330902, + "local_candidate_q_span_mean": 0.2129148542881012, + "data_action_best_of_8_rate": 0.1328125 + } + }, + "H16_g0.937500": { + "horizon": 16.0, + "gamma": 0.9375, + "primary_reward_expectation": { + "empirical_mean": 0.18521885573863983, + "empirical_std": 0.3457758128643036, + "model_mean": 0.18791230022907257, + "mae": 0.03987734764814377, + "normalized_mae": 0.11532717490506848, + "spearman": 0.674149652078374 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.32883530855178833, + "empirical_std": 0.28072816133499146, + "model_mean": 0.3211142122745514, + "mae": 0.036052726209163666, + "normalized_mae": 0.12842575549854485, + "spearman": 0.9008995605200513 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.2617530822753906, + "variance_rmse_in_latent_var": 0.32704925537109375, + "model_variance_ratio": 1.0174427032470703 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.09758799523115158, + "local_candidate_q_span_mean": 0.21420830488204956, + "data_action_best_of_8_rate": 0.125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.10296157002449036, + "local_candidate_q_span_mean": 0.22091668844223022, + "data_action_best_of_8_rate": 0.1640625 + } + }, + "H32_g0.968750": { + "horizon": 32.0, + "gamma": 0.96875, + "primary_reward_expectation": { + "empirical_mean": 0.2248353660106659, + "empirical_std": 0.34833934903144836, + "model_mean": 0.23518729209899902, + "mae": 0.0754486620426178, + "normalized_mae": 0.21659528919831056, + "spearman": 0.5997070133675151 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.3609498143196106, + "empirical_std": 0.28592050075531006, + "model_mean": 0.3503901958465576, + "mae": 0.06815029680728912, + "normalized_mae": 0.23835400619143415, + "spearman": 0.7807063724592564 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.3455696702003479, + "variance_rmse_in_latent_var": 0.39946186542510986, + "model_variance_ratio": 1.0900236368179321 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.12339513003826141, + "local_candidate_q_span_mean": 0.24908357858657837, + "data_action_best_of_8_rate": 0.2578125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.1162363737821579, + "local_candidate_q_span_mean": 0.2390945553779602, + "data_action_best_of_8_rate": 0.234375 + } + }, + "H64_g0.984375": { + "horizon": 64.0, + "gamma": 0.984375, + "primary_reward_expectation": { + "empirical_mean": 0.2933633327484131, + "empirical_std": 0.3458324670791626, + "model_mean": 0.302315354347229, + "mae": 0.11800991743803024, + "normalized_mae": 0.34123435094084803, + "spearman": 0.6299155374473538 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.41751429438591003, + "empirical_std": 0.28455299139022827, + "model_mean": 0.3926463723182678, + "mae": 0.10566326230764389, + "normalized_mae": 0.3713307029084792, + "spearman": 0.6905157022523347 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.4077112674713135, + "variance_rmse_in_latent_var": 0.45301464200019836, + "model_variance_ratio": 1.0754929780960083 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.1516457498073578, + "local_candidate_q_span_mean": 0.304062157869339, + "data_action_best_of_8_rate": 0.2734375 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.13381201028823853, + "local_candidate_q_span_mean": 0.2720354199409485, + "data_action_best_of_8_rate": 0.2890625 + } + }, + "H100_g0.990000": { + "horizon": 100.0, + "gamma": 0.9900000095367432, + "primary_reward_expectation": { + "empirical_mean": 0.34922516345977783, + "empirical_std": 0.3418257534503937, + "model_mean": 0.3401782512664795, + "mae": 0.14154976606369019, + "normalized_mae": 0.4140991854325924, + "spearman": 0.6336179271195751 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.463491290807724, + "empirical_std": 0.2809446454048157, + "model_mean": 0.41907042264938354, + "mae": 0.1306774616241455, + "normalized_mae": 0.465135975223344, + "spearman": 0.6640152902398828 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.4173930883407593, + "variance_rmse_in_latent_var": 0.4608377516269684, + "model_variance_ratio": 1.0617963075637817 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.1877017319202423, + "local_candidate_q_span_mean": 0.3408706784248352, + "data_action_best_of_8_rate": 0.328125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.16704705357551575, + "local_candidate_q_span_mean": 0.3062232732772827, + "data_action_best_of_8_rate": 0.390625 + } + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gstrat_h2_64.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gstrat_h2_64.json new file mode 100644 index 0000000000000000000000000000000000000000..3b0c753d7aaf49de6708014108a10f66aae513f3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_horizon_priority/stateh_ac_gstrat_h2_64.json @@ -0,0 +1,381 @@ +{ + "variant": "stateh_ac_gstrat_h2_64", + "fairness": { + "drop_proprio": true, + "pixels_only": true, + "uses_coordinates": false, + "occupancy_uses_reward_labels": false, + "discount_conditioned": true, + "discount_encoding": "log_horizon_fourier_k4", + "occupancy_definition": "(1-gamma)*sum_{k>=0} gamma^k P(z_{t+k}|s_t,a_t,g)", + "shifted_occupancy": false, + "occupancy_state_condition_feature": "frozen_pixel_encoder_fc0_hidden", + "occupancy_goal_condition_feature": "frozen_pixel_encoder_reward_latent_z", + "occupancy_future_target_feature": "frozen_pixel_encoder_reward_latent_z", + "reward_reader_goal_feature": "frozen_pixel_encoder_reward_latent_z", + "objective": "flow_matching_plus_reward_free_action_contrast_no_td", + "uses_td_or_bootstrap": false, + "uses_world_model_rollout": false, + "external_action_proposer": false + }, + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "future_sampler": "stratified", + "gamma_sampler": "stratified_bins", + "gamma_support": { + "kind": "task_plus_discrete_auxiliary", + "task_fraction": 0.5, + "aux_horizons": [ + 2.0, + 4.0, + 8.0, + 16.0, + 32.0, + 64.0 + ], + "aux_gammas": [ + 0.5, + 0.75, + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "aux_proposal_probabilities": [ + 0.16666666666666666, + 0.16666666666666666, + 0.16666666666666666, + 0.16666666666666666, + 0.16666666666666666, + 0.16666666666666666 + ], + "importance_weighted": false, + "importance_target": null + }, + "gamma_proposal_probe": { + "rows": 32768, + "task_branch_fraction": 0.5, + "gamma_weight_task_min": 1.0, + "gamma_weight_task_max": 1.0, + "gamma_weight_all_mean": 1.0, + "gamma_weight_all_max": 1.0, + "sampled_horizon_quantiles": { + "p10": 4.0, + "p50": 82.0000476837613, + "p90": 100.00009536752259 + }, + "zero_offset_fraction": 0.264984130859375, + "offset_support": "unshifted_k_ge_0", + "aux_bin_counts": { + "H2": 2736, + "H4": 2736, + "H8": 2736, + "H16": 2736, + "H32": 2720, + "H64": 2720 + } + }, + "state_key": "state_h", + "state_dim": 256, + "goal_key": "z", + "goal_dim": 8, + "future_target_key": "z", + "future_target_dim": 8, + "reward_reader_goal_key": "z", + "reward_reader_goal_dim": 8, + "discount_conditioned": true, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 443.55, + "final_loss": 0.5921785831451416 + }, + "readers": { + "primary_policy_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_index_d8_symrelu_s0.npz", + "target": "index", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "diagnostic_return_readout": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-horizon-priority/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret.npz", + "target": "gciql", + "features": "symmetric", + "activation": "relu", + "zdim": 8 + }, + "readers_used_during_occupancy_training": false + }, + "task_gamma_key": "H100_g0.990000", + "heldout_reward_expectation": { + "empirical_mean": 0.34922701120376587, + "empirical_std": 0.34182673692703247, + "model_mean": 0.3321167826652527, + "mae": 0.1431807577610016, + "normalized_mae": 0.4188693928631026, + "spearman": 0.6605932979307819 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.41563543677330017, + "variance_rmse_in_latent_var": 0.4597315490245819, + "model_variance_ratio": 1.060652494430542 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.20158684253692627, + "local_candidate_q_span_mean": 0.34335052967071533, + "data_action_best_of_8_rate": 0.375 + }, + "per_horizon": { + "H2_g0.500000": { + "horizon": 2.0, + "gamma": 0.5, + "primary_reward_expectation": { + "empirical_mean": 0.1505288928747177, + "empirical_std": 0.3439146876335144, + "model_mean": 0.14939570426940918, + "mae": 0.0032276627607643604, + "normalized_mae": 0.009385068090502295, + "spearman": 0.9365177060917017 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.29565542936325073, + "empirical_std": 0.25984257459640503, + "model_mean": 0.29457980394363403, + "mae": 0.006275509018450975, + "normalized_mae": 0.024151196270273557, + "spearman": 0.9924636055667461 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.06025809794664383, + "variance_rmse_in_latent_var": 0.0399111732840538, + "model_variance_ratio": 0.9445528388023376 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.08723265677690506, + "local_candidate_q_span_mean": 0.17531678080558777, + "data_action_best_of_8_rate": 0.0703125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.08592253923416138, + "local_candidate_q_span_mean": 0.1925496757030487, + "data_action_best_of_8_rate": 0.1328125 + } + }, + "H4_g0.750000": { + "horizon": 4.0, + "gamma": 0.75, + "primary_reward_expectation": { + "empirical_mean": 0.15416553616523743, + "empirical_std": 0.34448885917663574, + "model_mean": 0.152706116437912, + "mae": 0.006834795698523521, + "normalized_mae": 0.019840396914023273, + "spearman": 0.8445402498380157 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.3020879626274109, + "empirical_std": 0.2645036578178406, + "model_mean": 0.298951655626297, + "mae": 0.011945635080337524, + "normalized_mae": 0.045162457029476286, + "spearman": 0.983782732100348 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.10475967079401016, + "variance_rmse_in_latent_var": 0.09606234729290009, + "model_variance_ratio": 0.8965368270874023 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.09324441105127335, + "local_candidate_q_span_mean": 0.1768570840358734, + "data_action_best_of_8_rate": 0.078125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.09089930355548859, + "local_candidate_q_span_mean": 0.19997601211071014, + "data_action_best_of_8_rate": 0.1484375 + } + }, + "H8_g0.875000": { + "horizon": 8.0, + "gamma": 0.875, + "primary_reward_expectation": { + "empirical_mean": 0.16398364305496216, + "empirical_std": 0.3444366157054901, + "model_mean": 0.1631593108177185, + "mae": 0.015388590283691883, + "normalized_mae": 0.044677567894958845, + "spearman": 0.7313964933162425 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.31232064962387085, + "empirical_std": 0.27165499329566956, + "model_mean": 0.30522894859313965, + "mae": 0.019798971712589264, + "normalized_mae": 0.07288278220986001, + "spearman": 0.9610133217359457 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.16866593062877655, + "variance_rmse_in_latent_var": 0.19501811265945435, + "model_variance_ratio": 0.9171242713928223 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.10225994884967804, + "local_candidate_q_span_mean": 0.18513110280036926, + "data_action_best_of_8_rate": 0.1171875 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.10018400102853775, + "local_candidate_q_span_mean": 0.2101762890815735, + "data_action_best_of_8_rate": 0.1328125 + } + }, + "H16_g0.937500": { + "horizon": 16.0, + "gamma": 0.9375, + "primary_reward_expectation": { + "empirical_mean": 0.1852213740348816, + "empirical_std": 0.3457781672477722, + "model_mean": 0.1903775930404663, + "mae": 0.037877410650253296, + "normalized_mae": 0.10954251667113414, + "spearman": 0.6550254074345359 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.32881981134414673, + "empirical_std": 0.28073397278785706, + "model_mean": 0.3225141763687134, + "mae": 0.03435814380645752, + "normalized_mae": 0.12238683998684058, + "spearman": 0.9018895348837208 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.255788117647171, + "variance_rmse_in_latent_var": 0.31196826696395874, + "model_variance_ratio": 0.9831319451332092 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.1219872385263443, + "local_candidate_q_span_mean": 0.2138756513595581, + "data_action_best_of_8_rate": 0.1796875 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.11411020904779434, + "local_candidate_q_span_mean": 0.22506816685199738, + "data_action_best_of_8_rate": 0.171875 + } + }, + "H32_g0.968750": { + "horizon": 32.0, + "gamma": 0.96875, + "primary_reward_expectation": { + "empirical_mean": 0.2248375117778778, + "empirical_std": 0.348341166973114, + "model_mean": 0.2323639988899231, + "mae": 0.07506700605154037, + "normalized_mae": 0.21549852032658048, + "spearman": 0.6014809558688884 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.36093538999557495, + "empirical_std": 0.28592631220817566, + "model_mean": 0.3491703271865845, + "mae": 0.06606373190879822, + "normalized_mae": 0.23105159996852231, + "spearman": 0.8016217267899651 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.3442426323890686, + "variance_rmse_in_latent_var": 0.38998329639434814, + "model_variance_ratio": 1.0619302988052368 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.14738769829273224, + "local_candidate_q_span_mean": 0.25527215003967285, + "data_action_best_of_8_rate": 0.3203125 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.1302209198474884, + "local_candidate_q_span_mean": 0.2482670098543167, + "data_action_best_of_8_rate": 0.3203125 + } + }, + "H64_g0.984375": { + "horizon": 64.0, + "gamma": 0.984375, + "primary_reward_expectation": { + "empirical_mean": 0.2933652698993683, + "empirical_std": 0.3458337187767029, + "model_mean": 0.2925824820995331, + "mae": 0.12102405726909637, + "normalized_mae": 0.3499486912299576, + "spearman": 0.6335549807727522 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.4175015687942505, + "empirical_std": 0.28455883264541626, + "model_mean": 0.3907793164253235, + "mae": 0.10595044493675232, + "normalized_mae": 0.37233230102815085, + "spearman": 0.6943268174327046 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.40193402767181396, + "variance_rmse_in_latent_var": 0.4451538026332855, + "model_variance_ratio": 1.048370361328125 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.18237203359603882, + "local_candidate_q_span_mean": 0.30771851539611816, + "data_action_best_of_8_rate": 0.34375 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.15559569001197815, + "local_candidate_q_span_mean": 0.28144168853759766, + "data_action_best_of_8_rate": 0.375 + } + }, + "H100_g0.990000": { + "horizon": 100.0, + "gamma": 0.9900000095367432, + "primary_reward_expectation": { + "empirical_mean": 0.34922701120376587, + "empirical_std": 0.34182673692703247, + "model_mean": 0.3321167826652527, + "mae": 0.1431807577610016, + "normalized_mae": 0.4188693928631026, + "spearman": 0.6605932979307819 + }, + "diagnostic_reward_expectation": { + "empirical_mean": 0.4634796380996704, + "empirical_std": 0.28095051646232605, + "model_mean": 0.41663527488708496, + "mae": 0.12952128052711487, + "normalized_mae": 0.46101100705569614, + "spearman": 0.6746246108771287 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.41563543677330017, + "variance_rmse_in_latent_var": 0.4597315490245819, + "model_variance_ratio": 1.060652494430542 + }, + "primary_action_signal": { + "q_shuffle_abs_delta": 0.20158684253692627, + "local_candidate_q_span_mean": 0.34335052967071533, + "data_action_best_of_8_rate": 0.375 + }, + "diagnostic_action_signal": { + "q_shuffle_abs_delta": 0.1703833043575287, + "local_candidate_q_span_mean": 0.3048660159111023, + "data_action_best_of_8_rate": 0.3984375 + } + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/diff_abs_mlp_h256_l3.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/diff_abs_mlp_h256_l3.json new file mode 100644 index 0000000000000000000000000000000000000000..cb00e5295aaf0dee9c710bb3b0082671ec84fa91 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/diff_abs_mlp_h256_l3.json @@ -0,0 +1,36 @@ +{ + "variant": "diff_abs_mlp_h256_l3", + "training": { + "model": "diffusion", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 3, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 28.96, + "final_loss": 0.1393176019191742 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.3004290461540222, + "mae": 0.20381766557693481, + "normalized_mae": 0.7308044036852536, + "spearman": 0.4355895227740901 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 1.4760786294937134, + "variance_rmse_in_latent_var": 44.364219665527344, + "model_variance_ratio": 29.459264755249023 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.05399538204073906, + "local_candidate_q_span_mean": 0.11625824868679047, + "data_action_best_of_8_rate": 0.09765625 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/diff_delta_mlp_h256_l3.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/diff_delta_mlp_h256_l3.json new file mode 100644 index 0000000000000000000000000000000000000000..60984a7e4db4903f313c1b6a4b1b285b0c762f5d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/diff_delta_mlp_h256_l3.json @@ -0,0 +1,36 @@ +{ + "variant": "diff_delta_mlp_h256_l3", + "training": { + "model": "diffusion", + "target": "delta", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 3, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 30.72, + "final_loss": 0.13746562600135803 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.287575364112854, + "mae": 0.20455814898014069, + "normalized_mae": 0.7334594656514816, + "spearman": 0.4520377946898603 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 3.467923402786255, + "variance_rmse_in_latent_var": 166.387939453125, + "model_variance_ratio": 83.390380859375 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.05857015401124954, + "local_candidate_q_span_mean": 0.13927844166755676, + "data_action_best_of_8_rate": 0.1015625 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4.json new file mode 100644 index 0000000000000000000000000000000000000000..59e4a549d27bdad9170141767840dc265349c573 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 33.0, + "final_loss": 0.5511645078659058 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.4500044584274292, + "mae": 0.14205560088157654, + "normalized_mae": 0.5093516226797528, + "spearman": 0.5365937571526664 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.42908331751823425, + "variance_rmse_in_latent_var": 0.42596057057380676, + "model_variance_ratio": 1.0551716089248657 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.06674842536449432, + "local_candidate_q_span_mean": 0.10970691591501236, + "data_action_best_of_8_rate": 0.09375 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w01.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w01.json new file mode 100644 index 0000000000000000000000000000000000000000..067850cdf7254ca0456e73e209bfe6326954d4aa --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w01.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4_aclocal_w01", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 40.1, + "final_loss": 0.6130852699279785 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.44815897941589355, + "mae": 0.14162519574165344, + "normalized_mae": 0.5078083709172806, + "spearman": 0.5407201304646372 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.42892929911613464, + "variance_rmse_in_latent_var": 0.4261264204978943, + "model_variance_ratio": 1.0557148456573486 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.07317999005317688, + "local_candidate_q_span_mean": 0.21759119629859924, + "data_action_best_of_8_rate": 0.16015625 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05.json new file mode 100644 index 0000000000000000000000000000000000000000..1b3303f1b02dce66bb66b552a58c93661774a986 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4_aclocal_w05", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 42.18, + "final_loss": 0.7083173990249634 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.4370918273925781, + "mae": 0.14555051922798157, + "normalized_mae": 0.5218829295752734, + "spearman": 0.5154898146028838 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4322313368320465, + "variance_rmse_in_latent_var": 0.427173376083374, + "model_variance_ratio": 1.0512315034866333 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.14765915274620056, + "local_candidate_q_span_mean": 0.2621249556541443, + "data_action_best_of_8_rate": 0.4453125 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_s1.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_s1.json new file mode 100644 index 0000000000000000000000000000000000000000..56ff93d51b433cefd707a479881a4d2b06c95e87 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_s1.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4_aclocal_w05_s1", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 38.39, + "final_loss": 0.7127259373664856 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.4566039443016052, + "empirical_std": 0.27353402972221375, + "model_mean": 0.42045021057128906, + "mae": 0.16254886984825134, + "normalized_mae": 0.5942546527513491, + "spearman": 0.45005579079880975 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4301060438156128, + "variance_rmse_in_latent_var": 0.42202475666999817, + "model_variance_ratio": 1.0913528203964233 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.12255652993917465, + "local_candidate_q_span_mean": 0.26573607325553894, + "data_action_best_of_8_rate": 0.5234375 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_s2.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_s2.json new file mode 100644 index 0000000000000000000000000000000000000000..d5096da5da92c198d97df5367f0a1cbda0593dd2 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_s2.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4_aclocal_w05_s2", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 37.03, + "final_loss": 0.710529625415802 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.4636330306529999, + "empirical_std": 0.28558072447776794, + "model_mean": 0.44050008058547974, + "mae": 0.14176154136657715, + "normalized_mae": 0.4963974428799836, + "spearman": 0.6485408560311283 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.39077553153038025, + "variance_rmse_in_latent_var": 0.39657509326934814, + "model_variance_ratio": 1.1314475536346436 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.13359808921813965, + "local_candidate_q_span_mean": 0.2682167887687683, + "data_action_best_of_8_rate": 0.5234375 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_sigma01.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_sigma01.json new file mode 100644 index 0000000000000000000000000000000000000000..b6d0a425a968278572622ef8d59b38633e6cc0b5 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_sigma01.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4_aclocal_w05_sigma01", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 36.88, + "final_loss": 0.9230964183807373 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.44955894351005554, + "mae": 0.14249254763126373, + "normalized_mae": 0.5109183299028164, + "spearman": 0.5314044975967039 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.42884182929992676, + "variance_rmse_in_latent_var": 0.42579224705696106, + "model_variance_ratio": 1.055320143699646 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.06725199520587921, + "local_candidate_q_span_mean": 0.11422349512577057, + "data_action_best_of_8_rate": 0.09765625 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_sigma06.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_sigma06.json new file mode 100644 index 0000000000000000000000000000000000000000..5a2fcf4c98182f8e828522bd709a260b2224760b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_aclocal_w05_sigma06.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4_aclocal_w05_sigma06", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 36.4, + "final_loss": 0.6193126440048218 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.44285649061203003, + "mae": 0.1445794403553009, + "normalized_mae": 0.5184010492658708, + "spearman": 0.5205374513618677 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.43024975061416626, + "variance_rmse_in_latent_var": 0.42656952142715454, + "model_variance_ratio": 1.0522292852401733 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.14605861902236938, + "local_candidate_q_span_mean": 0.27605751156806946, + "data_action_best_of_8_rate": 0.40625 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_acshuf_w01.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_acshuf_w01.json new file mode 100644 index 0000000000000000000000000000000000000000..3874d9ea0251f6076feaa2f6c0e7fd4f55f97790 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_acshuf_w01.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4_acshuf_w01", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 44.65, + "final_loss": 0.6146612167358398 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949740171432495, + "empirical_std": 0.27889499068260193, + "model_mean": 0.4479646682739258, + "mae": 0.1419370174407959, + "normalized_mae": 0.5089263779654191, + "spearman": 0.5346847104600594 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4289490580558777, + "variance_rmse_in_latent_var": 0.4259709417819977, + "model_variance_ratio": 1.0543469190597534 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.08687573671340942, + "local_candidate_q_span_mean": 0.1409420222043991, + "data_action_best_of_8_rate": 0.109375 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_acshuf_w05.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_acshuf_w05.json new file mode 100644 index 0000000000000000000000000000000000000000..e4a8d22cc86830ed1090860c6c21c3047901540a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_abs_mlp_h256_l4_acshuf_w05.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_abs_mlp_h256_l4_acshuf_w05", + "training": { + "model": "flow", + "target": "absolute", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 43.09, + "final_loss": 0.7127178311347961 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.440720796585083, + "mae": 0.14314138889312744, + "normalized_mae": 0.5132448017035824, + "spearman": 0.5390306706340122 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.43054497241973877, + "variance_rmse_in_latent_var": 0.4264831840991974, + "model_variance_ratio": 1.0505110025405884 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.18033333122730255, + "local_candidate_q_span_mean": 0.2592442035675049, + "data_action_best_of_8_rate": 0.22265625 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_mlp_h256_l4.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_mlp_h256_l4.json new file mode 100644 index 0000000000000000000000000000000000000000..f512163472eb6a6261a8301542160bfa52a196bb --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_mlp_h256_l4.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_delta_mlp_h256_l4", + "training": { + "model": "flow", + "target": "delta", + "arch": "mlp", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 30.62, + "final_loss": 0.5346495509147644 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.44697001576423645, + "mae": 0.13987791538238525, + "normalized_mae": 0.5015433586210626, + "spearman": 0.5321276321812771 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4271599054336548, + "variance_rmse_in_latent_var": 0.4227566719055176, + "model_variance_ratio": 1.0439295768737793 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.06816648691892624, + "local_candidate_q_span_mean": 0.10405775904655457, + "data_action_best_of_8_rate": 0.07421875 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4.json new file mode 100644 index 0000000000000000000000000000000000000000..92c0576253ce6be278e77144f38533308e66d576 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_delta_res_h256_l4", + "training": { + "model": "flow", + "target": "delta", + "arch": "residual", + "sampler": "stratified", + "spectrum_lo": 0.0, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 61.3, + "final_loss": 0.5200647115707397 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.44361621141433716, + "mae": 0.14093737304210663, + "normalized_mae": 0.505342128080279, + "spearman": 0.5304088464179446 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4279423952102661, + "variance_rmse_in_latent_var": 0.4214054346084595, + "model_variance_ratio": 1.0467554330825806 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.07030051946640015, + "local_candidate_q_span_mean": 0.111355260014534, + "data_action_best_of_8_rate": 0.0625 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4_spec90.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4_spec90.json new file mode 100644 index 0000000000000000000000000000000000000000..3d9575bfa734fd11822d6a65c50a6ef7daf3eb50 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4_spec90.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_delta_res_h256_l4_spec90", + "training": { + "model": "flow", + "target": "delta", + "arch": "residual", + "sampler": "stratified", + "spectrum_lo": 0.9, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 63.0, + "final_loss": 0.4637031555175781 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.4394247531890869, + "mae": 0.14080965518951416, + "normalized_mae": 0.5048841855911449, + "spearman": 0.5342319466697184 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4279378056526184, + "variance_rmse_in_latent_var": 0.42083561420440674, + "model_variance_ratio": 1.0380284786224365 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.0709124356508255, + "local_candidate_q_span_mean": 0.10485325753688812, + "data_action_best_of_8_rate": 0.05859375 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4_spec90_direct.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4_spec90_direct.json new file mode 100644 index 0000000000000000000000000000000000000000..d42f6c889367a807100e6878981c8cd80e3a78b7 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h256_l4_spec90_direct.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_delta_res_h256_l4_spec90_direct", + "training": { + "model": "flow", + "target": "delta", + "arch": "residual", + "sampler": "direct", + "spectrum_lo": 0.9, + "hidden": 256, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 63.69, + "final_loss": 0.46163320541381836 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.43909895420074463, + "mae": 0.1414492130279541, + "normalized_mae": 0.5071773709410031, + "spearman": 0.5258397230487525 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.4274734556674957, + "variance_rmse_in_latent_var": 0.4214196503162384, + "model_variance_ratio": 1.0508545637130737 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.0688348039984703, + "local_candidate_q_span_mean": 0.10467901825904846, + "data_action_best_of_8_rate": 0.05859375 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h512_l4_spec90.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h512_l4_spec90.json new file mode 100644 index 0000000000000000000000000000000000000000..bbc4af416c30b3a42850a53fc3511396d1ab5ab0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/occupancy_sweep/flow_delta_res_h512_l4_spec90.json @@ -0,0 +1,36 @@ +{ + "variant": "flow_delta_res_h512_l4_spec90", + "training": { + "model": "flow", + "target": "delta", + "arch": "residual", + "sampler": "stratified", + "spectrum_lo": 0.9, + "hidden": 512, + "layers": 4, + "steps": 50000, + "batch": 2048, + "train_episodes": 900, + "holdout_episodes": 100, + "wall_sec": 87.65, + "final_loss": 0.4570941925048828 + }, + "heldout_reward_expectation": { + "empirical_mean": 0.44949719309806824, + "empirical_std": 0.27889496088027954, + "model_mean": 0.4495142102241516, + "mae": 0.14150477945804596, + "normalized_mae": 0.507376608782793, + "spearman": 0.5284440089265278 + }, + "heldout_future_moments": { + "mean_rmse_in_latent_sd": 0.42807283997535706, + "variance_rmse_in_latent_var": 0.4235745966434479, + "model_variance_ratio": 1.0531851053237915 + }, + "heldout_action_signal": { + "q_shuffle_abs_delta": 0.0737987756729126, + "local_candidate_q_span_mean": 0.11406267434358597, + "data_action_best_of_8_rate": 0.0859375 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/rdec_indexd4_diagmetric_official_goal_falsification.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/rdec_indexd4_diagmetric_official_goal_falsification.json new file mode 100644 index 0000000000000000000000000000000000000000..a40a75c08756191d3c1c64d79941297a11c16988 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/rdec_indexd4_diagmetric_official_goal_falsification.json @@ -0,0 +1,339 @@ +{ + "audit": "visual_reward_reader_semantic_invariance", + "schema_version": 1, + "strictly_pixels_and_indices_only": true, + "uses_td_or_bootstrap": false, + "artifacts": { + "latents": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret.npz", + "reward_decoder": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd4_diagmetric.npz", + "reward_decoder_sha256": "9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7", + "latent_arrays_available": [ + "z", + "proprio", + "proprio19", + "actions", + "terminals", + "z_dim", + "sigma_z", + "encoder_npz" + ], + "latent_arrays_read": [ + "z", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd4_diagmetric.npz", + "reader_model": "diag_metric", + "target": "index", + "index_delta": 4, + "neg_gap": 64, + "features": "concat", + "activation": "tanh", + "zdim": 8, + "pixels_only_latents": true, + "frozen_encoder": true, + "uses_coordinates_for_training": false, + "uses_coordinates_for_diagnostics": false, + "uses_reward_arrays": false, + "uses_td_or_bootstrap": false, + "label_source": "trajectory_index_positive_and_far_negative_relabeling", + "metric_formula": "bias-sum(weight*((future-goal)/scale)^2)", + "metric_scale": [ + 0.1212734580039978, + 0.11785601824522018, + 0.14360646903514862, + 0.12027847766876221, + 0.1290542036294937, + 0.11801266670227051, + 0.13187457621097565, + 0.15636976063251495 + ], + "metric_weight": [ + 0.8197049498558044, + 0.5192811489105225, + 2.501105308532715, + 2.897911310195923, + 2.5396385192871094, + 0.5441544055938721, + 1.0393574237823486, + 0.5873745083808899 + ], + "metric_scale_min": 0.11785601824522018, + "metric_scale_max": 0.15636976063251495, + "metric_weight_min": 0.5192811489105225, + "metric_weight_max": 2.897911310195923, + "metric_weight_sum": 11.448527336120605, + "metric_bias": 3.7990050315856934, + "metric_weight_nonnegative": true + } + }, + "primary_pixel_index_metrics": { + "split": { + "episodes_total": 1000, + "episodes_held_out": 50, + "first_held_out_episode": 950, + "first_held_out_row": 950950, + "rows": 10000 + }, + "labels": { + "index_delta": 4, + "negative_gap": 64, + "visual_safe_negative_radius": 2.1892776489257812, + "cross_neighbor_k": 128 + }, + "heldout_index": { + "positive_probability": { + "count": 10000, + "mean": 0.9488585271312447, + "std": 0.11893350574326572, + "p10": 0.9470738708972931, + "median": 0.9769390821456909, + "p90": 0.9780974984169006 + }, + "far_same_episode_probability": { + "count": 10000, + "mean": 0.04891985851649483, + "std": 0.17174263612221158, + "p10": 9.357623589846195e-14, + "median": 8.452177269191452e-08, + "p90": 0.061303384974598925 + }, + "balanced_auc": 0.996255775, + "positive_recall_at_half": 0.9794, + "far_false_positive_rate_at_half": 0.0443 + }, + "cross_episode_visual_substitution": { + "nearest": { + "reader_probability": { + "count": 10000, + "mean": 0.9430661101481004, + "std": 0.12092189098377355, + "p10": 0.9313660979270936, + "median": 0.9728943407535553, + "p90": 0.9772993445396423 + }, + "recall_at_half": 0.9794, + "absolute_change_from_local": { + "count": 10000, + "mean": 0.010423625640184037, + "std": 0.02801907401423843, + "p10": 0.0003518402576446534, + "median": 0.0029396414756774902, + "p90": 0.020750159025192273 + }, + "neighbor_equivalence_probability": { + "count": 10000, + "mean": 0.9733285096347332, + "std": 0.01112019016398362, + "p10": 0.9676816284656524, + "median": 0.9761276245117188, + "p90": 0.9777394533157349 + } + }, + "uniform_top_k": { + "reader_probability": { + "count": 10000, + "mean": 0.8960661686585012, + "std": 0.1725461949636339, + "p10": 0.7841723322868347, + "median": 0.9552823603153229, + "p90": 0.9735866606235504 + }, + "recall_at_half": 0.9541, + "absolute_change_from_local": { + "count": 10000, + "mean": 0.06218539325071324, + "std": 0.12361044776400334, + "p10": 0.0032848000526428224, + "median": 0.020179688930511475, + "p90": 0.1473862648010254 + }, + "neighbor_equivalence_probability": { + "count": 10000, + "mean": 0.9353118055151892, + "std": 0.08984732435743545, + "p10": 0.8931872427463532, + "median": 0.9595708847045898, + "p90": 0.9738853096961975 + } + } + }, + "safe_cross_episode_negatives": { + "probability": { + "count": 10000, + "mean": 0.00537873551580449, + "std": 0.03266925695484774, + "p10": 9.357623589846195e-14, + "median": 1.7920523731618232e-08, + "p90": 0.002818009606562558 + }, + "false_positive_rate_at_half": 0.0008, + "positive_vs_safe_auc": 0.99950282 + }, + "pair_order_symmetry": { + "absolute_probability_error": { + "count": 10000, + "mean": 0.0, + "std": 0.0, + "p10": 0.0, + "median": 0.0, + "p90": 0.0 + }, + "max_absolute_probability_error": 0.0 + } + }, + "selection_gate": { + "heldout_index_auc_at_least_0_95": true, + "cross_spectrum_recall_at_least_0_80": true, + "cross_spectrum_median_change_at_most_0_10": true, + "safe_negative_fpr_at_most_0_05": true, + "symmetry_max_error_at_most_1e_6": true, + "pass": true, + "permitted_for_recipe_selection": true, + "task_ids_used": false, + "coordinates_used": false + }, + "official_goal_falsification": { + "run": true, + "permitted_for_recipe_selection": false, + "must_run_only_after_recipe_is_frozen": true, + "metrics": { + "cache": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/visual_cube_official_goal_pixels_reader_9ab338b.npz", + "schema_version": 1, + "env_id": "visual-cube-single-play-v0", + "source": "reset_info_goal_actor_input", + "sha256": "0fb94965bacdc0c7c048c09ca3c6f0b9257595837eb2701c9929b2076d6c0001", + "uses_task_coordinates": false, + "contains_privileged_state": false, + "permitted_for_training": false, + "task_ids": [ + 1, + 2, + 3, + 4, + 5 + ], + "variants": 160, + "reset_seed_min": 100918, + "reset_seed_max": 500949 + }, + "encoder": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz", + "zdim": 8 + }, + "same_task_arm_nuisance": { + "probability": { + "count": 2480, + "mean": 0.8867954678582817, + "std": 0.1912227324590445, + "p10": 0.7018439888954162, + "median": 0.9617991745471954, + "p90": 0.9757795989513397 + }, + "recall_at_half": 0.9366935483870967, + "minimum_per_task_recall_at_half": 0.8245967741935484, + "per_task": { + "1": { + "probability": { + "count": 496, + "mean": 0.8610896957918979, + "std": 0.2196364116565264, + "p10": 0.6013102829456329, + "median": 0.9541253745555878, + "p90": 0.976114809513092 + }, + "recall_at_half": 0.9133064516129032 + }, + "2": { + "probability": { + "count": 496, + "mean": 0.9533424120877059, + "std": 0.06431481819511486, + "p10": 0.9472377002239227, + "median": 0.9692553281784058, + "p90": 0.9761082530021667 + }, + "recall_at_half": 0.9979838709677419 + }, + "3": { + "probability": { + "count": 496, + "mean": 0.7894852187732355, + "std": 0.29336999951472276, + "p10": 0.2055431455373764, + "median": 0.9531015753746033, + "p90": 0.9752497971057892 + }, + "recall_at_half": 0.8245967741935484 + }, + "4": { + "probability": { + "count": 496, + "mean": 0.953079123530657, + "std": 0.030834744178347438, + "p10": 0.918055534362793, + "median": 0.9656547904014587, + "p90": 0.9763265550136566 + }, + "recall_at_half": 1.0 + }, + "5": { + "probability": { + "count": 496, + "mean": 0.8769808891079118, + "std": 0.1561696634136741, + "p10": 0.6963017284870148, + "median": 0.9394759833812714, + "p90": 0.974140465259552 + }, + "recall_at_half": 0.9475806451612904 + } + } + }, + "different_task": { + "probability": { + "count": 10240, + "mean": 0.02475387043008933, + "std": 0.08008591244621441, + "p10": 3.0326013835541023e-12, + "median": 6.735456054229871e-06, + "p90": 0.07114792689681064 + }, + "false_positive_rate_at_half": 0.00791015625, + "same_vs_different_auc": 0.9960105846774193 + }, + "heldout_dataset_visual_neighbors": { + "k": 128, + "probability": { + "count": 20480, + "mean": 0.924978154996279, + "std": 0.09965960436350056, + "p10": 0.8695835828781128, + "median": 0.9543840885162354, + "p90": 0.9712518930435181 + }, + "recall_at_half": 0.982470703125, + "safe_negative_probability": { + "count": 20480, + "mean": 0.009614900328063282, + "std": 0.04723415117087879, + "p10": 9.357623589846195e-14, + "median": 1.51390302960408e-07, + "p90": 0.008105766866356228 + }, + "safe_negative_false_positive_rate_at_half": 0.002001953125 + } + }, + "gate": { + "same_task_recall_at_least_0_90": true, + "minimum_task_recall_at_least_0_80": true, + "different_task_fpr_at_most_0_05": true, + "same_vs_different_auc_at_least_0_98": true, + "dataset_neighbor_recall_at_least_0_80": true, + "dataset_safe_negative_fpr_at_most_0_05": true, + "pass": true + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/rdec_indexd4_diagmetric_pixel_semantics.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/rdec_indexd4_diagmetric_pixel_semantics.json new file mode 100644 index 0000000000000000000000000000000000000000..ddb1b05c5f2d3f144c4d417f168167347aa46458 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/rdec_indexd4_diagmetric_pixel_semantics.json @@ -0,0 +1,201 @@ +{ + "audit": "visual_reward_reader_semantic_invariance", + "schema_version": 1, + "strictly_pixels_and_indices_only": true, + "uses_td_or_bootstrap": false, + "artifacts": { + "latents": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret.npz", + "reward_decoder": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd4_diagmetric.npz", + "reward_decoder_sha256": "9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7", + "latent_arrays_available": [ + "z", + "proprio", + "proprio19", + "actions", + "terminals", + "z_dim", + "sigma_z", + "encoder_npz" + ], + "latent_arrays_read": [ + "z", + "terminals" + ], + "forbidden_arrays_read": [], + "reader": { + "path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rdec_fair_px_gpred_gciql_z8_w003_gciqlret_indexd4_diagmetric.npz", + "reader_model": "diag_metric", + "target": "index", + "index_delta": 4, + "neg_gap": 64, + "features": "concat", + "activation": "tanh", + "zdim": 8, + "pixels_only_latents": true, + "frozen_encoder": true, + "uses_coordinates_for_training": false, + "uses_coordinates_for_diagnostics": false, + "uses_reward_arrays": false, + "uses_td_or_bootstrap": false, + "label_source": "trajectory_index_positive_and_far_negative_relabeling", + "metric_formula": "bias-sum(weight*((future-goal)/scale)^2)", + "metric_scale": [ + 0.1212734580039978, + 0.11785601824522018, + 0.14360646903514862, + 0.12027847766876221, + 0.1290542036294937, + 0.11801266670227051, + 0.13187457621097565, + 0.15636976063251495 + ], + "metric_weight": [ + 0.8197049498558044, + 0.5192811489105225, + 2.501105308532715, + 2.897911310195923, + 2.5396385192871094, + 0.5441544055938721, + 1.0393574237823486, + 0.5873745083808899 + ], + "metric_scale_min": 0.11785601824522018, + "metric_scale_max": 0.15636976063251495, + "metric_weight_min": 0.5192811489105225, + "metric_weight_max": 2.897911310195923, + "metric_weight_sum": 11.448527336120605, + "metric_bias": 3.7990050315856934, + "metric_weight_nonnegative": true + } + }, + "primary_pixel_index_metrics": { + "split": { + "episodes_total": 1000, + "episodes_held_out": 50, + "first_held_out_episode": 950, + "first_held_out_row": 950950, + "rows": 10000 + }, + "labels": { + "index_delta": 4, + "negative_gap": 64, + "visual_safe_negative_radius": 2.1892776489257812, + "cross_neighbor_k": 128 + }, + "heldout_index": { + "positive_probability": { + "count": 10000, + "mean": 0.9488585271312447, + "std": 0.11893350574326572, + "p10": 0.9470738708972931, + "median": 0.9769390821456909, + "p90": 0.9780974984169006 + }, + "far_same_episode_probability": { + "count": 10000, + "mean": 0.04891985851649483, + "std": 0.17174263612221158, + "p10": 9.357623589846195e-14, + "median": 8.452177269191452e-08, + "p90": 0.061303384974598925 + }, + "balanced_auc": 0.996255775, + "positive_recall_at_half": 0.9794, + "far_false_positive_rate_at_half": 0.0443 + }, + "cross_episode_visual_substitution": { + "nearest": { + "reader_probability": { + "count": 10000, + "mean": 0.9430661101481004, + "std": 0.12092189098377355, + "p10": 0.9313660979270936, + "median": 0.9728943407535553, + "p90": 0.9772993445396423 + }, + "recall_at_half": 0.9794, + "absolute_change_from_local": { + "count": 10000, + "mean": 0.010423625640184037, + "std": 0.02801907401423843, + "p10": 0.0003518402576446534, + "median": 0.0029396414756774902, + "p90": 0.020750159025192273 + }, + "neighbor_equivalence_probability": { + "count": 10000, + "mean": 0.9733285096347332, + "std": 0.01112019016398362, + "p10": 0.9676816284656524, + "median": 0.9761276245117188, + "p90": 0.9777394533157349 + } + }, + "uniform_top_k": { + "reader_probability": { + "count": 10000, + "mean": 0.8960661686585012, + "std": 0.1725461949636339, + "p10": 0.7841723322868347, + "median": 0.9552823603153229, + "p90": 0.9735866606235504 + }, + "recall_at_half": 0.9541, + "absolute_change_from_local": { + "count": 10000, + "mean": 0.06218539325071324, + "std": 0.12361044776400334, + "p10": 0.0032848000526428224, + "median": 0.020179688930511475, + "p90": 0.1473862648010254 + }, + "neighbor_equivalence_probability": { + "count": 10000, + "mean": 0.9353118055151892, + "std": 0.08984732435743545, + "p10": 0.8931872427463532, + "median": 0.9595708847045898, + "p90": 0.9738853096961975 + } + } + }, + "safe_cross_episode_negatives": { + "probability": { + "count": 10000, + "mean": 0.00537873551580449, + "std": 0.03266925695484774, + "p10": 9.357623589846195e-14, + "median": 1.7920523731618232e-08, + "p90": 0.002818009606562558 + }, + "false_positive_rate_at_half": 0.0008, + "positive_vs_safe_auc": 0.99950282 + }, + "pair_order_symmetry": { + "absolute_probability_error": { + "count": 10000, + "mean": 0.0, + "std": 0.0, + "p10": 0.0, + "median": 0.0, + "p90": 0.0 + }, + "max_absolute_probability_error": 0.0 + } + }, + "selection_gate": { + "heldout_index_auc_at_least_0_95": true, + "cross_spectrum_recall_at_least_0_80": true, + "cross_spectrum_median_change_at_most_0_10": true, + "safe_negative_fpr_at_most_0_05": true, + "symmetry_max_error_at_most_1e_6": true, + "pass": true, + "permitted_for_recipe_selection": true, + "task_ids_used": false, + "coordinates_used": false + }, + "official_goal_falsification": { + "run": false, + "permitted_for_recipe_selection": false + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_gcbc_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_gcbc_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..c140cf32991f1589b47491749fc1aa9b80c68711 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_gcbc_s0.json @@ -0,0 +1,41 @@ +{ + "schema_version": 1, + "method": "visual_rich_gcbc", + "env": "visual-cube-single-play-v0", + "seed": 0, + "drop_proprio": true, + "pixels_only": true, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "state_dim": 256, + "actor_goal_dim": 256, + "future_feature": "compact_reward_predictive_z_unused", + "reward_goal_feature": "compact_reward_predictive_z_unused", + "compact_z_dim": 8, + "action_dim": 5, + "goal_sampling": "uniform_future_same_trajectory", + "actor_hidden_dims": [ + 512, + 512, + 512 + ], + "batch_size": 1024, + "learning_rate": 0.0003, + "train_steps": 300000, + "uses_occupancy": false, + "uses_reward": false, + "uses_td": false, + "latent_npz": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-rich-goal/ckpt/latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz", + "pixel_encoder": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-rich-goal/ckpt/pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz", + "eval_episodes": 50, + "success_rate": 0.0, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "checkpoint_step": 300000, + "wall_clock_sec": 812.3 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/gciql_control_300000.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/gciql_control_300000.json new file mode 100644 index 0000000000000000000000000000000000000000..ab4612947e7b611c7029478e79a325056501733f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/gciql_control_300000.json @@ -0,0 +1,105 @@ +{ + "method": "GCIQL", + "env": "visual-cube-single-play-v0", + "checkpoint": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/codex-visual-gciql-audit/ckpt/gciql_visual_control_s0/params_300000.pkl", + "checkpoint_step": 300000, + "episodes_per_task": 50, + "total_episodes": 250, + "success_rate": 0.364, + "per_task": [ + 0.58, + 0.62, + 0.28, + 0.16, + 0.18 + ], + "task_results": { + "task1_horizontal": 0.58, + "task2_vertical1": 0.62, + "task3_vertical2": 0.28, + "task4_diagonal1": 0.16, + "task5_diagonal2": 0.18 + }, + "pixels_only": true, + "drop_proprio": true, + "simulator_state_used": false, + "coordinate_used": false, + "policy_observation": "rendered_pixels_only", + "run_meta": { + "method": "GCIQL", + "purpose": "diagnostic_control_only", + "env": "visual-cube-single-play-v0", + "seed": 0, + "pixels_only": true, + "drop_proprio": true, + "simulator_state_used": false, + "coordinate_used": false, + "observation_shape": [ + 64, + 64, + 3 + ], + "observation_dtype": "uint8", + "action_shape": [ + 5 + ], + "dataset_keys": [ + "actions", + "observations", + "terminals", + "valids" + ], + "excluded_keys": [ + "button_states", + "coordinates", + "qpos", + "qvel" + ], + "reference_root": "/u/zwhong/ogbench_ref/impls", + "reference_sha256": "fe6a895a228506596712f2cf1571c5ffdcd15eb43c0ab31a24e9752f53b738ed", + "config": { + "actor_geom_sample": false, + "actor_hidden_dims": [ + 512, + 512, + 512 + ], + "actor_loss": "ddpgbc", + "actor_p_curgoal": 0.0, + "actor_p_randomgoal": 0.0, + "actor_p_trajgoal": 1.0, + "agent_name": "gciql", + "alpha": 1.0, + "batch_size": 256, + "const_std": true, + "dataset_class": "GCDataset", + "discount": 0.99, + "discrete": false, + "encoder": "impala_small", + "expectile": 0.9, + "frame_stack": null, + "gc_negative": true, + "layer_norm": true, + "lr": 0.0003, + "p_aug": 0.5, + "tau": 0.005, + "value_geom_sample": true, + "value_hidden_dims": [ + 512, + 512, + 512 + ], + "value_p_curgoal": 0.2, + "value_p_randomgoal": 0.3, + "value_p_trajgoal": 0.5 + }, + "train_steps": 300000, + "network_input_contract": { + "critic": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels], then dataset action", + "value": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels]", + "actor": "independent IMPALA-small encoder over channel-concatenated [state RGB pixels, goal RGB pixels]", + "training_augmentation": "with probability 0.5, one shared random-crop offset per row is applied to observation, next observation, value goal, and actor goal" + }, + "rsm_consumes_td_outputs": false + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/occ_diag_gpred_gciql_frozen.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/occ_diag_gpred_gciql_frozen.json new file mode 100644 index 0000000000000000000000000000000000000000..bb7cf96bc66d4043b8554942a45c014c619bfc42 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/occ_diag_gpred_gciql_frozen.json @@ -0,0 +1,40 @@ +{ + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": 256, + "samples_per_condition": 32, + "reward_reader": { + "target": "gciql", + "features": "symmetric", + "activation": "relu" + }, + "reward_expectation": { + "empirical_mean": 0.48142170906066895, + "empirical_std": 0.28829696774482727, + "model_mean": 0.40153980255126953, + "mae": 0.1649778187274933, + "normalized_mae": 0.5722495800702134, + "spearman": 0.5964186598764019 + }, + "future_moments": { + "mean_rmse_in_latent_sd": 0.6095908880233765, + "variance_rmse_in_latent_var": 13.015066146850586, + "model_variance_ratio": 3.4917314052581787 + }, + "denoising": { + "mse": 0.173762708902359, + "action_shuffle_delta": 0.018096651881933212, + "state_shuffle_delta": 0.039207376539707184, + "goal_shuffle_delta": 0.07670160382986069 + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": 0.08087494969367981, + "q_common_noise_zero_abs_delta": 0.05953001230955124, + "local_candidate_q_span_mean": 0.158859983086586, + "data_action_best_of_8_rate": 0.10546875, + "q_action_gradient_norm_mean": 0.3102003335952759, + "q_action_gradient_norm_median": 0.10071074962615967 + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": 0.20186251401901245 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubecomb_recoff.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubecomb_recoff.json new file mode 100644 index 0000000000000000000000000000000000000000..94d1f6bf22121f6d86c07a6bd8f0e1330149c50a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubecomb_recoff.json @@ -0,0 +1,195 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "alpha": 0.3, + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.0, + "latent": true, + "success_rate": 0.592, + "best_sr": 0.6, + "final_last_step": 0.23200000000000004, + "final_best_ckpt": 0.592, + "best_ckpt_periodic_sr": 0.6266666666666667, + "per_task": [ + 0.66, + 0.64, + 0.26, + 0.78, + 0.62 + ], + "curve": [ + [ + 25000, + 0.0 + ], + [ + 50000, + 0.0 + ], + [ + 75000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 125000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 175000, + 0.013333333333333332 + ], + [ + 200000, + 0.06666666666666668 + ], + [ + 225000, + 0.05333333333333333 + ], + [ + 250000, + 0.4133333333333333 + ], + [ + 275000, + 0.2533333333333333 + ], + [ + 300000, + 0.49333333333333335 + ], + [ + 325000, + 0.52 + ], + [ + 350000, + 0.5466666666666666 + ], + [ + 375000, + 0.6 + ], + [ + 400000, + 0.5333333333333333 + ], + [ + 425000, + 0.44000000000000006 + ], + [ + 450000, + 0.4933333333333333 + ], + [ + 475000, + 0.52 + ], + [ + 500000, + 0.36 + ], + [ + 525000, + 0.3733333333333333 + ], + [ + 550000, + 0.49333333333333335 + ], + [ + 575000, + 0.4133333333333334 + ], + [ + 600000, + 0.3466666666666666 + ], + [ + 625000, + 0.5066666666666667 + ], + [ + 650000, + 0.32 + ], + [ + 675000, + 0.31999999999999995 + ], + [ + 700000, + 0.30666666666666664 + ], + [ + 725000, + 0.38666666666666666 + ], + [ + 750000, + 0.29333333333333333 + ], + [ + 775000, + 0.26666666666666666 + ], + [ + 800000, + 0.16 + ], + [ + 825000, + 0.26666666666666666 + ], + [ + 850000, + 0.4133333333333334 + ], + [ + 875000, + 0.27999999999999997 + ], + [ + 900000, + 0.2 + ], + [ + 925000, + 0.13333333333333333 + ], + [ + 950000, + 0.21333333333333332 + ], + [ + 975000, + 0.21333333333333332 + ], + [ + 1000000, + 0.18666666666666668 + ], + [ + 1000000, + 0.23200000000000004 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 14501.0, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubecomb_recon.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubecomb_recon.json new file mode 100644 index 0000000000000000000000000000000000000000..bc0b9de12226fe7adb9b628abbf83a0cd416c8e3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubecomb_recon.json @@ -0,0 +1,79 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "alpha": 0.3, + "gamma": 0.99, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": true, + "success_rate": 0.684, + "best_sr": 0.7466666666666667, + "final_last_step": 0.616, + "final_best_ckpt": 0.684, + "best_ckpt_periodic_sr": 0.7466666666666667, + "per_task": [ + 0.74, + 0.8, + 0.6, + 0.66, + 0.62 + ], + "curve": [ + [ + 25000, + 0.0 + ], + [ + 50000, + 0.0 + ], + [ + 75000, + 0.05333333333333333 + ], + [ + 100000, + 0.0 + ], + [ + 125000, + 0.64 + ], + [ + 150000, + 0.7466666666666667 + ], + [ + 175000, + 0.52 + ], + [ + 200000, + 0.6 + ], + [ + 225000, + 0.5599999999999999 + ], + [ + 250000, + 0.6399999999999999 + ], + [ + 275000, + 0.6666666666666666 + ], + [ + 50000, + 0.616 + ] + ], + "train_steps": 50000, + "wall_clock_sec": 14539.2, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubereconlycal_recoff.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubereconlycal_recoff.json new file mode 100644 index 0000000000000000000000000000000000000000..2c3c4ef5e0025252fe52712e010a3997f989a695 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_cubereconlycal_recoff.json @@ -0,0 +1,195 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "alpha": 0.3, + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.0, + "latent": true, + "success_rate": 0.0, + "best_sr": 0.013333333333333332, + "final_last_step": 0.0, + "final_best_ckpt": 0.0, + "best_ckpt_periodic_sr": 0.013333333333333332, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 25000, + 0.0 + ], + [ + 50000, + 0.0 + ], + [ + 75000, + 0.0 + ], + [ + 100000, + 0.0 + ], + [ + 125000, + 0.0 + ], + [ + 150000, + 0.0 + ], + [ + 175000, + 0.0 + ], + [ + 200000, + 0.0 + ], + [ + 225000, + 0.0 + ], + [ + 250000, + 0.0 + ], + [ + 275000, + 0.0 + ], + [ + 300000, + 0.0 + ], + [ + 325000, + 0.0 + ], + [ + 350000, + 0.0 + ], + [ + 375000, + 0.0 + ], + [ + 400000, + 0.0 + ], + [ + 425000, + 0.0 + ], + [ + 450000, + 0.0 + ], + [ + 475000, + 0.0 + ], + [ + 500000, + 0.0 + ], + [ + 525000, + 0.0 + ], + [ + 550000, + 0.0 + ], + [ + 575000, + 0.0 + ], + [ + 600000, + 0.0 + ], + [ + 625000, + 0.0 + ], + [ + 650000, + 0.0 + ], + [ + 675000, + 0.0 + ], + [ + 700000, + 0.0 + ], + [ + 725000, + 0.0 + ], + [ + 750000, + 0.013333333333333332 + ], + [ + 775000, + 0.0 + ], + [ + 800000, + 0.0 + ], + [ + 825000, + 0.0 + ], + [ + 850000, + 0.0 + ], + [ + 875000, + 0.0 + ], + [ + 900000, + 0.0 + ], + [ + 925000, + 0.0 + ], + [ + 950000, + 0.0 + ], + [ + 975000, + 0.0 + ], + [ + 1000000, + 0.0 + ], + [ + 1000000, + 0.0 + ] + ], + "train_steps": 1000000, + "wall_clock_sec": 13658.2, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_gciqlraw_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_gciqlraw_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..1e0a8fccc7f6a25273c3d97ec2b692557bab04c0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_gciqlraw_s0.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 2155.0, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_gciqlraw_s0_mid110k.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_gciqlraw_s0_mid110k.json new file mode 100644 index 0000000000000000000000000000000000000000..d26882b443b1755c0d794f167b85d3276185679e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_gciqlraw_s0_mid110k.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 974.1, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_warmbc100k_gciqlraw_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_warmbc100k_gciqlraw_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..a650f3f73c80c8c50c7072f10f2551f4beb2dfbc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_warmbc100k_gciqlraw_s0.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 100000, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 2156.2, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_warmbc100k_gciqlraw_s0_mid150k.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_warmbc100k_gciqlraw_s0_mid150k.json new file mode 100644 index 0000000000000000000000000000000000000000..9634898f935132acf3e8f5b61021073938605c30 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_frozenextract_warmbc100k_gciqlraw_s0_mid150k.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 100000, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 1059.2, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_gciqlraw_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_gciqlraw_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..9f80b5703cd8bf559e283bd7f62326a3e63816d8 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_gciqlraw_s0.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 2406.5, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid190k.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid190k.json new file mode 100644 index 0000000000000000000000000000000000000000..a8dffb883bdbb418c29917e50dc82650a49a54a0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid190k.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 1348.0, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_joint_gciqlraw_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_joint_gciqlraw_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..03efd9a2d7ae714a649eaa950c2e780a62aacf15 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_joint_gciqlraw_s0.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "adapter", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 2644.5, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_joint_gciqlraw_s0_mid170k.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_joint_gciqlraw_s0_mid170k.json new file mode 100644 index 0000000000000000000000000000000000000000..56627d7a5d81d5acdddd64960194a773c44be1dd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_aclocal05_joint_gciqlraw_s0_mid170k.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "adapter", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 1383.6, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_gciqlraw_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_gciqlraw_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..899173f20567b7450402c879f53540e259a7b43b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_gciqlraw_s0.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.0, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "shuffle", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 2394.5, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_gciqlraw_s0_mid110k.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_gciqlraw_s0_mid110k.json new file mode 100644 index 0000000000000000000000000000000000000000..777a6b568e8a74534e00bb1bcb26b83ff1f50eef --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_flow_abs_h256l4_gciqlraw_s0_mid110k.json @@ -0,0 +1,32 @@ +{ + "method": "rsm", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "eval_only": true, + "eval_actor": "ema", + "checkpoint_step": 110000, + "eval_episodes_per_task": 50, + "success_rate": 0.0, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] +} diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_frozen_gciql_ddpgbc_raw_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_frozen_gciql_ddpgbc_raw_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..54d1e2b3ade7aa3224160dece6765fbd2f4420b1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_frozen_gciql_ddpgbc_raw_s0.json @@ -0,0 +1,50 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "diffusion", + "occ_hidden": 256, + "occ_layers": 3, + "flow_steps": 25, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 2071.0, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_frozen_gciql_ddpgbc_raw_s0_mid250k.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_frozen_gciql_ddpgbc_raw_s0_mid250k.json new file mode 100644 index 0000000000000000000000000000000000000000..b79e87b065cc299e3e6d986b6048b517b924b9ac --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_frozen_gciql_ddpgbc_raw_s0_mid250k.json @@ -0,0 +1,32 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "occupancy_model": "diffusion", + "occ_hidden": 256, + "occ_layers": 3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "eval_only": true, + "eval_actor": "ema", + "checkpoint_step": 250000, + "eval_episodes_per_task": 50, + "success_rate": 0.0, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] +} diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..7fec7fbe25e0c7368dfec033db7e5163810b0dcd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 2709.5, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid100k.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid100k.json new file mode 100644 index 0000000000000000000000000000000000000000..3bf034b6e30b36a403627d60af11d03b53927fa7 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid100k.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 758.2, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid100k_smoke5.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid100k_smoke5.json new file mode 100644 index 0000000000000000000000000000000000000000..d2012fed46dac83cc533a5e2c81a0c873c33d1ed --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_mid100k_smoke5.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 462.5, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_smoke5.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_smoke5.json new file mode 100644 index 0000000000000000000000000000000000000000..84d44e6b77ecfb610fe4cfacd6a78620b93c7180 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_flow_abs_h256l4_aclocal05_gciqlraw_s0_smoke5.json @@ -0,0 +1,54 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "gamma": 0.99, + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.0, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "readout_kind": "classifier", + "reward_decoder_target": "gciql", + "reward_decoder_features": "symmetric", + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 500000, + "wall_clock_sec": 1946.8, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..4795fb1bdf8f608ab01ecabac349573fdd84e782 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0.json @@ -0,0 +1,68 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "awr_distill", + "alpha": 30.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "distill_actor_goals": false, + "policy_extraction": "supervised_occupancy_q_distillation_awr", + "uses_td_or_bootstrap": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "gamma": 0.99, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.9, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "goal_hidden": true, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "latent_aux_target": null, + "latent_index_delta": null, + "latent_index_neg_gap": null, + "readout_kind": "classifier", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 2, + "reward_decoder_features": "symmetric", + "reward_decoder_logit": false, + "eval_episodes_periodic": 3, + "success_rate": null, + "best_sr": null, + "status": "train_only_complete", + "per_task": [], + "curve": [], + "train_steps": 300000, + "wall_clock_sec": 884.9, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step50000.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step50000.json new file mode 100644 index 0000000000000000000000000000000000000000..02f6ecdb541b4d84edac2f22b6f45e40a836d76b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step50000.json @@ -0,0 +1,115 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "awr_distill", + "alpha": 30.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "distill_actor_goals": false, + "distill_goal_loss_reduction": "value_goals_only", + "policy_extraction": "supervised_occupancy_q_distillation_awr", + "uses_td_or_bootstrap": false, + "occupancy_supervision": "monte_carlo_geometric_futures", + "occupancy_uses_reward_labels": false, + "occupancy_uses_simulator_coordinates": false, + "uses_completion_or_forward_model": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "gamma": 0.99, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "rec_max_depth": 10, + "rec_continuation_probability": 0.0, + "rec_cap_mass": 0.0, + "rec_beta_sample_prob": 0.0, + "recursion_state": null, + "recursion_intermediate_actor": null, + "offpolicy_zero_horizon_boundary_approximation": false, + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.9, + "gamma_sampler": "legacy_log_uniform", + "gamma_task_fraction": 0.5, + "gamma_horizons": null, + "gamma_aux_discounts": null, + "gamma_batch_allocation": "independent_task_vs_log_uniform_aux", + "gamma_task_rows_per_occ_batch": null, + "gamma_beta_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": null, + "gamma_sampling_importance_weighted": false, + "gamma_normalization": "sample_standardized", + "gamma_encoding_lo": 0.9, + "gamma_encoding_hi": 0.99, + "condition_normalizer_probe_size": 20000, + "condition_normalizer_seed": 0, + "condition_normalizer_goal_sampler": "legacy_same_trajectory_geometric", + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "goal_hidden": true, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "occupancy_future_dim": 8, + "reward_reader_dim": 8, + "occupancy_target_standardization": "per_dimension_dataset_mean_std", + "frozen_encoder_fc1_reward_projection": false, + "occupancy_active_future_dims": 8, + "occupancy_constant_future_dims": 0, + "constant_future_masking": false, + "recursive_state_support_projection": null, + "fc1_cached_z_max_abs": null, + "fc1_cached_z_mean_abs": null, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "latent_aux_target": null, + "latent_index_delta": null, + "latent_index_neg_gap": null, + "readout_kind": "classifier", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 2, + "reward_decoder_features": "symmetric", + "reward_decoder_logit": false, + "rdec_samples": 8, + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "checkpoint_step": 50000, + "checkpoint_path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_awr_ag0_s0_step50000.pkl", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 300000, + "wall_clock_sec": 768.1, + "wandb_url": null +} diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..582f58bba4670ed915458849baeaf517e4d6e66c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd2_frozen_ddpg_ag0_s0.json @@ -0,0 +1,68 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc_distill", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "distill_actor_goals": false, + "policy_extraction": "supervised_occupancy_q_distillation_ddpgbc", + "uses_td_or_bootstrap": false, + "critic_target_source": "ema_occupancy_within_2_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "gamma": 0.99, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.9, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "goal_hidden": true, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "latent_aux_target": null, + "latent_index_delta": null, + "latent_index_neg_gap": null, + "readout_kind": "classifier", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 2, + "reward_decoder_features": "symmetric", + "reward_decoder_logit": false, + "eval_episodes_periodic": 3, + "success_rate": null, + "best_sr": null, + "status": "train_only_complete", + "per_task": [], + "curve": [], + "train_steps": 300000, + "wall_clock_sec": 837.4, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0.json new file mode 100644 index 0000000000000000000000000000000000000000..44c167d15104121b21a85b3c7b4c49894a0dd73d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256_goalh256_flow_h256l4_aclocal05_indexd8_frozen_ddpg_ag0_s0.json @@ -0,0 +1,68 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc_distill", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "distill_actor_goals": false, + "policy_extraction": "supervised_occupancy_q_distillation_ddpgbc", + "uses_td_or_bootstrap": false, + "critic_target_source": "ema_occupancy_within_8_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "gamma": 0.99, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.9, + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "latent": true, + "drop_proprio": true, + "goal_hidden": true, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "latent_aux_target": null, + "latent_index_delta": null, + "latent_index_neg_gap": null, + "readout_kind": "classifier", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 8, + "reward_decoder_features": "symmetric", + "reward_decoder_logit": false, + "eval_episodes_periodic": 3, + "success_rate": null, + "best_sr": null, + "status": "train_only_complete", + "per_task": [], + "curve": [], + "train_steps": 300000, + "wall_clock_sec": 895.5, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_visual_rsm_onehop_v2_frozen_local_step30000_official.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_visual_rsm_onehop_v2_frozen_local_step30000_official.json new file mode 100644 index 0000000000000000000000000000000000000000..03bdc85c0f112c4ab90ff41f50094862e40f989f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_visual_rsm_onehop_v2_frozen_local_step30000_official.json @@ -0,0 +1,165 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc_distill", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "distill_actor_goals": true, + "distill_goal_loss_reduction": "mean_value_and_actor_goals", + "distill_actor_actions": true, + "distill_actor_action_local_k": 2, + "distill_actor_action_sigma": 0.3, + "distill_actor_action_pairwise_weight": 1.0, + "distill_actor_action_pointwise_weight": 1.0, + "distill_actor_action_candidate_count": 3, + "distill_actor_action_pairwise_candidate_count": 4, + "distill_actor_action_common_random_numbers": true, + "distill_actor_action_policy": "stop_gradient_current_actor_mode_plus_local_gaussian", + "distill_actor_action_target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "distill_actor_action_composed_occupancy": false, + "distill_actor_action_support_start_step": 0, + "actor_q_gradient_start_step": 0, + "distill_actor_action_loss_reduction": "normalized_point_and_pairwise_then_mean_with_existing_support", + "distill_actor_action_updates_occupancy": false, + "policy_extraction": "supervised_occupancy_q_distillation_ddpgbc", + "uses_td_or_bootstrap": false, + "occupancy_supervision": "monte_carlo_geometric_futures", + "occupancy_uses_reward_labels": false, + "occupancy_uses_simulator_coordinates": false, + "uses_completion_or_forward_model": false, + "critic_target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": false, + "occupancy_gradient_updates_actor": false, + "gamma": 0.99, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "rec_max_depth": 10, + "rec_continuation_probability": 0.0, + "rec_cap_mass": 0.0, + "rec_beta_sample_prob": 0.0, + "recursion_state": null, + "recursion_intermediate_actor": null, + "offpolicy_zero_horizon_boundary_approximation": false, + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.5, + "gamma_sampler": "stratified_bins", + "gamma_task_fraction": 0.5, + "gamma_horizons": [ + 2.0, + 4.0, + 8.0, + 16.0, + 32.0, + 64.0 + ], + "gamma_aux_discounts": [ + 0.5, + 0.75, + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "gamma_batch_allocation": "exact_task_count_balanced_aux_bins_then_shuffle", + "gamma_task_rows_per_occ_batch": 1024, + "gamma_beta_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": [ + 171, + 171, + 171, + 171, + 170, + 170 + ], + "gamma_sampling_importance_weighted": false, + "gamma_normalization": "fixed_fourier_identity", + "gamma_encoding_lo": 0.5, + "gamma_encoding_hi": 0.99, + "condition_normalizer_probe_size": 20000, + "condition_normalizer_seed": 0, + "condition_normalizer_goal_sampler": "gciql_value_goals_20_current_50_trajectory_30_random", + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "local", + "occ_action_negative_sigma": 0.3, + "occ_action_negative_local_k": 0, + "occ_action_negative_candidate_count": 1, + "occ_action_negative_policy": "behavior_action_plus_local_gaussian", + "occ_action_negative_actor_source": null, + "occ_action_negative_support_start_step": null, + "occ_action_negative_actions_stop_gradient": false, + "occ_action_negative_common_random_numbers": true, + "occ_action_negative_updates_actor": false, + "occ_action_negative_counterfactual_target": false, + "occ_action_negative_interpretation": null, + "latent": true, + "drop_proprio": true, + "goal_hidden": true, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "occupancy_future_dim": 8, + "reward_reader_dim": 8, + "occupancy_target_standardization": "per_dimension_dataset_mean_std", + "frozen_encoder_fc1_reward_projection": false, + "occupancy_active_future_dims": 8, + "occupancy_constant_future_dims": 0, + "constant_future_masking": false, + "recursive_state_support_projection": null, + "fc1_cached_z_max_abs": null, + "fc1_cached_z_mean_abs": null, + "latent_update": "frozen", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "latent_aux_target": null, + "latent_index_delta": null, + "latent_index_neg_gap": null, + "latent_reader_model": null, + "latent_index_negative_contract": null, + "readout_kind": "classifier", + "reward_decoder_model": "diag_metric", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 4, + "reward_decoder_features": "concat", + "reward_decoder_logit": false, + "rdec_samples": 16, + "eval_episodes_periodic": 3, + "success_rate": 0.0, + "best_sr": 0.0, + "eval_only": true, + "eval_actor": "ema", + "checkpoint_step": 30000, + "checkpoint_path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_visual_rsm_onehop_v2_frozen_local_s0_step30000_manual.pkl", + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [], + "train_steps": 50000, + "wall_clock_sec": 2684.8, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_visual_rsm_onehop_v2_rich_adapter_actor_local_step30000_official.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_visual_rsm_onehop_v2_rich_adapter_actor_local_step30000_official.json new file mode 100644 index 0000000000000000000000000000000000000000..7b581deed23496ff016c3e0a0520d092cf948bbf --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_fair_visual_rsm_onehop_v2_rich_adapter_actor_local_step30000_official.json @@ -0,0 +1,165 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "actor_loss": "ddpgbc_distill", + "alpha": 1.0, + "expectile": 0.9, + "actor_after": 0, + "adv_norm": false, + "actor_q_transform": "raw", + "distill_actor_goals": true, + "distill_goal_loss_reduction": "mean_value_and_actor_goals", + "distill_actor_actions": true, + "distill_actor_action_local_k": 2, + "distill_actor_action_sigma": 0.3, + "distill_actor_action_pairwise_weight": 1.0, + "distill_actor_action_pointwise_weight": 1.0, + "distill_actor_action_candidate_count": 3, + "distill_actor_action_pairwise_candidate_count": 4, + "distill_actor_action_common_random_numbers": true, + "distill_actor_action_policy": "stop_gradient_current_actor_mode_plus_local_gaussian", + "distill_actor_action_target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "distill_actor_action_composed_occupancy": false, + "distill_actor_action_support_start_step": 0, + "actor_q_gradient_start_step": 0, + "distill_actor_action_loss_reduction": "normalized_point_and_pairwise_then_mean_with_existing_support", + "distill_actor_action_updates_occupancy": false, + "policy_extraction": "supervised_occupancy_q_distillation_ddpgbc", + "uses_td_or_bootstrap": false, + "occupancy_supervision": "monte_carlo_geometric_futures_plus_detached_actor_query_likelihood_ranking", + "occupancy_uses_reward_labels": false, + "occupancy_uses_simulator_coordinates": false, + "uses_completion_or_forward_model": false, + "critic_target_source": "ema_occupancy_within_4_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": true, + "joint_update_semantics": "same_fused_step_occupancy_uses_detached_live_preupdate_actor_queries", + "occupancy_training_policy": "offline_behavior_futures_with_detached_live_actor_query_negatives", + "actor_gradient_updates_occupancy": false, + "occupancy_gradient_updates_actor": false, + "gamma": 0.99, + "discount_conditioned": true, + "discount_feature": "fourier_log_horizon", + "recursion": "off", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "rec_max_depth": 10, + "rec_continuation_probability": 0.0, + "rec_cap_mass": 0.0, + "rec_beta_sample_prob": 0.0, + "recursion_state": null, + "recursion_intermediate_actor": null, + "offpolicy_zero_horizon_boundary_approximation": false, + "elbo_logspace": false, + "elbo_antithetic": false, + "gamma_spectrum_lo": 0.5, + "gamma_sampler": "stratified_bins", + "gamma_task_fraction": 0.5, + "gamma_horizons": [ + 2.0, + 4.0, + 8.0, + 16.0, + 32.0, + 64.0 + ], + "gamma_aux_discounts": [ + 0.5, + 0.75, + 0.875, + 0.9375, + 0.96875, + 0.984375 + ], + "gamma_batch_allocation": "exact_task_count_balanced_aux_bins_then_shuffle", + "gamma_task_rows_per_occ_batch": 1024, + "gamma_beta_rows_per_occ_batch": null, + "gamma_aux_rows_per_occ_batch": [ + 171, + 171, + 171, + 171, + 170, + 170 + ], + "gamma_sampling_importance_weighted": false, + "gamma_normalization": "fixed_fourier_identity", + "gamma_encoding_lo": 0.5, + "gamma_encoding_hi": 0.99, + "condition_normalizer_probe_size": 20000, + "condition_normalizer_seed": 0, + "condition_normalizer_goal_sampler": "gciql_value_goals_20_current_50_trajectory_30_random", + "occupancy_model": "flow", + "occ_hidden": 256, + "occ_layers": 4, + "flow_steps": 25, + "occ_action_contrast_weight": 0.5, + "occ_action_contrast_margin": 0.1, + "occ_action_negative": "actor_local", + "occ_action_negative_sigma": 0.3, + "occ_action_negative_local_k": 2, + "occ_action_negative_candidate_count": 3, + "occ_action_negative_policy": "stop_gradient_live_preupdate_actor_mode_plus_local_gaussian", + "occ_action_negative_actor_source": "live_preupdate_actor", + "occ_action_negative_support_start_step": 0, + "occ_action_negative_actions_stop_gradient": true, + "occ_action_negative_common_random_numbers": true, + "occ_action_negative_updates_actor": false, + "occ_action_negative_counterfactual_target": false, + "occ_action_negative_interpretation": "anti_exploitation_likelihood_ranking_not_counterfactual_occupancy", + "latent": true, + "drop_proprio": true, + "goal_hidden": true, + "state_feature": "joint_encoder_hidden_adapter", + "actor_goal_feature": "joint_encoder_hidden_adapter", + "occupancy_goal_feature": "joint_encoder_hidden_adapter", + "future_feature": "frozen_compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "occupancy_future_dim": 8, + "reward_reader_dim": 8, + "occupancy_target_standardization": "per_dimension_dataset_mean_std", + "frozen_encoder_fc1_reward_projection": false, + "occupancy_active_future_dims": 8, + "occupancy_constant_future_dims": 0, + "constant_future_masking": false, + "recursive_state_support_projection": null, + "fc1_cached_z_max_abs": null, + "fc1_cached_z_mean_abs": null, + "latent_update": "rich_adapter", + "latent_lr": 3e-05, + "latent_hidden": 64, + "latent_goal_weight": 0.1, + "latent_anchor_weight": 0.01, + "latent_aux_target": "index", + "latent_index_delta": 4, + "latent_index_neg_gap": 64, + "latent_reader_model": "diag_metric", + "latent_index_negative_contract": "same_episode_far_only_cross_episode_excluded", + "readout_kind": "classifier", + "reward_decoder_model": "diag_metric", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 4, + "reward_decoder_features": "concat", + "reward_decoder_logit": false, + "rdec_samples": 16, + "eval_episodes_periodic": 3, + "success_rate": 0.012, + "best_sr": 0.012, + "eval_only": true, + "eval_actor": "ema", + "checkpoint_step": 30000, + "checkpoint_path": "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ckpt/rsm_fair_visual_rsm_onehop_v2_rich_adapter_actor_local_s0_step30000_manual.pkl", + "per_task": [ + 0.02, + 0.0, + 0.02, + 0.02, + 0.0 + ], + "curve": [], + "train_steps": 50000, + "wall_clock_sec": 2849.8, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_gpusmoke.json b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_gpusmoke.json new file mode 100644 index 0000000000000000000000000000000000000000..6e0ebe5565f75709456b4272a7fb81e946f7e90d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/rsm_gpusmoke.json @@ -0,0 +1,38 @@ +{ + "method": "rsm", + "readout": "elbo", + "env": "visual-cube-single-play-v0", + "seed": 0, + "alpha": 0.03, + "recursion": "prob", + "rec_after": 100000, + "rec_beta": 0.98, + "rec_guard": "tails", + "gamma_spectrum_lo": 0.95, + "latent": true, + "success_rate": 0.0, + "best_sr": 0.0, + "final_last_step": 0.0, + "final_best_ckpt": 0.0, + "best_ckpt_periodic_sr": 0.0, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "curve": [ + [ + 200, + 0.0 + ], + [ + 200, + 0.0 + ] + ], + "train_steps": 200, + "wall_clock_sec": 653.3, + "wandb_url": null +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/experiments/visual_rsm_fair_training_manifest.tsv b/gen_q_rsm/ogbench_genq/experiments/visual_rsm_fair_training_manifest.tsv new file mode 100644 index 0000000000000000000000000000000000000000..e16d5043a95396198848a2d6492f83953208dcd3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual_rsm_fair_training_manifest.tsv @@ -0,0 +1,19 @@ +pack cell kind latent_update actor_loss alpha gamma beta recursion_state rec_after gamma_horizons gamma_lo actor_action_support occ_hidden beta_mass rationale +nonrec-primary nr_frozen_ddpg_strat_a1 nonrec frozen ddpgbc_distill 1.0 0.99 - - - 2,4,8,16,32,64 0.50 1 256 - frozen latent; stratified horizon curriculum; primary DDPG+BC weight +nonrec-primary nr_frozen_ddpg_legacyhmatch_a1 nonrec frozen ddpgbc_distill 1.0 0.99 - - - 2,4,8,16,32,64 0.50 1 256 - frozen latent; continuous log-horizon control with matched H=2 lower edge +nonrec-primary nr_frozen_awr_strat_a10 nonrec frozen awr_distill 10.0 0.99 - - - 2,4,8,16,32,64 0.50 0 256 - frozen latent; stratified horizon curriculum; AWR extraction +nonrec-primary nr_frozen_awr_legacyhmatch_a10 nonrec frozen awr_distill 10.0 0.99 - - - 2,4,8,16,32,64 0.50 0 256 - frozen latent; continuous log-horizon control with matched H=2 lower edge; AWR extraction +nonrec-primary nr_rich_ddpg_strat_a1 nonrec rich_adapter ddpgbc_distill 1.0 0.99 - - - 2,4,8,16,32,64 0.50 1 256 - joint rich latent adapter; stratified horizon curriculum; primary DDPG+BC weight +nonrec-primary nr_rich_ddpg_legacyhmatch_a1 nonrec rich_adapter ddpgbc_distill 1.0 0.99 - - - 2,4,8,16,32,64 0.50 1 256 - joint rich latent adapter; continuous log-horizon control with matched H=2 lower edge +nonrec-primary nr_rich_awr_strat_a10 nonrec rich_adapter awr_distill 10.0 0.99 - - - 2,4,8,16,32,64 0.50 0 256 - joint rich latent adapter; stratified horizon curriculum; AWR extraction +nonrec-primary nr_rich_awr_legacyhmatch_a10 nonrec rich_adapter awr_distill 10.0 0.99 - - - 2,4,8,16,32,64 0.50 0 256 - joint rich latent adapter; continuous log-horizon control with matched H=2 lower edge; AWR extraction +nonrec-secondary nr_frozen_ddpg_strat_a3 nonrec frozen ddpgbc_distill 3.0 0.99 - - - 2,4,8,16,32,64 0.50 1 256 - frozen latent; stratified horizon curriculum; conservative DDPG+BC weight +nonrec-secondary nr_frozen_ddpg_legacyhmatch_a3 nonrec frozen ddpgbc_distill 3.0 0.99 - - - 2,4,8,16,32,64 0.50 1 256 - frozen latent; matched continuous log-horizon control; conservative DDPG+BC weight +nonrec-secondary nr_rich_ddpg_strat_a3 nonrec rich_adapter ddpgbc_distill 3.0 0.99 - - - 2,4,8,16,32,64 0.50 1 256 - joint rich latent adapter; stratified horizon curriculum; conservative DDPG+BC weight +nonrec-secondary nr_rich_ddpg_legacyhmatch_a3 nonrec rich_adapter ddpgbc_distill 3.0 0.99 - - - 2,4,8,16,32,64 0.50 1 256 - joint rich latent adapter; matched continuous log-horizon control; conservative DDPG+BC weight +recursion rec_hidden_g099_b098_h64_a1 recursion frozen ddpgbc_distill 1.0 0.99 0.98 hidden 50000 2,4,8,16,32,64 0.50 1 512 0.25 primary occupancy-only recursion +recursion rec_hidden_g099_b098_h64_a3 recursion frozen ddpgbc_distill 3.0 0.99 0.98 hidden 50000 2,4,8,16,32,64 0.50 1 512 0.25 conservative policy-extraction weight at the primary recursion horizon +recursion rec_hidden_g098_b096_h32_a1 recursion frozen ddpgbc_distill 1.0 0.98 0.96 hidden 50000 2,4,8,16,32 0.50 1 512 0.25 shorter gamma/beta recursion alternative +recursion rec_hidden_g099_b098_h64_a1_nocomp recursion frozen ddpgbc_distill 1.0 0.99 0.98 hidden TRAIN_STEPS 2,4,8,16,32,64 0.50 1 512 0.25 matched occupancy architecture and beta mass with composition disabled +recursion rec_compact_g099_b098_h64_a1 recursion frozen ddpgbc_distill 1.0 0.99 0.98 compact 50000 2,4,8,16,32,64 0.50 1 256 0.25 compact z8 recursive-carrier control +recursion rec_hidden_g099_b098_h32_a1_bridge recursion frozen ddpgbc_distill 1.0 0.99 0.98 hidden 50000 2,4,8,16,32 0.50 1 512 0.25 causal bridge: auxiliary horizons do not exceed H=32 before exact beta H=50 and task gamma H=100 diff --git a/gen_q_rsm/ogbench_genq/experiments/visual_rsm_onehop_v2_manifest.tsv b/gen_q_rsm/ogbench_genq/experiments/visual_rsm_onehop_v2_manifest.tsv new file mode 100644 index 0000000000000000000000000000000000000000..55da90f75c6e3862429b8fafe39f8c01dfa70ba8 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual_rsm_onehop_v2_manifest.tsv @@ -0,0 +1,5 @@ +cell latent_update occ_action_negative rationale +frozen_local frozen local frozen visual latent; behavior-local occupancy action contrast +frozen_actor_local frozen actor_local frozen visual latent; behavior-local plus live detached actor-query occupancy contrast +rich_adapter_local rich_adapter local joint rich visual adapter; behavior-local occupancy action contrast +rich_adapter_actor_local rich_adapter actor_local joint rich visual adapter; behavior-local plus live detached actor-query occupancy contrast diff --git a/gen_q_rsm/ogbench_genq/experiments/visual_rsm_recursion_sweep_manifest.tsv b/gen_q_rsm/ogbench_genq/experiments/visual_rsm_recursion_sweep_manifest.tsv new file mode 100644 index 0000000000000000000000000000000000000000..3acd398cbe28c11e3b27b7f717907d39a7e53889 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/experiments/visual_rsm_recursion_sweep_manifest.tsv @@ -0,0 +1,7 @@ +cell composition gamma beta depth continuation cap_mass beta_mass gamma_horizons rec_after reader_tag reader_sha256 rationale +rec_g099_b0985_d08_bm025 on 0.99 0.985 8 0.3367003367003367 0.00016517655554808348 0.25 2,4,8,16,32,64 50000 indexd4_diagmetric 9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7 short beta jumps minimize per-hop flow error; low continuation needs only depth 8 +rec_g099_b0980_d12_bm025 on 0.99 0.98 12 0.505050505050505 0.0002754341063237226 0.25 2,4,8,16,32,64 50000 indexd4_diagmetric 9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7 central balance between beta-query horizon and about two expected recursive hops +rec_g099_b0970_d20_bm025 on 0.99 0.97 20 0.6734006734006734 0.0003676807788245077 0.25 2,4,8,16,32,64 50000 indexd4_diagmetric 9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7 easier one-hop beta occupancy at the cost of about three expected hops +rec_g098_b0960_d12_bm025 on 0.98 0.96 12 0.5102040816326531 0.00031111943662680107 0.25 2,4,8,16,32 50000 indexd4_diagmetric 9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7 shorter task horizon control with matched continuation near the central pair +ctrl_g099_b0980_d12_bm025_nocomp off 0.99 0.98 12 0.505050505050505 0.0002754341063237226 0.25 2,4,8,16,32,64 1000000000 indexd4_diagmetric 9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7 matched hidden occupancy and beta training mass with recursive composition disabled by a fixed unreachable start step +abl_g099_b0980_d12_bm040 on 0.99 0.98 12 0.505050505050505 0.0002754341063237226 0.40 2,4,8,16,32,64 50000 indexd4_diagmetric 9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7 test beta-query support limitation while retaining 0.10 auxiliary-spectrum mass diff --git a/gen_q_rsm/ogbench_genq/figures/beta_recursion.gif b/gen_q_rsm/ogbench_genq/figures/beta_recursion.gif new file mode 100644 index 0000000000000000000000000000000000000000..c8d2866683c57c6f30db1b8d5573778cb86c9464 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/figures/beta_recursion.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3aa86b2cf73c561b0ae1bc2647f2f4f796c561cbee26f8fc5d3a29c6e11d9b06 +size 486040 diff --git a/gen_q_rsm/ogbench_genq/figures/fig_actor.png b/gen_q_rsm/ogbench_genq/figures/fig_actor.png new file mode 100644 index 0000000000000000000000000000000000000000..cb600e03608f234d01b77a972d994ed9f1b15154 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/figures/fig_actor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb19288906695d445a6124f235fc239d5bef4f775af638eda8a8feec84d9fabf +size 158853 diff --git a/gen_q_rsm/ogbench_genq/figures/fig_occupancy.png b/gen_q_rsm/ogbench_genq/figures/fig_occupancy.png new file mode 100644 index 0000000000000000000000000000000000000000..480fb2f397caf2ffff5bfce59ef39b46fd2df728 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/figures/fig_occupancy.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d3e277d69a0604b3805209efa7c7e012def6c42fc7da3b232a4ed0577701f19 +size 172393 diff --git a/gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.png b/gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.png new file mode 100644 index 0000000000000000000000000000000000000000..16e030bb2c5a904bca55e6a1bfe6a165473e3ea0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdc92c3284ff3408fffd969f9aa2a318e82ef84700b5dcace714c1969704975d +size 326107 diff --git a/gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.svg b/gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.svg new file mode 100644 index 0000000000000000000000000000000000000000..817b2466711bfd8cac6018b4f77911af16d97383 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.svg @@ -0,0 +1,332 @@ + + Reader-aligned visual Recursive Successor Model + + A three-stage diagram showing pixels-only representation learning, a + goal-relative reader-metric conditional flow, and joint non-TD policy + extraction. + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + PIXELS ONLY + Separate query from target + + + 2 + TRAIN AND QUERY + Learn futures; query by sampling + + + 3 + DISTILLED DEPLOYMENT + Act without future sampling + + + + + + + QUERY · TRAIN + TEST + TARGET · TRAIN ONLY + + + + + + + + state + + + + + + + + + + goal · reference + + + + + + + + + + future · outcome + + + + + + Frozen pixel encoder E + shared encoder for query and target images + + + + + + + CONDITIONING + Rich visual h + h(state), h(goal) + query context · 256-D + + + MODELED FUTURE + Reward latent z + z(goal), z(future*) + future* is training-only + + + + + TRAINING TARGET ONLY · D = diag(√w / s) + u* = D [ z(fut) − z(goal) ] + + goal = origin · u*=0 is a hit · the delta describes the miss + + + + flow-matching supervision + + + CONDITIONAL GENERATIVE MODEL + pθ(u | h(state), a, h(goal), γ) + test: noise ε → generated û; no future image input + + + h(s), h(g) + + + + a, γ + + + + + γ=.99 · β=.98 · horizons 8/16/32/64 with √h priority + + + + generate û + + + ẑ⁺ = z(goal) + D⁻¹û → Rψ(ẑ⁺, z(goal)) + invert the coordinate, then read reward + + + occupancy Qocc(s,a,g) + + + + TRAINING SIGNALS + + ON-SUPPORT + data action aᴰ + non-TD index anchor + + + COUNTERFACTUAL + μ and μ + ε + occupancy labels + + + + + + TRAINING ONLY + Pixel scorer Qω(s,a,g) + fit + local action ranking + + + + DDPG+BC + + + OFFICIAL TEST PATH + EMA pixel actor π + (state RGB, goal RGB) → action + + + training candidates + + + + OFFICIAL TEST: ACTOR ONLY · NO FUTURE SAMPLING + + + + + + RENDERED PIXELS ONLY + + + NO TD OR BOOTSTRAP + + + NO PROPRIO OR COORDINATES + + + NO WORLD MODEL · ONE HOP + diff --git a/gen_q_rsm/ogbench_genq/gciql.py b/gen_q_rsm/ogbench_genq/gciql.py new file mode 100644 index 0000000000000000000000000000000000000000..f533ee73128083a783834e1ff66fd4eec1f61683 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/gciql.py @@ -0,0 +1,18 @@ +"""Standard goal-conditioned IQL baseline (GCIQL) — JAX-only. + +This is the standard TD-based critic baseline: GCIQL learns a goal-conditioned critic Q(s, a, g) by +a Bellman/TD backup against an expectile value head V(s, g), then extracts a policy with a +(ddpgbc | awr) actor loss. It is the head-to-head foil for Gen-Q-GCIQL — the two differ ONLY in the +critic source (TD backup here vs occupancy-model regression in gciql_genq.py). + +We reuse OGBench's reference GCIQL agent unchanged (pure JAX/Flax, the canonical implementation the +OGBench paper reports) and only re-export it under the names this package uses. Goal-conditioning is +first-class throughout. +""" +from agents.gciql import GCIQLAgent, get_config + +# Public aliases for this package. +GCIQLAgent = GCIQLAgent +get_config = get_config + +__all__ = ["GCIQLAgent", "get_config"] diff --git a/gen_q_rsm/ogbench_genq/genq/__init__.py b/gen_q_rsm/ogbench_genq/genq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/gen_q_rsm/ogbench_genq/genq/build_expert64.py b/gen_q_rsm/ogbench_genq/genq/build_expert64.py new file mode 100644 index 0000000000000000000000000000000000000000..1d55f48efb5d0201706bc9109967204e8bb4d7bf --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/build_expert64.py @@ -0,0 +1,35 @@ +"""Stage 1 of the fair coordinate-free expert pipeline: package LeWM's EXPERT cube +h5 (states + 224^2 pixels, codec via hdf5plugin) into a 64^2 npz in the SAME schema +train_latent_variants_jax.py / precompute_pixel_latents.py consume. + +Fair: no reward/goal coordinate is baked into training data; qpos is carried only so +the DIAGNOSTIC proxy spearman can be computed later. step_idx/terminals carry the +trajectory structure the steps-to-go regression needs. +""" +import os, sys, numpy as np, hdf5plugin, h5py +from PIL import Image + +H5 = "/proj/inf-scaling/zwhong/projs/gen_q/misc/lewm/stablewm_home/datasets/ogbench/cube_single_expert.h5" +OUT = "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion/ckpt/cube_single_expert64.npz" +N = int(sys.argv[1]) if len(sys.argv) > 1 else 500000 # subset of frames +CH = 20000 + +f = h5py.File(H5, "r") +tot = f["pixels"].shape[0]; N = min(N, tot) +print(f"[build64] reading {N}/{tot} expert frames, 224->64", flush=True) +imgs = np.empty((N, 64, 64, 3), np.uint8) +for i in range(0, N, CH): + j = min(i + CH, N) + blk = np.asarray(f["pixels"][i:j]) # (b,224,224,3) uint8 + for r in range(blk.shape[0]): + imgs[i + r] = np.asarray(Image.fromarray(blk[r]).resize((64, 64), Image.BILINEAR)) + if i % (CH * 5) == 0: print(f" {j}/{N}", flush=True) + +qpos = np.asarray(f["qpos"][:N], np.float32) +actions = np.asarray(f["actions"][:N], np.float32) if "actions" in f else np.zeros((N, 5), np.float32) +term = (np.asarray(f["terminated"][:N]) | np.asarray(f["truncated"][:N])).astype(bool) +step_idx = np.asarray(f["step_idx"][:N], np.int32) +cube = np.asarray(f["privileged_block_0_pos"][:N], np.float32) # DIAGNOSTIC only +np.savez(OUT, observations=imgs, qpos=qpos, actions=actions, terminals=term, + step_idx=step_idx, cube=cube) +print(f"[build64] wrote {OUT} imgs={imgs.shape} eps={int(term.sum())}", flush=True) diff --git a/gen_q_rsm/ogbench_genq/genq/cache_visual_eval_goal_pixels.py b/gen_q_rsm/ogbench_genq/genq/cache_visual_eval_goal_pixels.py new file mode 100644 index 0000000000000000000000000000000000000000..ce819b08717b9f045663783c322fe9cc06a11b21 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/cache_visual_eval_goal_pixels.py @@ -0,0 +1,108 @@ +"""Cache the exact pixel goals passed to visual-cube evaluation agents. + +This is a renderer-only capture step for the semantic reward-reader audit. It +stores ``info["goal"]`` (the actor's goal input), not ``goal_rendered`` (the +optional video frame). Repeated reset seeds give nuisance views of the same +task goal because CubeEnv reinitializes and randomly steps the arm while the +cube remains at the task goal. + +The artifact contains pixels, task IDs, and reset seeds only. It intentionally +does not inspect or save qpos, qvel, goal coordinates, proprioception, rewards, +or actions, and must never be consumed by training. +""" + +import argparse +import hashlib +import json +import os + +import numpy as np + + +def capture(env_id, task_ids, variants, base_seed): + import ogbench + + env = ogbench.make_env_and_datasets(env_id, env_only=True) + goals = [] + recorded_tasks = [] + recorded_seeds = [] + try: + for task_id in task_ids: + for variant in range(variants): + reset_seed = int(base_seed + 100_000 * task_id + variant) + # CubeEnv samples two random actions while forming info["goal"]. + # Seed both RNG owners before reset for a reproducible cache. + env.action_space.seed(reset_seed ^ 0x5A17) + _, info = env.reset( + seed=reset_seed, + options={"task_id": int(task_id), "render_goal": False}, + ) + goal = np.asarray(info.get("goal")) + if goal.dtype != np.uint8 or goal.ndim != 3 or goal.shape[-1] != 3: + raise AssertionError( + f"task {task_id} seed {reset_seed}: expected uint8 HWC " + f"info['goal'], got {goal.dtype} {goal.shape}") + goals.append(goal.copy()) + recorded_tasks.append(task_id) + recorded_seeds.append(reset_seed) + finally: + env.close() + + pixels = np.stack(goals) + return ( + pixels, + np.asarray(recorded_tasks, np.int16), + np.asarray(recorded_seeds, np.int64), + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--env", default="visual-cube-single-play-v0") + parser.add_argument("--task_ids", default="1,2,3,4,5") + parser.add_argument("--variants", type=int, default=32) + parser.add_argument("--base_seed", type=int, default=918) + parser.add_argument("--out", required=True) + args = parser.parse_args() + + task_ids = [int(value) for value in args.task_ids.split(",") if value] + if not task_ids or min(task_ids) < 1: + raise ValueError("--task_ids must contain positive, one-indexed task IDs") + if args.variants < 2: + raise ValueError("--variants must be at least 2 for an invariance audit") + + pixels, recorded_tasks, recorded_seeds = capture( + args.env, task_ids, args.variants, args.base_seed) + digest = hashlib.sha256(pixels.tobytes()).hexdigest() + output = os.path.abspath(os.path.expanduser(args.out)) + os.makedirs(os.path.dirname(output), exist_ok=True) + np.savez_compressed( + output, + schema_version=np.asarray(1, np.int64), + env_id=np.asarray(args.env), + source=np.asarray("reset_info_goal_actor_input"), + goal_pixels=pixels, + task_ids=recorded_tasks, + reset_seeds=recorded_seeds, + sha256=np.asarray(digest), + uses_task_coordinates=np.asarray(False), + contains_privileged_state=np.asarray(False), + permitted_for_training=np.asarray(False), + ) + report = { + "output": output, + "env": args.env, + "tasks": task_ids, + "variants_per_task": args.variants, + "shape": list(pixels.shape), + "dtype": str(pixels.dtype), + "sha256": digest, + "source": "info['goal'] (the evaluation actor input)", + "forbidden_fields_read": [], + "permitted_for_training": False, + } + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/diagnose_visual_distilled_policy.py b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_distilled_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9b61e89d6181904c813a1aab6532dc568f03a2e2 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_distilled_policy.py @@ -0,0 +1,1736 @@ +"""Audit a pixels-only visual RSM supervised policy extractor offline. + +This is deliberately a read-only diagnostic. It loads one full RSM +checkpoint, the exact latent artifact named by that checkpoint, and the exact +frozen index reader named by that checkpoint. The reader may use an exact +``index_delta=0`` reward or an explicitly labeled within-delta reward. It never opens +proprioception, simulator state, cube coordinates, or reward-label arrays. + +The audit separates the three objects involved in policy extraction: + +* the discount-conditioned occupancy plus frozen reader (the direct Q source); +* the twin scalar scorer supervised from that direct source (never TD); and +* the actor/value extraction built on the scalar scorer. + +On a deterministic trailing-episode slice it reports scalar/direct fidelity, +common-noise local action rankings, data-versus-actor action values and support, +configured actor-neighborhood point/gap fidelity, twin-head disagreement, +value/advantage/AWR statistics, and a small discount horizon sweep. Rich +encoder-hidden actor/occupancy goals and compact +reward-reader goals remain separate throughout. +""" + +import argparse +import json +import os +import pickle +import sys +import tempfile +from types import SimpleNamespace + +import numpy as np + +if __package__ in (None, ""): + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) + +from ogbench_genq._runner import OGBENCH_IMPLS, _setup_paths +from ogbench_genq.genq.diagnose_visual_occupancy import _corr, _reader +from ogbench_genq.genq.reward_reader import load_numpy_reward_reader +from ogbench_genq.genq.train_genq_jax import build_ends, cosine_abar, make_model + + +OCC_T = 100 +FOURIER_K = 4 +SPECTRUM_PROBABILITY = 0.5 +LOCAL_ACTIONS = 8 + + +def _as_str(value): + """Convert a scalar numpy/string metadata field without array repr noise.""" + arr = np.asarray(value) + if arr.ndim == 0: + return str(arr.item()) + raise AssertionError(f"expected scalar string metadata, got shape {arr.shape}") + + +def _resolve_exact_artifact(requested, recorded, name): + """Resolve an artifact and fail if it is not the checkpoint-recorded file.""" + assert recorded, f"checkpoint does not record its {name} artifact" + recorded = os.path.abspath(os.path.expanduser(str(recorded))) + chosen = recorded if requested is None else os.path.abspath( + os.path.expanduser(requested)) + assert os.path.exists(recorded), ( + f"checkpoint-recorded {name} does not exist: {recorded}") + assert os.path.exists(chosen), f"{name} does not exist: {chosen}" + assert os.path.realpath(chosen) == os.path.realpath(recorded), ( + f"{name} must match the checkpoint exactly:\n" + f"recorded={recorded}\nprovided={chosen}") + return chosen + + +def _reader_metadata(path): + with np.load(path, allow_pickle=False) as rd: + required = {"target", "index_delta", "zdim"} + missing = sorted(required.difference(rd.files)) + assert not missing, f"reader lacks fairness metadata: {missing}" + _, metadata = load_numpy_reward_reader(path) + return metadata + + +def _index_reward_semantics(index_delta): + if index_delta == 0: + return "exact_index_match_reward" + return f"within_{index_delta}_trajectory_steps_index_reward" + + +def _assert_fair_checkpoint(meta, reader_meta, require_index_delta=None): + """Fail closed on every eligibility property this audit relies on.""" + assert isinstance(meta, dict) and meta, "full checkpoint lacks run_meta" + assert str(meta.get("env", "")).startswith("visual-"), ( + f"expected a visual checkpoint, got env={meta.get('env')!r}") + assert meta.get("drop_proprio") is True, ( + "diagnostic requires a checkpoint saved with drop_proprio=true") + assert meta.get("discount_conditioned") is True, ( + "occupancy must explicitly condition on discount") + assert meta.get("discount_feature") == "fourier_log_horizon", ( + "expected the audited Fourier log-horizon discount conditioning") + gamma = float(meta.get("gamma", -1.0)) + gamma_lo = float(meta.get("gamma_spectrum_lo", -1.0)) + assert 0.0 < gamma_lo < gamma < 1.0, ( + f"invalid discount support [{gamma_lo}, {gamma}]") + gamma_sampler = meta.get("gamma_sampler") + if gamma_sampler == "stratified_bins": + horizons = np.asarray(meta.get("gamma_horizons"), np.float64) + aux_discounts = np.asarray( + meta.get("gamma_aux_discounts"), np.float64) + assert horizons.ndim == 1 and horizons.size > 0 + assert np.all(np.isfinite(horizons)) and np.all(horizons > 1.0) + assert np.all(np.diff(horizons) > 0.0) + expected_discounts = 1.0 - 1.0 / horizons + assert aux_discounts.shape == expected_discounts.shape + assert np.allclose( + aux_discounts, expected_discounts, atol=1e-12, rtol=0.0) + task_fraction = float(meta.get("gamma_task_fraction", -1.0)) + assert 0.0 < task_fraction < 1.0 + assert meta.get("gamma_batch_allocation") == ( + "exact_task_count_balanced_aux_bins_then_shuffle") + assert meta.get("gamma_sampling_importance_weighted") is False + assert meta.get("gamma_normalization") == "fixed_fourier_identity" + assert meta.get("condition_normalizer_goal_sampler") == ( + "gciql_value_goals_20_current_50_trajectory_30_random") + occ_batch = int(meta["occ_batch"]) + task_rows = int(round(task_fraction * occ_batch)) + assert int(meta["gamma_task_rows_per_occ_batch"]) == task_rows + quotient, remainder = divmod( + occ_batch - task_rows, len(horizons)) + expected_rows = [ + quotient + int(i < remainder) for i in range(len(horizons))] + assert meta.get("gamma_aux_rows_per_occ_batch") == expected_rows + elif gamma_sampler is not None: + assert gamma_sampler == "legacy_log_uniform", ( + f"unknown discount sampler {gamma_sampler!r}") + assert meta.get("uses_td_or_bootstrap") is False, ( + "checkpoint must explicitly record uses_td_or_bootstrap=false") + actor_query_occ_support = bool( + float(meta.get("occ_action_contrast_weight", 0.0)) > 0.0 + and meta.get("occ_action_negative") == "actor_local") + if actor_query_occ_support: + local_k = int(meta.get("occ_action_negative_local_k", 0)) + assert local_k > 0 + assert int(meta.get( + "occ_action_negative_candidate_count", -1)) == 1 + local_k + assert meta.get("occ_action_negative_policy") == ( + "stop_gradient_live_preupdate_actor_mode_plus_local_gaussian") + assert meta.get("occ_action_negative_actor_source") == ( + "live_preupdate_actor") + assert int(meta.get( + "occ_action_negative_support_start_step", -1)) == 0 + assert meta.get( + "occ_action_negative_actions_stop_gradient") is True + assert meta.get( + "occ_action_negative_common_random_numbers") is True + assert meta.get("occ_action_negative_updates_actor") is False + assert meta.get("occupancy_gradient_updates_actor") is False + assert meta.get( + "occ_action_negative_counterfactual_target") is False + assert meta.get("occ_action_negative_interpretation") == ( + "anti_exploitation_likelihood_ranking_not_counterfactual_" + "occupancy") + assert meta.get("occupancy_supervision") == ( + "monte_carlo_geometric_futures_plus_detached_actor_query_" + "likelihood_ranking") + assert meta.get("occupancy_training_policy") == ( + "offline_behavior_futures_with_detached_live_actor_query_" + "negatives") + assert meta.get("joint_update_semantics") == ( + "same_fused_step_occupancy_uses_detached_live_preupdate_" + "actor_queries") + assert meta.get("occupancy_uses_reward_labels") is False + assert meta.get("occupancy_uses_simulator_coordinates") is False + assert meta.get("uses_completion_or_forward_model") is False + assert meta.get("actor_loss") in ("awr_distill", "ddpgbc_distill"), ( + "checkpoint is not a supervised occupancy-Q policy extractor") + if actor_query_occ_support: + assert meta["actor_loss"] == "ddpgbc_distill", ( + "actor-query occupancy support is only defined for a " + "score-maximizing DDPG+BC extractor") + expected_extraction = { + "awr_distill": "supervised_occupancy_q_distillation_awr", + "ddpgbc_distill": "supervised_occupancy_q_distillation_ddpgbc", + }[meta["actor_loss"]] + assert meta.get("policy_extraction") == expected_extraction + index_delta = int(reader_meta["index_delta"]) + exact_target_source = ( + "ema_occupancy_instant_index_reward_expectation" + if index_delta == 0 + else f"ema_occupancy_within_{index_delta}_step_index_reward_expectation") + accepted_target_sources = { + exact_target_source, + # Legacy schema-5/6 strings are accepted because the exact reader + # artifact and its delta remain independently checked below. + "ema_occupancy_immediate_reward_expectation", + "ema_occupancy_index_reward_expectation", + "ema_occupancy_within_delta_reward_expectation", + } + assert meta.get("critic_target_source") in accepted_target_sources, ( + "scalar scorer target is not a declared occupancy/index-reader Q") + actor_action_support = bool(meta.get("distill_actor_actions", False)) + if meta["actor_loss"] != "ddpgbc_distill": + assert not actor_action_support, ( + "actor-action scorer support is defined only for DDPG+BC " + "distillation") + if actor_action_support: + assert meta.get("distill_actor_goals") is True, ( + "actor-action gap support requires a point-anchored behavior " + "action at the same actor goal") + local_k = int(meta.get("distill_actor_action_local_k", 0)) + assert local_k > 0 + assert float(meta.get("distill_actor_action_sigma", 0.0)) > 0.0 + assert float( + meta.get("distill_actor_action_pairwise_weight", -1.0)) >= 0.0 + assert float(meta.get( + "distill_actor_action_pointwise_weight", -1.0)) == 1.0 + assert int(meta.get( + "distill_actor_action_candidate_count", -1)) == 1 + local_k + assert int(meta.get( + "distill_actor_action_pairwise_candidate_count", -1)) == 2 + local_k + assert meta.get( + "distill_actor_action_common_random_numbers") is True + assert meta.get("distill_actor_action_policy") == ( + "stop_gradient_current_actor_mode_plus_local_gaussian") + assert meta.get( + "distill_actor_action_target_source") == exact_target_source + assert meta.get( + "distill_actor_action_composed_occupancy", False) is False, ( + "the one-hop diagnostic cannot audit composed-recursion targets") + assert int(meta.get( + "distill_actor_action_support_start_step", -1)) == 0 + assert int(meta.get( + "actor_q_gradient_start_step", -1)) == int(meta["actor_after"]) + assert meta.get("distill_actor_action_loss_reduction") == ( + "normalized_point_and_pairwise_then_mean_with_existing_support") + assert meta.get( + "distill_actor_action_updates_occupancy") is False + assert meta.get("reward_decoder_target") == "index" + assert meta.get("reward_decoder_logit") is False, ( + "direct Q must be a calibrated sigmoid reward expectation") + declared_reader_model = meta.get("reward_decoder_model", "mlp") + assert declared_reader_model == reader_meta["reader_model"], ( + f"checkpoint declares reward_decoder_model={declared_reader_model!r} " + f"but artifact is {reader_meta['reader_model']!r}") + assert reader_meta["target"] == "index", ( + f"reader target must be index, got {reader_meta['target']!r}") + assert index_delta >= 0, "index reader delta must be nonnegative" + if require_index_delta is not None: + assert index_delta == int(require_index_delta), ( + f"reader index_delta={index_delta}, required " + f"{int(require_index_delta)}") + for metadata_key in ( + "reward_decoder_index_delta", "reader_index_delta"): + if meta.get(metadata_key) is not None: + assert int(meta[metadata_key]) == index_delta, ( + f"reader index_delta={index_delta} disagrees with " + f"run_meta.{metadata_key}={meta[metadata_key]}") + # Joint-adapter runs already store the auxiliary reader's delta. It is + # the same reader artifact used for the occupancy read-out. + if meta.get("latent_index_delta") is not None: + assert int(meta["latent_index_delta"]) == index_delta, ( + f"reader index_delta={index_delta} disagrees with " + f"run_meta.latent_index_delta={meta['latent_index_delta']}") + declared_aux_model = meta.get("latent_reader_model", "mlp") + assert declared_aux_model == reader_meta["reader_model"], ( + "joint latent auxiliary reader model disagrees with the frozen " + "read-out artifact") + if reader_meta["reader_model"] == "diag_metric": + assert meta.get("latent_index_negative_contract") == ( + "same_episode_far_only_cross_episode_excluded"), ( + "diagonal-metric joint auxiliary must exclude cross-episode " + "negative pairs") + assert meta.get("recursion") == "off", ( + "fair visual diagnostic excludes completion/forward-model recursion") + assert meta.get("latent_npz"), "visual checkpoint must name its latent artifact" + assert meta.get("reward_decoder"), ( + "visual checkpoint must name its frozen reward reader") + + state_feature = str(meta.get("state_feature", "")) + actor_goal_feature = str(meta.get("actor_goal_feature", "")) + occupancy_goal_feature = str(meta.get("occupancy_goal_feature", "")) + future_feature = str(meta.get("future_feature", "")) + reward_goal_feature = str(meta.get("reward_goal_feature", "")) + role_values = { + "state_feature": state_feature, + "actor_goal_feature": actor_goal_feature, + "occupancy_goal_feature": occupancy_goal_feature, + "future_feature": future_feature, + "reward_goal_feature": reward_goal_feature, + } + forbidden_tokens = ("proprio", "qpos", "coord") + for role, value in role_values.items(): + assert value, f"checkpoint lacks {role}" + assert not any(token in value.lower() for token in forbidden_tokens), ( + f"forbidden feature role {role}={value!r}") + + allowed_state = { + "compact_z", "encoder_hidden", "joint_compact_z_adapter", + "joint_encoder_hidden_adapter", + } + allowed_compact = { + "compact_reward_predictive_z", "frozen_compact_reward_predictive_z", + "joint_compact_z_adapter", + } + assert state_feature in allowed_state + assert future_feature in allowed_compact + assert reward_goal_feature in allowed_compact + if bool(meta.get("goal_hidden")): + allowed_rich = {"encoder_hidden", "joint_encoder_hidden_adapter"} + assert actor_goal_feature in allowed_rich + assert occupancy_goal_feature in allowed_rich + assert reward_goal_feature in allowed_compact + assert int(meta["actor_goal_dim"]) != int(meta["reward_goal_dim"]), ( + "rich actor goal and compact reward goal were accidentally conflated") + + return { + "drop_proprio": True, + "discount_conditioned": True, + "discount_feature": meta["discount_feature"], + "discount_support": [gamma_lo, gamma], + "uses_td_or_bootstrap": False, + "reader_target": "index", + "reader_model": reader_meta["reader_model"], + "reader_index_delta": index_delta, + "reader_reward_semantics": _index_reward_semantics(index_delta), + "strict_instant_reward_reader": index_delta == 0, + "recursion": "off", + "goal_roles_separate": bool(meta.get("goal_hidden")), + "actor_action_scorer_support": actor_action_support, + "actor_query_occupancy_support": actor_query_occ_support, + } + + +def _apply_adapter(params, features): + """Apply the residual latent adapter used by RSM without importing rsm.py.""" + import jax + import jax.numpy as jnp + + features = jnp.asarray(features, jnp.float32) + hidden = jax.nn.relu( + features @ params["a0.kernel"] + params["a0.bias"]) + return features + hidden @ params["a1.kernel"] + params["a1.bias"] + + +def _actor_mode(params, states, goals): + """Apply the deterministic mode of the reference goal-conditioned actor.""" + import jax + import jax.numpy as jnp + + hidden = jnp.concatenate([states, goals], axis=-1) + layer = 0 + while f"Dense_{layer}" in params["actor_net"]: + dense = params["actor_net"][f"Dense_{layer}"] + hidden = jax.nn.gelu( + hidden @ dense["kernel"] + dense["bias"]) + layer += 1 + assert layer > 0, "unrecognized actor parameter tree" + mean = ( + hidden @ params["mean_net"]["kernel"] + + params["mean_net"]["bias"]) + return jnp.clip(mean, -1.0, 1.0) + + +def _discount_features(discounts, gamma_lo, gamma_hi): + """Exact Fourier log-horizon encoding used by the visual RSM.""" + discounts = np.asarray(discounts, np.float32) + lo_h = np.log(1.0 / (1.0 - gamma_lo)) + hi_h = np.log(1.0 / (1.0 - gamma_hi)) + frequencies = ( + np.pi * (2.0 ** np.arange(FOURIER_K))).astype(np.float32) + unit = ( + np.log(1.0 / (1.0 - discounts)) - lo_h + ) / max(hi_h - lo_h, 1e-8) + angle = unit[:, None] * frequencies[None, :] + return np.concatenate([np.sin(angle), np.cos(angle)], axis=-1).astype( + np.float32) + + +def _condition_stats(state_base, actions, occupancy_goal_base, ends, meta): + """Reproduce rsm.py's deterministic 20k condition-normalizer probe.""" + gamma = float(meta["gamma"]) + gamma_lo = float(meta["gamma_spectrum_lo"]) + seed = int(meta["seed"]) + rng = np.random.default_rng(seed) + rows = rng.integers(0, len(actions), 20000) + goals = np.minimum( + rows + rng.geometric(1.0 - gamma, 20000), ends[rows] - 1) + + lo_h = np.log(1.0 / (1.0 - gamma_lo)) + hi_h = np.log(1.0 / (1.0 - gamma)) + horizon = np.exp(rng.uniform(lo_h, hi_h, 20000)) + spectrum_gamma = 1.0 - 1.0 / horizon + discounts = np.where( + rng.random(20000) >= SPECTRUM_PROBABILITY, + gamma, + spectrum_gamma, + ).astype(np.float32) + condition = np.concatenate( + [ + state_base[rows], + actions[rows], + occupancy_goal_base[goals], + _discount_features(discounts, gamma_lo, gamma), + ], + axis=-1, + ) + return ( + condition.mean(axis=0).astype(np.float32), + (condition.std(axis=0) + 1e-6).astype(np.float32), + ) + + +def _legacy_normalizer_contract(meta): + """Verify that a checkpoint without saved statistics uses the old sampler.""" + schema = int(meta.get("schema_version", -1)) + assert schema in (5, 6), ( + "normalization is not serialized and this schema is not one of the " + "audited legacy visual-distillation schemas (5, 6)") + expected_sampler = ( + "legacy_task_gamma_plus_log_uniform_horizon_mixture_p0.5") + explicit_sampler_keys = ( + "gamma_sampler", "discount_sampler", "horizon_sampler", + "discount_sampling", "gamma_sampling", + ) + explicit = { + key: meta[key] for key in explicit_sampler_keys + if meta.get(key) is not None + } + for key, value in explicit.items(): + assert value == expected_sampler, ( + f"cannot reconstruct normalization for run_meta.{key}={value!r}; " + f"expected {expected_sampler!r}") + for key in ( + "gamma_spectrum_probability", "spectrum_probability", + "task_gamma_mixture_probability"): + if meta.get(key) is not None: + assert np.isclose( + float(meta[key]), SPECTRUM_PROBABILITY, atol=1e-12), ( + f"legacy normalizer requires {key}=0.5, got {meta[key]}") + if meta.get("condition_normalizer_probe_size") is not None: + assert int(meta["condition_normalizer_probe_size"]) == 20000 + if meta.get("condition_normalizer_seed") is not None: + assert int(meta["condition_normalizer_seed"]) == int(meta["seed"]) + return { + "source": "legacy_reconstruction", + "exact_checkpoint_statistics": False, + "recipe": expected_sampler, + "sampler_metadata": ( + "explicit_verified" if explicit else "schema_5_or_6_inference"), + "task_gamma_probability": 1.0 - SPECTRUM_PROBABILITY, + "log_uniform_horizon_probability": SPECTRUM_PROBABILITY, + "probe_size": 20000, + "probe_seed": int(meta["seed"]), + "warning": ( + "Legacy fallback only. Do not use after changing prioritized " + "discount sampling; new checkpoints must serialize normalization."), + } + + +def _load_occupancy_normalization( + checkpoint, state_base, actions, occupancy_goal_base, ends, z_base, + meta): + """Prefer exact saved statistics; reconstruct only audited legacy schemas.""" + saved = checkpoint.get("occupancy_normalization") + expected_condition_dim = ( + state_base.shape[1] + actions.shape[1] + + occupancy_goal_base.shape[1] + 2 * FOURIER_K) + if saved is not None: + assert isinstance(saved, dict) + required = {"cond_mean", "cond_std", "target_mean", "target_std"} + missing = sorted(required.difference(saved)) + assert not missing, ( + f"serialized occupancy normalization lacks {missing}") + condition_mean = np.asarray(saved["cond_mean"], np.float32) + condition_std = np.asarray(saved["cond_std"], np.float32) + target_mean = np.asarray(saved["target_mean"], np.float32) + target_std = np.asarray(saved["target_std"], np.float32) + assert condition_mean.shape == (expected_condition_dim,) + assert condition_std.shape == (expected_condition_dim,) + assert target_mean.shape == (z_base.shape[1],) + assert target_std.shape == (z_base.shape[1],) + assert np.all(np.isfinite(condition_mean)) + assert np.all(np.isfinite(condition_std)) + assert np.all(np.isfinite(target_mean)) + assert np.all(np.isfinite(target_std)) + assert np.all(condition_std > 0.0) + assert np.all(target_std > 0.0) + return condition_mean, condition_std, target_mean, target_std, { + "source": "checkpoint_serialized", + "exact_checkpoint_statistics": True, + "condition_dim": expected_condition_dim, + "target_dim": int(z_base.shape[1]), + } + + contract = _legacy_normalizer_contract(meta) + condition_mean, condition_std = _condition_stats( + state_base, actions, occupancy_goal_base, ends, meta) + target_mean = z_base.mean(axis=0).astype(np.float32) + target_std = (z_base.std(axis=0) + 1e-6).astype(np.float32) + return ( + condition_mean, condition_std, target_mean, target_std, contract) + + +def _fidelity(prediction, target): + prediction = np.asarray(prediction, np.float64).reshape(-1) + target = np.asarray(target, np.float64).reshape(-1) + error = prediction - target + pred_sd = float(prediction.std()) + target_sd = float(target.std()) + if pred_sd > 1e-12 and target_sd > 1e-12: + pearson = float(np.corrcoef(prediction, target)[0, 1]) + else: + pearson = 0.0 + return { + "n": int(target.size), + "direct_mean": float(target.mean()), + "scorer_mean": float(prediction.mean()), + "bias": float(error.mean()), + "mae": float(np.abs(error).mean()), + "rmse": float(np.sqrt(np.mean(error ** 2))), + "normalized_mae_by_direct_sd": float( + np.abs(error).mean() / max(target_sd, 1e-8)), + "pearson": pearson, + "spearman": _corr(prediction, target), + } + + +def _pairwise_agreement(left, right): + left = np.asarray(left) + right = np.asarray(right) + count = left.shape[1] + ii, jj = np.triu_indices(count, 1) + left_sign = np.sign(left[:, ii] - left[:, jj]) + right_sign = np.sign(right[:, ii] - right[:, jj]) + return float(np.mean(left_sign == right_sign)) + + +def _ranking_metrics(direct, scorer): + direct = np.asarray(direct) + scorer = np.asarray(scorer) + assert direct.shape == scorer.shape and direct.ndim == 2 + per_row_corr = np.asarray([ + _corr(direct[i], scorer[i]) for i in range(len(direct)) + ]) + return { + "top1_agreement": float(np.mean( + np.argmax(direct, axis=1) == np.argmax(scorer, axis=1))), + "pairwise_agreement": _pairwise_agreement(direct, scorer), + "per_row_spearman_mean": float(per_row_corr.mean()), + "per_row_spearman_median": float(np.median(per_row_corr)), + "direct_span_mean": float( + np.mean(direct.max(axis=1) - direct.min(axis=1))), + "scorer_span_mean": float( + np.mean(scorer.max(axis=1) - scorer.min(axis=1))), + "direct_data_action_best_rate": float(np.mean( + np.argmax(direct, axis=1) == 0)), + "scorer_data_action_best_rate": float(np.mean( + np.argmax(scorer, axis=1) == 0)), + } + + +def _pairwise_gap_metrics(direct, scorer): + """Compare all within-row scorer action gaps to direct occupancy gaps.""" + direct = np.asarray(direct, np.float64) + scorer = np.asarray(scorer, np.float64) + assert direct.shape == scorer.shape and direct.ndim == 2 + ii, jj = np.triu_indices(direct.shape[1], 1) + direct_gap = direct[:, ii] - direct[:, jj] + scorer_gap = scorer[:, ii] - scorer[:, jj] + metrics = _fidelity(scorer_gap, direct_gap) + metrics.update({ + "candidate_count": int(direct.shape[1]), + "pair_count_per_row": int(len(ii)), + "sign_agreement": float(np.mean( + np.sign(direct_gap) == np.sign(scorer_gap))), + }) + return metrics + + +def _gap_metrics(heads): + heads = np.asarray(heads) + assert heads.shape[0] == 2 + gap = np.abs(heads[0] - heads[1]).reshape(-1) + return { + "absolute_mean": float(gap.mean()), + "absolute_median": float(np.median(gap)), + "absolute_p95": float(np.quantile(gap, 0.95)), + "absolute_max": float(gap.max()), + } + + +def _summary(values): + values = np.asarray(values, np.float64).reshape(-1) + return { + "mean": float(values.mean()), + "std": float(values.std()), + "min": float(values.min()), + "median": float(np.median(values)), + "p90": float(np.quantile(values, 0.90)), + "p99": float(np.quantile(values, 0.99)), + "max": float(values.max()), + } + + +def _discount_grid(meta, requested, count): + gamma_lo = float(meta["gamma_spectrum_lo"]) + gamma_hi = float(meta["gamma"]) + if requested: + horizons = np.asarray([ + float(item) for item in requested.split(",") if item.strip() + ]) + assert len(horizons), "--horizons did not contain any values" + assert np.all(horizons > 1.0), "effective horizons must exceed one" + discounts = 1.0 - 1.0 / horizons + elif count <= 1: + discounts = np.asarray([gamma_hi]) + else: + horizons = np.geomspace( + 1.0 / (1.0 - gamma_lo), + 1.0 / (1.0 - gamma_hi), + count, + ) + discounts = 1.0 - 1.0 / horizons + if not np.any(np.isclose(discounts, gamma_hi, atol=1e-8)): + discounts = np.r_[discounts, gamma_hi] + discounts = np.unique(np.round(discounts, 8)) + assert np.all(discounts >= gamma_lo - 1e-7) + assert np.all(discounts <= gamma_hi + 1e-7) + return discounts.astype(np.float32) + + +def _build_parser(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt") + parser.add_argument("--latents", + help="must resolve to checkpoint run_meta.latent_npz") + parser.add_argument("--reward_decoder", + help="must resolve to checkpoint run_meta.reward_decoder") + parser.add_argument("--out") + parser.add_argument("--rows", type=int, default=128) + parser.add_argument("--samples", type=int, default=32) + parser.add_argument("--episodes", type=int, default=100, + help="deterministic trailing episode slice") + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--actor", choices=("ema", "live"), default="ema") + parser.add_argument("--local_sigma", type=float, default=0.3) + parser.add_argument("--sample_steps", type=int, default=0, + help="0 uses 25 DDIM steps or checkpoint flow_steps") + parser.add_argument("--horizon_points", type=int, default=4) + parser.add_argument( + "--horizons", default="", + help="optional comma-separated effective horizons, e.g. 10,25,50,100") + parser.add_argument( + "--require_index_delta", type=int, + help="fail unless the frozen index reader has exactly this delta") + parser.add_argument("--ogbench_impls", default=OGBENCH_IMPLS) + parser.add_argument("--self_test", action="store_true") + return parser + + +def run_diagnostic(args): + import jax + import jax.numpy as jnp + + assert args.ckpt and args.out, "--ckpt and --out are required" + assert args.rows > 0 and args.samples > 0 and args.episodes > 0 + assert args.local_sigma > 0 + with open(args.ckpt, "rb") as file: + checkpoint = pickle.load(file) + assert "carry" in checkpoint, "not a full RSM checkpoint" + meta = dict(checkpoint.get("run_meta") or {}) + latent_path = _resolve_exact_artifact( + args.latents, meta.get("latent_npz"), "latent") + reader_path = _resolve_exact_artifact( + args.reward_decoder, meta.get("reward_decoder"), "reward reader") + reader_meta = _reader_metadata(reader_path) + if args.require_index_delta is not None: + assert args.require_index_delta >= 0 + fairness = _assert_fair_checkpoint( + meta, reader_meta, args.require_index_delta) + + # Deliberately enumerate and load only the allowed arrays. In particular, + # a proprio/proprio19 field may exist in the artifact but is never opened. + with np.load(latent_path, allow_pickle=False) as latent_file: + required = {"z", "state_h", "actions", "terminals"} + missing = sorted(required.difference(latent_file.files)) + assert not missing, f"latent artifact lacks required arrays: {missing}" + z_base = np.asarray(latent_file["z"], np.float32) + state_h = np.asarray(latent_file["state_h"], np.float32) + actions = np.clip( + np.asarray(latent_file["actions"], np.float32), -1.0, 1.0) + terminals = np.asarray(latent_file["terminals"], bool) + available_arrays = sorted(latent_file.files) + assert len(z_base) == len(state_h) == len(actions) == len(terminals) + assert reader_meta["zdim"] == z_base.shape[1] + assert int(meta["reward_goal_dim"]) == z_base.shape[1] + + ends = build_ends(terminals) + episode_ends = np.flatnonzero(terminals) + 1 + if len(episode_ends) == 0 or episode_ends[-1] != len(terminals): + episode_ends = np.r_[episode_ends, len(terminals)] + episode_starts = np.r_[0, episode_ends[:-1]] + episode_lengths = episode_ends - episode_starts + valid_episodes = np.flatnonzero(episode_lengths >= 2) + trailing = valid_episodes[-args.episodes:] + assert len(trailing), "no trailing episode contains a transition" + candidates = np.concatenate([ + np.arange(episode_starts[index], episode_ends[index] - 1) + for index in trailing + ]) + assert len(candidates) >= args.rows, ( + f"requested {args.rows} rows but trailing slice has {len(candidates)}") + + state_dim = int(meta["state_dim"]) + if state_dim == state_h.shape[1]: + state_base = state_h + elif state_dim == z_base.shape[1]: + state_base = z_base + else: + raise AssertionError( + f"checkpoint state_dim={state_dim} matches neither state_h " + f"({state_h.shape[1]}) nor z ({z_base.shape[1]})") + if bool(meta.get("goal_hidden")): + occupancy_goal_base = state_h + actor_goal_base = state_h + else: + occupancy_goal_base = z_base + actor_goal_base = z_base + assert int(meta["occupancy_goal_dim"]) == occupancy_goal_base.shape[1] + assert int(meta["actor_goal_dim"]) == actor_goal_base.shape[1] + + carry = checkpoint["carry"] + assert len(carry) >= 10, "unrecognized full-checkpoint carry" + agent = carry[6] + assert isinstance(agent, tuple) and len(agent) == 7, ( + "checkpoint does not contain actor, value, and twin supervised scorer") + actor_params = carry[7] if args.actor == "ema" else agent[0] + value_params = agent[2] + scorer_live_params = agent[4] + scorer_ema_params = agent[6] + occupancy_ema = carry[2] + checkpoint_step = int(np.asarray(carry[9]).item()) + + latent_update = str(meta.get("latent_update", "frozen")) + assert latent_update in ("frozen", "adapter", "rich_adapter") + adapter_params = None + if latent_update != "frozen": + assert len(carry) >= 13, "joint-latent checkpoint lacks adapter EMA" + adapter_params = carry[12] + + def transform(features): + if adapter_params is None: + return np.asarray(features, np.float32) + return np.asarray(_apply_adapter( + jax.device_put(adapter_params), jnp.asarray(features))) + + ( + condition_mean, + condition_std, + target_mean, + target_std, + normalization_contract, + ) = _load_occupancy_normalization( + checkpoint, + state_base, + actions, + occupancy_goal_base, + ends, + z_base, + meta, + ) + + rng = np.random.default_rng(args.seed + 918) + rows = rng.choice(candidates, size=args.rows, replace=False) + span = np.maximum(ends[rows] - rows - 1, 1) + goal_indices = rows + 1 + ( + rng.random(args.rows) * span).astype(np.int64) + goal_indices = np.minimum(goal_indices, ends[rows] - 1) + + if latent_update == "rich_adapter": + states = transform(state_h[rows]) + actor_goals = transform(state_h[goal_indices]) + occupancy_goals = actor_goals + reward_goals = z_base[goal_indices] + elif latent_update == "adapter": + states = transform(z_base[rows]) + actor_goals = transform(z_base[goal_indices]) + occupancy_goals = actor_goals + reward_goals = actor_goals + else: + states = state_base[rows] + actor_goals = actor_goal_base[goal_indices] + occupancy_goals = occupancy_goal_base[goal_indices] + reward_goals = z_base[goal_indices] + + assert states.shape[1] == int(meta["state_dim"]) + assert actor_goals.shape[1] == int(meta["actor_goal_dim"]) + assert occupancy_goals.shape[1] == int(meta["occupancy_goal_dim"]) + assert reward_goals.shape[1] == reader_meta["zdim"] + if bool(meta.get("goal_hidden")): + assert not np.shares_memory(actor_goals, reward_goals) + + action_dim = actions.shape[1] + local_actions = np.clip( + actions[rows, None, :] + args.local_sigma * rng.standard_normal( + (args.rows, LOCAL_ACTIONS, action_dim)), + -1.0, + 1.0, + ).astype(np.float32) + local_actions[:, 0] = actions[rows] + + actor_action = np.asarray(jax.jit(_actor_mode)( + jax.device_put(actor_params), + jnp.asarray(states), + jnp.asarray(actor_goals), + )) + actor_action = np.clip(actor_action, -1.0, 1.0) + actor_action_support_enabled = bool( + meta.get("distill_actor_actions", False)) + actor_action_local_k = ( + int(meta["distill_actor_action_local_k"]) + if actor_action_support_enabled else 0) + actor_action_local_sigma = ( + float(meta["distill_actor_action_sigma"]) + if actor_action_support_enabled else 0.0) + actor_local_actions = np.clip( + actor_action[:, None, :] + + actor_action_local_sigma * rng.standard_normal( + (args.rows, actor_action_local_k, action_dim)), + -1.0, + 1.0, + ).astype(np.float32) + evaluation_actions = np.concatenate( + [local_actions, actor_local_actions, actor_action[:, None, :]], axis=1) + action_count = evaluation_actions.shape[1] + actor_support_indices = np.asarray( + [0] + + list(range( + LOCAL_ACTIONS, LOCAL_ACTIONS + actor_action_local_k)) + + [action_count - 1], + dtype=np.int64, + ) + + _setup_paths(args.ogbench_impls) + from agents.gciql import get_config + from utils.networks import GCValue + + config = get_config() + value_def = GCValue( + hidden_dims=tuple(config["value_hidden_dims"]), + layer_norm=config["layer_norm"], + ensemble=False, + ) + scorer_def = GCValue( + hidden_dims=tuple(config["value_hidden_dims"]), + layer_norm=config["layer_norm"], + ensemble=True, + ) + + @jax.jit + def apply_value(params, state, goal): + return value_def.apply({"params": params}, state, goal) + + @jax.jit + def apply_scorer(params, state, goal, action): + return scorer_def.apply( + {"params": params}, state, goal, action) + + state_flat = np.repeat( + states[:, None, :], action_count, axis=1).reshape( + -1, states.shape[1]) + actor_goal_flat = np.repeat( + actor_goals[:, None, :], action_count, axis=1).reshape( + -1, actor_goals.shape[1]) + action_flat = evaluation_actions.reshape(-1, action_dim) + scorer_heads_live = np.asarray(apply_scorer( + jax.device_put(scorer_live_params), + jnp.asarray(state_flat), + jnp.asarray(actor_goal_flat), + jnp.asarray(action_flat), + )).reshape(2, args.rows, action_count) + scorer_heads_ema = np.asarray(apply_scorer( + jax.device_put(scorer_ema_params), + jnp.asarray(state_flat), + jnp.asarray(actor_goal_flat), + jnp.asarray(action_flat), + )).reshape(2, args.rows, action_count) + scorer_live = scorer_heads_live.min(axis=0) + scorer_ema = scorer_heads_ema.min(axis=0) + values = np.asarray(apply_value( + jax.device_put(value_params), + jnp.asarray(states), + jnp.asarray(actor_goals), + )) + + occupancy_model = str(meta.get("occupancy_model", "diffusion")) + assert occupancy_model in ("diffusion", "flow") + hidden = int(meta["occ_hidden"]) + layers = int(meta["occ_layers"]) + sample_steps = ( + int(args.sample_steps) if args.sample_steps > 0 + else int(meta["flow_steps"]) if occupancy_model == "flow" + else 25) + gamma_lo = float(meta["gamma_spectrum_lo"]) + gamma = float(meta["gamma"]) + condition_dim = ( + states.shape[1] + action_dim + occupancy_goals.shape[1] + + 2 * FOURIER_K) + occupancy_def = make_model( + condition_dim, z_base.shape[1], hidden, layers, 64) + reader_logit, loaded_reader_meta = _reader(reader_path) + assert loaded_reader_meta["target"] == "index" + abar = jnp.asarray(cosine_abar(OCC_T)) + schedule = np.unique(np.linspace( + OCC_T, 1, sample_steps).round().astype(np.int32))[::-1].copy() + schedule_now = jnp.asarray(schedule) + schedule_next = jnp.asarray(np.r_[schedule[1:], 0].astype(np.int32)) + condition_mean_j = jnp.asarray(condition_mean) + condition_std_j = jnp.asarray(condition_std) + target_mean_j = jnp.asarray(target_mean) + target_std_j = jnp.asarray(target_std) + + def discount_features_jax(discount): + lo_h = np.log(1.0 / (1.0 - gamma_lo)) + hi_h = np.log(1.0 / (1.0 - gamma)) + frequencies = jnp.asarray( + np.pi * (2.0 ** np.arange(FOURIER_K)), jnp.float32) + unit = ( + jnp.log(1.0 / (1.0 - discount)) - lo_h + ) / max(hi_h - lo_h, 1e-8) + angle = unit[:, None] * frequencies[None, :] + return jnp.concatenate([jnp.sin(angle), jnp.cos(angle)], axis=-1) + + def sample_with_noise(state, action, occupancy_goal, noise, discount): + batch, samples, _ = noise.shape + condition = jnp.concatenate( + [ + state, + action, + occupancy_goal, + discount_features_jax(discount), + ], + axis=-1, + ) + condition = (condition - condition_mean_j) / condition_std_j + repeated_condition = jnp.repeat(condition, samples, axis=0) + latent = noise.reshape(batch * samples, z_base.shape[1]) + if occupancy_model == "flow": + dt = 1.0 / sample_steps + + def flow_step(current, index): + time = jnp.full( + (batch * samples,), + index.astype(jnp.float32) * dt, + ) + velocity = occupancy_def.apply( + occupancy_ema, current, time, repeated_condition) + return current + dt * velocity, None + + latent, _ = jax.lax.scan( + flow_step, latent, jnp.arange(sample_steps)) + else: + def diffusion_step(current, index): + time_now = schedule_now[index] + time_next = schedule_next[index] + alpha_now = abar[time_now - 1] + alpha_next = jnp.where( + time_next > 0, + abar[jnp.maximum(time_next - 1, 0)], + 1.0, + ) + epsilon = jnp.clip( + occupancy_def.apply( + occupancy_ema, + current, + jnp.full( + (batch * samples,), + time_now.astype(jnp.float32) / OCC_T, + ), + repeated_condition, + ), + -6.0, + 6.0, + ) + clean = ( + current - jnp.sqrt(1.0 - alpha_now) * epsilon + ) / jnp.sqrt(jnp.maximum(alpha_now, 1e-8)) + return ( + jnp.sqrt(alpha_next) * clean + + jnp.sqrt(1.0 - alpha_next) * epsilon + ), None + + latent, _ = jax.lax.scan( + diffusion_step, latent, jnp.arange(len(schedule))) + return ( + latent.reshape(batch, samples, z_base.shape[1]) + * target_std_j + + target_mean_j + ) + + def direct_q( + state, action, occupancy_goal, reward_goal, noise, discount): + future = sample_with_noise( + state, action, occupancy_goal, noise, discount) + batch, samples, zdim = future.shape + repeated_reward_goal = jnp.repeat( + reward_goal, samples, axis=0) + logits = reader_logit( + future.reshape(batch * samples, zdim), + repeated_reward_goal, + ).reshape(batch, samples) + return jax.nn.sigmoid(logits).mean(axis=-1) + + direct_q_jit = jax.jit(direct_q) + base_noise = rng.standard_normal( + (args.rows, args.samples, z_base.shape[1])).astype(np.float32) + noise_flat = np.repeat( + base_noise[:, None, :, :], action_count, axis=1).reshape( + -1, args.samples, z_base.shape[1]) + occupancy_goal_flat = np.repeat( + occupancy_goals[:, None, :], action_count, axis=1).reshape( + -1, occupancy_goals.shape[1]) + reward_goal_flat = np.repeat( + reward_goals[:, None, :], action_count, axis=1).reshape( + -1, reward_goals.shape[1]) + + discounts = _discount_grid( + meta, args.horizons, args.horizon_points) + per_horizon = [] + task_direct = None + for discount in discounts: + discount_flat = np.full( + (args.rows * action_count,), discount, np.float32) + direct = np.asarray(direct_q_jit( + jnp.asarray(state_flat), + jnp.asarray(action_flat), + jnp.asarray(occupancy_goal_flat), + jnp.asarray(reward_goal_flat), + jnp.asarray(noise_flat), + jnp.asarray(discount_flat), + )).reshape(args.rows, action_count) + if np.isclose(discount, gamma, atol=1e-7): + task_direct = direct + per_horizon.append({ + "gamma": float(discount), + "effective_horizon": float(1.0 / (1.0 - discount)), + "is_task_gamma": bool(np.isclose( + discount, gamma, atol=1e-7)), + "direct_q_data_mean": float(direct[:, 0].mean()), + "direct_q_actor_mean": float(direct[:, -1].mean()), + "direct_q_actor_minus_data_mean": float( + np.mean(direct[:, -1] - direct[:, 0])), + "direct_prefers_actor_rate": float(np.mean( + direct[:, -1] > direct[:, 0])), + "live_scorer_fidelity_local": _fidelity( + scorer_live[:, :LOCAL_ACTIONS], + direct[:, :LOCAL_ACTIONS]), + "ema_scorer_fidelity_local": _fidelity( + scorer_ema[:, :LOCAL_ACTIONS], + direct[:, :LOCAL_ACTIONS]), + "live_local_ranking": _ranking_metrics( + direct[:, :LOCAL_ACTIONS], + scorer_live[:, :LOCAL_ACTIONS]), + "ema_local_ranking": _ranking_metrics( + direct[:, :LOCAL_ACTIONS], + scorer_ema[:, :LOCAL_ACTIONS]), + }) + assert task_direct is not None, "discount grid omitted task gamma" + + action_sd = actions.std(axis=0) + 1e-6 + action_l2 = np.linalg.norm(actor_action - actions[rows], axis=1) + normalized_action_l2 = np.linalg.norm( + (actor_action - actions[rows]) / action_sd, axis=1) + action_low = np.quantile(actions, 0.01, axis=0) + action_high = np.quantile(actions, 0.99, axis=0) + outside = (actor_action < action_low) | (actor_action > action_high) + + advantage = scorer_live[:, 0] - values + transformed_advantage = advantage.copy() + if bool(meta.get("adv_norm")): + transformed_advantage = ( + transformed_advantage - transformed_advantage.mean() + ) / (transformed_advantage.std() + 1e-6) + raw_weight = np.exp(np.minimum( + float(meta["alpha"]) * transformed_advantage, + np.log(100.0), + )) + actor_after_reached = checkpoint_step >= int(meta["actor_after"]) + effective_weight = ( + raw_weight if actor_after_reached else np.ones_like(raw_weight)) + weight_sum = float(effective_weight.sum()) + normalized_ess = float( + weight_sum ** 2 + / max(float(np.sum(effective_weight ** 2)) * len(effective_weight), + 1e-12)) + top_count = max(int(np.ceil(0.1 * len(effective_weight))), 1) + top_weight_share = float( + np.sort(effective_weight)[-top_count:].sum() + / max(weight_sum, 1e-12)) + + awr = None + if meta["actor_loss"] == "awr_distill": + awr = { + "alpha": float(meta["alpha"]), + "expectile": float(meta["expectile"]), + "adv_norm": bool(meta.get("adv_norm")), + "actor_after": int(meta["actor_after"]), + "actor_after_reached": actor_after_reached, + "value": _summary(values), + "advantage_q_live_min_minus_value": _summary(advantage), + "transformed_advantage": _summary(transformed_advantage), + "raw_weight": _summary(raw_weight), + "effective_weight": _summary(effective_weight), + "normalized_effective_sample_size": normalized_ess, + "top_10pct_weight_mass": top_weight_share, + "fraction_at_clip_100": float(np.mean(raw_weight >= 100.0 - 1e-5)), + } + + actor_action_support_metrics = { + "enabled": actor_action_support_enabled, + "scorer_support_start_step": ( + int(meta["distill_actor_action_support_start_step"]) + if actor_action_support_enabled else None), + "actor_q_gradient_start_step": ( + int(meta["actor_q_gradient_start_step"]) + if actor_action_support_enabled else None), + "scorer_support_active_at_checkpoint": bool( + actor_action_support_enabled + and checkpoint_step >= int( + meta["distill_actor_action_support_start_step"])), + "actor_q_gradient_active_at_checkpoint": bool( + actor_action_support_enabled + and checkpoint_step >= int(meta["actor_q_gradient_start_step"])), + "mode_action_count": 1 if actor_action_support_enabled else 0, + "local_action_k": actor_action_local_k, + "local_action_sigma": ( + actor_action_local_sigma + if actor_action_support_enabled else None), + "pointwise_weight": float(meta.get( + "distill_actor_action_pointwise_weight", 0.0)), + "pairwise_weight": float(meta.get( + "distill_actor_action_pairwise_weight", 0.0)), + "pointwise_candidate_count": int(meta.get( + "distill_actor_action_candidate_count", 0)), + "pairwise_candidate_count_including_behavior": int(meta.get( + "distill_actor_action_pairwise_candidate_count", 0)), + "behavior_action_is_pairwise_reference": actor_action_support_enabled, + "common_occupancy_random_numbers": bool(meta.get( + "distill_actor_action_common_random_numbers", False)), + "target_source": meta.get("distill_actor_action_target_source"), + "composed_occupancy_target": bool(meta.get( + "distill_actor_action_composed_occupancy", False)), + "actor_actions_are_stop_gradient_targets": ( + actor_action_support_enabled), + "updates_occupancy": bool(meta.get( + "distill_actor_action_updates_occupancy", False)), + "loss_reduction": meta.get( + "distill_actor_action_loss_reduction", "disabled"), + "diagnostic_uses_common_occupancy_noise": True, + "live_point_fidelity_mode_and_local": None, + "ema_point_fidelity_mode_and_local": None, + "live_pairwise_gap_fidelity_with_behavior": None, + "ema_pairwise_gap_fidelity_with_behavior": None, + "live_ranking_with_behavior": None, + "ema_ranking_with_behavior": None, + } + if actor_action_support_enabled: + actor_point_indices = actor_support_indices[1:] + actor_action_support_metrics.update({ + "live_point_fidelity_mode_and_local": _fidelity( + scorer_live[:, actor_point_indices], + task_direct[:, actor_point_indices]), + "ema_point_fidelity_mode_and_local": _fidelity( + scorer_ema[:, actor_point_indices], + task_direct[:, actor_point_indices]), + "live_pairwise_gap_fidelity_with_behavior": + _pairwise_gap_metrics( + task_direct[:, actor_support_indices], + scorer_live[:, actor_support_indices]), + "ema_pairwise_gap_fidelity_with_behavior": + _pairwise_gap_metrics( + task_direct[:, actor_support_indices], + scorer_ema[:, actor_support_indices]), + "live_ranking_with_behavior": _ranking_metrics( + task_direct[:, actor_support_indices], + scorer_live[:, actor_support_indices]), + "ema_ranking_with_behavior": _ranking_metrics( + task_direct[:, actor_support_indices], + scorer_ema[:, actor_support_indices]), + }) + + metrics = { + "audit": "visual_rsm_supervised_policy_extraction", + "audit_split": "fixed_trailing_episode_slice", + "checkpoint": os.path.abspath(args.ckpt), + "checkpoint_step": checkpoint_step, + "actor_source": args.actor, + "rows": int(args.rows), + "samples_per_condition": int(args.samples), + "episodes_requested": int(args.episodes), + "episodes_used": int(len(trailing)), + "seed": int(args.seed), + "fairness": fairness, + "artifact_contract": { + "latent": latent_path, + "reward_reader": reader_path, + "latent_arrays_available": available_arrays, + "latent_arrays_read": ["z", "state_h", "actions", "terminals"], + "forbidden_arrays_read": [], + "reader": reader_meta, + }, + "representation_roles": { + "latent_update": latent_update, + "state_feature": meta["state_feature"], + "actor_goal_feature": meta["actor_goal_feature"], + "occupancy_goal_feature": meta["occupancy_goal_feature"], + "future_feature": meta["future_feature"], + "reward_goal_feature": meta["reward_goal_feature"], + "state_dim": int(states.shape[1]), + "actor_goal_dim": int(actor_goals.shape[1]), + "occupancy_goal_dim": int(occupancy_goals.shape[1]), + "reward_goal_dim": int(reward_goals.shape[1]), + }, + "policy_extraction": { + "actor_loss": meta["actor_loss"], + "distill_actor_goals": bool(meta.get("distill_actor_goals")), + "distill_goal_loss_reduction": meta.get( + "distill_goal_loss_reduction"), + "distill_actor_actions": actor_action_support_enabled, + "distill_actor_action_local_k": actor_action_local_k, + "distill_actor_action_sigma": ( + actor_action_local_sigma + if actor_action_support_enabled else None), + "distill_actor_action_pairwise_weight": float(meta.get( + "distill_actor_action_pairwise_weight", 0.0)), + "distill_actor_action_support_start_step": meta.get( + "distill_actor_action_support_start_step"), + "distill_actor_action_composed_occupancy": bool(meta.get( + "distill_actor_action_composed_occupancy", False)), + "actor_q_gradient_start_step": meta.get( + "actor_q_gradient_start_step"), + "occupancy_and_actor_jointly_updated": bool( + meta.get("occupancy_and_actor_jointly_updated")), + "joint_update_semantics": meta.get("joint_update_semantics"), + "occupancy_training_policy": meta.get( + "occupancy_training_policy"), + "actor_gradient_updates_occupancy": bool( + meta.get("actor_gradient_updates_occupancy", False)), + "occupancy_gradient_updates_actor": bool( + meta.get("occupancy_gradient_updates_actor", False)), + "critic_target_source": meta["critic_target_source"], + "uses_td_or_bootstrap": False, + "alpha": float(meta["alpha"]), + "expectile": float(meta["expectile"]), + "actor_after": int(meta["actor_after"]), + "adv_norm": bool(meta.get("adv_norm")), + }, + "occupancy": { + "model": occupancy_model, + "hidden": hidden, + "layers": layers, + "sample_steps": sample_steps, + "normalization": normalization_contract, + "actor_query_anti_exploitation": { + key: meta.get(key) for key in ( + "occ_action_contrast_weight", + "occ_action_contrast_margin", + "occ_action_negative", + "occ_action_negative_sigma", + "occ_action_negative_local_k", + "occ_action_negative_candidate_count", + "occ_action_negative_policy", + "occ_action_negative_actor_source", + "occ_action_negative_support_start_step", + "occ_action_negative_actions_stop_gradient", + "occ_action_negative_common_random_numbers", + "occ_action_negative_updates_actor", + "occ_action_negative_counterfactual_target", + "occ_action_negative_interpretation", + ) + }, + "discount_sampling": { + key: meta.get(key) for key in ( + "gamma_sampler", + "gamma_task_fraction", + "gamma_horizons", + "gamma_aux_discounts", + "gamma_batch_allocation", + "gamma_task_rows_per_occ_batch", + "gamma_aux_rows_per_occ_batch", + "gamma_sampling_importance_weighted", + "gamma_normalization", + "gamma_encoding_lo", + "gamma_encoding_hi", + "condition_normalizer_probe_size", + "condition_normalizer_seed", + "condition_normalizer_goal_sampler", + ) + }, + }, + "integrated_reward_target": { + "target": "index", + "index_delta": int(reader_meta["index_delta"]), + "semantics": _index_reward_semantics( + int(reader_meta["index_delta"])), + "strict_instant_reward": ( + int(reader_meta["index_delta"]) == 0), + "checkpoint_declared_critic_target_source": meta[ + "critic_target_source"], + "checkpoint_target_label_exact": ( + meta["critic_target_source"] == ( + "ema_occupancy_instant_index_reward_expectation" + if int(reader_meta["index_delta"]) == 0 + else "ema_occupancy_within_" + f"{int(reader_meta['index_delta'])}_step_" + "index_reward_expectation")), + "all_direct_q_and_fidelity_metrics_use_this_target": True, + }, + "task_gamma_scalar_fidelity": { + "gamma": gamma, + "live_data_actions": _fidelity( + scorer_live[:, 0], task_direct[:, 0]), + "ema_data_actions": _fidelity( + scorer_ema[:, 0], task_direct[:, 0]), + "live_local_candidates": _fidelity( + scorer_live[:, :LOCAL_ACTIONS], + task_direct[:, :LOCAL_ACTIONS]), + "ema_local_candidates": _fidelity( + scorer_ema[:, :LOCAL_ACTIONS], + task_direct[:, :LOCAL_ACTIONS]), + "live_data_and_actor": _fidelity( + scorer_live[:, [0, -1]], + task_direct[:, [0, -1]]), + "ema_data_and_actor": _fidelity( + scorer_ema[:, [0, -1]], + task_direct[:, [0, -1]]), + }, + "task_gamma_local_action_ranking": { + "candidate_count": LOCAL_ACTIONS, + "sigma": float(args.local_sigma), + "common_base_noise": True, + "live": _ranking_metrics( + task_direct[:, :LOCAL_ACTIONS], + scorer_live[:, :LOCAL_ACTIONS]), + "ema": _ranking_metrics( + task_direct[:, :LOCAL_ACTIONS], + scorer_ema[:, :LOCAL_ACTIONS]), + }, + "actor_action_scorer_support": actor_action_support_metrics, + "data_actor": { + "direct_q_data": _summary(task_direct[:, 0]), + "direct_q_actor": _summary(task_direct[:, -1]), + "direct_q_actor_minus_data": _summary( + task_direct[:, -1] - task_direct[:, 0]), + "direct_prefers_actor_rate": float(np.mean( + task_direct[:, -1] > task_direct[:, 0])), + "live_scorer_q_data": _summary(scorer_live[:, 0]), + "live_scorer_q_actor": _summary(scorer_live[:, -1]), + "live_scorer_actor_minus_data": _summary( + scorer_live[:, -1] - scorer_live[:, 0]), + "live_scorer_prefers_actor_rate": float(np.mean( + scorer_live[:, -1] > scorer_live[:, 0])), + "ema_scorer_q_data": _summary(scorer_ema[:, 0]), + "ema_scorer_q_actor": _summary(scorer_ema[:, -1]), + "l2_to_paired_behavior_action": _summary(action_l2), + "l2_to_paired_behavior_action_normalized_by_action_sd": _summary( + normalized_action_l2), + "actor_component_outside_dataset_p01_p99_fraction": float( + outside.mean()), + "actor_row_outside_dataset_p01_p99_rate": float( + np.any(outside, axis=1).mean()), + "actor_action_saturation_fraction": float( + np.mean(np.abs(actor_action) > 0.99)), + }, + "scorer_ensemble_gap": { + "live_all_candidates": _gap_metrics(scorer_heads_live), + "live_data_actions": _gap_metrics( + scorer_heads_live[:, :, 0]), + "live_actor_actions": _gap_metrics( + scorer_heads_live[:, :, -1]), + "ema_all_candidates": _gap_metrics(scorer_heads_ema), + "ema_data_actions": _gap_metrics( + scorer_heads_ema[:, :, 0]), + "ema_actor_actions": _gap_metrics( + scorer_heads_ema[:, :, -1]), + }, + "value_and_advantage": { + "value": _summary(values), + "live_data_q_minus_value": _summary(advantage), + "awr": awr, + }, + "per_horizon": per_horizon, + } + out_dir = os.path.dirname(os.path.abspath(args.out)) + os.makedirs(out_dir, exist_ok=True) + with open(args.out, "w") as file: + json.dump(metrics, file, indent=2) + print(json.dumps(metrics, indent=2), flush=True) + return metrics + + +def _self_test(ogbench_impls): + """Tiny end-to-end rich-goal flow smoke with synthetic artifacts.""" + import jax + import jax.numpy as jnp + + _setup_paths(ogbench_impls) + from agents.gciql import get_config + from utils.networks import GCActor, GCValue + + rng = np.random.default_rng(7) + count, zdim, hdim, action_dim = 16, 3, 5, 2 + z = rng.normal(size=(count, zdim)).astype(np.float32) + state_h = rng.normal(size=(count, hdim)).astype(np.float32) + actions = np.clip( + rng.normal(size=(count, action_dim)), -1, 1).astype(np.float32) + terminals = np.zeros(count, bool) + terminals[[7, 15]] = True + gamma, gamma_lo = 0.99, 0.9 + cond_dim = hdim + action_dim + hdim + 2 * FOURIER_K + occupancy_def = make_model(cond_dim, zdim, 16, 2, 64) + occupancy_params = occupancy_def.init( + jax.random.PRNGKey(1), + jnp.zeros((1, zdim)), + jnp.zeros((1,)), + jnp.zeros((1, cond_dim)), + ) + config = get_config() + actor_def = GCActor( + hidden_dims=tuple(config["actor_hidden_dims"]), + action_dim=action_dim, + state_dependent_std=False, + const_std=config["const_std"], + ) + value_def = GCValue( + hidden_dims=tuple(config["value_hidden_dims"]), + layer_norm=config["layer_norm"], + ensemble=False, + ) + scorer_def = GCValue( + hidden_dims=tuple(config["value_hidden_dims"]), + layer_norm=config["layer_norm"], + ensemble=True, + ) + actor_params = actor_def.init( + jax.random.PRNGKey(2), + jnp.zeros((2, hdim)), + jnp.zeros((2, hdim)), + )["params"] + value_params = value_def.init( + jax.random.PRNGKey(3), + jnp.zeros((2, hdim)), + jnp.zeros((2, hdim)), + )["params"] + scorer_params = scorer_def.init( + jax.random.PRNGKey(4), + jnp.zeros((2, hdim)), + jnp.zeros((2, hdim)), + jnp.zeros((2, action_dim)), + )["params"] + + with tempfile.TemporaryDirectory( + prefix="visual_distill_diag_", dir="/tmp") as temp_dir: + latent_path = os.path.join(temp_dir, "latents.npz") + reader_path = os.path.join(temp_dir, "reader.npz") + checkpoint_path = os.path.join(temp_dir, "checkpoint.pkl") + output_path = os.path.join(temp_dir, "audit.json") + np.savez( + latent_path, + z=z, + state_h=state_h, + actions=actions, + terminals=terminals, + proprio=np.full((count, 19), np.nan, np.float32), + ) + reader_hidden = 4 + reader_rng = np.random.default_rng(11) + np.savez( + reader_path, + target=np.asarray("index"), + index_delta=np.asarray(2), + neg_gap=np.asarray(4), + zdim=np.asarray(zdim), + features=np.asarray("symmetric"), + activation=np.asarray("relu"), + **{ + "g0.kernel": reader_rng.normal( + scale=0.1, size=(4 * zdim, reader_hidden)).astype( + np.float32), + "g0.bias": np.zeros(reader_hidden, np.float32), + "g1.kernel": reader_rng.normal( + scale=0.1, size=(reader_hidden, reader_hidden)).astype( + np.float32), + "g1.bias": np.zeros(reader_hidden, np.float32), + "g2.kernel": reader_rng.normal( + scale=0.1, size=(reader_hidden, 1)).astype(np.float32), + "g2.bias": np.zeros(1, np.float32), + }, + ) + agent = ( + actor_params, None, value_params, None, + scorer_params, None, scorer_params, + ) + carry = ( + occupancy_params, None, occupancy_params, + None, None, None, agent, actor_params, + jax.random.PRNGKey(5), jnp.asarray(20), + ) + meta = { + "schema_version": 5, + "env": "visual-cube-single-play-v0", + "seed": 0, + "state_dim": hdim, + "goal_dim": hdim, + "actor_goal_dim": hdim, + "occupancy_goal_dim": hdim, + "reward_goal_dim": zdim, + "drop_proprio": True, + "goal_hidden": True, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "actor_loss": "awr_distill", + "alpha": 30.0, + "expectile": 0.7, + "actor_after": 0, + "adv_norm": False, + "policy_extraction": + "supervised_occupancy_q_distillation_awr", + "uses_td_or_bootstrap": False, + "critic_target_source": + "ema_occupancy_within_2_step_index_reward_expectation", + "occupancy_and_actor_jointly_updated": True, + "gamma": gamma, + "gamma_spectrum_lo": gamma_lo, + "discount_conditioned": True, + "discount_feature": "fourier_log_horizon", + "occupancy_model": "flow", + "occ_hidden": 16, + "occ_layers": 2, + "flow_steps": 2, + "recursion": "off", + "reward_decoder_target": "index", + "reward_decoder_index_delta": 2, + "reward_decoder_logit": False, + "latent_npz": os.path.abspath(latent_path), + "reward_decoder": os.path.abspath(reader_path), + "freeze_occupancy": False, + } + condition_mean, condition_std = _condition_stats( + state_h, actions, state_h, build_ends(terminals), meta) + occupancy_normalization = { + "cond_mean": condition_mean, + "cond_std": condition_std, + "target_mean": z.mean(axis=0).astype(np.float32), + "target_std": (z.std(axis=0) + 1e-6).astype(np.float32), + } + with open(checkpoint_path, "wb") as file: + pickle.dump({ + "carry": jax.device_get(carry), + "run_meta": meta, + "seed": 0, + "env": meta["env"], + "occupancy_normalization": occupancy_normalization, + }, file) + smoke_args = SimpleNamespace( + ckpt=checkpoint_path, + latents=latent_path, + reward_decoder=reader_path, + out=output_path, + rows=4, + samples=2, + episodes=1, + seed=3, + actor="ema", + local_sigma=0.3, + sample_steps=2, + horizon_points=1, + horizons="", + require_index_delta=2, + ogbench_impls=ogbench_impls, + ) + metrics = run_diagnostic(smoke_args) + assert metrics["fairness"]["drop_proprio"] is True + assert metrics["fairness"]["uses_td_or_bootstrap"] is False + assert metrics["fairness"]["reader_index_delta"] == 2 + assert metrics["fairness"]["strict_instant_reward_reader"] is False + assert metrics["artifact_contract"]["forbidden_arrays_read"] == [] + assert metrics["representation_roles"]["actor_goal_dim"] == hdim + assert metrics["representation_roles"]["reward_goal_dim"] == zdim + assert metrics["occupancy"]["normalization"][ + "exact_checkpoint_statistics"] is True + assert metrics["actor_action_scorer_support"]["enabled"] is False + assert len(metrics["per_horizon"]) == 1 + legacy_contract = _legacy_normalizer_contract(meta) + assert legacy_contract["recipe"] == ( + "legacy_task_gamma_plus_log_uniform_horizon_mixture_p0.5") + *_, reconstructed_contract = _load_occupancy_normalization( + {}, state_h, actions, state_h, build_ends(terminals), z, meta) + assert reconstructed_contract["source"] == "legacy_reconstruction" + unsupported_sampler_meta = dict(meta) + unsupported_sampler_meta["horizon_sampler"] = "prioritized_bins" + try: + _legacy_normalizer_contract(unsupported_sampler_meta) + except AssertionError: + pass + else: + raise AssertionError( + "legacy normalizer accepted a prioritized sampler") + synthetic_reader_meta = _reader_metadata(reader_path) + enabled_meta = dict(meta) + enabled_meta.update({ + "actor_loss": "ddpgbc_distill", + "policy_extraction": + "supervised_occupancy_q_distillation_ddpgbc", + "distill_actor_goals": True, + "distill_actor_actions": True, + "distill_actor_action_local_k": 2, + "distill_actor_action_sigma": 0.3, + "distill_actor_action_pairwise_weight": 1.0, + "distill_actor_action_pointwise_weight": 1.0, + "distill_actor_action_candidate_count": 3, + "distill_actor_action_pairwise_candidate_count": 4, + "distill_actor_action_common_random_numbers": True, + "distill_actor_action_policy": + "stop_gradient_current_actor_mode_plus_local_gaussian", + "distill_actor_action_target_source": + "ema_occupancy_within_2_step_index_reward_expectation", + "distill_actor_action_composed_occupancy": False, + "distill_actor_action_support_start_step": 0, + "actor_q_gradient_start_step": 10, + "actor_after": 10, + "distill_actor_action_loss_reduction": + "normalized_point_and_pairwise_then_mean_with_existing_support", + "distill_actor_action_updates_occupancy": False, + }) + enabled_fairness = _assert_fair_checkpoint( + enabled_meta, synthetic_reader_meta) + assert enabled_fairness["actor_action_scorer_support"] is True + actor_occ_meta = dict(enabled_meta) + actor_occ_meta.update({ + "occ_action_contrast_weight": 0.5, + "occ_action_negative": "actor_local", + "occ_action_negative_local_k": 2, + "occ_action_negative_candidate_count": 3, + "occ_action_negative_policy": + "stop_gradient_live_preupdate_actor_mode_plus_local_gaussian", + "occ_action_negative_actor_source": "live_preupdate_actor", + "occ_action_negative_support_start_step": 0, + "occ_action_negative_actions_stop_gradient": True, + "occ_action_negative_common_random_numbers": True, + "occ_action_negative_updates_actor": False, + "occupancy_gradient_updates_actor": False, + "occ_action_negative_counterfactual_target": False, + "occ_action_negative_interpretation": + "anti_exploitation_likelihood_ranking_not_counterfactual_" + "occupancy", + "occupancy_supervision": + "monte_carlo_geometric_futures_plus_detached_actor_query_" + "likelihood_ranking", + "occupancy_training_policy": + "offline_behavior_futures_with_detached_live_actor_query_" + "negatives", + "joint_update_semantics": + "same_fused_step_occupancy_uses_detached_live_preupdate_" + "actor_queries", + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": False, + }) + actor_occ_fairness = _assert_fair_checkpoint( + actor_occ_meta, synthetic_reader_meta) + assert actor_occ_fairness[ + "actor_query_occupancy_support"] is True + invalid_actor_occ_meta = dict(actor_occ_meta) + invalid_actor_occ_meta[ + "occ_action_negative_actions_stop_gradient"] = False + try: + _assert_fair_checkpoint( + invalid_actor_occ_meta, synthetic_reader_meta) + except AssertionError: + pass + else: + raise AssertionError( + "fairness gate accepted actor-query occupancy gradients") + invalid_support_meta = dict(enabled_meta) + invalid_support_meta["distill_actor_action_updates_occupancy"] = True + try: + _assert_fair_checkpoint( + invalid_support_meta, synthetic_reader_meta) + except AssertionError: + pass + else: + raise AssertionError( + "fairness gate accepted actor-action targets updating occupancy") + for key, forbidden_value in ( + ("drop_proprio", False), + ("discount_conditioned", False), + ("uses_td_or_bootstrap", True)): + invalid_meta = dict(meta) + invalid_meta[key] = forbidden_value + try: + _assert_fair_checkpoint(invalid_meta, synthetic_reader_meta) + except AssertionError: + pass + else: + raise AssertionError( + f"fairness gate accepted {key}={forbidden_value!r}") + negative_reader = dict(synthetic_reader_meta) + negative_reader["index_delta"] = -1 + try: + _assert_fair_checkpoint(meta, negative_reader) + except AssertionError: + pass + else: + raise AssertionError("fairness gate accepted a negative index delta") + try: + _assert_fair_checkpoint( + meta, synthetic_reader_meta, require_index_delta=0) + except AssertionError: + pass + else: + raise AssertionError("exact-delta gate accepted delta2 as delta0") + print("visual distilled-policy diagnostic self-test: PASS", flush=True) + + +def main(): + parser = _build_parser() + args = parser.parse_args() + if args.self_test: + _self_test(args.ogbench_impls) + return + run_diagnostic(args) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/diagnose_visual_extraction_sampling.py b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_extraction_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..931e3b5e9acd34c40ca759684befdae2d0c33792 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_extraction_sampling.py @@ -0,0 +1,279 @@ +"""Audit goal-support and Monte Carlo noise for visual RSM extraction. + +This diagnostic is deliberately independent of the RSM implementation and +uses only cached pixel latents, episode boundaries, and a frozen index reader. +It does not read proprioception, coordinates, simulator state, rewards, or a +temporal-difference target. + +It answers two policy-extraction questions: + +1. How different is the reference GCIQL value-goal distribution from the + uniform-future actor-goal distribution? +2. For a perfect empirical discounted occupancy, how noisy is an M-sample + index-reader expectation used as a scalar-scorer target? + +The latter is a lower-bound diagnostic for the learned occupancy: it isolates +finite-sample reader noise before occupancy-model error is added. +""" + +import argparse +import json +import os + +import numpy as np + +if __package__ in (None, ""): + import sys + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) + +from ogbench_genq.genq.reward_reader import load_numpy_reward_reader + + +def _scalar_string(value): + array = np.asarray(value) + assert array.ndim == 0 + return str(array.item()) + + +def _reader(path): + probability, metadata = load_numpy_reward_reader( + path, probability=True) + assert metadata["target"] == "index", metadata["target"] + if metadata["index_delta"] is None: + metadata["index_delta"] = 0 + return probability, metadata + + +def _episode_boundaries(terminals): + terminal_ends = np.flatnonzero(terminals) + 1 + if len(terminal_ends) == 0 or terminal_ends[-1] != len(terminals): + terminal_ends = np.r_[terminal_ends, len(terminals)] + starts = np.r_[0, terminal_ends[:-1]] + ends = np.empty(len(terminals), np.int64) + for start, end in zip(starts, terminal_ends): + ends[start:end] = end + return starts, terminal_ends, ends + + +def _summary(values): + values = np.asarray(values, np.float64) + return { + "mean": float(values.mean()), + "std": float(values.std()), + "p10": float(np.quantile(values, 0.10)), + "median": float(np.median(values)), + "p90": float(np.quantile(values, 0.90)), + } + + +def _sample_goal_indices(rng, rows, ends, count, gamma): + final = ends[rows] - 1 + + first_future = np.minimum(rows + 1, final) + fraction = rng.random(count) + actor = np.rint( + first_future * fraction + final * (1.0 - fraction)).astype(np.int64) + + trajectory = np.minimum( + rows + rng.geometric(1.0 - gamma, count), final) + random_goal = rng.integers(0, len(ends), count) + use_trajectory = rng.random(count) < 0.5 / 0.8 + use_current = rng.random(count) < 0.2 + value = np.where(use_trajectory, trajectory, random_goal) + value = np.where(use_current, rows, value) + value_kind = np.where(use_current, 0, np.where(use_trajectory, 1, 2)) + return actor, value, trajectory, value_kind + + +def _distance_overlap(actor_distance, value_trajectory_distance): + largest = int(max(actor_distance.max(), value_trajectory_distance.max())) + actor_hist = np.bincount( + actor_distance, minlength=largest + 1).astype(np.float64) + value_hist = np.bincount( + value_trajectory_distance, minlength=largest + 1).astype(np.float64) + actor_hist /= actor_hist.sum() + value_hist /= value_hist.sum() + overlap = float(np.minimum(actor_hist, value_hist).sum()) + return { + "probability_overlap": overlap, + "total_variation": float(1.0 - overlap), + } + + +def _conditional_moments( + latents, rows, goal_indices, ends, gamma, reader_probability +): + means = np.empty(len(rows), np.float64) + variances = np.empty(len(rows), np.float64) + log_gamma = np.log(gamma) + for index, (row, goal) in enumerate(zip(rows, goal_indices)): + future_indices = np.arange(row, ends[row]) + if row <= goal < ends[row]: + # Match RSM's absorbing-goal occupancy construction. + future_indices = np.minimum(future_indices, goal) + offsets = np.arange(len(future_indices), dtype=np.float64) + weights = np.exp(offsets * log_gamma) + weights /= weights.sum() + goal_batch = np.repeat( + latents[goal][None], len(future_indices), axis=0) + rewards = reader_probability( + latents[future_indices], goal_batch).astype(np.float64) + mean = np.dot(weights, rewards) + means[index] = mean + variances[index] = np.dot(weights, (rewards - mean) ** 2) + return means, variances + + +def _noise_report(means, variances, sample_counts, alphas): + report = { + "q": _summary(means), + "conditional_reward_sd": _summary(np.sqrt(variances)), + "monte_carlo": {}, + } + between_condition_sd = max(float(means.std()), 1e-12) + for samples in sample_counts: + standard_error = np.sqrt(variances / samples) + rms_standard_error = float(np.sqrt(variances.mean() / samples)) + awr_noise = {} + for alpha in alphas: + log_weight_noise_rms = alpha * rms_standard_error + # If the scorer inherited all target noise independently, this is + # the log-normal effective-sample-size fraction due to noise alone. + # It is a stress indicator, not a prediction of the trained model. + awr_noise[str(alpha)] = { + "log_weight_noise_rms": float(log_weight_noise_rms), + "lognormal_ess_fraction_stress": float( + np.exp(-(log_weight_noise_rms ** 2))), + } + report["monte_carlo"][str(samples)] = { + "standard_error": _summary(standard_error), + "rms_standard_error": rms_standard_error, + "rms_noise_over_between_condition_q_sd": float( + rms_standard_error / between_condition_sd), + "awr_noise_stress": awr_noise, + } + return report + + +def run(args): + assert 0.0 < args.gamma < 1.0 + assert args.rows > 0 + assert args.support_rows > 0 + sample_counts = sorted(set(args.samples)) + alphas = sorted(set(args.alphas)) + assert sample_counts and sample_counts[0] > 0 + assert alphas and alphas[0] > 0.0 + + with np.load(args.latents, allow_pickle=False) as artifact: + available = list(artifact.files) + latents = np.asarray(artifact["z"], np.float32) + terminals = np.asarray(artifact["terminals"], bool) + reader_probability, reader_metadata = _reader(args.reward_decoder) + assert reader_metadata["zdim"] == latents.shape[1] + + starts, terminal_ends, ends = _episode_boundaries(terminals) + rng = np.random.default_rng(args.seed) + support_rows = rng.integers(0, len(latents), args.support_rows) + ( + support_actor_goals, + _support_value_goals, + support_trajectory_goals, + support_value_kind, + ) = _sample_goal_indices( + rng, support_rows, ends, args.support_rows, args.gamma) + support_actor_distance = support_actor_goals - support_rows + support_trajectory_mask = support_value_kind == 1 + support_value_trajectory_distance = ( + support_trajectory_goals[support_trajectory_mask] + - support_rows[support_trajectory_mask]) + + rows = rng.integers(0, len(latents), args.rows) + ( + actor_goals, + value_goals, + _trajectory_goals, + _value_kind, + ) = _sample_goal_indices(rng, rows, ends, args.rows, args.gamma) + + actor_means, actor_variances = _conditional_moments( + latents, rows, actor_goals, ends, args.gamma, reader_probability) + value_means, value_variances = _conditional_moments( + latents, rows, value_goals, ends, args.gamma, reader_probability) + + result = { + "audit": "visual_rsm_extraction_sampling", + "strictly_pixels_only_cached_inputs": True, + "uses_td_or_bootstrap": False, + "artifacts": { + "latents": os.path.abspath(args.latents), + "reader": os.path.abspath(args.reward_decoder), + "latent_arrays_available": available, + "latent_arrays_read": ["z", "terminals"], + "forbidden_arrays_read": [], + "reader_metadata": reader_metadata, + }, + "rows": int(args.rows), + "goal_support_rows": int(args.support_rows), + "seed": int(args.seed), + "gamma": float(args.gamma), + "episodes": { + "count": int(len(terminal_ends)), + "length": _summary(terminal_ends - starts), + }, + "goal_support": { + "actor_uniform_future_distance": _summary( + support_actor_distance), + "value_trajectory_geometric_distance": _summary( + support_value_trajectory_distance), + "actor_vs_value_trajectory": _distance_overlap( + support_actor_distance, + support_value_trajectory_distance), + "value_kind_fractions": { + "current": float(np.mean(support_value_kind == 0)), + "trajectory": float(np.mean(support_value_kind == 1)), + "random": float(np.mean(support_value_kind == 2)), + }, + }, + "actor_uniform_future_targets": _noise_report( + actor_means, actor_variances, sample_counts, alphas), + "value_goal_mix_targets": _noise_report( + value_means, value_variances, sample_counts, alphas), + "interpretation": { + "monte_carlo_noise": ( + "Perfect-empirical-occupancy lower bound; learned occupancy " + "error is additional."), + "awr_noise_stress": ( + "Sensitivity if scalar-score error retained independent target " + "noise; not an estimate of final actor effective sample size."), + }, + } + if args.out: + output = os.path.abspath(args.out) + os.makedirs(os.path.dirname(output), exist_ok=True) + with open(output, "w") as file: + json.dump(result, file, indent=2) + print(json.dumps(result, indent=2), flush=True) + return result + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--latents", required=True) + parser.add_argument("--reward_decoder", required=True) + parser.add_argument("--rows", type=int, default=4096) + parser.add_argument( + "--support_rows", type=int, default=1_000_000, + help="cheap Monte Carlo rows used only for goal-horizon overlap") + parser.add_argument("--seed", type=int, default=918) + parser.add_argument("--gamma", type=float, default=0.99) + parser.add_argument( + "--samples", type=int, nargs="+", default=[4, 8, 16, 32, 64]) + parser.add_argument( + "--alphas", type=float, nargs="+", default=[3.0, 10.0, 30.0]) + parser.add_argument("--out") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/diagnose_visual_gciql.py b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_gciql.py new file mode 100644 index 0000000000000000000000000000000000000000..3f719ac94e1ab4424759c13dfc6c40df72d7569e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_gciql.py @@ -0,0 +1,248 @@ +"""Audit action ranking and policy extraction in the fair visual GCIQL control. + +The row/goal selection, eight local action candidates, perturbation scale, and +actor-versus-data diagnostics intentionally mirror +``diagnose_visual_occupancy.py``. This program uses only pixels, actions, and +trajectory boundaries from the offline dataset. It never reads simulator +coordinates or evaluates rollouts. +""" +import argparse +import json +import os +import pickle +import sys + +import numpy as np + + +ENV = "visual-cube-single-play-v0" +FORBIDDEN_KEYS = frozenset({"qpos", "qvel", "button_states", "coordinates"}) + + +def _corr(x, y): + from scipy.stats import spearmanr + + value = spearmanr(np.asarray(x), np.asarray(y)).statistic + return float(value) if np.isfinite(value) else 0.0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--checkpoint", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--rows", type=int, default=256) + ap.add_argument("--episodes", type=int, default=100) + ap.add_argument("--candidates", type=int, default=8) + ap.add_argument("--action_sigma", type=float, default=0.3) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--ogbench_impls", + default=os.environ.get( + "OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls"))) + args = ap.parse_args() + + reference_root = os.path.abspath(os.path.expanduser(args.ogbench_impls)) + sys.path.insert(0, reference_root) + + import jax + import jax.numpy as jnp + import ogbench + from agents.gciql import GCIQLAgent + from utils.datasets import Dataset, GCDataset + + with open(args.checkpoint, "rb") as f: + payload = pickle.load(f) + assert payload["format"] == "visual_gciql_params_v1" + meta = payload["run_meta"] + assert meta["pixels_only"] is True + assert meta["drop_proprio"] is True + assert meta["simulator_state_used"] is False + assert meta["coordinate_used"] is False + assert meta["env"] == ENV + + # Import here to keep the exact config definition shared with the trainer. + from ogbench_genq.genq.train_visual_gciql_control import exact_visual_config + + config = exact_visual_config() + assert dict(config) == payload["config"] + train_raw, _ = ogbench.make_env_and_datasets( + ENV, compact_dataset=True, dataset_only=True, add_info=False) + assert not (set(train_raw) & FORBIDDEN_KEYS) + assert set(train_raw) == {"observations", "actions", "terminals", "valids"} + observations = np.asarray(train_raw["observations"]) + actions = np.clip(np.asarray(train_raw["actions"], np.float32), -1.0, 1.0) + terminals = np.asarray(train_raw["terminals"], bool) + assert observations.dtype == np.uint8 and observations.ndim == 4 + + dataset = GCDataset(Dataset.create(**train_raw), config) + example = dataset.sample(2, evaluation=True) + agent = GCIQLAgent.create( + int(meta["seed"]), example["observations"], example["actions"], config) + agent = agent.replace(network=agent.network.replace(params=payload["params"])) + agent = jax.device_put(agent) + + # Copy diagnose_visual_occupancy.py's row selection exactly, including its + # interpretation of OGBench compact-dataset terminal markers. + episode_ends = np.flatnonzero(terminals) + 1 + episode_starts = np.r_[0, episode_ends[:-1]] + lo_ep = max(len(episode_ends) - args.episodes, 0) + candidate_rows = np.concatenate([ + np.arange(episode_starts[e], episode_ends[e] - 1) + for e in range(lo_ep, len(episode_ends)) + ]) + rng = np.random.default_rng(args.seed + 918) + rows = rng.choice(candidate_rows, size=args.rows, replace=False) + + # Copy diagnose_visual_occupancy.py's uniformly-future goal construction. + end_of = np.zeros(len(terminals), dtype=np.int64) + prev = 0 + for terminal_idx in np.flatnonzero(terminals): + end_of[prev:terminal_idx + 1] = terminal_idx + 1 + prev = terminal_idx + 1 + if prev < len(terminals): + end_of[prev:] = len(terminals) + span = np.maximum(end_of[rows] - rows - 1, 1) + goals_idx = rows + 1 + (rng.random(args.rows) * span).astype(np.int64) + goals_idx = np.minimum(goals_idx, end_of[rows] - 1) + + obs = jnp.asarray(observations[rows]) + goals = jnp.asarray(observations[goals_idx]) + data_actions = jnp.asarray(actions[rows]) + + @jax.jit + def critic_q(ob, goal, act): + q1, q2 = agent.network.select("critic")(ob, goal, act) + return jnp.minimum(q1, q2) + + @jax.jit + def target_q(ob, goal, act): + q1, q2 = agent.network.select("target_critic")(ob, goal, act) + return jnp.minimum(q1, q2) + + @jax.jit + def actor_mode(ob, goal): + dist = agent.network.select("actor")(ob, goal, temperature=0.0) + return jnp.clip(dist.mode(), -1.0, 1.0) + + @jax.jit + def value(ob, goal): + return agent.network.select("value")(ob, goal) + + q_data = np.asarray(critic_q(obs, goals, data_actions)) + tq_data = np.asarray(target_q(obs, goals, data_actions)) + v_data = np.asarray(value(obs, goals)) + actor_actions = np.asarray(actor_mode(obs, goals)) + q_actor = np.asarray( + critic_q(obs, goals, jnp.asarray(actor_actions))) + tq_actor = np.asarray( + target_q(obs, goals, jnp.asarray(actor_actions))) + + k = args.candidates + a_dim = actions.shape[-1] + local_actions = np.clip( + actions[rows, None, :] + args.action_sigma * rng.standard_normal( + (args.rows, k, a_dim)), + -1.0, + 1.0, + ).astype(np.float32) + local_actions[:, 0] = actions[rows] + obs_flat = np.repeat( + observations[rows, None], k, axis=1).reshape( + args.rows * k, *observations.shape[1:]) + goals_flat = np.repeat( + observations[goals_idx, None], k, axis=1).reshape( + args.rows * k, *observations.shape[1:]) + q_candidates = np.asarray(critic_q( + jnp.asarray(obs_flat), + jnp.asarray(goals_flat), + jnp.asarray(local_actions.reshape(-1, a_dim)), + )).reshape(args.rows, k) + tq_candidates = np.asarray(target_q( + jnp.asarray(obs_flat), + jnp.asarray(goals_flat), + jnp.asarray(local_actions.reshape(-1, a_dim)), + )).reshape(args.rows, k) + + @jax.jit + def action_gradient(act): + def q_sum(aa): + return critic_q(obs, goals, aa).sum() + return jax.grad(q_sum)(act) + + gradients = np.asarray(action_gradient(data_actions)) + ranks = 1 + np.sum(q_candidates[:, 1:] > q_candidates[:, :1], axis=1) + target_ranks = 1 + np.sum( + tq_candidates[:, 1:] > tq_candidates[:, :1], axis=1) + + metrics = { + "method": "GCIQL", + "checkpoint": os.path.abspath(args.checkpoint), + "checkpoint_step": int(payload["step"]), + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": int(args.rows), + "episodes": int(args.episodes), + "pixels_only": True, + "drop_proprio": True, + "simulator_state_used": False, + "coordinate_used": False, + "dataset_keys": sorted(train_raw), + "network_input_contract": meta["network_input_contract"], + "rsm_consumes_td_outputs": False, + "local_candidate_contract": { + "count": int(k), + "action_sigma": float(args.action_sigma), + "candidate_0": "recorded_dataset_action", + "other_candidates": "clipped_local_gaussian_perturbations", + "random_seed": int(args.seed + 918), + }, + "online_critic_action_signal": { + "data_action_best_of_8_rate": float(np.mean(ranks == 1)), + "data_action_top2_of_8_rate": float(np.mean(ranks <= 2)), + "data_action_rank_mean": float(ranks.mean()), + "local_candidate_q_span_mean": float(np.mean( + q_candidates.max(1) - q_candidates.min(1))), + "q_action_gradient_norm_mean": float( + np.linalg.norm(gradients, axis=1).mean()), + "q_action_gradient_norm_median": float( + np.median(np.linalg.norm(gradients, axis=1))), + }, + "target_critic_action_signal": { + "data_action_best_of_8_rate": float(np.mean(target_ranks == 1)), + "data_action_top2_of_8_rate": float(np.mean(target_ranks <= 2)), + "data_action_rank_mean": float(target_ranks.mean()), + "local_candidate_q_span_mean": float(np.mean( + tq_candidates.max(1) - tq_candidates.min(1))), + }, + "actor_signal": { + "data_action_l2_mean": float(np.linalg.norm( + actor_actions - actions[rows], axis=1).mean()), + "online_q_data_mean": float(q_data.mean()), + "online_q_actor_mean": float(q_actor.mean()), + "online_q_actor_minus_data_mean": float( + np.mean(q_actor - q_data)), + "online_prefers_actor_rate": float(np.mean(q_actor > q_data)), + "target_q_actor_minus_data_mean": float( + np.mean(tq_actor - tq_data)), + "target_prefers_actor_rate": float(np.mean(tq_actor > tq_data)), + "action_saturation_fraction": float( + np.mean(np.abs(actor_actions) > 0.99)), + }, + "value_mechanism": { + "value_mean": float(v_data.mean()), + "target_q_data_mean": float(tq_data.mean()), + "target_q_minus_value_mean": float( + np.mean(tq_data - v_data)), + "online_target_q_spearman_data_actions": _corr(q_data, tq_data), + "online_target_local_ranking_agreement": float(np.mean( + np.argmax(q_candidates, axis=1) + == np.argmax(tq_candidates, axis=1))), + }, + "run_meta": meta, + } + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as f: + json.dump(metrics, f, indent=2) + print(json.dumps(metrics, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/diagnose_visual_occupancy.py b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_occupancy.py new file mode 100644 index 0000000000000000000000000000000000000000..aa3c4abad0ee1d4388ec96b1d67c93f78fbb5acc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_occupancy.py @@ -0,0 +1,397 @@ +"""Control-relevant diagnostics for the fair pixels-only visual occupancy. + +The representation and occupancy are trained without coordinates or reward. +This audit may use the frozen goal-return reader as a diagnostic only. It +separates four properties that an occupancy needs for policy improvement: + + 1. held-out-tuple diffusion-denoising or flow-matching fit; + 2. future-latent moment fit; + 3. reward-under-occupancy calibration on behavior actions; and + 4. sensitivity to the initial action. + +The current full checkpoint was trained on every episode, so ``--episodes`` +selects a deterministic episode slice, not a genuinely unseen test set. +Occupancy-only sweeps use an episode split and report that distinction. +""" +import argparse +import json +import os +import pickle +import sys + +import numpy as np + +if __package__ in (None, ""): + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) + +from ogbench_genq.genq.train_genq_jax import build_ends, cosine_abar, make_model +from ogbench_genq.genq.reward_reader import load_jax_reward_reader + + +GAMMA = 0.99 +OCC_T = 100 + + +def _corr(x, y): + from scipy.stats import spearmanr + r = spearmanr(np.asarray(x), np.asarray(y)).statistic + return float(r) if np.isfinite(r) else 0.0 + + +def _reader(npz_path): + return load_jax_reward_reader(npz_path) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--ckpt", required=True) + ap.add_argument("--latents", required=True) + ap.add_argument("--reward_decoder", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--rows", type=int, default=256) + ap.add_argument("--samples", type=int, default=32) + ap.add_argument("--episodes", type=int, default=100, + help="deterministic trailing episode slice") + ap.add_argument("--occupancy_model", + choices=["auto", "diffusion", "flow"], default="auto") + ap.add_argument("--hidden", type=int, default=0, + help="model width; 0 reads the checkpoint metadata") + ap.add_argument("--layers", type=int, default=0, + help="model depth; 0 reads the checkpoint metadata") + ap.add_argument("--time_dim", type=int, default=64) + ap.add_argument("--sample_steps", type=int, default=0, + help="diffusion/ODE integration steps; 0 reads metadata") + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + import jax + import jax.numpy as jnp + + ld = np.load(args.latents) + z_base = np.asarray(ld["z"], np.float32) + actions = np.clip(np.asarray(ld["actions"], np.float32), -1.0, 1.0) + terminals = np.asarray(ld["terminals"], bool) + ends = build_ends(terminals) + episode_ends = np.flatnonzero(terminals) + 1 + episode_starts = np.r_[0, episode_ends[:-1]] + n_ep = len(episode_ends) + + with open(args.ckpt, "rb") as f: + blob = pickle.load(f) + meta = blob.get("run_meta", {}) + assert meta.get("drop_proprio") is True, "diagnostic requires pixels-only checkpoint" + state_dim = int(meta.get("state_dim", -1)) + if state_dim == z_base.shape[1]: + state_base = z_base + state_feature = "goal_latent" + elif "state_h" in ld.files and state_dim == ld["state_h"].shape[1]: + state_base = np.asarray(ld["state_h"], np.float32) + state_feature = "encoder_hidden" + else: + raise AssertionError( + f"checkpoint state_dim={state_dim} matches neither z " + f"({z_base.shape[1]}) nor state_h") + assert float(meta.get("gamma", GAMMA)) == GAMMA + occ_ema = jax.device_put(blob["carry"][2]) + latent_update = meta.get("latent_update", "frozen") + z = z_base + state = state_base + if latent_update == "adapter": + lp = jax.device_put(blob["carry"][12]) + + @jax.jit + def apply_adapter(zz): + h = jax.nn.relu(zz @ lp["a0.kernel"] + lp["a0.bias"]) + return zz + h @ lp["a1.kernel"] + lp["a1.bias"] + + z = np.asarray(apply_adapter(jnp.asarray(z_base))) + state = z + occupancy_model = ( + meta.get("occupancy_model", "diffusion") + if args.occupancy_model == "auto" else args.occupancy_model) + hidden = args.hidden or int(meta.get("occ_hidden", 256)) + layers = args.layers or int(meta.get("occ_layers", 3)) + sample_steps = args.sample_steps or int(meta.get("flow_steps", 25)) + + n_z = z.shape[1] + n_state = state.shape[1] + a_dim = actions.shape[1] + cond_dim = n_state + n_z + a_dim + model = make_model(cond_dim, n_z, hidden, layers, args.time_dim) + abar = jnp.asarray(cosine_abar(OCC_T)) + # rsm.py fixes target standardization and condition normalization before + # joint residual adaptation begins, so both statistics remain in the base + # frozen-latent coordinates even when final values are adapted. + z_mu = jnp.asarray(z_base.mean(0)) + z_sd = jnp.asarray(z_base.std(0) + 1e-6) + + # Reproduce rsm.py's deterministic condition-normalization probe exactly. + norm_rng = np.random.default_rng(int(blob.get("seed", args.seed))) + tp = norm_rng.integers(0, len(z), 20000) + gp = np.minimum(tp + norm_rng.geometric(1 - GAMMA, 20000), ends[tp] - 1) + cond_probe = np.concatenate([ + state_base[tp], actions[tp], z_base[gp]], -1) + cond_mean = jnp.asarray(cond_probe.mean(0)) + cond_std = jnp.asarray(cond_probe.std(0) + 1e-6) + + rdec_logit, rdec_meta = _reader(args.reward_decoder) + ts = np.unique(np.linspace(OCC_T, 1, sample_steps).round().astype( + np.int32))[::-1].copy() + ts_now = jnp.asarray(ts) + ts_next = jnp.asarray(np.r_[ts[1:], 0].astype(np.int32)) + + def sample_with_noise(s, a, g, noise): + """Occupancy samples with explicit common base noise.""" + b, m, _ = noise.shape + c = jnp.concatenate([s, a, g], -1) + c = (c - cond_mean) / cond_std + cc = jnp.repeat(c, m, 0) + x = noise.reshape(b * m, n_z) + + if occupancy_model == "flow": + dt = 1.0 / sample_steps + + def step(xn, ii): + tf = jnp.full((b * m,), ii.astype(jnp.float32) * dt) + return xn + dt * model.apply(occ_ema, xn, tf, cc), None + + x, _ = jax.lax.scan(step, x, jnp.arange(sample_steps)) + else: + def step(xn, ii): + tn, tx = ts_now[ii], ts_next[ii] + abn = abar[tn - 1] + abx = jnp.where(tx > 0, abar[jnp.maximum(tx - 1, 0)], 1.0) + eps_hat = jnp.clip(model.apply( + occ_ema, xn, + jnp.full((b * m,), tn.astype(jnp.float32) / OCC_T), cc), + -6.0, 6.0) + x0 = (xn - jnp.sqrt(1.0 - abn) * eps_hat) / jnp.sqrt( + jnp.maximum(abn, 1e-8)) + return (jnp.sqrt(abx) * x0 + + jnp.sqrt(1.0 - abx) * eps_hat), None + + x, _ = jax.lax.scan(step, x, jnp.arange(len(ts))) + return (x.reshape(b, m, n_z) * z_sd + z_mu) + + def q_with_noise(s, a, g, noise): + pred = sample_with_noise(s, a, g, noise) + b, m, _ = pred.shape + gg = jnp.repeat(g, m, 0) + logits = rdec_logit(pred.reshape(b * m, n_z), gg).reshape(b, m) + return jax.nn.sigmoid(logits).mean(-1), pred + + sample_jit = jax.jit(sample_with_noise) + q_jit = jax.jit(q_with_noise) + + # Trailing episodes make this deterministic and keep all rows away from + # episode boundaries. They were seen during the old full-data fit. + lo_ep = max(n_ep - args.episodes, 0) + candidate = np.concatenate([ + np.arange(episode_starts[e], episode_ends[e] - 1) + for e in range(lo_ep, n_ep) + ]) + rng = np.random.default_rng(args.seed + 918) + rows = rng.choice(candidate, size=args.rows, replace=False) + + # Actor-goal distribution: uniformly future in the same trajectory, which + # is exactly the reference visual GCIQL actor-goal sampler. + span = np.maximum(ends[rows] - rows - 1, 1) + goals_idx = rows + 1 + (rng.random(args.rows) * span).astype(np.int64) + goals_idx = np.minimum(goals_idx, ends[rows] - 1) + goals = z[goals_idx] + noise = rng.standard_normal((args.rows, args.samples, n_z)).astype(np.float32) + + s_j = jnp.asarray(state[rows]) + a_j = jnp.asarray(actions[rows]) + g_j = jnp.asarray(goals) + noise_j = jnp.asarray(noise) + q_model, pred = q_jit(s_j, a_j, g_j, noise_j) + q_model, pred = np.asarray(q_model), np.asarray(pred) + + # Reconstruct the matched GCIQL actor's deterministic mode directly from + # its checkpoint parameters. This keeps the audit standalone while + # distinguishing a bad occupancy from actor exploitation of a seemingly + # good one. + actor_ema = jax.device_put(blob["carry"][7]) + + def actor_mode(pp, ss, gg): + h = jnp.concatenate([ss, gg], -1) + ii = 0 + while f"Dense_{ii}" in pp["actor_net"]: + dense = pp["actor_net"][f"Dense_{ii}"] + h = jax.nn.gelu(h @ dense["kernel"] + dense["bias"]) + ii += 1 + mean = h @ pp["mean_net"]["kernel"] + pp["mean_net"]["bias"] + return jnp.clip(mean, -1.0, 1.0) + + actor_action = np.asarray(jax.jit(actor_mode)( + actor_ema, s_j, g_j)) + q_actor = np.asarray(q_jit( + s_j, jnp.asarray(actor_action), g_j, noise_j)[0]) + + # Exact finite-trajectory empirical *absorbing-goal* occupancy moments and + # goal return. rsm.py maps every draw at or after an in-trajectory goal to + # the goal index; its reward-targeted sampler is an importance-sampled + # implementation of this distribution, not the raw behavior continuation. + q_emp = np.empty(args.rows, np.float32) + mean_emp = np.empty((args.rows, n_z), np.float32) + var_emp = np.empty_like(mean_emp) + for bi, (t, gi) in enumerate(zip(rows, goals_idx)): + raw_k = np.arange(ends[t] - t) + mapped_idx = np.minimum(t + raw_k, gi) + fut = z[mapped_idx] + p = GAMMA ** raw_k.astype(np.float64) + p /= p.sum() + gj = np.repeat(z[gi][None], len(raw_k), 0) + logits = np.asarray(rdec_logit(jnp.asarray(fut), jnp.asarray(gj))) + rr = 1.0 / (1.0 + np.exp(-np.clip(logits, -30, 30))) + q_emp[bi] = np.sum(p * rr) + mean_emp[bi] = np.sum(p[:, None] * fut, 0) + var_emp[bi] = np.sum(p[:, None] * (fut - mean_emp[bi]) ** 2, 0) + + mean_model = pred.mean(1) + var_model = pred.var(1) + q_mae = float(np.mean(np.abs(q_model - q_emp))) + q_scale = float(np.std(q_emp)) + + # Common-random-number conditioning sensitivity. A useful model should + # change under action replacement, but correct-action calibration should + # remain better than goal/state shuffles on true tuples. + perm = rng.permutation(args.rows) + q_action_shuffle = np.asarray(q_jit( + s_j, jnp.asarray(actions[rows[perm]]), g_j, noise_j)[0]) + q_action_zero = np.asarray(q_jit( + s_j, jnp.zeros_like(a_j), g_j, noise_j)[0]) + q_state_shuffle = np.asarray(q_jit( + jnp.asarray(state[rows[perm]]), a_j, g_j, noise_j)[0]) + + # Local candidate span and gradient size diagnose whether policy + # extraction receives a usable action-ranking signal. + k_act = 8 + cand = np.clip( + actions[rows, None, :] + 0.3 * rng.standard_normal( + (args.rows, k_act, a_dim)), -1.0, 1.0).astype(np.float32) + cand[:, 0] = actions[rows] + sf = np.repeat(state[rows, None, :], k_act, 1).reshape(-1, n_state) + gf = np.repeat(goals[:, None, :], k_act, 1).reshape(-1, n_z) + nf = np.repeat(noise[:, None, :, :], k_act, 1).reshape( + -1, args.samples, n_z) + q_cand = np.asarray(q_jit( + jnp.asarray(sf), jnp.asarray(cand.reshape(-1, a_dim)), + jnp.asarray(gf), jnp.asarray(nf))[0]).reshape(args.rows, k_act) + + grad_noise = noise_j[:, :min(4, args.samples)] + + def q_sum(aa): + return q_with_noise(s_j, aa, g_j, grad_noise)[0].sum() + + action_grad = np.asarray(jax.jit(jax.grad(q_sum))(a_j)) + + # Fixed-noise held-out-tuple score. Targets follow the unbiased truncated + # geometric, without reward-targeted stratification. + u = rng.random(args.rows) + lengths = ends[rows] - rows + fmax = np.maximum(1.0 - GAMMA ** lengths, 1e-12) + kk = np.clip(np.ceil(np.log1p(-u * fmax) / np.log(GAMMA)).astype( + np.int64) - 1, 0, lengths - 1) + target = jnp.asarray(z[np.minimum(rows + kk, goals_idx)]) + tint = jnp.asarray(rng.integers(1, OCC_T + 1, args.rows), jnp.int32) + tflow = jnp.asarray(rng.random(args.rows), jnp.float32) + eps = jnp.asarray(rng.standard_normal((args.rows, n_z)), jnp.float32) + + def denoise_mse(ss, aa, gg): + c = (jnp.concatenate([ss, aa, gg], -1) - cond_mean) / cond_std + z0 = (target - z_mu) / z_sd + if occupancy_model == "flow": + zt = (1.0 - tflow[:, None]) * eps + tflow[:, None] * z0 + target_field = z0 - eps + out = model.apply(occ_ema, zt, tflow, c) + else: + ab = abar[tint - 1][:, None] + zt = jnp.sqrt(ab) * z0 + jnp.sqrt(1.0 - ab) * eps + target_field = eps + out = model.apply( + occ_ema, zt, tint.astype(jnp.float32) / OCC_T, c) + return jnp.mean((out - target_field) ** 2, axis=-1) + + denoise_jit = jax.jit(denoise_mse) + mse = np.asarray(denoise_jit(s_j, a_j, g_j)) + mse_a = np.asarray(denoise_jit( + s_j, jnp.asarray(actions[rows[perm]]), g_j)) + mse_s = np.asarray(denoise_jit( + jnp.asarray(state[rows[perm]]), a_j, g_j)) + mse_g = np.asarray(denoise_jit( + s_j, a_j, jnp.asarray(goals[perm]))) + + metrics = { + "audit_split": "trailing_episode_slice_seen_during_training", + "rows": int(args.rows), + "samples_per_condition": int(args.samples), + "occupancy_model": occupancy_model, + "latent_update": latent_update, + "state_feature": state_feature, + "model_hidden": hidden, + "model_layers": layers, + "sample_steps": sample_steps, + "reward_reader": rdec_meta, + "reward_expectation": { + "empirical_mean": float(q_emp.mean()), + "empirical_std": q_scale, + "model_mean": float(q_model.mean()), + "mae": q_mae, + "normalized_mae": q_mae / max(q_scale, 1e-8), + "spearman": _corr(q_model, q_emp), + }, + "future_moments": { + "mean_rmse_in_latent_sd": float(np.sqrt(np.mean( + ((mean_model - mean_emp) / np.asarray(z_sd)) ** 2))), + "variance_rmse_in_latent_var": float(np.sqrt(np.mean( + ((var_model - var_emp) / (np.asarray(z_sd) ** 2)) ** 2))), + "model_variance_ratio": float( + np.mean(var_model) / max(np.mean(var_emp), 1e-8)), + }, + "denoising": { + "mse": float(mse.mean()), + "action_shuffle_delta": float((mse_a - mse).mean()), + "state_shuffle_delta": float((mse_s - mse).mean()), + "goal_shuffle_delta": float((mse_g - mse).mean()), + }, + "action_signal": { + "q_common_noise_shuffle_abs_delta": float( + np.mean(np.abs(q_action_shuffle - q_model))), + "q_common_noise_zero_abs_delta": float( + np.mean(np.abs(q_action_zero - q_model))), + "local_candidate_q_span_mean": float( + np.mean(q_cand.max(1) - q_cand.min(1))), + "data_action_best_of_8_rate": float( + np.mean(np.argmax(q_cand, axis=1) == 0)), + "q_action_gradient_norm_mean": float( + np.linalg.norm(action_grad, axis=1).mean()), + "q_action_gradient_norm_median": float( + np.median(np.linalg.norm(action_grad, axis=1))), + }, + "actor_signal": { + "data_action_l2_mean": float(np.linalg.norm( + actor_action - actions[rows], axis=1).mean()), + "model_q_data_mean": float(q_model.mean()), + "model_q_actor_mean": float(q_actor.mean()), + "model_q_actor_minus_data_mean": float( + np.mean(q_actor - q_model)), + "model_prefers_actor_rate": float(np.mean(q_actor > q_model)), + "action_saturation_fraction": float( + np.mean(np.abs(actor_action) > 0.99)), + }, + "state_signal": { + "q_common_noise_shuffle_abs_delta": float( + np.mean(np.abs(q_state_shuffle - q_model))), + }, + } + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as f: + json.dump(metrics, f, indent=2) + print(json.dumps(metrics, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/diagnose_visual_pixel_scorer.py b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_pixel_scorer.py new file mode 100644 index 0000000000000000000000000000000000000000..ff452ace6e4112a3348d17d6171b00a4e0adc84e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_pixel_scorer.py @@ -0,0 +1,47 @@ +"""Strict read-only offline audit for schema-13 raw-RGB RSM scorers. + +The diagnostic delegates the direct occupancy queries to +``gate_visual_occupancy`` but tightens its data contract: + +* the checkpoint must be the fail-closed schema-13 pixels-only scorer arm; +* the rendered source opens only observations, actions, and terminals; +* the latent cache opens only z and state_h for occupancy conditioning and + frozen index-reader goals; +* reward, proprioception, simulator coordinates, and TD/bootstrap targets are + forbidden; and +* checkpoint, dataset, latent, encoder, and reader artifacts are immutable. + +The only write is the requested JSON report at ``--out``. No parameters, +optimizer state, dataset, checkpoint, or scheduler state are modified. +""" + +from ogbench_genq.genq.gate_visual_occupancy import ( + _build_parser, + run_gate, +) + + +def _configure_strict_pixel_scorer(args): + """Enable the fail-closed schema-13 data diet on parsed gate arguments.""" + args.require_pixel_scorer = True + args.strict_pixel_scorer_data_diet = True + return args + + +def main(): + parser = _build_parser() + parser.description = ( + "Read-only schema-13 raw-RGB scorer fidelity/ranking diagnostic") + args = parser.parse_args() + if args.self_test: + parser.error( + "--self_test belongs to gate_visual_occupancy; provide a " + "schema-13 checkpoint for this strict diagnostic") + metrics = run_gate(_configure_strict_pixel_scorer(args)) + assert metrics["artifact_contract"][ + "strict_pixel_scorer_data_diet"] is True + assert metrics["raw_pixel_scorer_diagnostic"] is not None + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/diagnose_visual_reward_semantics.py b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_reward_semantics.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa8d2041c67477c8d477f3ffdf49b64c2364ff3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/diagnose_visual_reward_semantics.py @@ -0,0 +1,626 @@ +"""Pixels/index-only semantic-invariance audit for visual reward readers. + +The primary gate reads only frozen compact pixel latents and episode boundaries. +It evaluates held-out temporal labels, cross-episode visual-neighbor +substitution, safe visual negatives, and pair-order symmetry. These metrics +may be used to freeze a reader recipe before any benchmark task or coordinate +diagnostic is revealed. + +An optional second, falsification-only section consumes a cache produced by +``cache_visual_eval_goal_pixels.py``. It tests the exact ``info["goal"]`` +images used by evaluation across repeated arm randomizations. It is explicitly +excluded from ``selection_gate`` and must not be used to tune or rank readers. + +No coordinate, qpos, proprioception, action, reward, or temporal-difference +target is read anywhere in this module. +""" + +import argparse +import hashlib +import json +import os +import sys + +# Goal-image encoding must stay CPU-only even on a login host with visible GPUs. +os.environ.setdefault("JAX_PLATFORMS", "cpu") +os.environ.setdefault("XLA_PYTHON_CLIENT_PREALLOCATE", "false") + +import numpy as np + +if __package__ in (None, ""): + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) + +from ogbench_genq.genq.reward_reader import load_numpy_reward_reader + + +def _scalar_string(value): + array = np.asarray(value) + if array.ndim != 0: + raise AssertionError(f"expected scalar string, got {array.shape}") + return str(array.item()) + + +def file_sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as stream: + for chunk in iter(lambda: stream.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def load_reader(path): + """Return NumPy probability function and auditable reader metadata. + + Reader parsing is centralized in ``reward_reader.py``. Canonical + ``diag_metric`` artifacts use the standardized diagonal Mahalanobis score + + bias - sum_i weight_i * ((z_i - goal_i) / scale_i) ** 2, + + with explicit ``metric_scale``, nonnegative ``metric_weight``, and + calibrated ``metric_bias``. Artifacts without ``reader_model`` retain the + exact legacy pairwise-MLP interpretation. + """ + return load_numpy_reward_reader(path, probability=True) + + +def episode_layout(terminals): + terminals = np.asarray(terminals, bool) + stops = np.flatnonzero(terminals) + 1 + if len(stops) == 0 or stops[-1] != len(terminals): + stops = np.r_[stops, len(terminals)] + starts = np.r_[0, stops[:-1]] + start_of = np.empty(len(terminals), np.int64) + end_of = np.empty(len(terminals), np.int64) + episode_of = np.empty(len(terminals), np.int32) + for episode, (start, stop) in enumerate(zip(starts, stops)): + start_of[start:stop] = start + end_of[start:stop] = stop + episode_of[start:stop] = episode + return starts, stops, start_of, end_of, episode_of + + +def summary(values): + values = np.asarray(values, np.float64) + if len(values) == 0: + return {"count": 0} + return { + "count": int(len(values)), + "mean": float(values.mean()), + "std": float(values.std()), + "p10": float(np.quantile(values, 0.10)), + "median": float(np.median(values)), + "p90": float(np.quantile(values, 0.90)), + } + + +def auc(pos_scores, neg_scores): + """Mann-Whitney area under the ROC curve, including score ties.""" + from scipy.stats import rankdata + + positive = np.asarray(pos_scores, np.float64) + negative = np.asarray(neg_scores, np.float64) + values = np.r_[positive, negative] + ranks = rankdata(values, method="average") + n_pos = len(positive) + n_neg = len(negative) + statistic = ranks[:n_pos].sum() - n_pos * (n_pos + 1) / 2.0 + return float(statistic / (n_pos * n_neg)) + + +def sample_far_same_episode( + rng, rows, start_of, end_of, negative_gap +): + output = np.empty_like(rows) + for index, row in enumerate(rows.tolist()): + start = int(start_of[row]) + end = int(end_of[row]) + left_count = max(row - negative_gap - start + 1, 0) + right_start = row + negative_gap + right_count = max(end - right_start, 0) + count = left_count + right_count + if count == 0: + raise AssertionError( + f"episode [{start},{end}) has no negative at gap {negative_gap}") + choice = int(rng.integers(0, count)) + output[index] = ( + start + choice + if choice < left_count + else right_start + choice - left_count) + return output + + +def cross_episode_neighbors( + latents, rows, episode_of, support_indices, k, rng +): + """Retrieve visual neighbors from an opposite episode-parity bank.""" + from scipy.spatial import cKDTree + + support = np.asarray(support_indices, np.int64) + mean = latents[support].mean(axis=0) + std = latents[support].std(axis=0) + 1e-6 + normalized_support = (latents[support] - mean) / std + banks = [] + trees = [] + for parity in (1, 0): + mask = (episode_of[support] % 2) == parity + bank = support[mask] + if len(bank) < k: + raise AssertionError( + f"opposite-parity bank has {len(bank)} rows, fewer than k={k}") + banks.append(bank) + trees.append(cKDTree(normalized_support[mask])) + + normalized_rows = (latents[rows] - mean) / std + nearest = np.empty_like(rows) + spectrum = np.empty_like(rows) + for source_parity in (0, 1): + mask = np.flatnonzero((episode_of[rows] % 2) == source_parity) + if len(mask) == 0: + continue + _, neighbor_rows = trees[source_parity].query( + normalized_rows[mask], k=k, workers=-1) + if k == 1: + neighbor_rows = neighbor_rows[:, None] + nearest[mask] = banks[source_parity][neighbor_rows[:, 0]] + rank = rng.integers(0, k, len(mask)) + spectrum[mask] = banks[source_parity][ + neighbor_rows[np.arange(len(mask)), rank]] + if np.any(episode_of[nearest] == episode_of[rows]): + raise AssertionError("cross-episode neighbor retrieval leaked an episode") + if np.any(episode_of[spectrum] == episode_of[rows]): + raise AssertionError("cross-episode spectrum retrieval leaked an episode") + return nearest, spectrum, mean, std + + +def sample_safe_cross_negatives( + rng, latents, rows, support, episode_of, mean, std, radius +): + output = np.empty_like(rows) + normalized_rows = (latents[rows] - mean) / std + unresolved = np.ones(len(rows), bool) + for _ in range(64): + positions = np.flatnonzero(unresolved) + if len(positions) == 0: + break + candidates = rng.choice(support, len(positions), replace=True) + candidate_z = (latents[candidates] - mean) / std + distance = np.linalg.norm( + normalized_rows[positions] - candidate_z, axis=-1) + accepted = ( + (episode_of[candidates] != episode_of[rows[positions]]) + & (distance > radius)) + output[positions[accepted]] = candidates[accepted] + unresolved[positions[accepted]] = False + if unresolved.any(): + raise AssertionError( + f"failed to draw {int(unresolved.sum())} safe visual negatives") + return output + + +def primary_audit( + latents, terminals, probability, reader_metadata, rows, knn_k, + holdout_episodes, seed +): + starts, stops, start_of, end_of, episode_of = episode_layout(terminals) + if holdout_episodes < 2 or holdout_episodes >= len(starts): + raise ValueError( + f"--holdout_episodes must be in [2,{len(starts) - 1}]") + holdout_start_episode = len(starts) - holdout_episodes + holdout_start = int(starts[holdout_start_episode]) + support = np.arange(holdout_start, len(latents), dtype=np.int64) + + index_delta = reader_metadata["index_delta"] + negative_gap = reader_metadata["neg_gap"] + if index_delta is None or negative_gap is None: + raise AssertionError("reader must save index_delta and neg_gap") + if negative_gap <= index_delta: + raise AssertionError("negative gap must exceed index delta") + + rng = np.random.default_rng(seed) + anchor = rng.choice(support, rows, replace=True) + local_goal = np.minimum( + anchor + rng.integers(0, index_delta + 1, rows), + end_of[anchor] - 1, + ) + far_goal = sample_far_same_episode( + rng, anchor, start_of, end_of, negative_gap) + neighbor_one, neighbor_spectrum, mean, std = cross_episode_neighbors( + latents, local_goal, episode_of, support, knn_k, rng) + + normalized_anchor = (latents[anchor] - mean) / std + normalized_local = (latents[local_goal] - mean) / std + local_distance = np.linalg.norm( + normalized_anchor - normalized_local, axis=-1) + safe_radius = float(np.quantile(local_distance, 0.99)) + safe_goal = sample_safe_cross_negatives( + rng, latents, anchor, support, episode_of, mean, std, safe_radius) + + local_probability = probability( + latents[anchor], latents[local_goal]) + far_probability = probability(latents[anchor], latents[far_goal]) + safe_probability = probability(latents[anchor], latents[safe_goal]) + substituted_one = probability( + latents[anchor], latents[neighbor_one]) + substituted_spectrum = probability( + latents[anchor], latents[neighbor_spectrum]) + equivalence_one = probability( + latents[local_goal], latents[neighbor_one]) + equivalence_spectrum = probability( + latents[local_goal], latents[neighbor_spectrum]) + swapped = probability(latents[local_goal], latents[anchor]) + symmetry_error = np.abs(local_probability - swapped) + + metrics = { + "split": { + "episodes_total": int(len(starts)), + "episodes_held_out": int(holdout_episodes), + "first_held_out_episode": int(holdout_start_episode), + "first_held_out_row": int(holdout_start), + "rows": int(rows), + }, + "labels": { + "index_delta": int(index_delta), + "negative_gap": int(negative_gap), + "visual_safe_negative_radius": safe_radius, + "cross_neighbor_k": int(knn_k), + }, + "heldout_index": { + "positive_probability": summary(local_probability), + "far_same_episode_probability": summary(far_probability), + "balanced_auc": auc(local_probability, far_probability), + "positive_recall_at_half": float( + np.mean(local_probability >= 0.5)), + "far_false_positive_rate_at_half": float( + np.mean(far_probability >= 0.5)), + }, + "cross_episode_visual_substitution": { + "nearest": { + "reader_probability": summary(substituted_one), + "recall_at_half": float(np.mean(substituted_one >= 0.5)), + "absolute_change_from_local": summary( + np.abs(substituted_one - local_probability)), + "neighbor_equivalence_probability": summary(equivalence_one), + }, + "uniform_top_k": { + "reader_probability": summary(substituted_spectrum), + "recall_at_half": float( + np.mean(substituted_spectrum >= 0.5)), + "absolute_change_from_local": summary( + np.abs(substituted_spectrum - local_probability)), + "neighbor_equivalence_probability": summary( + equivalence_spectrum), + }, + }, + "safe_cross_episode_negatives": { + "probability": summary(safe_probability), + "false_positive_rate_at_half": float( + np.mean(safe_probability >= 0.5)), + "positive_vs_safe_auc": auc( + local_probability, safe_probability), + }, + "pair_order_symmetry": { + "absolute_probability_error": summary(symmetry_error), + "max_absolute_probability_error": float(symmetry_error.max()), + }, + } + gates = { + "heldout_index_auc_at_least_0_95": ( + metrics["heldout_index"]["balanced_auc"] >= 0.95), + "cross_spectrum_recall_at_least_0_80": ( + metrics["cross_episode_visual_substitution"]["uniform_top_k"][ + "recall_at_half"] >= 0.80), + "cross_spectrum_median_change_at_most_0_10": ( + metrics["cross_episode_visual_substitution"]["uniform_top_k"][ + "absolute_change_from_local"]["median"] <= 0.10), + "safe_negative_fpr_at_most_0_05": ( + metrics["safe_cross_episode_negatives"][ + "false_positive_rate_at_half"] <= 0.05), + "symmetry_max_error_at_most_1e_6": ( + metrics["pair_order_symmetry"][ + "max_absolute_probability_error"] <= 1e-6), + } + return metrics, {**gates, "pass": bool(all(gates.values()))}, ( + support, mean, std, safe_radius) + + +def load_goal_cache(path): + with np.load(path, allow_pickle=False) as artifact: + required = { + "schema_version", + "env_id", + "source", + "goal_pixels", + "task_ids", + "reset_seeds", + "sha256", + "uses_task_coordinates", + "contains_privileged_state", + "permitted_for_training", + } + missing = required - set(artifact.files) + if missing: + raise AssertionError(f"goal cache missing fields: {sorted(missing)}") + pixels = np.asarray(artifact["goal_pixels"]) + task_ids = np.asarray(artifact["task_ids"], np.int64) + reset_seeds = np.asarray(artifact["reset_seeds"], np.int64) + metadata = { + "path": os.path.abspath(path), + "schema_version": int(artifact["schema_version"]), + "env_id": _scalar_string(artifact["env_id"]), + "source": _scalar_string(artifact["source"]), + "sha256": _scalar_string(artifact["sha256"]), + "uses_task_coordinates": bool(artifact["uses_task_coordinates"]), + "contains_privileged_state": bool( + artifact["contains_privileged_state"]), + "permitted_for_training": bool( + artifact["permitted_for_training"]), + } + digest = hashlib.sha256(pixels.tobytes()).hexdigest() + if digest != metadata["sha256"]: + raise AssertionError("goal-pixel cache SHA-256 mismatch") + if ( + pixels.dtype != np.uint8 + or pixels.ndim != 4 + or pixels.shape[-1] != 3 + or len(task_ids) != len(pixels) + or len(reset_seeds) != len(pixels) + ): + raise AssertionError( + f"bad goal cache arrays: {pixels.dtype} {pixels.shape}, " + f"tasks={task_ids.shape}, seeds={reset_seeds.shape}") + if ( + metadata["uses_task_coordinates"] + or metadata["contains_privileged_state"] + or metadata["permitted_for_training"] + or metadata["source"] != "reset_info_goal_actor_input" + ): + raise AssertionError(f"unsafe goal cache metadata: {metadata}") + return pixels, task_ids, reset_seeds, metadata + + +def official_goal_audit( + pixel_encoder, goal_cache, latents, probability, support_state +): + pixels, task_ids, reset_seeds, cache_metadata = load_goal_cache(goal_cache) + from train_pixel_encoder_jax import load_pixel_encoder + + encode, encoder_metadata = load_pixel_encoder(pixel_encoder) + goal_z = encode(pixels) + if goal_z.shape[1] != latents.shape[1]: + raise AssertionError( + f"goal zdim {goal_z.shape[1]} != latent zdim {latents.shape[1]}") + + same_first = [] + same_second = [] + cross_first = [] + cross_second = [] + per_task = {} + unique_tasks = np.unique(task_ids) + for task in unique_tasks: + indices = np.flatnonzero(task_ids == task) + if len(indices) < 2: + raise AssertionError(f"task {task} has fewer than two goal views") + row, col = np.triu_indices(len(indices), 1) + same_first.append(indices[row]) + same_second.append(indices[col]) + for first_position, first_task in enumerate(unique_tasks): + for second_task in unique_tasks[first_position + 1:]: + first = np.flatnonzero(task_ids == first_task) + second = np.flatnonzero(task_ids == second_task) + left, right = np.meshgrid(first, second, indexing="ij") + cross_first.append(left.ravel()) + cross_second.append(right.ravel()) + same_first = np.concatenate(same_first) + same_second = np.concatenate(same_second) + cross_first = np.concatenate(cross_first) + cross_second = np.concatenate(cross_second) + same_probability = probability( + goal_z[same_first], goal_z[same_second]) + cross_probability = probability( + goal_z[cross_first], goal_z[cross_second]) + for task in unique_tasks: + mask = task_ids[same_first] == task + values = same_probability[mask] + per_task[str(int(task))] = { + "probability": summary(values), + "recall_at_half": float(np.mean(values >= 0.5)), + } + + support, mean, std, safe_radius = support_state + from scipy.spatial import cKDTree + + normalized_support = (latents[support] - mean) / std + normalized_goals = (goal_z - mean) / std + tree = cKDTree(normalized_support) + k = min(128, len(support)) + _, neighbor_rows = tree.query(normalized_goals, k=k, workers=-1) + if k == 1: + neighbor_rows = neighbor_rows[:, None] + neighbors = support[neighbor_rows] + repeated_goals = np.repeat(goal_z, k, axis=0) + retrieval_probability = probability( + latents[neighbors.reshape(-1)], repeated_goals) + + rng = np.random.default_rng(1729) + negative_indices = np.empty((len(goal_z), 128), np.int64) + for goal_index in range(len(goal_z)): + unresolved = np.ones(128, bool) + for _ in range(64): + positions = np.flatnonzero(unresolved) + if len(positions) == 0: + break + candidate = rng.choice(support, len(positions), replace=True) + candidate_z = (latents[candidate] - mean) / std + distance = np.linalg.norm( + candidate_z - normalized_goals[goal_index], axis=-1) + accepted = distance > safe_radius + negative_indices[goal_index, positions[accepted]] = ( + candidate[accepted]) + unresolved[positions[accepted]] = False + if unresolved.any(): + raise AssertionError( + f"could not draw safe negatives for goal {goal_index}") + safe_goal_probability = probability( + latents[negative_indices.reshape(-1)], + np.repeat(goal_z, negative_indices.shape[1], axis=0), + ) + + metrics = { + "cache": { + **cache_metadata, + "task_ids": [int(value) for value in unique_tasks], + "variants": int(len(pixels)), + "reset_seed_min": int(reset_seeds.min()), + "reset_seed_max": int(reset_seeds.max()), + }, + "encoder": { + "path": os.path.abspath(pixel_encoder), + "zdim": int(encoder_metadata["z_dim"]), + }, + "same_task_arm_nuisance": { + "probability": summary(same_probability), + "recall_at_half": float(np.mean(same_probability >= 0.5)), + "minimum_per_task_recall_at_half": float(min( + value["recall_at_half"] for value in per_task.values())), + "per_task": per_task, + }, + "different_task": { + "probability": summary(cross_probability), + "false_positive_rate_at_half": float( + np.mean(cross_probability >= 0.5)), + "same_vs_different_auc": auc( + same_probability, cross_probability), + }, + "heldout_dataset_visual_neighbors": { + "k": int(k), + "probability": summary(retrieval_probability), + "recall_at_half": float( + np.mean(retrieval_probability >= 0.5)), + "safe_negative_probability": summary(safe_goal_probability), + "safe_negative_false_positive_rate_at_half": float( + np.mean(safe_goal_probability >= 0.5)), + }, + } + gates = { + "same_task_recall_at_least_0_90": ( + metrics["same_task_arm_nuisance"]["recall_at_half"] >= 0.90), + "minimum_task_recall_at_least_0_80": ( + metrics["same_task_arm_nuisance"][ + "minimum_per_task_recall_at_half"] >= 0.80), + "different_task_fpr_at_most_0_05": ( + metrics["different_task"][ + "false_positive_rate_at_half"] <= 0.05), + "same_vs_different_auc_at_least_0_98": ( + metrics["different_task"]["same_vs_different_auc"] >= 0.98), + "dataset_neighbor_recall_at_least_0_80": ( + metrics["heldout_dataset_visual_neighbors"][ + "recall_at_half"] >= 0.80), + "dataset_safe_negative_fpr_at_most_0_05": ( + metrics["heldout_dataset_visual_neighbors"][ + "safe_negative_false_positive_rate_at_half"] <= 0.05), + } + return metrics, {**gates, "pass": bool(all(gates.values()))} + + +def run(args): + with np.load(args.latents, allow_pickle=False) as artifact: + available = list(artifact.files) + latents = np.asarray(artifact["z"], np.float32) + terminals = np.asarray(artifact["terminals"], bool) + probability, reader_metadata = load_reader(args.reward_decoder) + if reader_metadata["target"] != "index": + raise AssertionError( + f"semantic audit requires index reader, got " + f"{reader_metadata['target']}") + if reader_metadata["zdim"] != latents.shape[1]: + raise AssertionError("reader/latent dimension mismatch") + + primary_metrics, selection_gate, support_state = primary_audit( + latents, + terminals, + probability, + reader_metadata, + args.rows, + args.knn_k, + args.holdout_episodes, + args.seed, + ) + result = { + "audit": "visual_reward_reader_semantic_invariance", + "schema_version": 1, + "strictly_pixels_and_indices_only": True, + "uses_td_or_bootstrap": False, + "artifacts": { + "latents": os.path.abspath(args.latents), + "reward_decoder": os.path.abspath(args.reward_decoder), + "reward_decoder_sha256": file_sha256(args.reward_decoder), + "latent_arrays_available": available, + "latent_arrays_read": ["z", "terminals"], + "forbidden_arrays_read": [], + "reader": reader_metadata, + }, + "primary_pixel_index_metrics": primary_metrics, + "selection_gate": { + **selection_gate, + "permitted_for_recipe_selection": True, + "task_ids_used": False, + "coordinates_used": False, + }, + "official_goal_falsification": { + "run": False, + "permitted_for_recipe_selection": False, + }, + } + if args.official_goal_pixels: + if not args.pixel_encoder: + raise ValueError( + "--official_goal_pixels requires --pixel_encoder") + metrics, gate = official_goal_audit( + args.pixel_encoder, + args.official_goal_pixels, + latents, + probability, + support_state, + ) + result["official_goal_falsification"] = { + "run": True, + "permitted_for_recipe_selection": False, + "must_run_only_after_recipe_is_frozen": True, + "metrics": metrics, + "gate": gate, + } + + if args.out: + output = os.path.abspath(os.path.expanduser(args.out)) + os.makedirs(os.path.dirname(output), exist_ok=True) + with open(output, "w") as file: + json.dump(result, file, indent=2) + print(json.dumps(result, indent=2), flush=True) + return result + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--latents", required=True) + parser.add_argument("--reward_decoder", required=True) + parser.add_argument("--rows", type=int, default=10_000) + parser.add_argument("--knn_k", type=int, default=128) + parser.add_argument("--holdout_episodes", type=int, default=50) + parser.add_argument("--seed", type=int, default=918) + parser.add_argument( + "--official_goal_pixels", + help="optional cache from cache_visual_eval_goal_pixels.py; " + "falsification only, never model selection") + parser.add_argument( + "--pixel_encoder", + help="frozen encoder required only with --official_goal_pixels") + parser.add_argument("--out") + args = parser.parse_args() + if args.rows <= 0 or args.knn_k <= 0: + raise ValueError("--rows and --knn_k must be positive") + run(args) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/eval_visual_gcbc_control.py b/gen_q_rsm/ogbench_genq/genq/eval_visual_gcbc_control.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe394be7c17e3736ccb64b8a84dbfd59d1be296 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/eval_visual_gcbc_control.py @@ -0,0 +1,129 @@ +"""Fresh official rollout of the pixels-only visual GCBC actor control.""" + +import argparse +import json +import os +import pickle +import sys +from pathlib import Path + +import numpy as np + + +ENV = "visual-cube-single-play-v0" + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--episodes", type=int, default=50) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument( + "--device", + choices=("cpu", "gpu"), + default="cpu", + help="policy-inference device; cpu matches the official GCIQL audit", + ) + parser.add_argument( + "--ogbench_impls", + default=os.environ.get( + "OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls")), + ) + args = parser.parse_args() + # Running this file by path places ``ogbench_genq/genq`` rather than the + # repository root on sys.path. Make the local audit module import + # independent of the submitter's shell environment. + sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + reference_root = os.path.abspath(os.path.expanduser(args.ogbench_impls)) + sys.path.insert(0, reference_root) + + import jax + import ogbench + from agents.gcbc import GCBCAgent + from utils.evaluation import evaluate + from ogbench_genq.genq.train_visual_gcbc_control import ( + exact_visual_gcbc_config, + ) + + with open(args.checkpoint, "rb") as file: + payload = pickle.load(file) + assert payload["format"] == "visual_gcbc_params_v1" + meta = payload["run_meta"] + assert meta["pixels_only"] and meta["drop_proprio"] + assert meta["simulator_state_used"] is False + assert meta["coordinate_used"] is False + assert meta["reward_used"] is False + assert meta["uses_td_or_bootstrap"] is False + + config = exact_visual_gcbc_config() + assert dict(config) == payload["config"] + agent = GCBCAgent.create( + int(meta["seed"]), + np.zeros((1, *meta["observation_shape"]), dtype=np.uint8), + np.zeros((1, *meta["action_shape"]), dtype=np.float32), + config, + ) + agent = agent.replace( + network=agent.network.replace(params=payload["params"])) + eval_device = jax.devices(args.device)[0] + eval_agent = jax.device_put(agent, device=eval_device) + + env = ogbench.make_env_and_datasets(ENV, env_only=True) + env.reset(seed=args.seed) + task_infos = ( + env.unwrapped.task_infos + if hasattr(env.unwrapped, "task_infos") else env.task_infos) + per_task = [] + task_results = {} + for task_id, task in enumerate(task_infos, 1): + info, _, _ = evaluate( + agent=eval_agent, + env=env, + task_id=task_id, + config=config, + num_eval_episodes=args.episodes, + num_video_episodes=0, + video_frame_skip=3, + eval_temperature=0.0, + eval_gaussian=None, + ) + success = float(info.get("success", 0.0)) + per_task.append(success) + task_results[task["task_name"]] = success + print( + f"[visual-gcbc-eval] task={task_id} " + f"name={task['task_name']} success={success:.6f}", + flush=True, + ) + + result = { + "method": "GCBC", + "purpose": meta["purpose"], + "env": ENV, + "checkpoint": os.path.abspath(args.checkpoint), + "checkpoint_step": int(payload["step"]), + "episodes_per_task": int(args.episodes), + "total_episodes": int(args.episodes * len(task_infos)), + "success_rate": float(np.mean(per_task)), + "per_task": per_task, + "task_results": task_results, + "pixels_only": True, + "drop_proprio": True, + "simulator_state_used": False, + "coordinate_used": False, + "reward_used": False, + "uses_td_or_bootstrap": False, + "policy_observation": "rendered_pixels_only", + "policy_inference_device": args.device, + "policy_inference_device_kind": eval_device.device_kind, + "run_meta": meta, + } + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as file: + json.dump(result, file, indent=2) + print(json.dumps(result, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/eval_visual_gciql_control.py b/gen_q_rsm/ogbench_genq/genq/eval_visual_gciql_control.py new file mode 100644 index 0000000000000000000000000000000000000000..f849ceb12257ba09a81f2fb0799cab5f445aac79 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/eval_visual_gciql_control.py @@ -0,0 +1,110 @@ +"""Fresh-rollout evaluation for a saved pixels-only visual GCIQL checkpoint.""" +import argparse +import json +import os +import pickle +import sys + +import numpy as np + + +ENV = "visual-cube-single-play-v0" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--checkpoint", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--env", default=ENV, + help="OGBench visual env id (match the checkpoint's env)") + ap.add_argument("--episodes", type=int, default=50) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--ogbench_impls", + default=os.environ.get( + "OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls"))) + args = ap.parse_args() + reference_root = os.path.abspath(os.path.expanduser(args.ogbench_impls)) + sys.path.insert(0, reference_root) + + import jax + import ogbench + from agents.gciql import GCIQLAgent + from utils.evaluation import evaluate + from ogbench_genq.genq.train_visual_gciql_control import exact_visual_config + + with open(args.checkpoint, "rb") as f: + payload = pickle.load(f) + assert payload["format"] == "visual_gciql_params_v1" + meta = payload["run_meta"] + assert meta["pixels_only"] and meta["drop_proprio"] + assert not meta["simulator_state_used"] and not meta["coordinate_used"] + + config = exact_visual_config() + assert dict(config) == payload["config"] + obs_shape = tuple(meta["observation_shape"]) + action_shape = tuple(meta["action_shape"]) + agent = GCIQLAgent.create( + int(meta["seed"]), + np.zeros((1, *obs_shape), dtype=np.uint8), + np.zeros((1, *action_shape), dtype=np.float32), + config, + ) + agent = agent.replace(network=agent.network.replace(params=payload["params"])) + eval_agent = jax.device_put(agent, device=jax.devices("cpu")[0]) + + # env_only=True prevents the evaluation job from loading any offline + # simulator-state arrays. The policy receives only rendered observations + # and rendered goal images from the official visual environment. + env = ogbench.make_env_and_datasets(args.env, env_only=True) + env.reset(seed=args.seed) + task_infos = ( + env.unwrapped.task_infos + if hasattr(env.unwrapped, "task_infos") else env.task_infos) + per_task = [] + task_results = {} + for task_id, task in enumerate(task_infos, 1): + info, _, _ = evaluate( + agent=eval_agent, + env=env, + task_id=task_id, + config=config, + num_eval_episodes=args.episodes, + num_video_episodes=0, + video_frame_skip=3, + eval_temperature=0.0, + eval_gaussian=None, + ) + success = float(info.get("success", 0.0)) + per_task.append(success) + task_results[task["task_name"]] = success + print( + f"[visual-gciql-eval] task={task_id} " + f"name={task['task_name']} success={success:.6f}", + flush=True, + ) + + result = { + "method": "GCIQL", + "env": args.env, + "checkpoint": os.path.abspath(args.checkpoint), + "checkpoint_step": int(payload["step"]), + "episodes_per_task": int(args.episodes), + "total_episodes": int(args.episodes * len(task_infos)), + "success_rate": float(np.mean(per_task)), + "per_task": per_task, + "task_results": task_results, + "pixels_only": True, + "drop_proprio": True, + "simulator_state_used": False, + "coordinate_used": False, + "policy_observation": "rendered_pixels_only", + "run_meta": meta, + } + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as f: + json.dump(result, f, indent=2) + print(json.dumps(result, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/eval_visual_rsm_pixel_actor.py b/gen_q_rsm/ogbench_genq/genq/eval_visual_rsm_pixel_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..15406e098edd8e5b291ef1e1521411cf3ce64df0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/eval_visual_rsm_pixel_actor.py @@ -0,0 +1,1161 @@ +"""Official raw-pixel rollout evaluator for a full visual RSM checkpoint. + +This evaluator deliberately reconstructs only the saved actor. The occupancy, +reward reader, dataset, and latent artifacts are never loaded at evaluation +time. A strict metadata and parameter-tree audit first proves that the actor is +the pixels-only IMPALA-small policy saved by ``rsm.py`` and that its training +run did not use proprioception, simulator coordinates, reward arrays, +temporal-difference bootstrapping, or a completion/world model. +""" + +import argparse +import hashlib +import json +import os +import pickle +import sys +from collections.abc import Mapping +from pathlib import Path + +import numpy as np + + +ENV = "visual-cube-single-play-v0" +EXPECTED_TASK_NAMES = ( + "task1_horizontal", + "task2_vertical1", + "task3_vertical2", + "task4_diagonal1", + "task5_diagonal2", +) +OBSERVATION_SHAPE = (64, 64, 3) +ACTION_SHAPE = (5,) +PIXEL_DATASET_KEYS = frozenset({ + "observations", "actions", "terminals", "valids", +}) +FORBIDDEN_DATASET_KEYS = frozenset({ + "qpos", "qvel", "button_states", "coordinates", "rewards", +}) +ACTOR_PARAMETER_GROUPS = frozenset({ + "actor_net", "gc_encoder", "mean_net", +}) +PIXEL_VALUE_PARAMETER_GROUPS = frozenset({ + "gc_encoder", "value_net", +}) +VISUAL_GCIQL_BATCH_SIZE = 256 +PIXEL_SCORER_TARGET_UPDATE_SOURCE = ( + "just_updated_live_twin_pixel_scorer" +) +PIXEL_SCORER_TARGET_UPDATE_TIMING = ( + "polyak_after_current_gradient_update_for_next_fused_step" +) +PIXEL_SCORER_TARGET_UPDATE_TAU = 0.005 +ACTOR_ARCHITECTURE = "GCActor_IMPALA_small_early_fusion_MLP_512x3" +TERMINAL_ALIGNMENT_CONTRACT = ( + "latent_source_endpoints_equal_pixel_valids_zero_and_compact_" + "terminals_equal_source_plus_shifted_source" +) +REFERENCE_PROVENANCE_FILES = ( + "agents/gcbc.py", + "utils/datasets.py", + "utils/encoders.py", + "utils/networks.py", +) +EVALUATOR_REFERENCE_FILES = ( + "agents/gciql.py", + "utils/encoders.py", + "utils/networks.py", + "utils/evaluation.py", +) + + +class CheckpointContractError(ValueError): + """Raised when a checkpoint cannot prove the fair pixel-actor contract.""" + + +def _is_sha256(value): + return ( + isinstance(value, str) + and len(value) == 64 + and all(character in "0123456789abcdef" for character in value) + ) + + +def _reference_sha256(reference_root, relative_paths): + digest = hashlib.sha256() + for relative_path in relative_paths: + path = os.path.join(reference_root, relative_path) + if not os.path.isfile(path): + raise CheckpointContractError( + f"missing active OGBench reference file: {path}") + with open(path, "rb") as file: + digest.update(relative_path.encode()) + digest.update(file.read()) + return digest.hexdigest() + + +def load_checkpoint(path, expected_sha256=None): + """Hash and deserialize one immutable view of ``path``. + + The hash and pickle are read through the same open file descriptor. This + prevents an atomic training-checkpoint replacement between the provenance + hash and deserialization from making them refer to different files. + """ + real_path = os.path.realpath(os.path.abspath(os.path.expanduser(path))) + if not os.path.isfile(real_path): + raise CheckpointContractError( + f"RSM full checkpoint does not exist: {real_path}") + digest = hashlib.sha256() + with open(real_path, "rb") as file: + for chunk in iter(lambda: file.read(1024 * 1024), b""): + digest.update(chunk) + actual_sha256 = digest.hexdigest() + if expected_sha256 is not None: + if not _is_sha256(expected_sha256): + raise CheckpointContractError( + "--expected_checkpoint_sha256 must be a lowercase " + "SHA-256 digest") + if actual_sha256 != expected_sha256: + raise CheckpointContractError( + "RSM checkpoint SHA-256 mismatch: " + f"expected={expected_sha256} actual={actual_sha256} " + f"path={real_path}") + file.seek(0) + payload = pickle.load(file) + return payload, actual_sha256, real_path + + +def _expected(errors, mapping, key, expected): + actual = mapping.get(key, object()) + if isinstance(expected, (tuple, list, set, frozenset)): + try: + matches = tuple(actual) == tuple(expected) + except TypeError: + matches = False + else: + try: + matches = bool(actual == expected) + except (TypeError, ValueError): + matches = False + if not matches: + errors.append( + f"run_meta.{key}: expected {expected!r}, got " + f"{mapping.get(key, '')!r}") + + +def _positive_int(value, label, errors): + if isinstance(value, (bool, np.bool_)): + errors.append(f"{label} must be a positive integer, got {value!r}") + return None + try: + integer = int(value) + scalar = np.asarray(value) + valid = scalar.shape == () and float(scalar) == float(integer) + except (TypeError, ValueError, OverflowError): + valid = False + integer = None + if not valid or integer <= 0: + errors.append(f"{label} must be a positive integer, got {value!r}") + return None + return integer + + +def _validate_artifact_provenance(meta, errors): + provenance = meta.get("pixel_artifact_provenance") + if not isinstance(provenance, Mapping): + errors.append("run_meta.pixel_artifact_provenance must be a mapping") + return + expected_labels = {"latent_npz", "pixel_encoder", "pixel_dataset"} + if set(provenance) != expected_labels: + errors.append( + "run_meta.pixel_artifact_provenance must contain exactly " + f"{sorted(expected_labels)}, got {sorted(provenance)}") + return + for label in sorted(expected_labels): + record = provenance[label] + if not isinstance(record, Mapping): + errors.append( + f"run_meta.pixel_artifact_provenance.{label} must be a " + "mapping") + continue + if not isinstance(record.get("path"), str) or not record["path"]: + errors.append( + f"run_meta.pixel_artifact_provenance.{label}.path is invalid") + if not _is_sha256(record.get("sha256")): + errors.append( + f"run_meta.pixel_artifact_provenance.{label}.sha256 is " + "invalid") + + +def _validate_pixel_dataset(meta, errors): + dataset = meta.get("pixel_actor_dataset") + if not isinstance(dataset, Mapping): + errors.append("run_meta.pixel_actor_dataset must be a mapping") + return + try: + dataset_keys = frozenset(dataset.get("dataset_keys", ())) + excluded_keys = frozenset(dataset.get("excluded_keys", ())) + except TypeError: + dataset_keys = excluded_keys = frozenset() + if dataset_keys != PIXEL_DATASET_KEYS: + errors.append( + "run_meta.pixel_actor_dataset.dataset_keys must be exactly " + f"{sorted(PIXEL_DATASET_KEYS)}, got {sorted(dataset_keys)}") + if not FORBIDDEN_DATASET_KEYS.issubset(excluded_keys): + errors.append( + "run_meta.pixel_actor_dataset.excluded_keys must include " + f"{sorted(FORBIDDEN_DATASET_KEYS)}") + expected = { + "observation_shape": list(OBSERVATION_SHAPE), + "observation_dtype": "uint8", + "action_shape": list(ACTION_SHAPE), + "actions_match_latent_cache": True, + "source_terminals_match_latent_cache": True, + "compact_terminals_match_reconstructed": True, + "terminal_alignment_contract": TERMINAL_ALIGNMENT_CONTRACT, + } + for key, value in expected.items(): + actual = dataset.get(key, object()) + if isinstance(value, list): + try: + matches = tuple(actual) == tuple(value) + except TypeError: + matches = False + else: + matches = actual == value + if not matches: + errors.append( + f"run_meta.pixel_actor_dataset.{key}: expected {value!r}, " + f"got {dataset.get(key, '')!r}") + row_count = _positive_int( + dataset.get("row_count"), + "run_meta.pixel_actor_dataset.row_count", + errors, + ) + valid_count = _positive_int( + dataset.get("valid_transition_count"), + "run_meta.pixel_actor_dataset.valid_transition_count", + errors, + ) + if ( + row_count is not None + and valid_count is not None + and valid_count > row_count): + errors.append( + "run_meta.pixel_actor_dataset.valid_transition_count exceeds " + "row_count") + if not isinstance(dataset.get("path"), str) or not dataset["path"]: + errors.append("run_meta.pixel_actor_dataset.path is invalid") + if not _is_sha256(dataset.get("sha256")): + errors.append("run_meta.pixel_actor_dataset.sha256 is invalid") + + +def validate_rsm_checkpoint_contract( + payload, actor_source="ema", active_reference_root=None): + """Validate and extract a live or exponential-moving-average pixel actor.""" + if actor_source not in ("live", "ema"): + raise CheckpointContractError( + f"actor_source must be live or ema, got {actor_source!r}") + if not isinstance(payload, Mapping): + raise CheckpointContractError( + "RSM full checkpoint payload must be a mapping") + errors = [] + meta = payload.get("run_meta") + carry = payload.get("carry") + if not isinstance(meta, Mapping): + raise CheckpointContractError( + "RSM full checkpoint run_meta must be a mapping") + if not isinstance(carry, (tuple, list)) or len(carry) not in (10, 13): + raise CheckpointContractError( + "RSM full checkpoint carry must have 10 frozen-latent entries " + "or 13 jointly-adapted-latent entries") + + schema_version = _positive_int( + meta.get("schema_version"), "run_meta.schema_version", errors) + if schema_version is not None and schema_version < 10: + errors.append( + "run_meta.schema_version must be at least 10 for a raw-pixel " + f"actor checkpoint, got {schema_version}") + pixel_scorer = ( + meta.get("distill_scorer_input") == "pixels") + reward_metric_target = ( + meta.get("occupancy_target_space") + == "goal_relative_reader_metric") + if schema_version is not None and schema_version >= 13: + if not (pixel_scorer or reward_metric_target): + errors.append( + "checkpoint schema_version >= 13 requires the fail-closed " + "raw-pixel scorer or reader-metric target contract") + elif pixel_scorer or reward_metric_target: + errors.append( + "raw-pixel scorer and reader-metric target metadata require " + "schema_version >= 13") + + exact_meta = { + "env": ENV, + "drop_proprio": True, + "actor_input": "pixels", + "actor_state_feature": "raw_rgb_pixels", + "actor_goal_feature": "raw_rgb_pixels", + "final_actor_consumes_pixels": True, + "policy_observation": "rendered_pixels_only", + "actor_architecture": ACTOR_ARCHITECTURE, + "actor_encoder": "impala_small", + "actor_encoder_trainable": True, + "actor_pixel_augmentation_probability": 0.5, + "actor_training_augmentation": + "batch_probability_shared_per_row_edge_padded_random_crop", + "actor_goal_relabeling": "uniform_future_same_trajectory", + "actor_pixel_state_shape": list(OBSERVATION_SHAPE), + "actor_pixel_goal_shape": list(OBSERVATION_SHAPE), + "actor_goal_dim_semantics": + "raw_rgb_pixel_scorer_goal_shape" + if pixel_scorer + else "latent_supervised_scorer_goal_width", + "actor_transition_sampling": "uniform_over_dataset_valid_indices", + "occupancy_consumes_raw_pixels": False, + "raw_pixels_update_actor_only": not pixel_scorer, + "pixel_dataset_device_transport": + "dynamic_jit_dispatch_argument_not_xla_constant", + "pixel_actor_occupancy_discount_required": True, + "pixel_actor_recursion_supported": False, + "pixel_actor_generated_midpoint_policy": None, + "pixel_actor_uses_image_or_world_model_reconstruction": False, + "completion_or_world_model_carrier_instantiated": False, + "uses_td_or_bootstrap": False, + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": False, + "occ_reader_metric_uses_reward_arrays": False, + "occ_reader_metric_uses_coordinates": False, + "occ_reader_metric_uses_td_or_bootstrap": False, + "discount_conditioned": True, + "discount_feature": "fourier_log_horizon", + "occupancy_and_actor_jointly_updated": True, + "pixel_actor_and_occupancy_same_fused_step": True, + "freeze_occupancy": False, + "actor_gradient_updates_occupancy": False, + "occupancy_gradient_updates_actor": False, + "reward_decoder_model": "diag_metric", + "reward_decoder_target": "index", + } + for key, expected in exact_meta.items(): + _expected(errors, meta, key, expected) + + if pixel_scorer: + pixel_scorer_exact = { + "supervised_scalar_scorer_input": "raw_rgb_pixels", + "supervised_scalar_scorer_goal_input": "raw_rgb_pixels", + "supervised_scalar_scorer_architecture": + "GCValue_IMPALA_small_early_fusion_twin_MLP_512x3", + "supervised_scalar_scorer_encoder": "impala_small", + "supervised_scalar_scorer_encoder_trainable": True, + "supervised_scalar_scorer_ensemble_size": 2, + "supervised_scalar_scorer_target_update_source": + PIXEL_SCORER_TARGET_UPDATE_SOURCE, + "supervised_scalar_scorer_target_update_timing": + PIXEL_SCORER_TARGET_UPDATE_TIMING, + "supervised_scalar_scorer_target_update_tau": + PIXEL_SCORER_TARGET_UPDATE_TAU, + "supervised_scalar_scorer_recorded_action_target_source": + "observed_same_trajectory_absorbing_first_passage_" + "geometric_successor_compact_z_through_frozen_index_reader", + "supervised_scalar_scorer_recorded_action_uses_occupancy": False, + "supervised_scalar_scorer_target_discount": + "explicit_task_gamma", + "supervised_scalar_scorer_receives_discount_feature": False, + "supervised_scalar_scorer_training_augmentation": + "batch_probability_shared_per_row_across_state_value_goal_" + "actor_goal_edge_padded_random_crop", + "supervised_scalar_scorer_uses_proprio": False, + "supervised_scalar_scorer_uses_coordinates": False, + "supervised_scalar_scorer_uses_reward_arrays": False, + "supervised_scalar_scorer_uses_td_or_bootstrap": False, + "supervised_expectile_value_input": "raw_rgb_pixels", + "supervised_expectile_value_architecture": + "GCValue_IMPALA_small_early_fusion_single_MLP_512x3", + "supervised_expectile_value_target_source": + "stop_gradient_ema_twin_pixel_scorer_empirical_absorbing_" + "index_return_expectile", + "supervised_expectile_value_target_discount": + "explicit_task_gamma", + "supervised_expectile_value_uses_next_state": False, + "supervised_expectile_value_uses_td_or_bootstrap": False, + "supervised_expectile_value_uses_reward_arrays": False, + "pixel_scorer_and_occupancy_same_fused_step": True, + "pixel_scorer_and_actor_same_fused_step": True, + "pixel_scorer_gradient_updates_occupancy": False, + "occupancy_gradient_updates_pixel_scorer": False, + "supervised_scalar_scorer_state_for_pixel_actor": + "raw_rgb_pixels", + "batch_size": VISUAL_GCIQL_BATCH_SIZE, + "distill_ema_tau": PIXEL_SCORER_TARGET_UPDATE_TAU, + } + for key, expected in pixel_scorer_exact.items(): + _expected(errors, meta, key, expected) + + actor_loss = meta.get("actor_loss") + if actor_loss == "awr_distill": + awr_exact = { + "expectile": 0.9, + "distill_actor_actions": False, + "supervised_scalar_scorer_counterfactual_target_source": + None, + "supervised_scalar_scorer_counterfactual_uses_empirical": + None, + "pixel_scorer_policy_extraction": + "awr_dataset_action_weighted_log_likelihood", + "pixel_scorer_actor_advantage_source": + "stop_gradient_live_twin_min_q_minus_preupdate_" + "expectile_v", + "pixel_scorer_actor_weight_formula": + "min(exp(alpha*(Q-V)),100)", + "pixel_scorer_actor_uses_dataset_actions_only": True, + "pixel_scorer_supervision_regime": + "empirical_recorded_actions_only", + } + for key, expected in awr_exact.items(): + _expected(errors, meta, key, expected) + elif actor_loss == "ddpgbc_distill": + counterfactual_support = bool( + meta.get("distill_actor_actions")) + ddpg_exact = { + "alpha": 1.0, + "expectile": 0.9, + "supervised_scalar_scorer_counterfactual_target_source": + "discount_conditioned_ema_occupancy_index_reader_" + "expectation" + if counterfactual_support else None, + "supervised_scalar_scorer_counterfactual_uses_empirical": + False if counterfactual_support else None, + "pixel_scorer_policy_extraction": + "ddpgbc_actor_gradient_control", + "pixel_scorer_actor_advantage_source": None, + "pixel_scorer_actor_weight_formula": None, + "pixel_scorer_actor_uses_dataset_actions_only": False, + "pixel_scorer_supervision_regime": ( + "empirical_recorded_actions_plus_discount_conditioned_" + "occupancy_counterfactuals" + if counterfactual_support + else "empirical_recorded_actions_only"), + } + for key, expected in ddpg_exact.items(): + _expected(errors, meta, key, expected) + else: + errors.append( + "raw-pixel scorer actor_loss must be awr_distill or " + f"ddpgbc_distill, got {actor_loss!r}") + + # Schema 10 predates the optional endpoint-hit auxiliary. Missing fields + # therefore mean that the auxiliary did not exist; any present field must + # still prove that it consumed no forbidden supervision. + if meta.get("occ_reader_hit_enabled", False): + for key in ( + "occ_reader_hit_uses_reward_arrays", + "occ_reader_hit_uses_coordinates", + "occ_reader_hit_uses_td_or_bootstrap"): + _expected(errors, meta, key, False) + + empirical_index_enabled = bool( + meta.get("distill_empirical_index_enabled", False)) + if ( + schema_version is not None + and schema_version >= 12 + and not empirical_index_enabled): + errors.append( + "checkpoint schema_version >= 12 requires empirical " + "index-successor anchoring") + if empirical_index_enabled: + if schema_version is not None and schema_version < 12: + errors.append( + "empirical index-successor anchoring requires checkpoint " + "schema_version >= 12") + for key in ( + "distill_empirical_index_uses_reward_arrays", + "distill_empirical_index_uses_coordinates", + "distill_empirical_index_uses_td_or_bootstrap"): + _expected(errors, meta, key, False) + _expected( + errors, meta, + "distill_empirical_index_behavior_action_only", True) + _expected( + errors, meta, + "distill_empirical_index_counterfactual_action_source", + ( + "none_awr_dataset_actions_only" + if pixel_scorer + and meta.get("actor_loss") == "awr_distill" + else "none_behavior_only_scorer_supervision" + if pixel_scorer + and not meta.get("distill_actor_actions") + else "discount_conditioned_ema_occupancy" + ), + ) + _expected( + errors, meta, + "distill_empirical_index_target_source", + "observed_same_trajectory_absorbing_first_passage_geometric_" + "successor_compact_z_through_frozen_index_reader", + ) + _expected( + errors, meta, + "distill_empirical_index_horizon", + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount", + ) + _expected( + errors, meta, + "distill_empirical_index_blend_formula", + ( + "recorded_successor_reader_expectation_only" + if pixel_scorer + else "(1-weight)*ema_occupancy_reader_expectation" + "+weight*recorded_successor_reader_expectation" + ), + ) + try: + empirical_weight = float( + meta["distill_empirical_index_weight"]) + if not 0.0 < empirical_weight <= 1.0: + raise ValueError + if pixel_scorer and empirical_weight != 1.0: + raise ValueError + except (KeyError, TypeError, ValueError): + errors.append( + "run_meta.distill_empirical_index_weight must lie in " + "(0, 1] when enabled and equal 1 for the raw-pixel scorer") + try: + empirical_samples = int( + meta["distill_empirical_index_samples"]) + if empirical_samples <= 0: + raise ValueError + except (KeyError, TypeError, ValueError): + errors.append( + "run_meta.distill_empirical_index_samples must be positive " + "when enabled") + if pixel_scorer: + _expected( + errors, meta, + "distill_empirical_index_recorded_action_uses_occupancy", + False) + _expected( + errors, meta, + "distill_empirical_index_counterfactual_uses_empirical", + ( + False + if ( + meta.get("actor_loss") == "ddpgbc_distill" + and meta.get("distill_actor_actions") + ) + else None + )) + + if reward_metric_target: + metric_target_meta = { + "occupancy_target_space": "goal_relative_reader_metric", + "occupancy_target_invertible": True, + "occupancy_target_reader_frozen": True, + "occupancy_target_reader_model": "diag_metric", + "occupancy_target_reader_target": "index", + "occupancy_target_goal_feature": + "compact_reward_predictive_z", + "occupancy_decoded_future_feature": + "compact_reward_predictive_z", + "occupancy_target_uses_index_relabeling": True, + "occupancy_target_uses_reward_arrays": False, + "occupancy_target_uses_coordinates": False, + "occupancy_target_uses_td_or_bootstrap": False, + } + for key, expected in metric_target_meta.items(): + _expected(errors, meta, key, expected) + if reward_metric_target and pixel_scorer: + _expected( + errors, meta, "reader_metric_pixel_scorer_combined", True) + _expected( + errors, meta, + "reader_metric_pixel_scorer_update_semantics", + "same_fused_step_separate_gradients", + ) + + if meta.get("recursion") != "off": + errors.append( + "run_meta.recursion must be 'off' while " + "pixel_actor_recursion_supported is false") + gamma = meta.get("gamma") + gamma_lo = meta.get("gamma_spectrum_lo") + try: + if not 0.0 < float(gamma_lo) <= float(gamma) < 1.0: + raise ValueError + except (TypeError, ValueError): + errors.append( + "run_meta gamma spectrum must satisfy " + f"0 < gamma_spectrum_lo <= gamma < 1, got lo={gamma_lo!r} " + f"gamma={gamma!r}") + + allowed_features = { + "state_feature": { + "encoder_hidden", "compact_z", + "joint_encoder_hidden_adapter", "joint_compact_z_adapter", + }, + "occupancy_goal_feature": { + "encoder_hidden", "compact_reward_predictive_z", + "joint_encoder_hidden_adapter", "joint_compact_z_adapter", + }, + "future_feature": { + "frozen_encoder_hidden_occupancy_state", + "compact_reward_predictive_z", + "frozen_compact_reward_predictive_z", + "joint_compact_z_adapter", + "goal_relative_reader_metric_u", + }, + "reward_goal_feature": {"compact_reward_predictive_z"}, + } + for key, allowed in allowed_features.items(): + if meta.get(key) not in allowed: + errors.append( + f"run_meta.{key} is not an allowed pixels-only latent " + f"feature: {meta.get(key, '')!r}") + + _validate_pixel_dataset(meta, errors) + _validate_artifact_provenance(meta, errors) + dataset = meta.get("pixel_actor_dataset") + provenance = meta.get("pixel_artifact_provenance") + if isinstance(dataset, Mapping) and isinstance(provenance, Mapping): + record = provenance.get("pixel_dataset") + if isinstance(record, Mapping): + if dataset.get("sha256") != record.get("sha256"): + errors.append( + "pixel dataset SHA-256 differs between actor dataset " + "metadata and artifact provenance") + try: + paths_match = ( + os.path.realpath(dataset["path"]) + == os.path.realpath(record["path"])) + except (KeyError, TypeError): + paths_match = False + if not paths_match: + errors.append( + "pixel dataset path differs between actor dataset " + "metadata and artifact provenance") + + actor_initialization = meta.get("actor_encoder_initialization") + init_meta = meta.get("pixel_actor_init") + if actor_initialization == "fresh_jointly_trainable": + if init_meta is not None: + errors.append( + "fresh actor initialization must have pixel_actor_init=None") + elif actor_initialization == "strict_non_td_gcbc_then_jointly_trainable": + if not isinstance(init_meta, Mapping): + errors.append( + "strict Goal-Conditioned Behavior Cloning initialization " + "requires run_meta.pixel_actor_init") + else: + init_expected = { + "format": "visual_gcbc_params_v1", + "uses_td_or_bootstrap": False, + "optimizer_state_loaded": False, + "actor_remains_trainable": True, + } + for key, expected in init_expected.items(): + if init_meta.get(key) != expected: + errors.append( + f"run_meta.pixel_actor_init.{key}: expected " + f"{expected!r}, got " + f"{init_meta.get(key, '')!r}") + _positive_int( + init_meta.get("step"), + "run_meta.pixel_actor_init.step", + errors, + ) + for key in ("sha256", "reference_sha256"): + if not _is_sha256(init_meta.get(key)): + errors.append( + f"run_meta.pixel_actor_init.{key} is invalid") + for key in ("path", "reference_root"): + if ( + not isinstance(init_meta.get(key), str) + or not init_meta[key]): + errors.append( + f"run_meta.pixel_actor_init.{key} is invalid") + if active_reference_root is not None: + active_reference_root = os.path.realpath( + os.path.abspath(os.path.expanduser( + active_reference_root))) + try: + root_matches = ( + os.path.realpath(init_meta["reference_root"]) + == active_reference_root) + except (KeyError, TypeError): + root_matches = False + if not root_matches: + errors.append( + "pixel actor initialization reference_root does not " + "match the active OGBench implementation") + else: + active_sha = _reference_sha256( + active_reference_root, + REFERENCE_PROVENANCE_FILES, + ) + if init_meta.get("reference_sha256") != active_sha: + errors.append( + "pixel actor initialization reference SHA-256 " + "does not match the active OGBench implementation") + else: + errors.append( + "run_meta.actor_encoder_initialization must be a strict non-TD " + "Goal-Conditioned Behavior Cloning initialization or fresh " + f"joint initialization, got {actor_initialization!r}") + + # A valid full checkpoint has no legacy completion carrier at all. + if any(value is not None for value in carry[3:6]): + errors.append( + "full checkpoint contains completion/world-model carrier state") + agent = carry[6] + ema_actor = carry[7] + if not isinstance(agent, (tuple, list)): + errors.append("full checkpoint carry[6] must be an actor-agent tuple") + live_actor = None + else: + expected_agent_lengths = { + "ddpgbc": 2, + "awr": 4, + "awr_distill": 7, + "ddpgbc_distill": 7, + } + expected_length = expected_agent_lengths.get(meta.get("actor_loss")) + if expected_length is None or len(agent) != expected_length: + errors.append( + "actor-agent tuple length does not match " + f"run_meta.actor_loss={meta.get('actor_loss')!r}: " + f"length={len(agent)} expected={expected_length}") + live_actor = agent[0] if agent else None + if len(agent) == 7: + value_params = agent[2] + scorer_params = agent[4] + if pixel_scorer: + for label, params in ( + ("expectile value", value_params), + ("twin scorer", scorer_params)): + if not isinstance(params, Mapping): + errors.append( + f"pixel {label} parameters must be a mapping") + elif set(params) != PIXEL_VALUE_PARAMETER_GROUPS: + errors.append( + f"pixel {label} parameter groups must be exactly " + f"{sorted(PIXEL_VALUE_PARAMETER_GROUPS)}, got " + f"{sorted(params)}") + else: + for label, params in ( + ("expectile value", value_params), + ("twin scorer", scorer_params)): + if ( + isinstance(params, Mapping) + and "gc_encoder" in params): + errors.append( + f"latent {label} unexpectedly contains a raw-" + "pixel encoder") + for label, params in (("live", live_actor), ("ema", ema_actor)): + if not isinstance(params, Mapping): + errors.append(f"{label} actor parameters must be a mapping") + elif set(params) != ACTOR_PARAMETER_GROUPS: + errors.append( + f"{label} actor parameter groups must be exactly " + f"{sorted(ACTOR_PARAMETER_GROUPS)}, got {sorted(params)}") + + step = _positive_int(carry[9], "full checkpoint carry step", errors) + if step is not None: + if step % 100 != 0: + errors.append( + f"full checkpoint step must align to 100-step dispatches: " + f"{step}") + try: + next_di = int(payload["next_di"]) + except (KeyError, TypeError, ValueError): + next_di = None + if next_di != step // 100 + 1: + errors.append( + f"full checkpoint next_di={next_di!r} is inconsistent with " + f"step={step}") + train_steps = _positive_int( + payload.get("train_steps"), "full checkpoint train_steps", errors) + if ( + step is not None + and train_steps is not None + and step > train_steps): + errors.append( + f"checkpoint step {step} exceeds train_steps {train_steps}") + seed = _positive_int( + int(meta.get("seed", -1)) + 1 + if isinstance(meta.get("seed"), (int, np.integer)) else None, + "run_meta.seed plus one", + errors, + ) + if seed is not None: + seed -= 1 + if payload.get("seed") != seed: + errors.append( + f"payload seed {payload.get('seed')!r} does not match " + f"run_meta.seed {seed}") + if payload.get("env") != ENV: + errors.append( + f"payload env must be {ENV!r}, got " + f"{payload.get('env', '')!r}") + + if errors: + raise CheckpointContractError( + "invalid fair visual RSM pixel-actor checkpoint:\n " + + "\n ".join(errors)) + actor_params = live_actor if actor_source == "live" else ema_actor + return { + "run_meta": dict(meta), + "actor_params": actor_params, + "actor_source": actor_source, + "checkpoint_step": step, + "checkpoint_train_steps": train_steps, + "seed": seed, + "schema_version": schema_version, + } + + +def _tree_leaves_with_paths(tree, path=()): + if isinstance(tree, Mapping): + for key in sorted(tree): + yield from _tree_leaves_with_paths(tree[key], path + (str(key),)) + return + yield path, np.asarray(tree) + + +def actor_parameter_sha256(params): + digest = hashlib.sha256() + parameter_count = 0 + for path, array in _tree_leaves_with_paths(params): + if array.dtype.kind not in "fc": + raise CheckpointContractError( + f"actor parameter {'/'.join(path)} has non-floating dtype " + f"{array.dtype}") + if not np.all(np.isfinite(array)): + raise CheckpointContractError( + f"actor parameter {'/'.join(path)} contains non-finite values") + contiguous = np.ascontiguousarray(array) + digest.update("/".join(path).encode()) + digest.update(contiguous.dtype.str.encode()) + digest.update(np.asarray(contiguous.shape, np.int64).tobytes()) + digest.update(contiguous.tobytes()) + parameter_count += int(contiguous.size) + if parameter_count == 0: + raise CheckpointContractError("actor parameter tree has no leaves") + return digest.hexdigest(), parameter_count + + +def validate_actor_parameter_tree(actual, expected): + actual_leaves = list(_tree_leaves_with_paths(actual)) + expected_leaves = list(_tree_leaves_with_paths(expected)) + actual_signature = [ + (path, array.shape, array.dtype.str) + for path, array in actual_leaves + ] + expected_signature = [ + (path, array.shape, array.dtype.str) + for path, array in expected_leaves + ] + if actual_signature != expected_signature: + raise CheckpointContractError( + "saved actor parameter tree does not match the exact " + "IMPALA-small actor:\n" + f"saved={actual_signature}\nexpected={expected_signature}") + return actor_parameter_sha256(actual) + + +def build_exact_actor(audit, reference_root): + """Reconstruct and structurally validate the exact reference actor.""" + reference_root = os.path.realpath( + os.path.abspath(os.path.expanduser(reference_root))) + if reference_root not in sys.path: + sys.path.insert(0, reference_root) + + import jax + import jax.numpy as jnp + from agents.gciql import get_config + from utils.encoders import GCEncoder, encoder_modules + from utils.networks import GCActor + + imported_files = { + "agents.gciql": sys.modules["agents.gciql"].__file__, + "utils.encoders": sys.modules["utils.encoders"].__file__, + "utils.networks": sys.modules["utils.networks"].__file__, + } + for module_name, path in imported_files.items(): + if os.path.commonpath([ + reference_root, os.path.realpath(path)]) != reference_root: + raise CheckpointContractError( + f"{module_name} was imported outside active reference root: " + f"{path}") + + config = get_config() + config.encoder = "impala_small" + config.p_aug = 0.5 + config.frame_stack = None + if tuple(config.actor_hidden_dims) != (512, 512, 512): + raise CheckpointContractError( + "active GCIQL actor_hidden_dims is not exact 512x3") + if config.const_std is not True or config.discrete is not False: + raise CheckpointContractError( + "active GCIQL actor distribution is not the exact continuous " + "constant-standard-deviation configuration") + + actor_def = GCActor( + hidden_dims=tuple(config.actor_hidden_dims), + action_dim=ACTION_SHAPE[0], + state_dependent_std=False, + const_std=config.const_std, + gc_encoder=GCEncoder( + concat_encoder=encoder_modules["impala_small"]()), + ) + expected_params = actor_def.init( + jax.random.PRNGKey(audit["seed"]), + jnp.zeros((1, *OBSERVATION_SHAPE), dtype=jnp.uint8), + jnp.zeros((1, *OBSERVATION_SHAPE), dtype=jnp.uint8), + )["params"] + actor_sha256, parameter_count = validate_actor_parameter_tree( + audit["actor_params"], expected_params) + return { + "actor_def": actor_def, + "config": config, + "actor_parameter_sha256": actor_sha256, + "actor_parameter_count": parameter_count, + "evaluator_reference_sha256": _reference_sha256( + reference_root, EVALUATOR_REFERENCE_FILES), + "reference_root": reference_root, + } + + +def make_cpu_eval_agent(actor_def, params, cpu_device): + """Create a mode-only actor that rejects anything except raw RGB pixels.""" + import jax + import jax.numpy as jnp + + params = jax.device_put(params, cpu_device) + + def act(actor_params, observations, goals): + distribution = actor_def.apply( + {"params": actor_params}, observations, goals) + return jnp.clip(distribution.mode(), -1.0, 1.0) + + act = jax.jit(act, device=cpu_device) + + class PixelEvalAgent: + def __init__(self): + self.calls = 0 + self.observation_shapes = set() + self.goal_shapes = set() + + def sample_actions( + self, observations, goals=None, seed=None, temperature=0.0): + del seed + if float(temperature) != 0.0: + raise CheckpointContractError( + "official RSM actor evaluation requires temperature=0") + observation_array = np.asarray(observations) + goal_array = np.asarray(goals) + if ( + observation_array.dtype != np.uint8 + or observation_array.shape[-3:] != OBSERVATION_SHAPE): + raise CheckpointContractError( + "policy received a non-raw-pixel observation: " + f"shape={observation_array.shape} " + f"dtype={observation_array.dtype}") + if ( + goal_array.dtype != np.uint8 + or goal_array.shape[-3:] != OBSERVATION_SHAPE): + raise CheckpointContractError( + "policy received a non-raw-pixel goal: " + f"shape={goal_array.shape} dtype={goal_array.dtype}") + self.calls += 1 + self.observation_shapes.add(tuple(observation_array.shape)) + self.goal_shapes.add(tuple(goal_array.shape)) + action = act(params, observation_array, goal_array) + if action.shape[-1:] != ACTION_SHAPE: + raise CheckpointContractError( + f"actor returned invalid action shape {action.shape}") + return action + + return PixelEvalAgent() + + +def _atomic_json(path, payload): + path = os.path.abspath(os.path.expanduser(path)) + os.makedirs(os.path.dirname(path), exist_ok=True) + temporary = f"{path}.tmp" + with open(temporary, "w") as file: + json.dump(payload, file, indent=2) + file.write("\n") + file.flush() + os.fsync(file.fileno()) + os.replace(temporary, path) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--out", required=True) + parser.add_argument("--actor", choices=("live", "ema"), default="ema") + parser.add_argument("--episodes", type=int, default=50) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--expected_checkpoint_sha256") + parser.add_argument("--validate_only", action="store_true") + parser.add_argument( + "--ogbench_impls", + default=os.environ.get( + "OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls")), + ) + args = parser.parse_args() + if args.episodes <= 0: + parser.error("--episodes must be positive") + + # Running this file by path places ``ogbench_genq/genq`` on sys.path. + sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + reference_root = os.path.realpath( + os.path.abspath(os.path.expanduser(args.ogbench_impls))) + payload, checkpoint_sha256, checkpoint_path = load_checkpoint( + args.checkpoint, args.expected_checkpoint_sha256) + audit = validate_rsm_checkpoint_contract( + payload, + actor_source=args.actor, + active_reference_root=reference_root, + ) + actor_build = build_exact_actor(audit, reference_root) + + base_result = { + "method": "RSM", + "env": ENV, + "checkpoint": checkpoint_path, + "checkpoint_sha256": checkpoint_sha256, + "checkpoint_step": audit["checkpoint_step"], + "checkpoint_train_steps": audit["checkpoint_train_steps"], + "checkpoint_schema_version": audit["schema_version"], + "actor_selection": args.actor, + "actor_checkpoint_slot": ( + "carry[7]" if args.actor == "ema" else "carry[6][0]"), + "actor_parameter_sha256": + actor_build["actor_parameter_sha256"], + "actor_parameter_count": + actor_build["actor_parameter_count"], + "actor_architecture": ACTOR_ARCHITECTURE, + "active_reference_root": actor_build["reference_root"], + "active_evaluator_reference_sha256": + actor_build["evaluator_reference_sha256"], + "pixels_only": True, + "drop_proprio": True, + "simulator_state_used": False, + "coordinate_used": False, + "reward_array_used": False, + "uses_td_or_bootstrap": False, + "uses_completion_or_forward_model": False, + "discount_conditioned_occupancy": True, + "occupancy_and_actor_jointly_updated": True, + "policy_observation": "rendered_pixels_only", + "policy_action_source": "deterministic_actor_mode", + "run_meta": audit["run_meta"], + } + if args.validate_only: + result = { + **base_result, + "validation_only": True, + "official_rollout": False, + } + _atomic_json(args.out, result) + print(json.dumps(result, indent=2), flush=True) + return + + if os.environ.get("MUJOCO_GL") != "egl": + raise CheckpointContractError( + "official visual rollout requires MUJOCO_GL=egl") + import jax + if jax.default_backend() != "cpu": + raise CheckpointContractError( + "official RSM actor rollout requires CPU JAX policy inference; " + "set JAX_PLATFORMS=cpu before process start") + import ogbench + from utils.evaluation import evaluate + + cpu_device = jax.devices("cpu")[0] + eval_agent = make_cpu_eval_agent( + actor_build["actor_def"], audit["actor_params"], cpu_device) + + # env_only=True prevents this process from loading offline arrays or + # privileged simulator-state datasets. The actor receives only the + # rendered observation and rendered goal supplied by the official env. + env = ogbench.make_env_and_datasets(ENV, env_only=True) + env.reset(seed=args.seed) + task_infos = ( + env.unwrapped.task_infos + if hasattr(env.unwrapped, "task_infos") else env.task_infos) + task_names = tuple(task["task_name"] for task in task_infos) + if task_names != EXPECTED_TASK_NAMES: + raise CheckpointContractError( + "official visual-cube task table mismatch: " + f"expected={EXPECTED_TASK_NAMES} actual={task_names}") + + per_task = [] + task_results = {} + for task_id, task_name in enumerate(task_names, 1): + info, _, _ = evaluate( + agent=eval_agent, + env=env, + task_id=task_id, + config=actor_build["config"], + num_eval_episodes=args.episodes, + num_video_episodes=0, + video_frame_skip=3, + eval_temperature=0.0, + eval_gaussian=None, + ) + success = float(info.get("success", 0.0)) + if not 0.0 <= success <= 1.0: + raise CheckpointContractError( + f"invalid success rate for {task_name}: {success}") + per_task.append(success) + task_results[task_name] = success + print( + f"[visual-rsm-pixel-eval] actor={args.actor} task={task_id} " + f"name={task_name} success={success:.6f}", + flush=True, + ) + + result = { + **base_result, + "validation_only": False, + "official_rollout": args.episodes == 50, + "official_protocol": ( + "five_fixed_visual_cube_tasks_x_50_episodes" + if args.episodes == 50 + else "nonstandard_episode_count_not_headline_eligible"), + "evaluation_seed": int(args.seed), + "episodes_per_task": int(args.episodes), + "total_episodes": int(args.episodes * len(task_infos)), + "success_rate": float(np.mean(per_task)), + "per_task": per_task, + "task_results": task_results, + "policy_inference_backend": jax.default_backend(), + "policy_inference_device_kind": cpu_device.device_kind, + "renderer": "mujoco_egl", + "environment_loading": "env_only_no_offline_dataset", + "policy_input_contract_checked_calls": int(eval_agent.calls), + "policy_observation_shapes_seen": [ + list(shape) for shape in sorted(eval_agent.observation_shapes)], + "policy_goal_shapes_seen": [ + list(shape) for shape in sorted(eval_agent.goal_shapes)], + } + _atomic_json(args.out, result) + print(json.dumps(result, indent=2), flush=True) + + # MuJoCo's EGL destructor can abort after a successful visual rollout on + # some cluster nodes. The auditable result is already atomically durable; + # bypass interpreter teardown so a completed job retains exit status zero. + sys.stdout.flush() + sys.stderr.flush() + os._exit(0) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/expert_metric.py b/gen_q_rsm/ogbench_genq/genq/expert_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..af2fc240ff58c984692c52a7c9a3c2cbb7f35425 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/expert_metric.py @@ -0,0 +1,50 @@ +"""Stage 3: on the REAL expert recon latent, learn the coordinate-free steps-to-go +metric W and report spearman(W-metric, cube). This is the decisive go/no-go for the +fair image-only win. FAIR: training uses only pixels (recon encoder) + the step-gap k +(trajectory structure) -- no cube coordinate, no dynamics, no proprio. The cube field +is used ONLY to score the diagnostic spearman. +""" +import os, sys, numpy as np, jax, jax.numpy as jnp, optax +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from train_pixel_encoder_jax import load_pixel_encoder +from scipy.stats import spearmanr + +NPZ = "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-recursion/ckpt/cube_single_expert64.npz" +ENC = sys.argv[1] # encoder npz +d = np.load(NPZ) +obs = d["observations"]; term = np.asarray(d["terminals"]); cube = np.asarray(d["cube"], np.float64) +N = len(term); rng = np.random.default_rng(0) + +encode_fn, meta = load_pixel_encoder(ENC) +z_dim = meta["z_dim"] +Z = np.empty((N, z_dim), np.float32) +for i in range(0, N, 8192): + Z[i:i+8192] = np.asarray(encode_fn(obs[i:i+8192])) +print(f"[expert-metric] encoded {N} frames -> z_dim={z_dim}", flush=True) + +ends = np.where(term > 0)[0]; eo = np.searchsorted(ends, np.arange(N)) +bnd = np.where(eo < len(ends), ends[np.minimum(eo, len(ends)-1)], N-1) +a = rng.integers(0, N, 8000); b = rng.integers(0, N, 8000); dc = np.linalg.norm(cube[a]-cube[b], axis=1) +sp = lambda X: float(spearmanr(np.linalg.norm(X[a]-X[b], axis=1), dc).statistic) +mu, sd = Z.mean(0), Z.std(0) + 1e-8; Zs = (Z - mu) / sd +print(f"[expert-metric] raw recon spearman(vs cube) = {sp(Z):.4f} (bar 0.55; combined-coord 0.560)") + +Zj = jnp.asarray(Zs); tr = np.where(term == 0)[0]; tr = tr[bnd[tr]-tr > 2] +W = jnp.eye(z_dim); opt = optax.adam(3e-3); st = opt.init(W) +def L(W, za, zp, k): # ||W(za-zp)|| ~ k (steps-to-go REGRESSION) + dd = jnp.sqrt(jnp.sum(((za-zp) @ W.T)**2, -1) + 1e-6) + return jnp.mean((dd - k)**2) +@jax.jit +def stp(W, st, za, zp, k): + l, g = jax.value_and_grad(L)(W, za, zp, k) + u, st = opt.update(g, st, W); return optax.apply_updates(W, u), st, l +for it in range(8000): + t = rng.choice(tr, 256); k = np.minimum(rng.integers(1, 40, 256), bnd[t]-t).astype(np.float32) + W, st, l = stp(W, st, Zj[t], Zj[t+k.astype(int)], jnp.asarray(k)) + if it % 2000 == 0: print(f" reg it={it} mse={float(l):.3f}", flush=True) +Wn = np.asarray(W) +final = sp(Zs @ Wn.T) +print(f"[expert-metric] steps-to-go W spearman(vs cube) = {final:.4f} (bar 0.55)", flush=True) +# bake W into the standardization so the read-out's plain euclidean metric is aligned: +np.savez(ENC.replace(".npz", "_stepsW.npz"), W=Wn, mu=mu, sd=sd, spearman=final) +print(f"[expert-metric] {'PASS -> proceed to RSM' if final>=0.55 else 'BELOW bar'} (saved W)", flush=True) diff --git a/gen_q_rsm/ogbench_genq/genq/gate_visual_occupancy.py b/gen_q_rsm/ogbench_genq/genq/gate_visual_occupancy.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9ed3e141eab3889a8a4cec071c50f953b35f6c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/gate_visual_occupancy.py @@ -0,0 +1,3884 @@ +"""Fail-closed checkpoint gate for fair one-hop visual RSM occupancies. + +The gate answers a narrower question than closed-loop evaluation: + + Is the learned conditional flow a sufficiently faithful, action-sensitive + model of the *offline geometric future distribution* to justify composing + it recursively? + +It deliberately does not claim counterfactual action truth. For recorded +actions, the finite trajectory gives an exact supervised target distribution +at every queried discount. For local and actor actions there is no such +target in an offline dataset, so the gate reports only model-internal ranking +stability, action support, and behavior-future likelihood under action +relabeling. Official rollouts remain the policy-improvement ground truth. + +Fairness is enforced before any metric is computed: + +* the checkpoint must record pixels-only input (``drop_proprio=true``); +* it must be compact recursion-off, a schema-10+ raw-pixel one-hop checkpoint + with frozen h256 futures, or hidden-h256 occupancy recursion staged no later + than ``rec_after``, before composition can activate; +* the occupancy must be a discount-conditioned conditional flow; +* occupancy supervision must contain no reward, coordinate, TD, bootstrap, + completion, or forward-model target; +* occupancy and actor must have updated in the same fused training run, while + retaining separate losses and stop-gradient boundaries; +* the frozen reward read-out must be the canonical diagonal metric trained + from trajectory-index relabels only; and +* hidden samples use the same exact dead-ReLU mask, constant-mean pinning, and + nonnegative support projection as ``rsm.py`` even when recursion is off, + then only the frozen pixel encoder ``fc_1`` maps generated h256 to compact z + for reward read-out; +* schema-10+ raw-pixel actor queries use RGB from the checkpoint-pinned, + checksum-verified dataset through the exact IMPALA-small actor; and +* the general gate opens only ``z``, ``state_h``, ``actions``, and + ``terminals`` plus scalar ``encoder_npz`` provenance from the latent + artifact. The strict schema-13 scorer wrapper opens only ``z`` and + ``state_h`` there and sources actions/trajectory endpoints from the + checksum-pinned rendered dataset. That source opens only RGB, actions, and + terminals; the compact loader's valid mask and shifted terminals are + reconstructed without opening qpos/qvel. Proprioception, simulator + state/coordinates, and reward arrays are never loaded. + +The output has three increasingly strong decisions: + +``one_hop_value_ready`` + Reward-under-occupancy Spearman and normalized MAE pass at task gamma and + the proposed recursion beta. + +``recursive_state_ready`` + The value gate passes and the full generated latent distribution has + acceptable mean, variance, and energy distance at both discounts. + +``ready_for_recursion_experiment`` + The recursive-state gate passes, local/actor action rankings are resolved + above Monte-Carlo noise, and actor queries remain on supported actions. + +These are offline screening decisions, not substitutes for official visual +cube rollouts. +""" + +import argparse +import hashlib +import json +import os +import pickle +import sys +import tempfile +from collections.abc import Mapping +from types import SimpleNamespace + +import numpy as np + +if __package__ in (None, ""): + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) + +from ogbench_genq.genq.diagnose_visual_distilled_policy import ( + FOURIER_K, + _actor_mode, + _apply_adapter, + _gap_metrics, + _load_occupancy_normalization, + _pairwise_gap_metrics, + _ranking_metrics, + _resolve_exact_artifact, + _summary, +) +from ogbench_genq.genq.reward_reader import ( + load_jax_reward_reader, + load_numpy_reward_reader, +) +from ogbench_genq.genq.train_genq_jax import ( + build_ends, + make_model, +) +from ogbench_genq._runner import OGBENCH_IMPLS, _setup_paths +from ogbench_genq.rsm import ( + decode_reader_metric_future, + encode_reader_metric_future, + reader_metric_coordinate_diagonal, + reward_metric_endpoint_batch_plan, +) + + +PIXEL_ACTOR_DATASET_KEYS = frozenset({ + "observations", "actions", "terminals", "valids", +}) +PIXEL_ACTOR_PHYSICAL_REQUIRED_KEYS = frozenset({ + "observations", "actions", "terminals", +}) +PIXEL_ACTOR_FORBIDDEN_KEYS = frozenset({ + "qpos", "qvel", "button_states", "coordinates", "rewards", +}) +VISUAL_ACTOR_REFERENCE_FILES = ( + "agents/gcbc.py", + "utils/datasets.py", + "utils/encoders.py", + "utils/networks.py", +) +VISUAL_GCIQL_BATCH_SIZE = 256 +PIXEL_SCORER_TARGET_UPDATE_SOURCE = ( + "just_updated_live_twin_pixel_scorer" +) +PIXEL_SCORER_TARGET_UPDATE_TIMING = ( + "polyak_after_current_gradient_update_for_next_fused_step" +) +PIXEL_SCORER_TARGET_UPDATE_TAU = 0.005 + + +def _sha256_file(path): + """Return the lowercase SHA-256 digest of an artifact without loading it.""" + digest = hashlib.sha256() + with open(path, "rb") as file: + for chunk in iter(lambda: file.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _visual_actor_reference_sha256(reference_root): + """Hash the exact OGBench modules pinned by the GCBC initializer.""" + digest = hashlib.sha256() + reference_root = os.path.realpath(os.path.abspath( + os.path.expanduser(reference_root))) + for relative_path in VISUAL_ACTOR_REFERENCE_FILES: + path = os.path.join(reference_root, relative_path) + assert os.path.isfile(path), ( + f"missing active OGBench reference file: {path}") + with open(path, "rb") as file: + digest.update(relative_path.encode()) + digest.update(file.read()) + return digest.hexdigest() + + +def _load_pinned_latent_occupancy_source( + latent_path, strict_pixel_data_diet): + """Open the exact allowlisted latent-cache arrays for the audit mode.""" + with np.load(latent_path, allow_pickle=False) as artifact: + required = {"z", "state_h"} + if not strict_pixel_data_diet: + required.update({"actions", "terminals"}) + missing = sorted(required.difference(artifact.files)) + assert not missing, f"latent artifact lacks {missing}" + available = sorted(artifact.files) + z_base = np.asarray(artifact["z"], np.float32) + state_h = np.asarray(artifact["state_h"], np.float32) + if strict_pixel_data_diet: + dataset_actions = None + terminals = None + latent_encoder_recorded = None + else: + dataset_actions = np.clip( + np.asarray(artifact["actions"], np.float32), + -1.0, 1.0) + terminals = np.asarray(artifact["terminals"], bool) + latent_encoder_recorded = ( + str(np.asarray(artifact["encoder_npz"]).item()) + if "encoder_npz" in artifact.files else None) + return { + "z": z_base, + "state_h": state_h, + "actions": dataset_actions, + "terminals": terminals, + "encoder_npz": latent_encoder_recorded, + "arrays_available": available, + "arrays_read": ( + ["z", "state_h"] + if strict_pixel_data_diet + else ["z", "state_h", "actions", "terminals"]), + "metadata_arrays_read": ( + ["encoder_npz"] + if latent_encoder_recorded is not None else []), + "forbidden_arrays_read": [], + } + + +def _load_pinned_pixel_source(meta): + """Load only rendered RGB, actions, and source trajectory terminals.""" + dataset_meta = meta.get("pixel_actor_dataset") + provenance = meta.get("pixel_artifact_provenance") + assert isinstance(dataset_meta, dict), ( + "raw-pixel checkpoint lacks pixel_actor_dataset metadata") + assert isinstance(provenance, dict), ( + "raw-pixel checkpoint lacks pixel artifact provenance") + pinned = provenance.get("pixel_dataset") + assert isinstance(pinned, dict), ( + "raw-pixel checkpoint lacks pinned pixel-dataset provenance") + dataset_path = os.path.realpath(os.path.abspath( + os.path.expanduser(str(pinned.get("path", ""))))) + assert os.path.isfile(dataset_path), ( + f"checkpoint-pinned pixel dataset does not exist: {dataset_path}") + expected_sha256 = str(pinned.get("sha256", "")) + assert ( + len(expected_sha256) == 64 + and all(piece in "0123456789abcdef" for piece in expected_sha256)), ( + "pixel dataset provenance lacks a lowercase SHA-256") + assert dataset_meta.get("path") == pinned["path"] + assert dataset_meta.get("sha256") == expected_sha256 + actual_sha256 = _sha256_file(dataset_path) + assert actual_sha256 == expected_sha256, ( + "pixel dataset SHA-256 does not match checkpoint provenance") + + assert set(dataset_meta.get("dataset_keys", ())) == ( + PIXEL_ACTOR_DATASET_KEYS) + assert PIXEL_ACTOR_FORBIDDEN_KEYS.issubset( + set(dataset_meta.get("excluded_keys", ()))), ( + "pixel dataset metadata does not exclude every forbidden field") + assert dataset_meta.get("actions_match_latent_cache") is True + assert dataset_meta.get( + "source_terminals_match_latent_cache") is True + assert dataset_meta.get( + "compact_terminals_match_reconstructed") is True + assert dataset_meta.get("terminal_alignment_contract") == ( + "latent_source_endpoints_equal_pixel_valids_zero_and_compact_" + "terminals_equal_source_plus_shifted_source") + + # ``pixel_actor_dataset.dataset_keys`` describes the compact OGBench loader + # view used in training, not the physical source NPZ. The released source + # also contains qpos/qvel; list them for audit but never index them. + with np.load(dataset_path, allow_pickle=False) as artifact: + available = sorted(artifact.files) + available_set = set(available) + assert PIXEL_ACTOR_PHYSICAL_REQUIRED_KEYS.issubset( + available_set), ( + "checkpoint-pinned pixel source lacks a required RGB/action/" + "terminal array") + assert ( + available_set - PIXEL_ACTOR_PHYSICAL_REQUIRED_KEYS + ).issubset(PIXEL_ACTOR_FORBIDDEN_KEYS), ( + "checkpoint-pinned pixel source contains an unexpected array") + observations = np.asarray(artifact["observations"]) + actions = np.asarray(artifact["actions"], dtype=np.float32) + source_terminals = np.asarray( + artifact["terminals"], dtype=bool) + assert observations.ndim == 4 and observations.shape[-1] == 3 + assert observations.dtype == np.uint8 + assert actions.ndim == 2 + assert len(observations) == len(actions) == len(source_terminals) + # The compact dataset-only loader sets valids from the source endpoints + # and then additionally marks the final valid transition as terminal. + # Reconstruct both arrays exactly without opening any simulator state. + valids = (~source_terminals).astype(np.float32) + expected_compact_terminals = np.minimum( + source_terminals.astype(np.int8) + + np.concatenate([ + source_terminals[1:].astype(np.int8), + np.ones((1,), np.int8), + ]), + 1, + ).astype(bool) + valid_indices = np.flatnonzero(valids > 0).astype(np.int32) + assert len(valid_indices) + assert list(observations.shape[1:]) == dataset_meta.get( + "observation_shape") + assert str(observations.dtype) == dataset_meta.get( + "observation_dtype") + assert list(actions.shape[1:]) == dataset_meta.get("action_shape") + assert int(dataset_meta.get("row_count", -1)) == len(observations) + assert int(dataset_meta.get( + "valid_transition_count", -1)) == len(valid_indices) + return ( + observations, + np.clip(actions, -1.0, 1.0), + source_terminals, + valid_indices, + { + "path": dataset_path, + "sha256": actual_sha256, + "physical_arrays_available": available, + "physical_arrays_read": [ + "actions", "observations", "terminals"], + "processed_dataset_view_arrays": sorted( + PIXEL_ACTOR_DATASET_KEYS), + "processed_valids_reconstructed": True, + "processed_compact_terminals_reconstructed": True, + "processed_compact_terminal_count": int( + expected_compact_terminals.sum()), + "forbidden_arrays_available": sorted( + available_set & PIXEL_ACTOR_FORBIDDEN_KEYS), + "forbidden_arrays_read": [], + "row_count": int(len(observations)), + "valid_transition_count": int(len(valid_indices)), + "actions_match_latent_cache_claim": True, + "source_terminals_match_latent_cache_claim": True, + "duplicate_latent_action_or_terminal_arrays_read": False, + }, + ) + + +def _load_pinned_pixel_actor_dataset( + meta, latent_actions, latent_terminals): + """Load the strict source and additionally verify legacy latent copies.""" + ( + observations, + actions, + source_terminals, + valid_indices, + audit, + ) = _load_pinned_pixel_source(meta) + latent_actions = np.asarray(latent_actions, np.float32) + latent_terminals = np.asarray(latent_terminals, bool) + assert len(actions) == len(latent_actions) == len(latent_terminals) + assert actions.shape == latent_actions.shape + assert np.array_equal(actions, latent_actions), ( + "pinned pixel-dataset actions are not row-aligned with latents") + assert np.array_equal(source_terminals, latent_terminals), ( + "pinned pixel-source trajectory endpoints are not row-aligned with " + "the latent cache") + audit.update({ + "actions_match_latent_cache": True, + "source_terminals_match_latent_cache": True, + "duplicate_latent_action_or_terminal_arrays_read": True, + }) + return observations, valid_indices, audit + + +def _pixel_actor_definition(action_dim, reference_root=None): + """Construct the checkpoint's exact raw-pixel actor definition.""" + if reference_root is None: + reference_root = os.environ.get("OGBENCH_IMPLS", OGBENCH_IMPLS) + _setup_paths(reference_root) + from utils.encoders import GCEncoder, encoder_modules + from utils.networks import GCActor + + return GCActor( + hidden_dims=(512, 512, 512), + action_dim=int(action_dim), + state_dependent_std=False, + const_std=True, + gc_encoder=GCEncoder( + concat_encoder=encoder_modules["impala_small"]()), + ) + + +def _pixel_actor_mode( + params, observations, goals, action_dim, reference_root=None): + """Apply the checkpoint's exact IMPALA-small raw-pixel actor.""" + actor = _pixel_actor_definition( + action_dim, reference_root=reference_root) + return actor.apply( + {"params": params}, observations, goals).mode() + + +def _pixel_scorer_definition(reference_root=None): + """Construct the exact schema-13 twin raw-RGB scorer.""" + if reference_root is None: + reference_root = os.environ.get("OGBENCH_IMPLS", OGBENCH_IMPLS) + _setup_paths(reference_root) + from agents.gciql import get_config + from utils.encoders import GCEncoder, encoder_modules + from utils.networks import GCValue + + config = get_config() + assert tuple(config["value_hidden_dims"]) == (512, 512, 512) + return GCValue( + hidden_dims=(512, 512, 512), + layer_norm=config["layer_norm"], + ensemble=True, + gc_encoder=GCEncoder( + concat_encoder=encoder_modules["impala_small"]()), + ) + + +def _repeat_pixel_pairs_for_actions(observations, goals, actions): + """Repeat one shared state/goal image pair over each action candidate.""" + observations = np.asarray(observations) + goals = np.asarray(goals) + actions = np.asarray(actions, np.float32) + assert observations.shape == goals.shape and observations.ndim == 4 + assert actions.ndim == 3 and actions.shape[0] == len(observations) + rows, candidates = actions.shape[:2] + return ( + np.repeat(observations[:, None], candidates, axis=1).reshape( + rows * candidates, *observations.shape[1:]), + np.repeat(goals[:, None], candidates, axis=1).reshape( + rows * candidates, *goals.shape[1:]), + actions.reshape(rows * candidates, actions.shape[2]), + ) + + +def _raw_pixel_scorer_metrics( + direct_reward_samples, live_heads, ema_heads, labels, + evaluation_actions, dataset_actions, rows, actor_action_support, + crop_live_heads=None, crop_ema_heads=None): + """Compare twin raw-pixel scorers against task-gamma occupancy Q.""" + direct_reward_samples = np.asarray( + direct_reward_samples, np.float32) + live_heads = np.asarray(live_heads, np.float32) + ema_heads = np.asarray(ema_heads, np.float32) + evaluation_actions = np.asarray(evaluation_actions, np.float32) + dataset_actions = np.asarray(dataset_actions, np.float32) + rows = np.asarray(rows, np.int64) + assert direct_reward_samples.ndim == 3 + row_count, candidate_count, sample_count = ( + direct_reward_samples.shape) + assert live_heads.shape == ema_heads.shape == ( + 2, row_count, candidate_count) + assert evaluation_actions.shape[:2] == ( + row_count, candidate_count) + assert len(labels) == candidate_count + assert labels.count("data") == labels.count("actor") == 1 + assert sample_count >= 4 + + direct = direct_reward_samples.mean(axis=-1) + split = sample_count // 2 + direct_first = direct_reward_samples[:, :, :split].mean(axis=-1) + direct_second = direct_reward_samples[:, :, split:].mean(axis=-1) + live = live_heads.min(axis=0) + ema = ema_heads.min(axis=0) + + data_index = labels.index("data") + actor_index = labels.index("actor") + data_local_indices = [ + index for index, label in enumerate(labels) + if label == "data" or label.startswith("data_local_") + ] + actor_local_indices = [ + index for index, label in enumerate(labels) + if label == "actor" or label.startswith("actor_local_") + ] + data_actor_indices = [data_index, actor_index] + + def scorer_block(scores): + return { + "all_candidates_fidelity": _fidelity(scores, direct), + "behavior_action_fidelity": _fidelity( + scores[:, data_index], direct[:, data_index]), + "data_local_fidelity": _fidelity( + scores[:, data_local_indices], + direct[:, data_local_indices]), + "actor_local_fidelity": _fidelity( + scores[:, actor_local_indices], + direct[:, actor_local_indices]), + "all_candidates_ranking": _ranking_metrics(direct, scores), + "data_local_ranking": _ranking_metrics( + direct[:, data_local_indices], + scores[:, data_local_indices]), + "actor_local_ranking": _ranking_metrics( + direct[:, actor_local_indices], + scores[:, actor_local_indices]), + "data_actor_ranking": _ranking_metrics( + direct[:, data_actor_indices], + scores[:, data_actor_indices]), + "all_candidate_gap_fidelity": _pairwise_gap_metrics( + direct, scores), + "data_actor_gap_fidelity": _pairwise_gap_metrics( + direct[:, data_actor_indices], + scores[:, data_actor_indices]), + } + + direct_actor_delta = ( + direct[:, actor_index] - direct[:, data_index]) + live_actor_delta = live[:, actor_index] - live[:, data_index] + ema_actor_delta = ema[:, actor_index] - ema[:, data_index] + direct_prefers_actor = direct_actor_delta > 0.0 + live_prefers_actor = live_actor_delta > 0.0 + ema_prefers_actor = ema_actor_delta > 0.0 + + action_sd = dataset_actions.std(axis=0) + 1e-6 + actor_action = evaluation_actions[:, actor_index] + paired_l2 = np.linalg.norm( + actor_action - dataset_actions[rows], axis=1) + normalized_l2 = np.linalg.norm( + (actor_action - dataset_actions[rows]) + / action_sd[None, :], + axis=1, + ) + low = np.quantile(dataset_actions, 0.01, axis=0) + high = np.quantile(dataset_actions, 0.99, axis=0) + outside = np.any( + (actor_action < low) | (actor_action > high), axis=1) + + crop_metrics = { + "enabled": crop_live_heads is not None, + "shared_state_goal_offset_per_row": ( + True if crop_live_heads is not None else None), + "same_cropped_pair_reused_across_action_candidates": ( + True if crop_live_heads is not None else None), + "padding": 3 if crop_live_heads is not None else None, + "padding_mode": "edge" if crop_live_heads is not None else None, + "live": None, + "ema": None, + } + if crop_live_heads is not None: + crop_live_heads = np.asarray(crop_live_heads, np.float32) + crop_ema_heads = np.asarray(crop_ema_heads, np.float32) + assert ( + crop_live_heads.shape == crop_ema_heads.shape + and crop_live_heads.ndim == 4 + and crop_live_heads.shape[1:] == live_heads.shape) + crop_live = crop_live_heads.min(axis=1) + crop_ema = crop_ema_heads.min(axis=1) + + def crop_block(cropped, unaugmented): + return { + "trial_count": int(cropped.shape[0]), + "fidelity_to_direct_q": _fidelity( + cropped, np.broadcast_to( + direct, cropped.shape)), + "absolute_change_from_unaugmented": _summary( + np.abs(cropped - unaugmented[None])), + "per_candidate_std_across_trials": _summary( + cropped.std(axis=0)), + "pairwise_rank_agreement_with_unaugmented_mean": float( + np.mean([ + _pairwise_rank_agreement( + unaugmented, trial) + for trial in cropped + ])), + } + + crop_metrics["live"] = crop_block(crop_live, live) + crop_metrics["ema"] = crop_block(crop_ema, ema) + + return { + "schema_version": 1, + "target": ( + "task_gamma_discount_conditioned_ema_occupancy_" + "index_reader_expectation"), + "recorded_action_training_target": ( + "empirical_absorbing_geometric_index_return_not_occupancy"), + "counterfactual_ground_truth_available": False, + "candidate_labels": list(labels), + "common_occupancy_noise_across_action_candidates": True, + "direct_q_monte_carlo": { + "samples": int(sample_count), + "split_half_pairwise_rank_agreement": + _pairwise_rank_agreement( + direct_first, direct_second), + "all_candidate_q": _summary(direct), + "data_q": _summary(direct[:, data_index]), + "actor_q": _summary(direct[:, actor_index]), + }, + "live_scorer": scorer_block(live), + "ema_scorer": scorer_block(ema), + "twin_disagreement": { + "live_all_candidates": _gap_metrics(live_heads), + "live_behavior_actions": _gap_metrics( + live_heads[:, :, data_index]), + "live_actor_actions": _gap_metrics( + live_heads[:, :, actor_index]), + "ema_all_candidates": _gap_metrics(ema_heads), + "ema_behavior_actions": _gap_metrics( + ema_heads[:, :, data_index]), + "ema_actor_actions": _gap_metrics( + ema_heads[:, :, actor_index]), + }, + "actor_drift": { + "paired_behavior_l2": _summary(paired_l2), + "paired_behavior_l2_normalized_by_action_sd": _summary( + normalized_l2), + "row_outside_dataset_p01_p99_rate": float(outside.mean()), + "direct_q_actor_minus_data": _summary(direct_actor_delta), + "live_scorer_actor_minus_data": _summary(live_actor_delta), + "ema_scorer_actor_minus_data": _summary(ema_actor_delta), + "direct_prefers_actor_rate": float( + direct_prefers_actor.mean()), + "live_scorer_prefers_actor_rate": float( + live_prefers_actor.mean()), + "ema_scorer_prefers_actor_rate": float( + ema_prefers_actor.mean()), + "live_preference_agrees_with_direct_rate": float(np.mean( + live_prefers_actor == direct_prefers_actor)), + "ema_preference_agrees_with_direct_rate": float(np.mean( + ema_prefers_actor == direct_prefers_actor)), + "live_scorer_only_actor_preference_rate": float(np.mean( + live_prefers_actor & ~direct_prefers_actor)), + "ema_scorer_only_actor_preference_rate": float(np.mean( + ema_prefers_actor & ~direct_prefers_actor)), + "live_scorer_only_actor_preference_and_ood_rate": float( + np.mean( + live_prefers_actor + & ~direct_prefers_actor + & outside)), + "ema_scorer_only_actor_preference_and_ood_rate": float( + np.mean( + ema_prefers_actor + & ~direct_prefers_actor + & outside)), + }, + "action_support": actor_action_support, + "shared_crop_stress": crop_metrics, + } + + +def _is_raw_pixel_hidden_one_hop(meta): + """Whether metadata names the schema-10+ pixel/h256 one-hop contract.""" + return bool( + int(meta.get("schema_version", -1)) >= 10 + and meta.get("actor_input") == "pixels" + and meta.get("recursion") == "off" + and meta.get("goal_hidden") is True + and meta.get("future_feature") + == "frozen_encoder_hidden_occupancy_state" + ) + + +def _is_raw_pixel_compact_one_hop(meta): + """Whether metadata names the schema-10+ pixel/z8 one-hop contract.""" + return bool( + int(meta.get("schema_version", -1)) >= 10 + and meta.get("actor_input") == "pixels" + and meta.get("recursion") == "off" + and meta.get("goal_hidden") is False + and meta.get("future_feature") + == "compact_reward_predictive_z" + ) + + +def _is_raw_pixel_reward_metric_one_hop(meta): + """Whether metadata names the schema-13 h-goal/metric-u contract.""" + return bool( + int(meta.get("schema_version", -1)) >= 13 + and meta.get("actor_input") == "pixels" + and meta.get("recursion") == "off" + and meta.get("goal_hidden") is True + and meta.get("future_feature") + == "goal_relative_reader_metric_u" + and meta.get("occupancy_target_space") + == "goal_relative_reader_metric" + ) + + +def _project_hidden_support( + values, target_mean, active_mask, array_module=np): + """Apply RSM's raw-h ReLU and constant-coordinate support projection.""" + xp = array_module + values = xp.asarray(values) + target_mean = xp.asarray(target_mean) + active_mask = xp.asarray(active_mask, dtype=bool) + projected = xp.where(active_mask, values, target_mean) + return xp.maximum(projected, xp.asarray(0.0, dtype=values.dtype)) + + +def _hidden_future_support_contract( + future_latents, meta, target_mean=None, target_std=None): + """Reconstruct and verify the exact h256 active-dimension contract.""" + future_latents = np.asarray(future_latents, np.float32) + assert future_latents.ndim == 2 + assert future_latents.shape[1] == 256, ( + "staged hidden recursion must model the frozen h256 feature") + assert np.all(np.isfinite(future_latents)) + assert float(future_latents.min()) >= 0.0, ( + "cached state_h must be the frozen encoder's ReLU output") + cached_mean = future_latents.mean(axis=0) + raw_std = future_latents.std(axis=0) + active = raw_std > 0.0 + active_count = int(active.sum()) + constant_count = int(len(active) - active_count) + assert active_count > 0 + assert int(meta["occupancy_active_future_dims"]) == active_count, ( + "saved active-future count does not match exact cached-h std>0 mask") + assert int(meta["occupancy_constant_future_dims"]) == constant_count, ( + "saved constant-future count does not match exact cached-h mask") + assert meta.get("constant_future_masking") is (constant_count > 0), ( + "saved constant-future masking flag does not match cached h256") + saved_recursive_projection = meta.get( + "recursive_state_support_projection") + if _is_raw_pixel_hidden_one_hop(meta): + # The field is deliberately recursion-specific and therefore None + # when composition is off. Schema-10+ rsm.py still applies the same + # active mask throughout flow sampling and then ReLU/constant-mean + # projection to every generated hidden future. + assert saved_recursive_projection is None + projection_source = ( + "schema10_hidden_future_sampling_contract_recursion_off") + else: + assert saved_recursive_projection == ( + "relu_nonnegative_plus_constant_mean") + projection_source = "saved_recursive_state_support_projection" + assert meta.get("occupancy_target_standardization") == ( + "per_dimension_dataset_mean_std") + if target_mean is not None: + assert np.allclose( + np.asarray(target_mean, np.float32), cached_mean, + rtol=2e-5, atol=2e-6), ( + "serialized hidden target mean differs from cached h256") + if target_std is not None: + assert np.allclose( + np.asarray(target_std, np.float32), raw_std + 1e-6, + rtol=2e-5, atol=2e-6), ( + "serialized hidden target std differs from cached h256") + return active, { + "rule": "exact_cached_future_std_greater_than_zero", + "total_dimensions": int(len(active)), + "active_dimensions": active_count, + "constant_dimensions": constant_count, + "mask_sha256": hashlib.sha256( + active.astype(np.uint8).tobytes()).hexdigest(), + "relu_nonnegative_cached_support_verified": True, + "projection": "relu_nonnegative_plus_constant_mean", + "projection_source": projection_source, + "saved_recursive_state_support_projection": + saved_recursive_projection, + } + + +def _spearman(left, right): + """Finite Spearman correlation, with a conservative zero for constants.""" + from scipy.stats import spearmanr + + value = spearmanr( + np.asarray(left).reshape(-1), + np.asarray(right).reshape(-1), + ).statistic + return float(value) if np.isfinite(value) else 0.0 + + +def _fidelity(prediction, target): + """Calibration and fidelity of a predicted conditional expectation.""" + prediction = np.asarray(prediction, np.float64).reshape(-1) + target = np.asarray(target, np.float64).reshape(-1) + assert prediction.shape == target.shape and prediction.size > 1 + error = prediction - target + target_sd = float(target.std()) + pred_sd = float(prediction.std()) + if target_sd > 1e-12 and pred_sd > 1e-12: + pearson = float(np.corrcoef(prediction, target)[0, 1]) + design = np.stack( + [np.ones_like(prediction), prediction], axis=1) + intercept, slope = np.linalg.lstsq( + design, target, rcond=None)[0] + else: + pearson = 0.0 + intercept, slope = float(target.mean()), 0.0 + + # Equal-count calibration bins avoid empty-bin ambiguity in sparse reward + # ranges. They compare the conditional target mean with the model mean; + # no environment reward or coordinate is involved. + order = np.argsort(prediction, kind="stable") + bins = np.array_split(order, min(10, len(order))) + bin_rows = [ + { + "count": int(len(indices)), + "prediction_mean": float(prediction[indices].mean()), + "target_mean": float(target[indices].mean()), + "absolute_gap": float(abs( + prediction[indices].mean() - target[indices].mean())), + } + for indices in bins if len(indices) + ] + calibration_mae = float(np.average( + [row["absolute_gap"] for row in bin_rows], + weights=[row["count"] for row in bin_rows], + )) + return { + "n": int(target.size), + "target_mean": float(target.mean()), + "target_std": target_sd, + "prediction_mean": float(prediction.mean()), + "prediction_std": pred_sd, + "bias": float(error.mean()), + "mae": float(np.abs(error).mean()), + "rmse": float(np.sqrt(np.mean(error ** 2))), + "normalized_mae": float( + np.abs(error).mean() / max(target_sd, 1e-8)), + "pearson": pearson, + "spearman": _spearman(prediction, target), + "calibration_target_on_prediction_intercept": float(intercept), + "calibration_target_on_prediction_slope": float(slope), + "equal_count_bin_calibration_mae": calibration_mae, + "equal_count_bins": bin_rows, + } + + +def _pairwise_rank_agreement(left, right): + """Agreement of all within-row candidate comparisons.""" + left = np.asarray(left) + right = np.asarray(right) + assert left.shape == right.shape and left.ndim == 2 + first, second = np.triu_indices(left.shape[1], 1) + if len(first) == 0: + return 1.0 + left_gap = left[:, first] - left[:, second] + right_gap = right[:, first] - right[:, second] + return float(np.mean(np.sign(left_gap) == np.sign(right_gap))) + + +def _energy_distance(model, target, scale): + """Per-condition energy distance in dataset-standardized latent units.""" + model = np.asarray(model, np.float64) + target = np.asarray(target, np.float64) + scale = np.asarray(scale, np.float64) + assert model.shape == target.shape and model.ndim == 3 + model = model / scale[None, None, :] + target = target / scale[None, None, :] + + cross = np.linalg.norm( + model[:, :, None, :] - target[:, None, :, :], axis=-1).mean( + axis=(1, 2)) + model_self = np.linalg.norm( + model[:, :, None, :] - model[:, None, :, :], axis=-1).mean( + axis=(1, 2)) + target_self = np.linalg.norm( + target[:, :, None, :] - target[:, None, :, :], axis=-1).mean( + axis=(1, 2)) + distance = np.maximum( + 2.0 * cross - model_self - target_self, 0.0) + ratio = distance / np.maximum(target_self, 1e-8) + return distance, ratio, target_self + + +def _exact_absorbing_occupancy( + future_latents, rows, goal_indices, ends, discount, sample_count, + reader_probability, reward_latents=None): + """Exact finite-trajectory target for RSM's absorbing-goal sampler. + + The deterministic quantile samples are used only for distributional + comparisons. Means, variances, and reward expectations are computed from + the exact normalized geometric weights, not from those samples. The + distribution and reward features may differ: hidden-future recursion is + compared in cached h256, while exact reward labels deliberately use the + separately cached compact z that trained the frozen diagonal reader. + """ + future_latents = np.asarray(future_latents, np.float32) + reward_latents = ( + future_latents if reward_latents is None + else np.asarray(reward_latents, np.float32)) + rows = np.asarray(rows, np.int64) + goal_indices = np.asarray(goal_indices, np.int64) + ends = np.asarray(ends, np.int64) + assert ( + future_latents.ndim == reward_latents.ndim == 2 + and len(future_latents) == len(reward_latents)) + assert 0.0 < float(discount) < 1.0 + assert sample_count > 1 + batch, latent_dim = len(rows), future_latents.shape[1] + means = np.empty((batch, latent_dim), np.float32) + variances = np.empty_like(means) + reward_means = np.empty(batch, np.float32) + samples = np.empty((batch, sample_count, latent_dim), np.float32) + reward_samples = np.empty((batch, sample_count), np.float32) + quantiles = ( + np.arange(sample_count, dtype=np.float64) + 0.5) / sample_count + + for index, (row, goal) in enumerate(zip(rows, goal_indices)): + assert row <= goal < ends[row], ( + "the gate uses same-trajectory future actor goals") + raw_steps = np.arange(ends[row] - row, dtype=np.int64) + mapped = np.minimum(row + raw_steps, goal) + values = future_latents[mapped] + log_weights = raw_steps.astype(np.float64) * np.log(discount) + weights = np.exp(log_weights - log_weights.max()) + weights /= weights.sum() + mean = np.sum(weights[:, None] * values, axis=0) + means[index] = mean + variances[index] = np.sum( + weights[:, None] * np.square(values - mean), axis=0) + + reward_values = reward_latents[mapped] + reward_goals = np.repeat( + reward_latents[goal][None, :], len(values), axis=0) + reward = np.asarray( + reader_probability(reward_values, reward_goals), np.float64) + assert reward.shape == (len(values),) + reward_means[index] = np.sum(weights * reward) + + chosen = np.searchsorted( + np.cumsum(weights), quantiles, side="left") + chosen = np.minimum(chosen, len(values) - 1) + samples[index] = values[chosen] + reward_samples[index] = reward[chosen] + + return { + "mean": means, + "variance": variances, + "reward_mean": reward_means, + "samples": samples, + "reward_samples": reward_samples, + } + + +def _distribution_metrics( + model_samples, model_reward_samples, exact, target_std, + active_mask=None): + """Distribution and reward-readout fidelity for one discount.""" + model_samples = np.asarray(model_samples, np.float32) + model_reward_samples = np.asarray( + model_reward_samples, np.float32) + target_std = np.asarray(target_std, np.float32) + if active_mask is None: + active_mask = np.ones(model_samples.shape[-1], dtype=bool) + active_mask = np.asarray(active_mask, bool) + assert active_mask.shape == (model_samples.shape[-1],) + assert np.any(active_mask) + model_distribution_samples = model_samples[..., active_mask] + exact_distribution_samples = exact["samples"][..., active_mask] + exact_mean = exact["mean"][..., active_mask] + exact_variance = exact["variance"][..., active_mask] + distribution_std = target_std[active_mask] + model_mean = model_distribution_samples.mean(axis=1) + model_variance = model_distribution_samples.var(axis=1) + mean_rmse = float(np.sqrt(np.mean(np.square( + (model_mean - exact_mean) / distribution_std[None, :])))) + variance_rmse = float(np.sqrt(np.mean(np.square( + (model_variance - exact_variance) + / np.square(distribution_std)[None, :])))) + energy, energy_ratio, exact_spread = _energy_distance( + model_distribution_samples, exact_distribution_samples, + distribution_std) + model_reward = model_reward_samples.mean(axis=1) + reward_wasserstein = np.mean(np.abs( + np.sort(model_reward_samples, axis=1) + - np.sort(exact["reward_samples"], axis=1)), axis=1) + model_mc_se = ( + model_reward_samples.std(axis=1, ddof=1) + / np.sqrt(model_reward_samples.shape[1])) + aggregate_energy_ratio = float( + energy.mean() / max(float(exact_spread.mean()), 1e-8)) + return { + "reward_expectation": _fidelity( + model_reward, exact["reward_mean"]), + "reward_distribution_wasserstein": { + **_summary(reward_wasserstein), + "space": "canonical_diag_metric_probability", + }, + "reward_monte_carlo_standard_error": _summary(model_mc_se), + "future_latent_distribution": { + "total_dimension_count": int(model_samples.shape[-1]), + "evaluated_active_dimension_count": int(active_mask.sum()), + "exact_active_dimension_mask_applied": bool( + not np.all(active_mask)), + "mean_rmse_in_dataset_latent_sd": mean_rmse, + "variance_rmse_in_dataset_latent_variance": variance_rmse, + "model_to_exact_variance_ratio": float( + model_variance.mean() + / max(float(exact_variance.mean()), 1e-8)), + "energy_distance_in_dataset_latent_sd": _summary(energy), + "energy_distance_over_exact_pairwise_spread": _summary( + energy_ratio), + "mean_energy_distance_over_mean_exact_pairwise_spread": + aggregate_energy_ratio, + "exact_pairwise_spread_in_dataset_latent_sd": _summary( + exact_spread), + }, + } + + +def _discount_grid(meta, requested, recursion_beta): + """Audited training bins plus candidate beta and task gamma.""" + gamma_lo = float(meta["gamma_spectrum_lo"]) + gamma_hi = float(meta["gamma"]) + if requested: + horizons = np.asarray([ + float(piece) for piece in requested.split(",") + if piece.strip() + ], np.float64) + assert len(horizons) and np.all(horizons > 1.0) + discounts = 1.0 - 1.0 / horizons + elif meta.get("gamma_aux_discounts") is not None: + discounts = np.asarray( + meta["gamma_aux_discounts"], np.float64) + else: + discounts = np.asarray([], np.float64) + discounts = np.r_[discounts, recursion_beta, gamma_hi] + discounts = np.unique(np.round(discounts, 8)) + assert np.all(discounts >= gamma_lo - 1e-7), ( + "requested discount lies below the trained spectrum") + assert np.all(discounts <= gamma_hi + 1e-7), ( + "requested discount lies above the trained spectrum") + return discounts.astype(np.float32) + + +def _stable_largest_remainder_counts(total, weights): + """Independently reconstruct the trainer's deterministic allocation.""" + weights = np.asarray(weights, np.float64) + assert weights.ndim == 1 and len(weights) + assert np.all(np.isfinite(weights)) and np.all(weights >= 0.0) + assert float(weights.sum()) > 0.0 + ideal = int(total) * weights / weights.sum() + counts = np.floor(ideal).astype(np.int64) + order = np.argsort(-(ideal - counts), kind="stable") + counts[order[:int(total) - int(counts.sum())]] += 1 + return [int(value) for value in counts] + + +def _assert_protected_endpoint_contract(meta): + """Fail closed on schema-11 protected gamma/beta supervision.""" + assert int(meta.get("schema_version", -1)) >= 11 + assert meta.get("protected_endpoint_sampler") is True + assert float(meta.get("gamma_task_fraction", -1.0)) == 0.60 + assert float(meta.get( + "protected_endpoint_task_fraction", -1.0)) == 0.60 + assert float(meta.get( + "protected_endpoint_beta_fraction", -1.0)) == 0.30 + assert float(meta.get( + "protected_endpoint_aux_fraction", -1.0)) == 0.10 + assert meta.get("protected_endpoint_aux_allocation") == ( + "deterministic_largest_remainder_sqrt_h") + assert meta.get( + "protected_endpoint_overrides_legacy_fraction_flags") is True + assert meta.get("gamma_batch_allocation") == ( + "exact_60pct_task_30pct_beta_10pct_sqrt_h_aux_then_joint_" + "discount_goal_source_shuffle") + assert meta.get("gamma_sampling_importance_weighted") is False + assert meta.get("gamma_normalization") == "fixed_fourier_identity" + + gamma = float(meta["gamma"]) + beta = float(meta["rec_beta"]) + assert 0.0 < beta < gamma < 1.0 + requested_horizons = np.asarray( + meta.get("protected_endpoint_requested_horizons"), np.float64) + excluded_horizons = np.asarray( + meta.get("protected_endpoint_excluded_beta_horizons"), np.float64) + aux_horizons = np.asarray(meta.get("gamma_horizons"), np.float64) + aux_discounts = np.asarray( + meta.get("gamma_aux_discounts"), np.float64) + assert requested_horizons.ndim == excluded_horizons.ndim == 1 + assert aux_horizons.ndim == aux_discounts.ndim == 1 + assert len(aux_horizons) and len(aux_horizons) == len(aux_discounts) + assert np.all(np.diff(requested_horizons) > 0.0) + requested_discounts = 1.0 - 1.0 / requested_horizons + beta_duplicate = np.isclose( + requested_discounts, beta, rtol=1e-7, atol=1e-9) + np.testing.assert_allclose( + excluded_horizons, requested_horizons[beta_duplicate]) + np.testing.assert_allclose( + aux_horizons, requested_horizons[~beta_duplicate]) + np.testing.assert_allclose( + aux_discounts, 1.0 - 1.0 / aux_horizons) + assert not np.any(np.isclose( + aux_discounts, beta, rtol=1e-7, atol=1e-9)) + assert np.all(aux_discounts < gamma) + + batch = int(meta["occ_batch"]) + task_rows = int(round(0.60 * batch)) + beta_rows = int(round(0.30 * batch)) + aux_rows = batch - task_rows - beta_rows + aux_counts = _stable_largest_remainder_counts( + aux_rows, np.sqrt(aux_horizons)) + assert int(meta["gamma_task_rows_per_occ_batch"]) == task_rows + assert int(meta["gamma_beta_rows_per_occ_batch"]) == beta_rows + assert list(meta["gamma_aux_rows_per_occ_batch"]) == aux_counts + group_counts = [task_rows, beta_rows, *aux_counts] + actor_counts = _stable_largest_remainder_counts( + int(round(0.50 * batch)), group_counts) + value_counts = [ + count - actor + for count, actor in zip(group_counts, actor_counts) + ] + assert float(meta["protected_endpoint_goal_source_fraction"]) == 0.50 + assert float(meta["occupancy_actor_goal_fraction"]) == 0.50 + assert int(meta["occupancy_actor_goal_rows_per_batch"]) == int( + round(0.50 * batch)) + assert list(meta[ + "protected_endpoint_actor_rows_by_discount"]) == actor_counts + assert list(meta[ + "protected_endpoint_value_rows_by_discount"]) == value_counts + assert meta.get("protected_endpoint_cross_stratification") == ( + "exact_global_50pct_each_source_largest_remainder_by_discount") + assert meta.get("condition_normalizer_goal_sampler") == ( + "exact_mixture_actor_uniform_future_0.5_plus_" + "gciql_value_goals_20_current_50_trajectory_30_random") + + probe_count = int(meta["condition_normalizer_probe_size"]) + assert probe_count == 20000 + probe_task = int(round(0.60 * probe_count)) + probe_beta = int(round(0.30 * probe_count)) + probe_aux = probe_count - probe_task - probe_beta + probe_aux_counts = _stable_largest_remainder_counts( + probe_aux, np.sqrt(aux_horizons)) + probe_groups = [probe_task, probe_beta, *probe_aux_counts] + probe_actor = _stable_largest_remainder_counts( + int(round(0.50 * probe_count)), probe_groups) + probe_value = [ + count - actor + for count, actor in zip(probe_groups, probe_actor) + ] + assert list(meta[ + "protected_endpoint_normalizer_discount_rows"]) == probe_groups + assert list(meta[ + "protected_endpoint_normalizer_actor_rows_by_discount"]) == ( + probe_actor) + assert list(meta[ + "protected_endpoint_normalizer_value_rows_by_discount"]) == ( + probe_value) + assert int(meta["condition_normalizer_actor_goal_rows"]) == int( + round(0.50 * probe_count)) + assert float(meta["rec_beta_sample_prob"]) == 0.30 + + for key in ( + "occ_reader_metric_uses_reward_arrays", + "occ_reader_metric_uses_coordinates", + "occ_reader_metric_uses_td_or_bootstrap", + "occ_reader_hit_importance_weighted", + "occ_reader_hit_action_contrast_weights_changed", + "occ_reader_hit_uses_reward_arrays", + "occ_reader_hit_uses_coordinates", + "occ_reader_hit_uses_td_or_bootstrap"): + assert meta.get(key) is False, ( + f"protected checkpoint violates {key}=false") + hit_weight = float(meta.get("occ_reader_hit_weight", 0.0)) + assert hit_weight >= 0.0 + assert meta.get("occ_reader_hit_enabled") is (hit_weight > 0.0) + if hit_weight > 0.0: + assert float(meta.get("occ_reader_metric_weight", -1.0)) == 0.0 + assert meta.get("occ_reader_metric_enabled") is False + assert meta.get("occ_reader_geometry_enabled") is True + assert meta.get("occ_reader_metric_model") == "diag_metric" + assert meta.get("occ_reader_metric_target") == "index" + assert meta.get("occ_reader_hit_endpoint_weights") == [0.5, 0.5] + assert meta.get("occ_reader_hit_mask") == ( + "same_trajectory_and_goal_index_gt_t_and_take_hit") + assert meta.get("occ_reader_hit_importance_weighted") is False + assert meta.get("occ_reader_hit_base_mle_formula") == ( + "E_q[w_IS*e_base]=" + "mean(hit_miss_importance_weight*base_flow_mse)") + assert meta.get("occ_reader_hit_take_hit_probability") == 0.5 + assert meta.get("occ_reader_hit_target_source") == ( + "sampled_same_trajectory_future_index_relabel_take_hit") + assert meta.get("occ_reader_hit_uses_index_relabeling") is True + else: + assert meta.get("occ_reader_hit_enabled") is False + + +def _assert_reward_metric_endpoint_contract(meta): + """Reconstruct the schema-13 configurable exact endpoint allocation.""" + assert int(meta.get("schema_version", -1)) >= 13 + assert meta.get("gamma_sampler") == "reward_metric_endpoints" + assert meta.get("reward_metric_endpoint_sampler") is True + assert meta.get("protected_endpoint_sampler") is False + assert float(meta.get("gamma", -1.0)) == 0.99 + assert float(meta.get("rec_beta", -1.0)) == 0.98 + assert float(meta.get("gamma_spectrum_lo", -1.0)) == 0.875 + task_fraction = float(meta.get("gamma_task_fraction", -1.0)) + beta_fraction = float(meta.get("rec_beta_sample_prob", -1.0)) + assert 0.0 < task_fraction < 1.0 + assert 0.0 < beta_fraction < 1.0 + assert task_fraction + beta_fraction < 1.0 + aux_fraction = 1.0 - task_fraction - beta_fraction + assert np.isclose( + float(meta.get( + "reward_metric_endpoint_task_fraction", -1.0)), + task_fraction, rtol=0.0, atol=1e-12) + assert np.isclose( + float(meta.get( + "reward_metric_endpoint_beta_fraction", -1.0)), + beta_fraction, rtol=0.0, atol=1e-12) + assert np.isclose( + float(meta.get( + "reward_metric_endpoint_aux_fraction", -1.0)), + aux_fraction, rtol=0.0, atol=1e-12) + allocation_meta = meta.get( + "reward_metric_endpoint_aux_allocation") + allocation_by_meta = { + "deterministic_largest_remainder_uniform_horizon": "uniform", + "deterministic_largest_remainder_sqrt_h": "sqrt_h", + } + assert allocation_meta in allocation_by_meta + aux_allocation = allocation_by_meta[allocation_meta] + assert meta.get("gamma_batch_allocation") == ( + "exact_configurable_task_beta_remaining_aux_" + f"{aux_allocation}_then_shuffle") + assert meta.get("gamma_sampling_importance_weighted") is False + assert meta.get("gamma_normalization") == "fixed_fourier_identity" + horizons = tuple( + float(value) for value in meta.get("gamma_horizons", ())) + assert horizons == (8.0, 16.0, 32.0, 64.0) + assert tuple( + float(value) + for value in meta.get("reward_metric_endpoint_horizons", ()) + ) == horizons + np.testing.assert_allclose( + np.asarray(meta.get("gamma_aux_discounts"), np.float64), + 1.0 - 1.0 / np.asarray(horizons, np.float64), + rtol=0.0, + atol=1e-12, + ) + + batch = int(meta["occ_batch"]) + assert batch == 2048 + plan = reward_metric_endpoint_batch_plan( + batch, 0.99, 0.98, horizons, + task_fraction, beta_fraction, aux_allocation) + expected_task = int(round(task_fraction * batch)) + expected_beta = int(round(beta_fraction * batch)) + expected_aux = batch - expected_task - expected_beta + expected_weights = ( + np.ones(len(horizons), np.float64) + if aux_allocation == "uniform" + else np.sqrt(np.asarray(horizons, np.float64))) + expected_aux_counts = _stable_largest_remainder_counts( + expected_aux, expected_weights) + assert plan["task_rows"] == expected_task + assert plan["beta_rows"] == expected_beta + assert list(plan["aux_rows_by_horizon"]) == expected_aux_counts + assert int(meta["gamma_task_rows_per_occ_batch"]) == ( + plan["task_rows"]) + assert int(meta["gamma_beta_rows_per_occ_batch"]) == ( + plan["beta_rows"]) + assert list(meta["gamma_aux_rows_per_occ_batch"]) == list( + plan["aux_rows_by_horizon"]) + + probe_count = int(meta["condition_normalizer_probe_size"]) + assert probe_count == 20000 + probe = reward_metric_endpoint_batch_plan( + probe_count, 0.99, 0.98, horizons, + task_fraction, beta_fraction, aux_allocation) + probe_task = int(round(task_fraction * probe_count)) + probe_beta = int(round(beta_fraction * probe_count)) + probe_aux = probe_count - probe_task - probe_beta + probe_aux_counts = _stable_largest_remainder_counts( + probe_aux, expected_weights) + assert probe["task_rows"] == probe_task + assert probe["beta_rows"] == probe_beta + assert list(probe["aux_rows_by_horizon"]) == probe_aux_counts + assert list(meta[ + "reward_metric_endpoint_normalizer_discount_rows"]) == [ + probe["task_rows"], + probe["beta_rows"], + *probe["aux_rows_by_horizon"], + ] + assert float(meta["occupancy_actor_goal_fraction"]) == 0.50 + assert int(meta["occupancy_actor_goal_rows_per_batch"]) == 1024 + assert int(meta["condition_normalizer_actor_goal_rows"]) == 10000 + assert meta.get("condition_normalizer_goal_sampler") == ( + "exact_mixture_actor_uniform_future_0.5_plus_" + "gciql_value_goals_20_current_50_trajectory_30_random") + + +def _assert_raw_pixel_actor_contract( + meta, active_reference_root=None): + """Validate every saved input-diet claim for schema-10+ pixel actors.""" + schema_version = int(meta.get("schema_version", -1)) + assert schema_version >= 10 + pixel_scorer = meta.get("distill_scorer_input") == "pixels" + reward_metric_target = ( + meta.get("occupancy_target_space") + == "goal_relative_reader_metric") + if schema_version >= 13: + assert pixel_scorer or reward_metric_target, ( + "schema-13 checkpoint lacks both the raw-pixel scorer and " + "reader-metric target contracts") + else: + assert not pixel_scorer and not reward_metric_target, ( + "raw-pixel scorer and reader-metric targets require " + "schema_version >= 13") + assert meta.get("actor_input") == "pixels" + assert meta.get("actor_state_feature") == "raw_rgb_pixels" + assert meta.get("actor_goal_feature") == "raw_rgb_pixels" + assert meta.get("final_actor_consumes_pixels") is True + assert meta.get("policy_observation") == "rendered_pixels_only" + assert meta.get("actor_architecture") == ( + "GCActor_IMPALA_small_early_fusion_MLP_512x3") + assert meta.get("actor_encoder") == "impala_small" + assert meta.get("actor_encoder_trainable") is True + actor_initialization = meta.get("actor_encoder_initialization") + assert actor_initialization in ( + "fresh_jointly_trainable", + "strict_non_td_gcbc_then_jointly_trainable", + ) + assert float(meta.get( + "actor_pixel_augmentation_probability", -1.0)) == 0.5 + assert meta.get("actor_training_augmentation") == ( + "batch_probability_shared_per_row_edge_padded_random_crop") + assert meta.get("actor_goal_relabeling") == ( + "uniform_future_same_trajectory") + assert meta.get("actor_goal_dim_semantics") == ( + "raw_rgb_pixel_scorer_goal_shape" + if pixel_scorer + else "latent_supervised_scorer_goal_width") + assert meta.get("actor_transition_sampling") == ( + "uniform_over_dataset_valid_indices") + assert meta.get("pixel_dataset_device_transport") == ( + "dynamic_jit_dispatch_argument_not_xla_constant") + assert meta.get("occupancy_consumes_raw_pixels") is False + assert meta.get("raw_pixels_update_actor_only") is ( + not pixel_scorer) + assert meta.get("occupancy_state_for_pixel_actor") == meta.get( + "state_feature") + assert meta.get("occupancy_goal_for_pixel_actor") == meta.get( + "occupancy_goal_feature") + assert meta.get( + "supervised_scalar_scorer_state_for_pixel_actor") == ( + "raw_rgb_pixels" + if pixel_scorer else meta.get("state_feature")) + assert meta.get("pixel_actor_occupancy_discount_required") is True + assert meta.get("pixel_actor_recursion_supported") is False + assert meta.get("pixel_actor_generated_midpoint_policy") is None + assert meta.get( + "pixel_actor_uses_image_or_world_model_reconstruction") is False + assert meta.get( + "completion_or_world_model_carrier_instantiated") is False + assert meta.get("pixel_actor_and_occupancy_same_fused_step") is True + if pixel_scorer: + exact_pixel_scorer = { + "supervised_scalar_scorer_input": "raw_rgb_pixels", + "supervised_scalar_scorer_goal_input": "raw_rgb_pixels", + "supervised_scalar_scorer_architecture": + "GCValue_IMPALA_small_early_fusion_twin_MLP_512x3", + "supervised_scalar_scorer_encoder": "impala_small", + "supervised_scalar_scorer_encoder_trainable": True, + "supervised_scalar_scorer_ensemble_size": 2, + "supervised_scalar_scorer_target_update_source": + PIXEL_SCORER_TARGET_UPDATE_SOURCE, + "supervised_scalar_scorer_target_update_timing": + PIXEL_SCORER_TARGET_UPDATE_TIMING, + "supervised_scalar_scorer_target_update_tau": + PIXEL_SCORER_TARGET_UPDATE_TAU, + "supervised_scalar_scorer_recorded_action_target_source": + "observed_same_trajectory_absorbing_first_passage_" + "geometric_successor_compact_z_through_frozen_index_reader", + "supervised_scalar_scorer_recorded_action_uses_occupancy": False, + "supervised_scalar_scorer_target_discount": + "explicit_task_gamma", + "supervised_scalar_scorer_receives_discount_feature": False, + "supervised_scalar_scorer_training_augmentation": + "batch_probability_shared_per_row_across_state_value_goal_" + "actor_goal_edge_padded_random_crop", + "supervised_scalar_scorer_uses_proprio": False, + "supervised_scalar_scorer_uses_coordinates": False, + "supervised_scalar_scorer_uses_reward_arrays": False, + "supervised_scalar_scorer_uses_td_or_bootstrap": False, + "supervised_expectile_value_input": "raw_rgb_pixels", + "supervised_expectile_value_architecture": + "GCValue_IMPALA_small_early_fusion_single_MLP_512x3", + "supervised_expectile_value_target_source": + "stop_gradient_ema_twin_pixel_scorer_empirical_absorbing_" + "index_return_expectile", + "supervised_expectile_value_target_discount": + "explicit_task_gamma", + "supervised_expectile_value_uses_next_state": False, + "supervised_expectile_value_uses_td_or_bootstrap": False, + "supervised_expectile_value_uses_reward_arrays": False, + "pixel_scorer_and_occupancy_same_fused_step": True, + "pixel_scorer_and_actor_same_fused_step": True, + "pixel_scorer_gradient_updates_occupancy": False, + "occupancy_gradient_updates_pixel_scorer": False, + "batch_size": VISUAL_GCIQL_BATCH_SIZE, + "distill_ema_tau": PIXEL_SCORER_TARGET_UPDATE_TAU, + } + for key, expected in exact_pixel_scorer.items(): + assert meta.get(key) == expected, ( + f"raw-pixel scorer violates {key}: " + f"{meta.get(key)!r} != {expected!r}") + if meta.get("actor_loss") == "awr_distill": + assert float(meta.get("expectile", -1.0)) == 0.9 + assert meta.get("distill_actor_actions") is False + assert meta.get( + "supervised_scalar_scorer_counterfactual_target_source" + ) is None + assert meta.get( + "supervised_scalar_scorer_counterfactual_uses_empirical" + ) is None + assert meta.get("pixel_scorer_policy_extraction") == ( + "awr_dataset_action_weighted_log_likelihood") + assert meta.get("pixel_scorer_actor_advantage_source") == ( + "stop_gradient_live_twin_min_q_minus_preupdate_expectile_v") + assert meta.get("pixel_scorer_actor_weight_formula") == ( + "min(exp(alpha*(Q-V)),100)") + assert meta.get( + "pixel_scorer_actor_uses_dataset_actions_only") is True + assert meta.get("pixel_scorer_supervision_regime") == ( + "empirical_recorded_actions_only") + else: + assert meta.get("actor_loss") == "ddpgbc_distill" + assert float(meta.get("alpha", -1.0)) == 1.0 + assert float(meta.get("expectile", -1.0)) == 0.9 + counterfactual_support = bool( + meta.get("distill_actor_actions")) + assert meta.get( + "supervised_scalar_scorer_counterfactual_target_source" + ) == ( + "discount_conditioned_ema_occupancy_index_reader_expectation" + if counterfactual_support else None) + assert meta.get( + "supervised_scalar_scorer_counterfactual_uses_empirical" + ) is (False if counterfactual_support else None) + assert meta.get("pixel_scorer_policy_extraction") == ( + "ddpgbc_actor_gradient_control") + assert meta.get( + "pixel_scorer_actor_uses_dataset_actions_only") is False + assert meta.get("pixel_scorer_supervision_regime") == ( + "empirical_recorded_actions_plus_discount_conditioned_" + "occupancy_counterfactuals" + if counterfactual_support + else "empirical_recorded_actions_only") + state_shape = meta.get("actor_pixel_state_shape") + goal_shape = meta.get("actor_pixel_goal_shape") + assert ( + isinstance(state_shape, list) + and state_shape == goal_shape + and len(state_shape) == 3 + and state_shape[-1] == 3) + provenance = meta.get("pixel_artifact_provenance") + assert isinstance(provenance, dict) + for label, recorded_path in ( + ("latent_npz", meta.get("latent_npz")), + ("pixel_encoder", meta.get("pixel_encoder"))): + artifact = provenance.get(label) + assert isinstance(artifact, dict) + assert os.path.realpath(str(artifact.get("path"))) == ( + os.path.realpath(str(recorded_path))) + digest = str(artifact.get("sha256", "")) + assert ( + len(digest) == 64 + and all(piece in "0123456789abcdef" for piece in digest)) + dataset_meta = meta.get("pixel_actor_dataset") + dataset_artifact = provenance.get("pixel_dataset") + assert isinstance(dataset_meta, dict) + assert isinstance(dataset_artifact, dict) + assert dataset_meta.get("path") == dataset_artifact.get("path") + assert dataset_meta.get("sha256") == dataset_artifact.get("sha256") + assert set(dataset_meta.get("dataset_keys", ())) == ( + PIXEL_ACTOR_DATASET_KEYS) + assert PIXEL_ACTOR_FORBIDDEN_KEYS.issubset( + set(dataset_meta.get("excluded_keys", ()))) + init_meta = meta.get("pixel_actor_init") + init_checkpoint_verified = False + active_reference_verified = False + if actor_initialization == "fresh_jointly_trainable": + assert init_meta is None, ( + "fresh pixel actor must not claim an initialization checkpoint") + else: + assert isinstance(init_meta, dict), ( + "strict non-TD GCBC pixel actor lacks initialization metadata") + expected_init = { + "format": "visual_gcbc_params_v1", + "uses_td_or_bootstrap": False, + "optimizer_state_loaded": False, + "actor_remains_trainable": True, + } + for key, expected in expected_init.items(): + assert init_meta.get(key) == expected, ( + f"pixel actor initialization violates {key}={expected!r}") + assert int(init_meta.get("step", 0)) > 0 + for key in ("sha256", "reference_sha256"): + digest = str(init_meta.get(key, "")) + assert ( + len(digest) == 64 + and all(piece in "0123456789abcdef" for piece in digest)), ( + f"pixel actor initialization has invalid {key}") + init_path = os.path.realpath(os.path.abspath( + os.path.expanduser(str(init_meta.get("path", ""))))) + assert os.path.isfile(init_path), ( + "strict non-TD GCBC initialization checkpoint is missing") + assert _sha256_file(init_path) == init_meta["sha256"], ( + "strict non-TD GCBC initialization checkpoint SHA-256 mismatch") + init_checkpoint_verified = True + + saved_reference_root = os.path.realpath(os.path.abspath( + os.path.expanduser(str( + init_meta.get("reference_root", ""))))) + assert os.path.isdir(saved_reference_root), ( + "saved OGBench reference root does not exist") + if active_reference_root is not None: + active_reference_root = os.path.realpath(os.path.abspath( + os.path.expanduser(active_reference_root))) + assert saved_reference_root == active_reference_root, ( + "pixel actor initialization reference root does not match " + "the active OGBench implementation") + assert _visual_actor_reference_sha256( + active_reference_root) == init_meta["reference_sha256"], ( + "pixel actor initialization reference SHA-256 does not " + "match the active OGBench implementation") + active_reference_verified = True + return { + "actor_initialization": actor_initialization, + "strict_non_td_gcbc": ( + actor_initialization + == "strict_non_td_gcbc_then_jointly_trainable"), + "init_checkpoint_sha256_verified": init_checkpoint_verified, + "active_reference_root": ( + os.path.realpath(os.path.abspath(os.path.expanduser( + active_reference_root))) + if active_reference_root is not None else None), + "active_reference_sha256_verified": active_reference_verified, + "active_reference_files": list(VISUAL_ACTOR_REFERENCE_FILES), + } + + +def _assert_pixel_hidden_representation_contract(meta, reader_meta): + """Validate frozen/rich conditioning with frozen h256 future targets.""" + assert _is_raw_pixel_hidden_one_hop(meta) + assert meta.get("recursion_state") is None + assert meta.get("goal_hidden") is True + assert int(meta["state_dim"]) == 256 + assert int(meta["actor_goal_dim"]) == 256 + assert int(meta["occupancy_goal_dim"]) == 256 + assert int(meta["occupancy_future_dim"]) == 256 + assert int(meta.get("reward_reader_dim", -1)) == int( + reader_meta["zdim"]) + assert meta.get("future_feature") == ( + "frozen_encoder_hidden_occupancy_state") + assert meta.get("reward_goal_feature") == ( + "compact_reward_predictive_z") + assert meta.get("frozen_encoder_fc1_reward_projection") is True + latent_update = meta.get("latent_update") or "frozen" + assert latent_update in ("frozen", "rich_adapter") + if latent_update == "frozen": + assert meta.get("state_feature") == "encoder_hidden" + assert meta.get("occupancy_goal_feature") == "encoder_hidden" + else: + assert meta.get("state_feature") == ( + "joint_encoder_hidden_adapter") + assert meta.get("occupancy_goal_feature") == ( + "joint_encoder_hidden_adapter") + assert meta.get("latent_aux_target") == "index" + assert meta.get("latent_reader_model") == "diag_metric" + assert int(meta.get("latent_index_delta", -1)) == int( + reader_meta["index_delta"]) + assert int(meta.get("latent_index_neg_gap", -1)) > int( + meta["latent_index_delta"]) + assert meta.get("latent_index_negative_contract") == ( + "same_episode_far_only_cross_episode_excluded") + assert int(meta.get("adapter_feature_dim", -1)) == 256 + assert int(meta.get("latent_hidden", 0)) > 0 + assert float(meta.get("latent_lr", 0.0)) > 0.0 + assert float(meta.get("latent_goal_weight", 0.0)) > 0.0 + assert float(meta.get("latent_anchor_weight", -1.0)) >= 0.0 + active_count = int(meta.get("occupancy_active_future_dims", -1)) + constant_count = int(meta.get( + "occupancy_constant_future_dims", -1)) + assert 0 < active_count <= 256 + assert constant_count >= 0 + assert active_count + constant_count == 256 + assert meta.get("constant_future_masking") is ( + constant_count > 0) + assert meta.get("recursive_state_support_projection") is None + assert meta.get("occupancy_target_standardization") == ( + "per_dimension_dataset_mean_std") + + +def _assert_pixel_compact_representation_contract(meta, reader_meta): + """Validate h256 state conditioning with compact z8 goals/futures.""" + assert _is_raw_pixel_compact_one_hop(meta) + assert meta.get("recursion_state") is None + assert meta.get("goal_hidden") is False + assert (meta.get("latent_update") or "frozen") == "frozen" + assert int(meta["state_dim"]) == 256 + assert int(meta["actor_goal_dim"]) == int(reader_meta["zdim"]) + assert int(meta["occupancy_goal_dim"]) == int(reader_meta["zdim"]) + assert int(meta["occupancy_future_dim"]) == int(reader_meta["zdim"]) + assert int(meta.get("reward_reader_dim", -1)) == int( + reader_meta["zdim"]) + assert meta.get("state_feature") == "encoder_hidden" + assert meta.get("occupancy_goal_feature") == ( + "compact_reward_predictive_z") + assert meta.get("future_feature") == "compact_reward_predictive_z" + assert meta.get("reward_goal_feature") == ( + "compact_reward_predictive_z") + assert meta.get("frozen_encoder_fc1_reward_projection") is False + assert int(meta.get("occupancy_active_future_dims", -1)) == int( + reader_meta["zdim"]) + assert int(meta.get("occupancy_constant_future_dims", -1)) == 0 + assert meta.get("constant_future_masking") is False + assert meta.get("recursive_state_support_projection") is None + assert meta.get("occupancy_target_standardization") == ( + "per_dimension_dataset_mean_std") + + +def _assert_pixel_reward_metric_representation_contract(meta, reader_meta): + """Validate h256 conditions and the invertible compact metric target.""" + assert _is_raw_pixel_reward_metric_one_hop(meta) + assert meta.get("recursion_state") is None + assert meta.get("goal_hidden") is True + assert (meta.get("latent_update") or "frozen") == "frozen" + reader_dim = int(reader_meta["zdim"]) + assert int(meta["state_dim"]) == 256 + assert int(meta["actor_goal_dim"]) == 256 + assert int(meta["occupancy_goal_dim"]) == 256 + assert int(meta["occupancy_future_dim"]) == reader_dim == 8 + assert int(meta.get("reward_reader_dim", -1)) == reader_dim + assert meta.get("state_feature") == "encoder_hidden" + assert meta.get("occupancy_goal_feature") == "encoder_hidden" + assert meta.get("future_feature") == ( + "goal_relative_reader_metric_u") + assert meta.get("reward_goal_feature") == ( + "compact_reward_predictive_z") + assert meta.get("occupancy_target_goal_feature") == ( + "compact_reward_predictive_z") + assert meta.get("occupancy_decoded_future_feature") == ( + "compact_reward_predictive_z") + assert meta.get("frozen_encoder_fc1_reward_projection") is False + assert int(meta.get("occupancy_active_future_dims", -1)) == reader_dim + assert int(meta.get("occupancy_constant_future_dims", -1)) == 0 + assert meta.get("constant_future_masking") is False + assert meta.get("recursive_state_support_projection") is None + assert meta.get("occupancy_target_standardization") == ( + "identity_in_frozen_reader_metric_coordinates") + assert meta.get("occupancy_target_formula") == ( + "u_i=sqrt(reader_weight_i)/reader_scale_i*" + "(z_future_i-z_goal_i)") + assert meta.get("occupancy_target_decoder") == ( + "z_future_i=z_goal_i+u_i*reader_scale_i/" + "sqrt(reader_weight_i)") + assert meta.get("occupancy_target_invertible") is True + assert meta.get("occupancy_target_reader_frozen") is True + assert meta.get("occupancy_target_reader_model") == "diag_metric" + assert meta.get("occupancy_target_reader_target") == "index" + assert int(meta.get( + "occupancy_target_reader_index_delta", -1)) == int( + reader_meta["index_delta"]) + assert meta.get("occupancy_target_uses_index_relabeling") is True + for key in ( + "occupancy_target_uses_reward_arrays", + "occupancy_target_uses_coordinates", + "occupancy_target_uses_td_or_bootstrap"): + assert meta.get(key) is False + + scale = np.asarray(reader_meta["metric_scale"], np.float32) + weight = np.asarray(reader_meta["metric_weight"], np.float32) + diagonal = reader_metric_coordinate_diagonal(scale, weight) + inverse = 1.0 / diagonal + np.testing.assert_array_equal( + np.asarray(meta["occupancy_target_metric_scale"], np.float32), + scale) + np.testing.assert_array_equal( + np.asarray(meta["occupancy_target_metric_weight"], np.float32), + weight) + np.testing.assert_array_equal( + np.asarray(meta["occupancy_target_metric_diagonal"], np.float32), + diagonal) + np.testing.assert_array_equal( + np.asarray( + meta["occupancy_target_metric_inverse_diagonal"], np.float32), + inverse) + assert int(meta.get("occ_hidden", -1)) == 256 + assert int(meta.get("occ_layers", -1)) == 4 + assert float(meta.get("occupancy_learning_rate", -1.0)) == 3e-4 + assert int(meta.get("occ_batch", -1)) == 2048 + assert float(meta.get("occ_reader_metric_weight", -1.0)) == 0.0 + assert meta.get("occ_reader_metric_enabled") is False + assert float(meta.get("occ_reader_hit_weight", -1.0)) == 0.0 + assert meta.get("occ_reader_hit_enabled") is False + + +def _assert_checkpoint_contract( + meta, reader_meta, checkpoint_step=None, + active_reference_root=None): + """Fail closed on the scientific and implementation contract.""" + assert isinstance(meta, dict) and meta, "checkpoint lacks run_meta" + assert str(meta.get("env", "")).startswith("visual-") + assert meta.get("drop_proprio") is True, ( + "checkpoint must save drop_proprio=true") + assert meta.get("discount_conditioned") is True + assert meta.get("discount_feature") == "fourier_log_horizon" + gamma_lo = float(meta.get("gamma_spectrum_lo", -1.0)) + gamma = float(meta.get("gamma", -1.0)) + assert 0.0 < gamma_lo < gamma < 1.0 + assert meta.get("occupancy_model") == "flow", ( + "this gate is for conditional-flow occupancies") + recursion = meta.get("recursion") + assert recursion in ("off", "occupancy_latent"), ( + "gate supports compact recursion-off or staged hidden occupancy " + "recursion only") + raw_pixel_actor = meta.get("actor_input") == "pixels" + pixel_hidden_one_hop = _is_raw_pixel_hidden_one_hop(meta) + pixel_compact_one_hop = _is_raw_pixel_compact_one_hop(meta) + pixel_reward_metric_one_hop = ( + _is_raw_pixel_reward_metric_one_hop(meta)) + pixel_actor_reference = None + if raw_pixel_actor: + assert recursion == "off", ( + "raw-pixel actor checkpoints must keep recursive composition off") + assert ( + pixel_hidden_one_hop + or pixel_compact_one_hop + or pixel_reward_metric_one_hop), ( + "raw-pixel gate requires a schema-10+ hidden-h256, compact-z8, " + "or schema-13 goal-relative reader-metric one-hop contract") + pixel_actor_reference = _assert_raw_pixel_actor_contract( + meta, active_reference_root=active_reference_root) + if recursion == "off": + assert meta.get("recursion_state") in (None, "compact"), ( + "recursion-off checkpoint has an unexpected recursion state") + if pixel_reward_metric_one_hop: + checkpoint_mode = "pixel_reward_metric_one_hop" + future_space = ( + "decoded_compact_reward_predictive_z_from_reader_metric_u") + _assert_pixel_reward_metric_representation_contract( + meta, reader_meta) + elif pixel_hidden_one_hop: + checkpoint_mode = "pixel_hidden_one_hop" + future_space = "frozen_encoder_hidden_h256" + _assert_pixel_hidden_representation_contract( + meta, reader_meta) + elif pixel_compact_one_hop: + checkpoint_mode = "pixel_compact_one_hop" + future_space = "compact_reward_predictive_z" + _assert_pixel_compact_representation_contract( + meta, reader_meta) + else: + checkpoint_mode = "compact_recursion_off" + future_space = "compact_z" + assert int(meta["occupancy_future_dim"]) == int( + reader_meta["zdim"]) + composition_has_activated = False + else: + checkpoint_mode = "staged_hidden_precomposition" + future_space = "frozen_encoder_hidden_h256" + assert meta.get("recursion_state") == "hidden" + assert checkpoint_step is not None, ( + "staged hidden checkpoint contract needs checkpoint_step") + checkpoint_step = int(checkpoint_step) + rec_after = int(meta.get("rec_after", -1)) + assert checkpoint_step >= 0 and rec_after >= 0 + assert checkpoint_step <= rec_after, ( + "hidden checkpoint is not safely pre-composition: " + f"checkpoint_step={checkpoint_step} > rec_after={rec_after}") + # rsm.py activates composition only for a training update whose input + # step is strictly greater than rec_after. This conservative staged + # boundary therefore guarantees that no composed target was consumed. + composition_has_activated = False + assert meta.get("goal_hidden") is True + assert (meta.get("latent_update") or "frozen") == "frozen", ( + "hidden checkpoint must use the frozen pixel representation") + assert int(meta["state_dim"]) == 256 + assert int(meta["actor_goal_dim"]) == 256 + assert int(meta["occupancy_goal_dim"]) == 256 + assert int(meta["occupancy_future_dim"]) == 256 + assert int(meta.get("reward_reader_dim", -1)) == int( + reader_meta["zdim"]) + assert meta.get("state_feature") == "encoder_hidden" + assert meta.get("actor_goal_feature") == "encoder_hidden" + assert meta.get("occupancy_goal_feature") == "encoder_hidden" + assert meta.get("future_feature") == ( + "frozen_encoder_hidden_occupancy_state") + assert meta.get("reward_goal_feature") == ( + "compact_reward_predictive_z") + assert meta.get("frozen_encoder_fc1_reward_projection") is True + active_count = int(meta.get( + "occupancy_active_future_dims", -1)) + constant_count = int(meta.get( + "occupancy_constant_future_dims", -1)) + assert 0 < active_count <= 256 + assert constant_count >= 0 + assert active_count + constant_count == 256 + assert meta.get("constant_future_masking") is ( + constant_count > 0) + assert meta.get("recursive_state_support_projection") == ( + "relu_nonnegative_plus_constant_mean") + assert meta.get("occupancy_target_standardization") == ( + "per_dimension_dataset_mean_std") + assert meta.get("uses_td_or_bootstrap") is False + assert meta.get("occupancy_uses_reward_labels") is False + assert meta.get("occupancy_uses_simulator_coordinates") is False + assert meta.get("uses_completion_or_forward_model") is False + schema_version = int(meta.get("schema_version", -1)) + pixel_scorer = meta.get("distill_scorer_input") == "pixels" + reward_metric_target = ( + meta.get("occupancy_target_space") + == "goal_relative_reader_metric") + if schema_version >= 13: + assert ( + raw_pixel_actor + and (pixel_scorer or reward_metric_target) + ), ( + "schema-13 requires a raw-pixel actor plus a raw-pixel scorer " + "or reader-metric target") + else: + assert not pixel_scorer and not reward_metric_target, ( + "raw-pixel scorer and reader-metric targets require " + "schema_version >= 13") + empirical_index_enabled = bool( + meta.get("distill_empirical_index_enabled", False)) + if schema_version >= 12: + assert empirical_index_enabled, ( + "schema-12 checkpoint lacks empirical index-successor anchoring") + if empirical_index_enabled: + assert schema_version >= 12 + empirical_weight = float( + meta.get("distill_empirical_index_weight", -1.0)) + assert 0.0 < empirical_weight <= 1.0 + if pixel_scorer: + assert empirical_weight == 1.0 + assert meta.get( + "distill_empirical_index_behavior_action_only") is True + assert meta.get( + "distill_empirical_index_counterfactual_action_source") == ( + "none_awr_dataset_actions_only" + if meta.get("actor_loss") == "awr_distill" + and pixel_scorer + else "none_behavior_only_scorer_supervision" + if pixel_scorer + and not meta.get("distill_actor_actions") + else "discount_conditioned_ema_occupancy") + assert meta.get("distill_empirical_index_target_source") == ( + "observed_same_trajectory_absorbing_first_passage_geometric_" + "successor_compact_z_through_frozen_index_reader") + assert meta.get("distill_empirical_index_horizon") == ( + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount") + assert int(meta.get("distill_empirical_index_samples", 0)) > 0 + assert meta.get("distill_empirical_index_blend_formula") == ( + "recorded_successor_reader_expectation_only" + if pixel_scorer + else "(1-weight)*ema_occupancy_reader_expectation" + "+weight*recorded_successor_reader_expectation") + for key in ( + "distill_empirical_index_uses_reward_arrays", + "distill_empirical_index_uses_coordinates", + "distill_empirical_index_uses_td_or_bootstrap"): + assert meta.get(key) is False, ( + f"empirical index-successor checkpoint violates {key}=false") + if pixel_scorer: + assert meta.get( + "distill_empirical_index_recorded_action_uses_occupancy" + ) is False + assert meta.get( + "distill_empirical_index_counterfactual_uses_empirical" + ) is ( + False + if ( + meta.get("actor_loss") == "ddpgbc_distill" + and meta.get("distill_actor_actions") + ) + else None) + if raw_pixel_actor and int(meta["schema_version"]) >= 11: + expected_sampler = ( + "reward_metric_endpoints" + if pixel_reward_metric_one_hop else "protected_endpoints") + assert meta.get("gamma_sampler") == expected_sampler, ( + "schema-11+ raw-pixel checkpoints must use their fail-closed " + "gamma/beta endpoint sampler") + if meta.get("gamma_sampler") == "protected_endpoints": + _assert_protected_endpoint_contract(meta) + if pixel_reward_metric_one_hop: + _assert_reward_metric_endpoint_contract(meta) + if pixel_reward_metric_one_hop and pixel_scorer: + assert meta.get("reader_metric_pixel_scorer_combined") is True + assert meta.get( + "reader_metric_pixel_scorer_update_semantics") == ( + "same_fused_step_separate_gradients") + assert meta.get("occupancy_and_actor_jointly_updated") is True, ( + "occupancy and actor were not jointly updated") + assert meta.get("freeze_occupancy") is False + assert str(meta.get("joint_update_semantics", "")).startswith( + "same_fused_step_") + assert meta.get("actor_gradient_updates_occupancy") is False + assert meta.get("occupancy_gradient_updates_actor") is False + assert meta.get("occupancy_supervision") in ( + "monte_carlo_geometric_futures", + "monte_carlo_geometric_futures_plus_detached_actor_query_" + "likelihood_ranking", + ) + assert meta.get("occupancy_training_policy") in ( + "offline_behavior_data", + "offline_behavior_futures_with_detached_live_actor_query_negatives", + ) + assert meta.get("reward_decoder_target") == "index" + assert meta.get("reward_decoder_logit") is False + assert meta.get("reward_decoder_model") == "diag_metric" + assert reader_meta["reader_model"] == "diag_metric" + assert reader_meta["target"] == "index" + assert int(reader_meta["index_delta"]) >= 0 + assert reader_meta.get("pixels_only_latents") is True + assert reader_meta.get("frozen_encoder") is True + assert reader_meta.get("uses_coordinates_for_training") is False + assert reader_meta.get("uses_coordinates_for_diagnostics") is False + assert reader_meta.get("uses_reward_arrays") is False + assert reader_meta.get("uses_td_or_bootstrap") is False + assert reader_meta.get("label_source") == ( + "trajectory_index_positive_and_far_negative_relabeling") + if meta.get("reward_decoder_index_delta") is not None: + assert int(meta["reward_decoder_index_delta"]) == int( + reader_meta["index_delta"]) + if meta.get("latent_index_delta") is not None: + assert int(meta["latent_index_delta"]) == int( + reader_meta["index_delta"]) + assert meta.get("latent_reader_model") == "diag_metric" + assert meta.get("latent_index_negative_contract") == ( + "same_episode_far_only_cross_episode_excluded") + + role_fields = ( + "state_feature", + "actor_goal_feature", + "occupancy_goal_feature", + "future_feature", + "reward_goal_feature", + ) + for field in role_fields: + value = str(meta.get(field, "")) + assert value + assert not any( + forbidden in value.lower() + for forbidden in ("proprio", "coord", "simulator")) + assert meta.get("latent_npz") + assert meta.get("pixel_encoder") + assert meta.get("reward_decoder") + + actor_query_contrast = bool( + float(meta.get("occ_action_contrast_weight", 0.0)) > 0.0 + and meta.get("occ_action_negative") == "actor_local") + if actor_query_contrast: + local_k = int(meta.get("occ_action_negative_local_k", 0)) + assert local_k > 0 + assert int(meta.get( + "occ_action_negative_candidate_count", -1)) == 1 + local_k + expected_actor_query_policy = ( + "stop_gradient_live_preupdate_pixel_actor_mode_plus_" + "local_gaussian" + if raw_pixel_actor + else "stop_gradient_live_preupdate_actor_mode_plus_" + "local_gaussian") + assert meta.get("occ_action_negative_policy") == ( + expected_actor_query_policy) + assert meta.get("occ_action_negative_actor_source") == ( + "live_preupdate_actor") + assert int(meta.get( + "occ_action_negative_support_start_step", -1)) == 0 + assert meta.get( + "occ_action_negative_actions_stop_gradient") is True + assert meta.get( + "occ_action_negative_common_random_numbers") is True + assert meta.get("occ_action_negative_updates_actor") is False + assert meta.get( + "occ_action_negative_counterfactual_target") is False + assert meta.get("occ_action_negative_interpretation") == ( + "anti_exploitation_likelihood_ranking_not_counterfactual_" + "occupancy") + + return { + "pixels_only": True, + "drop_proprio": True, + "conditional_flow": True, + "discount_conditioned": True, + "discount_support": [gamma_lo, gamma], + "checkpoint_mode": checkpoint_mode, + "future_distribution_space": future_space, + "raw_pixel_actor": raw_pixel_actor, + "pixel_actor_reference": pixel_actor_reference, + "hidden_future": bool( + pixel_hidden_one_hop + or checkpoint_mode == "staged_hidden_precomposition"), + "reward_metric_future": bool(pixel_reward_metric_one_hop), + "raw_pixel_scorer": bool(pixel_scorer), + "reader_metric_pixel_scorer_combined": bool( + pixel_reward_metric_one_hop and pixel_scorer), + "reward_reader_space": "cached_compact_z", + "checkpoint_step": ( + int(checkpoint_step) + if checkpoint_step is not None else None), + "rec_after": ( + int(meta["rec_after"]) + if meta.get("rec_after") is not None else None), + "composition_has_activated": composition_has_activated, + "composition_activation_rule": ( + "training_step_strictly_greater_than_rec_after" + if recursion == "occupancy_latent" else "recursion_disabled"), + "generated_hidden_support_projection": ( + "relu_nonnegative_plus_constant_mean" + if future_space == "frozen_encoder_hidden_h256" else None), + "saved_recursive_state_support_projection": meta.get( + "recursive_state_support_projection"), + "uses_td_or_bootstrap": False, + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": False, + "occupancy_and_actor_jointly_updated": True, + "separate_stop_gradient_losses": True, + "canonical_reader_model": "diag_metric", + "reader_index_delta": int(reader_meta["index_delta"]), + "actor_query_contrast_trained": actor_query_contrast, + } + + +def _action_metrics( + reward_samples, actions, dataset_actions, rows, labels, + rng, support_reference_rows): + """Model-internal ranking stability and marginal action support.""" + reward_samples = np.asarray(reward_samples, np.float32) + actions = np.asarray(actions, np.float32) + assert reward_samples.ndim == 3 + batch, candidate_count, sample_count = reward_samples.shape + assert actions.shape[:2] == (batch, candidate_count) + assert sample_count >= 4 + midpoint = sample_count // 2 + first = reward_samples[:, :, :midpoint].mean(axis=2) + second = reward_samples[:, :, midpoint:].mean(axis=2) + value = reward_samples.mean(axis=2) + span = value.max(axis=1) - value.min(axis=1) + # Common random numbers make a candidate gap much less noisy than either + # candidate value alone. Resolve the observed best-vs-worst gap against + # the *paired* gap standard error, preserving that variance cancellation. + row_index = np.arange(batch) + best_index = np.argmax(value, axis=1) + worst_index = np.argmin(value, axis=1) + extreme_gap_samples = ( + reward_samples[row_index, best_index] + - reward_samples[row_index, worst_index]) + extreme_gap_standard_error = ( + extreme_gap_samples.std(axis=1, ddof=1) + / np.sqrt(sample_count)) + resolution = span / np.maximum(extreme_gap_standard_error, 1e-8) + + data_index = labels.index("data") + actor_index = labels.index("actor") + local_indices = [ + index for index, label in enumerate(labels) + if label == "data" or label.startswith("data_local_") + ] + actor_local_indices = [ + index for index, label in enumerate(labels) + if label == "actor" or label.startswith("actor_local_") + ] + data_value = value[:, data_index] + actor_value = value[:, actor_index] + paired_delta_samples = ( + reward_samples[:, actor_index] + - reward_samples[:, data_index]) + paired_delta = paired_delta_samples.mean(axis=1) + paired_delta_se = ( + paired_delta_samples.std(axis=1, ddof=1) + / np.sqrt(sample_count)) + + action_sd = dataset_actions.std(axis=0) + 1e-6 + paired_l2 = np.linalg.norm( + actions[:, actor_index] - dataset_actions[rows], axis=1) + paired_l2_normalized = np.linalg.norm( + (actions[:, actor_index] - dataset_actions[rows]) + / action_sd[None, :], axis=1) + low = np.quantile(dataset_actions, 0.01, axis=0) + high = np.quantile(dataset_actions, 0.99, axis=0) + actor_action = actions[:, actor_index] + outside = (actor_action < low) | (actor_action > high) + + reference_count = min( + int(support_reference_rows), len(dataset_actions)) + reference_indices = rng.choice( + len(dataset_actions), reference_count, replace=False) + reference = ( + dataset_actions[reference_indices] / action_sd[None, :]) + normalized_actor = actor_action / action_sd[None, :] + nearest = np.empty(batch, np.float32) + # Chunk the reference to avoid a batch x million x action tensor. + for index in range(batch): + nearest[index] = np.sqrt(np.min(np.sum(np.square( + reference - normalized_actor[index][None, :]), axis=1))) + + significant_actor_advantage = ( + paired_delta > 2.0 * np.maximum(paired_delta_se, 1e-8)) + actor_row_outside = np.any(outside, axis=1) + return { + "candidate_labels": labels, + "candidate_count": int(candidate_count), + "common_base_noise_across_actions": True, + "counterfactual_ground_truth_available": False, + "interpretation": ( + "model_internal_ranking_and_support_not_counterfactual_value"), + "q_by_candidate": { + label: _summary(value[:, index]) + for index, label in enumerate(labels) + }, + "all_candidate_q_span": _summary(span), + "all_candidate_q_span_over_paired_gap_mc_se": _summary( + resolution), + "split_half_pairwise_rank_agreement": _pairwise_rank_agreement( + first, second), + "split_half_top1_agreement": float(np.mean( + np.argmax(first, axis=1) == np.argmax(second, axis=1))), + "data_local": { + "candidate_count": int(len(local_indices)), + "q_span": _summary( + value[:, local_indices].max(axis=1) + - value[:, local_indices].min(axis=1)), + "data_action_best_rate": float(np.mean( + np.argmax(value[:, local_indices], axis=1) == 0)), + "split_half_pairwise_rank_agreement": + _pairwise_rank_agreement( + first[:, local_indices], second[:, local_indices]), + }, + "actor_local": { + "candidate_count": int(len(actor_local_indices)), + "q_span": _summary( + value[:, actor_local_indices].max(axis=1) + - value[:, actor_local_indices].min(axis=1)), + "actor_mode_best_rate": float(np.mean( + np.argmax(value[:, actor_local_indices], axis=1) == 0)), + "split_half_pairwise_rank_agreement": + _pairwise_rank_agreement( + first[:, actor_local_indices], + second[:, actor_local_indices]), + }, + "data_vs_actor": { + "q_data": _summary(data_value), + "q_actor": _summary(actor_value), + "q_actor_minus_data": _summary(paired_delta), + "model_prefers_actor_rate": float(np.mean( + actor_value > data_value)), + "actor_preference_significant_over_mc_rate": float(np.mean( + significant_actor_advantage)), + "actor_rank_mean": float(np.mean( + 1 + np.sum( + value > actor_value[:, None], axis=1))), + }, + "actor_action_support": { + "paired_behavior_l2": _summary(paired_l2), + "paired_behavior_l2_normalized_by_action_sd": _summary( + paired_l2_normalized), + "nearest_reference_action_l2_normalized_by_action_sd": _summary( + nearest), + "reference_action_count": int(reference_count), + "component_outside_dataset_p01_p99_fraction": float( + outside.mean()), + "row_outside_dataset_p01_p99_rate": float( + actor_row_outside.mean()), + "action_saturation_fraction": float( + np.mean(np.abs(actor_action) > 0.99)), + "high_q_and_outside_support_row_rate": float(np.mean( + significant_actor_advantage & actor_row_outside)), + }, + } + + +def _conditional_loss_metrics(losses, labels): + """Behavior-target fit after data/local/actor action relabeling.""" + losses = np.asarray(losses, np.float32) + assert losses.ndim == 2 and losses.shape[1] == len(labels) + data_index = labels.index("data") + actor_index = labels.index("actor") + local_indices = [ + index for index, label in enumerate(labels) + if label.startswith("data_local_") + ] + actor_local_indices = [ + index for index, label in enumerate(labels) + if label.startswith("actor_local_") + ] + data = losses[:, data_index] + actor = losses[:, actor_index] + return { + "target": "recorded_behavior_geometric_future", + "counterfactual_interpretation": False, + "common_flow_bridge_time_and_noise": True, + "data_action_loss": _summary(data), + "actor_action_loss": _summary(actor), + "actor_minus_data_loss": _summary(actor - data), + "data_fits_behavior_future_better_than_actor_rate": float( + np.mean(data < actor)), + "data_local_minus_data_loss": ( + _summary(losses[:, local_indices] - data[:, None]) + if local_indices else None), + "actor_local_minus_data_loss": ( + _summary(losses[:, actor_local_indices] - data[:, None]) + if actor_local_indices else None), + } + + +def _decision(metrics_by_discount, action_by_discount, + loss_by_discount, required_discounts, actor_support, + thresholds): + """Compute explicit offline gates and retain every failure reason.""" + required = [] + for discount in required_discounts: + key = min( + metrics_by_discount, + key=lambda candidate: abs(float(candidate) - float(discount))) + assert abs(float(key) - float(discount)) < 2e-6 + required.append((key, metrics_by_discount[key])) + + failures = { + "value": [], + "distribution": [], + "ranking": [], + "actor_support": [], + } + for key, row in required: + horizon = 1.0 / (1.0 - float(key)) + reward = row["reward_expectation"] + distribution = row["future_latent_distribution"] + if reward["spearman"] < thresholds["min_reward_spearman"]: + failures["value"].append( + f"horizon={horizon:.4g}: reward Spearman " + f"{reward['spearman']:.4g} < " + f"{thresholds['min_reward_spearman']:.4g}") + if reward["normalized_mae"] > thresholds[ + "max_reward_normalized_mae"]: + failures["value"].append( + f"horizon={horizon:.4g}: reward normalized MAE " + f"{reward['normalized_mae']:.4g} > " + f"{thresholds['max_reward_normalized_mae']:.4g}") + if distribution["mean_rmse_in_dataset_latent_sd"] > thresholds[ + "max_future_mean_rmse"]: + failures["distribution"].append( + f"horizon={horizon:.4g}: latent mean RMSE " + f"{distribution['mean_rmse_in_dataset_latent_sd']:.4g} > " + f"{thresholds['max_future_mean_rmse']:.4g}") + energy_ratio = distribution[ + "mean_energy_distance_over_mean_exact_pairwise_spread"] + if energy_ratio > thresholds["max_energy_distance_ratio"]: + failures["distribution"].append( + f"horizon={horizon:.4g}: energy-distance ratio " + f"{energy_ratio:.4g} > " + f"{thresholds['max_energy_distance_ratio']:.4g}") + variance_ratio = distribution["model_to_exact_variance_ratio"] + if not ( + thresholds["min_variance_ratio"] + <= variance_ratio + <= thresholds["max_variance_ratio"]): + failures["distribution"].append( + f"horizon={horizon:.4g}: variance ratio " + f"{variance_ratio:.4g} outside " + f"[{thresholds['min_variance_ratio']:.4g}, " + f"{thresholds['max_variance_ratio']:.4g}]") + + action = action_by_discount[key] + if action["split_half_pairwise_rank_agreement"] < thresholds[ + "min_rank_split_agreement"]: + failures["ranking"].append( + f"horizon={horizon:.4g}: split rank agreement " + f"{action['split_half_pairwise_rank_agreement']:.4g} < " + f"{thresholds['min_rank_split_agreement']:.4g}") + resolution = action[ + "all_candidate_q_span_over_paired_gap_mc_se"]["median"] + if resolution < thresholds["min_action_resolution"]: + failures["ranking"].append( + f"horizon={horizon:.4g}: median action resolution " + f"{resolution:.4g} < " + f"{thresholds['min_action_resolution']:.4g}") + + if actor_support: + behavior_preferred = loss_by_discount[key][ + "data_fits_behavior_future_better_than_actor_rate"] + if behavior_preferred < thresholds[ + "min_behavior_preferred_to_actor_rate"]: + failures["actor_support"].append( + f"horizon={horizon:.4g}: behavior-target data-action " + f"preference {behavior_preferred:.4g} < " + f"{thresholds['min_behavior_preferred_to_actor_rate']:.4g}") + + task_key = required[0][0] + actor_ood = action_by_discount[task_key][ + "actor_action_support"]["row_outside_dataset_p01_p99_rate"] + if actor_ood > thresholds["max_actor_ood_row_rate"]: + failures["actor_support"].append( + f"task-gamma actor OOD row rate {actor_ood:.4g} > " + f"{thresholds['max_actor_ood_row_rate']:.4g}") + high_q_ood = action_by_discount[task_key][ + "actor_action_support"]["high_q_and_outside_support_row_rate"] + if high_q_ood > thresholds["max_high_q_actor_ood_rate"]: + failures["actor_support"].append( + f"task-gamma high-Q actor OOD rate {high_q_ood:.4g} > " + f"{thresholds['max_high_q_actor_ood_rate']:.4g}") + + one_hop_value_ready = not failures["value"] + recursive_state_ready = ( + one_hop_value_ready and not failures["distribution"]) + ready = ( + recursive_state_ready + and not failures["ranking"] + and not failures["actor_support"]) + return { + "thresholds": thresholds, + "required_discounts": [float(value) for value in required_discounts], + "required_effective_horizons": [ + float(1.0 / (1.0 - value)) + for value in required_discounts + ], + "one_hop_value_ready": one_hop_value_ready, + "recursive_state_ready": recursive_state_ready, + "ready_for_recursion_experiment": ready, + "failure_reasons": failures, + "scope": ( + "offline_screen_only_official_closed_loop_rollout_still_required"), + } + + +def _build_parser(): + parser = argparse.ArgumentParser() + parser.add_argument("--ckpt") + parser.add_argument( + "--expected_checkpoint_sha256", + help="optional immutable lowercase SHA-256 for --ckpt") + parser.add_argument( + "--latents", + help="must resolve to checkpoint run_meta.latent_npz") + parser.add_argument( + "--reward_decoder", + help="must resolve to checkpoint run_meta.reward_decoder") + parser.add_argument("--out") + parser.add_argument("--rows", type=int, default=96) + parser.add_argument("--samples", type=int, default=16) + parser.add_argument("--loss_draws", type=int, default=4) + parser.add_argument("--episodes", type=int, default=100) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--actor", choices=("ema", "live"), default="ema") + parser.add_argument("--local_k", type=int, default=4) + parser.add_argument("--local_sigma", type=float, default=0.3) + parser.add_argument("--actor_local_k", type=int, default=2) + parser.add_argument("--actor_local_sigma", type=float, default=0.3) + parser.add_argument( + "--scorer_crop_trials", type=int, default=2, + help="schema-13 scorer only: exact shared state/goal edge-crop " + "stress trials (default: 2)") + parser.add_argument("--support_reference_rows", type=int, default=20000) + parser.add_argument( + "--sample_steps", type=int, default=0, + help="0 uses checkpoint flow_steps") + parser.add_argument( + "--horizons", default="", + help="optional comma-separated effective horizons; default audits " + "saved training bins plus candidate beta and task gamma") + parser.add_argument( + "--rec_beta", type=float, default=0.0, + help="candidate recursion discount; 0 uses checkpoint run_meta.rec_beta") + parser.add_argument("--min_reward_spearman", type=float, default=0.70) + parser.add_argument( + "--max_reward_normalized_mae", type=float, default=0.35) + parser.add_argument("--max_future_mean_rmse", type=float, default=0.50) + parser.add_argument( + "--max_energy_distance_ratio", type=float, default=1.0) + parser.add_argument("--min_variance_ratio", type=float, default=0.50) + parser.add_argument("--max_variance_ratio", type=float, default=2.0) + parser.add_argument( + "--min_rank_split_agreement", type=float, default=0.65) + parser.add_argument("--min_action_resolution", type=float, default=1.0) + parser.add_argument( + "--min_behavior_preferred_to_actor_rate", + type=float, default=0.55) + parser.add_argument( + "--max_actor_ood_row_rate", type=float, default=0.25) + parser.add_argument( + "--max_high_q_actor_ood_rate", type=float, default=0.05) + parser.add_argument( + "--fail_on_gate", action="store_true", + help="exit nonzero unless ready_for_recursion_experiment is true") + parser.add_argument("--self_test", action="store_true") + return parser + + +def run_gate(args): + """Run the read-only checkpoint gate and return its JSON-ready metrics.""" + import jax + import jax.numpy as jnp + + assert args.ckpt and args.out, "--ckpt and --out are required" + assert args.rows > 1 and args.samples >= 4 + assert args.loss_draws > 0 and args.episodes > 0 + assert args.local_k > 0 and args.actor_local_k >= 0 + assert args.local_sigma > 0.0 and args.actor_local_sigma > 0.0 + require_pixel_scorer = bool( + getattr(args, "require_pixel_scorer", False)) + strict_pixel_data_diet = bool( + getattr(args, "strict_pixel_scorer_data_diet", False)) + scorer_crop_trials = int( + getattr(args, "scorer_crop_trials", 2)) + assert scorer_crop_trials >= 0 + if require_pixel_scorer: + assert strict_pixel_data_diet, ( + "required pixel-scorer diagnostics must use the strict RGB plus " + "z/state_h data diet") + assert args.actor_local_k > 0, ( + "pixel-scorer diagnostics require actor-local candidates") + assert scorer_crop_trials > 0, ( + "pixel-scorer diagnostics require a shared-crop stress probe") + checkpoint_path = os.path.abspath(args.ckpt) + checkpoint_sha256 = _sha256_file(checkpoint_path) + expected_checkpoint_sha256 = getattr( + args, "expected_checkpoint_sha256", None) + if expected_checkpoint_sha256 is not None: + assert ( + isinstance(expected_checkpoint_sha256, str) + and len(expected_checkpoint_sha256) == 64 + and all( + piece in "0123456789abcdef" + for piece in expected_checkpoint_sha256) + ), "--expected_checkpoint_sha256 must be lowercase SHA-256" + assert checkpoint_sha256 == expected_checkpoint_sha256, ( + "checkpoint SHA-256 mismatch: " + f"expected={expected_checkpoint_sha256} " + f"actual={checkpoint_sha256}") + with open(checkpoint_path, "rb") as file: + checkpoint = pickle.load(file) + assert "carry" in checkpoint + meta = dict(checkpoint.get("run_meta") or {}) + carry = checkpoint["carry"] + assert len(carry) >= 10 + checkpoint_step = int(np.asarray(carry[9]).item()) + latent_path = _resolve_exact_artifact( + args.latents, meta.get("latent_npz"), "latent") + encoder_path = _resolve_exact_artifact( + None, meta.get("pixel_encoder"), "pixel encoder") + reader_path = _resolve_exact_artifact( + args.reward_decoder, meta.get("reward_decoder"), "reward reader") + reader_probability, reader_meta = load_numpy_reward_reader( + reader_path, probability=True) + active_reference_root = os.path.realpath(os.path.abspath( + os.path.expanduser( + os.environ.get("OGBENCH_IMPLS", OGBENCH_IMPLS)))) + fairness = _assert_checkpoint_contract( + meta, reader_meta, checkpoint_step=checkpoint_step, + active_reference_root=active_reference_root) + hidden_future = bool(fairness["hidden_future"]) + reward_metric_future = bool(fairness["reward_metric_future"]) + raw_pixel_actor = bool(fairness["raw_pixel_actor"]) + if reward_metric_future: + reward_metric_diagonal = reader_metric_coordinate_diagonal( + reader_meta["metric_scale"], reader_meta["metric_weight"]) + reward_metric_inverse = 1.0 / reward_metric_diagonal + else: + reward_metric_diagonal = None + reward_metric_inverse = None + pixel_scorer = bool( + int(meta.get("schema_version", -1)) == 13 + and meta.get("distill_scorer_input") == "pixels") + if require_pixel_scorer: + assert pixel_scorer and raw_pixel_actor, ( + "strict diagnostic requires a schema-13 raw-RGB scorer and actor") + + # The strict schema-13 path opens only z/state_h from the latent cache. + # RGB, actions, and trajectory endpoints come from the pinned rendered + # source. The general occupancy gate retains its legacy duplicate-array + # alignment check. Neither path opens proprioception, simulator + # coordinates, or reward arrays. + latent_source = _load_pinned_latent_occupancy_source( + latent_path, strict_pixel_data_diet) + z_base = latent_source["z"] + state_h = latent_source["state_h"] + dataset_actions = latent_source["actions"] + terminals = latent_source["terminals"] + available_arrays = latent_source["arrays_available"] + latent_encoder_recorded = latent_source["encoder_npz"] + pixel_observations = None + pixel_valid_indices = None + pixel_dataset_audit = None + pixel_artifact_provenance_verified = False + if raw_pixel_actor: + if strict_pixel_data_diet: + ( + pixel_observations, + dataset_actions, + terminals, + pixel_valid_indices, + pixel_dataset_audit, + ) = _load_pinned_pixel_source(meta) + else: + ( + pixel_observations, + pixel_valid_indices, + pixel_dataset_audit, + ) = _load_pinned_pixel_actor_dataset( + meta, dataset_actions, terminals) + provenance = meta["pixel_artifact_provenance"] + assert _sha256_file(latent_path) == provenance[ + "latent_npz"]["sha256"], ( + "latent artifact SHA-256 does not match pixel-checkpoint " + "provenance") + assert _sha256_file(encoder_path) == provenance[ + "pixel_encoder"]["sha256"], ( + "encoder artifact SHA-256 does not match pixel-checkpoint " + "provenance") + pixel_artifact_provenance_verified = True + assert dataset_actions is not None and terminals is not None + assert len(z_base) == len(state_h) == len(dataset_actions) == len( + terminals) + assert z_base.shape[1] == int(reader_meta["zdim"]) + if latent_encoder_recorded is not None: + assert os.path.realpath(os.path.abspath( + os.path.expanduser(latent_encoder_recorded))) == os.path.realpath( + encoder_path), ( + "latent artifact and checkpoint name different pixel encoders") + elif ( + (hidden_future or reward_metric_future) + and not strict_pixel_data_diet): + raise AssertionError( + "h256-conditioned gate requires latent encoder_npz provenance") + + if strict_pixel_data_diet: + output_path = os.path.realpath(os.path.abspath(args.out)) + immutable_inputs = { + os.path.realpath(checkpoint_path), + os.path.realpath(latent_path), + os.path.realpath(encoder_path), + os.path.realpath(reader_path), + os.path.realpath(pixel_dataset_audit["path"]), + } + assert output_path not in immutable_inputs, ( + "diagnostic output must not overwrite an immutable input") + + encoder_arrays_read = [] + with np.load(encoder_path, allow_pickle=False) as encoder: + encoder_arrays_available = sorted(encoder.files) + + def encoder_scalar(name, default=None): + if name not in encoder.files: + return default + encoder_arrays_read.append(name) + value = np.asarray(encoder[name]) + assert value.ndim == 0, ( + f"pixel encoder metadata {name} must be scalar") + return value.item() + + encoder_hidden_dim = encoder_scalar("hidden") + encoder_z_dim = encoder_scalar("z_dim") + encoder_variant = encoder_scalar("variant") + encoder_coordinate_training = encoder_scalar( + "cube_coordinate_training") + if encoder_coordinate_training is not None: + assert bool(encoder_coordinate_training) is False, ( + "pixel encoder records cube-coordinate training") + fc1_weight = fc1_bias = None + if hidden_future: + required_encoder = { + "hidden", "z_dim", "cube_coordinate_training", + "fc_1.weight", "fc_1.bias", + } + missing = sorted(required_encoder.difference(encoder.files)) + assert not missing, f"pixel encoder lacks {missing}" + assert encoder_coordinate_training is not None + fc1_weight = np.asarray( + encoder["fc_1.weight"], np.float32).T + fc1_bias = np.asarray(encoder["fc_1.bias"], np.float32) + encoder_arrays_read.extend(["fc_1.weight", "fc_1.bias"]) + + if encoder_hidden_dim is not None: + assert int(encoder_hidden_dim) == state_h.shape[1] + if encoder_z_dim is not None: + assert int(encoder_z_dim) == z_base.shape[1] + encoder_provenance = { + "path": encoder_path, + "sha256": _sha256_file(encoder_path), + "checkpoint_recorded_path": os.path.abspath( + os.path.expanduser(str(meta["pixel_encoder"]))), + "latent_artifact_recorded_path": latent_encoder_recorded, + "latent_artifact_binding_verified": bool( + latent_encoder_recorded is not None), + "checkpoint_pixel_artifact_provenance_verified": + pixel_artifact_provenance_verified, + "artifact_binding_source": ( + "checkpoint_pixel_artifact_provenance_exact_sha256" + if pixel_artifact_provenance_verified + else "latent_encoder_npz_scalar" + if latent_encoder_recorded is not None + else None), + "variant": ( + str(encoder_variant) + if encoder_variant is not None else None), + "hidden_dim": ( + int(encoder_hidden_dim) + if encoder_hidden_dim is not None else None), + "compact_z_dim": ( + int(encoder_z_dim) + if encoder_z_dim is not None else None), + "cube_coordinate_training": ( + bool(encoder_coordinate_training) + if encoder_coordinate_training is not None else None), + "arrays_available": encoder_arrays_available, + "arrays_read": sorted(set(encoder_arrays_read)), + } + + ends = build_ends(terminals) + episode_ends = np.flatnonzero(terminals) + 1 + if not len(episode_ends) or episode_ends[-1] != len(terminals): + episode_ends = np.r_[episode_ends, len(terminals)] + episode_starts = np.r_[0, episode_ends[:-1]] + valid_episodes = np.flatnonzero( + episode_ends - episode_starts >= 2) + trailing = valid_episodes[-args.episodes:] + assert len(trailing) + candidate_rows = np.concatenate([ + np.arange(episode_starts[index], episode_ends[index] - 1) + for index in trailing + ]) + assert len(candidate_rows) >= args.rows + if raw_pixel_actor: + assert np.all(np.isin(candidate_rows, pixel_valid_indices)), ( + "gate actor-query rows are not valid pixel transitions") + + state_dim = int(meta["state_dim"]) + if state_dim == state_h.shape[1]: + state_base = state_h + elif state_dim == z_base.shape[1]: + state_base = z_base + else: + raise AssertionError( + f"state_dim={state_dim} matches neither state_h nor z") + goal_hidden = bool(meta.get("goal_hidden")) + occupancy_goal_base = state_h if goal_hidden else z_base + assert occupancy_goal_base.shape[1] == int(meta["occupancy_goal_dim"]) + + occupancy_ema = jax.device_put(carry[2]) + agent = carry[6] + pixel_scorer = meta.get("distill_scorer_input") == "pixels" + if pixel_scorer: + assert isinstance(agent, (tuple, list)) and len(agent) == 7 + for label, params in ( + ("expectile value", agent[2]), + ("twin scorer", agent[4])): + assert isinstance(params, Mapping) + assert set(params) == {"gc_encoder", "value_net"}, ( + f"raw-pixel {label} lacks exact IMPALA-small GCValue " + f"parameter groups: {sorted(params)}") + actor_params = carry[7] if args.actor == "ema" else agent[0] + latent_update = str(meta.get("latent_update") or "frozen") + assert latent_update in ("frozen", "adapter", "rich_adapter") + adapter_params = None + if latent_update != "frozen": + assert len(carry) >= 13 + adapter_params = jax.device_put(carry[12]) + + def transform(features): + if adapter_params is None: + return np.asarray(features, np.float32) + return np.asarray(_apply_adapter( + adapter_params, jnp.asarray(features, jnp.float32))) + + if hidden_future: + future_latents = state_h + exact_reward_latents = z_base + future_active_mask = None + hidden_support = None + elif latent_update == "adapter": + future_latents = transform(z_base) + exact_reward_latents = future_latents + future_active_mask = np.ones( + future_latents.shape[1], dtype=bool) + hidden_support = None + else: + future_latents = z_base + exact_reward_latents = z_base + future_active_mask = np.ones( + future_latents.shape[1], dtype=bool) + hidden_support = None + future_dim = int(future_latents.shape[1]) + assert future_dim == int(meta["occupancy_future_dim"]) + + ( + condition_mean, + condition_std, + target_mean, + target_std, + normalization_contract, + ) = _load_occupancy_normalization( + checkpoint, + state_base, + dataset_actions, + occupancy_goal_base, + ends, + future_latents, + meta, + ) + assert normalization_contract["exact_checkpoint_statistics"] is True, ( + "production gate requires serialized checkpoint normalization") + if reward_metric_future: + np.testing.assert_array_equal( + target_mean, np.zeros_like(target_mean)) + np.testing.assert_array_equal( + target_std, np.ones_like(target_std)) + distribution_target_std = ( + future_latents.std(axis=0) + 1e-6).astype(np.float32) + else: + distribution_target_std = target_std + if hidden_future: + future_active_mask, hidden_support = ( + _hidden_future_support_contract( + future_latents, meta, target_mean, target_std)) + + assert fc1_weight is not None and fc1_bias is not None + assert fc1_weight.shape == (future_dim, z_base.shape[1]), ( + "pixel encoder fc_1 must map generated h256 to compact reader z") + assert fc1_bias.shape == (z_base.shape[1],) + fc1_probe_count = min(4096, len(state_h)) + fc1_probe = ( + state_h[:fc1_probe_count] @ fc1_weight + fc1_bias) + fc1_difference = np.abs( + z_base[:fc1_probe_count] - fc1_probe) + fc1_cached_z_audit = { + "probe_rows": int(fc1_probe_count), + "max_abs": float(fc1_difference.max()), + "mean_abs": float(fc1_difference.mean()), + "required_max_abs_below": 2e-4, + "passed": bool(fc1_difference.max() < 2e-4), + "checkpoint_recorded_max_abs": ( + float(meta["fc1_cached_z_max_abs"]) + if meta.get("fc1_cached_z_max_abs") is not None else None), + "checkpoint_recorded_mean_abs": ( + float(meta["fc1_cached_z_mean_abs"]) + if meta.get("fc1_cached_z_mean_abs") is not None else None), + "cached_target": "latent_artifact_z", + "projection": "frozen_pixel_encoder_fc_1_affine_only", + } + assert fc1_cached_z_audit["passed"], ( + "frozen fc_1 does not reproduce cached compact z: " + f"max_abs={fc1_cached_z_audit['max_abs']:.6g}") + if meta.get("fc1_cached_z_max_abs") is not None: + assert float(meta["fc1_cached_z_max_abs"]) < 2e-4 + encoder_provenance.update({ + "generated_hidden_to_reader_projection": + "fc_1_affine_only_no_encoder_reexecution", + "fc1_weight_shape": list(fc1_weight.shape), + "fc1_bias_shape": list(fc1_bias.shape), + "fc1_cached_z_error": fc1_cached_z_audit, + }) + else: + fc1_cached_z_audit = None + encoder_provenance[ + "generated_hidden_to_reader_projection"] = None + + rng = np.random.default_rng(args.seed + 918) + rows = rng.choice(candidate_rows, args.rows, replace=False) + span = np.maximum(ends[rows] - rows - 1, 1) + goal_indices = rows + 1 + ( + rng.random(args.rows) * span).astype(np.int64) + goal_indices = np.minimum(goal_indices, ends[rows] - 1) + + if latent_update == "rich_adapter": + states = transform(state_h[rows]) + occupancy_goals = transform(state_h[goal_indices]) + reward_goals = z_base[goal_indices] + elif latent_update == "adapter": + states = transform(z_base[rows]) + occupancy_goals = transform(z_base[goal_indices]) + reward_goals = occupancy_goals + else: + states = state_base[rows] + occupancy_goals = occupancy_goal_base[goal_indices] + reward_goals = z_base[goal_indices] + + if raw_pixel_actor: + actor_states = pixel_observations[rows] + actor_goals = pixel_observations[goal_indices] + + def apply_pixel_actor(params, observations, goals): + return _pixel_actor_mode( + params, observations, goals, + dataset_actions.shape[1], + reference_root=active_reference_root) + + actor_action = np.asarray(jax.jit(apply_pixel_actor)( + jax.device_put(actor_params), + jnp.asarray(actor_states), + jnp.asarray(actor_goals), + ), np.float32) + else: + actor_goals = occupancy_goals + actor_action = np.asarray(jax.jit(_actor_mode)( + jax.device_put(actor_params), + jnp.asarray(states), + jnp.asarray(actor_goals), + ), np.float32) + actor_action = np.clip(actor_action, -1.0, 1.0) + action_dim = dataset_actions.shape[1] + data_local = np.clip( + dataset_actions[rows, None, :] + + args.local_sigma * rng.standard_normal( + (args.rows, args.local_k, action_dim)), + -1.0, 1.0).astype(np.float32) + actor_local = np.clip( + actor_action[:, None, :] + + args.actor_local_sigma * rng.standard_normal( + (args.rows, args.actor_local_k, action_dim)), + -1.0, 1.0).astype(np.float32) + evaluation_actions = np.concatenate([ + dataset_actions[rows, None, :], + data_local, + actor_action[:, None, :], + actor_local, + ], axis=1) + labels = ( + ["data"] + + [f"data_local_{index}" for index in range(args.local_k)] + + ["actor"] + + [f"actor_local_{index}" for index in range( + args.actor_local_k)] + ) + action_count = evaluation_actions.shape[1] + + scorer_heads_live = None + scorer_heads_ema = None + crop_scorer_heads_live = None + crop_scorer_heads_ema = None + if pixel_scorer: + scorer_def = _pixel_scorer_definition( + reference_root=active_reference_root) + + @jax.jit + def apply_pixel_scorer( + params, observations, goals, actions): + return scorer_def.apply( + {"params": params}, observations, goals, actions) + + def query_pixel_scorer(params, observations, goals): + ( + flat_observations, + flat_goals, + flat_actions, + ) = _repeat_pixel_pairs_for_actions( + observations, goals, evaluation_actions) + heads = np.asarray(apply_pixel_scorer( + jax.device_put(params), + jnp.asarray(flat_observations), + jnp.asarray(flat_goals), + jnp.asarray(flat_actions), + ), np.float32) + assert heads.shape == (2, args.rows * action_count), ( + "raw-pixel scorer did not return two scalar heads") + assert np.all(np.isfinite(heads)) + return heads.reshape(2, args.rows, action_count) + + scorer_heads_live = query_pixel_scorer( + agent[4], actor_states, actor_goals) + scorer_heads_ema = query_pixel_scorer( + agent[6], actor_states, actor_goals) + + if scorer_crop_trials: + from ogbench_genq.rsm import ( + visual_actor_shared_random_crop, + ) + + scorer_crop_seed = int(args.seed + 7919) + scorer_crop_rng = np.random.default_rng(scorer_crop_seed) + crop_live_trials = [] + crop_ema_trials = [] + for _ in range(scorer_crop_trials): + # Match the visual GCIQL augmentation exactly: edge pad by + # three pixels and apply one shared offset to the state and + # goal in each row. The resulting pair is then reused for + # every candidate action so crops cannot confound ranking. + crop_xy = scorer_crop_rng.integers( + 0, 7, size=(args.rows, 2), dtype=np.int32) + cropped_states, cropped_goals = ( + visual_actor_shared_random_crop( + jnp.asarray(actor_states), + jnp.asarray(actor_goals), + jnp.asarray(crop_xy), + True, + )) + cropped_states = np.asarray(cropped_states) + cropped_goals = np.asarray(cropped_goals) + crop_live_trials.append(query_pixel_scorer( + agent[4], cropped_states, cropped_goals)) + crop_ema_trials.append(query_pixel_scorer( + agent[6], cropped_states, cropped_goals)) + crop_scorer_heads_live = np.stack( + crop_live_trials, axis=0) + crop_scorer_heads_ema = np.stack( + crop_ema_trials, axis=0) + + gamma = float(meta["gamma"]) + gamma_lo = float(meta["gamma_spectrum_lo"]) + recursion_beta = ( + float(args.rec_beta) if args.rec_beta > 0.0 + else float(meta.get("rec_beta", 0.98))) + assert gamma_lo <= recursion_beta < gamma + discounts = _discount_grid(meta, args.horizons, recursion_beta) + sample_steps = ( + int(args.sample_steps) if args.sample_steps > 0 + else int(meta["flow_steps"])) + assert sample_steps > 0 + condition_dim = ( + states.shape[1] + action_dim + occupancy_goals.shape[1] + + 2 * FOURIER_K) + occupancy_def = make_model( + condition_dim, future_dim, + int(meta["occ_hidden"]), int(meta["occ_layers"]), 64) + reader_logit, loaded_reader_meta = load_jax_reward_reader(reader_path) + assert loaded_reader_meta["reader_model"] == "diag_metric" + condition_mean_j = jnp.asarray(condition_mean) + condition_std_j = jnp.asarray(condition_std) + target_mean_j = jnp.asarray(target_mean) + target_std_j = jnp.asarray(target_std) + reward_metric_diagonal_j = ( + jnp.asarray(reward_metric_diagonal) + if reward_metric_future else None) + reward_metric_inverse_j = ( + jnp.asarray(reward_metric_inverse) + if reward_metric_future else None) + future_active_j = jnp.asarray( + future_active_mask.astype(np.float32)) + future_active_bool_j = jnp.asarray(future_active_mask) + future_active_den_j = jnp.asarray( + float(future_active_mask.sum()), jnp.float32) + fc1_weight_j = ( + jnp.asarray(fc1_weight) if hidden_future else None) + fc1_bias_j = jnp.asarray(fc1_bias) if hidden_future else None + + def discount_features_jax(discount): + frequencies = jnp.asarray( + np.pi * (2.0 ** np.arange(FOURIER_K)), jnp.float32) + lo_h = np.log(1.0 / (1.0 - gamma_lo)) + hi_h = np.log(1.0 / (1.0 - gamma)) + unit = ( + jnp.log(1.0 / (1.0 - discount)) - lo_h + ) / max(hi_h - lo_h, 1e-8) + angle = unit[:, None] * frequencies[None, :] + return jnp.concatenate( + [jnp.sin(angle), jnp.cos(angle)], axis=-1) + + def sample_flow( + state, action, goal, reward_goal, noise, discount): + batch, samples, latent_dim = noise.shape + condition = jnp.concatenate([ + state, + action, + goal, + discount_features_jax(discount), + ], axis=-1) + condition = (condition - condition_mean_j) / condition_std_j + repeated_condition = jnp.repeat( + condition, samples, axis=0) + latent = noise.reshape(batch * samples, latent_dim) + if hidden_future: + # Match rsm.py exactly: inactive standardized coordinates receive + # neither base noise nor flow updates. + latent = latent * future_active_j[None, :] + dt = 1.0 / sample_steps + + def step(current, index): + time = jnp.full( + (batch * samples,), + index.astype(jnp.float32) * dt) + velocity = occupancy_def.apply( + occupancy_ema, current, time, repeated_condition) + following = current + dt * velocity + if hidden_future: + following = following * future_active_j[None, :] + return following, None + + latent, _ = jax.lax.scan( + step, latent, jnp.arange(sample_steps)) + future = ( + latent.reshape(batch, samples, latent_dim) + * target_std_j + target_mean_j) + if reward_metric_future: + future = decode_reader_metric_future( + future, + reward_goal[:, None, :], + reward_metric_inverse_j, + array_module=jnp, + ) + if hidden_future: + # state_h is fc_0's ReLU feature; constant units are pinned to + # their exact cached mean before the known nonnegative projection. + future = _project_hidden_support( + future, target_mean_j, future_active_bool_j, + array_module=jnp) + return future + + def reward_samples_from_flow( + state, action, occupancy_goal, reward_goal, noise, discount): + future = sample_flow( + state, action, occupancy_goal, reward_goal, noise, discount) + batch, samples, _ = future.shape + reward_future = ( + future @ fc1_weight_j + fc1_bias_j + if hidden_future else future) + reward_dim = reward_future.shape[-1] + repeated_goal = jnp.repeat(reward_goal, samples, axis=0) + logits = reader_logit( + reward_future.reshape(batch * samples, reward_dim), + repeated_goal, + ).reshape(batch, samples) + return future, jax.nn.sigmoid(logits) + + sample_reward_jit = jax.jit(reward_samples_from_flow) + + # Flow-matching loss under action relabeling. The exact behavior future, + # bridge time, and base noise are common across all action candidates. + def action_conditional_loss( + state, action, occupancy_goal, reward_goal, exact_future, + bridge_noise, bridge_time, discount): + batch, candidates, _ = action.shape + draws = exact_future.shape[1] + state_flat = jnp.repeat( + state[:, None, None, :], candidates, axis=1) + state_flat = jnp.repeat(state_flat, draws, axis=2).reshape( + batch * candidates * draws, state.shape[1]) + action_flat = jnp.repeat( + action[:, :, None, :], draws, axis=2).reshape( + batch * candidates * draws, action.shape[2]) + goal_flat = jnp.repeat( + occupancy_goal[:, None, None, :], candidates, axis=1) + goal_flat = jnp.repeat(goal_flat, draws, axis=2).reshape( + batch * candidates * draws, occupancy_goal.shape[1]) + discount_flat = jnp.repeat( + discount[:, None, None], candidates, axis=1) + discount_flat = jnp.repeat( + discount_flat, draws, axis=2).reshape(-1) + condition = jnp.concatenate([ + state_flat, + action_flat, + goal_flat, + discount_features_jax(discount_flat), + ], axis=-1) + condition = (condition - condition_mean_j) / condition_std_j + + target_future = ( + encode_reader_metric_future( + exact_future, + reward_goal[:, None, :], + reward_metric_diagonal_j, + array_module=jnp, + ) + if reward_metric_future else exact_future) + clean = ( + (target_future - target_mean_j[None, None, :]) + / target_std_j[None, None, :]) + clean = jnp.repeat( + clean[:, None, :, :], candidates, axis=1).reshape( + batch * candidates * draws, clean.shape[2]) + noise = jnp.repeat( + bridge_noise[:, None, :, :], candidates, axis=1).reshape( + batch * candidates * draws, clean.shape[1]) + if hidden_future: + noise = noise * future_active_j[None, :] + time = jnp.repeat( + bridge_time[:, None, :], candidates, axis=1).reshape(-1) + noised = ( + (1.0 - time[:, None]) * noise + + time[:, None] * clean) + target_velocity = clean - noise + prediction = occupancy_def.apply( + occupancy_ema, noised, time, condition) + squared_error = jnp.square(prediction - target_velocity) + loss = ( + (squared_error * future_active_j[None, :]).sum(axis=-1) + / future_active_den_j + if hidden_future else jnp.mean(squared_error, axis=-1)) + return loss.reshape(batch, candidates, draws).mean(axis=2) + + action_loss_jit = jax.jit(action_conditional_loss) + metrics_by_discount = {} + action_by_discount = {} + loss_by_discount = {} + task_action_reward_samples = None + task_action_discount_key = None + base_noise = rng.standard_normal( + (args.rows, args.samples, future_dim)).astype(np.float32) + + required_discounts = np.asarray([gamma, recursion_beta], np.float64) + for discount in discounts: + discount_rows = np.full(args.rows, discount, np.float32) + exact = _exact_absorbing_occupancy( + future_latents, + rows, + goal_indices, + ends, + float(discount), + args.samples, + reader_probability, + reward_latents=exact_reward_latents, + ) + model_future, model_reward = sample_reward_jit( + jnp.asarray(states), + jnp.asarray(dataset_actions[rows]), + jnp.asarray(occupancy_goals), + jnp.asarray(reward_goals), + jnp.asarray(base_noise), + jnp.asarray(discount_rows), + ) + model_future = np.asarray(model_future) + model_reward = np.asarray(model_reward) + row_metrics = _distribution_metrics( + model_future, model_reward, exact, distribution_target_std, + active_mask=future_active_mask) + row_metrics.update({ + "gamma": float(discount), + "effective_horizon": float(1.0 / (1.0 - discount)), + "future_distribution_space": + fairness["future_distribution_space"], + "reward_label_space": "cached_compact_z", + "is_task_gamma": bool(np.isclose( + discount, gamma, atol=2e-7)), + "is_candidate_recursion_beta": bool(np.isclose( + discount, recursion_beta, atol=2e-7)), + }) + key = float(discount) + metrics_by_discount[key] = row_metrics + + if np.any(np.isclose( + discount, required_discounts, atol=2e-7)): + states_flat = np.repeat( + states[:, None, :], action_count, axis=1).reshape( + args.rows * action_count, states.shape[1]) + actions_flat = evaluation_actions.reshape( + args.rows * action_count, action_dim) + occupancy_goals_flat = np.repeat( + occupancy_goals[:, None, :], action_count, axis=1).reshape( + args.rows * action_count, occupancy_goals.shape[1]) + reward_goals_flat = np.repeat( + reward_goals[:, None, :], action_count, axis=1).reshape( + args.rows * action_count, reward_goals.shape[1]) + noise_flat = np.repeat( + base_noise[:, None, :, :], action_count, axis=1).reshape( + args.rows * action_count, + args.samples, + future_dim) + discount_flat = np.full( + args.rows * action_count, discount, np.float32) + _, action_reward = sample_reward_jit( + jnp.asarray(states_flat), + jnp.asarray(actions_flat), + jnp.asarray(occupancy_goals_flat), + jnp.asarray(reward_goals_flat), + jnp.asarray(noise_flat), + jnp.asarray(discount_flat), + ) + action_reward_samples = np.asarray( + action_reward, np.float32).reshape( + args.rows, action_count, args.samples) + action_by_discount[key] = _action_metrics( + action_reward_samples, + evaluation_actions, + dataset_actions, + rows, + labels, + rng, + args.support_reference_rows, + ) + if np.isclose(discount, gamma, atol=2e-7): + task_action_reward_samples = action_reward_samples + task_action_discount_key = key + + loss_indices = np.linspace( + 0, args.samples - 1, args.loss_draws + ).round().astype(np.int64) + bridge_noise = rng.standard_normal( + (args.rows, args.loss_draws, future_dim) + ).astype(np.float32) + bridge_time = rng.random( + (args.rows, args.loss_draws)).astype(np.float32) + losses = action_loss_jit( + jnp.asarray(states), + jnp.asarray(evaluation_actions), + jnp.asarray(occupancy_goals), + jnp.asarray(reward_goals), + jnp.asarray(exact["samples"][:, loss_indices]), + jnp.asarray(bridge_noise), + jnp.asarray(bridge_time), + jnp.asarray(discount_rows), + ) + loss_by_discount[key] = _conditional_loss_metrics( + np.asarray(losses), labels) + + raw_pixel_scorer_diagnostic = None + if pixel_scorer: + assert ( + task_action_reward_samples is not None + and task_action_discount_key is not None + and scorer_heads_live is not None + and scorer_heads_ema is not None + ), "schema-13 diagnostic lacks task-gamma scorer or occupancy reads" + raw_pixel_scorer_diagnostic = _raw_pixel_scorer_metrics( + task_action_reward_samples, + scorer_heads_live, + scorer_heads_ema, + labels, + evaluation_actions, + dataset_actions, + rows, + action_by_discount[task_action_discount_key][ + "actor_action_support"], + crop_live_heads=crop_scorer_heads_live, + crop_ema_heads=crop_scorer_heads_ema, + ) + raw_pixel_scorer_diagnostic["shared_crop_stress"].update({ + "seed": int(args.seed + 7919), + "independent_from_occupancy_and_action_candidate_rng": True, + }) + if require_pixel_scorer: + assert raw_pixel_scorer_diagnostic is not None + + thresholds = { + "min_reward_spearman": float(args.min_reward_spearman), + "max_reward_normalized_mae": float( + args.max_reward_normalized_mae), + "max_future_mean_rmse": float(args.max_future_mean_rmse), + "max_energy_distance_ratio": float( + args.max_energy_distance_ratio), + "min_variance_ratio": float(args.min_variance_ratio), + "max_variance_ratio": float(args.max_variance_ratio), + "min_rank_split_agreement": float( + args.min_rank_split_agreement), + "min_action_resolution": float(args.min_action_resolution), + "min_behavior_preferred_to_actor_rate": float( + args.min_behavior_preferred_to_actor_rate), + "max_actor_ood_row_rate": float(args.max_actor_ood_row_rate), + "max_high_q_actor_ood_rate": float( + args.max_high_q_actor_ood_rate), + } + # Put task gamma first so task-key support checks are unambiguous. + required_ordered = [gamma] + if not np.isclose(recursion_beta, gamma, atol=2e-7): + required_ordered.append(recursion_beta) + decision = _decision( + metrics_by_discount, + action_by_discount, + loss_by_discount, + required_ordered, + fairness["actor_query_contrast_trained"], + thresholds, + ) + + per_horizon = [ + { + **metrics_by_discount[key], + "action_ranking": action_by_discount.get(key), + "behavior_future_action_relabeling": + loss_by_discount.get(key), + } + for key in sorted( + metrics_by_discount, + key=lambda value: metrics_by_discount[value][ + "effective_horizon"]) + ] + ready = decision["ready_for_recursion_experiment"] + assert type(ready) is bool + metrics = { + "schema_version": 2, + "audit": "fair_visual_rsm_one_hop_occupancy_checkpoint_gate", + # The continuation launcher requires this strict top-level boolean + # and revalidates the checkpoint/representation/reader provenance + # below. The nested decision retains the full audit rationale. + "pass": ready, + "checkpoint": checkpoint_path, + "checkpoint_sha256": checkpoint_sha256, + "checkpoint_step": checkpoint_step, + "checkpoint_run_contract": { + "env": meta["env"], + "seed": int(meta["seed"]), + "recursion": meta["recursion"], + "recursion_state": meta.get("recursion_state"), + }, + "audit_split": ( + "deterministic_trailing_episode_slice_offline_target_" + "distribution"), + "rows": int(args.rows), + "samples_per_condition": int(args.samples), + "loss_draws_per_condition": int(args.loss_draws), + "seed": int(args.seed), + "actor_source": args.actor, + "fairness_and_training_contract": fairness, + "artifact_contract": { + "latent": latent_path, + "pixel_encoder": encoder_provenance, + "reward_reader_path": reader_path, + "reward_reader_sha256": _sha256_file(reader_path), + "latent_arrays_available": available_arrays, + "latent_arrays_read": latent_source["arrays_read"], + "latent_data_arrays_read": latent_source["arrays_read"], + "latent_metadata_arrays_read": + latent_source["metadata_arrays_read"], + "strict_pixel_scorer_data_diet": + strict_pixel_data_diet, + "checkpoint_pixel_artifact_provenance_verified": + pixel_artifact_provenance_verified, + "forbidden_arrays_read": + latent_source["forbidden_arrays_read"], + "proprioception_arrays_read": [], + "simulator_coordinate_arrays_read": [], + "reward_arrays_read": [], + "reward_reader": reader_meta, + "occupancy_normalization": normalization_contract, + "pixel_actor_dataset": pixel_dataset_audit, + "pixel_actor_physical_arrays_read": ( + pixel_dataset_audit["physical_arrays_read"] + if pixel_dataset_audit is not None else []), + "pixel_actor_processed_arrays_reconstructed": ( + ["terminals", "valids"] + if pixel_dataset_audit is not None else []), + }, + "representation": { + "latent_update": latent_update, + "actor_input": meta.get("actor_input", "latent"), + "state_feature": meta["state_feature"], + "actor_goal_feature": meta["actor_goal_feature"], + "occupancy_goal_feature": meta["occupancy_goal_feature"], + "future_feature": meta["future_feature"], + "reward_goal_feature": meta["reward_goal_feature"], + "state_dim": int(states.shape[1]), + "occupancy_goal_dim": int(occupancy_goals.shape[1]), + "future_distribution_space": + fairness["future_distribution_space"], + "future_dim": future_dim, + "reward_reader_space": "cached_compact_z", + "reward_reader_dim": int(z_base.shape[1]), + "hidden_future_support": hidden_support, + "generated_future_reward_projection": ( + "frozen_pixel_encoder_fc_1_affine_only" + if hidden_future + else "invertible_reader_metric_u_to_compact_z" + if reward_metric_future + else "identity_compact_z"), + "occupancy_flow_target_space": ( + "goal_relative_reader_metric_u" + if reward_metric_future else meta["future_feature"]), + "decoded_gate_distribution_space": ( + "compact_reward_predictive_z" + if reward_metric_future + else fairness["future_distribution_space"]), + "fc1_cached_z_error": fc1_cached_z_audit, + }, + "occupancy": { + "model": "conditional_flow", + "hidden": int(meta["occ_hidden"]), + "layers": int(meta["occ_layers"]), + "flow_steps": int(sample_steps), + "gamma_sampler": meta.get("gamma_sampler"), + "gamma_task_fraction": meta.get("gamma_task_fraction"), + "gamma_horizons": meta.get("gamma_horizons"), + "gamma_aux_discounts": meta.get("gamma_aux_discounts"), + "task_gamma": gamma, + "candidate_recursion_beta": recursion_beta, + "candidate_recursion_depth": int(meta.get( + "rec_max_depth", 0)), + "candidate_recursion_beta_mass": float(meta.get( + "rec_beta_sample_prob", 0.0)), + "active_future_dimensions": int( + future_active_mask.sum()), + "constant_future_dimensions": int( + future_dim - future_active_mask.sum()), + "active_dimension_mask_applied_to_noise_flow_and_loss": + bool(hidden_future), + "raw_future_support_projection": ( + "relu_nonnegative_plus_constant_mean" + if hidden_future else None), + "reward_metric_aux_allocation": meta.get( + "reward_metric_endpoint_aux_allocation"), + "behavior_future_loss_space": ( + "goal_relative_reader_metric_u" + if reward_metric_future else meta["future_feature"]), + }, + "per_horizon": per_horizon, + "raw_pixel_scorer_diagnostic": raw_pixel_scorer_diagnostic, + "decision": decision, + "interpretation": { + "recorded_action_distribution_metrics": ( + "exact_against_finite_offline_absorbing_geometric_target"), + "exact_reward_labels": ( + "canonical_diagonal_reader_on_cached_compact_z_not_" + "reconstructed_from_h"), + "generated_hidden_reward_labels": ( + "canonical_diagonal_reader_after_frozen_encoder_fc_1_only" + if hidden_future else "canonical_diagonal_reader_on_compact_z"), + "actor_queries": ( + "exact_checkpoint_pinned_raw_rgb_impala_small_actor" + if raw_pixel_actor else "checkpoint_latent_mlp_actor"), + "local_and_actor_action_metrics": ( + "model_internal_only_no_counterfactual_labels"), + "raw_pixel_scorer_comparison": ( + "live_and_ema_twin_minima_against_direct_task_gamma_" + "discount_conditioned_occupancy_reader_expectation" + if raw_pixel_scorer_diagnostic is not None else None), + "why_value_is_not_enough": ( + "recursion_feeds_generated_latents_back_as_conditions_so_" + "mean_reward_can_pass_while_state_distribution_is_off_support"), + "why_action_stability_is_required": ( + "policy_extraction_needs_resolved_rankings_not_monte_carlo_" + "noise_or_actor_ood_extrapolation"), + "official_rollout_required": True, + }, + } + assert metrics["pass"] is metrics["decision"][ + "ready_for_recursion_experiment"] + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as file: + json.dump(metrics, file, indent=2) + print(json.dumps(metrics, indent=2), flush=True) + if args.fail_on_gate and not decision[ + "ready_for_recursion_experiment"]: + raise SystemExit(2) + return metrics + + +def _self_test(): + """Tiny CPU end-to-end flow checkpoint smoke using only allowed arrays.""" + import jax + import jax.numpy as jnp + + rng = np.random.default_rng(7) + count, zdim, hidden_dim, action_dim = 24, 3, 5, 2 + z = rng.normal(size=(count, zdim)).astype(np.float32) + state_h = rng.normal(size=(count, hidden_dim)).astype(np.float32) + actions = np.clip( + rng.normal(size=(count, action_dim)), -1.0, 1.0).astype(np.float32) + terminals = np.zeros(count, bool) + terminals[[11, 23]] = True + gamma, gamma_lo, beta = 0.99, 0.5, 0.75 + condition_dim = hidden_dim + action_dim + hidden_dim + 2 * FOURIER_K + occupancy_def = make_model(condition_dim, zdim, 16, 2, 64) + occupancy_params = occupancy_def.init( + jax.random.PRNGKey(1), + jnp.zeros((1, zdim)), + jnp.zeros((1,)), + jnp.zeros((1, condition_dim)), + ) + actor_params = { + "actor_net": { + "Dense_0": { + "kernel": jnp.zeros((2 * hidden_dim, 4)), + "bias": jnp.zeros((4,)), + }, + }, + "mean_net": { + "kernel": jnp.zeros((4, action_dim)), + "bias": jnp.zeros((action_dim,)), + }, + } + + with tempfile.TemporaryDirectory( + prefix="visual_occ_gate_", dir="/tmp") as directory: + latent_path = os.path.join(directory, "latents.npz") + encoder_path = os.path.join(directory, "encoder.npz") + reader_path = os.path.join(directory, "reader.npz") + checkpoint_path = os.path.join(directory, "checkpoint.pkl") + output_path = os.path.join(directory, "gate.json") + np.savez( + encoder_path, + hidden=np.asarray(hidden_dim), + z_dim=np.asarray(zdim), + variant=np.asarray("self_test_compact"), + cube_coordinate_training=np.asarray(False), + ) + np.savez( + latent_path, + z=z, + state_h=state_h, + actions=actions, + terminals=terminals, + encoder_npz=np.asarray(os.path.abspath(encoder_path)), + proprio=np.full((count, 19), np.nan, np.float32), + rewards=np.full(count, np.nan, np.float32), + ) + np.savez( + reader_path, + reader_model=np.asarray("diag_metric"), + target=np.asarray("index"), + index_delta=np.asarray(2), + neg_gap=np.asarray(4), + zdim=np.asarray(zdim), + features=np.asarray("concat"), + activation=np.asarray("tanh"), + metric_scale=np.ones(zdim, np.float32), + metric_weight=np.ones(zdim, np.float32), + metric_bias=np.asarray(2.0, np.float32), + pixels_only_latents=np.asarray(True), + frozen_encoder=np.asarray(True), + uses_coordinates_for_training=np.asarray(False), + uses_coordinates_for_diagnostics=np.asarray(False), + uses_reward_arrays=np.asarray(False), + uses_td_or_bootstrap=np.asarray(False), + label_source=np.asarray( + "trajectory_index_positive_and_far_negative_relabeling"), + ) + meta = { + "schema_version": 9, + "env": "visual-cube-single-play-v0", + "seed": 0, + "state_dim": hidden_dim, + "goal_dim": hidden_dim, + "actor_goal_dim": hidden_dim, + "occupancy_goal_dim": hidden_dim, + "reward_goal_dim": zdim, + "occupancy_future_dim": zdim, + "reward_reader_dim": zdim, + "drop_proprio": True, + "goal_hidden": True, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "actor_loss": "ddpgbc_distill", + "uses_td_or_bootstrap": False, + "occupancy_supervision": "monte_carlo_geometric_futures", + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": False, + "occupancy_and_actor_jointly_updated": True, + "joint_update_semantics": + "same_fused_step_separate_supervised_losses", + "occupancy_training_policy": "offline_behavior_data", + "actor_gradient_updates_occupancy": False, + "occupancy_gradient_updates_actor": False, + "freeze_occupancy": False, + "gamma": gamma, + "gamma_spectrum_lo": gamma_lo, + "discount_conditioned": True, + "discount_feature": "fourier_log_horizon", + "gamma_sampler": "stratified_bins", + "gamma_task_fraction": 0.5, + "gamma_horizons": [2.0, 4.0], + "gamma_aux_discounts": [0.5, 0.75], + "occupancy_model": "flow", + "occ_hidden": 16, + "occ_layers": 2, + "flow_steps": 2, + "recursion": "off", + "rec_beta": beta, + "reward_decoder_target": "index", + "reward_decoder_model": "diag_metric", + "reward_decoder_index_delta": 2, + "reward_decoder_logit": False, + "latent_npz": os.path.abspath(latent_path), + "pixel_encoder": os.path.abspath(encoder_path), + "reward_decoder": os.path.abspath(reader_path), + } + carry = ( + occupancy_params, None, occupancy_params, + None, None, None, (actor_params,), actor_params, + jax.random.PRNGKey(2), jnp.asarray(20), + ) + normalization = { + "cond_mean": np.zeros(condition_dim, np.float32), + "cond_std": np.ones(condition_dim, np.float32), + "target_mean": z.mean(axis=0).astype(np.float32), + "target_std": (z.std(axis=0) + 1e-6).astype(np.float32), + } + with open(checkpoint_path, "wb") as file: + pickle.dump({ + "carry": jax.device_get(carry), + "run_meta": meta, + "occupancy_normalization": normalization, + }, file) + args = SimpleNamespace( + ckpt=checkpoint_path, + latents=latent_path, + reward_decoder=reader_path, + out=output_path, + rows=4, + samples=4, + loss_draws=2, + episodes=1, + seed=3, + actor="ema", + local_k=2, + local_sigma=0.3, + actor_local_k=1, + actor_local_sigma=0.3, + support_reference_rows=12, + sample_steps=2, + horizons="2,4,100", + rec_beta=beta, + min_reward_spearman=0.7, + max_reward_normalized_mae=0.35, + max_future_mean_rmse=0.5, + max_energy_distance_ratio=1.0, + min_variance_ratio=0.5, + max_variance_ratio=2.0, + min_rank_split_agreement=0.65, + min_action_resolution=1.0, + min_behavior_preferred_to_actor_rate=0.55, + max_actor_ood_row_rate=0.25, + max_high_q_actor_ood_rate=0.05, + fail_on_gate=False, + ) + metrics = run_gate(args) + assert isinstance(metrics["pass"], bool) + assert metrics["pass"] is metrics["decision"][ + "ready_for_recursion_experiment"] + assert metrics["fairness_and_training_contract"]["pixels_only"] + assert metrics["fairness_and_training_contract"][ + "occupancy_and_actor_jointly_updated"] + assert metrics["artifact_contract"]["forbidden_arrays_read"] == [] + assert metrics["checkpoint_sha256"] == _sha256_file( + checkpoint_path) + assert metrics["artifact_contract"]["pixel_encoder"][ + "latent_artifact_binding_verified"] + assert metrics["artifact_contract"]["reward_arrays_read"] == [] + assert metrics["artifact_contract"]["reward_reader_path"] == ( + os.path.abspath(reader_path)) + assert metrics["artifact_contract"]["reward_reader_sha256"] == ( + _sha256_file(reader_path)) + assert metrics["artifact_contract"]["reward_reader"][ + "reader_model"] == "diag_metric" + assert len(metrics["per_horizon"]) == 3 + required = [ + row for row in metrics["per_horizon"] + if row["is_task_gamma"] + or row["is_candidate_recursion_beta"] + ] + assert len(required) == 2 + assert all(row["action_ranking"] is not None for row in required) + assert os.path.exists(output_path) + + # Exercise the staged hidden-future path end to end. The compact + # reward labels are cached independently from h so this smoke catches + # accidental reader calls on h256. + rich_dim = 256 + rich_h = np.maximum( + rng.normal(size=(count, rich_dim)), 0.0).astype(np.float32) + rich_h[:, -16:] = 0.0 + fc1_weight = rng.normal( + scale=0.05, size=(rich_dim, zdim)).astype(np.float32) + fc1_bias = rng.normal(scale=0.01, size=(zdim,)).astype(np.float32) + rich_z = rich_h @ fc1_weight + fc1_bias + rich_active = rich_h.std(axis=0) > 0.0 + rich_encoder_path = os.path.join(directory, "hidden_encoder.npz") + rich_latent_path = os.path.join(directory, "hidden_latents.npz") + rich_checkpoint_path = os.path.join( + directory, "hidden_checkpoint.pkl") + rich_output_path = os.path.join(directory, "hidden_gate.json") + np.savez( + rich_encoder_path, + hidden=np.asarray(rich_dim), + z_dim=np.asarray(zdim), + variant=np.asarray("self_test_hidden"), + cube_coordinate_training=np.asarray(False), + **{ + "fc_1.weight": fc1_weight.T, + "fc_1.bias": fc1_bias, + }, + ) + np.savez( + rich_latent_path, + z=rich_z, + state_h=rich_h, + actions=actions, + terminals=terminals, + encoder_npz=np.asarray(os.path.abspath(rich_encoder_path)), + proprio=np.full((count, 19), np.nan, np.float32), + coordinates=np.full((count, 3), np.nan, np.float32), + rewards=np.full(count, np.nan, np.float32), + ) + rich_condition_dim = ( + rich_dim + action_dim + rich_dim + 2 * FOURIER_K) + rich_occupancy_def = make_model( + rich_condition_dim, rich_dim, 16, 2, 64) + rich_occupancy_params = rich_occupancy_def.init( + jax.random.PRNGKey(11), + jnp.zeros((1, rich_dim)), + jnp.zeros((1,)), + jnp.zeros((1, rich_condition_dim)), + ) + rich_actor_params = { + "actor_net": { + "Dense_0": { + "kernel": jnp.zeros((2 * rich_dim, 4)), + "bias": jnp.zeros((4,)), + }, + }, + "mean_net": { + "kernel": jnp.zeros((4, action_dim)), + "bias": jnp.zeros((action_dim,)), + }, + } + rich_meta = dict(meta) + rich_meta.update({ + "schema_version": 9, + "state_dim": rich_dim, + "goal_dim": rich_dim, + "actor_goal_dim": rich_dim, + "occupancy_goal_dim": rich_dim, + "reward_goal_dim": zdim, + "occupancy_future_dim": rich_dim, + "reward_reader_dim": zdim, + "goal_hidden": True, + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "frozen_encoder_hidden_occupancy_state", + "reward_goal_feature": "compact_reward_predictive_z", + "recursion": "occupancy_latent", + "recursion_state": "hidden", + "rec_after": 20, + "frozen_encoder_fc1_reward_projection": True, + "occupancy_active_future_dims": int(rich_active.sum()), + "occupancy_constant_future_dims": int( + rich_dim - rich_active.sum()), + "constant_future_masking": bool( + rich_dim - rich_active.sum()), + "recursive_state_support_projection": + "relu_nonnegative_plus_constant_mean", + "occupancy_target_standardization": + "per_dimension_dataset_mean_std", + "fc1_cached_z_max_abs": 0.0, + "fc1_cached_z_mean_abs": 0.0, + "latent_npz": os.path.abspath(rich_latent_path), + "pixel_encoder": os.path.abspath(rich_encoder_path), + }) + rich_carry = ( + rich_occupancy_params, None, rich_occupancy_params, + None, None, None, (rich_actor_params,), rich_actor_params, + jax.random.PRNGKey(12), jnp.asarray(20), + ) + rich_normalization = { + "cond_mean": np.zeros(rich_condition_dim, np.float32), + "cond_std": np.ones(rich_condition_dim, np.float32), + "target_mean": rich_h.mean(axis=0).astype(np.float32), + "target_std": ( + rich_h.std(axis=0) + 1e-6).astype(np.float32), + } + with open(rich_checkpoint_path, "wb") as file: + pickle.dump({ + "carry": jax.device_get(rich_carry), + "run_meta": rich_meta, + "occupancy_normalization": rich_normalization, + }, file) + rich_args = SimpleNamespace(**vars(args)) + rich_args.ckpt = rich_checkpoint_path + rich_args.latents = rich_latent_path + rich_args.out = rich_output_path + rich_metrics = run_gate(rich_args) + assert rich_metrics["pass"] is rich_metrics["decision"][ + "ready_for_recursion_experiment"] + assert rich_metrics["fairness_and_training_contract"][ + "checkpoint_mode"] == "staged_hidden_precomposition" + assert not rich_metrics["fairness_and_training_contract"][ + "composition_has_activated"] + assert rich_metrics["representation"]["future_dim"] == rich_dim + assert rich_metrics["representation"]["reward_reader_dim"] == zdim + assert rich_metrics["representation"]["fc1_cached_z_error"]["passed"] + assert rich_metrics["occupancy"][ + "active_dimension_mask_applied_to_noise_flow_and_loss"] + assert rich_metrics["artifact_contract"]["proprioception_arrays_read"] == [] + assert rich_metrics["artifact_contract"][ + "simulator_coordinate_arrays_read"] == [] + assert rich_metrics["artifact_contract"]["reward_arrays_read"] == [] + + # Exercise the schema-10 raw-pixel actor path end to end while keeping + # occupancy futures in frozen h256 and reward read-out in compact z. + pixel_shape = (16, 16, 3) + pixel_observations = rng.integers( + 0, 256, size=(count, *pixel_shape), dtype=np.uint8) + pixel_dataset_path = os.path.join( + directory, "pixel_actor_dataset.npz") + np.savez_compressed( + pixel_dataset_path, + observations=pixel_observations, + actions=actions, + terminals=terminals, + qpos=np.zeros((count, 9), np.float32), + qvel=np.zeros((count, 9), np.float32), + ) + pixel_actor_def = _pixel_actor_definition(action_dim) + pixel_actor_params = pixel_actor_def.init( + jax.random.PRNGKey(21), + jnp.asarray(pixel_observations[:2]), + jnp.asarray(pixel_observations[2:4]), + )["params"] + pixel_checkpoint_path = os.path.join( + directory, "pixel_checkpoint.pkl") + pixel_output_path = os.path.join( + directory, "pixel_gate.json") + pixel_dataset_sha256 = _sha256_file(pixel_dataset_path) + pixel_meta = dict(rich_meta) + pixel_meta.update({ + "schema_version": 10, + "actor_input": "pixels", + "actor_state_feature": "raw_rgb_pixels", + "actor_goal_feature": "raw_rgb_pixels", + "final_actor_consumes_pixels": True, + "policy_observation": "rendered_pixels_only", + "actor_architecture": + "GCActor_IMPALA_small_early_fusion_MLP_512x3", + "actor_encoder": "impala_small", + "actor_encoder_trainable": True, + "actor_encoder_initialization": "fresh_jointly_trainable", + "actor_pixel_augmentation_probability": 0.5, + "actor_training_augmentation": + "batch_probability_shared_per_row_edge_padded_random_crop", + "actor_goal_relabeling": "uniform_future_same_trajectory", + "actor_pixel_state_shape": list(pixel_shape), + "actor_pixel_goal_shape": list(pixel_shape), + "actor_goal_dim_semantics": + "latent_supervised_scorer_goal_width", + "actor_transition_sampling": + "uniform_over_dataset_valid_indices", + "pixel_dataset_device_transport": + "dynamic_jit_dispatch_argument_not_xla_constant", + "occupancy_consumes_raw_pixels": False, + "raw_pixels_update_actor_only": True, + "occupancy_state_for_pixel_actor": "encoder_hidden", + "occupancy_goal_for_pixel_actor": "encoder_hidden", + "supervised_scalar_scorer_state_for_pixel_actor": + "encoder_hidden", + "pixel_actor_occupancy_discount_required": True, + "pixel_actor_recursion_supported": False, + "pixel_actor_generated_midpoint_policy": None, + "pixel_actor_uses_image_or_world_model_reconstruction": False, + "completion_or_world_model_carrier_instantiated": False, + "pixel_actor_and_occupancy_same_fused_step": True, + "pixel_actor_dataset": { + "path": os.path.abspath(pixel_dataset_path), + "sha256": pixel_dataset_sha256, + "dataset_keys": sorted(PIXEL_ACTOR_DATASET_KEYS), + "excluded_keys": sorted(PIXEL_ACTOR_FORBIDDEN_KEYS), + "observation_shape": list(pixel_shape), + "observation_dtype": "uint8", + "action_shape": [action_dim], + "row_count": count, + "valid_transition_count": int((~terminals).sum()), + "actions_match_latent_cache": True, + "source_terminals_match_latent_cache": True, + "compact_terminals_match_reconstructed": True, + "terminal_alignment_contract": + "latent_source_endpoints_equal_pixel_valids_zero_and_" + "compact_terminals_equal_source_plus_shifted_source", + }, + "pixel_artifact_provenance": { + "latent_npz": { + "path": os.path.abspath(rich_latent_path), + "sha256": _sha256_file(rich_latent_path), + }, + "pixel_encoder": { + "path": os.path.abspath(rich_encoder_path), + "sha256": _sha256_file(rich_encoder_path), + }, + "pixel_dataset": { + "path": os.path.abspath(pixel_dataset_path), + "sha256": pixel_dataset_sha256, + }, + }, + "recursion": "off", + "recursion_state": None, + "recursive_state_support_projection": None, + }) + pixel_carry = ( + rich_occupancy_params, None, rich_occupancy_params, + None, None, None, (pixel_actor_params,), pixel_actor_params, + jax.random.PRNGKey(22), jnp.asarray(20), + ) + with open(pixel_checkpoint_path, "wb") as file: + pickle.dump({ + "carry": jax.device_get(pixel_carry), + "run_meta": pixel_meta, + "occupancy_normalization": rich_normalization, + }, file) + pixel_args = SimpleNamespace(**vars(args)) + pixel_args.ckpt = pixel_checkpoint_path + pixel_args.latents = rich_latent_path + pixel_args.out = pixel_output_path + pixel_metrics = run_gate(pixel_args) + assert pixel_metrics["fairness_and_training_contract"][ + "checkpoint_mode"] == "pixel_hidden_one_hop" + assert pixel_metrics["fairness_and_training_contract"][ + "raw_pixel_actor"] + assert pixel_metrics["representation"]["actor_input"] == "pixels" + assert pixel_metrics["artifact_contract"][ + "pixel_actor_physical_arrays_read"] == [ + "actions", "observations", "terminals"] + assert pixel_metrics["artifact_contract"][ + "pixel_actor_processed_arrays_reconstructed"] == [ + "terminals", "valids"] + assert pixel_metrics["artifact_contract"][ + "pixel_actor_dataset"]["forbidden_arrays_available"] == [ + "qpos", "qvel"] + assert pixel_metrics["artifact_contract"][ + "pixel_actor_dataset"]["forbidden_arrays_read"] == [] + assert pixel_metrics["interpretation"]["actor_queries"] == ( + "exact_checkpoint_pinned_raw_rgb_impala_small_actor") + + # Pure exact-target and energy checks have transparent analytic answers. + line = np.arange(3, dtype=np.float32)[:, None] + exact = _exact_absorbing_occupancy( + line, + np.asarray([0]), + np.asarray([1]), + np.asarray([3, 3, 3]), + 0.5, + 4, + lambda future, goal: np.ones(len(future), np.float32), + ) + np.testing.assert_allclose(exact["mean"], [[3.0 / 7.0]], atol=1e-7) + distance, ratio, _ = _energy_distance( + exact["samples"], exact["samples"], np.ones(1)) + np.testing.assert_allclose(distance, 0.0, atol=1e-12) + np.testing.assert_allclose(ratio, 0.0, atol=1e-12) + print("visual occupancy checkpoint gate self-test: PASS", flush=True) + + +def main(): + parser = _build_parser() + args = parser.parse_args() + if args.self_test: + _self_test() + return + run_gate(args) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/learn_metric_coordfree.py b/gen_q_rsm/ogbench_genq/genq/learn_metric_coordfree.py new file mode 100644 index 0000000000000000000000000000000000000000..8967db477043a0efaa08886363f042e65a6d33dc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/learn_metric_coordfree.py @@ -0,0 +1,97 @@ +"""Coordinate-free METRIC surgery on a frozen recon latent (fair, dynamics-free). + +The recon latent HAS the cube (linear xy_R2=0.70) but its raw euclidean metric is +arm-dominated (spearman 0.47, needs ~0.56). None of these fixes use the cube +coordinate in TRAINING (qpos is loaded ONLY to score the diagnostic spearman) and +none use forward dynamics: + raw : identity metric (control, ~0.47) + standardize: per-dim z-score (equalize marginal variance) + whiten : PCA whitening (decorrelate + equalize) -- coordinate-free + learnedW : linear W trained by SHORT-horizon InfoNCE (a state's t+delta is its + nearest neighbour; arm moves, cube ~constant) -- coordinate-free + +Prints spearman(metric-dist, cube-dist) for each. If one clears ~0.55 we bake it +into the latents (z' = f(z)) and run standard RSM -- still the standard euclidean +read-out, so unambiguously RSM. +""" +import os, sys, numpy as np +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from train_pixel_encoder_jax import reward_target_fn # cube coords: DIAGNOSTIC ONLY + +ENV = "visual-cube-single-play-v0" +LAT = sys.argv[1] if len(sys.argv) > 1 else ( + "/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/" + "rsm-visual-recursion/ckpt/visual_cube_single_recononly_latents.npz") +DATA = os.path.expanduser(f"~/.ogbench/data/{ENV}.npz") +N = 60000 # subsample for speed +rng = np.random.default_rng(0) + +d = np.load(LAT); Z = np.asarray(d["z"][:N], np.float64); term = np.asarray(d["terminals"][:N]) +qpos = np.asarray(np.load(DATA)["qpos"][:N]) +tgt_fn, _ = reward_target_fn(ENV); CUBE = np.asarray(tgt_fn(qpos), np.float64) # (N, k) cube coords +ends = np.where(term > 0)[0]; end_of = np.searchsorted(ends, np.arange(N)); +end_bound = np.where(end_of < len(ends), ends[np.minimum(end_of, len(ends)-1)], N-1) + +from scipy.stats import spearmanr +a = rng.integers(0, N, 8000); b = rng.integers(0, N, 8000) +dc = np.linalg.norm(CUBE[a] - CUBE[b], axis=1) +def spear(Zt): return float(spearmanr(np.linalg.norm(Zt[a]-Zt[b],axis=1), dc).statistic) + +print(f"[metric] N={N} z_dim={Z.shape[1]} cube_dim={CUBE.shape[1]}", flush=True) +print(f" raw spearman={spear(Z):.4f}") +mu, sd = Z.mean(0), Z.std(0) + 1e-8 +print(f" standardize spearman={spear((Z-mu)/sd):.4f}") +# PCA whiten +Zc = Z - mu; C = np.cov(Zc.T); ev, evec = np.linalg.eigh(C) +Wpca = evec @ np.diag(1.0/np.sqrt(np.maximum(ev,1e-8))) @ evec.T +print(f" whiten spearman={spear(Zc @ Wpca):.4f}") + +# learned linear W via SHORT-horizon InfoNCE (coordinate-free) +import jax, jax.numpy as jnp, optax +Zj = jnp.asarray((Z - mu) / sd) # standardize first +def short_future(t): + return np.minimum(t + rng.integers(3, 13, len(t)), end_bound[t]) +W = jnp.eye(Z.shape[1]); opt = optax.adam(3e-3); st = opt.init(W) +def loss_fn(W, za, zp): + wa, wp = za @ W.T, zp @ W.T + d2 = jnp.sum((wa[:,None,:]-wp[None,:,:])**2, -1) + lab = jnp.arange(za.shape[0]) + return (optax.softmax_cross_entropy_with_integer_labels(-d2, lab).mean() + + optax.softmax_cross_entropy_with_integer_labels(-d2.T, lab).mean()) +@jax.jit +def step(W, st, za, zp): + l, g = jax.value_and_grad(loss_fn)(W, za, zp); u, st = opt.update(g, st, W) + return optax.apply_updates(W, u), st, l +tr = np.where(term[:N] == 0)[0]; tr = tr[tr < N-13] +for it in range(4000): + t = rng.choice(tr, 256); tp = short_future(t) + W, st, l = step(W, st, Zj[t], Zj[tp]) + if it % 1000 == 0: print(f" learnedW it={it} infonce={float(l):.3f}", flush=True) +Wn = np.asarray(W) +print(f" learnedW spearman={spear(((Z-mu)/sd) @ Wn.T):.4f} (bar: 0.55; combined 0.560)") + +# nonlinear MLP metric phi(z); metric = ||phi(z)-phi(z_g)|| ; same short-horizon InfoNCE +import flax.linen as nn +class Phi(nn.Module): + @nn.compact + def __call__(self, x): + for w in (64, 64): + x = nn.gelu(nn.Dense(w)(x)) + return nn.Dense(Z.shape[1])(x) +phi = Phi(); pk = jax.random.PRNGKey(0) +pp = phi.init(pk, jnp.zeros((1, Z.shape[1]))); optm = optax.adam(1e-3); sm = optm.init(pp) +def mloss(pp, za, zp): + wa, wp = phi.apply(pp, za), phi.apply(pp, zp) + d2 = jnp.sum((wa[:,None,:]-wp[None,:,:])**2, -1); lab = jnp.arange(za.shape[0]) + return (optax.softmax_cross_entropy_with_integer_labels(-d2, lab).mean() + + optax.softmax_cross_entropy_with_integer_labels(-d2.T, lab).mean()) +@jax.jit +def mstep(pp, sm, za, zp): + l, g = jax.value_and_grad(mloss)(pp, za, zp); u, sm = optm.update(g, sm, pp) + return optax.apply_updates(pp, u), sm, l +for it in range(6000): + t = rng.choice(tr, 256); tp = short_future(t) + pp, sm, l = mstep(pp, sm, Zj[t], Zj[tp]) + if it % 2000 == 0: print(f" MLP it={it} infonce={float(l):.3f}", flush=True) +PHI = np.asarray(phi.apply(pp, Zj)) +print(f" learned MLP spearman={spear(PHI):.4f} (bar: 0.55; combined 0.560)") diff --git a/gen_q_rsm/ogbench_genq/genq/precompute_pixel_latents.py b/gen_q_rsm/ogbench_genq/genq/precompute_pixel_latents.py new file mode 100644 index 0000000000000000000000000000000000000000..66e99dcf5eed5b827a024c15df33f2a6b7a7e804 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/precompute_pixel_latents.py @@ -0,0 +1,177 @@ +"""Precompute frozen-encoder latents for the RSM pixel path (issue #65 Track C, stage 1). + +Loads the frozen reward-predictive pixel encoder (train_pixel_encoder_jax.py), encodes +EVERY frame of visual-cube-single-play-v0, and writes one npz that stage 2 (RSM on +pixels) consumes without ever touching pixels again: + + z (N, z_dim) float32 frozen-encoder latent of each frame + proprio19 (N, 19) float32 OGBench arm proprio (see below) + actions (N, 5) float32 passed through from the released npz + terminals (N,) bool passed through from the released npz + z_dim, sigma_z, encoder_npz provenance meta + +How stage 2 uses this (the RSM wiring contract): + state-for-RSM = concat(proprio19, z) -- (19 + z_dim)-dim conditioning state + target-for-RSM = z -- the occupancy models p(z' | state, a) + goal-z = E(goal pixels) -- encode goal frames with the SAME frozen + encoder (load_pixel_encoder), read out + r = exp(-||z' - z_g||^2 / (2 sigma_z^2)) + +proprio19 is the deterministic reconstruction of OGBench's 19 state-mode arm-proprio +dims from qpos/qvel (cube-single-v0 env, set qpos/qvel, mj_forward, +compute_observation()[:19]) — exactly what misc/lewm/convert_ogbench_npz_to_h5.py +already built and verified into cube_single_play_ogb64.h5. We copy that h5's +'observation' column instead of re-running 1M MuJoCo forwards, after asserting the h5 +qpos is byte-identical to the npz qpos on sampled rows (same dataset guarantee). +Pixels are also read from the h5 ('pixels', byte-identity to the npz was verified at +conversion time) because the h5 is chunked for streaming — we never materialize the +12 GB pixel array. + +Verification built in: shape/finiteness asserts, plus a sanity probe that z-distance +correlates with TRUE scaled-cube-xyz distance (Spearman over random frame pairs; +clearly positive = the latent metric tracks the reward-relevant geometry). + +Usage: + python ogbench_genq/genq/precompute_pixel_latents.py \ + --encoder ckpt/pixel_enc_cube_single_visual.npz \ + --out ckpt/cube_single_visual_latents.npz +""" +import argparse +import os +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from train_pixel_encoder_jax import (load_pixel_encoder, reward_target_fn, # noqa: E402 + scaled_cube_xyz) + +DEFAULT_CUBE_H5 = ("/proj/inf-scaling/zwhong/projs/gen_q/misc/lewm/stablewm_home/" + "datasets/ogbench/cube_single_play_ogb64.h5") + + +def maze_proprio(d, N): + """antmaze proprio channel = the ant state MINUS its global xy. + + The released visual-maze npz stores full qpos/qvel with state_obs == + concat(qpos, qvel) (verified) and the reward-relevant xy == qpos[:, :2]. + Vision (z) supplies xy; proprio supplies everything else, so proprio = + concat(qpos, qvel)[:, 2:] — no h5, no compute_ob_info() reconstruction.""" + full = np.concatenate([np.asarray(d["qpos"][:N], np.float32), + np.asarray(d["qvel"][:N], np.float32)], axis=1) + return full[:, 2:] # drop the global xy + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--env", default="visual-cube-single-play-v0", + help="visual env id; selects the reward geometry + proprio channel") + ap.add_argument("--encoder", required=True, help="npz from train_pixel_encoder_jax.py") + ap.add_argument("--data", default=None, + help="dataset npz (default ~/.ogbench/data/.npz)") + ap.add_argument("--h5", default=None, + help="CUBE ONLY: h5 with byte-identical 'pixels' + reconstructed " + "19-D 'observation' (proprio) — streams pixels without " + "materializing the full array. Maze reads the npz directly.") + ap.add_argument("--out", default=None) + ap.add_argument("--batch", type=int, default=4096) + ap.add_argument("--save_hidden", action="store_true", + help="also save the encoder's pixels-only fc_0 feature as " + "'state_h' for control-sufficient RSM conditioning") + ap.add_argument("--max_frames", type=int, default=0, help="0 = all (smoke aid)") + ap.add_argument("--probe_pairs", type=int, default=10000) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + is_maze = "maze" in args.env + repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + safe = args.env.replace("-", "_") + out = args.out or os.path.join(repo_root, "ckpt", f"{safe}_latents.npz") + os.makedirs(os.path.dirname(out), exist_ok=True) + data = args.data or os.path.expanduser(f"~/.ogbench/data/{args.env}.npz") + target_fn, _ = reward_target_fn(args.env) + + encode_fn, meta = load_pixel_encoder( + args.encoder, return_hidden=args.save_hidden) + print(f"[precompute] env={args.env} encoder z_dim={meta['z_dim']} " + f"sigma_z={meta['sigma_z']}", flush=True) + + d = np.load(os.path.expanduser(data)) + qpos = np.asarray(d["qpos"]) + actions = np.asarray(d["actions"], dtype=np.float32) + terminals = np.asarray(d["terminals"]).astype(bool) + N = len(terminals) if not args.max_frames else min(args.max_frames, len(terminals)) + + # ---- pixels + proprio, per env family ---- + if is_maze: + # everything is in the npz: pixels in 'observations', proprio from qpos/qvel + pix_all = np.asarray(d["observations"]) + proprio = maze_proprio(d, N) + def _pixels(i, hi): + return pix_all[i:hi] + h5f = None + else: + import h5py + h5 = args.h5 or DEFAULT_CUBE_H5 + h5f = h5py.File(os.path.expanduser(h5), "r") + assert len(h5f["pixels"]) == len(terminals), "h5/npz length mismatch" + for i in (0, N // 2, N - 1): + assert np.array_equal(h5f["qpos"][i], qpos[i]), f"h5/npz qpos mismatch at row {i}" + proprio = np.asarray(h5f["observation"][:N], dtype=np.float32) + def _pixels(i, hi): + return h5f["pixels"][i:hi] + + z = np.empty((N, meta["z_dim"]), dtype=np.float32) + state_h = ( + np.empty((N, meta["hidden"]), dtype=np.float32) + if args.save_hidden else None) + for i in range(0, N, args.batch): + hi = min(i + args.batch, N) + encoded = encode_fn(_pixels(i, hi)) + if args.save_hidden: + z[i:hi], state_h[i:hi] = encoded + else: + z[i:hi] = encoded + if (i // args.batch) % 25 == 0: + print(f" encode {i}/{N}", flush=True) + if h5f is not None: + h5f.close() + + assert z.shape == (N, meta["z_dim"]) and np.isfinite(z).all(), "bad z" + assert proprio.shape[0] == N and np.isfinite(proprio).all(), "bad proprio" + print(f"[precompute] z {z.shape} std/dim {np.round(z.std(0), 3)} | " + f"proprio {proprio.shape}", flush=True) + + # Saved under both keys: 'proprio' (generic) and 'proprio19' (back-compat with + # the cube-era loader). rsm.py reads whichever is present (see its latent branch). + payload = dict( + z=z, proprio=proprio, proprio19=proprio, + actions=actions[:N], terminals=terminals[:N], + z_dim=np.asarray(meta["z_dim"]), sigma_z=np.asarray(meta["sigma_z"]), + encoder_npz=np.asarray(os.path.abspath(args.encoder))) + if state_h is not None: + assert state_h.shape == (N, meta["hidden"]) + assert np.isfinite(state_h).all(), "bad state_h" + payload["state_h"] = state_h + payload["state_h_dim"] = np.asarray(meta["hidden"]) + print(f"[precompute] state_h {state_h.shape} " + f"mean std={state_h.std(0).mean():.3f}", flush=True) + np.savez(out, **payload) + print(f"[precompute] wrote {out} ({os.path.getsize(out)/1e6:.1f} MB)", flush=True) + + # ---- sanity probe: z-distance vs TRUE reward-coordinate distance ---- + from scipy.stats import spearmanr + rng = np.random.default_rng(args.seed) + i1 = rng.integers(0, N, args.probe_pairs) + i2 = rng.integers(0, N, args.probe_pairs) + true_coord = target_fn(qpos[:N]) + dz = np.linalg.norm(z[i1] - z[i2], axis=1) + dx = np.linalg.norm(true_coord[i1] - true_coord[i2], axis=1) + rho = spearmanr(dz, dx).statistic + print(f"[precompute] sanity probe: spearman(z-dist, true reward-coord dist) = " + f"{rho:.4f} over {args.probe_pairs} random pairs (expect clearly positive)", + flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/readout_diag.py b/gen_q_rsm/ogbench_genq/genq/readout_diag.py new file mode 100644 index 0000000000000000000000000000000000000000..84eea92f6d8039f70aaf2b484ddd4fa729ce943d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/readout_diag.py @@ -0,0 +1,165 @@ +"""De-risk the learned coordinate-free RSM read-out (issue: fair image RSM > GCIQL 0.33). + +Question. The RSM pixel read-out is a FIXED Gaussian kernel on latent distance, + Q = E_{z'~occ}[ exp(-||z'-z_g||^2 / 2 sigma_z^2) ]. +On fair (coordinate-free) latents the metric plateaus at spearman(z,xy)~0.47 and the +fixed-kernel read-out reads SR 0.000 -- a knife-edge. GCIQL wins at 0.33 with a +*learned* value on a moderately-aligned rep. The CLAUDE.md image spec prescribes a +*learned* reward decoder R_psi(z,g), not a fixed kernel. + +This script tests, WITHOUT training an occupancy model, whether a learned +coordinate-free read-out extracts cube-proximity better than the fixed kernel on the +SAME fair latent. R_psi is trained ONLY on gamma^steps hindsight value (trajectory +index structure -- no cube coordinate). The cube coordinate is used ONLY to score the +final ranking (diagnostic, exactly like proxy_spearman). Fair. + +Usage: + python genq/readout_diag.py --latents ckpt/visual_cube_single_recononly_latents.npz +""" +import argparse, os, sys +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from train_pixel_encoder_jax import scaled_cube_xyz # diagnostic ground truth only + + +def episode_bounds(terminals): + ends = np.where(terminals)[0] + starts = np.concatenate([[0], ends[:-1] + 1]) + return list(zip(starts.tolist(), ends.tolist())) + + +def sample_pairs(eps, rng, n, gamma_v, min_gap=1, max_gap=200): + """Within-episode (t, g) pairs with g downstream of t. value = gamma_v^(g-t).""" + ts, gs = [], [] + ep_idx = rng.integers(0, len(eps), n) + for e in ep_idx: + s, en = eps[e] + if en - s < 2: + continue + t = rng.integers(s, en) # not the last frame + hi = min(en, t + max_gap) + if hi <= t: + continue + g = rng.integers(t + 1, hi + 1) + ts.append(t); gs.append(g) + ts = np.asarray(ts); gs = np.asarray(gs) + val = (gamma_v ** (gs - ts).astype(np.float32)).astype(np.float32) + return ts, gs, val + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--latents", required=True) + ap.add_argument("--data", default=os.path.expanduser( + "~/.ogbench/data/visual-cube-single-play-v0.npz")) + ap.add_argument("--gamma_v", type=float, default=0.98) + ap.add_argument("--n_train", type=int, default=200000) + ap.add_argument("--n_val", type=int, default=40000) + ap.add_argument("--epochs", type=int, default=40) + ap.add_argument("--hidden", type=int, default=256) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + from scipy.stats import spearmanr + import jax, jax.numpy as jnp, optax + + rng = np.random.default_rng(args.seed) + L = np.load(args.latents, allow_pickle=True) + z = np.asarray(L["z"], np.float32) + terminals = np.asarray(L["terminals"]) + sigma_z = float(L["sigma_z"]) if "sigma_z" in L.files else 1.0 + N = len(z) + print(f"[diag] latents={args.latents} N={N} z_dim={z.shape[1]} sigma_z={sigma_z}") + + # diagnostic ground truth: cube xyz (SCORING ONLY, never trains R_psi) + d = np.load(args.data) + qpos = np.asarray(d["qpos"])[:N] + xyz = scaled_cube_xyz(qpos).astype(np.float32) + + eps = episode_bounds(terminals) + # split episodes into train/val so val pairs are unseen states + n_ep = len(eps) + perm = rng.permutation(n_ep) + tr_eps = [eps[i] for i in perm[: int(0.9 * n_ep)]] + va_eps = [eps[i] for i in perm[int(0.9 * n_ep):]] + print(f"[diag] episodes={n_ep} train={len(tr_eps)} val={len(va_eps)}") + + t_tr, g_tr, v_tr = sample_pairs(tr_eps, rng, args.n_train, args.gamma_v) + t_va, g_va, v_va = sample_pairs(va_eps, rng, args.n_val, args.gamma_v) + + # ground-truth proximity for ranking: closeness of cube(t) to cube(goal g) + cube_d_va = np.linalg.norm(xyz[t_va] - xyz[g_va], axis=1) + prox_va = -cube_d_va # higher = closer = should read higher Q + + # ---- baseline 1: FIXED Gaussian kernel on latent distance ---- + dz_va = np.sum((z[t_va] - z[g_va]) ** 2, axis=1) + kfix_va = np.exp(-dz_va / (2 * sigma_z ** 2)) + rho_fix = spearmanr(kfix_va, prox_va).statistic + + # ---- baseline 2: learned linear metric (Mahalanobis-ish) on |z_t - z_g| ---- + # ---- primary: learned MLP read-out R_psi([z_t, z_g, z_t-z_g]) -> value ---- + def feats(t_idx, g_idx): + a = z[t_idx]; b = z[g_idx] + return np.concatenate([a, b, a - b, (a - b) ** 2], axis=1).astype(np.float32) + + Xtr = feats(t_tr, g_tr); Xva = feats(t_va, g_va) + mu = Xtr.mean(0); sd = Xtr.std(0) + 1e-6 + Xtr = (Xtr - mu) / sd; Xva = (Xva - mu) / sd + ytr = v_tr.astype(np.float32) + din = Xtr.shape[1] + H = args.hidden + key = jax.random.PRNGKey(args.seed) + def init(key): + k1, k2, k3 = jax.random.split(key, 3) + s = lambda k, a, b: jax.random.normal(k, (a, b)) * (2.0 / a) ** 0.5 + return {"w1": s(k1, din, H), "b1": jnp.zeros(H), + "w2": s(k2, H, H), "b2": jnp.zeros(H), + "w3": s(k3, H, 1) * 0.1, "b3": jnp.zeros(1)} + p = init(key) + def fwd(p, X): + h = jnp.tanh(X @ p["w1"] + p["b1"]) + h = jnp.tanh(h @ p["w2"] + p["b2"]) + return (h @ p["w3"] + p["b3"])[:, 0] + def loss(p, X, y): + return jnp.mean((fwd(p, X) - y) ** 2) + tx = optax.adam(1e-3) + opt = tx.init(p) + @jax.jit + def step(p, opt, X, y): + l, g = jax.value_and_grad(loss)(p, X, y) + u, opt = tx.update(g, opt, p) + return optax.apply_updates(p, u), opt, l + Xtr_j = jnp.asarray(Xtr); ytr_j = jnp.asarray(ytr) + bs = 8192 + nb = len(Xtr) // bs + for ep in range(args.epochs): + order = rng.permutation(len(Xtr)) + ll = 0.0 + for bi in range(nb): + idx = order[bi * bs:(bi + 1) * bs] + p, opt, l = step(p, opt, Xtr_j[idx], ytr_j[idx]) + ll += float(l) + if ep % 5 == 0 or ep == args.epochs - 1: + rpsi_va = np.asarray(fwd(p, jnp.asarray(Xva))) + rho_learn = spearmanr(rpsi_va, prox_va).statistic + print(f"[diag] epoch {ep:2d} mse={ll/max(nb,1):.5f} " + f"spearman(R_psi, cube-prox)={rho_learn:.4f}", flush=True) + + rpsi_va = np.asarray(fwd(p, jnp.asarray(Xva))) + rho_learn = spearmanr(rpsi_va, prox_va).statistic + + print("\n==== READ-OUT DIAGNOSTIC (higher spearman-vs-cube-proximity = better) ====") + print(f" fixed Gaussian kernel spearman = {rho_fix:.4f}") + print(f" learned R_psi (MLP) spearman = {rho_learn:.4f} " + f"[trained coordinate-free on gamma^steps]") + print(f" --> learned read-out {'WINS' if rho_learn > rho_fix + 0.03 else 'no better'} " + f"by {rho_learn - rho_fix:+.4f}") + # also: how well does the coordinate-free value itself track cube proximity? + rho_val = spearmanr(v_va, prox_va).statistic + print(f" (ref) gamma^steps value spearman = {rho_val:.4f} " + f"[the coordinate-free training signal's own cube-alignment]") + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/reward_reader.py b/gen_q_rsm/ogbench_genq/genq/reward_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..5ce67a3c6edaa2d7bfe7bf92d022d3645b163510 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/reward_reader.py @@ -0,0 +1,266 @@ +"""Load frozen visual reward readers without changing legacy MLP semantics. + +Reader artifacts created before ``reader_model`` was introduced are interpreted +as pairwise MLPs. The alternative ``diag_metric`` reader is a calibrated +logistic diagonal Mahalanobis metric, + + logit(z, g) = bias - sum_i weight_i * ((z_i - g_i) / scale_i) ** 2, + +with positive scales and nonnegative weights. Both readers consume only the +cached pixel latent and are used after occupancy fitting (or as the frozen +semantic auxiliary for a latent adapter). +""" + +import os + +import numpy as np + + +READER_MODELS = ("mlp", "diag_metric") + + +def joint_index_pair_masks( + rows, goals, row_starts, row_ends, index_delta, neg_gap, + reader_model, array_module=np): + """Return positive/negative masks for the frozen-reader adapter auxiliary. + + Legacy MLP readers keep cross-episode negatives. A diagonal metric gets + same-episode far negatives only: episode identity is not part of its + distance and must not become an adapter shortcut. + """ + if reader_model not in READER_MODELS: + raise ValueError(f"unknown reader_model={reader_model!r}") + goal_distance = goals - rows + same_episode = (goals >= row_starts) & (goals < row_ends) + positive = ( + same_episode + & (goal_distance >= 0) + & (goal_distance <= index_delta)) + if reader_model == "diag_metric": + negative = same_episode & ( + array_module.abs(goal_distance) >= neg_gap) + else: + negative = ( + ~same_episode + | (array_module.abs(goal_distance) >= neg_gap)) + return positive, negative + + +def _scalar_string(value): + array = np.asarray(value) + if array.ndim != 0: + raise ValueError(f"expected scalar string, got shape {array.shape}") + return str(array.item()) + + +def _reader_arrays(path): + """Copy an npz reader into ordinary arrays and validate its schema.""" + with np.load(path, allow_pickle=False) as artifact: + arrays = {key: np.asarray(artifact[key]) for key in artifact.files} + + model = ( + _scalar_string(arrays["reader_model"]) + if "reader_model" in arrays else "mlp") + if model not in READER_MODELS: + raise ValueError( + f"unknown reader_model={model!r}; expected one of {READER_MODELS}") + if "zdim" not in arrays: + raise ValueError("reward reader lacks zdim") + zdim = int(np.asarray(arrays["zdim"]).item()) + + features = ( + _scalar_string(arrays["features"]) + if "features" in arrays else "concat") + activation = ( + _scalar_string(arrays["activation"]) + if "activation" in arrays else "tanh") + if model == "mlp": + if features not in ("concat", "symmetric"): + raise ValueError(f"unknown MLP reader features={features!r}") + if activation not in ("relu", "tanh"): + raise ValueError(f"unknown MLP reader activation={activation!r}") + required = { + "g0.kernel", "g0.bias", + "g1.kernel", "g1.bias", + "g2.kernel", "g2.bias", + } + else: + required = {"metric_scale", "metric_weight", "metric_bias"} + missing = sorted(required.difference(arrays)) + if missing: + raise ValueError( + f"{model} reward reader lacks parameters: {missing}") + + metadata = { + "path": os.path.abspath(path), + "reader_model": model, + "target": ( + _scalar_string(arrays["target"]) + if "target" in arrays else "unknown"), + "index_delta": ( + int(np.asarray(arrays["index_delta"]).item()) + if "index_delta" in arrays else None), + "neg_gap": ( + int(np.asarray(arrays["neg_gap"]).item()) + if "neg_gap" in arrays else None), + "features": features, + "activation": activation, + "zdim": zdim, + } + for key in ( + "pixels_only_latents", + "frozen_encoder", + "uses_coordinates_for_training", + "uses_coordinates_for_diagnostics", + "uses_reward_arrays", + "uses_td_or_bootstrap", + "label_source"): + if key not in arrays: + continue + value = np.asarray(arrays[key]) + metadata[key] = ( + _scalar_string(value) + if value.dtype.kind in ("U", "S", "O") + else bool(value.item())) + + if model == "diag_metric": + scale = np.asarray(arrays["metric_scale"], np.float32) + weight = np.asarray(arrays["metric_weight"], np.float32) + bias = np.asarray(arrays["metric_bias"], np.float32) + if scale.shape != (zdim,) or weight.shape != (zdim,): + raise ValueError( + "diag_metric scale and weight must both have shape " + f"({zdim},), got {scale.shape} and {weight.shape}") + if bias.size != 1: + raise ValueError( + f"diag_metric bias must be scalar, got shape {bias.shape}") + if (not np.all(np.isfinite(scale)) + or not np.all(np.isfinite(weight)) + or not np.all(np.isfinite(bias))): + raise ValueError("diag_metric parameters must be finite") + if np.any(scale <= 0.0): + raise ValueError("diag_metric scale must be strictly positive") + if np.any(weight < 0.0): + raise ValueError("diag_metric weight must be nonnegative") + metadata.update({ + "metric_formula": ( + "bias-sum(weight*((future-goal)/scale)^2)"), + "metric_scale": scale.tolist(), + "metric_weight": weight.tolist(), + "metric_scale_min": float(scale.min()), + "metric_scale_max": float(scale.max()), + "metric_weight_min": float(weight.min()), + "metric_weight_max": float(weight.max()), + "metric_weight_sum": float(weight.sum()), + "metric_bias": float(bias.reshape(())), + "metric_weight_nonnegative": True, + }) + return arrays, metadata + + +def load_jax_reward_reader(path): + """Return ``(logits, metadata)`` for use in JAX training/evaluation.""" + import jax + import jax.numpy as jnp + + arrays, metadata = _reader_arrays(path) + model = metadata["reader_model"] + if model == "diag_metric": + scale = jnp.asarray( + np.asarray(arrays["metric_scale"], np.float32)) + weight = jnp.asarray( + np.asarray(arrays["metric_weight"], np.float32)) + bias = jnp.asarray( + np.asarray(arrays["metric_bias"], np.float32)).reshape(()) + + def logits(zf, zg): + difference = (zf - zg) / scale + return bias - jnp.sum( + weight * jnp.square(difference), axis=-1) + + return logits, metadata + + features = metadata["features"] + activation = metadata["activation"] + # Keep the legacy parameter selection and operation order unchanged. + params = { + key: jnp.asarray(np.asarray(arrays[key], np.float32)) + for key in arrays + if key.endswith("kernel") or key.endswith("bias") + } + + def logits(zf, zg): + if features == "symmetric": + hidden = jnp.concatenate( + [zf, zg, jnp.abs(zf - zg), zf * zg], axis=-1) + else: + hidden = jnp.concatenate([zf, zg], axis=-1) + activate = jax.nn.relu if activation == "relu" else jnp.tanh + hidden = activate( + hidden @ params["g0.kernel"] + params["g0.bias"]) + hidden = activate( + hidden @ params["g1.kernel"] + params["g1.bias"]) + return ( + hidden @ params["g2.kernel"] + params["g2.bias"])[:, 0] + + return logits, metadata + + +def load_numpy_reward_reader(path, probability=False): + """Return a NumPy logit or calibrated-probability reader.""" + arrays, metadata = _reader_arrays(path) + model = metadata["reader_model"] + if model == "diag_metric": + scale = np.asarray(arrays["metric_scale"], np.float32) + weight = np.asarray(arrays["metric_weight"], np.float32) + bias = np.asarray(arrays["metric_bias"], np.float32).reshape(()) + + def logits(zf, zg): + difference = (zf - zg) / scale + return bias - np.sum( + weight * np.square(difference), axis=-1) + + else: + features = metadata["features"] + activation = metadata["activation"] + parameters = { + key: np.asarray(arrays[key], np.float32) + for key in arrays + if key.endswith("kernel") or key.endswith("bias") + } + + def logits(zf, zg): + if features == "symmetric": + hidden = np.concatenate( + [ + zf, + zg, + np.abs(zf - zg), + zf * zg, + ], + axis=-1, + ) + else: + hidden = np.concatenate([zf, zg], axis=-1) + activate = ( + lambda value: np.maximum(value, 0.0) + if activation == "relu" else np.tanh(value)) + hidden = activate( + hidden @ parameters["g0.kernel"] + + parameters["g0.bias"]) + hidden = activate( + hidden @ parameters["g1.kernel"] + + parameters["g1.bias"]) + return ( + hidden @ parameters["g2.kernel"] + + parameters["g2.bias"])[:, 0] + + if not probability: + return logits, metadata + + def calibrated_probability(zf, zg): + values = logits(zf, zg) + return 1.0 / ( + 1.0 + np.exp(-np.clip(values, -30.0, 30.0))) + + return calibrated_probability, metadata diff --git a/gen_q_rsm/ogbench_genq/genq/summarize_gciql_goal_screen.py b/gen_q_rsm/ogbench_genq/genq/summarize_gciql_goal_screen.py new file mode 100644 index 0000000000000000000000000000000000000000..58e77bbf6a540cf203c7a1b7f4a0e2aa5d4fb710 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/summarize_gciql_goal_screen.py @@ -0,0 +1,57 @@ +"""Rank GCIQL-matched, pixels-only goal-return encoder variants.""" +import argparse +import os + +import numpy as np + + +def scalar(data, key, default=np.nan): + return data[key].item() if key in data else default + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("encoders", nargs="+") + args = ap.parse_args() + + rows = [] + for path in args.encoders: + if not os.path.exists(path): + continue + data = np.load(path, allow_pickle=True) + auc = float(scalar(data, "goalpred_val_auc")) + value_rho = float(scalar(data, "goalvalue_val_spearman")) + value_mae = float(scalar(data, "goalvalue_val_mae")) + cube_rho = float(scalar(data, "goalvalue_cube_spearman")) + latent_rho = float(scalar(data, "proxy_spearman")) + # Selection is strictly coordinate-free: calibrated soft-return + # prediction and exact index-reward ranking. Cube correlations are + # printed only for post-selection diagnosis and never affect rank. + score = value_rho - value_mae + 0.1 * auc + rows.append(( + score, + str(scalar(data, "variant", os.path.basename(path))), + float(scalar(data, "w_goalcls_bin")), + value_rho, + value_mae, + auc, + cube_rho, + latent_rho, + path, + )) + + rows.sort(reverse=True) + print( + "rank\ttag\tweight\tvalue_rho\tvalue_mae\treward_auc\t" + "value_cube_rho\tlatent_cube_rho\tpath" + ) + for rank, row in enumerate(rows, 1): + _, tag, weight, value_rho, value_mae, auc, cube_rho, latent_rho, path = row + print( + f"{rank}\t{tag}\t{weight:g}\t{value_rho:.4f}\t{value_mae:.4f}\t" + f"{auc:.4f}\t{cube_rho:.4f}\t{latent_rho:.4f}\t{path}" + ) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/summarize_goalpred_screen.py b/gen_q_rsm/ogbench_genq/genq/summarize_goalpred_screen.py new file mode 100644 index 0000000000000000000000000000000000000000..839810c129146aee12eeff93c92742d664bf5ac1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/summarize_goalpred_screen.py @@ -0,0 +1,44 @@ +"""Print a compact ranking for pixels-only goal-prediction encoder screens.""" +import argparse +import os + +import numpy as np + + +def scalar(data, key, default=np.nan): + return data[key].item() if key in data else default + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("encoders", nargs="+") + args = ap.parse_args() + + rows = [] + for path in args.encoders: + if not os.path.exists(path): + continue + data = np.load(path, allow_pickle=True) + auc = float(scalar(data, "goalpred_val_auc")) + acc = float(scalar(data, "goalpred_val_acc")) + rho = float(scalar(data, "proxy_spearman")) + r2 = float(scalar(data, "proxy_xy_r2")) + # The temporal-label AUC is the coordinate-free primary metric. Cube + # distance is a diagnostic tie-breaker only, never a training target. + score = auc + 0.25 * max(rho, 0.0) + rows.append((score, str(scalar(data, "variant", os.path.basename(path))), + int(scalar(data, "z_dim", -1)), + int(scalar(data, "hidden", -1)), + float(scalar(data, "w_goalcls_bin")), + auc, acc, rho, r2, path)) + + rows.sort(reverse=True) + print("rank\ttag\tz\thidden\tweight\tgoal_auc\tgoal_acc\tcube_rho\tcube_r2\tpath") + for rank, row in enumerate(rows, 1): + _, tag, zdim, hidden, weight, auc, acc, rho, r2, path = row + print(f"{rank}\t{tag}\t{zdim}\t{hidden}\t{weight:g}\t" + f"{auc:.4f}\t{acc:.4f}\t{rho:.4f}\t{r2:.4f}\t{path}") + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/target_extractors.py b/gen_q_rsm/ogbench_genq/genq/target_extractors.py new file mode 100644 index 0000000000000000000000000000000000000000..a39a785739ed0503e1f091fc80e1b77f5cc3dfc3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/target_extractors.py @@ -0,0 +1,182 @@ +"""Reward-relevant occupancy targets for every state-based OGBench env. + +The occupancy models ONLY these coordinates (z); the read-out evaluates their +likelihood at the goal, so z must be exactly "the coordinates whose value at +the goal defines success". Resolution is by env-id prefix, so every dataset +variant of a family (navigate / stitch / explore, play / noisy) and every size +(medium / large / giant / teleport, 3x3 / 4x4 / 4x5 / 4x6, single..quadruple) +maps to the same verified layout. + +Layout facts, verified against the installed OGBench source and the cached +datasets (obs dims + per-dim value ranges): + +mazes (pointmaze / antmaze / humanoidmaze) — agent xy at obs[:2] + locomaze envs build obs = concat([qpos, qvel]) and qpos[:2] is the global + xy. Dataset check: dims 0/1 span the maze coordinate range (~[-2, 22] on + medium). pointmaze obs 4, antmaze 29 (qpos 15 + qvel 14), humanoidmaze 69. + +antsoccer — BALL xy at obs[15:17], not the ant's + Success is measured on the ball: maze.py's set_goal / success check use + get_agent_ball_xy()[1] = qpos[-7:-5]. obs = concat([qpos, qvel]) with + qpos = 15 ant dims + 7 ball freejoint dims, so ball x,y = obs[15], obs[16] + (obs is 42-dim). Dataset check: dims 15/16 span the maze range while + dim 17 is the ball height (0.19..1.18) and 18+ are quaternion entries. + +manipulation (cube / scene / puzzle) — 19 proprio dims, then per-object blocks + From ManipSpaceEnv.compute_observation: arm joint pos (6) + vel (6) + + scaled effector pos (3) + effector yaw cos/sin (2) + gripper opening (1) + + gripper contact (1) = 19 dims, then: + cube: 9 dims per cube -> cube i xyz (scaled) at obs[19+9i : 19+9i+3] + obs dim 19+9n (single 28, double 37 verified from datasets) + puzzle: 4 dims per button -> "pressed" bit (2nd one-hot entry) at + obs[19 + 4i + 1]; obs dim 19+4*NM (3x3: 55, 4x4: 83 verified) + scene: cube xyz + 2 button bits + drawer_pos + window_pos at + indices [19,20,21,29,33,36,38]; obs dim 40 verified +""" +from __future__ import annotations + +import numpy as np + + +def env_safe_name(env_id: str) -> str: + """Filesystem-safe env id (used for checkpoint / result filenames).""" + return env_id.replace("-", "_") + + +# --------------------------------------------------------------------------- +# Per-family extractors. Each spec is (fn, target_dim, expected_obs_dim|None, +# description); expected_obs_dim is asserted when known so a wrong-layout env +# fails loudly instead of training on garbage coordinates. +# --------------------------------------------------------------------------- + +_CUBE_COUNT = {"single": 1, "double": 2, "triple": 3, "quadruple": 4} + +_SCENE_TARGET_IDX = np.array([19, 20, 21, 29, 33, 36, 38], dtype=np.int64) + + +def _maze_xy(obs): + return obs[..., :2] + + +def _ball_xy(obs): + return obs[..., 15:17] + + +def _spec_for(env_id: str): + parts = env_id.split("-") + family, size = parts[0], parts[1] if len(parts) > 1 else "" + if family in ("pointmaze", "antmaze", "humanoidmaze"): + return _maze_xy, 2, None, f"{family} agent xy" + if family == "antsoccer": + return _ball_xy, 2, 42, "soccer ball xy (success is measured on the ball)" + if family == "cube": + n = _CUBE_COUNT[size] + idx = np.concatenate( + [np.arange(19 + 9 * i, 19 + 9 * i + 3) for i in range(n)]) + return ((lambda o, idx=idx: o[..., idx]), 3 * n, 19 + 9 * n, + f"{n} cube xyz (scaled)") + if family == "scene": + return ((lambda o: o[..., _SCENE_TARGET_IDX]), 7, 40, + "cube xyz + 2 button bits + drawer + window") + if family == "puzzle": + rows, cols = size.split("x") + nb = int(rows) * int(cols) + idx = 19 + 4 * np.arange(nb, dtype=np.int64) + 1 + return ((lambda o, idx=idx: o[..., idx]), nb, 19 + 4 * nb, + f"{nb} button-pressed bits") + raise KeyError(f"no target extractor for env family '{family}' ({env_id})") + + +def get_target_dim(env_id: str) -> int: + """Dimensionality of the occupancy target for `env_id`.""" + return _spec_for(env_id)[1] + + +def extract_target(env_id: str, obs: np.ndarray) -> np.ndarray: + """Extract the reward-relevant slice from raw obs. + + obs: shape [..., obs_dim]. Returns shape [..., target_dim]. + """ + fn, dim, obs_dim, _ = _spec_for(env_id) + if obs_dim is not None and obs.shape[-1] != obs_dim: + raise ValueError( + f"{env_id}: obs dim {obs.shape[-1]} != expected {obs_dim} — " + "layout drift, do not train on this") + out = fn(obs) + if out.shape[-1] != dim: + raise ValueError( + f"extractor for {env_id} returned dim {out.shape[-1]} != {dim}") + return np.ascontiguousarray(out) + + +# --------------------------------------------------------------------------- +# Static goal fallbacks in target space. Rollout-time goals always come from +# the env (per-episode goal observation -> extract_target); these exist only +# for offline diagnostics that need "a" goal point. +# --------------------------------------------------------------------------- + +def goal_for(env_id: str) -> np.ndarray: + """Canonical fallback goal point in target space.""" + family = env_id.split("-")[0] + dim = get_target_dim(env_id) + if family in ("pointmaze", "antmaze", "humanoidmaze", "antsoccer"): + return np.full(dim, 20.0, dtype=np.float32) + if family == "cube": # each cube lifted above table center (scaled) + return np.tile(np.array([0.0, 0.0, 1.5], dtype=np.float32), dim // 3) + if family == "puzzle": # all buttons pressed + return np.ones(dim, dtype=np.float32) + if family == "scene": # neutral all-zero task signals + return np.zeros(dim, dtype=np.float32) + raise KeyError(f"no fallback goal for {env_id}") + + +# ---- target VARIANTS (issue #57 diagnostics): wider occupancy targets ---- +# "bits_eff": button bits + effector xyz (obs dims 12:15, the scaled +# (effector_pos - center)*10 slice). The effector responds to actions +# IMMEDIATELY while bits flip only when a press completes (~50 steps), so a +# read-out that softly matches goal effector position adds the dense +# action-sensitive signal the bits-only target lacks. +# "full": the entire raw observation (proprio + buttons); the read-out weights +# bit dims sharply and the rest softly (see runner sigma_vec). +_PUZZLE_EFF_IDX = np.arange(12, 15, dtype=np.int64) +_PUZZLE3X3_PRESSED_IDX = 19 + 4 * np.arange(9, dtype=np.int64) + 1 +_PUZZLE4X4_PRESSED_IDX = 19 + 4 * np.arange(16, dtype=np.int64) + 1 + + +def _identity(obs): + return obs + + +# VARIANT_TARGETS[env][variant] = (fn, dim, is_bit_dim mask, description) +VARIANT_TARGETS = { + "puzzle-3x3-play-v0": { + "bits_eff": (lambda o: o[..., np.concatenate([_PUZZLE_EFF_IDX, _PUZZLE3X3_PRESSED_IDX])], 12, + np.array([False] * 3 + [True] * 9), + "effector xyz (scaled) + 9 button bits"), + "full": (_identity, 55, + np.isin(np.arange(55), _PUZZLE3X3_PRESSED_IDX), + "full 55-d observation"), + }, + "puzzle-4x4-play-v0": { + "bits_eff": (lambda o: o[..., np.concatenate([_PUZZLE_EFF_IDX, _PUZZLE4X4_PRESSED_IDX])], 19, + np.array([False] * 3 + [True] * 16), + "effector xyz (scaled) + 16 button bits"), + }, +} + + +def extract_target_variant(env_id: str, obs: np.ndarray, variant: str): + """extract_target with a named variant; variant='default' = extract_target.""" + if variant in (None, "", "default"): + return extract_target(env_id, obs) + fn, dim, _, _ = VARIANT_TARGETS[env_id][variant] + out = fn(obs) + assert out.shape[-1] == dim + return np.ascontiguousarray(out) + + +def variant_bit_mask(env_id: str, variant: str): + """Boolean mask of which target dims are button bits (for per-dim read-out sigma).""" + if variant in (None, "", "default"): + return np.ones(get_target_dim(env_id), dtype=bool) + return VARIANT_TARGETS[env_id][variant][2] diff --git a/gen_q_rsm/ogbench_genq/genq/train_genq_jax.py b/gen_q_rsm/ogbench_genq/genq/train_genq_jax.py new file mode 100644 index 0000000000000000000000000000000000000000..da9eddbda1f24e1c99861301d529148df1b82fdc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_genq_jax.py @@ -0,0 +1,627 @@ +"""Native-JAX Gen-Q occupancy trainer — replaces the PyTorch train_m9.py -> convert_npz pipeline. + +Owner directive (PR #23, "Yes" to two questions): implement the Gen-Q score network + DDPM training +loop entirely in JAX/Flax so Gen-Q is JAX end-to-end (no torch, no torch->npz bridge). This trains a +conditional denoising diffusion model + + p_theta(x_{t+k} | s_t, a_t, g), k ~ Geom(1 - gamma) + +where x is the env's low-dim Gen-Q target (xy for mazes, target_extractors slice otherwise — or, when +--latent_npz is given, a frozen reward-aware latent z; see train_latent_encoder_jax.py). The architecture +is byte-for-byte the same MLP as src/models.py:ConditionalDiffusion (SinusoidalEmbedding -> time MLP, +cond_emb, x_emb, num_layers SiLU trunk, out), so the weights it saves load straight into +genq_jax.py:load_genq_params via the SAME `.genqjax.npz` schema the torch converter emitted: + + time_emb.1.{weight,bias}, time_emb.3.{weight,bias}, + cond_emb.0.{weight,bias}, x_emb.{weight,bias}, + trunk.{0,2,4,...}.{weight,bias}, out.{weight,bias}, + abar, abar_prev, cond_mean, cond_std, y_mean, y_std, + meta_{cond_dim,y_dim,num_layers,diffusion_T,sample_steps} + +Linear weights are stored torch-style ([out,in]) because genq_jax._lin does `x @ w.T + b`. + +Run (JAX venv, NO torch needed): + PYTHONPATH=$OGB:ogbench_genq:src python ogbench_genq/train_genq_jax.py \ + --env pointmaze-medium-navigate-v0 --train_steps 100000 +""" +import argparse +import math +import os +import sys + +import numpy as np + + +# ----------------------------- noise schedule ----------------------------- +def cosine_abar(T, s=0.008): + """Cosine alpha_bar schedule, matching src/models.py:_cosine_abar (float64 then clamp->f32).""" + steps = np.arange(T + 1, dtype=np.float64) + f = np.cos(((steps / T) + s) / (1 + s) * math.pi / 2) ** 2 + abar = f / f[0] + return np.clip(abar[1:], 1e-6, 0.9999).astype(np.float32) # abar[t], t=1..T + + +# ----------------------------- data: geometric horizon ----------------------------- +def build_ends(terminals): + """end_of[i] = one-past-the-last index of the trajectory containing i (matches main_genq_jax).""" + term = np.asarray(terminals) + ends = np.where(term > 0)[0] + end_of = np.zeros(len(term), dtype=np.int64) + prev = 0 + for e in ends: + end_of[prev:e + 1] = e + 1 + prev = e + 1 + if prev < len(term): + end_of[prev:] = len(term) + return end_of + + +def future_idx(t, end_of, gamma, rng): + """j = t + k, k ~ truncated Geom(1-gamma) within the trajectory. Matches train_gc._future.""" + L = end_of[t] - t + logg = math.log(gamma) + Fmax = np.maximum(1.0 - gamma ** L, 1e-12) + u = rng.random(len(t)) * Fmax + k = np.clip(np.ceil(np.log1p(-u) / logg).astype(np.int64) - 1, 0, L - 1) + return t + k + + +def sample_goal_after(j, end_of, rng): + """Hindsight goal index at/after target j in the same trajectory. Matches train_gc.sample_goal_after.""" + e = end_of[j] + span = np.maximum(e - j, 1) + return np.clip(j + (rng.random(len(j)) * span).astype(np.int64), 0, e - 1) + + +# ----------------------------- score network (flax) ----------------------------- +def make_model(cond_dim, y_dim, hidden_dim, num_layers, time_dim): + import flax.linen as fnn + import jax.numpy as jnp + + def sinusoid(t, dim): + half = dim // 2 + freqs = jnp.exp(-math.log(10000.0) * jnp.arange(half, dtype=jnp.float32) / max(half - 1, 1)) + ang = t[:, None] * freqs[None] * 1000.0 + return jnp.concatenate([jnp.sin(ang), jnp.cos(ang)], axis=-1) + + class ScoreNet(fnn.Module): + @fnn.compact + def __call__(self, x, t_frac, c): + # time MLP: SinusoidalEmbedding(time_dim) -> Linear -> SiLU -> Linear + te = sinusoid(t_frac, time_dim) + te = fnn.Dense(time_dim, name="time_emb_1")(te) + te = fnn.silu(te) + te = fnn.Dense(time_dim, name="time_emb_3")(te) + ce = fnn.silu(fnn.Dense(hidden_dim, name="cond_emb_0")(c)) + xe = fnn.Dense(hidden_dim, name="x_emb")(x) + h = jnp.concatenate([xe, ce, te], axis=-1) + for i in range(num_layers): + h = fnn.silu(fnn.Dense(hidden_dim, name=f"trunk_{i}")(h)) + return fnn.Dense(y_dim, name="out")(h) + + return ScoreNet() + + +# ----------------------------- weight export (torch-compatible npz) ----------------------------- +def flax_params_to_npz_arrays(params): + """Map flax param tree -> the torch-style key names genq_jax.py expects. + + flax Dense kernel is [in,out]; torch Linear weight is [out,in] and genq_jax does x@w.T. So we + store kernel.T under the torch key name. num_layers is inferred from the trunk_* entries. + """ + p = params["params"] if "params" in params else params + out = {} + + def lin(name, torch_prefix): + out[f"{torch_prefix}.weight"] = np.asarray(p[name]["kernel"]).T.astype(np.float32) + out[f"{torch_prefix}.bias"] = np.asarray(p[name]["bias"]).astype(np.float32) + + lin("time_emb_1", "time_emb.1") + lin("time_emb_3", "time_emb.3") + lin("cond_emb_0", "cond_emb.0") + lin("x_emb", "x_emb") + n_layers = sum(1 for k in p if k.startswith("trunk_")) + for i in range(n_layers): + lin(f"trunk_{i}", f"trunk.{2 * i}") # torch trunk has SiLU at odd indices + lin("out", "out") + return out, n_layers + + +# ----------------------------- main ----------------------------- +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--env", required=True) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=100000) + ap.add_argument("--batch_size", type=int, default=256) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--weight_decay", type=float, default=0.0) + ap.add_argument("--hidden_dim", type=int, default=256) + ap.add_argument("--num_layers", type=int, default=3) + ap.add_argument("--time_dim", type=int, default=64) + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--diffusion_T", type=int, default=100) + ap.add_argument("--sample_steps", type=int, default=30) + ap.add_argument("--ogbench_impls", + default=os.environ.get("OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls"))) + ap.add_argument("--state_target", action="store_true", + help="condition the occupancy on extract_target(obs) instead of the full " + "observation, so state==target and the recursive-d_gamma composition " + "(genq_recursive_jax.py) is fully in-graph. Exact for pointmaze (already " + "xy); a position-/target-Markov approximation elsewhere.") + ap.add_argument("--latent_npz", default=None, + help="if given, train occupancy in the frozen latent z-space of this encoder " + "(train_latent_encoder_jax.py output) instead of the raw target.") + ap.add_argument("--target_variant", default="default", + help="occupancy target variant (target_extractors.VARIANT_TARGETS): e.g. " + "puzzle 'bits_eff' (effector xyz + bits) or 'full' (whole obs). The " + "wider targets carry action-responsive dims the bits lack (issue #57).") + ap.add_argument("--model", default="diffusion", choices=["diffusion", "flow"], + help="occupancy model family: DDPM (eps-MSE, DDIM sampling) or conditional " + "flow-matching (linear-path velocity-MSE, Euler sampling). Both are " + "CLAUDE.md-sanctioned; flow added for the issue #57 model-axis sweep.") + ap.add_argument("--absorb_goal", action="store_true", + help="ABSORBING occupancy (issue #57, owner catch): sample the hindsight goal " + "index gi FIRST, then k~Geom(1-gamma), and clamp the future at the goal " + "(j = min(t+k, gi)). The sharp read-out then estimates P(first-passage " + "to g within a Geom window) = the SAME functional GCIQL's sparse reward " + "+ mask-at-success TD backup learns — not the sit-at-g-at-Geom-time " + "probability of the non-absorbing occupancy.") + ap.add_argument("--action_in_target", action="store_true", + help="model the JOINT p(a_t, target(x_{t+k}) | s_t): cond = s only, " + "y = [a_t, target]. Enables the inpainting policy pi(a|s,g) ~ " + "p(a, x=g | s) (genq_inpaint_jax.py) — improvement by conditioning " + "on reaching the goal, no AWR/critic (issue #57).") + ap.add_argument("--mixed_bits", action="store_true", + help="HYBRID continuous/discrete occupancy (issue #57, owner hypothesis: one " + "Gaussian eps-head over mixed cont+bit target dims must place mass BETWEEN " + "bit configurations). Bit dims (target_extractors.variant_bit_mask) use " + "masked absorbing-state discrete diffusion (D3PM/MDLM class): forward keeps " + "a bit visible w.p. abar_t (diffusion) / t (flow) else MASKs it; the net " + "sees [values(+-1 or 0 when masked), mask flags] and predicts Bernoulli " + "logits, trained with BCE on masked bits. Continuous dims keep the Gaussian " + "eps/velocity path. One trunk, one time schedule; sampling commits bits by " + "categorical draws (never by rounding a Gaussian).") + ap.add_argument("--bit_loss_weight", type=float, default=1.0, + help="weight of the masked-bit BCE term vs the continuous MSE (--mixed_bits)") + ap.add_argument("--actor_pkl", default=None, + help="OFFLINE OCCUPANCY ITERATION (issue #57 v2, pure-GenQ co-adaptation): " + "pickle of a trained PI agent (run_gciql_ablate --save_agent). Each " + "training tuple's future is weighted by how well its dataset actions " + "agree with this actor: w_pi = exp(-pi_alpha * mean_i ||a_i - " + "mu(s_i,g)||^2 / 2) over the first pi_horizon future steps, " + "self-normalized per batch — the occupancy shifts toward the IMPROVED " + "policy's futures (policy iteration without rollouts or TD).") + ap.add_argument("--pi_alpha", type=float, default=1.0, + help="temperature of the actor-agreement future weighting (--actor_pkl)") + ap.add_argument("--pi_horizon", type=int, default=25, + help="future steps scored by the actor-agreement weighting (--actor_pkl)") + ap.add_argument("--stitch_relabel", type=float, default=0.0, + help="COMPOSE-IN-DATA stitching (issue #57, owner idea: recursion x " + "iterated re-fitting): with this probability a tuple's goal/future " + "is a TWO-SEGMENT composite of real data — follow the own trajectory " + "K~Geom steps to a junction, RETRIEVE an eps-close state from another " + "trajectory, follow it K' more steps, hindsight-relabel that endpoint " + "as the goal (hit) or an intermediate as the future (miss, rt-style). " + "Both segments are realized data (pure MC); errors average in " + "training instead of compounding at read-out. NO discreteness " + "assumption: junctions match within an eps-grid over the normalized " + "target space (--stitch_eps); exact-config matching (puzzle bits) is " + "the special case where identical values share a cell.") + ap.add_argument("--stitch_eps", type=float, default=0.5, + help="junction tolerance for --stitch_relabel, as the per-dim grid width " + "in UNITS OF THAT DIM'S STD over the target space. Two states are " + "junction-compatible iff they share an eps-grid cell (per-dim gap " + "< eps*std). The composite path then has an eps-bounded discontinuity " + "at the junction; bias -> 0 as eps -> 0 at the cost of stitch rate.") + ap.add_argument("--rt_eta", type=float, default=0.0, + help="REWARD-TARGETED stratified sampling (issue #57, owner idea): for " + "in-trajectory goals under --absorb_goal, force the first-passage HIT " + "event (y = g) with probability eta and the MISS event otherwise, " + "importance-weighting the loss by the exact truncated-Geom event " + "probabilities (hit w = p_hit/eta, miss w = (1-p_hit)/(1-eta), " + "p_hit = (g^d - g^L)/(1 - g^L)). The conditional occupancy stays " + "unbiased; reward-bearing futures get dense gradient signal.") + ap.add_argument("--goal_mix", default="hindsight", choices=["hindsight", "ref"], + help="conditioning-goal distribution for occupancy training. 'hindsight' " + "(legacy): uniform within-trajectory downstream goals only. 'ref': mirror " + "the OGBench GCDataset VALUE-goal mix the PI critic is queried with — " + "20%% current state, 50%% within-traj GEOMETRIC future (Geom(1-gamma), " + "offsets>=1, clamped at traj end), 30%% RANDOM cross-trajectory states " + "(issue #57 owner audit: the occupancy was never trained on the random " + "goals that make up ~30%% of GCIQL's critic queries — OOD conditioning " + "exactly where stitching-relevant value is read).") + ap.add_argument("--out", default=None, help="output .genqjax.npz path (default: checkpoints/m9_genq_.genqjax.npz)") + args = ap.parse_args() + + # path order: this genq dir first (local helpers), then OGBench impls (utils.*). + sys.path.insert(0, os.path.dirname(__file__)) + sys.path.insert(0, args.ogbench_impls) + + import jax + import jax.numpy as jnp + import optax + from utils.env_utils import make_env_and_datasets + from target_extractors import env_safe_name + import target_extractors + + LOCO_FULL = ("antmaze", "humanoidmaze", "antsoccer") + safe = env_safe_name(args.env) + occ_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + ckpt_dir = os.path.join(occ_dir, "checkpoints") + os.makedirs(ckpt_dir, exist_ok=True) + out = args.out or os.path.join(ckpt_dir, f"m9_genq_{safe}.genqjax.npz") + + print(f"[train_genq_jax] env={args.env} devices={jax.devices()}", flush=True) + # frame_stack matches GCIQL's config default (None) — we only need raw transitions. + env, train_dataset, _val = make_env_and_datasets(args.env, frame_stack=None) + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1.0, 1.0) + end_of = build_ends(train_dataset["terminals"]) + N = len(obs) + + is_maze = (not args.env.startswith(LOCO_FULL)) and ("maze" in args.env) + s = obs[:, :2].astype(np.float32) if is_maze else obs # Gen-Q conditioning state + s_dim = s.shape[1] + a_dim = act.shape[1] + + # ---- target space: raw extractor target, or frozen reward-aware latent ---- + if args.latent_npz: + from train_latent_encoder_jax import load_encoder, encode_np + enc_params, enc_meta = load_encoder(args.latent_npz) + # encoder input: the raw target slice, or the FULL obs for a --full_obs encoder. + enc_in = (lambda o: np.asarray(o, dtype=np.float32)) if enc_meta["full_obs"] else \ + (lambda o: target_extractors.extract_target(args.env, o).astype(np.float32)) + target_full = encode_np(enc_params, enc_meta, enc_in(obs)) # [N, z_dim] + goal_in_target = lambda gf_obs: encode_np(enc_params, enc_meta, enc_in(gf_obs)) + target_kind = (f"latent-z{target_full.shape[1]} full_obs={enc_meta['full_obs']} " + f"({os.path.basename(args.latent_npz)})") + elif args.target_variant != "default": + tv = args.target_variant + target_full = target_extractors.extract_target_variant(args.env, obs, tv).astype(np.float32) + goal_in_target = lambda gf_obs: target_extractors.extract_target_variant( + args.env, gf_obs, tv).astype(np.float32) + target_kind = f"variant={tv} target_dim={target_full.shape[1]}" + else: + target_full = target_extractors.extract_target(args.env, obs).astype(np.float32) + goal_in_target = lambda gf_obs: target_extractors.extract_target(args.env, gf_obs).astype(np.float32) + target_kind = f"raw target_dim={target_full.shape[1]}" + y_dim = target_full.shape[1] + if args.state_target: + # state == target so the recursive composition can feed samples back in-graph. + assert not args.latent_npz, "--state_target is not supported together with --latent_npz" + s = target_full + s_dim = y_dim + target_kind += " [state_target]" + if args.action_in_target: + # Joint (first-action, future-target) generative model for the inpainting policy: + # y = [a_t, target(x_{t+k})], cond = s_t only (no action, no goal in cond). + assert not args.state_target and not args.latent_npz + y_dim = a_dim + y_dim + cond_dim = s_dim + else: + cond_dim = s_dim + a_dim + y_dim + print(f"[train_genq_jax] s_dim={s_dim} a_dim={a_dim} y_dim={y_dim} cond_dim={cond_dim} " + f"target={target_kind} action_in_target={args.action_in_target}", flush=True) + + # ---- hybrid continuous/discrete target split (--mixed_bits) ---- + bit_mask = None + n_bits = 0 + if args.mixed_bits: + assert not args.latent_npz, "--mixed_bits operates on raw target bits, not a latent" + assert not args.action_in_target, "--mixed_bits + --action_in_target not supported" + if args.target_variant in (None, "", "default"): + assert args.env.startswith("puzzle"), ( + "--mixed_bits with the default target assumes an all-bit target (puzzle envs)") + bit_mask = np.asarray( + target_extractors.variant_bit_mask(args.env, args.target_variant), dtype=bool) + assert bit_mask.shape[0] == y_dim and bit_mask.any() + n_bits = int(bit_mask.sum()) + print(f"[train_genq_jax] MIXED-BITS: {n_bits} masked-diffusion bit dims + " + f"{y_dim - n_bits} Gaussian dims (bit_loss_weight={args.bit_loss_weight})", flush=True) + + rng_np = np.random.default_rng(args.seed) + + # ---- junction retrieval index for --stitch_relabel (eps-grid over target space) ---- + # No discreteness assumption: cells are an eps-grid on the per-dim-normalized target. + # Identical discrete values (puzzle bits, exactly 0/1) always share a cell, so exact + # config matching falls out as the special case; continuous targets get eps-close + # junctions. Singleton cells degenerate to a self-junction = an ordinary own-trajectory + # composite, so no fallback path is needed. + stitch_inv = None + if args.stitch_relabel > 0: + assert args.absorb_goal, "--stitch_relabel builds on the absorbing-occupancy semantics" + _w_st = args.stitch_eps * (target_full.std(0) + 1e-6) + _cells = np.floor(target_full / _w_st).astype(np.int64) + _, stitch_inv = np.unique(_cells, axis=0, return_inverse=True) + stitch_order = np.argsort(stitch_inv, kind="stable") + stitch_bounds = np.searchsorted(stitch_inv[stitch_order], + np.arange(stitch_inv.max() + 2)) + _sizes = np.diff(stitch_bounds) + print(f"[train_genq_jax] STITCH-RELABEL p={args.stitch_relabel} eps={args.stitch_eps}: " + f"{len(_sizes)} junction cells, " + f"{(_sizes[stitch_inv] >= 2).mean():.1%} of rows stitchable", flush=True) + + def stitch_tuple(t): + """Two-segment composite: own traj t --d1--> j1 (junction, Geom-biased short), + RETRIEVE an eps-close j1r from another trajectory (same eps-grid cell), goal := + a state j2 downstream of j1r. The composite path (t..j1, j1r..end) is then treated + exactly like ONE trajectory under the --absorb_goal + --rt_eta semantics: + stratified hit/miss with truncated-Geom IS weights over the COMPOSITE distance + D = d1 + d2 (so the first segment's discount is paid), and miss futures land on + segment 1 or segment 2 according to the same single truncated-Geom draw.""" + B = len(t) + j1 = future_idx(t, end_of, args.gamma, rng_np) + # eps-grid retrieval: uniform member of j1's junction cell, preferring a row + # other than j1 itself when the cell has one (singleton -> self-junction). + lo, hi = stitch_bounds[stitch_inv[j1]], stitch_bounds[stitch_inv[j1] + 1] + idx = lo + (rng_np.random(B) * (hi - lo)).astype(np.int64) + j1r = stitch_order[np.minimum(idx, hi - 1)] + clash = (j1r == j1) & (hi - lo >= 2) + idx2 = lo + ((idx - lo + 1) % np.maximum(hi - lo, 1)) + j1r = np.where(clash, stitch_order[idx2], j1r) + j2 = future_idx(j1r, end_of, args.gamma, rng_np) + gi = j2 + d1 = j1 - t + D = (d1 + (j2 - j1r)).astype(np.float64) # composite distance to goal + Ltot = (d1 + (end_of[j1r] - j1r)).astype(np.float64) # composite path length + g_, eta = args.gamma, max(args.rt_eta, 0.5) + gL = np.power(g_, Ltot) + p_hit = (np.power(g_, D) - gL) / (1.0 - gL) + take_hit = (rng_np.random(B) < eta) | (D == 0) + # miss branch: K | K < D over the composite path (front-truncated Geom) + u = rng_np.random(B) + pD = 1.0 - np.power(g_, np.maximum(D, 1.0)) + k_miss = np.ceil(np.log1p(-u * pD) / math.log(g_)).astype(np.int64) - 1 + k_miss = np.clip(k_miss, 0, np.maximum(D.astype(np.int64) - 1, 0)) + j_miss = np.where(k_miss < d1, t + k_miss, j1r + (k_miss - d1)) + j = np.where(take_hit, j2, j_miss) + w = np.ones(B) + w = np.where(take_hit & (D > 0), p_hit / eta, w) + w = np.where(~take_hit, (1.0 - p_hit) / (1.0 - eta), w) + return j, gi, w.astype(np.float32) + + # ---- v2: actor-agreement future weighting (offline occupancy iteration) ---- + actor_mu_fn = None + if args.actor_pkl: + import pickle + import jax as _jax + import jax.numpy as _jnp + from utils.networks import GCActor + with open(args.actor_pkl, "rb") as f: + _saved = pickle.load(f) + _acfg = _saved["config"] + _actor_def = GCActor(hidden_dims=tuple(_acfg["actor_hidden_dims"]), action_dim=a_dim, + state_dependent_std=False, const_std=_acfg["const_std"]) + _aparams = {"params": _saved["params"]["modules_actor"]} + + @_jax.jit + def _mu(obs_b, goal_b): + dist = _actor_def.apply(_aparams, obs_b, goal_b) + return _jnp.clip(dist.mode(), -1, 1) + + actor_mu_fn = lambda o, g: np.asarray(_mu(_jnp.asarray(o), _jnp.asarray(g))) + print(f"[train_genq_jax] OCCUPANCY ITERATION: futures weighted by actor agreement " + f"({os.path.basename(args.actor_pkl)}, alpha={args.pi_alpha}, " + f"horizon={args.pi_horizon})", flush=True) + + def pi_future_weight(t, j, gi): + """w_pi[b] = exp(-alpha * mean_i ||a_i - mu(s_i, g)||^2 / 2), i in (t, min(j, t+H)], + self-normalized per batch. Tuples whose realized future actions agree with the + improved policy get upweighted; conditional occupancy shifts toward d^pi.""" + B = len(t) + H = args.pi_horizon + offs = np.arange(1, H + 1) + idx = np.minimum(t[:, None] + offs[None, :], j[:, None]) # [B, H] + valid = (t[:, None] + offs[None, :]) <= j[:, None] + flat = idx.reshape(-1) + g_obs = np.repeat(obs[gi], H, axis=0) + mu = actor_mu_fn(obs[flat], g_obs) # [B*H, a_dim] + mse = ((act[flat] - mu) ** 2).sum(-1).reshape(B, H) + denom = np.maximum(valid.sum(-1), 1) + m_mse = (mse * valid).sum(-1) / denom + m_mse = np.where(valid.any(-1), m_mse, 0.0) # j == t: neutral + w = np.exp(-args.pi_alpha * m_mse / 2.0) + return (w / max(w.mean(), 1e-8)).astype(np.float32) + + def sample_tuple(t): + """Return (j, gi): future index and hindsight goal index for query index t. + + Default: j = t + Geom, gi downstream of j (non-absorbing occupancy). + --absorb_goal: gi downstream of t FIRST, then j = min(t + Geom, gi) — the + future absorbs at the goal, so P(x = g) = P(first-passage <= Geom window). + --goal_mix ref: gi follows the GCDataset VALUE-goal mix (cur/traj-geom/random) + instead of uniform-downstream, so the occupancy is TRAINED on the same goal + distribution the PI critic QUERIES it with. Absorbing clamp applies only to + within-trajectory goals (a cross-trajectory goal index has no order relation + to t; those futures simply never absorb — the honest behavior answer). + """ + if args.goal_mix == "ref": + B = len(t) + # 50/30/20 traj-geom / random / current, matching GCDataset.sample_goals + # (value_p_curgoal=0.2, value_p_trajgoal=0.5, value_p_randomgoal=0.3, + # value_geom_sample=True: offsets ~ Geom(1-gamma) in [1, inf), clamp at end). + offsets = rng_np.geometric(1.0 - args.gamma, size=B) + gi_traj = np.minimum(t + offsets, end_of[t] - 1) + gi_rand = rng_np.integers(0, N, B) + gi = np.where(rng_np.random(B) < 0.5 / (1.0 - 0.2), gi_traj, gi_rand) + gi = np.where(rng_np.random(B) < 0.2, t, gi) + in_traj = (gi >= t) & (gi < end_of[t]) + if args.absorb_goal and args.rt_eta > 0: + # Stratified hit/miss with exact truncated-Geom importance weights. + # K ~ Geom(1-gamma) truncated to [0, L-1]; hit event = {K >= d} (absorb at g). + g_, eta = args.gamma, args.rt_eta + L = (end_of[t] - t).astype(np.float64) + d = np.clip(gi - t, 0, None).astype(np.float64) + gL = np.power(g_, L) + p_hit = np.where(in_traj, (np.power(g_, d) - gL) / (1.0 - gL), 0.0) + take_hit = in_traj & ((rng_np.random(B) < eta) | (gi == t)) + # miss branch: K | K < d (inverse CDF of the front-truncated Geom) + u = rng_np.random(B) + pd = 1.0 - np.power(g_, np.maximum(d, 1.0)) + k_miss = np.ceil(np.log1p(-u * pd) / math.log(g_)).astype(np.int64) - 1 + k_miss = np.clip(k_miss, 0, np.maximum(gi - t - 1, 0)) + j_plain = future_idx(t, end_of, args.gamma, rng_np) + j = np.where(take_hit, gi, np.where(in_traj, t + k_miss, j_plain)) + w = np.ones(B) + w = np.where(take_hit & (gi != t), p_hit / eta, w) + w = np.where(in_traj & ~take_hit, (1.0 - p_hit) / (1.0 - eta), w) + return j, gi, w.astype(np.float32) + j = future_idx(t, end_of, args.gamma, rng_np) + if args.absorb_goal: + j = np.where(in_traj, np.minimum(j, gi), j) + return j, gi, np.ones(B, np.float32) + if args.absorb_goal: + gi = sample_goal_after(t, end_of, rng_np) + j = np.minimum(future_idx(t, end_of, args.gamma, rng_np), gi) + else: + j = future_idx(t, end_of, args.gamma, rng_np) + gi = sample_goal_after(j, end_of, rng_np) + return j, gi, np.ones(len(t), np.float32) + + def make_cond(t, gi): + """cond = [s_t, a_t, goal_in_target(gi)].""" + if args.action_in_target: + return s[t].astype(np.float32) + g = goal_in_target(obs[gi]) + return np.concatenate([s[t], act[t], g], axis=1).astype(np.float32) + + def make_y(t, j): + if args.action_in_target: + return np.concatenate([act[t], target_full[j]], axis=1).astype(np.float32) + return target_full[j] + + # normalization from a 20k sample (matches train_gc_occ) + t0 = rng_np.integers(0, N, 20000) + j0, gi0, _w0 = sample_tuple(t0) + cond0 = make_cond(t0, gi0) + y0 = make_y(t0, j0) + cond_mean = cond0.mean(0); cond_std = cond0.std(0) + 1e-6 + y_mean = y0.mean(0); y_std = y0.std(0) + 1e-6 + if args.mixed_bits: + # bit dims live on the categorical path: keep them un-normalized (raw 0/1 in the + # data; the model input/output uses signed +-1 with 0 = MASK). + y_mean[bit_mask] = 0.0 + y_std[bit_mask] = 1.0 + abar = cosine_abar(args.diffusion_T) + abar_prev = np.concatenate([np.ones(1, np.float32), abar[:-1]]) + + # ---- model + optimizer ---- + model = make_model(cond_dim, y_dim, args.hidden_dim, args.num_layers, args.time_dim) + key = jax.random.PRNGKey(args.seed) + key, ik = jax.random.split(key) + # mixed_bits: x input = [y_dim values ; n_bits mask flags]; output stays y_dim + # (eps/velocity at continuous positions, Bernoulli logits at bit positions). + dummy_x = jnp.zeros((1, y_dim + n_bits)); dummy_t = jnp.zeros((1,)); dummy_c = jnp.zeros((1, cond_dim)) + params = model.init(ik, dummy_x, dummy_t, dummy_c) + n_p = sum(int(np.prod(p.shape)) for p in jax.tree_util.tree_leaves(params)) + print(f"[train_genq_jax] params={n_p/1e3:.1f}k", flush=True) + + tx = optax.chain(optax.clip_by_global_norm(10.0), + optax.adamw(args.lr, weight_decay=args.weight_decay)) + opt_state = tx.init(params) + + abar_j = jnp.asarray(abar) + cond_mean_j, cond_std_j = jnp.asarray(cond_mean), jnp.asarray(cond_std) + y_mean_j, y_std_j = jnp.asarray(y_mean), jnp.asarray(y_std) + T = args.diffusion_T + + if args.mixed_bits: + bit_idx_j = jnp.asarray(np.where(bit_mask)[0]) + cont_idx_j = jnp.asarray(np.where(~bit_mask)[0]) + n_cont = int((~bit_mask).sum()) + + def loss_fn(params, c_raw, y_raw, t_int, noise, m, w): + c = (c_raw - cond_mean_j) / cond_std_j + x0 = (y_raw - y_mean_j) / y_std_j + tf = t_int.astype(jnp.float32) / T # t in (0,1] + if args.model == "flow": + # CFM linear path: x_t = (1-t) z + t x1, z~N(0,I); target velocity v = x1 - z. + xt = (1.0 - tf[:, None]) * noise + tf[:, None] * x0 + target = x0 - noise + else: + ab = abar_j[t_int - 1][:, None] + xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1.0 - ab) * noise + target = noise + if not args.mixed_bits: + pred = model.apply(params, xt, tf, c) + return jnp.mean(w[:, None] * (pred - target) ** 2) + # HYBRID: bit positions carry the clean signed bit (+-1) when visible, 0 when MASKed + # (m=1); mask flags ride along as extra input channels. Loss = Gaussian eps/velocity + # MSE on continuous dims + BCE on the MASKED bits (MDLM-style simplified weighting — + # uniform over masked positions; ELBO weight omitted for optimization robustness). + b01 = y_raw[:, bit_idx_j] + xt = xt.at[:, bit_idx_j].set((2.0 * b01 - 1.0) * (1.0 - m)) + pred = model.apply(params, jnp.concatenate([xt, m], axis=-1), tf, c) + bce = optax.sigmoid_binary_cross_entropy(pred[:, bit_idx_j], b01) + loss_bits = (w[:, None] * bce * m).sum() / jnp.maximum(m.sum(), 1.0) + if n_cont == 0: + return args.bit_loss_weight * loss_bits + loss_cont = jnp.mean(w[:, None] * (pred[:, cont_idx_j] - target[:, cont_idx_j]) ** 2) + return loss_cont + args.bit_loss_weight * loss_bits + + @jax.jit + def update(params, opt_state, c_raw, y_raw, t_int, noise, m, w): + loss, grads = jax.value_and_grad(loss_fn)(params, c_raw, y_raw, t_int, noise, m, w) + updates, opt_state = tx.update(grads, opt_state, params) + params = optax.apply_updates(params, updates) + return params, opt_state, loss + + # ---- training loop ---- + import tqdm + losses = [] + recent = [] + for step in tqdm.trange(1, args.train_steps + 1, smoothing=0.1, dynamic_ncols=True): + t = rng_np.integers(0, N, args.batch_size) + j, gi, w_is = sample_tuple(t) + if stitch_inv is not None: + st_mask = rng_np.random(args.batch_size) < args.stitch_relabel + if st_mask.any(): + js, gis, ws = stitch_tuple(t[st_mask]) + j[st_mask] = js; gi[st_mask] = gis; w_is[st_mask] = ws + if actor_mu_fn is not None: + w_is = w_is * pi_future_weight(t, j, gi) + c_raw = make_cond(t, gi) + y_raw = make_y(t, j) + t_int = rng_np.integers(1, T + 1, args.batch_size).astype(np.int32) + noise = rng_np.standard_normal((args.batch_size, y_dim)).astype(np.float32) + if args.mixed_bits: + # bit kept visible w.p. its signal level: kappa_t = t/T (flow) or abar_t (diffusion) + keep = (t_int.astype(np.float64) / T) if args.model == "flow" else abar[t_int - 1] + m_np = (rng_np.random((args.batch_size, n_bits)) >= keep[:, None]).astype(np.float32) + else: + m_np = np.zeros((args.batch_size, 0), dtype=np.float32) + key, _ = jax.random.split(key) # keep determinism advancing (noise is numpy here) + params, opt_state, loss = update(params, opt_state, + jnp.asarray(c_raw), jnp.asarray(y_raw), + jnp.asarray(t_int), jnp.asarray(noise), + jnp.asarray(m_np), jnp.asarray(w_is)) + recent.append(float(loss)) + if len(recent) > 200: + recent.pop(0) + if step % 2000 == 0 or step == 1: + lv = float(np.mean(recent)) + losses.append((step, lv)) + print(f"[train_genq_jax:{safe}] step {step} loss(running) {lv:.4f}", flush=True) + + # ---- export weights to the torch-compatible .genqjax.npz schema ---- + arrs, n_layers_saved = flax_params_to_npz_arrays(params) + arrs.update(dict(abar=abar, abar_prev=abar_prev, + cond_mean=cond_mean.astype(np.float32), cond_std=cond_std.astype(np.float32), + y_mean=y_mean.astype(np.float32), y_std=y_std.astype(np.float32))) + meta = dict(meta_cond_dim=np.asarray(cond_dim), meta_y_dim=np.asarray(y_dim), + meta_num_layers=np.asarray(n_layers_saved), meta_diffusion_T=np.asarray(T), + meta_sample_steps=np.asarray(args.sample_steps), + meta_action_in_target=np.asarray(int(args.action_in_target)), + meta_a_dim=np.asarray(a_dim), + meta_model_flow=np.asarray(int(args.model == "flow"))) + if args.mixed_bits: + arrs["bit_mask"] = bit_mask.astype(np.float32) + meta["meta_mixed_bits"] = np.asarray(1) + np.savez(out, **arrs, **meta) + print(f"[train_genq_jax] saved {out} (final loss {losses[-1][1]:.4f}, {n_layers_saved} trunk layers)", + flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/train_latent_encoder_jax.py b/gen_q_rsm/ogbench_genq/genq/train_latent_encoder_jax.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa9fc100607575553b03a24d641a6e5e41d113b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_latent_encoder_jax.py @@ -0,0 +1,257 @@ +"""Reward-aware JAX latent encoder for Cube/Puzzle Gen-Q (PR #23 task 2). + +Closes the gap between GenQ-GCIQL (cube 23.2%) and GCIQL reference (cube 68%) by training Gen-Q's +occupancy in a learned reward-aware latent z instead of the raw target slice. CLAUDE.md §M3: train + + z = E_psi(target_slice), r_hat = R_psi(z, z_goal), freeze E, then learn p_theta(z' | s,a,z_goal). + +Design (goal-reaching preserving): the encoder maps the env's low-dim *target slice* (cube xyz / +9 puzzle bits, via target_extractors) to z in R^{z_dim}. The reward decoder is + + R(z, z_g) = exp(-||z - z_g||^2 / (2 sigma_z^2)), z_g = E_psi(goal_slice), + +and E is trained so this matches the analytical goal-reaching reward in the *raw* target space, + + r(x; g) = exp(-||x - g||^2 / (2 sigma^2)), + +over hindsight (target, goal) pairs sampled from the data — plus an L2 penalty lambda*|z|^2. This +makes z a reward-aware metric embedding: occupancy in z-space + the SAME genq_q "encode-goal, +sample-and-average exp(-||z_x - z_g||^2)" estimator gives Q, with the latent absorbing the awkward +raw-target geometry (cube's anisotropic xyz scaling, puzzle's binary bits) that made the raw-target +dense reward a poor critic signal. + +Because the genq estimator only needs ||z_x - z_g||, the trained occupancy lives in z-space and the +goal is encoded the same way — so train_genq_jax.py with --latent_npz and a downstream +"goal = E(goal_slice)" wiring is all that's required; the genq_q sigma becomes sigma_z. + +Saved npz schema (loaded by load_encoder): + enc_.{weight,bias} (torch-style [out,in]), z_dim, in_dim, n_layers, hidden, sigma_z, + in_mean, in_std (target-slice normalization). +""" +import argparse +import math +import os +import sys + +import numpy as np + + +def _ends(terminals): + term = np.asarray(terminals) + ends = np.where(term > 0)[0] + end_of = np.zeros(len(term), dtype=np.int64) + prev = 0 + for e in ends: + end_of[prev:e + 1] = e + 1 + prev = e + 1 + if prev < len(term): + end_of[prev:] = len(term) + return end_of + + +def _future(t, end_of, gamma, rng): + L = end_of[t] - t + logg = math.log(gamma) + Fmax = np.maximum(1.0 - gamma ** L, 1e-12) + u = rng.random(len(t)) * Fmax + k = np.clip(np.ceil(np.log1p(-u) / logg).astype(np.int64) - 1, 0, L - 1) + return t + k + + +def _goal_after(j, end_of, rng): + e = end_of[j] + span = np.maximum(e - j, 1) + return np.clip(j + (rng.random(len(j)) * span).astype(np.int64), 0, e - 1) + + +def make_encoder(in_dim, z_dim, hidden, n_layers): + import flax.linen as fnn + + class Enc(fnn.Module): + @fnn.compact + def __call__(self, x): + h = x + for i in range(n_layers): + h = fnn.relu(fnn.Dense(hidden, name=f"enc_{i}")(h)) + return fnn.Dense(z_dim, name=f"enc_{n_layers}")(h) + + return Enc() + + +def load_encoder(npz_path): + """Load encoder weights into a callable param dict + meta (numpy forward, for data prep).""" + d = np.load(npz_path) + meta = dict(z_dim=int(d["z_dim"]), in_dim=int(d["in_dim"]), n_layers=int(d["n_layers"]), + hidden=int(d["hidden"]), sigma_z=float(d["sigma_z"]), + in_mean=d["in_mean"].astype(np.float32), in_std=d["in_std"].astype(np.float32), + full_obs=bool(int(d["full_obs"])) if "full_obs" in d.files else False) + W = {k: d[k] for k in d.files if k.startswith("enc_")} + return W, meta + + +def encode_np(W, meta, target_slice): + """Numpy forward of the frozen encoder: target_slice [N, in_dim] -> z [N, z_dim]. + + NOTE: target_slice here is the RAW env target (target_extractors.extract_target output), NOT the + full obs. The caller normalizes via in_mean/in_std internally. + """ + x = (np.asarray(target_slice, dtype=np.float32) - meta["in_mean"]) / meta["in_std"] + nl = meta["n_layers"] + for i in range(nl): + x = x @ W[f"enc_{i}.weight"].T + W[f"enc_{i}.bias"] + x = np.maximum(x, 0.0) # relu + x = x @ W[f"enc_{nl}.weight"].T + W[f"enc_{nl}.bias"] + return x.astype(np.float32) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--env", required=True) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=30000) + ap.add_argument("--batch_size", type=int, default=512) + ap.add_argument("--lr", type=float, default=1e-3) + ap.add_argument("--z_dim", type=int, default=4) + ap.add_argument("--hidden", type=int, default=256) + ap.add_argument("--n_layers", type=int, default=2) + ap.add_argument("--sigma_z", type=float, default=1.0, help="reward bandwidth in z-space") + ap.add_argument("--lam", type=float, default=1e-4, help="L2 penalty on |z|^2") + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--sigma", type=float, default=0.5, help="raw-target dense-reward bandwidth (analytical target)") + ap.add_argument("--full_obs", action="store_true", + help="encode the FULL observation instead of the target slice (issue #57). The " + "reward target still comes from the task slice, so pair this with " + "--dyn_weight>0 or z provably collapses onto the slice.") + ap.add_argument("--dyn_weight", type=float, default=0.0, + help="weight of the forward-dynamics auxiliary ||D(z_t,a_t)-sg(E(x_{t+1}))||^2 — " + "keeps action-responsive (controllable) dims in z.") + ap.add_argument("--ogbench_impls", + default=os.environ.get("OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls"))) + ap.add_argument("--out", default=None) + args = ap.parse_args() + + sys.path.insert(0, os.path.dirname(__file__)) + sys.path.insert(0, args.ogbench_impls) + + import jax + import jax.numpy as jnp + import optax + from utils.env_utils import make_env_and_datasets + from target_extractors import env_safe_name + import target_extractors + + safe = env_safe_name(args.env) + occ_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + ckpt_dir = os.path.join(occ_dir, "checkpoints") + os.makedirs(ckpt_dir, exist_ok=True) + out = args.out or os.path.join(ckpt_dir, f"m3_latent_jax_{safe}.npz") + + print(f"[latent_jax] env={args.env} devices={jax.devices()}", flush=True) + _env, train_dataset, _val = make_env_and_datasets(args.env, frame_stack=None) + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1) + end_of = _ends(train_dataset["terminals"]) + N = len(obs) + tgt = target_extractors.extract_target(args.env, obs).astype(np.float32) # task slice (reward) + X = obs if args.full_obs else tgt # encoder input + in_dim = X.shape[1] + a_dim = act.shape[1] + sigma = float(args.sigma) + rng = np.random.default_rng(args.seed) + + in_mean = X.mean(0); in_std = X.std(0) + 1e-6 + enc = make_encoder(in_dim, args.z_dim, args.hidden, args.n_layers) + key = jax.random.PRNGKey(args.seed) + key, ik = jax.random.split(key) + params = enc.init(ik, jnp.zeros((1, in_dim))) + n_p = sum(int(np.prod(p.shape)) for p in jax.tree_util.tree_leaves(params)) + print(f"[latent_jax] in_dim={in_dim} z_dim={args.z_dim} params={n_p/1e3:.1f}k", flush=True) + + # forward-dynamics auxiliary head (trained jointly, discarded at export) + import flax.linen as fnn + + class Dyn(fnn.Module): + @fnn.compact + def __call__(self, z, a): + h = jnp.concatenate([z, a], -1) + h = fnn.relu(fnn.Dense(args.hidden)(h)) + h = fnn.relu(fnn.Dense(args.hidden)(h)) + return fnn.Dense(args.z_dim)(h) + + dyn = Dyn() + key, dk = jax.random.split(key) + dyn_params = dyn.init(dk, jnp.zeros((1, args.z_dim)), jnp.zeros((1, a_dim))) + all_params = {"enc": params, "dyn": dyn_params} + + tx = optax.adam(args.lr) + opt_state = tx.init(all_params) + in_mean_j, in_std_j = jnp.asarray(in_mean), jnp.asarray(in_std) + sz2 = 2.0 * args.sigma_z ** 2 + + def enc_fwd(params, x_raw): + return enc.apply(params, (x_raw - in_mean_j) / in_std_j) + + def loss_fn(ap_, x_raw, g_raw, r_true, s_raw, a_b, sn_raw): + zx = enc_fwd(ap_["enc"], x_raw) + zg = enc_fwd(ap_["enc"], g_raw) + d2 = jnp.sum((zx - zg) ** 2, axis=-1) + r_hat = jnp.exp(-d2 / sz2) + rec = jnp.mean((r_hat - r_true) ** 2) + reg = args.lam * (jnp.mean(jnp.sum(zx ** 2, -1)) + jnp.mean(jnp.sum(zg ** 2, -1))) + loss = rec + reg + if args.dyn_weight > 0: + zs = enc_fwd(ap_["enc"], s_raw) + zn = jax.lax.stop_gradient(enc_fwd(ap_["enc"], sn_raw)) + dl = jnp.mean(jnp.sum((dyn.apply(ap_["dyn"], zs, a_b) - zn) ** 2, -1)) + loss = loss + args.dyn_weight * dl + return loss, rec + + @jax.jit + def update(ap_, opt_state, x_raw, g_raw, r_true, s_raw, a_b, sn_raw): + (loss, rec), grads = jax.value_and_grad(loss_fn, has_aux=True)( + ap_, x_raw, g_raw, r_true, s_raw, a_b, sn_raw) + updates, opt_state = tx.update(grads, opt_state, ap_) + ap_ = optax.apply_updates(ap_, updates) + return ap_, opt_state, loss, rec + + import tqdm + recent = [] + for step in tqdm.trange(1, args.train_steps + 1, smoothing=0.1, dynamic_ncols=True): + # sample (x, goal g) pairs: x at index j (geometric future of some t), g downstream of j. + # r_true ALWAYS comes from the task slice (tgt) — the reward reads bits only. + t = rng.integers(0, N, args.batch_size) + j = _future(t, end_of, args.gamma, rng) + gi = _goal_after(j, end_of, rng) + x_raw = X[j]; g_raw = X[gi] + d = np.linalg.norm(tgt[j] - tgt[gi], axis=1) + r_true = np.exp(-(d ** 2) / (2 * sigma ** 2)).astype(np.float32) + # dynamics pairs: consecutive steps within a trajectory + td = rng.integers(0, N - 1, args.batch_size) + td = np.where(end_of[td] > td + 1, td, np.maximum(td - 1, 0)) + params_ = update(all_params, opt_state, jnp.asarray(x_raw), jnp.asarray(g_raw), + jnp.asarray(r_true), jnp.asarray(X[td]), jnp.asarray(act[td]), + jnp.asarray(X[td + 1])) + all_params, opt_state, loss, rec = params_ + recent.append(float(rec)) + if len(recent) > 200: + recent.pop(0) + if step % 2000 == 0 or step == 1: + print(f"[latent_jax:{safe}] step {step} recon_mse(running) {np.mean(recent):.5f}", flush=True) + + # export (encoder only; the dynamics head is a training-time auxiliary) + ep = all_params["enc"] + p = ep["params"] if "params" in ep else ep + arrs = {} + for i in range(args.n_layers + 1): + arrs[f"enc_{i}.weight"] = np.asarray(p[f"enc_{i}"]["kernel"]).T.astype(np.float32) + arrs[f"enc_{i}.bias"] = np.asarray(p[f"enc_{i}"]["bias"]).astype(np.float32) + np.savez(out, z_dim=np.asarray(args.z_dim), in_dim=np.asarray(in_dim), + n_layers=np.asarray(args.n_layers), hidden=np.asarray(args.hidden), + sigma_z=np.asarray(args.sigma_z), in_mean=in_mean.astype(np.float32), + in_std=in_std.astype(np.float32), full_obs=np.asarray(int(args.full_obs)), + **arrs) + print(f"[latent_jax] saved {out} final recon_mse {np.mean(recent):.5f}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/train_latent_variants_jax.py b/gen_q_rsm/ogbench_genq/genq/train_latent_variants_jax.py new file mode 100644 index 0000000000000000000000000000000000000000..f360687ae2c9f2a7764b9f402c40a895ad8cd643 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_latent_variants_jax.py @@ -0,0 +1,770 @@ +"""Multi-objective image-latent trainer for the RSM pixel path (visual antmaze). + +The RSM pixel path learns the occupancy in a LATENT space z = E(pixels), then +predicts future z' from (z, a). The open question (owner, 2026-07-17): *what +signal should train E?* This module makes that an experiment by composing three +objectives, each optionally applied to the CURRENT and/or FUTURE embedding: + + reward R(z, z_g) = exp(-||z - z_g||^2 / 2 sigma_z^2) matches the true + goal-reaching reward r(x;g). Makes z a reward-metric embedding. + Applied at the FUTURE embedding (z_x vs z_g, the classic Gen-Q + read-out) and/or the CURRENT embedding (z_s vs z_g). + recon D(E(x)) ~ x pixel reconstruction. Forces z to retain enough to + render the scene -> occupancy predictions are grounded, not + collapsed. Applied to the CURRENT state x_t and/or the FUTURE + state x_{t+k}. + consistency a latent predictor F(z_t, a_t) ~ stopgrad(E(x_{t+1})) — a + self-predictive (BYOL-style) signal that makes z one the + occupancy can actually predict one step ahead. Collapse guard: + only meaningful when paired with reward or recon (which anchor z + to observable content); a stop-grad target is used regardless. + +Each term has a weight (--w_reward/--w_recon/--w_consistency) and a +which-embedding flag (--reward_on/--recon_on in {current,future,both}). Setting a +weight to 0 drops that head. Standard variants (race these): + reward-only : --w_reward 1 --w_recon 0 --w_consistency 0 + recon-only : --w_reward 0 --w_recon 1 --w_consistency 0 + combined : --w_reward 1 --w_recon 1 (recon+reward; the + owner's headline hypothesis) + +consistency : add --w_consistency 0.5 + +The reward ground-truth coordinate + sigma come from +train_pixel_encoder_jax.reward_target_fn(env) (maze -> ant xy, sigma 5.0). The +export schema is a SUPERSET of the pixel-encoder schema (same conv_/fc_ keys + +meta) so load_pixel_encoder and the whole precompute -> RSM -> eval path consume +it UNCHANGED — only the training signal differs. A --variant tag is saved for +provenance and used in the default output filename. + +Proxy quality metrics (printed at eval, and saved) so variants can be ranked +BEFORE a full RSM run (owner directive: cheap proxy first, then SR on the top): + spearman(z-dist, true-xy-dist) — is the latent metric reward-aligned? + linear xy-decodability R^2 — how much position info is linearly in z? + 1-step latent predictability — held-out MSE of a tiny fitted F(z,a)->z' + (normalized by z variance); low = the + occupancy has an easy target. + +Usage (GPU node): + python ogbench_genq/genq/train_latent_variants_jax.py \ + --env visual-antmaze-medium-navigate-v0 --variant combined \ + --w_reward 1 --w_recon 1 --train_steps 100000 +""" +import argparse +import math +import os + +import numpy as np + +# reward geometry (ant xy / cube xyz) + hindsight-pair samplers are shared with +# the single-objective trainer so the reward target is identical across variants. +import sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from train_pixel_encoder_jax import (reward_target_fn, _ends, _future, # noqa: E402 + _goal_after, make_pixel_encoder) + + +def make_decoder(img_hw, in_ch, channels, hidden): + """Mirror of make_pixel_encoder: z -> Dense -> reshape -> transpose-convs -> pixels. + Output is in the normalized (x/255 - 0.5) space; loss compares to normalized x.""" + import flax.linen as fnn + + # spatial size after the encoder's stride-2 convs: img_hw / 2^n_conv + n = len(channels) + base_hw = img_hw // (2 ** n) + + class Dec(fnn.Module): + @fnn.compact + def __call__(self, z): + top = channels[-1] + h = fnn.relu(fnn.Dense(hidden, name="dfc_0")(z)) + h = fnn.relu(fnn.Dense(base_hw * base_hw * top, name="dfc_1")(h)) + h = h.reshape((h.shape[0], base_hw, base_hw, top)) + for i, ch in enumerate(reversed(channels[:-1])): + h = fnn.relu(fnn.ConvTranspose(ch, (3, 3), strides=(2, 2), + name=f"dconv_{i}")(h)) + # final transpose-conv back to in_ch at full resolution + h = fnn.ConvTranspose(in_ch, (3, 3), strides=(2, 2), name="dconv_out")(h) + return h + + return Dec() + + +def make_predictor(z_dim, a_dim, hidden): + """F(z_t, a_t) -> z_{t+1} : a small MLP latent forward model (consistency).""" + import flax.linen as fnn + + class Pred(fnn.Module): + @fnn.compact + def __call__(self, z, a): + h = jnp_cat(z, a) + h = fnn.relu(fnn.Dense(hidden, name="p0")(h)) + h = fnn.relu(fnn.Dense(hidden, name="p1")(h)) + return fnn.Dense(z_dim, name="p2")(h) + + return Pred() + + +def make_gcls(z_dim, hidden, features="concat"): + """Binary GOAL-REACHING classifier R_psi([z_s, z_g]) -> logit P(s reaches g). + A learned MLP head (Form B): shapes the encoder via BCE on true (state, + downstream-goal) pairs vs random pairs, more flexibly than the distance metric. + Reusable later as a learned RSM read-out.""" + import flax.linen as fnn + import jax.numpy as jnp + + class GCls(fnn.Module): + @fnn.compact + def __call__(self, zs, zg): + if features == "symmetric": + # An at-goal predicate should not depend on pair order. Difference + # and product features expose matching dimensions without making a + # shallow head rediscover them from raw concatenation. + h = jnp.concatenate([zs, zg, jnp.abs(zs - zg), zs * zg], -1) + else: + h = jnp_cat(zs, zg) + h = fnn.relu(fnn.Dense(hidden, name="g0")(h)) + h = fnn.relu(fnn.Dense(hidden, name="g1")(h)) + return fnn.Dense(1, name="g2")(h)[:, 0] + + return GCls() + + +def jnp_cat(z, a): + import jax.numpy as jnp + return jnp.concatenate([z, a], -1) + + +def _sample_gciql_goals(rng, t, lo, hi, end_of, p_curgoal, p_trajgoal, + discount): + """Pure NumPy implementation of GCIQL goal relabeling and return targets.""" + n = len(t) + final = end_of[t] - 1 + offsets = rng.geometric(1.0 - discount, size=n) + traj = np.minimum(t + offsets, final) + random_goal = rng.integers(lo, hi, n) + u = rng.random(n) + is_cur = u < p_curgoal + is_traj = (u >= p_curgoal) & (u < p_curgoal + p_trajgoal) + goal = np.where(is_cur, t, np.where(is_traj, traj, random_goal)) + value = np.where( + is_cur, + 1.0, + np.where(is_traj, discount ** np.maximum(traj - t, 0), 0.0), + ).astype(np.float32) + # Match GCDataset's exact index reward in the rare cases where a + # terminal-clipped trajectory or random draw equals the current index. + exact = goal == t + value = np.where(exact, 1.0, value).astype(np.float32) + kind = np.where(is_cur, 0, np.where(is_traj, 1, 2)).astype(np.int8) + return goal.astype(np.int64), value, exact.astype(np.float32), kind + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--env", default="visual-antmaze-medium-navigate-v0") + ap.add_argument("--variant", default="combined", + help="provenance tag (also the default output filename)") + ap.add_argument("--data", default=None) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=100000) + ap.add_argument("--batch_size", type=int, default=256) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--z_dim", type=int, default=8) + ap.add_argument("--hidden", type=int, default=256) + ap.add_argument("--channels", default="32,64,128,256") + ap.add_argument("--sigma_z", type=float, default=1.0) + ap.add_argument("--lam", type=float, default=1e-4, help="L2 penalty on |z|^2") + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--sigma", type=float, default=None, help="raw-space reward bw (env default)") + # objective weights + ap.add_argument("--w_reward", type=float, default=1.0) + ap.add_argument("--w_recon", type=float, default=1.0) + ap.add_argument("--w_consistency", type=float, default=0.0) + # DYNAMICS-FREE coordinate-free heads (no forward-dynamics = no WM machinery): + ap.add_argument("--w_tempcon", type=float, default=0.0, + help="temporal-contrastive: a state's own geometric-horizon " + "future is its nearest neighbour over the batch, in the " + "SAME euclidean metric the RSM read-out uses. Aligns " + "||z-z'|| with reachability. No coordinate, no action, " + "no prediction.") + ap.add_argument("--tempcon_tau", type=float, default=1.0, + help="temperature (sq-dist scale) for the temporal-contrastive InfoNCE") + ap.add_argument("--w_stepsto", type=float, default=0.0, + help="steps-to-go REGRESSION head: ||z_s - z_x|| ~ (steps-to-future). " + "On EXPERT data pushes the encoder onto the cube (directed) and " + "aligns the read-out metric. Coordinate-free, dynamics-free.") + ap.add_argument("--stepsto_scale", type=float, default=0.02, + help="scale mapping step-count to target latent distance") + ap.add_argument("--value_reward", action="store_true", + help="reward head target = COORDINATE-FREE hindsight value " + "gamma_v^(steps-to-goal), replacing the cube-kernel target. " + "Fair: uses only trajectory structure, no cube coordinate.") + ap.add_argument("--value_gamma", type=float, default=0.98, + help="discount for the coordinate-free value-reward target") + ap.add_argument("--w_goalcls", type=float, default=0.0, + help="GOAL-REACHING classifier head (jointly with recon): InfoNCE " + "matching anchor state z_s to its OWN long-horizon downstream " + "goal z_g vs other trajectories' goals. Fair analog of GCIQL " + "letting the coordinate-free reward shape the encoder (no TD). " + "Long horizon + cross-traj negatives force the CUBE (not arm) " + "into z, and InfoNCE spreads the latent (fixes occupancy " + "collapse). Coordinate-free, dynamics-free.") + ap.add_argument("--goalcls_tau", type=float, default=1.0, + help="temperature (sq-dist scale) for the goal-reaching InfoNCE") + ap.add_argument("--w_goalcls_bin", type=float, default=0.0, + help="Form B: BINARY goal-reaching classifier (learned MLP head " + "R_psi([z_s,z_g])->P(reaches)), BCE on true (state,downstream-goal) " + "pairs vs random goals. Shapes the encoder via a flexible MLP " + "(not the metric). Coordinate-free, dynamics-free.") + ap.add_argument("--goalcls_target", default="reach", + choices=["reach", "index", "gciql"], + help="binary/InfoNCE goal target. reach preserves the original " + "random downstream positive. index uses a near-in-time " + "positive and far/cross-episode negatives. gciql uses the " + "official current/trajectory/random relabel mixture and " + "trains a soft discounted goal-return predictor.") + ap.add_argument("--goalcls_index_delta", type=int, default=8, + help="maximum forward frame gap for an index positive") + ap.add_argument("--goalcls_neg_gap", type=int, default=64, + help="minimum same-episode frame gap for an index negative") + ap.add_argument("--goalcls_cross_neg_frac", type=float, default=0.5, + help="fraction of index negatives sampled from another episode; " + "the remainder are hard far-in-time same-episode negatives") + ap.add_argument("--gciql_p_curgoal", type=float, default=0.2) + ap.add_argument("--gciql_p_trajgoal", type=float, default=0.5) + ap.add_argument("--gciql_p_randomgoal", type=float, default=0.3) + ap.add_argument("--gciql_discount", type=float, default=0.99, + help="official GCIQL discount and geometric future sampler; " + "trajectory soft target is discount**steps_to_goal") + ap.add_argument("--p_aug", type=float, default=0.0, + help="batch probability of the official shared random crop " + "(padding=3); visual GCIQL uses 0.5") + ap.add_argument("--goalcls_features", default="concat", + choices=["concat", "symmetric"], + help="pair features for the binary goal head") + ap.add_argument("--goalcls_after", type=int, default=0, + help="reconstruction-only warmup steps before goal supervision") + ap.add_argument("--goalcls_ramp", type=int, default=0, + help="linear ramp steps after --goalcls_after") + ap.add_argument("--w_smooth", type=float, default=0.0, + help="SLOW-FEATURE head: penalize latent velocity " + "||E(x_{t+dt}) - E(x_t)||^2. The cube is a slow, rigid, " + "low-frequency signal; the arm is fast/jerky. Suppressing " + "fast latent variance (with recon retaining info) exposes " + "the SLOW cube -> the euclidean metric becomes " + "cube-dominant, which the diagnosis (arm->cube R2=0.90 but " + "recon spearman 0.47: metric follows the 19-D arm not the " + "3-D cube) says is exactly what's missing. Fair: time-order " + "only, no coordinate, no action, no dynamics model.") + ap.add_argument("--smooth_dt", type=int, default=1, + help="frame gap for the slow-feature velocity penalty (default 1)") + ap.add_argument("--reward_on", default="both", choices=["current", "future", "both"]) + ap.add_argument("--recon_on", default="both", choices=["current", "future", "both"]) + ap.add_argument("--max_frames", type=int, default=0) + ap.add_argument("--val_episodes", type=int, default=20) + ap.add_argument("--val_pairs", type=int, default=8192) + ap.add_argument("--eval_every", type=int, default=5000) + ap.add_argument("--out", default=None) + args = ap.parse_args() + assert 0.0 <= args.goalcls_cross_neg_frac <= 1.0 + assert args.goalcls_neg_gap > args.goalcls_index_delta + assert np.isclose( + args.gciql_p_curgoal + args.gciql_p_trajgoal + args.gciql_p_randomgoal, 1.0) + assert 0.0 < args.gciql_discount < 1.0 + assert 0.0 <= args.p_aug <= 1.0 + assert args.goalcls_target != "gciql" or ( + args.w_goalcls_bin > 0 and args.w_goalcls == 0) + + import jax + import jax.numpy as jnp + import optax + import tqdm + + repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + safe = args.env.replace("-", "_") + out = args.out or os.path.join(repo_root, "ckpt", + f"pixel_enc_{safe}_{args.variant}.npz") + os.makedirs(os.path.dirname(out), exist_ok=True) + channels = tuple(int(c) for c in args.channels.split(",")) + data = args.data or os.path.expanduser(f"~/.ogbench/data/{args.env}.npz") + target_fn, sigma_default = reward_target_fn(args.env) + sigma = float(args.sigma if args.sigma is not None else sigma_default) + + d = np.load(os.path.expanduser(data)) + terminals = np.asarray(d["terminals"]) + qpos = np.asarray(d["qpos"]) + actions = np.clip(np.asarray(d["actions"], np.float32), -1, 1) + N = len(terminals) if not args.max_frames else min(args.max_frames, len(terminals)) + pix = np.asarray(d["observations"][:N]) + assert pix.dtype == np.uint8 and pix.ndim == 4, pix.shape + img_hw, in_ch = int(pix.shape[1]), int(pix.shape[3]) + a_dim = actions.shape[1] + tgt = target_fn(qpos[:N]) + end_of = _ends(terminals[:N]) + print(f"[latvar:{args.variant}] env={args.env} frames={N} img={img_hw}x{in_ch} " + f"z_dim={args.z_dim} w=(r{args.w_reward},rec{args.w_recon}," + f"c{args.w_consistency}) devices={jax.devices()}", flush=True) + + # train/val split at an episode boundary + ends_here = np.where(terminals[:N] > 0)[0] + n_val_ep = min(args.val_episodes, max(len(ends_here) - 1, 1)) + split = int(ends_here[-n_val_ep - 1]) + 1 if n_val_ep < len(ends_here) else N + rng = np.random.default_rng(args.seed) + + enc = make_pixel_encoder(args.z_dim, channels, args.hidden) + dec = make_decoder(img_hw, in_ch, channels, args.hidden) if args.w_recon > 0 else None + pred = make_predictor(args.z_dim, a_dim, args.hidden) if args.w_consistency > 0 else None + gcls = (make_gcls(args.z_dim, args.hidden, args.goalcls_features) + if args.w_goalcls_bin > 0 else None) + + key = jax.random.PRNGKey(args.seed) + key, ke = jax.random.split(key) + params = {"enc": enc.init(ke, jnp.zeros((1, img_hw, img_hw, in_ch)))} + if dec is not None: + key, kd = jax.random.split(key) + params["dec"] = dec.init(kd, jnp.zeros((1, args.z_dim))) + if pred is not None: + key, kp = jax.random.split(key) + params["pred"] = pred.init(kp, jnp.zeros((1, args.z_dim)), jnp.zeros((1, a_dim))) + if gcls is not None: + key, kg = jax.random.split(key) + params["gcls"] = gcls.init(kg, jnp.zeros((1, args.z_dim)), jnp.zeros((1, args.z_dim))) + n_p = sum(int(np.prod(p.shape)) for p in jax.tree_util.tree_leaves(params)) + print(f"[latvar] params={n_p/1e6:.2f}M (enc" + f"{'+dec' if dec is not None else ''}{'+pred' if pred is not None else ''}" + f"{'+gcls' if gcls is not None else ''})", + flush=True) + + tx = optax.adam(args.lr) + opt_state = tx.init(params) + sz2 = 2.0 * args.sigma_z ** 2 + + def enc_z(p, xu8): + return enc.apply(p["enc"], xu8.astype(jnp.float32) / 255.0 - 0.5) + + def norm_pix(xu8): + return xu8.astype(jnp.float32) / 255.0 - 0.5 + + def maybe_augment(key_, *images): + """Official GCIQL shared random crop for pixel state/goal batches.""" + if args.p_aug <= 0: + return images + k_apply, k_crop = jax.random.split(key_) + batch = images[0].shape[0] + offsets_xy = jax.random.randint(k_crop, (batch, 2), 0, 7) + crop_froms = jnp.concatenate( + [offsets_xy, jnp.zeros((batch, 1), dtype=offsets_xy.dtype)], axis=1) + + def crop_one(image, crop_from): + padded = jnp.pad(image, ((3, 3), (3, 3), (0, 0)), mode="edge") + return jax.lax.dynamic_slice(padded, crop_from, image.shape) + + def crop_batch(x): + return jax.vmap(crop_one)(x, crop_froms) + + apply_crop = jax.random.bernoulli(k_apply, args.p_aug) + return tuple(jnp.where(apply_crop, crop_batch(x), x) for x in images) + + def loss_fn(p, s_u8, x_u8, g_u8, sn_u8, gc_u8, gn_u8, + goal_value, a_b, r_fut, r_cur, gap, goal_mult): + # embeddings + z_s = enc_z(p, s_u8) # current state + z_x = enc_z(p, x_u8) # future state (geometric horizon) + z_g = enc_z(p, g_u8) # reward/trajectory goal + z_gc = (enc_z(p, gc_u8) + if args.w_goalcls > 0 or args.w_goalcls_bin > 0 else z_g) + terms = {} + loss = args.lam * (jnp.mean(jnp.sum(z_x ** 2, -1))) + + if args.w_reward > 0: + rl = 0.0 + if args.reward_on in ("future", "both"): + rhat = jnp.exp(-jnp.sum((z_x - z_g) ** 2, -1) / sz2) + rl = rl + jnp.mean((rhat - r_fut) ** 2) + if args.reward_on in ("current", "both"): + rhat_c = jnp.exp(-jnp.sum((z_s - z_g) ** 2, -1) / sz2) + rl = rl + jnp.mean((rhat_c - r_cur) ** 2) + terms["reward"] = rl + loss = loss + args.w_reward * rl + + if args.w_recon > 0 and dec is not None: + rc = 0.0 + if args.recon_on in ("current", "both"): + rc = rc + jnp.mean((dec.apply(p["dec"], z_s) - norm_pix(s_u8)) ** 2) + if args.recon_on in ("future", "both"): + rc = rc + jnp.mean((dec.apply(p["dec"], z_x) - norm_pix(x_u8)) ** 2) + terms["recon"] = rc + loss = loss + args.w_recon * rc + + if args.w_consistency > 0 and pred is not None: + zn = jax.lax.stop_gradient(enc_z(p, sn_u8)) # next-step target (stop-grad) + zhat = pred.apply(p["pred"], z_s, a_b) + cl = jnp.mean(jnp.sum((zhat - zn) ** 2, -1)) + terms["consistency"] = cl + loss = loss + args.w_consistency * cl + + if args.w_tempcon > 0: + # SHORT-horizon identity contrastive (DYNAMICS-FREE, coordinate-free): + # the positive for anchor z_s is a SHORT-horizon future z_d (sn_u8 = + # t+delta, delta~[3,12]) — over a few steps the ARM moves but the CUBE + # barely does, so "same-state" is dominated by the cube. InfoNCE with + # NEGATIVE squared-euclidean logits aligns the SAME euclidean metric + # the RSM read-out uses (exp(-||z-z_g||^2/..)) to cube-IDENTITY (not + # reachability — the geometric-horizon positive FAILED: cube moves too + # far, spearman 0.47->0.14). No action, no next-state prediction (WM + # machinery), no coordinate. + z_d = enc_z(p, sn_u8) + d2 = jnp.sum((z_s[:, None, :] - z_d[None, :, :]) ** 2, -1) # (B,B) + logits = -d2 / args.tempcon_tau + labels = jnp.arange(z_s.shape[0]) + tcl = optax.softmax_cross_entropy_with_integer_labels(logits, labels).mean() + tcl = tcl + optax.softmax_cross_entropy_with_integer_labels( + logits.T, labels).mean() + terms["tempcon"] = tcl + loss = loss + args.w_tempcon * tcl + + if args.w_smooth > 0: + # SLOW-FEATURE: penalize latent velocity over dt frames (sn_u8 = t+dt). + # Suppresses the FAST arm variance; recon (w_recon>0) retains info and + # prevents collapse; the surviving VARIABLE-and-slow factor is the cube, + # so ||z-z'|| becomes cube-dominant. Coordinate-free, dynamics-free. + z_sp = enc_z(p, sn_u8) + sml = jnp.mean(jnp.sum((z_s - z_sp) ** 2, -1)) + terms["smooth"] = sml + loss = loss + args.w_smooth * sml + + if args.w_goalcls > 0: + # GOAL-REACHING CLASSIFIER (jointly with recon) -- the fair analog of GCIQL + # letting the (coordinate-free) reward shape the encoder, but via a classifier + # instead of TD. Anchor z_s (state at t) must identify its OWN long-horizon + # downstream goal z_g (=gi, several steps ahead) among the batch's goals, via + # InfoNCE on negative squared-euclidean logits (the metric the read-out uses). + # Why this dodges the value_reward/tempcon arm-shortcut: + # * LONG horizon: the arm at t decorrelates from the arm at the far goal, so + # the arm can't solve the classification; the persistent/directed factor + # (the cube) is what predicts the goal. + # * CROSS-trajectory negatives (other batch goals) differ mainly in cube + # position, so the encoder MUST represent the cube to separate them. + # InfoNCE also SPREADS the latent (pushes non-matching goals apart) -> fixes + # the slow-feature collapse that flattened the occupancy read-out. + dg2 = jnp.sum((z_s[:, None, :] - z_gc[None, :, :]) ** 2, -1) # (B,B) + glog = -dg2 / args.goalcls_tau + glbl = jnp.arange(z_s.shape[0]) + gcl = optax.softmax_cross_entropy_with_integer_labels(glog, glbl).mean() + gcl = gcl + optax.softmax_cross_entropy_with_integer_labels(glog.T, glbl).mean() + terms["goalcls"] = gcl + terms["goal_mult"] = goal_mult + loss = loss + goal_mult * args.w_goalcls * gcl + + if args.w_goalcls_bin > 0: + # Form B: BINARY goal-reaching classifier (learned MLP head) trained jointly + # with recon. Positive = (z_s, its true downstream goal z_g) -> 1; negative = + # (z_s, a random other goal z_g[roll]) -> 0. The classifier gradient flows into + # the encoder, forcing z to carry whatever distinguishes reachable from random + # goals -- the cube (cross-traj negatives differ by cube; the far goal + # decorrelates the arm). GCIQL's reward-shaping via a classifier, no TD, no + # coordinate. A flexible MLP (not the metric) so it can extract the cube even + # if the euclidean geometry doesn't align. + pos = gcls.apply(p["gcls"], z_s, z_gc) # (B,) + if args.goalcls_target == "gciql": + # Supervised Monte-Carlo analogue of what GCIQL propagates from + # its sparse index reward: 1 for current goals, gamma**gap for + # geometrically sampled same-trajectory goals, and 0 for random + # goals. This uses indices/relabel type only, never coordinates. + bce = -(goal_value * jax.nn.log_sigmoid(pos) + + (1.0 - goal_value) * jax.nn.log_sigmoid(-pos)).mean() + else: + zg_neg = enc_z(p, gn_u8) + neg = gcls.apply(p["gcls"], z_s, zg_neg) + bce = -(jax.nn.log_sigmoid(pos) + + jax.nn.log_sigmoid(-neg)).mean() + terms["goalcls_bin"] = bce + terms["goal_mult"] = goal_mult + loss = loss + goal_mult * args.w_goalcls_bin * bce + + if args.w_stepsto > 0: + # Steps-to-go REGRESSION (fair, coordinate-free, dynamics-free): make the + # euclidean gap ||z_s - z_x|| track the number of steps k=j-t to the future. + # On EXPERT data the arm is temporally quiet and the cube advances ~monotonically, + # so this PUSHES THE ENCODER to represent the CUBE (the directed component) in a + # read-out-aligned metric. Uses only k (trajectory structure) -- no coordinate, + # no next-state prediction (that would be WM machinery). + dd = jnp.sqrt(jnp.sum((z_s - z_x) ** 2, -1) + 1e-6) + sl = jnp.mean((dd - args.stepsto_scale * gap) ** 2) + terms["stepsto"] = sl + loss = loss + args.w_stepsto * sl + + return loss, terms + + @jax.jit + def update(p, opt_state, s_u8, x_u8, g_u8, sn_u8, gc_u8, gn_u8, + goal_value, a_b, r_fut, r_cur, gap, goal_mult, aug_key): + s_u8, x_u8, g_u8, sn_u8, gc_u8, gn_u8 = maybe_augment( + aug_key, s_u8, x_u8, g_u8, sn_u8, gc_u8, gn_u8) + (loss, terms), grads = jax.value_and_grad(loss_fn, has_aux=True)( + p, s_u8, x_u8, g_u8, sn_u8, gc_u8, gn_u8, + goal_value, a_b, r_fut, r_cur, gap, goal_mult) + updates, opt_state = tx.update(grads, opt_state, p) + return optax.apply_updates(p, updates), opt_state, loss, terms + + # Episode starts complement _ends' exclusive end index. They are used only + # to form coordinate-free temporal labels for goal-prediction negatives. + start_of = np.empty(N, dtype=np.int64) + ep_starts = np.concatenate([ + np.asarray([0], np.int64), + np.where(terminals[:N] > 0)[0].astype(np.int64) + 1, + ]) + ep_starts = ep_starts[ep_starts < N] + for ei, es in enumerate(ep_starts): + ee = ep_starts[ei + 1] if ei + 1 < len(ep_starts) else N + start_of[es:ee] = es + + def sample_index_negatives(rng_, t, lo, hi): + """Mix hard far-in-episode and cross-episode negatives without coordinates.""" + out_idx = np.empty_like(t) + ngap = max(int(args.goalcls_neg_gap), args.goalcls_index_delta + 1) + for bi, ti in enumerate(t.tolist()): + es, ee = int(start_of[ti]), int(end_of[ti]) # ee is exclusive + left_n = max(ti - ngap - es + 1, 0) + right_lo = ti + ngap + right_n = max(ee - right_lo, 0) + use_cross = (rng_.random() < args.goalcls_cross_neg_frac + or left_n + right_n == 0) + if not use_cross: + u = int(rng_.integers(0, left_n + right_n)) + out_idx[bi] = es + u if u < left_n else right_lo + (u - left_n) + continue + # The train/validation split is an episode boundary, so keeping the + # draw in [lo, hi) also keeps validation labels held out. + cand = int(rng_.integers(lo, hi)) + for _ in range(32): + if start_of[cand] != es: + break + cand = int(rng_.integers(lo, hi)) + if start_of[cand] == es and left_n + right_n: + u = int(rng_.integers(0, left_n + right_n)) + cand = es + u if u < left_n else right_lo + (u - left_n) + out_idx[bi] = cand + return out_idx + + def sample_gciql_goals(rng_, t, lo, hi): + """Official GCIQL value-goal relabel mix plus a soft return target. + + Current / trajectory / random probabilities default to 0.2 / 0.5 / 0.3. + Trajectory goals use the official geometric sampler with p=1-discount. + The supervised target is the normalized return induced by the sparse + index reward along the known trajectory: discount**gap. Random goals + receive zero because no same-trajectory witness is available. + """ + goal, value, exact, _ = _sample_gciql_goals( + rng_, t, lo, hi, end_of, + args.gciql_p_curgoal, args.gciql_p_trajgoal, + args.gciql_discount) + return goal, value, exact + + def sample_batch(rng_, n, lo, hi): + t = rng_.integers(lo, hi, n) # current state s_t + j = _future(t, end_of, args.gamma, rng_) # future x_{t+k} + gi = _goal_after(j, end_of, rng_) # goal downstream of j + if args.goalcls_target == "index": + gc = np.minimum( + t + rng_.integers(0, args.goalcls_index_delta + 1, n), + end_of[t] - 1) + gn = sample_index_negatives(rng_, t, lo, hi) + goal_value = np.ones(n, np.float32) + goal_exact = (gc == t).astype(np.float32) + elif args.goalcls_target == "gciql": + gc, goal_value, goal_exact = sample_gciql_goals(rng_, t, lo, hi) + # Kept only to preserve the common update signature; the GCIQL + # soft-target branch consumes one relabeled pair rather than a + # separately constructed binary negative. + gn = rng_.integers(lo, hi, n) + else: + gc = gi + # Preserve the original cross-row negative construction. + gn = np.roll(gi, 1) + goal_value = np.ones(n, np.float32) + goal_exact = np.zeros(n, np.float32) + # sn slot = SHORT-horizon future (delta~[3,12]) within the same episode: + # the tempcon identity positive (arm moves, cube ~constant). (When the + # dropped consistency head is off this is a pure relabel of that slot.) + if args.w_smooth > 0: + # slow-feature velocity slot: the immediate (t+dt) frame within-episode + tn = np.minimum(t + args.smooth_dt, end_of[t] - 1) + else: + tn = np.minimum(t + rng_.integers(3, 13, n), end_of[t] - 1) + if args.w_reward <= 0: + # Keep privileged coordinates completely outside the training batch + # whenever the reward objective is disabled. `tgt` remains available + # only to proxy_metrics(), which is a diagnostic after the update. + r_fut = np.zeros(n, np.float32) + r_cur = np.zeros(n, np.float32) + elif args.value_reward: + # COORDINATE-FREE reward target: the hindsight temporal value + # gamma_v^(steps-to-reach-goal). Dense, uses ONLY trajectory index + # structure (no cube coordinate). The reward head exp(-||z-z_g||^2/2sz^2) + # then learns to track steps-to-goal -> a cube-aware latent (this is the + # fair analog of the combined encoder's cube-kernel reward; the mechanism + # GCIQL's value proved works on these pixels). + r_fut = (args.value_gamma ** np.maximum(gi - j, 0)).astype(np.float32) + r_cur = (args.value_gamma ** np.maximum(gi - t, 0)).astype(np.float32) + else: + d_fut = np.linalg.norm(tgt[j] - tgt[gi], axis=1) + d_cur = np.linalg.norm(tgt[t] - tgt[gi], axis=1) + r_fut = np.exp(-(d_fut ** 2) / (2 * sigma ** 2)).astype(np.float32) + r_cur = np.exp(-(d_cur ** 2) / (2 * sigma ** 2)).astype(np.float32) + gap = (j - t).astype(np.float32) # steps-to-go regression target + return (pix[t], pix[j], pix[gi], pix[tn], pix[gc], pix[gn], + goal_value, goal_exact, actions[t], r_fut, r_cur, gap) + + # ---- proxy metrics (rank variants before a full RSM run) ---- + @jax.jit + def _encode(p, xu8): + return enc_z(p, xu8) + + def proxy_metrics(p): + # encode a val slab + idx = rng.integers(split, N, min(6000, N - split)) if split < N \ + else rng.integers(0, N, 6000) + Z = np.asarray(_encode(p, jnp.asarray(pix[idx]))) + XY = tgt[idx] + # 1) spearman(z-dist, xy-dist) over random pairs + from scipy.stats import spearmanr + a = rng.integers(0, len(idx), 4000) + b = rng.integers(0, len(idx), 4000) + dz = np.linalg.norm(Z[a] - Z[b], axis=1) + dx = np.linalg.norm(XY[a] - XY[b], axis=1) + rho = float(spearmanr(dz, dx).statistic) + # 2) linear xy-decodability R^2 (least squares z -> xy) + Zc = np.concatenate([Z, np.ones((len(Z), 1), np.float32)], 1) + W, *_ = np.linalg.lstsq(Zc, XY, rcond=None) + pred_xy = Zc @ W + ss_res = ((pred_xy - XY) ** 2).sum() + ss_tot = ((XY - XY.mean(0)) ** 2).sum() + r2 = float(1.0 - ss_res / max(ss_tot, 1e-9)) + return rho, r2 + + def goalpred_metrics(p): + """Held-out relabel metrics; cube coordinates enter one named diagnostic only.""" + if gcls is None: + return (float("nan"),) * 5 + nv = min(args.val_pairs, 2048) + lo = split if split < N else 0 + if args.goalcls_target == "gciql": + t_idx = rng.integers(lo, N, nv) + g_idx, goal_value, goal_exact = sample_gciql_goals( + rng, t_idx, lo, N) + s_u8, gc_u8 = pix[t_idx], pix[g_idx] + gn_u8 = None + else: + batch = sample_batch(rng, nv, lo, N) + s_u8, _, _, _, gc_u8, gn_u8, goal_value, goal_exact, *_ = batch + zs = np.asarray(_encode(p, jnp.asarray(s_u8))) + zp = np.asarray(_encode(p, jnp.asarray(gc_u8))) + pos = np.asarray(gcls.apply(p["gcls"], jnp.asarray(zs), jnp.asarray(zp))) + if args.goalcls_target == "gciql": + pred = 1.0 / (1.0 + np.exp(-np.clip(pos, -30.0, 30.0))) + is_pos = goal_exact > 0.5 + is_neg = ~is_pos + acc = float( + 0.5 * ((pos[is_pos] > 0).mean() + (pos[is_neg] < 0).mean())) + auc = float( + (pos[is_pos, None] > pos[None, is_neg]).mean() + + 0.5 * (pos[is_pos, None] == pos[None, is_neg]).mean()) + value_mae = float(np.abs(pred - goal_value).mean()) + from scipy.stats import spearmanr + value_rho = float(spearmanr(pred, goal_value).statistic) + # Privileged diagnostic only: does the index-trained predictor + # generalize from temporal relabels to the actual cube geometry? + cube_prox = -np.linalg.norm(tgt[t_idx] - tgt[g_idx], axis=1) + cube_rho = float(spearmanr(pred, cube_prox).statistic) + return acc, auc, value_mae, value_rho, cube_rho + + zn = np.asarray(_encode(p, jnp.asarray(gn_u8))) + neg = np.asarray(gcls.apply(p["gcls"], jnp.asarray(zs), jnp.asarray(zn))) + acc = float(((pos > 0).mean() + (neg < 0).mean()) / 2.0) + # Pairwise AUC estimate is exact for these matched positive/negative rows. + auc = float((pos[:, None] > neg[None, :]).mean() + + 0.5 * (pos[:, None] == neg[None, :]).mean()) + return acc, auc, float("nan"), float("nan"), float("nan") + + recent = {"loss": []} + train_key = jax.random.PRNGKey(args.seed + 1729) + for step in tqdm.trange(1, args.train_steps + 1, smoothing=0.1, dynamic_ncols=True): + (s_u8, x_u8, g_u8, sn_u8, gc_u8, gn_u8, + goal_value, _, a_b, r_fut, r_cur, gap) = sample_batch( + rng, args.batch_size, 0, split) + if step <= args.goalcls_after: + goal_mult = 0.0 + elif args.goalcls_ramp > 0: + goal_mult = min((step - args.goalcls_after) / args.goalcls_ramp, 1.0) + else: + goal_mult = 1.0 + train_key, aug_key = jax.random.split(train_key) + params, opt_state, loss, terms = update( + params, opt_state, jnp.asarray(s_u8), jnp.asarray(x_u8), jnp.asarray(g_u8), + jnp.asarray(sn_u8), jnp.asarray(gc_u8), jnp.asarray(gn_u8), + jnp.asarray(goal_value), jnp.asarray(a_b), + jnp.asarray(r_fut), jnp.asarray(r_cur), + jnp.asarray(gap), jnp.asarray(goal_mult, jnp.float32), aug_key) + recent["loss"].append(float(loss)) + if len(recent["loss"]) > 200: + recent["loss"].pop(0) + if step % args.eval_every == 0 or step == 1: + rho, r2 = proxy_metrics(params) + gp_acc, gp_auc, gv_mae, gv_rho, gv_cube_rho = goalpred_metrics(params) + tstr = " ".join(f"{k}={float(v):.4f}" for k, v in terms.items()) + print(f"[latvar:{args.variant}] step {step} loss={np.mean(recent['loss']):.5f} " + f"{tstr} | PROXY spearman={rho:.4f} xy_R2={r2:.4f} " + f"goalpred_acc={gp_acc:.4f} goalpred_auc={gp_auc:.4f} " + f"goalvalue_mae={gv_mae:.4f} goalvalue_rho={gv_rho:.4f} " + f"goalvalue_cube_rho={gv_cube_rho:.4f}", + flush=True) + + # ---- export in the SAME schema as train_pixel_encoder_jax (enc only) ---- + ep = params["enc"]["params"] if "params" in params["enc"] else params["enc"] + arrs = {} + for i in range(len(channels)): + arrs[f"conv_{i}.kernel"] = np.asarray(ep[f"conv_{i}"]["kernel"]).astype(np.float32) + arrs[f"conv_{i}.bias"] = np.asarray(ep[f"conv_{i}"]["bias"]).astype(np.float32) + for i in range(2): + arrs[f"fc_{i}.weight"] = np.asarray(ep[f"fc_{i}"]["kernel"]).T.astype(np.float32) + arrs[f"fc_{i}.bias"] = np.asarray(ep[f"fc_{i}"]["bias"]).astype(np.float32) + rho, r2 = proxy_metrics(params) + gp_acc, gp_auc, gv_mae, gv_rho, gv_cube_rho = goalpred_metrics(params) + np.savez(out, z_dim=np.asarray(args.z_dim), hidden=np.asarray(args.hidden), + channels=np.asarray(channels), img_hw=np.asarray(img_hw), in_ch=np.asarray(in_ch), + sigma_z=np.asarray(args.sigma_z), sigma=np.asarray(sigma), + gamma=np.asarray(args.gamma), + variant=np.asarray(args.variant), proxy_spearman=np.asarray(rho), + proxy_xy_r2=np.asarray(r2), + w_recon=np.asarray(args.w_recon), + w_goalcls=np.asarray(args.w_goalcls), + w_goalcls_bin=np.asarray(args.w_goalcls_bin), + goalcls_target=np.asarray(args.goalcls_target), + goalcls_features=np.asarray(args.goalcls_features), + goalcls_index_delta=np.asarray(args.goalcls_index_delta), + goalcls_neg_gap=np.asarray(args.goalcls_neg_gap), + goalcls_cross_neg_frac=np.asarray(args.goalcls_cross_neg_frac), + goalcls_after=np.asarray(args.goalcls_after), + goalcls_ramp=np.asarray(args.goalcls_ramp), + gciql_p_curgoal=np.asarray(args.gciql_p_curgoal), + gciql_p_trajgoal=np.asarray(args.gciql_p_trajgoal), + gciql_p_randomgoal=np.asarray(args.gciql_p_randomgoal), + gciql_discount=np.asarray(args.gciql_discount), + p_aug=np.asarray(args.p_aug), + cube_coordinate_training=np.asarray( + bool(args.w_reward > 0 and not args.value_reward)), + goalpred_val_acc=np.asarray(gp_acc), + goalpred_val_auc=np.asarray(gp_auc), + goalvalue_val_mae=np.asarray(gv_mae), + goalvalue_val_spearman=np.asarray(gv_rho), + goalvalue_cube_spearman=np.asarray(gv_cube_rho), **arrs) + print(f"[latvar:{args.variant}] saved {out} FINAL proxy spearman={rho:.4f} " + f"xy_R2={r2:.4f} goalpred_acc={gp_acc:.4f} " + f"goalpred_auc={gp_auc:.4f} goalvalue_mae={gv_mae:.4f} " + f"goalvalue_rho={gv_rho:.4f} goalvalue_cube_rho={gv_cube_rho:.4f}", + flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/train_pixel_encoder_jax.py b/gen_q_rsm/ogbench_genq/genq/train_pixel_encoder_jax.py new file mode 100644 index 0000000000000000000000000000000000000000..8b0aff52c5106ce80c5456aa9ab736348c9616fb --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_pixel_encoder_jax.py @@ -0,0 +1,360 @@ +"""Reward-predictive pixel encoder for OGBench visual manipulation (issue #65 Track C, stage 1). + +Pixel-path counterpart of train_latent_encoder_jax.py, per the CLAUDE.md hard requirement +for image observations: train an encoder E and reward decoder R so z = E(x) retains +reward-relevant information, FREEZE both, then learn the occupancy in z-space. + + z = E_psi(pixels), r_hat = R_psi(z, z_g) = exp(-||z - z_g||^2 / (2 sigma_z^2)), + +trained so r_hat matches the analytical goal-reaching reward in the RAW target space + + r(x; g) = exp(-||cube_xyz_scaled(x) - cube_xyz_scaled(g)||^2 / (2 sigma^2)), + +over hindsight (future, goal) pairs sampled exactly like the low-dim trainer +(geometric-horizon future j of a uniform t, goal g uniformly downstream of j), plus the +L2 penalty lambda * |z|^2. Ground-truth cube xyz comes from the qpos tail of the released +visual npz — qpos[:, -7:-4] is the cube freejoint position (verified layout, same slice +convert_ogbench_npz_to_h5.py uses for privileged/block_0_pos) — scaled the OGBench +manipspace way, (raw - [0.425, 0, 0]) * 10, to match the state-based target_extractors +frame; sigma = 0.5 matches SIGMA_BY_ENV for cube. + +Encoder: 4 stride-2 3x3 conv layers (64 -> 32 -> 16 -> 8 -> 4 spatial, channels +32/64/128/256), flatten, Dense(hidden) + relu, Dense(z_dim). Input is uint8 pixels +normalized as x/255 - 0.5 (the normalization is part of the export contract below). + +Deviation from the low-dim trainer: no --full_obs (input is always full pixels) and no +forward-dynamics auxiliary head (--dyn_weight). Collapse-onto-the-reward-slice is +acceptable here BY DESIGN: the RSM pixel path carries proprio/arm information through a +separate proprio19 channel (see precompute_pixel_latents.py), so z only has to be a +reward-metric embedding of the cube configuration. + +Saved npz schema (loaded by load_pixel_encoder): + conv_.kernel (3, 3, C_in, C_out) float32 flax HWIO conv kernels, i = 0..n_conv-1 + conv_.bias (C_out,) float32 + fc_0.weight (hidden, flat) float32 torch-style [out, in] + fc_0.bias (hidden,) float32 + fc_1.weight (z_dim, hidden) float32 + fc_1.bias (z_dim,) float32 + z_dim, hidden, channels (n_conv,), img_hw, in_ch, sigma_z, sigma, gamma (meta) +Input contract: uint8 [B, img_hw, img_hw, in_ch], normalized internally as /255 - 0.5. + +Usage (full run belongs on a GPU node; CPU smoke works with --h5_pixels + --max_frames): + python ogbench_genq/genq/train_pixel_encoder_jax.py \ + --data ~/.ogbench/data/visual-cube-single-play-v0.npz \ + --out ckpt/pixel_enc_cube_single_visual.npz +""" +import argparse +import math +import os + +import numpy as np + +# OGBench manipspace cube-position scaling: obs stores (raw_xyz - CUBE_XYZ_OFFSET) * 10. +CUBE_XYZ_OFFSET = np.array([0.425, 0.0, 0.0], dtype=np.float32) +CUBE_XYZ_SCALE = 10.0 + + +def scaled_cube_xyz(qpos): + """qpos [N, 21] -> cube xyz in the state-based extractor's (scaled) frame [N, 3].""" + raw = np.asarray(qpos)[:, -7:-4].astype(np.float32) # freejoint tail: pos(3) + quat(4) + return (raw - CUBE_XYZ_OFFSET) * CUBE_XYZ_SCALE + + +def antmaze_xy(qpos): + """qpos [N, >=2] -> ant root xy [N, 2]. The maze reward reads ONLY the ant's + global x,y (qpos[:, :2]) — the SAME coordinate the state-based extractor uses + (target_extractors._maze_xy = obs[:, :2]) and at the SAME (unscaled) scale, so + the latent's reward metric matches the maze geometry (SIGMA_BY_ENV = 5.0).""" + return np.asarray(qpos)[:, :2].astype(np.float32) + + +# The reward-relevant ground-truth coordinate per env family. Pixels are the +# observation; this is what the encoder's reward decoder must be able to predict. +def reward_target_fn(env_id): + """Return (fn: qpos -> [N, d], sigma) for the env's reward geometry.""" + if "maze" in env_id: # antmaze / pointmaze / humanoidmaze + return antmaze_xy, 5.0 # xy, maze dense-reward bandwidth + if "cube" in env_id: + return scaled_cube_xyz, 0.5 # scaled cube xyz, manip bandwidth + raise ValueError(f"no pixel reward-target geometry registered for {env_id}") + + +# ---- hindsight pair sampling (identical to train_latent_encoder_jax.py) ---- + +def _ends(terminals): + term = np.asarray(terminals) + ends = np.where(term > 0)[0] + end_of = np.zeros(len(term), dtype=np.int64) + prev = 0 + for e in ends: + end_of[prev:e + 1] = e + 1 + prev = e + 1 + if prev < len(term): + end_of[prev:] = len(term) + return end_of + + +def _future(t, end_of, gamma, rng): + L = end_of[t] - t + logg = math.log(gamma) + Fmax = np.maximum(1.0 - gamma ** L, 1e-12) + u = rng.random(len(t)) * Fmax + k = np.clip(np.ceil(np.log1p(-u) / logg).astype(np.int64) - 1, 0, L - 1) + return t + k + + +def _goal_after(j, end_of, rng): + e = end_of[j] + span = np.maximum(e - j, 1) + return np.clip(j + (rng.random(len(j)) * span).astype(np.int64), 0, e - 1) + + +# ---- model ---- + +def make_pixel_encoder(z_dim, channels, hidden, return_hidden=False): + import flax.linen as fnn + + class PixelEnc(fnn.Module): + @fnn.compact + def __call__(self, x): # x float32 [B, H, W, C], already /255 - 0.5 + h = x + for i, ch in enumerate(channels): + h = fnn.relu(fnn.Conv(ch, (3, 3), strides=(2, 2), name=f"conv_{i}")(h)) + h = h.reshape((h.shape[0], -1)) + h = fnn.relu(fnn.Dense(hidden, name="fc_0")(h)) + z = fnn.Dense(z_dim, name="fc_1")(h) + return (z, h) if return_hidden else z + + return PixelEnc() + + +def load_pixel_encoder(npz_path, return_hidden=False): + """Load a frozen pixel encoder -> (encode_fn, meta). + + encode_fn(frames) maps uint8 pixels [B, H, W, C] -> z [B, z_dim] (np.float32); + it jit-compiles on first call and handles the /255 - 0.5 normalization itself. + meta carries z_dim/sigma_z/... (see module docstring schema). + """ + import jax + import jax.numpy as jnp + + d = np.load(npz_path, allow_pickle=True) + channels = tuple(int(c) for c in d["channels"]) + meta = dict(z_dim=int(d["z_dim"]), hidden=int(d["hidden"]), channels=channels, + img_hw=int(d["img_hw"]), in_ch=int(d["in_ch"]), + sigma_z=float(d["sigma_z"]), sigma=float(d["sigma"]), + gamma=float(d["gamma"])) + enc = make_pixel_encoder( + meta["z_dim"], channels, meta["hidden"], + return_hidden=return_hidden) + p = {} + for i in range(len(channels)): + p[f"conv_{i}"] = {"kernel": jnp.asarray(d[f"conv_{i}.kernel"]), + "bias": jnp.asarray(d[f"conv_{i}.bias"])} + for i in range(2): + p[f"fc_{i}"] = {"kernel": jnp.asarray(d[f"fc_{i}.weight"].T), + "bias": jnp.asarray(d[f"fc_{i}.bias"])} + params = {"params": p} + + @jax.jit + def _fwd(xu8): + x = xu8.astype(jnp.float32) / 255.0 - 0.5 + return enc.apply(params, x) + + def encode_fn(frames): + out = _fwd(jnp.asarray(frames, dtype=jnp.uint8)) + if return_hidden: + return tuple(np.asarray(v, dtype=np.float32) for v in out) + return np.asarray(out, dtype=np.float32) + + return encode_fn, meta + + +def encode_frames(encode_fn, frames, batch=4096, log_every=0): + """Encode frames [N, H, W, C] uint8 in batches -> z [N, z_dim] float32.""" + outs = [] + for i in range(0, len(frames), batch): + outs.append(encode_fn(frames[i:i + batch])) + if log_every and (i // batch) % log_every == 0: + print(f" encode {i}/{len(frames)}", flush=True) + return np.concatenate(outs, axis=0) + + +# ---- training ---- + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--env", default="visual-cube-single-play-v0", + help="visual env id; picks the reward-target geometry " + "(maze -> ant xy; cube -> scaled cube xyz) and the " + "default raw-space sigma") + ap.add_argument("--data", default=None, + help="dataset npz (default ~/.ogbench/data/.npz)") + ap.add_argument("--h5_pixels", default=None, + help="optionally read pixels from this h5 ('pixels' column, byte-" + "identical to the npz) — partial-read friendly for CPU smokes") + ap.add_argument("--max_frames", type=int, default=0, + help="truncate the dataset to this many frames (rounded down to an " + "episode boundary); 0 = all") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=100000) + ap.add_argument("--batch_size", type=int, default=256) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--z_dim", type=int, default=8) + ap.add_argument("--hidden", type=int, default=256) + ap.add_argument("--channels", default="32,64,128,256") + ap.add_argument("--sigma_z", type=float, default=1.0, help="reward bandwidth in z-space") + ap.add_argument("--lam", type=float, default=1e-4, help="L2 penalty on |z|^2") + ap.add_argument("--gamma", type=float, default=0.99) + ap.add_argument("--sigma", type=float, default=None, + help="raw-space dense-reward bandwidth; default from --env " + "(cube 0.5, maze 5.0 — matches SIGMA_BY_ENV)") + ap.add_argument("--val_episodes", type=int, default=20, + help="hold out the LAST k episodes for the reward-prediction MSE probe") + ap.add_argument("--val_pairs", type=int, default=8192) + ap.add_argument("--eval_every", type=int, default=2000) + ap.add_argument("--out", default=None) + args = ap.parse_args() + + import jax + import jax.numpy as jnp + import optax + import tqdm + + repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + safe = args.env.replace("-", "_") + out = args.out or os.path.join(repo_root, "ckpt", f"pixel_enc_{safe}.npz") + os.makedirs(os.path.dirname(out), exist_ok=True) + channels = tuple(int(c) for c in args.channels.split(",")) + data = args.data or os.path.expanduser(f"~/.ogbench/data/{args.env}.npz") + target_fn, sigma_default = reward_target_fn(args.env) + sigma = float(args.sigma if args.sigma is not None else sigma_default) + + d = np.load(os.path.expanduser(data)) + terminals = np.asarray(d["terminals"]) + qpos = np.asarray(d["qpos"]) + N_all = len(terminals) + ep_ends = np.where(terminals > 0)[0] + assert len(ep_ends) > 1, "no terminals in dataset" + + N = N_all + if args.max_frames and args.max_frames < N_all: + usable = ep_ends[ep_ends < args.max_frames] + assert len(usable) >= 2, "--max_frames must cover at least 2 episodes" + N = int(usable[-1]) + 1 + print(f"[pixel_enc] frames {N}/{N_all} episodes {int((terminals[:N] > 0).sum())}", + flush=True) + + if args.h5_pixels: + import h5py + with h5py.File(os.path.expanduser(args.h5_pixels), "r") as f: + assert np.array_equal(f["qpos"][0], qpos[0]) and \ + np.array_equal(f["qpos"][N - 1], qpos[N - 1]), "h5/npz misaligned" + pix = f["pixels"][:N] + else: + pix = np.asarray(d["observations"][:N]) + assert pix.dtype == np.uint8 and pix.ndim == 4 and pix.shape[0] == N, pix.shape + img_hw, in_ch = int(pix.shape[1]), int(pix.shape[3]) + + tgt = target_fn(qpos[:N]) # reward reads ONLY this + end_of = _ends(terminals[:N]) + + # train/val split at an episode boundary: last val_episodes episodes held out + ends_here = np.where(terminals[:N] > 0)[0] + n_val_ep = min(args.val_episodes, max(len(ends_here) - 1, 1)) + split = int(ends_here[-n_val_ep - 1]) + 1 if n_val_ep < len(ends_here) else N + print(f"[pixel_enc] train frames [0,{split}) val frames [{split},{N})", flush=True) + + rng = np.random.default_rng(args.seed) + + def sample_pairs(rng_, n, lo, hi): + t = rng_.integers(lo, hi, n) + j = _future(t, end_of, args.gamma, rng_) + gi = _goal_after(j, end_of, rng_) + dist = np.linalg.norm(tgt[j] - tgt[gi], axis=1) + r_true = np.exp(-(dist ** 2) / (2 * sigma ** 2)).astype(np.float32) + return j, gi, r_true + + # fixed held-out probe pairs + vrng = np.random.default_rng(args.seed + 1) + vj, vgi, vr = sample_pairs(vrng, args.val_pairs, split, N) if split < N else \ + sample_pairs(vrng, args.val_pairs, 0, N) + + enc = make_pixel_encoder(args.z_dim, channels, args.hidden) + key = jax.random.PRNGKey(args.seed) + params = enc.init(key, jnp.zeros((1, img_hw, img_hw, in_ch))) + n_p = sum(int(np.prod(p.shape)) for p in jax.tree_util.tree_leaves(params)) + print(f"[pixel_enc] z_dim={args.z_dim} channels={channels} params={n_p/1e6:.2f}M " + f"devices={jax.devices()}", flush=True) + + tx = optax.adam(args.lr) + opt_state = tx.init(params) + sz2 = 2.0 * args.sigma_z ** 2 + + def fwd(params_, xu8): + return enc.apply(params_, xu8.astype(jnp.float32) / 255.0 - 0.5) + + def loss_fn(params_, xu8, gu8, r_true): + zx = fwd(params_, xu8) + zg = fwd(params_, gu8) + d2 = jnp.sum((zx - zg) ** 2, axis=-1) + r_hat = jnp.exp(-d2 / sz2) + rec = jnp.mean((r_hat - r_true) ** 2) + reg = args.lam * (jnp.mean(jnp.sum(zx ** 2, -1)) + jnp.mean(jnp.sum(zg ** 2, -1))) + return rec + reg, rec + + @jax.jit + def update(params_, opt_state_, xu8, gu8, r_true): + (loss, rec), grads = jax.value_and_grad(loss_fn, has_aux=True)( + params_, xu8, gu8, r_true) + updates, opt_state_ = tx.update(grads, opt_state_, params_) + return optax.apply_updates(params_, updates), opt_state_, loss, rec + + @jax.jit + def val_rec(params_, xu8, gu8, r_true): + return loss_fn(params_, xu8, gu8, r_true)[1] + + def held_out_mse(params_): + tot, cnt = 0.0, 0 + for i in range(0, len(vj), 1024): + sl = slice(i, i + 1024) + m = float(val_rec(params_, jnp.asarray(pix[vj[sl]]), jnp.asarray(pix[vgi[sl]]), + jnp.asarray(vr[sl]))) + tot += m * (len(vr[sl])); cnt += len(vr[sl]) + return tot / cnt + + recent, val_hist = [], [] + for step in tqdm.trange(1, args.train_steps + 1, smoothing=0.1, dynamic_ncols=True): + j, gi, r_true = sample_pairs(rng, args.batch_size, 0, split) + params, opt_state, loss, rec = update( + params, opt_state, jnp.asarray(pix[j]), jnp.asarray(pix[gi]), + jnp.asarray(r_true)) + recent.append(float(rec)) + if len(recent) > 200: + recent.pop(0) + if step % args.eval_every == 0 or step == 1: + vm = held_out_mse(params) + val_hist.append(vm) + print(f"[pixel_enc] step {step} train recon_mse(running) {np.mean(recent):.5f} " + f"held-out reward-mse {vm:.5f}", flush=True) + + # ---- export (schema in module docstring) ---- + p = params["params"] if "params" in params else params + arrs = {} + for i in range(len(channels)): + arrs[f"conv_{i}.kernel"] = np.asarray(p[f"conv_{i}"]["kernel"]).astype(np.float32) + arrs[f"conv_{i}.bias"] = np.asarray(p[f"conv_{i}"]["bias"]).astype(np.float32) + for i in range(2): + arrs[f"fc_{i}.weight"] = np.asarray(p[f"fc_{i}"]["kernel"]).T.astype(np.float32) + arrs[f"fc_{i}.bias"] = np.asarray(p[f"fc_{i}"]["bias"]).astype(np.float32) + np.savez(out, z_dim=np.asarray(args.z_dim), hidden=np.asarray(args.hidden), + channels=np.asarray(channels), img_hw=np.asarray(img_hw), in_ch=np.asarray(in_ch), + sigma_z=np.asarray(args.sigma_z), sigma=np.asarray(args.sigma), + gamma=np.asarray(args.gamma), **arrs) + print(f"[pixel_enc] saved {out}", flush=True) + print(f"[pixel_enc] final held-out reward-mse {val_hist[-1]:.5f} " + f"(first {val_hist[0]:.5f})", flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/train_reward_decoder.py b/gen_q_rsm/ogbench_genq/genq/train_reward_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..a5da91393ca7836712b412fbd7a1a376a97aa62b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_reward_decoder.py @@ -0,0 +1,388 @@ +"""Train a coordinate-free GOAL classifier R_psi(z_a, z_b) on a FROZEN encoder's latents, +for the RSM classifier read-out Q(s,a,g) = E_{z'~occ(s,a)}[ sigmoid(R_psi(z', z_g)) ]. + +Replaces the mass-at-goal DENSITY read-out (q_elbo), which averages denoise error over ALL +latent dims so the high-variance arm dims swamp the cube -> flat q_self~q_rand. A classifier +can IGNORE the arm dims and key on the reward-relevant (cube) match -> discriminative Q. + +R_psi is either the legacy small pairwise MLP or a constrained diagonal +Mahalanobis metric trained by BCE. The metric reader uses + + bias - sum_i weight_i * ((z_a_i - z_b_i) / scale_i) ** 2, + +where ``scale`` is the frozen training-latent standard deviation and +``weight >= 0`` is enforced by a softplus parameterization. Its learned bias +calibrates the radial score as an index-reward probability. For the MLP index +target, the preferred input is [z_a, z_b, |z_a-z_b|, z_a*z_b], matching the +symmetric goal-proximity encoder objective. Positives are near in trajectory +time; negatives mix far same-episode and cross-episode frames. Coordinate +diagnostics are disabled by default; ``--coordinate_diagnostics`` explicitly +opts into a post-hoc cube-xyz audit that never enters the loss. + +Saves a plain-numpy npz (g0/g1/g2 kernels+biases + meta) that rsm.py --reward_decoder loads. + +Usage: + python genq/train_reward_decoder.py --latents ckpt/valrew_smooth_s10_fast_latents.npz \ + --out ckpt/rdec_smooth_s10_fast.npz +""" +import argparse, os, sys +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + + +def episode_bounds(terminals): + ends = np.where(terminals)[0] + starts = np.concatenate([[0], ends[:-1] + 1]) + return list(zip(starts.tolist(), ends.tolist())) + + +def sample(eps, z, rng, n, max_gap=400, target="reach", index_delta=8, + neg_gap=64, cross_neg_frac=0.5): + """Positive/negative (anchor t, goal) pairs for R_psi. + + target="reach": positive g = a DOWNSTREAM goal (t+1..t+max_gap) — "t reaches g" + (value-like; g may be far). negative = goal from another episode. + target="index": positive g = a NEAR-in-time frame (t..t+index_delta) — the INDEX + reward "t is AT goal g" (the actual reward, sharp). negative = far frame + (cross-episode OR same-episode >max_gap away).""" + ts, gs, ng = [], [], [] + E = len(eps) + for _ in range(n): + e = rng.integers(0, E); s, en = eps[e] + if en - s < 2: + continue + t = rng.integers(s, en) + if target == "index": + g = min(t + rng.integers(0, index_delta + 1), en) # AT/near goal + else: + g = rng.integers(t + 1, min(en, t + max_gap) + 1) # downstream (reachable) + if target == "index": + left_n = max(t - neg_gap - s + 1, 0) + right_lo = t + neg_gap + right_n = max(en - right_lo + 1, 0) + use_cross = rng.random() < cross_neg_frac or left_n + right_n == 0 + if use_cross and E > 1: + e2 = int(rng.integers(0, E - 1)) + e2 += int(e2 >= e) + s2, en2 = eps[e2] + gneg = rng.integers(s2, en2 + 1) + else: + u = int(rng.integers(0, left_n + right_n)) + gneg = s + u if u < left_n else right_lo + (u - left_n) + else: + e2 = int(rng.integers(0, E - 1)) if E > 1 else e + e2 += int(E > 1 and e2 >= e) + s2, en2 = eps[e2] + gneg = rng.integers(s2, en2 + 1) + ts.append(t); gs.append(g); ng.append(gneg) + return np.asarray(ts), np.asarray(gs), np.asarray(ng) + + +def sample_index_same_episode(eps, rng, n, index_delta=4, neg_gap=64): + """Vectorized minimal metric-reader pairs. + + This is the ``cross_neg_frac=0`` index recipe used by the constrained + diagonal reader. It samples exactly the same per-episode anchor, + nonnegative near-future positive, and uniform far same-episode negative + distribution as :func:`sample`, without a Python loop over batch rows. + Every selected episode must admit a far negative for every anchor; the + visual-cube trajectories satisfy this by a wide margin. + """ + bounds = np.asarray(eps, np.int64) + episode = rng.integers(0, len(bounds), size=n) + start = bounds[episode, 0] + end = bounds[episode, 1] + anchor_width = end - start + if np.any(anchor_width <= 0): + raise ValueError("index-pair episodes must contain two or more rows") + row = start + np.floor( + rng.random(n) * anchor_width).astype(np.int64) + positive = np.minimum( + row + rng.integers(0, index_delta + 1, size=n), end) + + left_count = np.maximum(row - neg_gap - start + 1, 0) + right_start = row + neg_gap + right_count = np.maximum(end - right_start + 1, 0) + candidate_count = left_count + right_count + if np.any(candidate_count <= 0): + raise ValueError( + "same-episode-only index negatives require trajectories long " + "enough to provide a far negative for every anchor") + choice = np.floor( + rng.random(n) * candidate_count).astype(np.int64) + negative = np.where( + choice < left_count, + start + choice, + right_start + (choice - left_count), + ) + return row, positive, negative + + +def build_ends(terminals): + """Exclusive episode end for every row, matching GCIQL's dataset relabeler.""" + terminals = np.asarray(terminals).astype(bool) + out = np.empty(len(terminals), dtype=np.int64) + start = 0 + for stop in np.where(terminals)[0] + 1: + out[start:stop] = stop + start = stop + if start < len(out): + out[start:] = len(out) + return out + + +def sample_gciql(rng, end_of, n, lo, hi, discount=0.99, + p_curgoal=0.2, p_trajgoal=0.5): + """GCIQL current/trajectory/random goals and normalized return targets.""" + t = rng.integers(lo, hi, n) + final = end_of[t] - 1 + offset = rng.geometric(1.0 - discount, size=n) + traj = np.minimum(t + offset, final) + random_goal = rng.integers(lo, hi, n) + u = rng.random(n) + is_cur = u < p_curgoal + is_traj = (u >= p_curgoal) & (u < p_curgoal + p_trajgoal) + goal = np.where(is_cur, t, np.where(is_traj, traj, random_goal)) + value = np.where( + is_cur, 1.0, + np.where(is_traj, discount ** np.maximum(traj - t, 0), 0.0), + ).astype(np.float32) + # Exact equality is the sparse index reward, including a clipped trajectory + # goal or the rare random draw that lands on the current row. + value = np.where(goal == t, 1.0, value).astype(np.float32) + return t.astype(np.int64), goal.astype(np.int64), value + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--latents", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--data", default=os.path.expanduser( + "~/.ogbench/data/visual-cube-single-play-v0.npz")) + ap.add_argument( + "--coordinate_diagnostics", action="store_true", + help="opt into cube-coordinate validation diagnostics; off by default " + "and never used by the reader loss") + ap.add_argument("--model", choices=["mlp", "diag_metric"], default="mlp", + help="pairwise MLP or calibrated nonnegative diagonal " + "Mahalanobis index reader") + ap.add_argument("--hidden", type=int, default=256) + ap.add_argument("--steps", type=int, default=40000) + ap.add_argument("--batch", type=int, default=4096) + ap.add_argument("--lr", type=float, default=1e-3) + ap.add_argument("--max_gap", type=int, default=400) + ap.add_argument("--target", choices=["reach", "index", "gciql"], default="index", + help="index = at-goal reward (positive = near-in-time, the ACTUAL " + "reward GCIQL uses); reach = reachability (positive = downstream); " + "gciql = current/trajectory/random goals with a discounted soft " + "return target.") + ap.add_argument("--index_delta", type=int, default=8, + help="'at goal' horizon for --target index (frames)") + ap.add_argument("--neg_gap", type=int, default=64, + help="minimum temporal separation for same-episode index negatives") + ap.add_argument("--cross_neg_frac", type=float, default=0.5, + help="fraction of index negatives drawn from another episode") + ap.add_argument("--features", choices=["concat", "symmetric"], default="concat", + help="pair features; symmetric matches the goal-proximity encoder head") + ap.add_argument("--activation", choices=["tanh", "relu"], default="tanh") + ap.add_argument("--gciql_discount", type=float, default=0.99) + ap.add_argument("--gciql_p_curgoal", type=float, default=0.2) + ap.add_argument("--gciql_p_trajgoal", type=float, default=0.5) + ap.add_argument("--gciql_p_randomgoal", type=float, default=0.3) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + if args.model == "diag_metric" and args.target != "index": + ap.error("--model diag_metric is defined only for --target index") + assert args.neg_gap > args.index_delta + assert 0.0 <= args.cross_neg_frac <= 1.0 + assert np.isclose(args.gciql_p_curgoal + args.gciql_p_trajgoal + + args.gciql_p_randomgoal, 1.0) + assert 0.0 < args.gciql_discount < 1.0 + + import jax, jax.numpy as jnp, optax + from scipy.stats import spearmanr + + rng = np.random.default_rng(args.seed) + L = np.load(args.latents, allow_pickle=True) + z = np.asarray(L["z"], np.float32); N = len(z); zdim = z.shape[1] + term = np.asarray(L["terminals"]) + eps = episode_bounds(term) + ne = len(eps); tr_eps = eps[: int(0.95 * ne)]; va_eps = eps[int(0.95 * ne):] + end_of = build_ends(term) + train_hi = tr_eps[-1][1] + 1 + val_lo = va_eps[0][0] + xyz = None + if args.coordinate_diagnostics: + from train_pixel_encoder_jax import scaled_cube_xyz + with np.load(args.data) as data: + xyz = scaled_cube_xyz( + np.asarray(data["qpos"])[:N]).astype(np.float32) + print(f"[rdec] latents={args.latents} N={N} zdim={zdim} eps={ne}", flush=True) + + din = (4 if args.features == "symmetric" else 2) * zdim + H = args.hidden + key = jax.random.PRNGKey(args.seed) + metric_scale = ( + z[:train_hi].std(axis=0).astype(np.float32) + np.float32(1e-6)) + + def init_mlp(key): + k = jax.random.split(key, 3) + s = lambda kk, a, b: jax.random.normal(kk, (a, b)) * (2.0 / a) ** 0.5 + return {"g0.kernel": s(k[0], din, H), "g0.bias": jnp.zeros(H), + "g1.kernel": s(k[1], H, H), "g1.bias": jnp.zeros(H), + "g2.kernel": s(k[2], H, 1) * 0.1, "g2.bias": jnp.zeros(1)} + + if args.model == "mlp": + # This is deliberately the exact legacy initialization path. + P = init_mlp(key) + else: + # Start from the mean standardized squared distance. Softplus keeps + # every learned diagonal entry nonnegative without projection. + initial_weight = np.float32(1.0 / zdim) + raw_weight = np.log(np.expm1(initial_weight)).astype(np.float32) + P = { + "metric.raw_weight": jnp.full((zdim,), raw_weight), + "metric.bias": jnp.asarray(0.0, jnp.float32), + } + metric_scale_j = jnp.asarray(metric_scale) + + def pair_features(za, zb): + if args.features == "symmetric": + return jnp.concatenate([za, zb, jnp.abs(za - zb), za * zb], -1) + return jnp.concatenate([za, zb], -1) + + def activate(x): + return jax.nn.relu(x) if args.activation == "relu" else jnp.tanh(x) + + def fwd(P, za, zb): + if args.model == "diag_metric": + weight = jax.nn.softplus(P["metric.raw_weight"]) + difference = (za - zb) / metric_scale_j + return P["metric.bias"] - jnp.sum( + weight * jnp.square(difference), axis=-1) + h = pair_features(za, zb) + h = activate(h @ P["g0.kernel"] + P["g0.bias"]) + h = activate(h @ P["g1.kernel"] + P["g1.bias"]) + return (h @ P["g2.kernel"] + P["g2.bias"])[:, 0] + def binary_loss(P, za, zgp, zgn): + pos = fwd(P, za, zgp); neg = fwd(P, za, zgn) + return -(jax.nn.log_sigmoid(pos) + jax.nn.log_sigmoid(-neg)).mean() + + def soft_loss(P, za, zg, value): + logit = fwd(P, za, zg) + return -(value * jax.nn.log_sigmoid(logit) + + (1.0 - value) * jax.nn.log_sigmoid(-logit)).mean() + + tx = optax.adam(args.lr); opt = tx.init(P) + @jax.jit + def binary_step(P, opt, za, zgp, zgn): + l, g = jax.value_and_grad(binary_loss)(P, za, zgp, zgn) + u, opt = tx.update(g, opt, P); return optax.apply_updates(P, u), opt, l + + @jax.jit + def soft_step(P, opt, za, zg, value): + l, g = jax.value_and_grad(soft_loss)(P, za, zg, value) + u, opt = tx.update(g, opt, P); return optax.apply_updates(P, u), opt, l + + zj = jnp.asarray(z) + for it in range(1, args.steps + 1): + if args.target == "gciql": + t, gp, value = sample_gciql( + rng, end_of, args.batch, 0, train_hi, + args.gciql_discount, args.gciql_p_curgoal, + args.gciql_p_trajgoal) + P, opt, l = soft_step(P, opt, zj[t], zj[gp], jnp.asarray(value)) + else: + if ( + args.model == "diag_metric" + and args.target == "index" + and args.cross_neg_frac == 0.0): + t, gp, gn = sample_index_same_episode( + tr_eps, rng, args.batch, + args.index_delta, args.neg_gap) + else: + t, gp, gn = sample( + tr_eps, z, rng, args.batch, args.max_gap, args.target, + args.index_delta, args.neg_gap, args.cross_neg_frac) + P, opt, l = binary_step(P, opt, zj[t], zj[gp], zj[gn]) + if it % 5000 == 0 or it == 1: + # diagnostic: does R_psi(z_t, z_g) track cube-proximity? (coordinate = diag only) + if args.target == "gciql": + tv, gv, vv = sample_gciql( + rng, end_of, 8000, val_lo, N, + args.gciql_discount, args.gciql_p_curgoal, + args.gciql_p_trajgoal) + sc = np.asarray(fwd(P, zj[tv], zj[gv])) + pred = 1.0 / (1.0 + np.exp(-np.clip(sc, -30.0, 30.0))) + mae = float(np.abs(pred - vv).mean()) + value_rho = float(spearmanr(pred, vv).statistic) + exact = gv == tv + acc = 0.5 * ((sc[exact] > 0).mean() + (sc[~exact] < 0).mean()) + else: + if ( + args.model == "diag_metric" + and args.target == "index" + and args.cross_neg_frac == 0.0): + tv, gv, gnv = sample_index_same_episode( + va_eps, rng, 8000, + args.index_delta, args.neg_gap) + else: + tv, gv, gnv = sample( + va_eps, z, rng, 8000, args.max_gap, args.target, + args.index_delta, args.neg_gap, args.cross_neg_frac) + sc = np.asarray(fwd(P, zj[tv], zj[gv])) + acc = ((np.asarray(fwd(P, zj[tv], zj[gv])) > 0).mean() + + (np.asarray(fwd(P, zj[tv], zj[gnv])) < 0).mean()) / 2 + mae = float("nan") + value_rho = float("nan") + if xyz is None: + rho_text = "disabled" + else: + prox = -np.linalg.norm(xyz[tv] - xyz[gv], axis=1) + rho = spearmanr(sc, prox).statistic + rho_text = f"{rho:.4f}" + print(f"[rdec] step {it} bce={float(l):.4f} val_acc={acc:.3f} " + f"value_mae={mae:.4f} value_rho={value_rho:.4f} " + f"spearman(R_psi,cube-prox)={rho_text}", flush=True) + + if args.model == "mlp": + out = {k: np.asarray(v) for k, v in P.items()} + else: + metric_weight = np.asarray( + jax.nn.softplus(P["metric.raw_weight"]), np.float32) + assert np.all(metric_weight >= 0.0) + out = { + "metric_scale": metric_scale, + "metric_weight": metric_weight, + "metric_bias": np.asarray(P["metric.bias"], np.float32), + } + label_source = { + "index": "trajectory_index_positive_and_far_negative_relabeling", + "reach": "trajectory_reachability_relabeling", + "gciql": "gciql_goal_mix_index_return_relabeling", + }[args.target] + np.savez(args.out, zdim=np.asarray(zdim), hidden=np.asarray(H), + reader_model=np.asarray(args.model), + activation=np.asarray(args.activation), features=np.asarray(args.features), + target=np.asarray(args.target), index_delta=np.asarray(args.index_delta), + neg_gap=np.asarray(args.neg_gap), + cross_neg_frac=np.asarray(args.cross_neg_frac), + gciql_discount=np.asarray(args.gciql_discount), + gciql_p_curgoal=np.asarray(args.gciql_p_curgoal), + gciql_p_trajgoal=np.asarray(args.gciql_p_trajgoal), + gciql_p_randomgoal=np.asarray(args.gciql_p_randomgoal), + pixels_only_latents=np.asarray(True), + frozen_encoder=np.asarray(True), + uses_coordinates_for_training=np.asarray(False), + uses_coordinates_for_diagnostics=np.asarray( + args.coordinate_diagnostics), + uses_reward_arrays=np.asarray(False), + uses_td_or_bootstrap=np.asarray(False), + label_source=np.asarray(label_source), + **out) + print(f"[rdec] saved {args.out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/train_visual_gcbc_control.py b/gen_q_rsm/ogbench_genq/genq/train_visual_gcbc_control.py new file mode 100644 index 0000000000000000000000000000000000000000..97d7cc190b01385286a438dc2a87f4a559399de9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_visual_gcbc_control.py @@ -0,0 +1,281 @@ +"""Train a strictly pixels-only visual goal-conditioned BC actor control. + +This isolates the policy-input question exposed by the fair visual RSM +rollout: can the exact IMPALA-small actor architecture used by the reproduced +visual GCIQL control learn cube actions without any critic or TD signal? + +The program uses only rendered uint8 observations, dataset actions, terminal +boundaries, and same-trajectory future-index relabeling. It never constructs +the simulator while training and never reads proprioception, coordinates, +rewards, qpos, or qvel. Its checkpoint is intended as a diagnostic and a +possible non-TD initialization for a subsequently joint occupancy/actor run; +it is not itself an RSM result. +""" + +import argparse +import hashlib +import json +import os +import pickle +import random +import sys +import time + +import numpy as np + + +ENV = "visual-cube-single-play-v0" +FORBIDDEN_KEYS = frozenset({ + "qpos", "qvel", "button_states", "coordinates", "rewards", +}) + + +def _setup_reference_path(path): + path = os.path.abspath(os.path.expanduser(path)) + if path not in sys.path: + sys.path.insert(0, path) + return path + + +def _reference_sha256(reference_root): + digest = hashlib.sha256() + for rel in ( + "agents/gcbc.py", + "utils/datasets.py", + "utils/encoders.py", + "utils/networks.py", + ): + with open(os.path.join(reference_root, rel), "rb") as file: + digest.update(rel.encode()) + digest.update(file.read()) + return digest.hexdigest() + + +def exact_visual_gcbc_config(): + """Return the visual actor control configuration.""" + from agents.gcbc import get_config + + config = get_config() + config.batch_size = 256 + config.encoder = "impala_small" + config.p_aug = 0.5 + config.frame_stack = None + assert config.lr == 3e-4 + assert config.actor_hidden_dims == (512, 512, 512) + assert config.actor_p_curgoal == 0.0 + assert config.actor_p_trajgoal == 1.0 + assert config.actor_p_randomgoal == 0.0 + assert not config.actor_geom_sample + return config + + +def _atomic_pickle(path, payload): + temporary = f"{path}.tmp" + with open(temporary, "wb") as file: + pickle.dump(payload, file, protocol=pickle.HIGHEST_PROTOCOL) + file.flush() + os.fsync(file.fileno()) + os.replace(temporary, path) + + +def _save_resume(path, agent, step): + import flax + import jax + + _atomic_pickle(path, { + "format": "visual_gcbc_resume_v1", + "step": int(step), + "agent": flax.serialization.to_state_dict(jax.device_get(agent)), + "numpy_random_state": np.random.get_state(), + "python_random_state": random.getstate(), + }) + + +def _save_export(path, agent, step, config, run_meta): + import jax + + _atomic_pickle(path, { + "format": "visual_gcbc_params_v1", + "step": int(step), + "params": jax.device_get(agent.network.params), + "config": dict(config), + "run_meta": dict(run_meta), + }) + + +def _load_resume(path, agent): + import flax + + with open(path, "rb") as file: + payload = pickle.load(file) + assert payload["format"] == "visual_gcbc_resume_v1" + agent = flax.serialization.from_state_dict(agent, payload["agent"]) + np.random.set_state(payload["numpy_random_state"]) + random.setstate(payload["python_random_state"]) + return agent, int(payload["step"]) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output_dir", required=True) + parser.add_argument("--train_steps", type=int, default=300_000) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--checkpoint_interval", type=int, default=10_000) + parser.add_argument("--export_interval", type=int, default=50_000) + parser.add_argument("--log_interval", type=int, default=1_000) + parser.add_argument("--resume", default="auto") + parser.add_argument("--wandb_mode", default="disabled") + parser.add_argument( + "--ogbench_impls", + default=os.environ.get( + "OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls")), + ) + args = parser.parse_args() + assert args.train_steps > 0 + assert args.checkpoint_interval > 0 and args.export_interval > 0 + + reference_root = _setup_reference_path(args.ogbench_impls) + os.makedirs(args.output_dir, exist_ok=True) + + import flax + import jax + import ogbench + import wandb + from agents.gcbc import GCBCAgent + from utils.datasets import Dataset, GCDataset + + config = exact_visual_gcbc_config() + train_raw, _ = ogbench.make_env_and_datasets( + ENV, compact_dataset=True, dataset_only=True, add_info=False) + assert not (set(train_raw) & FORBIDDEN_KEYS), sorted(train_raw) + assert set(train_raw) == { + "observations", "actions", "terminals", "valids"} + observations = train_raw["observations"] + actions = train_raw["actions"] + assert observations.dtype == np.uint8 and observations.ndim == 4 + assert actions.ndim == 2 and len(actions) == len(observations) + + train_dataset = GCDataset(Dataset.create(**train_raw), config) + random.seed(args.seed) + np.random.seed(args.seed) + example = train_dataset.sample(2, evaluation=True) + agent = GCBCAgent.create( + args.seed, example["observations"], example["actions"], config) + + resume_path = ( + os.path.join(args.output_dir, "resume_latest.pkl") + if args.resume == "auto" else None + if args.resume == "none" else os.path.abspath(args.resume)) + start_step = 0 + if resume_path and os.path.exists(resume_path): + agent, start_step = _load_resume(resume_path, agent) + print( + f"[visual-gcbc] resumed step={start_step} from {resume_path}", + flush=True, + ) + assert start_step <= args.train_steps + + run_meta = { + "method": "GCBC", + "purpose": "pixels_only_actor_input_control_for_visual_rsm", + "env": ENV, + "seed": int(args.seed), + "pixels_only": True, + "drop_proprio": True, + "simulator_state_used": False, + "coordinate_used": False, + "reward_used": False, + "uses_td_or_bootstrap": False, + "uses_occupancy": False, + "observation_shape": list(observations.shape[1:]), + "observation_dtype": str(observations.dtype), + "action_shape": list(actions.shape[1:]), + "dataset_keys": sorted(train_raw), + "excluded_keys": sorted(FORBIDDEN_KEYS), + "reference_root": reference_root, + "reference_sha256": _reference_sha256(reference_root), + "config": dict(config), + "train_steps": int(args.train_steps), + "goal_relabeling": "uniform_future_same_trajectory", + "network_input_contract": ( + "IMPALA-small over channel-concatenated state and goal RGB"), + "training_augmentation": ( + "probability_0.5_shared_edge_padded_random_crop"), + } + with open(os.path.join(args.output_dir, "metadata.json"), "w") as file: + json.dump(run_meta, file, indent=2) + + run = wandb.init( + project="gen-q-visual-gcbc-control", + name=f"visual-gcbc-control-s{args.seed}", + mode=args.wandb_mode, + config=run_meta, + settings=wandb.Settings(start_method="thread"), + ) + metrics_path = os.path.join(args.output_dir, "train_metrics.jsonl") + start_time = time.time() + print( + "[visual-gcbc] exact actor-input control " + f"steps={start_step}->{args.train_steps} " + f"batch={config.batch_size} encoder={config.encoder} " + f"p_aug={config.p_aug} non_td=true", + flush=True, + ) + + for step in range(start_step + 1, args.train_steps + 1): + agent, info = agent.update(train_dataset.sample(config.batch_size)) + if step % args.log_interval == 0: + scalars = { + key: float(np.asarray(value)) + for key, value in info.items() + if np.asarray(value).ndim == 0 + } + scalars.update({ + "step": step, + "wall_clock_sec": round(time.time() - start_time, 3), + }) + with open(metrics_path, "a") as file: + file.write(json.dumps(scalars) + "\n") + run.log({ + f"train/{key}": value + for key, value in scalars.items() + if key not in ("step", "wall_clock_sec") + }, step=step) + print( + f"[visual-gcbc] step={step} " + f"loss={scalars['actor/actor_loss']:.6f} " + f"mse={scalars['actor/mse']:.6f} " + f"wall={scalars['wall_clock_sec']:.1f}", + flush=True, + ) + if step % args.checkpoint_interval == 0 or step == args.train_steps: + _save_resume( + os.path.join(args.output_dir, "resume_latest.pkl"), + agent, + step, + ) + if step % args.export_interval == 0 or step == args.train_steps: + _save_export( + os.path.join(args.output_dir, f"params_{step}.pkl"), + agent, + step, + config, + run_meta, + ) + + done = { + **run_meta, + "completed_step": int(args.train_steps), + "wall_clock_sec_this_process": round( + time.time() - start_time, 3), + "flax_version": flax.__version__, + "jax_version": jax.__version__, + } + with open(os.path.join(args.output_dir, "done.json"), "w") as file: + json.dump(done, file, indent=2) + run.finish() + print(json.dumps(done, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/train_visual_gciql_control.py b/gen_q_rsm/ogbench_genq/genq/train_visual_gciql_control.py new file mode 100644 index 0000000000000000000000000000000000000000..4cde5ea4df9e476bc4605c3ecad8c4c6e6119ac3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_visual_gciql_control.py @@ -0,0 +1,291 @@ +"""Train the exact pixels-only visual OGBench GCIQL control and export its networks. + +This is deliberately a diagnostic baseline, not part of the RSM implementation. +It preserves the official OGBench GCIQL agent, goal relabeling, IMPALA encoder, +and image augmentation. The only harness changes are: + +* dataset-only loading, so training never initializes MuJoCo or reads simulator + state; +* resumable, atomic checkpoints; and +* explicit parameter exports for critic/value/actor audits. + +No temporal-difference target from this program is shared with RSM training. +""" +import argparse +import glob +import hashlib +import json +import os +import pickle +import random +import sys +import time + +import numpy as np + + +ENV = "visual-cube-single-play-v0" +FORBIDDEN_KEYS = frozenset({"qpos", "qvel", "button_states", "coordinates"}) + + +def _setup_reference_path(path): + path = os.path.abspath(os.path.expanduser(path)) + if path not in sys.path: + sys.path.insert(0, path) + return path + + +def _reference_sha256(reference_root): + digest = hashlib.sha256() + for rel in ( + "agents/gciql.py", + "utils/datasets.py", + "utils/encoders.py", + "utils/networks.py", + ): + with open(os.path.join(reference_root, rel), "rb") as f: + digest.update(rel.encode()) + digest.update(f.read()) + return digest.hexdigest() + + +def exact_visual_config(): + """Return the configuration used by the established visual GCIQL run.""" + from agents.gciql import get_config + + config = get_config() + config.alpha = 1.0 + config.batch_size = 256 + config.encoder = "impala_small" + config.p_aug = 0.5 + config.frame_stack = None + # Assert the remaining official defaults that matter for this control. + assert config.actor_loss == "ddpgbc" + assert config.discount == 0.99 + assert config.expectile == 0.9 + assert config.gc_negative + assert config.actor_p_curgoal == 0.0 + assert config.actor_p_trajgoal == 1.0 + assert config.actor_p_randomgoal == 0.0 + assert not config.actor_geom_sample + return config + + +def _atomic_pickle(path, obj): + tmp = f"{path}.tmp" + with open(tmp, "wb") as f: + pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + + +def _save_resume(path, agent, step): + import flax + import jax + + payload = { + "format": "visual_gciql_resume_v1", + "step": int(step), + "agent": flax.serialization.to_state_dict(jax.device_get(agent)), + "numpy_random_state": np.random.get_state(), + "python_random_state": random.getstate(), + } + _atomic_pickle(path, payload) + + +def _save_export(path, agent, step, config, run_meta): + import jax + + payload = { + "format": "visual_gciql_params_v1", + "step": int(step), + "params": jax.device_get(agent.network.params), + "config": dict(config), + "run_meta": dict(run_meta), + } + _atomic_pickle(path, payload) + + +def _load_resume(path, agent): + import flax + + with open(path, "rb") as f: + payload = pickle.load(f) + assert payload["format"] == "visual_gciql_resume_v1" + agent = flax.serialization.from_state_dict(agent, payload["agent"]) + np.random.set_state(payload["numpy_random_state"]) + random.setstate(payload["python_random_state"]) + return agent, int(payload["step"]) + + +def _find_resume(output_dir, resume): + if resume == "none": + return None + if resume != "auto": + return os.path.abspath(resume) + candidate = os.path.join(output_dir, "resume_latest.pkl") + return candidate if os.path.exists(candidate) else None + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--output_dir", required=True) + ap.add_argument("--train_steps", type=int, default=300_000) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--checkpoint_interval", type=int, default=10_000) + ap.add_argument("--export_interval", type=int, default=100_000) + ap.add_argument("--log_interval", type=int, default=1_000) + ap.add_argument("--resume", default="auto", + help="'auto', 'none', or a resume checkpoint path") + ap.add_argument("--wandb_mode", default="offline") + ap.add_argument("--ogbench_impls", + default=os.environ.get( + "OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls"))) + args = ap.parse_args() + + reference_root = _setup_reference_path(args.ogbench_impls) + os.makedirs(args.output_dir, exist_ok=True) + + import flax + import jax + import ogbench + import wandb + from agents.gciql import GCIQLAgent + from utils.datasets import Dataset, GCDataset + + config = exact_visual_config() + # dataset_only=True is the key fairness guard: this path neither constructs + # the simulator nor asks OGBench to retain qpos/qvel. + train_raw, _ = ogbench.make_env_and_datasets( + ENV, compact_dataset=True, dataset_only=True, add_info=False) + assert not (set(train_raw) & FORBIDDEN_KEYS), sorted(train_raw) + observations = train_raw["observations"] + actions = train_raw["actions"] + assert observations.dtype == np.uint8 and observations.ndim == 4 + assert actions.ndim == 2 and len(actions) == len(observations) + assert set(train_raw) == {"observations", "actions", "terminals", "valids"} + + train_ds = GCDataset(Dataset.create(**train_raw), config) + random.seed(args.seed) + np.random.seed(args.seed) + example = train_ds.sample(2, evaluation=True) + agent = GCIQLAgent.create( + args.seed, example["observations"], example["actions"], config) + + resume_path = _find_resume(args.output_dir, args.resume) + start_step = 0 + if resume_path is not None: + agent, start_step = _load_resume(resume_path, agent) + print(f"[visual-gciql] resumed step={start_step} from {resume_path}", + flush=True) + assert start_step <= args.train_steps + + reference_hash = _reference_sha256(reference_root) + run_meta = { + "method": "GCIQL", + "purpose": "diagnostic_control_only", + "env": ENV, + "seed": int(args.seed), + "pixels_only": True, + "drop_proprio": True, + "simulator_state_used": False, + "coordinate_used": False, + "observation_shape": list(observations.shape[1:]), + "observation_dtype": str(observations.dtype), + "action_shape": list(actions.shape[1:]), + "dataset_keys": sorted(train_raw), + "excluded_keys": sorted(FORBIDDEN_KEYS), + "reference_root": reference_root, + "reference_sha256": reference_hash, + "config": dict(config), + "train_steps": int(args.train_steps), + "network_input_contract": { + "critic": ( + "independent IMPALA-small encoder over channel-concatenated " + "[state RGB pixels, goal RGB pixels], then dataset action"), + "value": ( + "independent IMPALA-small encoder over channel-concatenated " + "[state RGB pixels, goal RGB pixels]"), + "actor": ( + "independent IMPALA-small encoder over channel-concatenated " + "[state RGB pixels, goal RGB pixels]"), + "training_augmentation": ( + "with probability 0.5, one shared random-crop offset per row " + "is applied to observation, next observation, value goal, " + "and actor goal"), + }, + "rsm_consumes_td_outputs": False, + } + with open(os.path.join(args.output_dir, "metadata.json"), "w") as f: + json.dump(run_meta, f, indent=2) + + run = wandb.init( + project="gen-q-visual-gciql-control", + name=f"visual-gciql-control-s{args.seed}", + mode=args.wandb_mode, + config=run_meta, + settings=wandb.Settings(start_method="thread"), + ) + t0 = time.time() + metrics_path = os.path.join(args.output_dir, "train_metrics.jsonl") + print( + "[visual-gciql] exact control " + f"steps={start_step}->{args.train_steps} batch={config.batch_size} " + f"encoder={config.encoder} p_aug={config.p_aug} alpha={config.alpha} " + f"dataset_keys={sorted(train_raw)} reference_sha256={reference_hash}", + flush=True, + ) + + for step in range(start_step + 1, args.train_steps + 1): + agent, info = agent.update(train_ds.sample(config.batch_size)) + if step % args.log_interval == 0: + scalar = { + k: float(np.asarray(v)) + for k, v in info.items() + if np.asarray(v).ndim == 0 + } + scalar.update({ + "step": step, + "wall_clock_sec": round(time.time() - t0, 3), + }) + with open(metrics_path, "a") as f: + f.write(json.dumps(scalar) + "\n") + wandb.log({f"train/{k}": v for k, v in scalar.items() + if k not in ("step", "wall_clock_sec")}, step=step) + print( + f"[visual-gciql] step={step} " + f"critic={scalar.get('critic/critic_loss', float('nan')):.5f} " + f"value={scalar.get('value/value_loss', float('nan')):.5f} " + f"actor={scalar.get('actor/actor_loss', float('nan')):.5f} " + f"wall={scalar['wall_clock_sec']:.1f}", + flush=True, + ) + if step % args.checkpoint_interval == 0 or step == args.train_steps: + _save_resume( + os.path.join(args.output_dir, "resume_latest.pkl"), agent, step) + print(f"[visual-gciql] saved resumable checkpoint step={step}", + flush=True) + if step % args.export_interval == 0 or step == args.train_steps: + export_path = os.path.join(args.output_dir, f"params_{step}.pkl") + _save_export(export_path, agent, step, config, run_meta) + print(f"[visual-gciql] exported critic/value/actor -> {export_path}", + flush=True) + + done = { + **run_meta, + "completed_step": int(args.train_steps), + "wall_clock_sec_this_process": round(time.time() - t0, 3), + "wandb_mode": args.wandb_mode, + "wandb_url": run.get_url(), + "flax_version": flax.__version__, + "jax_version": jax.__version__, + } + with open(os.path.join(args.output_dir, "done.json"), "w") as f: + json.dump(done, f, indent=2) + wandb.finish() + print(json.dumps(done, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/train_visual_occupancy_sweep.py b/gen_q_rsm/ogbench_genq/genq/train_visual_occupancy_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..c184fb654175e66154e396b59e4b953fe9677d8c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_visual_occupancy_sweep.py @@ -0,0 +1,803 @@ +"""Episode-held-out screen for fair pixels-only visual occupancies. + +This is deliberately occupancy-only: no actor, reward, coordinates, or +proprioception enters training. Frozen readers are used after training solely +to measure whether samples support calibrated action values. +The screen compares diffusion with conditional flow matching, absolute with +delta targets, MLP with residual-FiLM trunks, and task-only with +discount-spectrum training. + +Every model receives an explicit discount encoding, including the fixed +gamma=0.99 control. Spectrum variants differ only in the distribution used to +sample that conditioning discount. The preferred visual setup conditions on +the frozen encoder's rich ``state_h`` feature while predicting the compact, +reward-predictive ``z`` future. Both are derived from pixels only. +""" +import argparse +import json +import math +import os +import pickle +import sys +import time + +import numpy as np + +if __package__ in (None, ""): + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) + +from ogbench_genq.genq.train_genq_jax import build_ends, cosine_abar, make_model +from ogbench_genq.genq.reward_reader import load_jax_reward_reader + + +GAMMA = 0.99 +OCC_T = 100 +FOURIER_K = 4 + + +def make_residual_model(cond_dim, y_dim, hidden_dim, num_layers, time_dim): + import flax.linen as nn + import jax.numpy as jnp + + def sinusoid(t, dim): + half = dim // 2 + freq = jnp.exp( + -math.log(10000.0) * jnp.arange(half) / max(half - 1, 1)) + ang = t[:, None] * freq[None] * 1000.0 + return jnp.concatenate([jnp.sin(ang), jnp.cos(ang)], -1) + + class ResidualVelocity(nn.Module): + @nn.compact + def __call__(self, x, t, c): + te = nn.silu(nn.Dense(hidden_dim, name="time_0")( + sinusoid(t, time_dim))) + ce = nn.silu(nn.Dense(hidden_dim, name="cond_0")(c)) + h = nn.Dense(hidden_dim, name="x_0")(x) + te + ce + for i in range(num_layers): + r = nn.LayerNorm(name=f"ln_{i}")(h) + # FiLM makes every block directly condition-aware instead of + # asking one concatenation layer to carry action information. + film = nn.Dense(2 * hidden_dim, name=f"film_{i}")(ce + te) + scale, shift = jnp.split(film, 2, -1) + r = r * (1.0 + 0.1 * scale) + 0.1 * shift + r = nn.silu(nn.Dense(2 * hidden_dim, name=f"up_{i}")(r)) + r = nn.Dense(hidden_dim, name=f"down_{i}")(r) + h = h + r / math.sqrt(num_layers) + return nn.Dense(y_dim, name="out")(nn.silu(h)) + + return ResidualVelocity() + + +def reader_from_npz(path): + return load_jax_reward_reader(path) + + +def parse_horizons(text): + """Parse expected geometric horizons H=1/(1-gamma).""" + values = np.asarray([float(x) for x in text.split(",") if x.strip()]) + if values.size == 0 or np.any(values <= 1.0): + raise ValueError("gamma horizons must be comma-separated values > 1") + if len(np.unique(values)) != len(values): + raise ValueError("gamma horizons must be unique") + return values.astype(np.float32) + + +def corr(x, y): + from scipy.stats import spearmanr + v = spearmanr(x, y).statistic + return float(v) if np.isfinite(v) else 0.0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--latents", required=True) + ap.add_argument("--reward_decoder", required=True) + ap.add_argument( + "--diagnostic_reward_decoder", default=None, + help="optional second frozen read-out used only after occupancy training") + ap.add_argument( + "--require_index_reader", action="store_true", + help="fail unless the primary post-training reader is immediate/index") + ap.add_argument("--out", required=True) + ap.add_argument("--ckpt", required=True) + ap.add_argument("--variant", required=True) + ap.add_argument( + "--state_key", choices=["z", "state_h"], default="z", + help="pixels-only current-state feature; occupancy targets remain z") + ap.add_argument( + "--goal_key", choices=["z", "state_h"], default="z", + help="pixels-only occupancy goal condition; target/reader goal remain z") + ap.add_argument("--model", choices=["diffusion", "flow"], default="diffusion") + ap.add_argument("--target", choices=["absolute", "delta"], default="absolute") + ap.add_argument("--arch", choices=["mlp", "residual"], default="mlp") + ap.add_argument("--sampler", choices=["stratified", "direct"], + default="stratified") + ap.add_argument( + "--gamma_sampler", + choices=["fixed", "legacy_log_uniform", "stratified_bins", + "short_iw", "action_priority"], + default="fixed", + help="training-discount proposal; every arm explicitly conditions on gamma") + ap.add_argument( + "--gamma_horizons", default="2,4,8,16,32,64", + help="auxiliary expected horizons H=1/(1-gamma)") + ap.add_argument( + "--gamma_eval_horizons", default="2,4,8,16,32,64,100", + help="held-out per-horizon diagnostic grid") + ap.add_argument( + "--gamma_task_fraction", type=float, default=0.5, + help="fraction fixed at task gamma for non-fixed curricula") + ap.add_argument( + "--short_priority_power", type=float, default=1.0, + help="short_iw proposal q(H) proportional to H^-power") + ap.add_argument("--spectrum_lo", type=float, default=0.0) + ap.add_argument("--spectrum_p", type=float, default=0.5) + ap.add_argument("--hidden", type=int, default=256) + ap.add_argument("--layers", type=int, default=3) + ap.add_argument("--time_dim", type=int, default=64) + ap.add_argument("--steps", type=int, default=50000) + ap.add_argument("--batch", type=int, default=2048) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--ema_tau", type=float, default=0.005) + ap.add_argument("--action_contrast_weight", type=float, default=0.0, + help="weight on reward-free conditional likelihood ranking") + ap.add_argument("--action_contrast_margin", type=float, default=0.1) + ap.add_argument("--action_negative", choices=["shuffle", "local"], + default="shuffle") + ap.add_argument("--action_negative_sigma", type=float, default=0.3) + ap.add_argument("--holdout_episodes", type=int, default=100) + ap.add_argument("--eval_rows", type=int, default=256) + ap.add_argument("--eval_samples", type=int, default=32) + ap.add_argument("--sample_steps", type=int, default=25) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + if args.spectrum_lo > 0 and args.gamma_sampler == "fixed": + # Backward-compatible interpretation of the original spectrum flags. + args.gamma_sampler = "legacy_log_uniform" + args.gamma_task_fraction = 1.0 - args.spectrum_p + if not 0.0 <= args.gamma_task_fraction <= 1.0: + ap.error("--gamma_task_fraction must lie in [0, 1]") + if args.short_priority_power < 0: + ap.error("--short_priority_power must be nonnegative") + + import jax + import jax.numpy as jnp + import optax + + ld = np.load(args.latents) + z = np.asarray(ld["z"], np.float32) + state = np.asarray(ld[args.state_key], np.float32) + goal_condition = np.asarray(ld[args.goal_key], np.float32) + actions = np.clip(np.asarray(ld["actions"], np.float32), -1.0, 1.0) + terminals = np.asarray(ld["terminals"], bool) + assert (len(state) == len(goal_condition) == len(z) + == len(actions) == len(terminals)) + assert args.state_key in ("z", "state_h") + assert args.goal_key in ("z", "state_h") + ends = build_ends(terminals) + ep_ends = np.flatnonzero(terminals) + 1 + ep_starts = np.r_[0, ep_ends[:-1]] + assert 0 < args.holdout_episodes < len(ep_ends) + train_n = int(ep_starts[-args.holdout_episodes]) + val_start = train_n + n_z = z.shape[1] + state_dim = state.shape[1] + goal_dim = goal_condition.shape[1] + a_dim = actions.shape[1] + gamma_horizons = parse_horizons(args.gamma_horizons) + eval_horizons = parse_horizons(args.gamma_eval_horizons) + if np.any(gamma_horizons > 100.0) or np.any(eval_horizons > 100.0): + ap.error("this screen evaluates task gamma=0.99; horizons must be <= 100") + gamma_values = 1.0 - 1.0 / gamma_horizons + eval_gammas = 1.0 - 1.0 / eval_horizons + g_cols = 2 * FOURIER_K + assert g_cols > 0, "discount encoding is mandatory for every occupancy arm" + cond_dim = state_dim + a_dim + goal_dim + g_cols + + z_d = jnp.asarray(z) + state_d = jnp.asarray(state) + goal_d = jnp.asarray(goal_condition) + a_d = jnp.asarray(actions) + end_d = jnp.asarray(ends.astype(np.int32)) + logg = float(np.log(GAMMA)) + enc_lo_h = float(np.log(2.0)) + enc_hi_h = float(np.log(100.0)) + freqs = jnp.asarray( + (np.pi * 2.0 ** np.arange(FOURIER_K)).astype(np.float32)) + gamma_values_d = jnp.asarray(gamma_values) + + if args.gamma_sampler == "short_iw": + aux_probs = gamma_horizons.astype(np.float64) ** ( + -args.short_priority_power) + elif args.gamma_sampler == "action_priority": + # Reward-free analytic proxy for first-action visibility: under the + # unshifted geometric occupancy, P(K=1)=(1-gamma)*gamma. + aux_probs = gamma_values.astype(np.float64) * ( + 1.0 - gamma_values.astype(np.float64)) + else: + aux_probs = np.ones(len(gamma_horizons), np.float64) + aux_probs /= aux_probs.sum() + aux_probs_d = jnp.asarray(aux_probs.astype(np.float32)) + legacy_lo_gamma = args.spectrum_lo if args.spectrum_lo > 0 else 0.90 + legacy_lo_log_h = float(np.log(1.0 / (1.0 - legacy_lo_gamma))) + task_count = int(round(args.gamma_task_fraction * args.batch)) + + def genc(gam): + u = ((jnp.log(1.0 / (1.0 - gam)) - enc_lo_h) + / (enc_hi_h - enc_lo_h)) + ang = u[:, None] * freqs[None] + return jnp.concatenate([jnp.sin(ang), jnp.cos(ang)], -1) + + def geom(k, shape): + u = jax.random.uniform(k, shape, minval=1e-6, maxval=1 - 1e-6) + return (jnp.floor(jnp.log1p(-u) / logg).astype(jnp.int32) + 1) + + def gammas(k, shape): + """Sample conditioning discounts and any proposal correction.""" + if args.gamma_sampler == "fixed": + return (jnp.full(shape, GAMMA), jnp.ones(shape), + jnp.full(shape, -1, jnp.int32)) + k_aux, k_perm = jax.random.split(k) + order = jax.random.permutation(k_perm, shape[0]) + base = jnp.arange(shape[0]) + is_task = (base < task_count)[order] + if args.gamma_sampler == "legacy_log_uniform": + log_h = jax.random.uniform( + k_aux, shape, minval=legacy_lo_log_h, + maxval=enc_hi_h) + draw = 1.0 - jnp.exp(-log_h) + aux_idx = jnp.full(shape, -2, jnp.int32) + iw = jnp.ones(shape) + elif args.gamma_sampler == "stratified_bins": + # Exact balanced coverage within every batch, then shuffled. + raw_idx = jnp.mod( + jnp.maximum(base - task_count, 0), len(gamma_horizons)) + aux_idx = raw_idx[order] + draw = gamma_values_d[aux_idx] + iw = jnp.ones(shape) + else: + aux_idx = jax.random.categorical( + k_aux, jnp.log(aux_probs_d), shape=shape) + draw = gamma_values_d[aux_idx] + if args.gamma_sampler == "short_iw": + # Correct the short-horizon proposal back to a uniform + # auxiliary-bin objective. The task-gamma branch is unchanged. + iw = 1.0 / ( + len(gamma_horizons) * aux_probs_d[aux_idx]) + else: + iw = jnp.ones(shape) + gam = jnp.where(is_task, GAMMA, draw) + weight = jnp.where(is_task, 1.0, iw) + bin_idx = jnp.where(is_task, -1, aux_idx) + return gam, weight, bin_idx + + def goals(k, t, random_hi): + """Reference GCIQL 20/50/30 value-goal mixture.""" + k1, k2, k3, k4 = jax.random.split(k, 4) + traj = jnp.minimum(t + geom(k1, t.shape), end_d[t] - 1) + rand = jax.random.randint(k2, t.shape, 0, random_hi) + use_traj = jax.random.uniform(k3, t.shape) < 0.5 / 0.8 + use_cur = jax.random.uniform(k4, t.shape) < 0.2 + gi = jnp.where(use_traj, traj, rand) + return jnp.where(use_cur, t, gi) + + def direct_future(k, t, gi, gam): + u = jax.random.uniform(k, t.shape, minval=1e-6, maxval=1 - 1e-6) + length = end_d[t] - t + lg = jnp.log(gam) + fmax = jnp.maximum(1.0 - jnp.exp(length * lg), 1e-12) + step = jnp.ceil(jnp.log1p(-u * fmax) / lg).astype(jnp.int32) - 1 + raw = t + jnp.clip(step, 0, length - 1) + intraj = (gi >= t) & (gi < end_d[t]) + return jnp.where(intraj, jnp.minimum(raw, gi), raw) + + def sample_tuple(k, lo, hi, random_hi, batch): + ks = jax.random.split(k, 8) + t = jax.random.randint(ks[0], (batch,), lo, hi) + gi = goals(ks[1], t, random_hi) + gam, gamma_weight, gamma_bin = gammas(ks[2], t.shape) + if args.sampler == "direct": + j = direct_future(ks[3], t, gi, gam) + weight = gamma_weight + else: + # Same unbiased absorbing-goal stratification as rsm.py. + lg = jnp.log(gam) + intraj = (gi >= t) & (gi < end_d[t]) + length = (end_d[t] - t).astype(jnp.float32) + dist = jnp.clip((gi - t).astype(jnp.float32), 0) + gL = jnp.exp(length * lg) + p_hit = jnp.where( + intraj, (jnp.exp(dist * lg) - gL) / (1.0 - gL), 0.0) + take = intraj & ( + (jax.random.uniform(ks[4], t.shape) < 0.5) | (gi == t)) + u = jax.random.uniform( + ks[5], t.shape, minval=1e-6, maxval=1 - 1e-6) + pd = 1.0 - jnp.exp(jnp.maximum(dist, 1.0) * lg) + km = jnp.ceil(jnp.log1p(-u * pd) / lg).astype(jnp.int32) - 1 + km = jnp.clip(km, 0, jnp.maximum(gi - t - 1, 0)) + raw = direct_future(ks[6], t, gi + end_d[t], gam) + j = jnp.where(take, gi, jnp.where(intraj, t + km, raw)) + weight = jnp.ones((batch,)) + weight = jnp.where( + take & (gi != t), p_hit / 0.5, weight) + weight = jnp.where( + intraj & ~take, (1.0 - p_hit) / 0.5, weight) + weight = weight * gamma_weight + parts = [state_d[t], a_d[t], goal_d[gi], genc(gam)] + assert len(parts) == 4 and g_cols > 0 + return (jnp.concatenate(parts, -1), z_d[j], z_d[t], weight, + t, gi, j, gam, gamma_bin, gamma_weight) + + # Fixed normalizers use tuples from the exact training curriculum and only + # training episodes. This is especially important for rich state_h input. + probe_sample = jax.jit(lambda k: sample_tuple( + k, 0, train_n, train_n, args.batch)) + probe_key = jax.random.PRNGKey(args.seed + 13) + probe_c, probe_yf, probe_zs = [], [], [] + probe_gammas, probe_bins, probe_gamma_weights = [], [], [] + probe_zero_offsets = [] + for _ in range(16): + probe_key, pk = jax.random.split(probe_key) + (pc, pyf, pzs, _, pt, pgi, pj, pgam, pbin, + pgamma_weight) = jax.device_get(probe_sample(pk)) + assert np.all(pj >= pt) + assert np.all(pj < ends[pt]) + intraj = (pgi >= pt) & (pgi < ends[pt]) + assert np.all(pj[intraj] <= pgi[intraj]) + task_mask = pbin == -1 + expected_task = args.batch if args.gamma_sampler == "fixed" else task_count + assert int(task_mask.sum()) == expected_task + assert np.all(pgamma_weight[task_mask] == 1.0), ( + "gamma prioritization must not reweight the task-gamma branch") + expected_enc = np.asarray(genc(jnp.asarray(pgam))) + assert np.max(np.abs(pc[:, -g_cols:] - expected_enc)) < 1e-6 + probe_c.append(pc) + probe_yf.append(pyf) + probe_zs.append(pzs) + probe_gammas.append(pgam) + probe_bins.append(pbin) + probe_gamma_weights.append(pgamma_weight) + probe_zero_offsets.append(pj == pt) + cp = np.concatenate(probe_c) + probe_yf = np.concatenate(probe_yf) + probe_zs = np.concatenate(probe_zs) + probe_gammas = np.concatenate(probe_gammas) + probe_bins = np.concatenate(probe_bins) + probe_gamma_weights = np.concatenate(probe_gamma_weights) + probe_zero_offsets = np.concatenate(probe_zero_offsets) + cond_mean_np = cp.mean(0) + cond_std_np = cp.std(0) + 1e-6 + # Fourier discount features already have a fixed [-1, 1] scale. Do not + # normalize them by curriculum-specific statistics: that would confound + # the sampler comparison and make fixed-gamma controls explode off-support. + cond_mean_np[-g_cols:] = 0.0 + cond_std_np[-g_cols:] = 1.0 + cond_mean = jnp.asarray(cond_mean_np) + cond_std = jnp.asarray(cond_std_np) + assert cond_mean.shape[0] == cond_dim + raw_target = (probe_yf if args.target == "absolute" + else probe_yf - probe_zs) + if args.target == "absolute": + y_mean = jnp.asarray(z[:train_n].mean(0)) + y_std = jnp.asarray(z[:train_n].std(0) + 1e-6) + else: + y_mean = jnp.asarray(raw_target.mean(0)) + y_std = jnp.asarray(raw_target.std(0) + 1e-6) + + model = (make_model(cond_dim, n_z, args.hidden, args.layers, args.time_dim) + if args.arch == "mlp" else + make_residual_model( + cond_dim, n_z, args.hidden, args.layers, args.time_dim)) + key = jax.random.PRNGKey(args.seed) + key, init_key = jax.random.split(key) + params = model.init( + init_key, jnp.zeros((1, n_z)), jnp.zeros((1,)), + jnp.zeros((1, cond_dim))) + tx = optax.chain(optax.clip_by_global_norm(10), optax.adamw(args.lr)) + opt = tx.init(params) + ema = jax.tree_util.tree_map(lambda x: x, params) + abar = jnp.asarray(cosine_abar(OCC_T)) + + def train_step(carry, _): + p, o, e, k = carry + k, kt, kn, ku, ka = jax.random.split(k, 5) + c, yf, zs, w, *_ = sample_tuple( + kt, 0, train_n, train_n, args.batch) + y = yf if args.target == "absolute" else yf - zs + yn = (y - y_mean) / y_std + cn = (c - cond_mean) / cond_std + + if args.model == "diffusion": + ti = jax.random.randint(kn, (args.batch,), 1, OCC_T + 1) + noise = jax.random.normal(ku, yn.shape) + ab = abar[ti - 1][:, None] + xt = jnp.sqrt(ab) * yn + jnp.sqrt(1.0 - ab) * noise + tf = ti.astype(jnp.float32) / OCC_T + target = noise + else: + tf = jax.random.uniform(kn, (args.batch,)) + noise = jax.random.normal(ku, yn.shape) + xt = (1.0 - tf[:, None]) * noise + tf[:, None] * yn + target = yn - noise + + def loss_fn(pp): + pred = model.apply(pp, xt, tf, cn) + err = jnp.mean((pred - target) ** 2, -1) + base = jnp.mean(w * err) + if args.action_contrast_weight <= 0: + return base + if args.action_negative == "shuffle": + neg_action = jnp.roll( + c[:, state_dim:state_dim + a_dim], 1, axis=0) + else: + neg_action = jnp.clip( + c[:, state_dim:state_dim + a_dim] + + args.action_negative_sigma * jax.random.normal( + ka, (args.batch, a_dim)), -1.0, 1.0) + cneg = c.at[:, state_dim:state_dim + a_dim].set(neg_action) + cneg = (cneg - cond_mean) / cond_std + pred_neg = model.apply(pp, xt, tf, cneg) + err_neg = jnp.mean((pred_neg - target) ** 2, -1) + rank = jax.nn.softplus( + args.action_contrast_margin + err - err_neg).mean() + return base + args.action_contrast_weight * rank + + loss, grad = jax.value_and_grad(loss_fn)(p) + upd, o = tx.update(grad, o, p) + p = optax.apply_updates(p, upd) + e = jax.tree_util.tree_map( + lambda ee, pp: ee * (1 - args.ema_tau) + pp * args.ema_tau, + e, p) + return (p, o, e, k), loss + + dispatch_len = 100 + dispatch = jax.jit(lambda carry: jax.lax.scan( + train_step, carry, None, length=dispatch_len)) + carry = (params, opt, ema, key) + start = time.time() + for step in range(dispatch_len, args.steps + 1, dispatch_len): + carry, losses = dispatch(carry) + if step % 5000 == 0 or step == args.steps: + print(f"[{args.variant}] step={step} loss={float(losses.mean()):.5f} " + f"elapsed={time.time() - start:.1f}s", flush=True) + params, opt, ema, key = carry + + # ---------------- held-out control-relevant evaluation ---------------- + # Readers are intentionally loaded only after occupancy fitting. They do + # not participate in tuple sampling, flow matching, or action contrast. + read_logits, reader_meta = reader_from_npz(args.reward_decoder) + if args.require_index_reader: + assert reader_meta["target"] == "index", ( + "primary policy read-out must be the immediate/index reader") + if args.diagnostic_reward_decoder: + diag_logits, diag_reader_meta = reader_from_npz( + args.diagnostic_reward_decoder) + else: + diag_logits, diag_reader_meta = read_logits, None + ts = np.unique(np.linspace(OCC_T, 1, args.sample_steps).round().astype( + np.int32))[::-1].copy() + ts0 = jnp.asarray(ts) + ts1 = jnp.asarray(np.r_[ts[1:], 0].astype(np.int32)) + + def sample_model(s, zs, a, gc, gam, noise): + b, m, _ = noise.shape + parts = [s, a, gc, genc(gam)] + assert len(parts) == 4 and g_cols > 0 + c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std + cc = jnp.repeat(c, m, 0) + x = noise.reshape(b * m, n_z) + zzs = jnp.repeat(zs, m, 0) + if args.model == "diffusion": + def body(xn, ii): + tn, tx_ = ts0[ii], ts1[ii] + abn = abar[tn - 1] + abx = jnp.where( + tx_ > 0, abar[jnp.maximum(tx_ - 1, 0)], 1.0) + eps = jnp.clip(model.apply( + ema, xn, + jnp.full((b * m,), tn.astype(jnp.float32) / OCC_T), + cc), -6, 6) + y0 = (xn - jnp.sqrt(1 - abn) * eps) / jnp.sqrt( + jnp.maximum(abn, 1e-8)) + return jnp.sqrt(abx) * y0 + jnp.sqrt(1 - abx) * eps, None + x, _ = jax.lax.scan(body, x, jnp.arange(len(ts))) + else: + dt = 1.0 / args.sample_steps + def body(xn, ii): + tf = jnp.full((b * m,), ii.astype(jnp.float32) * dt) + v = model.apply(ema, xn, tf, cc) + return xn + dt * v, None + x, _ = jax.lax.scan( + body, x, jnp.arange(args.sample_steps)) + raw = x * y_std + y_mean + if args.target == "delta": + raw = raw + zzs + return raw.reshape(b, m, n_z) + + def q_model(s, zs, a, gc, gz, gam, noise): + pred = sample_model(s, zs, a, gc, gam, noise) + b, m, _ = pred.shape + gg = jnp.repeat(gz, m, 0) + qp = jax.nn.sigmoid(read_logits( + pred.reshape(b * m, n_z), gg)).reshape(b, m).mean(-1) + qd = jax.nn.sigmoid(diag_logits( + pred.reshape(b * m, n_z), gg)).reshape(b, m).mean(-1) + return qp, qd, pred + + qjit = jax.jit(q_model) + val_rng = np.random.default_rng(args.seed + 991) + val_candidates = np.arange(val_start, len(z) - 1) + val_candidates = val_candidates[ends[val_candidates] - val_candidates > 1] + vr = val_rng.choice(val_candidates, args.eval_rows, replace=False) + span = ends[vr] - vr - 1 + vg_idx = vr + 1 + (val_rng.random(args.eval_rows) * span).astype(np.int64) + vg_idx = np.minimum(vg_idx, ends[vr] - 1) + vs = state[vr] + vzs = z[vr] + va = actions[vr] + vgc = goal_condition[vg_idx] + vgz = z[vg_idx] + noise = val_rng.standard_normal( + (args.eval_rows, args.eval_samples, n_z)).astype(np.float32) + + # Vectorized exact finite-episode absorbing occupancy. Keeping one static + # [B, max_episode_len] shape avoids recompiling the reader for every + # different remaining trajectory length. + max_len = int(np.max(ends[vr] - vr)) + raw_k = np.arange(max_len)[None, :] + valid = raw_k < (ends[vr] - vr)[:, None] + mapped = np.minimum(vr[:, None] + raw_k, vg_idx[:, None]) + fut = z[mapped] + gg = np.repeat(vgz[:, None, :], max_len, axis=1) + primary_logits = np.asarray(read_logits( + jnp.asarray(fut.reshape(-1, n_z)), + jnp.asarray(gg.reshape(-1, n_z)))).reshape(args.eval_rows, max_len) + primary_reward = 1.0 / ( + 1.0 + np.exp(-np.clip(primary_logits, -30, 30))) + diag_raw_logits = np.asarray(diag_logits( + jnp.asarray(fut.reshape(-1, n_z)), + jnp.asarray(gg.reshape(-1, n_z)))).reshape(args.eval_rows, max_len) + diag_reward = 1.0 / ( + 1.0 + np.exp(-np.clip(diag_raw_logits, -30, 30))) + perm = val_rng.permutation(args.eval_rows) + kact = 8 + cand = np.clip( + va[:, None] + 0.3 * val_rng.standard_normal( + (args.eval_rows, kact, a_dim)), -1, 1).astype(np.float32) + cand[:, 0] = va + sf = np.repeat(vs[:, None], kact, 1).reshape(-1, state_dim) + zsf = np.repeat(vzs[:, None], kact, 1).reshape(-1, n_z) + gcf = np.repeat(vgc[:, None], kact, 1).reshape(-1, goal_dim) + gzf = np.repeat(vgz[:, None], kact, 1).reshape(-1, n_z) + nf = np.repeat(noise[:, None], kact, 1).reshape( + -1, args.eval_samples, n_z) + + latent_sd = z[:train_n].std(0) + 1e-6 + + def reward_metrics(qm, qe): + qmae = float(np.mean(np.abs(qm - qe))) + return { + "empirical_mean": float(qe.mean()), + "empirical_std": float(qe.std()), + "model_mean": float(qm.mean()), + "mae": qmae, + "normalized_mae": qmae / max(float(qe.std()), 1e-8), + "spearman": corr(qm, qe), + } + + per_horizon = {} + for horizon, gamma in zip(eval_horizons.tolist(), eval_gammas.tolist()): + gam = np.full((args.eval_rows,), gamma, np.float32) + qm, qdm, pred = qjit( + jnp.asarray(vs), jnp.asarray(vzs), jnp.asarray(va), + jnp.asarray(vgc), jnp.asarray(vgz), jnp.asarray(gam), + jnp.asarray(noise)) + qm, qdm, pred = np.asarray(qm), np.asarray(qdm), np.asarray(pred) + qshuf, qdshuf, _ = qjit( + jnp.asarray(vs), jnp.asarray(vzs), jnp.asarray(va[perm]), + jnp.asarray(vgc), jnp.asarray(vgz), jnp.asarray(gam), + jnp.asarray(noise)) + qshuf, qdshuf = np.asarray(qshuf), np.asarray(qdshuf) + gamf = np.full((args.eval_rows * kact,), gamma, np.float32) + qc, qdc, _ = qjit( + jnp.asarray(sf), jnp.asarray(zsf), + jnp.asarray(cand.reshape(-1, a_dim)), jnp.asarray(gcf), + jnp.asarray(gzf), jnp.asarray(gamf), jnp.asarray(nf)) + qc = np.asarray(qc).reshape(args.eval_rows, kact) + qdc = np.asarray(qdc).reshape(args.eval_rows, kact) + + prob = (float(gamma) ** raw_k.astype(np.float64)) * valid + prob /= prob.sum(1, keepdims=True) + qe = np.sum(prob * primary_reward, 1).astype(np.float32) + qde = np.sum(prob * diag_reward, 1).astype(np.float32) + me = np.sum(prob[:, :, None] * fut, 1).astype(np.float32) + ve = np.sum( + prob[:, :, None] * (fut - me[:, None, :]) ** 2, 1).astype( + np.float32) + mm, vm = pred.mean(1), pred.var(1) + key_h = f"H{horizon:g}_g{float(gamma):.6f}" + per_horizon[key_h] = { + "horizon": float(horizon), + "gamma": float(gamma), + "primary_reward_expectation": reward_metrics(qm, qe), + "diagnostic_reward_expectation": ( + reward_metrics(qdm, qde) + if diag_reader_meta is not None else None), + "future_moments": { + "mean_rmse_in_latent_sd": float(np.sqrt(np.mean( + ((mm - me) / latent_sd) ** 2))), + "variance_rmse_in_latent_var": float(np.sqrt(np.mean( + ((vm - ve) / latent_sd ** 2) ** 2))), + "model_variance_ratio": float( + vm.mean() / max(float(ve.mean()), 1e-8)), + }, + "primary_action_signal": { + "q_shuffle_abs_delta": float( + np.mean(np.abs(qshuf - qm))), + "local_candidate_q_span_mean": float( + np.mean(qc.max(1) - qc.min(1))), + "data_action_best_of_8_rate": float( + np.mean(np.argmax(qc, 1) == 0)), + }, + "diagnostic_action_signal": ({ + "q_shuffle_abs_delta": float( + np.mean(np.abs(qdshuf - qdm))), + "local_candidate_q_span_mean": float( + np.mean(qdc.max(1) - qdc.min(1))), + "data_action_best_of_8_rate": float( + np.mean(np.argmax(qdc, 1) == 0)), + } if diag_reader_meta is not None else None), + } + + task_key = min( + per_horizon, + key=lambda k: abs(per_horizon[k]["gamma"] - GAMMA)) + task_eval = per_horizon[task_key] + assert abs(task_eval["gamma"] - GAMMA) < 1e-6, ( + "--gamma_eval_horizons must include task horizon 100") + + if args.gamma_sampler == "fixed": + gamma_support = { + "kind": "point_mass", + "horizons": [100.0], + "gammas": [GAMMA], + "proposal_probabilities": [1.0], + "importance_weighted": False, + } + elif args.gamma_sampler == "legacy_log_uniform": + gamma_support = { + "kind": "task_plus_continuous_log_uniform_horizon", + "task_fraction": args.gamma_task_fraction, + "aux_horizon_range": [ + float(1.0 / (1.0 - legacy_lo_gamma)), 100.0], + "importance_weighted": False, + } + else: + gamma_support = { + "kind": "task_plus_discrete_auxiliary", + "task_fraction": args.gamma_task_fraction, + "aux_horizons": gamma_horizons.astype(float).tolist(), + "aux_gammas": gamma_values.astype(float).tolist(), + "aux_proposal_probabilities": aux_probs.astype(float).tolist(), + "importance_weighted": args.gamma_sampler == "short_iw", + "importance_target": ( + "uniform_auxiliary_bins" + if args.gamma_sampler == "short_iw" else None), + } + + probe_horizons = 1.0 / (1.0 - probe_gammas.astype(np.float64)) + proposal_probe = { + "rows": int(len(probe_gammas)), + "task_branch_fraction": float(np.mean(probe_bins == -1)), + "gamma_weight_task_min": float( + probe_gamma_weights[probe_bins == -1].min()), + "gamma_weight_task_max": float( + probe_gamma_weights[probe_bins == -1].max()), + "gamma_weight_all_mean": float(probe_gamma_weights.mean()), + "gamma_weight_all_max": float(probe_gamma_weights.max()), + "sampled_horizon_quantiles": { + "p10": float(np.quantile(probe_horizons, 0.1)), + "p50": float(np.quantile(probe_horizons, 0.5)), + "p90": float(np.quantile(probe_horizons, 0.9)), + }, + "zero_offset_fraction": float(probe_zero_offsets.mean()), + "offset_support": "unshifted_k_ge_0", + } + if args.gamma_sampler not in ("fixed", "legacy_log_uniform"): + proposal_probe["aux_bin_counts"] = { + f"H{float(h):g}": int(np.sum(probe_bins == i)) + for i, h in enumerate(gamma_horizons)} + if args.gamma_sampler == "short_iw": + denom = float(probe_gamma_weights[probe_bins >= 0].sum()) + proposal_probe["importance_weighted_aux_bin_mass"] = { + f"H{float(h):g}": float( + probe_gamma_weights[probe_bins == i].sum() / denom) + for i, h in enumerate(gamma_horizons)} + + def feature_name(key): + return ("frozen_pixel_encoder_fc0_hidden" + if key == "state_h" + else "frozen_pixel_encoder_reward_latent_z") + + metrics = { + "variant": args.variant, + "fairness": { + "drop_proprio": True, + "pixels_only": True, + "uses_coordinates": False, + "occupancy_uses_reward_labels": False, + "discount_conditioned": True, + "discount_encoding": "log_horizon_fourier_k4", + "occupancy_definition": ( + "(1-gamma)*sum_{k>=0} gamma^k P(z_{t+k}|s_t,a_t,g)"), + "shifted_occupancy": False, + "occupancy_state_condition_feature": feature_name(args.state_key), + "occupancy_goal_condition_feature": feature_name(args.goal_key), + "occupancy_future_target_feature": ( + "frozen_pixel_encoder_reward_latent_z"), + "reward_reader_goal_feature": ( + "frozen_pixel_encoder_reward_latent_z"), + "objective": ( + f"{args.model}_matching_plus_reward_free_action_contrast_no_td"), + "uses_td_or_bootstrap": False, + "uses_world_model_rollout": False, + "external_action_proposer": False, + }, + "training": { + "model": args.model, "target": args.target, "arch": args.arch, + "future_sampler": args.sampler, + "gamma_sampler": args.gamma_sampler, + "gamma_support": gamma_support, + "gamma_proposal_probe": proposal_probe, + "state_key": args.state_key, + "state_dim": state_dim, + "goal_key": args.goal_key, + "goal_dim": goal_dim, + "future_target_key": "z", + "future_target_dim": n_z, + "reward_reader_goal_key": "z", + "reward_reader_goal_dim": n_z, + "discount_conditioned": True, + "hidden": args.hidden, "layers": args.layers, + "steps": args.steps, "batch": args.batch, + "train_episodes": int(len(ep_ends) - args.holdout_episodes), + "holdout_episodes": args.holdout_episodes, + "wall_sec": round(time.time() - start, 2), + "final_loss": float(losses.mean()), + }, + "readers": { + "primary_policy_readout": reader_meta, + "diagnostic_return_readout": diag_reader_meta, + "readers_used_during_occupancy_training": False, + }, + "task_gamma_key": task_key, + "heldout_reward_expectation": task_eval[ + "primary_reward_expectation"], + "heldout_future_moments": task_eval["future_moments"], + "heldout_action_signal": task_eval["primary_action_signal"], + "per_horizon": per_horizon, + } + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as f: + json.dump(metrics, f, indent=2) + os.makedirs(os.path.dirname(os.path.abspath(args.ckpt)), exist_ok=True) + with open(args.ckpt, "wb") as f: + pickle.dump({ + "occupancy": jax.device_get((params, opt, ema)), + "config": vars(args), + "fairness": metrics["fairness"], + "gamma_support": gamma_support, + "normalization": { + "cond_mean": np.asarray(cond_mean), + "cond_std": np.asarray(cond_std), + "y_mean": np.asarray(y_mean), + "y_std": np.asarray(y_std), + }, + "metrics": metrics, + }, f) + print(json.dumps(metrics, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/train_visual_rich_gcbc.py b/gen_q_rsm/ogbench_genq/genq/train_visual_rich_gcbc.py new file mode 100644 index 0000000000000000000000000000000000000000..95c16251fd1fca3870566e6b5b5825bce7b3f64f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/train_visual_rich_gcbc.py @@ -0,0 +1,264 @@ +"""Pixels-only visual GCBC on frozen rich encoder features. + +This is a representation gate, not an RSM experiment. It deliberately has no +occupancy model, reward, critic, temporal-difference target, simulator state, +or proprioception. Both the current observation and the future trajectory +goal are the frozen pixel encoder's 256-dimensional ``fc_0`` hidden feature. + +The goal sampler and actor match OGBench GCBC: the goal is sampled uniformly +from the remainder of the current offline trajectory, and a 3x512 MLP Gaussian +actor is optimized by action log likelihood. +""" + +import argparse +import json +import os +import pickle +import time + +import numpy as np + + +STEPS_PER_DISPATCH = 100 + + +def _atomic_pickle(path, value): + os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) + tmp = path + ".tmp" + with open(tmp, "wb") as f: + pickle.dump(value, f) + os.replace(tmp, path) + + +def _metadata(args, state_dim, compact_z_dim, action_dim): + return { + "schema_version": 1, + "method": "visual_rich_gcbc", + "env": args.env, + "seed": int(args.seed), + "drop_proprio": True, + "pixels_only": True, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "state_dim": int(state_dim), + "actor_goal_dim": int(state_dim), + # These compact features are recorded to make the representation + # separation explicit. They are not consumed by this BC-only gate. + "future_feature": "compact_reward_predictive_z_unused", + "reward_goal_feature": "compact_reward_predictive_z_unused", + "compact_z_dim": int(compact_z_dim), + "action_dim": int(action_dim), + "goal_sampling": "uniform_future_same_trajectory", + "actor_hidden_dims": [512, 512, 512], + "batch_size": int(args.batch_size), + "learning_rate": float(args.lr), + "train_steps": int(args.train_steps), + "uses_occupancy": False, + "uses_reward": False, + "uses_td": False, + "latent_npz": os.path.abspath(args.latent_npz), + "pixel_encoder": os.path.abspath(args.pixel_encoder), + } + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--env", default="visual-cube-single-play-v0") + ap.add_argument("--latent_npz", required=True) + ap.add_argument("--pixel_encoder", required=True) + ap.add_argument("--ckpt", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300_000) + ap.add_argument("--batch_size", type=int, default=1024) + ap.add_argument("--lr", type=float, default=3e-4) + ap.add_argument("--ckpt_every", type=int, default=10_000) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--train_only", action="store_true") + ap.add_argument("--eval_only", action="store_true") + args = ap.parse_args() + + assert args.train_only != args.eval_only, ( + "choose exactly one of --train_only and --eval_only") + assert args.train_steps % STEPS_PER_DISPATCH == 0 + assert args.ckpt_every % STEPS_PER_DISPATCH == 0 + + impls = os.environ.get( + "OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls")) + import sys + pkg_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + sys.path[:0] = [os.path.dirname(pkg_dir), pkg_dir, + os.path.join(pkg_dir, "genq"), impls] + + import jax + import jax.numpy as jnp + import optax + from agents.gcbc import get_config + from utils.evaluation import evaluate + from utils.networks import GCActor + from ogbench_genq._runner import _make_eval_fn + from ogbench_genq.genq.train_genq_jax import build_ends + from ogbench_genq.pixel_eval import make_latent_eval_env + + with np.load(args.latent_npz) as ld: + assert "state_h" in ld.files, ( + "rich GCBC requires the frozen encoder hidden feature `state_h`") + state_h = np.asarray(ld["state_h"], np.float32) + compact_z = np.asarray(ld["z"], np.float32) + actions = np.clip(np.asarray(ld["actions"], np.float32), -1.0, 1.0) + ends = build_ends(np.asarray(ld["terminals"])) + + assert state_h.ndim == 2 and compact_z.ndim == 2 and actions.ndim == 2 + assert len(state_h) == len(compact_z) == len(actions) == len(ends) + assert state_h.shape[1] == 256, state_h.shape + assert np.isfinite(state_h).all() and np.isfinite(actions).all() + assert os.path.isfile(args.pixel_encoder) + + n_rows, state_dim = state_h.shape + action_dim = actions.shape[1] + meta = _metadata(args, state_dim, compact_z.shape[1], action_dim) + config = get_config() + config["batch_size"] = int(args.batch_size) + config["lr"] = float(args.lr) + + actor_def = GCActor( + hidden_dims=tuple(config["actor_hidden_dims"]), + action_dim=action_dim, + state_dependent_std=False, + const_std=config["const_std"], + ) + key = jax.random.PRNGKey(args.seed) + key, init_key = jax.random.split(key) + params = actor_def.init( + init_key, np.zeros((2, state_dim), np.float32), + np.zeros((2, state_dim), np.float32))["params"] + tx = optax.adam(args.lr) + opt_state = tx.init(params) + step = 0 + wall_offset = 0.0 + + if os.path.exists(args.ckpt): + with open(args.ckpt, "rb") as f: + saved = pickle.load(f) + if saved["metadata"] != meta: + raise ValueError( + "checkpoint metadata mismatch:\n" + f"saved={saved['metadata']}\nrequested={meta}") + params = jax.device_put(saved["params"]) + opt_state = jax.device_put(saved["opt_state"]) + key = jax.device_put(saved["key"]) + step = int(saved["step"]) + wall_offset = float(saved.get("wall_clock_sec", 0.0)) + print(f"[rich-gcbc] RESUMED step {step}/{args.train_steps}", flush=True) + elif args.eval_only: + raise FileNotFoundError(args.ckpt) + + @jax.jit + def eval_action(pp, observations, goals): + dist = actor_def.apply({"params": pp}, observations, goals) + return jnp.clip(dist.mode(), -1.0, 1.0) + + class EvalAgent: + def __init__(self, pp): + self.params = pp + + def sample_actions( + self, observations, goals=None, seed=None, temperature=0.0): + return eval_action(self.params, observations, goals) + + if args.eval_only: + os.environ.setdefault("MUJOCO_GL", "egl") + env = make_latent_eval_env( + args.env, args.pixel_encoder, drop_proprio=True, + state_hidden=True, goal_hidden=True) + eval_success = _make_eval_fn( + env, config, evaluate, jax, wrap=lambda pp: EvalAgent(pp)) + started = time.time() + success, per_task = eval_success(params, args.eval_episodes) + result = { + **meta, + "eval_episodes": int(args.eval_episodes), + "success_rate": float(success), + "per_task": per_task, + "checkpoint_step": step, + "wall_clock_sec": round(wall_offset + time.time() - started, 1), + } + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as f: + json.dump(result, f, indent=2) + print( + f"[rich-gcbc] OFFICIAL success={success:.3f} " + f"per_task={per_task} -> {args.out}", flush=True) + os._exit(0) # avoid the known MuJoCo EGL interpreter-teardown crash + + states_d = jnp.asarray(state_h) + actions_d = jnp.asarray(actions) + ends_d = jnp.asarray(ends.astype(np.int32)) + + def one_step(carry, _): + pp, oo, kk, st = carry + kk, kt, kg = jax.random.split(kk, 3) + rows = jax.random.randint(kt, (args.batch_size,), 0, n_rows) + final_rows = ends_d[rows] - 1 + first_goal = jnp.minimum(rows + 1, final_rows) + frac = jax.random.uniform(kg, (args.batch_size,)) + goal_rows = jnp.round( + first_goal.astype(jnp.float32) * frac + + final_rows.astype(jnp.float32) * (1.0 - frac) + ).astype(jnp.int32) + + def loss_fn(p): + dist = actor_def.apply( + {"params": p}, states_d[rows], states_d[goal_rows]) + return -dist.log_prob(actions_d[rows]).mean() + + loss, grads = jax.value_and_grad(loss_fn)(pp) + updates, oo = tx.update(grads, oo, pp) + pp = optax.apply_updates(pp, updates) + return (pp, oo, kk, st + 1), loss + + dispatch = jax.jit( + lambda carry: jax.lax.scan( + one_step, carry, None, length=STEPS_PER_DISPATCH)) + carry = (params, opt_state, key, jnp.asarray(step)) + started = time.time() + first_dispatch = True + while step < args.train_steps: + carry, losses = dispatch(carry) + step += STEPS_PER_DISPATCH + if first_dispatch: + jax.block_until_ready(carry[0]) + first_dispatch = False + print("[rich-gcbc] compiled", flush=True) + if step % 1_000 == 0: + print( + f"[rich-gcbc] step {step}/{args.train_steps} " + f"loss={float(losses.mean()):.5f}", flush=True) + if step % args.ckpt_every == 0 or step == args.train_steps: + params, opt_state, key, _ = carry + _atomic_pickle(args.ckpt, { + "params": jax.device_get(params), + "opt_state": jax.device_get(opt_state), + "key": jax.device_get(key), + "step": step, + "wall_clock_sec": ( + wall_offset + time.time() - started), + "metadata": meta, + }) + + result = { + **meta, + "status": "train_only_complete", + "checkpoint_step": step, + "success_rate": None, + "per_task": [], + "wall_clock_sec": round(wall_offset + time.time() - started, 1), + } + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, "w") as f: + json.dump(result, f, indent=2) + print(f"[rich-gcbc] TRAIN complete -> {args.ckpt}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/genq/visual_recursion_sweep_contract.py b/gen_q_rsm/ogbench_genq/genq/visual_recursion_sweep_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..526e39c47d9087952a8bdc5afeaaf9615d551d23 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/genq/visual_recursion_sweep_contract.py @@ -0,0 +1,750 @@ +"""Static contract checks for the fair visual RSM recursion sweep. + +The sweep is intentionally configured from a small, auditable TSV rather than +an open-ended hyperparameter launcher. This module validates the +distributional recursion arithmetic, the fixed no-cheating reader provenance, +and the one-hop quality gate used by the scheduler wrapper. + +It does not import an environment, inspect simulator coordinates, or submit +jobs. +""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +import os +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +from ogbench_genq.rsm import ( + occupancy_recursion_continuation, + occupancy_recursion_tail_mass, +) + + +TAIL_CAP = 5e-4 +CALIBRATION_STEPS = 50_000 +CONTINUATION_STEPS = 100_000 +NO_COMPOSITION_AFTER = 1_000_000_000 +PINNED_READER_TAG = "indexd4_diagmetric" +PINNED_READER_SHA256 = ( + "9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7" +) +EXPECTED_HEADER = ( + "cell", + "composition", + "gamma", + "beta", + "depth", + "continuation", + "cap_mass", + "beta_mass", + "gamma_horizons", + "rec_after", + "reader_tag", + "reader_sha256", + "rationale", +) +EXPECTED_RECIPES = { + ("on", 0.99, 0.985, 8, 0.25), + ("on", 0.99, 0.98, 12, 0.25), + ("on", 0.99, 0.97, 20, 0.25), + ("on", 0.98, 0.96, 12, 0.25), + ("off", 0.99, 0.98, 12, 0.25), + ("on", 0.99, 0.98, 12, 0.40), +} +_SAFE_CELL = re.compile(r"^[A-Za-z0-9._-]+$") +_SHA256 = re.compile(r"^[0-9a-f]{64}$") + + +@dataclass(frozen=True) +class RecursionCell: + """One fully specified recursion sweep cell.""" + + cell: str + composition: str + gamma: float + beta: float + depth: int + continuation: float + cap_mass: float + beta_mass: float + gamma_horizons: str + rec_after: str + reader_tag: str + reader_sha256: str + rationale: str + + @property + def recipe(self) -> tuple[str, float, float, int, float]: + return ( + self.composition, + self.gamma, + self.beta, + self.depth, + self.beta_mass, + ) + + +@dataclass(frozen=True) +class ContinuationGate: + """Validated immutable inputs for one recursive continuation cell.""" + + cell: str + gate_path: str + gate_sha256: str + source_checkpoint: str + source_checkpoint_sha256: str + source_checkpoint_step: int + source_seed: int + reader_path: str + reader_sha256: str + + +def file_sha256(path: str | Path) -> str: + """Return a streaming SHA-256 digest for ``path``.""" + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _parse_horizons(value: str) -> tuple[float, ...]: + horizons = tuple(float(piece) for piece in value.split(",")) + if not horizons: + raise ValueError("gamma_horizons must not be empty") + if not all(math.isfinite(horizon) and horizon > 1.0 for horizon in horizons): + raise ValueError( + f"all gamma_horizons must be finite and >1, got {value!r}" + ) + if not all(a < b for a, b in zip(horizons[:-1], horizons[1:])): + raise ValueError( + f"gamma_horizons must be strictly increasing, got {value!r}" + ) + return horizons + + +def _cell_from_row(row: dict[str, str], line_number: int) -> RecursionCell: + try: + cell = RecursionCell( + cell=row["cell"], + composition=row["composition"], + gamma=float(row["gamma"]), + beta=float(row["beta"]), + depth=int(row["depth"]), + continuation=float(row["continuation"]), + cap_mass=float(row["cap_mass"]), + beta_mass=float(row["beta_mass"]), + gamma_horizons=row["gamma_horizons"], + rec_after=row["rec_after"], + reader_tag=row["reader_tag"], + reader_sha256=row["reader_sha256"], + rationale=row["rationale"], + ) + except (KeyError, TypeError, ValueError) as error: + raise ValueError(f"invalid manifest row {line_number}: {error}") from error + return cell + + +def validate_cell(cell: RecursionCell) -> None: + """Validate one row against the mathematical and fairness contract.""" + if not _SAFE_CELL.fullmatch(cell.cell): + raise ValueError(f"unsafe cell name: {cell.cell!r}") + if cell.composition not in {"on", "off"}: + raise ValueError( + f"{cell.cell}: composition must be 'on' or 'off', " + f"got {cell.composition!r}" + ) + if cell.depth < 1: + raise ValueError(f"{cell.cell}: depth must be positive") + + continuation = occupancy_recursion_continuation(cell.gamma, cell.beta) + cap_mass = occupancy_recursion_tail_mass( + cell.gamma, cell.beta, cell.depth + ) + if not math.isclose( + cell.continuation, continuation, rel_tol=1e-12, abs_tol=1e-15 + ): + raise ValueError( + f"{cell.cell}: continuation mismatch: manifest={cell.continuation} " + f"computed={continuation}" + ) + if not math.isclose( + cell.cap_mass, cap_mass, rel_tol=1e-12, abs_tol=1e-15 + ): + raise ValueError( + f"{cell.cell}: cap_mass mismatch: manifest={cell.cap_mass} " + f"computed={cap_mass}" + ) + if cap_mass > TAIL_CAP: + raise ValueError( + f"{cell.cell}: cap_mass={cap_mass:.9g} exceeds {TAIL_CAP:.9g}" + ) + + # Gamma occupies exactly half of every batch. Beta is an exact query + # inside the other half, leaving the residual for shorter-horizon bins. + if not (0.0 < cell.beta_mass < 0.5): + raise ValueError( + f"{cell.cell}: beta_mass must leave positive auxiliary mass " + f"under gamma_task_fraction=0.5" + ) + horizons = _parse_horizons(cell.gamma_horizons) + auxiliary_gammas = tuple(1.0 - 1.0 / horizon for horizon in horizons) + if max(auxiliary_gammas) >= cell.gamma: + raise ValueError( + f"{cell.cell}: an auxiliary horizon reaches/exceeds task gamma" + ) + + if not cell.rec_after.isdigit(): + raise ValueError( + f"{cell.cell}: rec_after must be a nonnegative integer" + ) + rec_after = int(cell.rec_after) + if rec_after < CALIBRATION_STEPS: + raise ValueError( + f"{cell.cell}: rec_after={rec_after} would activate composition " + f"inside the {CALIBRATION_STEPS}-step one-hop calibration" + ) + if cell.composition == "on": + if rec_after != CALIBRATION_STEPS: + raise ValueError( + f"{cell.cell}: composing arms must start immediately after " + f"the {CALIBRATION_STEPS}-step gated checkpoint" + ) + elif rec_after != NO_COMPOSITION_AFTER: + raise ValueError( + f"{cell.cell}: matched no-composition control must use fixed " + f"rec_after={NO_COMPOSITION_AFTER}" + ) + + if cell.reader_tag != PINNED_READER_TAG: + raise ValueError( + f"{cell.cell}: reader_tag={cell.reader_tag!r}, expected " + f"{PINNED_READER_TAG!r}" + ) + if cell.reader_sha256 != PINNED_READER_SHA256: + raise ValueError( + f"{cell.cell}: reader SHA-256 is not the frozen diagonal reader" + ) + if not cell.rationale.strip(): + raise ValueError(f"{cell.cell}: rationale must not be empty") + + +def load_manifest(path: str | Path) -> tuple[RecursionCell, ...]: + """Load and fully validate the fixed recursion sweep manifest.""" + with Path(path).open(newline="", encoding="utf-8") as handle: + reader = csv.DictReader(handle, delimiter="\t") + if tuple(reader.fieldnames or ()) != EXPECTED_HEADER: + raise ValueError( + f"manifest header mismatch: got={reader.fieldnames!r}, " + f"expected={EXPECTED_HEADER!r}" + ) + cells = tuple( + _cell_from_row(row, line_number) + for line_number, row in enumerate(reader, start=2) + ) + + if not cells: + raise ValueError("recursion sweep manifest is empty") + names = [cell.cell for cell in cells] + if len(names) != len(set(names)): + raise ValueError("recursion sweep manifest has duplicate cell names") + for cell in cells: + validate_cell(cell) + + recipes = {cell.recipe for cell in cells} + if recipes != EXPECTED_RECIPES or len(cells) != len(EXPECTED_RECIPES): + missing = EXPECTED_RECIPES - recipes + extra = recipes - EXPECTED_RECIPES + raise ValueError( + "recursion sweep recipe set mismatch: " + f"missing={sorted(missing)!r} extra={sorted(extra)!r} " + f"rows={len(cells)}" + ) + return cells + + +def validate_onehop_gate( + path: str | Path, expected_sha256: str | None = None +) -> tuple[dict, str]: + """Require a strict top-level ``"pass": true`` one-hop gate. + + The gate's metrics and thresholds are owned by the one-hop diagnostic. + This boundary deliberately does not reinterpret them: it accepts only the + diagnostic's final boolean and binds the exact JSON bytes by SHA-256. + """ + gate_path = Path(path) + if not gate_path.is_file(): + raise ValueError(f"one-hop gate JSON does not exist: {gate_path}") + try: + gate_bytes = gate_path.read_bytes() + except OSError as error: + raise ValueError(f"cannot read one-hop gate JSON: {error}") from error + digest = hashlib.sha256(gate_bytes).hexdigest() + if expected_sha256 and digest != expected_sha256: + raise ValueError( + "one-hop gate SHA-256 mismatch: " + f"expected={expected_sha256} actual={digest}" + ) + try: + payload = json.loads(gate_bytes.decode("utf-8")) + except (UnicodeError, json.JSONDecodeError) as error: + raise ValueError(f"invalid one-hop gate JSON: {error}") from error + if not isinstance(payload, dict): + raise ValueError("one-hop gate JSON must contain an object") + if payload.get("pass") is not True: + raise ValueError( + "one-hop gate is closed: require a top-level JSON boolean " + '"pass": true' + ) + return payload, digest + + +def _mapping(parent: dict, key: str, context: str) -> dict: + value = parent.get(key) + if not isinstance(value, dict): + raise ValueError(f"{context}.{key} must be a JSON object") + return value + + +def _exact(parent: dict, key: str, expected, context: str) -> None: + actual = parent.get(key) + if isinstance(expected, bool): + matches = actual is expected + elif isinstance(expected, int): + matches = type(actual) is int and actual == expected + else: + matches = actual == expected + if not matches: + raise ValueError( + f"{context}.{key} mismatch: expected={expected!r} " + f"actual={actual!r}" + ) + + +def _finite_float(parent: dict, key: str, expected: float, context: str) -> None: + actual = parent.get(key) + if isinstance(actual, bool): + raise ValueError( + f"{context}.{key} mismatch: expected={expected!r} " + f"actual={actual!r}" + ) + try: + numeric = float(actual) + except (TypeError, ValueError) as error: + raise ValueError( + f"{context}.{key} must be numeric, got {actual!r}" + ) from error + if not math.isfinite(numeric) or not math.isclose( + numeric, expected, rel_tol=1e-12, abs_tol=1e-12): + raise ValueError( + f"{context}.{key} mismatch: expected={expected!r} " + f"actual={actual!r}" + ) + + +def _sha256(value, context: str) -> str: + if not isinstance(value, str) or not _SHA256.fullmatch(value): + raise ValueError(f"{context} must be a lowercase SHA-256 digest") + return value + + +def _absolute_path(value, context: str) -> Path: + if not isinstance(value, str) or not value or not os.path.isabs(value): + raise ValueError(f"{context} must be an absolute path") + if any(character in value for character in ("\n", "\r", "\t")): + raise ValueError(f"{context} contains a control character") + return Path(value) + + +def validate_continuation_gate( + path: str | Path, + cell: RecursionCell, + expected_gate_sha256: str | None = None, + expected_source_sha256: str | None = None, +) -> ContinuationGate: + """Validate a gate and bind one exact step-50k continuation source. + + Unlike :func:`validate_onehop_gate`, this is the fail-closed scheduler + boundary. It accepts only the staged frozen h256 pre-composition gate + for the selected manifest cell, verifies the immutable checkpoint bytes, + and binds the frozen coordinate-free reader provenance. + """ + validate_cell(cell) + payload, gate_digest = validate_onehop_gate( + path, expected_gate_sha256) + _exact( + payload, "audit", + "fair_visual_rsm_one_hop_occupancy_checkpoint_gate", "gate") + _exact(payload, "schema_version", 2, "gate") + + decision = _mapping(payload, "decision", "gate") + _exact(decision, "one_hop_value_ready", True, "gate.decision") + _exact(decision, "recursive_state_ready", True, "gate.decision") + _exact( + decision, "ready_for_recursion_experiment", True, + "gate.decision") + _exact(payload, "pass", True, "gate") + + source = _absolute_path(payload.get("checkpoint"), "gate.checkpoint") + if not source.is_file(): + raise ValueError( + f"gated source checkpoint does not exist: {source}") + if not source.name.endswith( + f"_step{CALIBRATION_STEPS}.pkl"): + raise ValueError( + "gated source must be an immutable " + f"*_step{CALIBRATION_STEPS}.pkl archive: {source}") + _exact(payload, "checkpoint_step", CALIBRATION_STEPS, "gate") + run_contract = _mapping(payload, "checkpoint_run_contract", "gate") + _exact( + run_contract, "env", "visual-cube-single-play-v0", + "gate.checkpoint_run_contract") + source_seed = run_contract.get("seed") + if type(source_seed) is not int or source_seed < 0: + raise ValueError( + "gate.checkpoint_run_contract.seed must be a nonnegative integer") + for key, expected in { + "recursion": "occupancy_latent", + "recursion_state": "hidden", + }.items(): + _exact( + run_contract, key, expected, "gate.checkpoint_run_contract") + source_digest = file_sha256(source) + recorded_source_digest = _sha256( + payload.get("checkpoint_sha256"), "gate.checkpoint_sha256") + if source_digest != recorded_source_digest: + raise ValueError( + "gated source checkpoint SHA-256 mismatch: " + f"recorded={recorded_source_digest} actual={source_digest} " + f"path={source}") + if ( + expected_source_sha256 is not None + and source_digest != expected_source_sha256 + ): + raise ValueError( + "expected source checkpoint SHA-256 mismatch: " + f"expected={expected_source_sha256} actual={source_digest}" + ) + + fairness = _mapping( + payload, "fairness_and_training_contract", "gate") + for key, expected in { + "pixels_only": True, + "drop_proprio": True, + "conditional_flow": True, + "discount_conditioned": True, + "checkpoint_mode": "staged_hidden_precomposition", + "future_distribution_space": "frozen_encoder_hidden_h256", + "reward_reader_space": "cached_compact_z", + "checkpoint_step": CALIBRATION_STEPS, + "rec_after": int(cell.rec_after), + "composition_has_activated": False, + "composition_activation_rule": + "training_step_strictly_greater_than_rec_after", + "uses_td_or_bootstrap": False, + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": False, + "occupancy_and_actor_jointly_updated": True, + "separate_stop_gradient_losses": True, + "canonical_reader_model": "diag_metric", + "reader_index_delta": 4, + "actor_query_contrast_trained": True, + }.items(): + _exact(fairness, key, expected, "gate.fairness_and_training_contract") + discount_support = fairness.get("discount_support") + if not isinstance(discount_support, list) or len(discount_support) != 2: + raise ValueError( + "gate.fairness_and_training_contract.discount_support " + "must contain [gamma_lo, task_gamma]") + if not ( + 0.0 < float(discount_support[0]) < float(discount_support[1]) < 1.0 + ): + raise ValueError( + "gate fairness discount support is not strictly ordered") + if not math.isclose( + float(discount_support[1]), cell.gamma, + rel_tol=1e-12, abs_tol=1e-12 + ): + raise ValueError( + "gate fairness task-gamma support does not match manifest") + + representation = _mapping(payload, "representation", "gate") + for key, expected in { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "frozen_encoder_hidden_occupancy_state", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "occupancy_goal_dim": 256, + "future_distribution_space": "frozen_encoder_hidden_h256", + "future_dim": 256, + "reward_reader_space": "cached_compact_z", + "generated_future_reward_projection": + "frozen_pixel_encoder_fc_1_affine_only", + }.items(): + _exact(representation, key, expected, "gate.representation") + reward_reader_dim = representation.get("reward_reader_dim") + if type(reward_reader_dim) is not int or reward_reader_dim <= 0: + raise ValueError( + "gate.representation.reward_reader_dim must be positive") + support = _mapping( + representation, "hidden_future_support", "gate.representation") + for key, expected in { + "rule": "exact_cached_future_std_greater_than_zero", + "total_dimensions": 256, + "relu_nonnegative_cached_support_verified": True, + "projection": "relu_nonnegative_plus_constant_mean", + }.items(): + _exact( + support, key, expected, + "gate.representation.hidden_future_support") + active = support.get("active_dimensions") + constant = support.get("constant_dimensions") + if ( + type(active) is not int + or type(constant) is not int + or active <= 0 + or constant < 0 + or active + constant != 256 + ): + raise ValueError( + "gate hidden h256 active/constant dimensions are inconsistent") + _sha256( + support.get("mask_sha256"), + "gate.representation.hidden_future_support.mask_sha256") + fc1_audit = _mapping( + representation, "fc1_cached_z_error", "gate.representation") + _exact( + fc1_audit, "passed", True, + "gate.representation.fc1_cached_z_error") + + artifacts = _mapping(payload, "artifact_contract", "gate") + for key in ( + "forbidden_arrays_read", + "proprioception_arrays_read", + "simulator_coordinate_arrays_read", + "reward_arrays_read", + ): + _exact(artifacts, key, [], "gate.artifact_contract") + encoder = _mapping( + artifacts, "pixel_encoder", "gate.artifact_contract") + _absolute_path( + encoder.get("path"), "gate.artifact_contract.pixel_encoder.path") + _sha256( + encoder.get("sha256"), + "gate.artifact_contract.pixel_encoder.sha256") + for key, expected in { + "latent_artifact_binding_verified": True, + "hidden_dim": 256, + "compact_z_dim": reward_reader_dim, + "cube_coordinate_training": False, + }.items(): + _exact( + encoder, key, expected, + "gate.artifact_contract.pixel_encoder") + arrays_read = encoder.get("arrays_read") + if not isinstance(arrays_read, list) or not { + "fc_1.weight", "fc_1.bias" + }.issubset(arrays_read): + raise ValueError( + "gate pixel encoder audit did not read fc_1 weight and bias") + + reader_path = _absolute_path( + artifacts.get("reward_reader_path"), + "gate.artifact_contract.reward_reader_path") + reader_digest = _sha256( + artifacts.get("reward_reader_sha256"), + "gate.artifact_contract.reward_reader_sha256") + if reader_digest != cell.reader_sha256: + raise ValueError( + f"{cell.cell}: gate reader SHA-256 does not match manifest") + if reader_path.is_file(): + actual_reader_digest = file_sha256(reader_path) + if actual_reader_digest != reader_digest: + raise ValueError( + "gate reward-reader SHA-256 mismatch: " + f"recorded={reader_digest} actual={actual_reader_digest} " + f"path={reader_path}") + reader = _mapping( + artifacts, "reward_reader", "gate.artifact_contract") + for key, expected in { + "reader_model": "diag_metric", + "target": "index", + "index_delta": 4, + "zdim": reward_reader_dim, + "pixels_only_latents": True, + "frozen_encoder": True, + "uses_coordinates_for_training": False, + "uses_coordinates_for_diagnostics": False, + "uses_reward_arrays": False, + "uses_td_or_bootstrap": False, + "label_source": + "trajectory_index_positive_and_far_negative_relabeling", + }.items(): + _exact( + reader, key, expected, + "gate.artifact_contract.reward_reader") + + occupancy = _mapping(payload, "occupancy", "gate") + _exact(occupancy, "model", "conditional_flow", "gate.occupancy") + _exact( + occupancy, "gamma_sampler", "stratified_bins", + "gate.occupancy") + _finite_float( + occupancy, "gamma_task_fraction", 0.5, "gate.occupancy") + _finite_float( + occupancy, "task_gamma", cell.gamma, "gate.occupancy") + _finite_float( + occupancy, "candidate_recursion_beta", cell.beta, + "gate.occupancy") + _exact( + occupancy, "candidate_recursion_depth", cell.depth, + "gate.occupancy") + _finite_float( + occupancy, "candidate_recursion_beta_mass", cell.beta_mass, + "gate.occupancy") + gate_horizons = occupancy.get("gamma_horizons") + try: + parsed_gate_horizons = tuple(float(value) for value in gate_horizons) + except (TypeError, ValueError) as error: + raise ValueError( + "gate.occupancy.gamma_horizons must be numeric") from error + if parsed_gate_horizons != _parse_horizons(cell.gamma_horizons): + raise ValueError( + f"{cell.cell}: gate gamma_horizons do not match manifest") + _exact( + occupancy, "active_future_dimensions", active, "gate.occupancy") + _exact( + occupancy, "constant_future_dimensions", constant, + "gate.occupancy") + _exact( + occupancy, + "active_dimension_mask_applied_to_noise_flow_and_loss", + True, + "gate.occupancy", + ) + _exact( + occupancy, "raw_future_support_projection", + "relu_nonnegative_plus_constant_mean", "gate.occupancy") + + gate_path = str(Path(path).resolve()) + return ContinuationGate( + cell=cell.cell, + gate_path=gate_path, + gate_sha256=gate_digest, + source_checkpoint=str(source), + source_checkpoint_sha256=source_digest, + source_checkpoint_step=CALIBRATION_STEPS, + source_seed=source_seed, + reader_path=str(reader_path), + reader_sha256=reader_digest, + ) + + +def _manifest_command(path: str) -> None: + cells = load_manifest(path) + print( + "manifest_pass=true " + f"cells={len(cells)} tail_cap={TAIL_CAP:.9g} " + f"reader_tag={PINNED_READER_TAG} " + f"reader_sha256={PINNED_READER_SHA256}" + ) + for cell in cells: + print( + f"cell={cell.cell} composition={cell.composition} " + f"gamma={cell.gamma:g} beta={cell.beta:g} depth={cell.depth} " + f"continuation={cell.continuation:.12g} " + f"cap_mass={cell.cap_mass:.12g} beta_mass={cell.beta_mass:g}" + ) + + +def _gate_command(path: str, expected_sha256: str | None) -> None: + _, digest = validate_onehop_gate(path, expected_sha256) + print(f"gate_pass=true gate_sha256={digest} path={Path(path).resolve()}") + + +def _continuation_command( + manifest_path: str, + cell_name: str, + gate_path: str, + expected_gate_sha256: str | None, + expected_source_sha256: str | None, +) -> None: + cells = {cell.cell: cell for cell in load_manifest(manifest_path)} + try: + cell = cells[cell_name] + except KeyError as error: + raise ValueError( + f"unknown continuation cell: {cell_name!r}") from error + validated = validate_continuation_gate( + gate_path, + cell, + expected_gate_sha256=expected_gate_sha256, + expected_source_sha256=expected_source_sha256, + ) + fields = ( + ("continuation_gate_pass", "true"), + ("cell", validated.cell), + ("gate_path", validated.gate_path), + ("gate_sha256", validated.gate_sha256), + ("source_checkpoint", validated.source_checkpoint), + ( + "source_checkpoint_sha256", + validated.source_checkpoint_sha256, + ), + ( + "source_checkpoint_step", + str(validated.source_checkpoint_step), + ), + ("source_seed", str(validated.source_seed)), + ("reader_path", validated.reader_path), + ("reader_sha256", validated.reader_sha256), + ) + for key, value in fields: + if any(character in value for character in ("\n", "\r")): + raise ValueError(f"unsafe newline in continuation field {key}") + print(f"{key}={value}") + + +def main(argv: Iterable[str] | None = None) -> None: + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers(dest="command", required=True) + manifest_parser = subparsers.add_parser("manifest") + manifest_parser.add_argument("path") + gate_parser = subparsers.add_parser("gate") + gate_parser.add_argument("path") + gate_parser.add_argument("--expected-sha256") + continuation_parser = subparsers.add_parser("continuation") + continuation_parser.add_argument("--manifest", required=True) + continuation_parser.add_argument("--cell", required=True) + continuation_parser.add_argument("--gate", required=True) + continuation_parser.add_argument("--expected-gate-sha256") + continuation_parser.add_argument("--expected-source-sha256") + args = parser.parse_args(argv) + if args.command == "manifest": + _manifest_command(args.path) + elif args.command == "gate": + _gate_command(args.path, args.expected_sha256) + else: + _continuation_command( + args.manifest, + args.cell, + args.gate, + args.expected_gate_sha256, + args.expected_source_sha256, + ) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/pixel_eval.py b/gen_q_rsm/ogbench_genq/pixel_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..f8d793983a7a750a9d545f2bb56876b951a1caad --- /dev/null +++ b/gen_q_rsm/ogbench_genq/pixel_eval.py @@ -0,0 +1,138 @@ +"""Eval-time pixel -> latent wrapper for the RSM pixel path (issue #65 Track C). + +Rolls episodes in the VISUAL env while presenting the trained agent with the +exact observation contract of the precomputed latent dataset +(genq/precompute_pixel_latents.py): + + observation = concat(proprio19, z), z = frozen pixel encoder E(pixels) + goal = E(goal pixels), encoded once per episode at reset + +The proprio channel is assembled live from the env's sim state, per env family: + + * manip (cube): compute_ob_info() -> the 19 state-mode arm-proprio dims (and + the same scaling) OGBench's compute_observation() emits. + * maze (antmaze): concat(qpos, qvel) with the global xy dropped — the SAME + 27-D channel precompute_pixel_latents.py::maze_proprio built from the + dataset (state_obs == concat(qpos, qvel), xy == qpos[:, :2], both verified). + Read live from MuJoCo data; reset/step leave it current. +""" +import os +import sys + +import gymnasium +import numpy as np + +# OGBench manipspace scaling (manipspace_env.compute_observation, state mode). +_XYZ_CENTER = np.array([0.425, 0.0, 0.0]) +_XYZ_SCALER = 10.0 +_GRIPPER_SCALER = 3.0 + + +class PixelLatentEvalWrapper(gymnasium.Wrapper): + """Visual-env observations -> concat(proprio, E(pixels)); goal -> E(goal pixels). + + `family` picks how proprio is read: 'manip' (cube arm proprio, 19-D) or + 'maze' (ant state minus xy, 27-D).""" + + def __init__(self, env, encode_fn, family="manip", drop_proprio=False, + latent_transform=None, state_encode_fn=None, + goal_hidden=False, state_transform=None): + super().__init__(env) + self._encode = encode_fn + self._family = family + # strictly-pixels-only: observation is E(pixels) alone, no proprio channel + # (matches GCIQL's pixels-only input diet exactly). + self._drop_proprio = drop_proprio + self._latent_transform = latent_transform + self._state_encode = state_encode_fn + self._goal_hidden = goal_hidden + self._state_transform = state_transform + if goal_hidden and state_encode_fn is None: + raise ValueError( + "goal_hidden requires the encoder-hidden state path") + + def _encode_pixels(self, pixels, state=False): + if state and self._state_encode is not None: + hidden = self._state_encode(np.asarray(pixels)[None]) + if self._state_transform is not None: + hidden = self._state_transform(hidden) + return np.asarray(hidden)[0] + z = self._encode(np.asarray(pixels)[None]) + if self._latent_transform is not None: + z = self._latent_transform(z) + return np.asarray(z)[0] + + def _proprio_manip(self): + info = self.env.unwrapped.compute_ob_info() + return np.concatenate([ + info["proprio/joint_pos"], + info["proprio/joint_vel"], + (info["proprio/effector_pos"] - _XYZ_CENTER) * _XYZ_SCALER, + np.cos(info["proprio/effector_yaw"]), + np.sin(info["proprio/effector_yaw"]), + info["proprio/gripper_opening"] * _GRIPPER_SCALER, + info["proprio/gripper_contact"], + ]).astype(np.float32) + + def _proprio_maze(self): + # ant state minus global xy: concat(qpos, qvel)[2:], read live from + # MuJoCo. The dataset guarantee state_obs == concat(qpos, qvel) means + # this matches the training proprio channel exactly. + data = self.env.unwrapped.data # dm_control / mujoco sim data + full = np.concatenate([np.asarray(data.qpos, np.float32), + np.asarray(data.qvel, np.float32)]) + return full[2:] + + def _proprio(self): + return self._proprio_maze() if self._family == "maze" else self._proprio_manip() + + def _latent_ob(self, pixels): + z = self._encode_pixels(pixels, state=True) + if self._drop_proprio: + return z.astype(np.float32) + return np.concatenate([self._proprio(), z]) + + def reset(self, **kwargs): + ob, info = self.env.reset(**kwargs) + if info.get("goal") is not None: + info["goal"] = self._encode_pixels( + info["goal"], state=self._goal_hidden) + return self._latent_ob(ob), info + + def step(self, action): + ob, reward, terminated, truncated, info = self.env.step(action) + return self._latent_ob(ob), reward, terminated, truncated, info + + +def make_latent_eval_env(env_id, pixel_encoder_npz, drop_proprio=False, + latent_transform=None, state_hidden=False, + goal_hidden=False, state_transform=None): + """Create the visual env (env_only — no full pixel dataset load) wrapped so + the RSM latent-path agent can act in it. Needs a renderer (GPU node, + MUJOCO_GL=egl). drop_proprio=True -> strictly-pixels-only observation + (E(pixels) alone), matching GCIQL's input diet.""" + import ogbench + + sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "genq")) + from train_pixel_encoder_jax import load_pixel_encoder + + if state_hidden: + encode_both, _ = load_pixel_encoder( + pixel_encoder_npz, return_hidden=True) + + def encode_fn(frames): + return encode_both(frames)[0] + + def state_encode_fn(frames): + return encode_both(frames)[1] + else: + encode_fn, _ = load_pixel_encoder(pixel_encoder_npz) + state_encode_fn = None + family = "maze" if "maze" in env_id else "manip" + env = ogbench.make_env_and_datasets(env_id, env_only=True) + return PixelLatentEvalWrapper(env, encode_fn, family=family, + drop_proprio=drop_proprio, + latent_transform=latent_transform, + state_encode_fn=state_encode_fn, + goal_hidden=goal_hidden, + state_transform=state_transform) diff --git a/gen_q_rsm/ogbench_genq/rsm.py b/gen_q_rsm/ogbench_genq/rsm.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8ef4668d209329c67c35285a74f292da285d73 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/rsm.py @@ -0,0 +1,7070 @@ +"""RSM — Recursive Successor Model. + +Policy iteration with an occupancy model and actor, with no TD: + + * an OCCUPANCY model: a conditional diffusion model p(z | s, a, gamma~) + of the reward-relevant coordinates z of the state the policy reaches + after a geometrically-distributed number of steps (the discounted + successor measure). Trained by plain maximum likelihood on offline + data — no reward, no bootstrap. + * an ACTOR trained either by gradient ascent on a Q read directly off the + occupancy, anchored by behavior cloning, or by advantage-weighted + regression (AWR) on dataset actions. AWR fits only an expectile baseline + V(s,g). The visual policy-extraction control can first regress a twin + scalar scorer onto Monte-Carlo occupancy expectations, then use the same + expectile-V + AWR extraction as GCIQL. This scorer is purely supervised: + it never uses a next-state value, Bellman target, or TD bootstrap. + For DDPG+BC, the scorer is additionally anchored on the detached current + actor mode and local actions, including direct action-gap regression under + common occupancy noise. An optional non-TD on-support anchor applies the + same frozen index reader to recorded geometrically sampled successors of a + dataset action; actor-mode and local counterfactual targets remain supplied + by the fitted exponential-moving-average (EMA) occupancy. Neither path + reads reward arrays, next-state values, or Bellman targets, and neither + alters the occupancy fit. + +The training loop, in plain words (one fused step): + + 1. occupancy update : one diffusion MLE step on (s,a) -> z_{t+k} pairs, + k ~ Geom(1-gamma~), gamma~ drawn from a spectrum + An optional fair visual auxiliary ranks each + recorded tuple above detached live-actor/local + action relabelings under shared flow noise. This + hardens actor-query support but is not + counterfactual occupancy supervision. + 2. recursion carrier : state-space tasks may use the legacy completion + head. Fair visual recursion instead closes the + chain in a frozen pixel latent (rich h256 primary, + compact z control): a sample is already the next + actor/occupancy state. This occupancy-only path + has no completion/forward model. + 3. actor update : DDPG+BC uses Q(s, mu(s), g) from the occupancy. + AWR uses stop-gradient Q(s, a_data, g), fits an + expectile V, and weights behavior cloning by + exp(alpha * (Q - V)). + 4. EMA + banking : Polyak copies of occupancy and actor; periodic + evals bank the best snapshot for offline evals + +The fair visual path must select ``--recursion occupancy`` explicitly. It +uses the geometric splitting identity with independently configurable target +discount gamma and shorter jump discount beta. Every occupancy query includes +its discount Fourier features; no Bellman/TD target enters either fit. + +The legacy state-space recipe uses beta-recursion everywhere. The goal space +picks only what it must: + discrete alphabet (puzzle bits) -> exact likelihood read-out ("gl"), + fully differentiated chain + continuous coordinates (mazes) -> diffusion-ELBO read-out, chain with + the "tails" guard (stop-grad heads; + the differentiated form collapses) + +Run: + python ogbench_genq/rsm.py --env puzzle-3x3-play-v0 --save_best ckpt/best.pkl + python ogbench_genq/rsm.py --env pointmaze-medium-navigate-v0 ... + +Everything here IS the record recipe; settled hyperparameters live in the +RECIPE CONSTANTS block below and are not command-line arguments (the +evidence for each is in ABLATION.md — change them only with new evidence). +Dropped designs and the levers that lost their races are archived in +unused/genq_joint_fast.py. Method + math: root README.md. Internals + +dropped designs: DESIGN.md. Numbers + protocol: RESULTS.md. +""" +import json +import hashlib +import os +import time + +import numpy as np + +if __package__ in (None, ""): # allow direct `python ogbench_genq/rsm.py` + import sys as _sys + _sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from ogbench_genq._runner import (OGBENCH_IMPLS, PKG_DIR, _make_eval_fn, _result_dir, + _setup_paths) +from ogbench_genq.genq.reward_reader import ( + joint_index_pair_masks, + load_jax_reward_reader, +) + +# ======================= RECIPE CONSTANTS (settled) ======================= +# Every value below was fixed by ablation — see ABLATION.md for the verdicts. +GAMMA = 0.99 # task discount (OGBench standard) +OCC_LR = 3e-4 # occupancy / completion AdamW learning rate +OCC_HIDDEN = 256 # occupancy MLP width (512 tried: no gain) +OCC_LAYERS = 3 +OCC_TIME_DIM = 64 +OCC_T = 100 # diffusion timesteps +OCC_TAU = 0.005 # occupancy Polyak rate (all read-outs use the EMA) +RT_ETA = 0.5 # reward-targeted stratification rate (exact IS weights) +N_ORDERS = 16 # gl order-average for targets and evals +N_ORDERS_PI = 4 # fewer orders inside the actor loss — the large + # batch absorbs the extra Monte-Carlo noise (~2x faster) +GAMMA_SPECTRUM_P = 0.5 # legacy P(log-uniform spectrum draw) vs task gamma +GAMMA_TASK_FRACTION = 1.0 - GAMMA_SPECTRUM_P +GAMMA_STRATIFIED_HORIZONS = (2.0, 4.0, 8.0, 16.0, 32.0, 64.0) +FOURIER_K = 4 # sin/cos pairs of the log-horizon gamma encoding +REC_EVERY = 1 # compose every step (every-2 measured worse) +REC_MAX_DEPTH = 10 # chain cap; P(depth > 10) ~ 1e-3 at beta = 0.98 +ACTOR_EMA_TAU = 0.005 # EMA actor for banking (load-bearing: the records + # are EMA-actor banks) +DISTILL_EMA_TAU = 0.005 # smoothing for the supervised occupancy-Q regressor; + # this is not a Bellman/TD target network +VISUAL_GCIQL_BATCH_SIZE = 256 +PIXEL_SCORER_TARGET_UPDATE_SOURCE = ( + "just_updated_live_twin_pixel_scorer" +) +PIXEL_SCORER_TARGET_UPDATE_TIMING = ( + "polyak_after_current_gradient_update_for_next_fused_step" +) +EVAL_EPISODES_PERIODIC = 15 # in-training eval size (overstates; see RESULTS.md) +STEPS_PER_DISPATCH = 100 # fused lax.scan window per host dispatch +PIXEL_ACTOR_DATASET_KEYS = frozenset({ + "observations", "actions", "terminals", "valids", +}) +PIXEL_ACTOR_FORBIDDEN_KEYS = frozenset({ + "qpos", "qvel", "button_states", "coordinates", "rewards", +}) + + +def checkpoint_due(step, checkpoint_every, archive_every=None): + """Return whether either resumability or archival cadence is due. + + Archive cadence is independent of the primary checkpoint cadence. Using + only their intersection silently drops requested selection checkpoints + (for example 25k archives with 10k resumability saves). + """ + step = int(step) + checkpoint_every = int(checkpoint_every) + assert step > 0 and checkpoint_every > 0 + if step % checkpoint_every == 0: + return True + return bool( + archive_every is not None + and int(archive_every) > 0 + and step % int(archive_every) == 0 + ) + + +def file_sha256(path): + """Return a streaming SHA-256 digest for an immutable checkpoint.""" + digest = hashlib.sha256() + with open(path, "rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def visual_actor_reference_sha256(reference_root): + """Hash the exact reference modules that define the visual GC actor.""" + digest = hashlib.sha256() + reference_root = os.path.realpath(os.path.abspath(reference_root)) + for relative_path in ( + "agents/gcbc.py", + "utils/datasets.py", + "utils/encoders.py", + "utils/networks.py"): + path = os.path.join(reference_root, relative_path) + with open(path, "rb") as handle: + digest.update(relative_path.encode()) + digest.update(handle.read()) + return digest.hexdigest() + + +def _is_sha256_digest(value): + return bool( + isinstance(value, str) + and len(value) == 64 + and all(character in "0123456789abcdef" for character in value) + ) + + +def truncated_geometric_future_indices( + rows, trajectory_ends, discounts, uniforms, absorbing_goals=None, + array_module=np): + """Sample finite-trajectory discounted-successor indices. + + ``trajectory_ends`` is the exclusive end for each row and ``uniforms`` has + shape ``(batch, samples)``. Before optional absorption, the returned + offset has probability ``(1-discount) * discount**k / + (1-discount**length)`` for ``0 <= k < length``. If + ``absorbing_goals`` is supplied, a goal at or after the row in the same + trajectory clamps every later draw to its first-passage index. Passing + uniforms explicitly keeps the helper equally usable in NumPy contract + tests and JAX training code. + """ + xp = array_module + rows = xp.asarray(rows) + trajectory_ends = xp.asarray(trajectory_ends) + discounts = xp.asarray(discounts) + uniforms = xp.asarray(uniforms) + length = (trajectory_ends - rows)[:, None] + log_discount = xp.log(discounts)[:, None] + finite_mass = xp.maximum( + 1.0 - xp.exp(length * log_discount), 1e-12) + offset = ( + xp.ceil(xp.log1p(-uniforms * finite_mass) / log_discount) + .astype(np.int32) - 1) + offset = xp.clip(offset, 0, length - 1) + future = rows[:, None] + offset + if absorbing_goals is not None: + absorbing_goals = xp.asarray(absorbing_goals) + in_trajectory = ( + (absorbing_goals >= rows) + & (absorbing_goals < trajectory_ends)) + future = xp.where( + in_trajectory[:, None], + xp.minimum(future, absorbing_goals[:, None]), + future, + ) + return future + + +def audit_visual_pixel_actor_dataset( + dataset, latent_actions, latent_terminals): + """Validate the exact pixels-only actor dataset against the latent cache. + + The occupancy continues to train from the compact cached artifact. The + trainable actor additionally needs the released RGB frames, but accepting a + second data source creates an alignment hazard. Fail closed unless it has + only the four fields used by the exact visual GCIQL control and its action + and trajectory-boundary rows exactly match the occupancy artifact. + """ + keys = frozenset(dataset) + if keys != PIXEL_ACTOR_DATASET_KEYS: + raise ValueError( + "pixel actor dataset keys must be exactly " + f"{sorted(PIXEL_ACTOR_DATASET_KEYS)}; got {sorted(keys)}") + forbidden = keys & PIXEL_ACTOR_FORBIDDEN_KEYS + if forbidden: + raise ValueError( + f"pixel actor dataset contains forbidden keys: {sorted(forbidden)}") + + observations = np.asarray(dataset["observations"]) + actions = np.asarray(dataset["actions"], np.float32) + valids = np.asarray(dataset["valids"]) + compact_terminals = np.asarray(dataset["terminals"], bool) + latent_actions = np.asarray(latent_actions, np.float32) + latent_terminals = np.asarray(latent_terminals, bool) + if observations.dtype != np.uint8 or observations.ndim != 4: + raise ValueError( + "pixel actor observations must be rank-4 uint8 RGB images; " + f"got shape={observations.shape} dtype={observations.dtype}") + if observations.shape[-1] != 3: + raise ValueError( + "pixel actor observations must have exactly three RGB channels; " + f"got shape={observations.shape}") + n = len(observations) + if actions.ndim != 2 or actions.shape != latent_actions.shape: + raise ValueError( + "pixel actor and latent-cache action shapes differ: " + f"pixels={actions.shape} latent={latent_actions.shape}") + if compact_terminals.shape != (n,) or latent_terminals.shape != (n,): + raise ValueError( + "pixel actor and latent-cache terminal shapes must both be (N,); " + f"pixels={compact_terminals.shape} " + f"latent={latent_terminals.shape}") + if valids.shape != (n,): + raise ValueError( + f"pixel actor valids must have shape {(n,)}, got {valids.shape}") + if not np.array_equal( + np.clip(actions, -1.0, 1.0), latent_actions): + raise ValueError( + "pixel actor dataset actions are not row-aligned with the latent " + "occupancy artifact") + # OGBench's compact policy dataset deliberately changes the terminal + # convention: ``valids`` is formed from the original trajectory endpoints, + # then ``terminals`` additionally marks the last valid transition. The + # latent artifact stores the original endpoints. Reconstruct and verify + # both conventions rather than comparing their intentionally different + # bit patterns. + source_terminals = np.asarray(valids <= 0, bool) + expected_compact_terminals = np.minimum( + source_terminals.astype(np.int8), + 1, + ) + expected_compact_terminals = np.minimum( + expected_compact_terminals + + np.concatenate([ + source_terminals[1:].astype(np.int8), + np.ones((1,), np.int8), + ]), + 1, + ).astype(bool) + if not np.array_equal( + compact_terminals, expected_compact_terminals): + raise ValueError( + "pixel actor compact terminals do not match the exact OGBench " + "valids-to-terminal transform") + if not np.array_equal(source_terminals, latent_terminals): + raise ValueError( + "pixel actor dataset trajectory endpoints reconstructed from " + "valids are not row-aligned with the latent occupancy artifact") + valid_indices = np.flatnonzero(valids > 0).astype(np.int32) + if len(valid_indices) == 0: + raise ValueError("pixel actor dataset has no valid transition rows") + return observations, valid_indices, { + "dataset_keys": sorted(keys), + "excluded_keys": sorted(PIXEL_ACTOR_FORBIDDEN_KEYS), + "observation_shape": list(observations.shape[1:]), + "observation_dtype": str(observations.dtype), + "action_shape": list(actions.shape[1:]), + "row_count": int(n), + "valid_transition_count": int(len(valid_indices)), + "actions_match_latent_cache": True, + "source_terminals_match_latent_cache": True, + "compact_terminals_match_reconstructed": True, + "terminal_alignment_contract": ( + "latent_source_endpoints_equal_pixel_valids_zero_and_compact_" + "terminals_equal_source_plus_shifted_source"), + } + + +def validate_visual_gcbc_actor_init( + payload, env, seed, observation_shape, action_shape, p_aug, + active_reference_root=None): + """Validate a non-TD GCBC export before using its actor initialization. + + Only the dedicated ``visual_gcbc_params_v1`` format is accepted. In + particular, a GCIQL export is rejected even though it contains an + architecturally compatible actor: those actor weights were shaped by a + temporal-difference critic and would violate the RSM experiment contract. + """ + if not isinstance(payload, dict): + raise ValueError( + "invalid visual GCBC actor initialization: payload must be a " + "dictionary") + errors = [] + if payload.get("format") != "visual_gcbc_params_v1": + errors.append( + "format must be visual_gcbc_params_v1 (TD-trained GCIQL exports " + "are forbidden)") + meta = payload.get("run_meta") + config = payload.get("config") + params = payload.get("params") + if not isinstance(meta, dict): + errors.append("run_meta must be a dictionary") + meta = {} + if not isinstance(config, dict): + errors.append("config must be a dictionary") + config = {} + if not isinstance(params, dict) or set(params) != {"modules_actor"}: + errors.append("params must contain only modules_actor") + + expected_meta = { + "method": "GCBC", + "env": env, + "seed": int(seed), + "pixels_only": True, + "drop_proprio": True, + "simulator_state_used": False, + "coordinate_used": False, + "reward_used": False, + "uses_td_or_bootstrap": False, + "uses_occupancy": False, + "goal_relabeling": "uniform_future_same_trajectory", + "network_input_contract": ( + "IMPALA-small over channel-concatenated state and goal RGB"), + "training_augmentation": ( + "probability_0.5_shared_edge_padded_random_crop"), + } + for key, expected in expected_meta.items(): + if meta.get(key) != expected: + errors.append( + f"run_meta.{key}: expected {expected!r}, " + f"got {meta.get(key)!r}") + if tuple(meta.get("observation_shape", ())) != tuple(observation_shape): + errors.append( + "run_meta.observation_shape does not match the actor dataset") + if tuple(meta.get("action_shape", ())) != tuple(action_shape): + errors.append("run_meta.action_shape does not match the actor dataset") + if set(meta.get("dataset_keys", ())) != PIXEL_ACTOR_DATASET_KEYS: + errors.append("run_meta.dataset_keys is not the strict pixel dataset") + if PIXEL_ACTOR_FORBIDDEN_KEYS - set(meta.get("excluded_keys", ())): + errors.append( + "run_meta.excluded_keys does not include every forbidden field") + + expected_config = { + "agent_name": "gcbc", + "lr": 3e-4, + "batch_size": 256, + "actor_hidden_dims": (512, 512, 512), + "const_std": True, + "discrete": False, + "encoder": "impala_small", + "p_aug": float(p_aug), + "frame_stack": None, + "actor_p_curgoal": 0.0, + "actor_p_trajgoal": 1.0, + "actor_p_randomgoal": 0.0, + "actor_geom_sample": False, + } + for key, expected in expected_config.items(): + actual = config.get(key) + if key == "actor_hidden_dims": + actual = tuple(actual or ()) + if actual != expected: + errors.append( + f"config.{key}: expected {expected!r}, got {actual!r}") + if active_reference_root is not None: + active_reference_root = os.path.realpath( + os.path.abspath(active_reference_root)) + saved_reference_root = meta.get("reference_root") + if ( + not isinstance(saved_reference_root, str) + or os.path.realpath(os.path.abspath(saved_reference_root)) + != active_reference_root): + errors.append( + "run_meta.reference_root does not match the active OGBench " + "implementation") + else: + active_reference_sha256 = visual_actor_reference_sha256( + active_reference_root) + if meta.get("reference_sha256") != active_reference_sha256: + errors.append( + "run_meta.reference_sha256 does not match the active " + "visual GC actor implementation") + if errors: + raise ValueError( + "invalid visual GCBC actor initialization:\n " + + "\n ".join(errors)) + try: + step = int(payload["step"]) + except (KeyError, TypeError, ValueError): + raise ValueError( + "invalid visual GCBC actor initialization: step must be an " + "integer") from None + if step <= 0: + raise ValueError( + "invalid visual GCBC actor initialization: step must be positive") + actor_params = params["modules_actor"] + actor_leaves = [] + + def collect_actor_leaves(value): + if isinstance(value, dict): + for child in value.values(): + collect_actor_leaves(child) + else: + actor_leaves.append(np.asarray(value)) + + collect_actor_leaves(actor_params) + if not actor_leaves: + raise ValueError( + "invalid visual GCBC actor initialization: actor parameter tree " + "is empty") + if any( + leaf.size == 0 + or not np.issubdtype(leaf.dtype, np.number) + or not np.all(np.isfinite(leaf)) + for leaf in actor_leaves): + raise ValueError( + "invalid visual GCBC actor initialization: every actor parameter " + "must be a nonempty finite numeric array") + return params["modules_actor"], { + "format": payload["format"], + "step": step, + "reference_root": meta.get("reference_root"), + "reference_sha256": meta.get("reference_sha256"), + "uses_td_or_bootstrap": False, + } + + +def validate_visual_pixel_actor_run_contract( + *, actor_input, latent_npz, pixel_encoder, drop_proprio, + discount_conditioned, recursion_enabled, freeze_occupancy, + actor_loss, actor_q_transform, reward_decoder, qfilter, + latent_npz_sha256, pixel_encoder_sha256, + pixel_dataset, pixel_dataset_sha256, + pixel_actor_p_aug, pixel_actor_init_ckpt, + pixel_actor_init_ckpt_sha256): + """Fail closed on unsupported or scientifically invalid pixel-policy arms.""" + if actor_input not in ("latent", "pixels"): + raise ValueError( + f"actor_input must be latent or pixels, got {actor_input!r}") + if not 0.0 <= pixel_actor_p_aug <= 1.0: + raise ValueError("pixel_actor_p_aug must lie in [0, 1]") + pixel_actor = actor_input == "pixels" + if pixel_actor: + if not (latent_npz and pixel_encoder and drop_proprio): + raise ValueError( + "the trainable pixel actor requires --latent_npz, " + "--pixel_encoder, and --drop_proprio") + pinned_artifacts = { + "--latent_npz_sha256": latent_npz_sha256, + "--pixel_encoder_sha256": pixel_encoder_sha256, + "--pixel_dataset_sha256": pixel_dataset_sha256, + } + if not pixel_dataset: + raise ValueError( + "the trainable pixel actor requires an explicit " + "--pixel_dataset") + for option, digest in pinned_artifacts.items(): + if not _is_sha256_digest(digest): + raise ValueError( + f"{option} must be a lowercase SHA-256 digest") + if not discount_conditioned: + raise ValueError( + "every pixel-actor occupancy must be explicitly " + "discount-conditioned") + if recursion_enabled: + raise ValueError( + "pixel-actor recursive composition is unsupported until an " + "audited latent proxy actor exists; image reconstruction and " + "world models are forbidden") + if freeze_occupancy: + raise ValueError( + "the pixel actor and occupancy must be jointly updated") + if actor_loss not in ("ddpgbc", "ddpgbc_distill"): + raise ValueError( + "the pixel actor supports occupancy-derived DDPG+BC " + "extraction") + if actor_q_transform != "raw": + raise ValueError( + "the pixel actor requires the raw calibrated occupancy/index " + "reward expectation") + if reward_decoder is None: + raise ValueError( + "the pixel actor requires the frozen local index-reward " + "reader") + if qfilter > 0: + raise ValueError( + "pixel proposal plus latent occupancy Q-filter evaluation is " + "unsupported by the single-observation evaluator") + if pixel_actor_init_ckpt is not None: + if not pixel_actor: + raise ValueError( + "--pixel_actor_init_ckpt requires --actor_input pixels") + if not pixel_actor_init_ckpt_sha256: + raise ValueError( + "--pixel_actor_init_ckpt requires " + "--pixel_actor_init_ckpt_sha256") + if not _is_sha256_digest(pixel_actor_init_ckpt_sha256): + raise ValueError( + "--pixel_actor_init_ckpt_sha256 must be a lowercase SHA-256 " + "digest") + if pixel_actor_p_aug != 0.5: + raise ValueError( + "the exact visual GCBC initialization uses p_aug=0.5") + elif pixel_actor_init_ckpt_sha256 is not None: + raise ValueError( + "--pixel_actor_init_ckpt_sha256 requires " + "--pixel_actor_init_ckpt") + if not pixel_actor and any(( + latent_npz_sha256, + pixel_encoder_sha256, + pixel_dataset, + pixel_dataset_sha256)): + raise ValueError( + "pixel dataset/artifact checksum arguments require " + "--actor_input pixels") + return pixel_actor + + +def validate_visual_pixel_scorer_run_contract( + *, scorer_input, pixel_actor, actor_loss, + distill_empirical_index_weight, distill_actor_goals, + distill_actor_actions, discount_conditioned, recursion, + freeze_occupancy, drop_proprio, pixel_actor_p_aug, + alpha, expectile, batch_size): + """Fail closed on the empirical raw-pixel scorer extraction arm. + + The pixel scorer deliberately has a narrower contract than the historical + latent scorer. Its recorded-action labels must come exclusively from + finite-trajectory absorbing index returns; the fitted occupancy may label + only detached actor/local counterfactual actions. This prevents a + misconfigured run from silently turning the pixel scorer back into an + occupancy-regression critic. + """ + if scorer_input not in ("latent", "pixels"): + raise ValueError( + "distill_scorer_input must be latent or pixels, got " + f"{scorer_input!r}") + pixel_scorer = scorer_input == "pixels" + if not pixel_scorer: + return False + if not pixel_actor: + raise ValueError( + "the raw-pixel scorer requires --actor_input pixels so scorer " + "and actor share the exact rendered-pixel input diet") + if actor_loss not in ("awr_distill", "ddpgbc_distill"): + raise ValueError( + "the raw-pixel scorer is defined only for matched visual GCIQL " + "AWR or DDPG+BC extraction") + if float(distill_empirical_index_weight) != 1.0: + raise ValueError( + "the raw-pixel scorer requires " + "--distill_empirical_index_weight 1 so every recorded-action " + "label is empirical rather than occupancy-blended; the " + "recorded-action label is empirical by contract") + if not distill_actor_goals: + raise ValueError( + "the raw-pixel scorer must be supervised at the actor's " + "uniform-future goals") + if actor_loss == "awr_distill" and distill_actor_actions: + raise ValueError( + "the raw-pixel AWR extractor must use recorded dataset actions " + "only; counterfactual action support belongs to the DDPG+BC " + "control") + if float(expectile) != 0.9: + raise ValueError( + "the raw-pixel scorer requires expectile=0.9 to match visual " + "GCIQL") + if actor_loss == "ddpgbc_distill" and float(alpha) != 1.0: + raise ValueError( + "the raw-pixel DDPG+BC extractor requires alpha=1.0 to match " + "the reproduced visual GCIQL baseline") + if not discount_conditioned: + raise ValueError( + "the raw-pixel scorer arm requires an explicitly " + "discount-conditioned occupancy") + if recursion != "off": + raise ValueError( + "the raw-pixel scorer arm supports one-hop occupancy only; " + "recursive or completion targets are forbidden") + if freeze_occupancy: + raise ValueError( + "the raw-pixel scorer, occupancy, and actor must be jointly " + "updated in the same fused training step") + if not drop_proprio: + raise ValueError( + "the raw-pixel scorer arm requires --drop_proprio") + if float(pixel_actor_p_aug) != 0.5: + raise ValueError( + "the raw-pixel scorer requires p_aug=0.5 to match visual GCIQL") + if ( + isinstance(batch_size, (bool, np.bool_)) + or not isinstance(batch_size, (int, np.integer)) + or int(batch_size) != VISUAL_GCIQL_BATCH_SIZE): + raise ValueError( + "the raw-pixel scorer requires batch_size=256 to match visual " + "GCIQL") + return True + + +def visual_actor_shared_random_crop( + observations, goals, crop_xy, apply_crop): + """Apply the reference edge-padded crop shared by each state/goal pair.""" + import jax + import jax.numpy as jnp + + observations = jnp.asarray(observations) + goals = jnp.asarray(goals) + crop_xy = jnp.asarray(crop_xy) + if observations.shape != goals.shape or observations.ndim != 4: + raise ValueError( + "state and goal crop batches must have the same rank-4 shape") + if crop_xy.shape != (observations.shape[0], 2): + raise ValueError( + "crop_xy must have shape (batch, 2), got " + f"{crop_xy.shape}") + + def crop_one(image, xy): + padded = jnp.pad( + image, + ((3, 3), (3, 3), (0, 0)), + mode="edge", + ) + return jax.lax.dynamic_slice( + padded, + (xy[0], xy[1], jnp.asarray(0, xy.dtype)), + image.shape, + ) + + cropped_observations = jax.vmap(crop_one)(observations, crop_xy) + cropped_goals = jax.vmap(crop_one)(goals, crop_xy) + return jax.lax.cond( + jnp.asarray(apply_crop, bool), + lambda _: (cropped_observations, cropped_goals), + lambda _: (observations, goals), + operand=None, + ) + + +def backfill_actor_input_metadata(saved_meta, requested_actor_meta): + """Backfill new actor-input fields without rewriting checkpoint claims.""" + saved_meta = dict(saved_meta) + # Pixel checkpoints were introduced together with the full schema-10 + # contract. Never infer missing safety claims for one. Only historical + # latent checkpoints receive compatibility defaults. + if requested_actor_meta.get("actor_input") == "pixels": + return saved_meta + for key, value in requested_actor_meta.items(): + saved_meta.setdefault( + key, "latent" if key == "actor_input" else value) + return saved_meta + + +def resolve_checkpoint_load(ckpt, resume_ckpt=None, + resume_ckpt_sha256=None): + """Resolve a safe read source and immutable continuation provenance. + + Ordinary preemptable jobs resume from ``ckpt`` in place. A gated + continuation instead names an immutable ``resume_ckpt`` plus its expected + digest and writes all new states to the distinct ``ckpt`` destination. + Once the destination exists, subsequent preemption resumes load it while + retaining and revalidating the original source provenance. + """ + if resume_ckpt is None: + if resume_ckpt_sha256 is not None: + raise ValueError( + "--resume_ckpt_sha256 requires --resume_ckpt") + return ( + os.path.abspath(ckpt) + if ckpt and os.path.exists(ckpt) else None, + None, + ) + if not ckpt: + raise ValueError("--resume_ckpt requires a distinct --ckpt output") + if not resume_ckpt_sha256: + raise ValueError( + "--resume_ckpt requires --resume_ckpt_sha256 so the gated input " + "cannot drift") + + source = os.path.realpath(os.path.abspath(resume_ckpt)) + destination = os.path.realpath(os.path.abspath(ckpt)) + if not os.path.isfile(source): + raise ValueError(f"resume checkpoint does not exist: {source}") + if source == destination or ( + os.path.exists(destination) and os.path.samefile( + source, destination)): + raise ValueError( + "--resume_ckpt must be a read-only source distinct from --ckpt") + actual_sha256 = file_sha256(source) + if actual_sha256 != resume_ckpt_sha256: + raise ValueError( + "resume checkpoint SHA-256 mismatch: " + f"expected={resume_ckpt_sha256} actual={actual_sha256} " + f"path={source}") + provenance = { + "path": source, + "sha256": actual_sha256, + } + return ( + destination if os.path.exists(destination) else source, + provenance, + ) + + +def _parse_gamma_horizons(value): + """Parse a comma-separated horizon grid into an immutable float tuple.""" + if isinstance(value, str): + value = [piece.strip() for piece in value.split(",") if piece.strip()] + horizons = tuple(float(h) for h in value) + if not horizons: + raise ValueError("gamma_horizons must contain at least one horizon") + return horizons + + +def occupancy_recursion_continuation(gamma, beta): + """Continuation probability for composing beta occupancies into gamma. + + If K_i ~ Geom(1-beta) on {0, 1, ...} and the number of beta jumps is + Geom(1-c) on {1, 2, ...}, then sum_i K_i ~ Geom(1-gamma) exactly for + + c = (gamma - beta) / (gamma * (1 - beta)). + + This is a distributional occupancy identity, not a Bellman target. + """ + gamma = float(gamma) + beta = float(beta) + if not (0.0 < beta < gamma < 1.0): + raise ValueError( + "occupancy recursion requires 0 < beta < gamma < 1 " + f"(got beta={beta}, gamma={gamma})") + return (gamma - beta) / (gamma * (1.0 - beta)) + + +def occupancy_recursion_tail_mass(gamma, beta, max_depth): + """Probability that a fixed-depth continuation scan hits its cap.""" + if int(max_depth) < 1: + raise ValueError("occupancy recursion max_depth must be positive") + return occupancy_recursion_continuation(gamma, beta) ** int(max_depth) + + +def actor_local_negative_actions(actor_mode, local_noise, sigma): + """Build detached actor-mode and local actions for occupancy contrast. + + ``actor_mode`` has shape ``(batch, action_dim)`` and ``local_noise`` has + shape ``(k, batch, action_dim)``. The returned first candidate is the + clipped current actor mode; the remaining candidates are Gaussian + perturbations around that mode. The whole cloud is stop-gradient by + construction: the occupancy may learn *at* current actor queries, but its + likelihood-ranking loss must never update the actor (or a latent adapter + used to compute the actor query). + """ + import jax + import jax.numpy as jnp + + mode = jax.lax.stop_gradient(jnp.clip(actor_mode, -1.0, 1.0)) + local = jax.lax.stop_gradient(jnp.clip( + mode[None, ...] + sigma * local_noise, -1.0, 1.0)) + return jnp.concatenate([mode[None, ...], local], axis=0) + + +def actor_query_contrast_loss(positive_error, negative_errors, weights, + margin): + """Importance-weighted behavior-vs-actor likelihood ranking loss. + + Lower flow-matching error is treated as higher conditional likelihood. + ``negative_errors`` is ``(num_actor_queries, batch)``. This auxiliary + ranks the recorded behavior tuple over detached actor-query relabelings; + it is deliberately not interpreted as counterfactual occupancy truth. + """ + import jax + import jax.numpy as jnp + + per_pair = jax.nn.softplus( + margin + positive_error[None, :] - negative_errors) + return jnp.mean(per_pair * weights[None, :]) + + +def exact_batch_fraction_count(batch_size, fraction): + """Resolve a requested mixture fraction to a deterministic batch count.""" + batch_size = int(batch_size) + fraction = float(fraction) + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0.0 <= fraction <= 1.0: + raise ValueError("fraction must lie in [0, 1]") + return int(round(fraction * batch_size)) + + +def exact_batch_fraction_mask(batch_size, fraction, permutation, + array_module=np): + """Return a shuffled mask with an exact, reproducible mixture count.""" + xp = array_module + batch_size = int(batch_size) + count = exact_batch_fraction_count(batch_size, fraction) + permutation = xp.asarray(permutation) + if permutation.shape != (batch_size,): + raise ValueError( + f"permutation must have shape ({batch_size},), " + f"got {permutation.shape}") + return (xp.arange(batch_size) < count)[permutation] + + +def deterministic_largest_remainder_counts(total, weights): + """Allocate an integer total proportionally with stable tie-breaking.""" + total = int(total) + weights = np.asarray(weights, dtype=np.float64) + if total < 0: + raise ValueError("total must be nonnegative") + if weights.ndim != 1 or weights.size == 0: + raise ValueError("weights must be a nonempty one-dimensional array") + if not np.all(np.isfinite(weights)) or np.any(weights < 0.0): + raise ValueError("weights must be finite and nonnegative") + if not float(weights.sum()) > 0.0: + raise ValueError("weights must have positive total mass") + ideal = total * weights / weights.sum() + counts = np.floor(ideal).astype(np.int64) + remainder = total - int(counts.sum()) + # Stable mergesort makes equal fractional remainders prefer the earlier + # cell, so the allocation is deterministic across NumPy versions. + order = np.argsort(-(ideal - counts), kind="stable") + counts[order[:remainder]] += 1 + return tuple(int(x) for x in counts) + + +def protected_endpoint_batch_plan(batch_size, gamma, beta, horizons): + """Build the exact protected-endpoint discount x goal-source plan. + + The protected recipe fixes 60% of rows at task gamma, 30% at recursive + beta, and gives the remaining 10% to shorter auxiliary horizons in + proportion to ``sqrt(h)``. Any auxiliary horizon whose implied discount + equals beta is removed before allocation. Goal source is cross-stratified + to an exact 50/50 actor-uniform/value-goal split over the whole batch and + differs by at most one row within every discount cell. + """ + batch_size = int(batch_size) + gamma = float(gamma) + beta = float(beta) + horizons = _parse_gamma_horizons(horizons) + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0.0 < beta < gamma < 1.0: + raise ValueError("protected endpoints require 0 < beta < gamma < 1") + if not all(np.isfinite(h) and h > 1.0 for h in horizons): + raise ValueError("all protected auxiliary horizons must exceed one") + if not all(a < b for a, b in zip(horizons[:-1], horizons[1:])): + raise ValueError("protected auxiliary horizons must be increasing") + + requested_discounts = tuple(1.0 - 1.0 / h for h in horizons) + keep = tuple( + not np.isclose(d, beta, rtol=1e-7, atol=1e-9) + for d in requested_discounts) + aux_horizons = tuple(h for h, use in zip(horizons, keep) if use) + aux_discounts = tuple( + d for d, use in zip(requested_discounts, keep) if use) + excluded_horizons = tuple( + h for h, use in zip(horizons, keep) if not use) + if not aux_horizons: + raise ValueError( + "protected endpoints need an auxiliary horizon distinct from beta") + if max(aux_discounts) >= gamma: + raise ValueError( + "protected auxiliary horizons must be shorter than task gamma") + + task_rows = exact_batch_fraction_count(batch_size, 0.60) + beta_rows = exact_batch_fraction_count(batch_size, 0.30) + aux_rows = batch_size - task_rows - beta_rows + if aux_rows < 0: + raise ValueError("protected endpoint allocation exceeds batch size") + aux_counts = deterministic_largest_remainder_counts( + aux_rows, np.sqrt(np.asarray(aux_horizons, np.float64))) + group_counts = (task_rows, beta_rows) + aux_counts + actor_total = exact_batch_fraction_count(batch_size, 0.50) + actor_counts = deterministic_largest_remainder_counts( + actor_total, group_counts) + value_counts = tuple( + count - actor for count, actor in zip(group_counts, actor_counts)) + group_discounts = (gamma, beta) + aux_discounts + + discounts = np.concatenate([ + np.full(count, discount, np.float32) + for count, discount in zip(group_counts, group_discounts) + ]) + actor_goal_mask = np.concatenate([ + np.concatenate([ + np.ones(actor, dtype=bool), + np.zeros(count - actor, dtype=bool), + ]) + for count, actor in zip(group_counts, actor_counts) + ]) + assert discounts.shape == (batch_size,) + assert actor_goal_mask.shape == (batch_size,) + return { + "task_rows": task_rows, + "beta_rows": beta_rows, + "aux_rows": aux_rows, + "requested_horizons": horizons, + "excluded_beta_horizons": excluded_horizons, + "aux_horizons": aux_horizons, + "aux_discounts": aux_discounts, + "aux_rows_by_horizon": aux_counts, + "discount_group_rows": group_counts, + "actor_rows_by_discount": actor_counts, + "value_rows_by_discount": value_counts, + "actor_rows": actor_total, + "value_rows": batch_size - actor_total, + "discounts": discounts, + "actor_goal_mask": actor_goal_mask, + } + + +def reward_metric_endpoint_batch_plan( + batch_size, gamma, beta, horizons, task_fraction=0.50, + beta_fraction=0.25, aux_allocation="uniform"): + """Build the exact discount allocation for reward-metric occupancies. + + By default half of every batch is trained at the task discount, one + quarter at the recursion discount, and the final quarter is divided + evenly over the requested shorter horizons. ``sqrt_h`` instead + prioritizes longer auxiliary horizons in proportion to their square root. + Explicit fractions and allocation allow paired horizon-priority cells to + keep every other factor fixed. Beta remains a supervised occupancy + endpoint even while recursive composition is off, not a TD target. + """ + batch_size = int(batch_size) + gamma = float(gamma) + beta = float(beta) + task_fraction = float(task_fraction) + beta_fraction = float(beta_fraction) + horizons = _parse_gamma_horizons(horizons) + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0.0 < beta < gamma < 1.0: + raise ValueError( + "reward-metric endpoints require 0 < beta < gamma < 1") + if ( + not 0.0 < task_fraction < 1.0 + or not 0.0 < beta_fraction < 1.0 + or not task_fraction + beta_fraction < 1.0): + raise ValueError( + "reward-metric task and beta fractions must be positive and " + "sum to less than one") + if aux_allocation not in ("uniform", "sqrt_h"): + raise ValueError( + "reward-metric auxiliary allocation must be uniform or sqrt_h") + if not horizons: + raise ValueError( + "reward-metric endpoints require auxiliary horizons") + if not all(np.isfinite(h) and h > 1.0 for h in horizons): + raise ValueError( + "all reward-metric auxiliary horizons must exceed one") + if not all(a < b for a, b in zip(horizons[:-1], horizons[1:])): + raise ValueError( + "reward-metric auxiliary horizons must be increasing") + aux_discounts = tuple(1.0 - 1.0 / h for h in horizons) + if max(aux_discounts) >= gamma: + raise ValueError( + "reward-metric auxiliary horizons must be shorter than task gamma") + if any(np.isclose(value, beta, rtol=1e-7, atol=1e-9) + for value in aux_discounts): + raise ValueError( + "reward-metric auxiliary horizons must not duplicate beta") + + task_rows = exact_batch_fraction_count(batch_size, task_fraction) + beta_rows = exact_batch_fraction_count(batch_size, beta_fraction) + aux_rows = batch_size - task_rows - beta_rows + if aux_rows <= 0: + raise ValueError( + "reward-metric exact counts leave no auxiliary rows") + aux_weights = ( + np.ones(len(horizons), np.float64) + if aux_allocation == "uniform" + else np.sqrt(np.asarray(horizons, np.float64))) + aux_counts = deterministic_largest_remainder_counts( + aux_rows, aux_weights) + discounts = np.concatenate([ + np.full(task_rows, gamma, np.float32), + np.full(beta_rows, beta, np.float32), + *[ + np.full(count, discount, np.float32) + for count, discount in zip(aux_counts, aux_discounts) + ], + ]) + assert discounts.shape == (batch_size,) + return { + "task_rows": task_rows, + "beta_rows": beta_rows, + "aux_rows": aux_rows, + "task_fraction": task_fraction, + "beta_fraction": beta_fraction, + "aux_fraction": 1.0 - task_fraction - beta_fraction, + "aux_allocation": aux_allocation, + "aux_horizons": horizons, + "aux_discounts": aux_discounts, + "aux_rows_by_horizon": aux_counts, + "discounts": discounts, + } + + +def reader_metric_coordinate_diagonal(metric_scale, metric_weight): + """Return the invertible diagonal ``sqrt(weight) / scale``. + + A diagonal reader may legally contain zero weights for ordinary reward + read-out, but a zero coordinate would make the proposed occupancy target + non-invertible. This helper therefore fails closed unless every reader + coordinate has finite, strictly positive scale and weight. + """ + metric_scale = np.asarray(metric_scale, np.float32) + metric_weight = np.asarray(metric_weight, np.float32) + if ( + metric_scale.ndim != 1 + or metric_weight.shape != metric_scale.shape): + raise ValueError( + "reader metric scale and weight must be matching vectors") + if ( + not np.all(np.isfinite(metric_scale)) + or not np.all(np.isfinite(metric_weight))): + raise ValueError("reader metric coordinate must be finite") + if np.any(metric_scale <= 0.0) or np.any(metric_weight <= 0.0): + raise ValueError( + "invertible reader metric requires strictly positive scale " + "and weight in every coordinate") + diagonal = np.sqrt(metric_weight) / metric_scale + if not np.all(np.isfinite(diagonal)) or np.any(diagonal <= 0.0): + raise ValueError("reader metric coordinate diagonal is invalid") + return diagonal.astype(np.float32) + + +def encode_reader_metric_future( + future, goal, diagonal, array_module=np): + """Encode ``u = D (z_future - z_goal)`` in reader-metric coordinates.""" + xp = array_module + return ( + xp.asarray(future) - xp.asarray(goal) + ) * xp.asarray(diagonal) + + +def decode_reader_metric_future( + coordinate, goal, inverse_diagonal, array_module=np): + """Invert a reader-metric coordinate back into compact future ``z``.""" + xp = array_module + return ( + xp.asarray(goal) + + xp.asarray(coordinate) * xp.asarray(inverse_diagonal) + ) + + +def actor_uniform_goal_indices(rows, ends, uniforms, array_module=np): + """Map uniform draws to the actor's inclusive future-goal distribution.""" + xp = array_module + rows = xp.asarray(rows) + ends = xp.asarray(ends) + uniforms = xp.asarray(uniforms) + if rows.shape != ends.shape or rows.shape != uniforms.shape: + raise ValueError("rows, ends, and uniforms must have matching shapes") + last = ends - 1 + first = xp.minimum(rows + 1, last) + return xp.round( + first * uniforms + last * (1.0 - uniforms)).astype(rows.dtype) + + +def endpoint_future_hit_mask(rows, goals, row_ends, take_hit, + array_module=np): + """Select sampled future goal hits, excluding current and cross goals.""" + xp = array_module + rows = xp.asarray(rows) + goals = xp.asarray(goals) + row_ends = xp.asarray(row_ends) + take_hit = xp.asarray(take_hit, dtype=bool) + if not ( + rows.shape == goals.shape == row_ends.shape + == take_hit.shape): + raise ValueError( + "rows, goals, row_ends, and take_hit must have matching shapes") + return take_hit & (goals > rows) & (goals < row_ends) + + +def reader_metric_projected_errors( + residual, target_scale, reward_projection, metric_scale, + metric_weight, active_mask, array_module=np): + """Frozen-reader error only, normalized by its pullback trace.""" + xp = array_module + residual = xp.asarray(residual) + target_scale = xp.asarray(target_scale) + reward_projection = xp.asarray(reward_projection) + metric_scale = xp.asarray(metric_scale) + metric_weight = xp.asarray(metric_weight) + active_mask = xp.asarray(active_mask, dtype=residual.dtype) + if residual.shape[-1] != target_scale.shape[0]: + raise ValueError("target_scale does not match residual width") + if reward_projection.shape[0] != residual.shape[-1]: + raise ValueError("reward_projection input width mismatch") + reward_dim = reward_projection.shape[1] + if metric_scale.shape != (reward_dim,): + raise ValueError("metric_scale does not match projection output") + if metric_weight.shape != (reward_dim,): + raise ValueError("metric_weight does not match projection output") + if active_mask.shape != (residual.shape[-1],): + raise ValueError("active_mask does not match residual width") + raw_residual = residual * target_scale * active_mask + projected = (raw_residual @ reward_projection) / metric_scale + metric_denominator = xp.maximum( + reader_metric_pullback_trace( + target_scale, + reward_projection, + metric_scale, + metric_weight, + active_mask, + array_module=xp, + ), + 1e-8, + ) + return ( + xp.square(projected) * metric_weight + ).sum(axis=-1) / metric_denominator + + +def endpoint_hit_reader_loss(reader_errors, hit_mask, discounts, gamma, beta, + array_module=np): + """Unweighted mean reader error at exact gamma and beta future hits.""" + xp = array_module + reader_errors = xp.asarray(reader_errors) + hit_mask = xp.asarray(hit_mask, dtype=bool) + discounts = xp.asarray(discounts) + if ( + reader_errors.shape != hit_mask.shape + or reader_errors.shape != discounts.shape): + raise ValueError( + "reader_errors, hit_mask, and discounts must match") + + def masked_mean(mask): + mask_f = mask.astype(reader_errors.dtype) + return ( + (reader_errors * mask_f).sum() + / xp.maximum(mask_f.sum(), 1.0)) + + gamma_rows = hit_mask & xp.isclose( + discounts, float(gamma), rtol=1e-7, atol=1e-9) + beta_rows = hit_mask & xp.isclose( + discounts, float(beta), rtol=1e-7, atol=1e-9) + return 0.5 * (masked_mean(gamma_rows) + masked_mean(beta_rows)) + + +def occupancy_base_and_endpoint_hit_loss( + base_errors, importance_weights, reader_errors, hit_mask, discounts, + gamma, beta, hit_weight, array_module=np): + """Keep base MLE exact and add an unweighted endpoint reader auxiliary.""" + xp = array_module + base_errors = xp.asarray(base_errors) + importance_weights = xp.asarray(importance_weights) + if base_errors.shape != importance_weights.shape: + raise ValueError("base errors and importance weights must match") + hit_weight = float(hit_weight) + if hit_weight < 0.0: + raise ValueError("hit_weight must be nonnegative") + base = xp.mean(importance_weights * base_errors) + if hit_weight == 0.0: + return base, base, xp.asarray(0.0, dtype=base.dtype) + hit = endpoint_hit_reader_loss( + reader_errors, hit_mask, discounts, gamma, beta, + array_module=xp) + return base + hit_weight * hit, base, hit + + +def backfill_protected_endpoint_metadata(saved_meta): + """Backfill disabled protected/hit fields for exact legacy resume checks.""" + saved_meta = dict(saved_meta) + defaults = { + "protected_endpoint_sampler": False, + "protected_endpoint_task_fraction": None, + "protected_endpoint_beta_fraction": None, + "protected_endpoint_aux_fraction": None, + "protected_endpoint_aux_allocation": None, + "protected_endpoint_overrides_legacy_fraction_flags": None, + "protected_endpoint_requested_horizons": None, + "protected_endpoint_excluded_beta_horizons": None, + "protected_endpoint_goal_source_fraction": None, + "protected_endpoint_actor_rows_by_discount": None, + "protected_endpoint_value_rows_by_discount": None, + "protected_endpoint_cross_stratification": None, + "protected_endpoint_normalizer_discount_rows": None, + "protected_endpoint_normalizer_actor_rows_by_discount": None, + "protected_endpoint_normalizer_value_rows_by_discount": None, + "occ_reader_geometry_enabled": bool( + saved_meta.get("occ_reader_metric_enabled", False)), + "occ_reader_hit_weight": 0.0, + "occ_reader_hit_enabled": False, + "occ_reader_hit_formula": None, + "occ_reader_hit_reader_error_formula": None, + "occ_reader_hit_reader_error_normalization": None, + "occ_reader_hit_mask": None, + "occ_reader_hit_empty_endpoint_mean": None, + "occ_reader_hit_importance_weighted": False, + "occ_reader_hit_endpoint_weights": None, + "occ_reader_hit_base_mle_formula": None, + "occ_reader_hit_total_loss_formula": None, + "occ_reader_hit_take_hit_probability": None, + "occ_reader_hit_target_source": None, + "occ_reader_hit_action_contrast_weights_changed": False, + "occ_reader_hit_uses_index_relabeling": False, + "occ_reader_hit_uses_reward_arrays": False, + "occ_reader_hit_uses_coordinates": False, + "occ_reader_hit_uses_td_or_bootstrap": False, + } + for key, value in defaults.items(): + saved_meta.setdefault(key, value) + return saved_meta + + +def reader_metric_pullback_trace( + target_scale, reward_projection, metric_scale, metric_weight, + active_mask, array_module=np): + """Return the reader metric's trace in standardized future coordinates.""" + xp = array_module + target_scale = xp.asarray(target_scale) + reward_projection = xp.asarray(reward_projection) + metric_scale = xp.asarray(metric_scale) + metric_weight = xp.asarray(metric_weight) + active_mask = xp.asarray(active_mask, dtype=target_scale.dtype) + pullback_squared = ( + xp.square( + target_scale[:, None] + * reward_projection + / metric_scale[None, :]) + * metric_weight[None, :] + * active_mask[:, None]) + return pullback_squared.sum() + + +def reader_metric_flow_errors( + residual, target_scale, reward_projection, metric_scale, + metric_weight, active_mask, auxiliary_weight, + array_module=np): + """Blend ordinary and frozen-reader-projected flow velocity errors. + + ``residual`` is the predicted-minus-target velocity in standardized + occupancy coordinates. The auxiliary first restores raw future units, + projects them through the frozen pixel encoder ``fc_1`` (or identity for + compact-z futures), then measures the residual in the canonical diagonal + reader's scale. Dividing by the trace of this metric pulled back into + standardized future coordinates makes an isotropic unit residual have + expected auxiliary error one. It is also invariant to a global rescaling + of the reader weights, including when a hidden future uses a non-isometric + ``fc_1`` projection. The convex + ``(base + lambda * metric) / (1 + lambda)`` blend preserves the overall + loss scale. No reward, coordinate, return, or bootstrap target is used. + """ + xp = array_module + residual = xp.asarray(residual) + target_scale = xp.asarray(target_scale) + reward_projection = xp.asarray(reward_projection) + metric_scale = xp.asarray(metric_scale) + metric_weight = xp.asarray(metric_weight) + active_mask = xp.asarray(active_mask, dtype=residual.dtype) + auxiliary_weight = float(auxiliary_weight) + if auxiliary_weight < 0.0: + raise ValueError("auxiliary_weight must be nonnegative") + if residual.shape[-1] != target_scale.shape[0]: + raise ValueError("target_scale does not match residual width") + if reward_projection.shape[0] != residual.shape[-1]: + raise ValueError("reward_projection input width mismatch") + reward_dim = reward_projection.shape[1] + if metric_scale.shape != (reward_dim,): + raise ValueError("metric_scale does not match projection output") + if metric_weight.shape != (reward_dim,): + raise ValueError("metric_weight does not match projection output") + if active_mask.shape != (residual.shape[-1],): + raise ValueError("active_mask does not match residual width") + + active_denominator = xp.maximum(active_mask.sum(), 1.0) + base = ( + (xp.square(residual) * active_mask).sum(axis=-1) + / active_denominator) + if auxiliary_weight == 0.0: + return base + raw_residual = residual * target_scale * active_mask + projected = (raw_residual @ reward_projection) / metric_scale + metric_denominator = xp.maximum( + reader_metric_pullback_trace( + target_scale, + reward_projection, + metric_scale, + metric_weight, + active_mask, + array_module=xp, + ), + 1e-8, + ) + metric = ( + xp.square(projected) * metric_weight + ).sum(axis=-1) / metric_denominator + return ( + base + auxiliary_weight * metric + ) / (1.0 + auxiliary_weight) + + +def run_rsm(env_id, seed=0, train_steps=2000000, alpha=1.0, + actor_loss="ddpgbc", expectile=0.7, actor_after=0, + adv_norm=False, actor_q_transform="log", + distill_actor_goals=True, + distill_actor_actions=None, + distill_actor_action_k=2, + distill_actor_action_sigma=0.3, + distill_actor_action_pairwise_weight=1.0, + distill_empirical_index_weight=0.0, + distill_scorer_input="latent", + recursion="auto", rec_beta=0.98, rec_after=100000, rec_guard="off", + rec_max_depth=REC_MAX_DEPTH, rec_beta_sample_prob=0.25, + recursion_state="hidden", gamma_spectrum_lo=0.0, + gamma_sampler="legacy_log_uniform", + gamma_task_fraction=GAMMA_TASK_FRACTION, + gamma_horizons=GAMMA_STRATIFIED_HORIZONS, elbo_K=16, + elbo_logspace=False, elbo_antithetic=False, + occupancy_model="diffusion", occ_hidden=OCC_HIDDEN, + occ_layers=OCC_LAYERS, flow_steps=25, + occ_action_contrast_weight=0.0, + occ_action_contrast_margin=0.1, + occ_action_negative="shuffle", occ_action_negative_sigma=0.3, + occ_action_negative_k=2, + occ_actor_goal_fraction=0.0, + occ_reader_metric_weight=0.0, + occ_reader_hit_weight=0.0, + occ_target_space="absolute_future", + reward_metric_aux_allocation="uniform", + batch_size=4096, occ_batch=2048, + eval_interval=25000, eval_episodes=50, eval_episodes_periodic=15, + latent_npz=None, pixel_encoder=None, drop_proprio=False, + goal_hidden=False, + actor_input="latent", pixel_actor_p_aug=0.5, + latent_npz_sha256=None, pixel_encoder_sha256=None, + pixel_dataset=None, pixel_dataset_sha256=None, + pixel_actor_init_ckpt=None, + pixel_actor_init_ckpt_sha256=None, + reward_decoder=None, rdec_samples=8, + latent_update="frozen", latent_lr=3e-5, latent_hidden=64, + latent_goal_weight=0.1, latent_anchor_weight=0.01, + train_only=False, eval_only=False, eval_actor="ema", + qfilter=0, qfilter_sigma=0.3, qfilter_bc=0.0, + variant_tag=None, save_best=None, wandb_mode="online", + ckpt=None, ckpt_every=None, ckpt_archive_every=None, + resume_ckpt=None, resume_ckpt_sha256=None, + init_occupancy_ckpt=None, + init_occupancy_ckpt_sha256=None, + freeze_occupancy=False, + gamma=GAMMA, + ogbench_impls=OGBENCH_IMPLS): + """Train RSM on one OGBench environment. Returns the result-JSON path. + + ``gamma`` is the desired policy/read-out discount and the spectrum upper + edge. ``rec_beta`` is independently the shorter occupancy-query discount + used by recursion; their geometric continuation probability composes beta + jumps into gamma. It defaults to the module constant ``GAMMA`` (0.99). + The official GCIQL uses 0.995 for humanoidmaze — pass ``gamma=0.995`` to + match that target horizon. + """ + _setup_paths(ogbench_impls) + import jax + import jax.numpy as jnp + import optax + import tqdm + import wandb + from utils.env_utils import make_env_and_datasets + from utils.evaluation import evaluate + from utils.encoders import GCEncoder, encoder_modules + from utils.networks import GCActor, GCValue + import target_extractors + from train_genq_jax import build_ends, cosine_abar, make_model + from agents.gciql import get_config + + # =================================================================== + # 0. Resolve the recipe from the goal space + # =================================================================== + # Discrete goal alphabets get the exact likelihood read-out; continuous + # coordinates get the ELBO read-out. Recursion is part of the recipe in + # BOTH spaces; the guard level differs (DESIGN.md section 3). + is_bits = env_id.startswith("puzzle") + readout = "gl" if is_bits else "elbo" + rec_guard = "off" if rec_guard == "none" else rec_guard # alias + assert not (is_bits and (elbo_logspace or elbo_antithetic)), \ + "--elbo_logspace / --elbo_antithetic apply to the continuous ELBO read-out only" + occupancy_rec_on = recursion == "occupancy" + completion_rec_on = ( + recursion == "on" or (recursion == "auto" and is_bits)) + rec_on = occupancy_rec_on or completion_rec_on + rec_p = ( + occupancy_recursion_continuation(gamma, rec_beta) + if rec_on else 0.0) + if rec_on: + # which parameters serve the policy evaluations INSIDE the chain + # (midpoint re-decisions + the actions continuation values are read at) + chain_pi_src = "EMA actor (lagged ~1/tau updates)" if rec_guard == "ema" \ + else "live actor" + print(f"[rsm] rec_guard={rec_guard}: chain-internal re-decisions use the " + f"{chain_pi_src}", flush=True) + print( + f"[rsm] recursion={recursion}: gamma={gamma:g} beta={rec_beta:g} " + f"continue={rec_p:.6f} expected_hops={1.0 / (1.0 - rec_p):.2f} " + f"depth={rec_max_depth} cap_mass=" + f"{occupancy_recursion_tail_mass(gamma, rec_beta, rec_max_depth):.3g}", + flush=True) + # the discount spectrum is only needed when chains hop at beta + # A discount spectrum can be useful even without recursive composition: + # short-horizon occupancies make the first action's effect much easier to + # identify. Recursion still uses the same encoding for beta hops. + spec_on = gamma_spectrum_lo > 0.0 + assert 0.0 < gamma < 1.0, "task gamma must lie strictly between 0 and 1" + assert gamma_sampler in ( + "legacy_log_uniform", "stratified_bins", "protected_endpoints", + "reward_metric_endpoints"), ( + gamma_sampler) + protected_endpoint_mode = gamma_sampler == "protected_endpoints" + reward_metric_endpoint_mode = ( + gamma_sampler == "reward_metric_endpoints") + assert occ_target_space in ( + "absolute_future", "goal_relative_reader_metric"), ( + occ_target_space) + assert reward_metric_aux_allocation in ("uniform", "sqrt_h"), ( + reward_metric_aux_allocation) + reward_metric_target = ( + occ_target_space == "goal_relative_reader_metric") + gamma_horizons = _parse_gamma_horizons(gamma_horizons) + _aux_gammas = () + assert 0.0 <= gamma_task_fraction <= 1.0, ( + "gamma_task_fraction must lie in [0, 1]") + assert 0.0 <= occ_actor_goal_fraction <= 1.0, ( + "occ_actor_goal_fraction must lie in [0, 1]") + assert occ_reader_metric_weight >= 0.0, ( + "occ_reader_metric_weight must be nonnegative") + assert occ_reader_hit_weight >= 0.0, ( + "occ_reader_hit_weight must be nonnegative") + assert not ( + occ_reader_hit_weight > 0.0 and occ_reader_metric_weight > 0.0), ( + "the endpoint future-hit reader auxiliary preserves the ordinary " + "base MLE exactly and cannot be combined with the legacy globally " + "blended reader metric") + effective_gamma_task_fraction = ( + 0.60 if protected_endpoint_mode + else float(gamma_task_fraction)) + effective_rec_beta_sample_prob = ( + 0.30 if protected_endpoint_mode + else float(rec_beta_sample_prob)) + effective_occ_actor_goal_fraction = ( + 0.50 if ( + protected_endpoint_mode or reward_metric_endpoint_mode) + else float(occ_actor_goal_fraction)) + if spec_on: + assert 0.0 < gamma_spectrum_lo < gamma, ( + "discount-spectrum lower edge must satisfy " + "0 < gamma_spectrum_lo < gamma < 1") + assert 0.0 < effective_gamma_task_fraction < 1.0, ( + "a discount spectrum requires both task-gamma and auxiliary rows; " + "set 0 < gamma_task_fraction < 1") + if gamma_sampler in ( + "stratified_bins", "protected_endpoints", + "reward_metric_endpoints"): + assert gamma_horizons, ( + "stratified gamma sampling requires at least one horizon") + assert all( + np.isfinite(h) and h > 1.0 for h in gamma_horizons), ( + "all stratified horizons must be finite and greater than one") + assert all( + a < b for a, b in zip( + gamma_horizons[:-1], gamma_horizons[1:])), ( + "stratified horizons must be strictly increasing") + if protected_endpoint_mode: + _protected_plan = protected_endpoint_batch_plan( + occ_batch, gamma, rec_beta, gamma_horizons) + _aux_horizons = _protected_plan["aux_horizons"] + _aux_gammas = _protected_plan["aux_discounts"] + elif reward_metric_endpoint_mode: + _reward_metric_plan = reward_metric_endpoint_batch_plan( + occ_batch, gamma, rec_beta, gamma_horizons, + effective_gamma_task_fraction, + effective_rec_beta_sample_prob, + reward_metric_aux_allocation) + _aux_horizons = _reward_metric_plan["aux_horizons"] + _aux_gammas = _reward_metric_plan["aux_discounts"] + else: + _aux_horizons = gamma_horizons + _aux_gammas = tuple(1.0 - 1.0 / h for h in gamma_horizons) + assert min(_aux_gammas) >= gamma_spectrum_lo - 1e-8, ( + "gamma_spectrum_lo must not exceed the shortest stratified " + "horizon's discount") + assert max(_aux_gammas) < gamma, ( + "stratified auxiliary horizons must be shorter than the " + "task-gamma horizon") + if protected_endpoint_mode: + assert spec_on, ( + "protected_endpoints requires explicit discount conditioning") + assert gamma_spectrum_lo <= rec_beta, ( + "the protected beta endpoint must lie inside the encoded discount " + "support: gamma_spectrum_lo <= rec_beta < gamma") + if reward_metric_endpoint_mode: + assert spec_on, ( + "reward_metric_endpoints requires explicit discount conditioning") + assert reward_metric_target, ( + "reward_metric_endpoints is reserved for the goal-relative " + "reader-metric occupancy target") + assert np.isclose(gamma, 0.99, rtol=0.0, atol=1e-12) + assert np.isclose(rec_beta, 0.98, rtol=0.0, atol=1e-12) + assert gamma_horizons == (8.0, 16.0, 32.0, 64.0), ( + "reward-metric occupancy requires auxiliary horizons " + "8,16,32,64") + assert np.isclose( + gamma_spectrum_lo, min(_aux_gammas), rtol=0.0, atol=1e-12), ( + "reward-metric gamma_spectrum_lo must equal the shortest " + "auxiliary horizon's discount") + if occupancy_rec_on: + assert spec_on, ( + "occupancy-only recursion requires explicit discount conditioning; " + "pass a positive --gamma_spectrum_lo") + assert gamma_spectrum_lo <= rec_beta, ( + "the recursive beta query must lie inside the trained discount " + "spectrum: gamma_spectrum_lo <= rec_beta < gamma") + assert ( + 0.0 < effective_rec_beta_sample_prob + <= 1.0 - effective_gamma_task_fraction + 1e-12), ( + "occupancy-only recursion places exact beta mass inside the " + "non-task sampler: require 0 < rec_beta_sample_prob <= " + "1 - gamma_task_fraction") + assert rec_guard in ("off", "ema"), ( + "occupancy-only latent recursion supports rec_guard=off (live " + "recursive actor) or ema (lagged recursive actor)") + if occ_reader_hit_weight > 0.0: + assert protected_endpoint_mode, ( + "the endpoint future-hit reader auxiliary requires the protected " + "gamma/beta endpoint sampler") + assert occupancy_model == "flow" and not is_bits, ( + "the endpoint future-hit reader auxiliary is defined for " + "continuous conditional-flow occupancy only") + assert reward_decoder is not None, ( + "the endpoint future-hit reader auxiliary requires a frozen " + "index reader") + assert latent_npz and pixel_encoder and drop_proprio, ( + "the endpoint future-hit reader auxiliary is restricted to the " + "strict pixels-only latent path with --drop_proprio") + resolved_gamma_sampler = gamma_sampler if spec_on else "fixed_task_gamma" + gamma_normalization = ( + "fixed_fourier_identity" + if spec_on and gamma_sampler in ( + "stratified_bins", "protected_endpoints", + "reward_metric_endpoints") + else "sample_standardized" + if spec_on else "none") + effective_gamma_task_fraction = ( + effective_gamma_task_fraction if spec_on else 1.0) + gamma_horizons_meta = ( + list(_aux_horizons) + if spec_on and gamma_sampler in ( + "stratified_bins", "protected_endpoints", + "reward_metric_endpoints") else None) + gamma_aux_discounts_meta = ( + list(_aux_gammas) + if spec_on and gamma_sampler in ( + "stratified_bins", "protected_endpoints", + "reward_metric_endpoints") else None) + if not spec_on: + gamma_batch_allocation = "all_task_gamma" + elif protected_endpoint_mode: + gamma_batch_allocation = ( + "exact_60pct_task_30pct_beta_10pct_sqrt_h_aux_then_joint_" + "discount_goal_source_shuffle") + elif reward_metric_endpoint_mode: + gamma_batch_allocation = ( + "exact_configurable_task_beta_remaining_aux_" + f"{reward_metric_aux_allocation}_then_shuffle") + elif gamma_sampler == "stratified_bins": + gamma_batch_allocation = ( + "exact_task_count_exact_beta_count_balanced_aux_bins_then_shuffle" + if occupancy_rec_on + else "exact_task_count_balanced_aux_bins_then_shuffle") + else: + gamma_batch_allocation = ( + "independent_task_vs_exact_beta_vs_log_uniform_aux" + if occupancy_rec_on + else "independent_task_vs_log_uniform_aux") + _value_goal_sampler_name = ( + "gciql_value_goals_20_current_50_trajectory_30_random" + if spec_on and gamma_sampler in ( + "stratified_bins", "protected_endpoints", + "reward_metric_endpoints") + else "legacy_same_trajectory_geometric") + condition_normalizer_goal_sampler = ( + f"exact_mixture_actor_uniform_future_" + f"{effective_occ_actor_goal_fraction:g}_" + f"plus_{_value_goal_sampler_name}" + if effective_occ_actor_goal_fraction > 0.0 + else _value_goal_sampler_name) + occ_actor_goal_rows_per_batch = exact_batch_fraction_count( + occ_batch, effective_occ_actor_goal_fraction) + normalizer_actor_goal_rows = exact_batch_fraction_count( + 20000, effective_occ_actor_goal_fraction) + if protected_endpoint_mode: + _task_rows = _protected_plan["task_rows"] + _beta_rows = _protected_plan["beta_rows"] + gamma_aux_rows_per_occ_batch = list( + _protected_plan["aux_rows_by_horizon"]) + _protected_normalizer_plan = protected_endpoint_batch_plan( + 20000, gamma, rec_beta, gamma_horizons) + elif reward_metric_endpoint_mode: + _task_rows = _reward_metric_plan["task_rows"] + _beta_rows = _reward_metric_plan["beta_rows"] + gamma_aux_rows_per_occ_batch = list( + _reward_metric_plan["aux_rows_by_horizon"]) + _reward_metric_normalizer_plan = ( + reward_metric_endpoint_batch_plan( + 20000, gamma, rec_beta, gamma_horizons, + effective_gamma_task_fraction, + effective_rec_beta_sample_prob, + reward_metric_aux_allocation)) + elif spec_on and gamma_sampler == "stratified_bins": + _task_rows = int(round(effective_gamma_task_fraction * int(occ_batch))) + _beta_row_count = ( + int(round(effective_rec_beta_sample_prob * int(occ_batch))) + if occupancy_rec_on else 0) + _beta_rows = _beta_row_count if occupancy_rec_on else None + _aux_rows = int(occ_batch) - _task_rows - _beta_row_count + assert _aux_rows >= 0, ( + "rounded task-gamma and exact-beta allocations exceed occ_batch") + _q, _r = divmod(_aux_rows, len(gamma_horizons)) + gamma_aux_rows_per_occ_batch = [ + _q + int(i < _r) for i in range(len(gamma_horizons))] + else: + _task_rows = None + _beta_rows = None + gamma_aux_rows_per_occ_batch = None + gamma_sampling_meta = { + "gamma_sampler": resolved_gamma_sampler, + "gamma_task_fraction": effective_gamma_task_fraction, + "gamma_horizons": gamma_horizons_meta, + "gamma_aux_discounts": gamma_aux_discounts_meta, + "gamma_batch_allocation": gamma_batch_allocation, + "gamma_task_rows_per_occ_batch": _task_rows, + "gamma_beta_rows_per_occ_batch": _beta_rows, + "gamma_aux_rows_per_occ_batch": gamma_aux_rows_per_occ_batch, + "gamma_sampling_importance_weighted": False, + "gamma_normalization": gamma_normalization, + "gamma_encoding_lo": ( + float(gamma_spectrum_lo) if spec_on else None), + "gamma_encoding_hi": float(gamma) if spec_on else None, + "condition_normalizer_probe_size": 20000, + "condition_normalizer_seed": int(seed), + "condition_normalizer_goal_sampler": ( + condition_normalizer_goal_sampler), + "occupancy_actor_goal_fraction": float( + effective_occ_actor_goal_fraction), + "occupancy_actor_goal_rows_per_batch": int( + occ_actor_goal_rows_per_batch), + "condition_normalizer_actor_goal_rows": int( + normalizer_actor_goal_rows), + "protected_endpoint_sampler": bool(protected_endpoint_mode), + "protected_endpoint_task_fraction": ( + 0.60 if protected_endpoint_mode else None), + "protected_endpoint_beta_fraction": ( + 0.30 if protected_endpoint_mode else None), + "protected_endpoint_aux_fraction": ( + 0.10 if protected_endpoint_mode else None), + "protected_endpoint_aux_allocation": ( + "deterministic_largest_remainder_sqrt_h" + if protected_endpoint_mode else None), + "protected_endpoint_overrides_legacy_fraction_flags": ( + True if protected_endpoint_mode else None), + "protected_endpoint_requested_horizons": ( + list(_protected_plan["requested_horizons"]) + if protected_endpoint_mode else None), + "protected_endpoint_excluded_beta_horizons": ( + list(_protected_plan["excluded_beta_horizons"]) + if protected_endpoint_mode else None), + "protected_endpoint_goal_source_fraction": ( + 0.50 if protected_endpoint_mode else None), + "protected_endpoint_actor_rows_by_discount": ( + list(_protected_plan["actor_rows_by_discount"]) + if protected_endpoint_mode else None), + "protected_endpoint_value_rows_by_discount": ( + list(_protected_plan["value_rows_by_discount"]) + if protected_endpoint_mode else None), + "protected_endpoint_cross_stratification": ( + "exact_global_50pct_each_source_largest_remainder_by_discount" + if protected_endpoint_mode else None), + "protected_endpoint_normalizer_discount_rows": ( + list(_protected_normalizer_plan["discount_group_rows"]) + if protected_endpoint_mode else None), + "protected_endpoint_normalizer_actor_rows_by_discount": ( + list(_protected_normalizer_plan["actor_rows_by_discount"]) + if protected_endpoint_mode else None), + "protected_endpoint_normalizer_value_rows_by_discount": ( + list(_protected_normalizer_plan["value_rows_by_discount"]) + if protected_endpoint_mode else None), + "reward_metric_endpoint_sampler": bool( + reward_metric_endpoint_mode), + "reward_metric_endpoint_task_fraction": ( + float(effective_gamma_task_fraction) + if reward_metric_endpoint_mode else None), + "reward_metric_endpoint_beta_fraction": ( + float(effective_rec_beta_sample_prob) + if reward_metric_endpoint_mode else None), + "reward_metric_endpoint_aux_fraction": ( + float( + 1.0 + - effective_gamma_task_fraction + - effective_rec_beta_sample_prob) + if reward_metric_endpoint_mode else None), + "reward_metric_endpoint_aux_allocation": ( + "deterministic_largest_remainder_" + + ( + "uniform_horizon" + if reward_metric_aux_allocation == "uniform" + else "sqrt_h") + if reward_metric_endpoint_mode else None), + "reward_metric_endpoint_horizons": ( + list(_reward_metric_plan["aux_horizons"]) + if reward_metric_endpoint_mode else None), + "reward_metric_endpoint_normalizer_discount_rows": ( + [ + int(_reward_metric_normalizer_plan["task_rows"]), + int(_reward_metric_normalizer_plan["beta_rows"]), + *[ + int(value) for value in + _reward_metric_normalizer_plan[ + "aux_rows_by_horizon"] + ], + ] + if reward_metric_endpoint_mode else None), + } + hop_disc = rec_beta if spec_on else gamma + + assert eval_interval % STEPS_PER_DISPATCH == 0 + assert not (train_only and eval_only), \ + "--train_only and --eval_only are mutually exclusive" + assert eval_actor in ("live", "ema"), eval_actor + pixel_actor = validate_visual_pixel_actor_run_contract( + actor_input=actor_input, + latent_npz=latent_npz, + pixel_encoder=pixel_encoder, + drop_proprio=drop_proprio, + discount_conditioned=spec_on, + recursion_enabled=rec_on, + freeze_occupancy=freeze_occupancy, + actor_loss=actor_loss, + actor_q_transform=actor_q_transform, + reward_decoder=reward_decoder, + qfilter=qfilter, + latent_npz_sha256=latent_npz_sha256, + pixel_encoder_sha256=pixel_encoder_sha256, + pixel_dataset=pixel_dataset, + pixel_dataset_sha256=pixel_dataset_sha256, + pixel_actor_p_aug=pixel_actor_p_aug, + pixel_actor_init_ckpt=pixel_actor_init_ckpt, + pixel_actor_init_ckpt_sha256=( + pixel_actor_init_ckpt_sha256), + ) + pixel_artifact_provenance = None + if pixel_actor: + pinned = { + "latent_npz": ( + latent_npz, latent_npz_sha256), + "pixel_encoder": ( + pixel_encoder, pixel_encoder_sha256), + "pixel_dataset": ( + pixel_dataset, pixel_dataset_sha256), + } + pixel_artifact_provenance = {} + for label, (path, expected_sha256) in pinned.items(): + real_path = os.path.realpath(os.path.abspath(path)) + if not os.path.isfile(real_path): + raise ValueError( + f"pinned pixel artifact does not exist: " + f"{label}={real_path}") + actual_sha256 = file_sha256(real_path) + if actual_sha256 != expected_sha256: + raise ValueError( + f"{label} SHA-256 mismatch: " + f"expected={expected_sha256} actual={actual_sha256} " + f"path={real_path}") + pixel_artifact_provenance[label] = { + "path": real_path, + "sha256": actual_sha256, + } + latent_npz = pixel_artifact_provenance["latent_npz"]["path"] + pixel_encoder = pixel_artifact_provenance["pixel_encoder"]["path"] + pixel_dataset = pixel_artifact_provenance["pixel_dataset"]["path"] + print( + "[rsm] pinned pixel artifacts verified: " + f"latent={latent_npz_sha256} " + f"encoder={pixel_encoder_sha256} " + f"dataset={pixel_dataset_sha256}", + flush=True, + ) + t0 = time.time() + config = get_config() # reference GCActor sizes / lr / goal mix + assert actor_loss in ( + "ddpgbc", "awr", "awr_distill", "ddpgbc_distill"), actor_loss + # This flag has semantics only for the supervised scalar extractors. It + # defaults ON there because their scorer has no Bellman structure with + # which to extrapolate from value-goal supervision to the actor's much + # longer uniform-future goal distribution. The explicit opt-out remains + # for the historical matched-goal-split control. + distill_actor_goals = bool( + distill_actor_goals + and actor_loss in ("awr_distill", "ddpgbc_distill")) + distill_goal_loss_reduction = ( + "mean_value_and_actor_goals" + if distill_actor_goals else "value_goals_only") + # A deterministic actor can exploit a scalar scorer between the dataset + # actions on which that scorer was fitted. The DDPG+BC distilled extractor + # therefore anchors the scorer on the current mode and a small local action + # cloud by default. AWR never queries Q at actor actions, so this option is + # intentionally inert there. + if distill_actor_actions is None: + distill_actor_actions = actor_loss == "ddpgbc_distill" + distill_actor_actions = bool( + distill_actor_actions and actor_loss == "ddpgbc_distill") + assert not distill_actor_actions or distill_actor_goals, ( + "actor-action scorer support uses the paired behavior action as its " + "point-anchored pairwise reference; enable --distill_actor_goals") + assert int(distill_actor_action_k) == distill_actor_action_k + distill_actor_action_k = int(distill_actor_action_k) + if distill_actor_actions: + assert distill_actor_action_k > 0, ( + "--distill_actor_action_k must be positive when actor-action " + "scorer support is enabled") + assert distill_actor_action_sigma > 0.0, ( + "--distill_actor_action_sigma must be positive") + assert distill_actor_action_pairwise_weight >= 0.0, ( + "--distill_actor_action_pairwise_weight must be nonnegative") + distill_actor_action_candidate_count = ( + 1 + distill_actor_action_k if distill_actor_actions else 0) + distill_actor_action_pairwise_candidate_count = ( + 1 + distill_actor_action_candidate_count + if distill_actor_actions else 0) + distill_actor_action_loss_reduction = ( + "normalized_point_and_pairwise_then_mean_with_existing_support" + if distill_actor_actions else "disabled") + if not 0.0 <= distill_empirical_index_weight <= 1.0: + raise ValueError( + "--distill_empirical_index_weight must lie in [0, 1]") + if distill_empirical_index_weight > 0.0: + assert actor_loss in ("awr_distill", "ddpgbc_distill"), ( + "empirical index-successor anchoring requires a supervised " + "occupancy-Q scorer") + assert reward_decoder is not None, ( + "empirical index-successor anchoring requires the frozen index " + "reward reader") + assert latent_npz and drop_proprio, ( + "empirical index-successor anchoring is restricted to the " + "strictly pixels-only latent path with --drop_proprio") + assert recursion == "off", ( + "empirical behavior-policy successors cannot be blended with " + "composed current-policy recursion targets") + assert latent_update != "adapter", ( + "empirical index-successor anchoring supports the frozen and " + "rich_adapter arms; compact adapter futures would require a " + "different adapted-reader target") + pixel_scorer = validate_visual_pixel_scorer_run_contract( + scorer_input=distill_scorer_input, + pixel_actor=pixel_actor, + actor_loss=actor_loss, + distill_empirical_index_weight=( + distill_empirical_index_weight), + distill_actor_goals=distill_actor_goals, + distill_actor_actions=distill_actor_actions, + discount_conditioned=spec_on, + recursion=recursion, + freeze_occupancy=freeze_occupancy, + drop_proprio=drop_proprio, + pixel_actor_p_aug=pixel_actor_p_aug, + alpha=alpha, + expectile=expectile, + batch_size=batch_size, + ) + assert actor_q_transform in ("log", "raw"), actor_q_transform + assert recursion_state in ("hidden", "compact"), recursion_state + assert occupancy_model in ("diffusion", "flow"), occupancy_model + if occ_reader_metric_weight > 0.0: + assert occupancy_model == "flow", ( + "the frozen-reader metric auxiliary is defined on conditional " + "flow velocity error") + assert latent_npz and drop_proprio and reward_decoder is not None, ( + "the frozen-reader metric auxiliary requires a strictly " + "pixels-only latent artifact and frozen reward reader") + assert occupancy_model != "flow" or ( + not is_bits and reward_decoder is not None), ( + "conditional flow currently supports continuous latents with the " + "classifier reward-under-occupancy read-out") + assert occ_action_negative in ( + "shuffle", "local", "actor_local"), occ_action_negative + assert int(occ_action_negative_k) == occ_action_negative_k + occ_action_negative_k = int(occ_action_negative_k) + actor_query_occ_contrast = bool( + occ_action_contrast_weight > 0 + and occ_action_negative == "actor_local") + if actor_query_occ_contrast: + assert occ_action_negative_k > 0, ( + "--occ_action_negative_k must be positive for actor_local " + "occupancy contrast") + assert occ_action_negative_sigma > 0.0, ( + "--occ_action_negative_sigma must be positive for actor_local " + "occupancy contrast") + assert spec_on, ( + "actor-query occupancy contrast requires explicit discount " + "conditioning; pass a positive --gamma_spectrum_lo") + assert latent_npz and drop_proprio, ( + "actor-query occupancy contrast is a fair visual recipe and " + "requires a strictly pixels-only latent artifact plus " + "--drop_proprio") + assert actor_loss in ("ddpgbc", "ddpgbc_distill"), ( + "actor-query occupancy contrast is only meaningful for an actor " + "that maximizes an occupancy-derived score") + assert not freeze_occupancy, ( + "actor-query occupancy contrast cannot harden a frozen occupancy") + assert occ_action_contrast_weight <= 0 or ( + occupancy_model == "flow" and not is_bits), ( + "action-contrastive likelihood is currently implemented for " + "continuous conditional flow occupancies") + effective_occ_action_negative_k = ( + occ_action_negative_k if actor_query_occ_contrast else 0) + occ_action_negative_candidate_count = ( + 1 + effective_occ_action_negative_k + if actor_query_occ_contrast else + 1 if occ_action_contrast_weight > 0 else 0) + occ_action_negative_policy = ( + "stop_gradient_live_preupdate_pixel_actor_mode_plus_local_gaussian" + if actor_query_occ_contrast and pixel_actor + else "stop_gradient_live_preupdate_latent_actor_mode_plus_local_gaussian" + if actor_query_occ_contrast + else "behavior_action_plus_local_gaussian" + if occ_action_contrast_weight > 0 + and occ_action_negative == "local" + else "batch_rolled_behavior_action" + if occ_action_contrast_weight > 0 else None) + occ_action_negative_actor_source = ( + "live_preupdate_actor" if actor_query_occ_contrast else None) + occ_action_negative_interpretation = ( + "anti_exploitation_likelihood_ranking_not_counterfactual_occupancy" + if actor_query_occ_contrast else None) + occupancy_supervision_kind = ( + "monte_carlo_geometric_futures_plus_detached_actor_query_" + "likelihood_ranking" + if actor_query_occ_contrast + else "monte_carlo_geometric_futures") + occupancy_training_policy = ( + "offline_behavior_futures_with_detached_live_actor_query_negatives" + if actor_query_occ_contrast + else "offline_behavior_data") + joint_update_semantics = ( + "same_fused_step_occupancy_uses_detached_live_preupdate_actor_queries" + if actor_query_occ_contrast and not freeze_occupancy + else "same_fused_step_separate_supervised_losses" + if not freeze_occupancy + else "frozen_occupancy_policy_extraction") + assert latent_update in ( + "frozen", "adapter", "rich_adapter"), latent_update + joint_latent = latent_update in ("adapter", "rich_adapter") + rich_joint_latent = latent_update == "rich_adapter" + if reward_metric_target: + assert reward_metric_endpoint_mode + assert pixel_actor and latent_npz and pixel_encoder and drop_proprio, ( + "goal-relative reader-metric occupancy is restricted to the " + "strict rendered-pixel actor path") + assert occupancy_model == "flow" and not is_bits + assert recursion == "off" and not rec_on, ( + "the reward-metric arm is a one-hop occupancy experiment") + assert goal_hidden, ( + "reward-metric occupancy must condition on frozen h_goal256") + assert latent_update == "frozen" and not joint_latent, ( + "reward-metric coordinates are defined by the frozen z8 reader") + assert int(occ_hidden) == 256 and int(occ_layers) == 4, ( + "reward-metric occupancy uses the plain conditional flow 256x4") + assert int(occ_batch) == 2048, ( + "reward-metric occupancy uses an exact 2048-row allocation") + assert occ_reader_metric_weight == 0.0 + assert occ_reader_hit_weight == 0.0 + assert distill_empirical_index_weight > 0.0, ( + "reward-metric actor extraction requires the absorbing empirical " + "behavior-action index-successor anchor") + assert actor_loss == "ddpgbc_distill" + assert actor_q_transform == "raw" + assert not freeze_occupancy, ( + "reward-metric occupancy and actor must train jointly") + assert not freeze_occupancy or init_occupancy_ckpt, ( + "--freeze_occupancy requires --init_occupancy_ckpt") + assert not init_occupancy_ckpt or not joint_latent, ( + "selective occupancy loading is currently defined only for the frozen " + "latent arm") + if pixel_actor and init_occupancy_ckpt: + if not _is_sha256_digest(init_occupancy_ckpt_sha256): + raise ValueError( + "pixel-policy --init_occupancy_ckpt requires " + "--init_occupancy_ckpt_sha256") + elif init_occupancy_ckpt_sha256 is not None: + if not init_occupancy_ckpt: + raise ValueError( + "--init_occupancy_ckpt_sha256 requires " + "--init_occupancy_ckpt") + if not _is_sha256_digest(init_occupancy_ckpt_sha256): + raise ValueError( + "--init_occupancy_ckpt_sha256 must be a lowercase SHA-256 " + "digest") + assert not ( + actor_loss in ("awr", "awr_distill", "ddpgbc_distill") + and rec_on + and not ( + occupancy_rec_on and actor_loss == "ddpgbc_distill")), ( + "AWR and legacy completion recursion are incompatible. Fair " + "occupancy-only recursion supports matched ddpgbc_distill targets " + "from a stop-gradient composed-occupancy Monte Carlo expectation.") + if occupancy_rec_on: + assert actor_loss in ("ddpgbc", "ddpgbc_distill"), ( + "occupancy-only recursion supports matched supervised DDPG+BC " + "extraction or the direct-gradient DDPG+BC control") + assert actor_q_transform == "raw", ( + "fair visual occupancy recursion matches the reference DDPG+BC " + "extraction with the calibrated raw reward expectation") + assert latent_npz and pixel_encoder and drop_proprio, ( + "fair occupancy-only recursion requires a strictly pixels-only " + "latent artifact and --drop_proprio") + assert latent_update == "frozen", ( + "occupancy-only recursion currently requires a frozen pixel " + "representation so the occupancy target cannot drift") + assert goal_hidden == (recursion_state == "hidden"), ( + "hidden occupancy recursion requires --goal_hidden; compact " + "occupancy recursion must omit it") + assert reward_decoder is not None, ( + "fair visual recursion requires a local index-reward reader " + "at occupancy read-out") + if completion_rec_on and latent_npz: + raise ValueError( + "visual recursion may not use the completion/world-model path; " + "select --recursion occupancy for a closed latent occupancy chain " + "or --recursion off") + if actor_loss in ("awr_distill", "ddpgbc_distill"): + assert spec_on, ( + "supervised occupancy-Q distillation requires explicit discount " + "conditioning; pass a positive --gamma_spectrum_lo") + assert reward_decoder is not None, ( + "supervised occupancy-Q distillation needs the frozen local " + "index-reward reader used to integrate the occupancy") + if joint_latent: + assert latent_npz and drop_proprio, ( + "joint latent adaptation is defined only for the strictly pixels-only " + "cached-latent path") + assert not rec_on, ( + "joint latent adaptation targets the fair visual one-hop recipe " + "with --recursion off") + assert reward_decoder is not None, ( + "joint latent adaptation needs the immediate/index reader as its " + "coordinate-free semantic anchor") + if rich_joint_latent: + assert goal_hidden, ( + "--latent_update rich_adapter requires --goal_hidden so both " + "current and goal hidden features share the adapter") + assert train_only or eval_only, ( + "joint latent runs use separate train-only/eval-only jobs so the " + "time-varying adapter is checkpointed and evaluated exactly") + config["actor_loss"] = actor_loss + config["alpha"] = alpha + config["expectile"] = expectile + if pixel_actor: + config["encoder"] = "impala_small" + config["p_aug"] = float(pixel_actor_p_aug) + config["frame_stack"] = None + # batch is a QUALITY lever here: targets are simulation-based (occupancy + # samples + chain estimates), so a bigger batch directly averages + # generation noise — there is no TD backup to wait on. + config["batch_size"] = int(batch_size) + B_pi = int(config["batch_size"]) + + # =================================================================== + # 1. Dataset -> device arrays + # =================================================================== + state_hidden = False + hidden_occupancy_future = False + state_h_np = None + pixel_obs_np = None + pixel_valid_indices_np = None + pixel_actor_dataset_meta = None + if latent_npz: + # Pixel path (issue #65 Track C): the state is concat(proprio19, z) + # from the precomputed frozen-encoder latents + # (genq/precompute_pixel_latents.py), and z itself IS the + # reward-relevant coordinate — no extract_target. The visual env is + # only needed for eval and is created lazily there (it needs a + # renderer; eval-free CPU smokes never pay for one). + env = None + ld = np.load(latent_npz) + if "encoder_npz" in ld.files: + latent_encoder = os.path.realpath(str(ld["encoder_npz"])) + requested_encoder = os.path.realpath(pixel_encoder) + assert latent_encoder == requested_encoder, ( + "cached pixel latents were produced by a different encoder: " + f"latent artifact records {latent_encoder}, but " + f"--pixel_encoder resolves to {requested_encoder}") + z_np = np.asarray(ld["z"], dtype=np.float32) + # proprio channel: 'proprio' (generic) or legacy 'proprio19' (cube era). + # cube: 19-D arm state; antmaze: 27-D ant state minus xy. The dim is + # free — obs_np is just concat(proprio, z), used only by shape. + pro_key = "proprio" if "proprio" in ld.files else "proprio19" + if drop_proprio: + # strictly-pixels-only: the state IS the frozen-encoder latent alone, + # matching GCIQL's pixels-only input diet (no proprio channel). + # The legacy compact adapter intentionally adapts z. Frozen and + # rich-adapter arms use the encoder's 256-D hidden feature. Fair + # occupancy-only recursion selects its closed recursive state + # explicitly: rich h256 is primary; compact z is the control. + state_hidden = ( + recursion_state == "hidden" if occupancy_rec_on + else "state_h" in ld.files and latent_update != "adapter") + state_h_np = ( + np.asarray(ld["state_h"], dtype=np.float32) + if "state_h" in ld.files else None) + if state_hidden: + assert state_h_np is not None, ( + "hidden occupancy recursion/conditioning requires state_h " + "in the cached latent artifact") + obs_np = state_h_np if state_hidden else z_np + else: + obs_np = np.concatenate([np.asarray(ld[pro_key], dtype=np.float32), z_np], 1) + act_np = np.clip(np.asarray(ld["actions"], dtype=np.float32), -1.0, 1.0) + end_np = build_ends(ld["terminals"]) + if pixel_actor: + import ogbench + + # Use the exact dataset-only loader used by the reproduced visual + # GCIQL control. It does not construct MuJoCo or expose qpos/qvel. + pixel_dataset, _ = ogbench.make_env_and_datasets( + env_id, + dataset_path=pixel_dataset, + compact_dataset=True, + dataset_only=True, + add_info=False, + ) + (pixel_obs_np, pixel_valid_indices_np, + pixel_actor_dataset_meta) = audit_visual_pixel_actor_dataset( + pixel_dataset, act_np, ld["terminals"]) + pixel_actor_dataset_meta.update( + pixel_artifact_provenance["pixel_dataset"]) + print( + "[rsm] trainable pixel actor dataset verified: " + f"shape={pixel_obs_np.shape} dtype={pixel_obs_np.dtype} " + f"valid={len(pixel_valid_indices_np)} " + "actions_aligned=true terminals_aligned=true " + "simulator_state=false coordinates=false reward=false", + flush=True, + ) + # A rich hidden-goal occupancy always models h_j, independently of + # whether recursive composition is enabled. This keeps the one-hop + # frozen and joint-latent arms in the same future space as the + # recursion-ready occupancy recipe. Compact z stays separate and + # enters only the frozen local index-reward reader. + hidden_occupancy_future = bool( + goal_hidden and not reward_metric_target) + if hidden_occupancy_future: + assert state_hidden and state_h_np is not None, ( + "hidden-goal occupancy futures require the cached encoder " + "state_h feature") + tgt_np = state_h_np if hidden_occupancy_future else z_np + reward_goal_np = z_np + else: + env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"]) + obs_np = np.asarray(train_dataset["observations"], dtype=np.float32) + act_np = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1.0, 1.0) + end_np = build_ends(train_dataset["terminals"]) # end_np[i] = end of i's trajectory + # z = the reward-relevant coordinates (puzzle: 9 button bits; mazes: x,y). + # This is the ONLY thing the occupancy models — see target_extractors.py. + tgt_np = target_extractors.extract_target(env_id, obs_np).astype(np.float32) + reward_goal_np = tgt_np + assert not (latent_update == "adapter" and state_hidden), ( + "the compact adapter must use compact z as its state") + if goal_hidden: + assert latent_npz and drop_proprio and state_hidden, ( + "--goal_hidden requires a strictly pixels-only latent artifact " + "containing the frozen encoder's `state_h` feature") + assert not joint_latent or rich_joint_latent, ( + "rich hidden goals may be frozen or use --latent_update " + "rich_adapter, but cannot be paired with the compact-z adapter") + assert not completion_rec_on, ( + "rich hidden goals cannot use the completion-model recursion; use " + "--recursion off or the fair --recursion occupancy path") + assert spec_on, ( + "rich-goal occupancy must explicitly condition on discount; pass " + "--gamma_spectrum_lo with a positive lower edge") + assert qfilter <= 0, ( + "rich-goal Q-filter evaluation needs both h_goal for the actor/" + "occupancy condition and compact z_goal for reward read-out; the " + "current evaluator exposes one goal tensor, so refuse to conflate them") + N = len(obs_np) + a_dim = act_np.shape[1] + n_bits = tgt_np.shape[1] + reward_goal_dim = reward_goal_np.shape[1] + if occupancy_rec_on: + assert obs_np.shape[1] == n_bits, ( + "occupancy-only recursion requires state and generated future in " + "the identical latent space") + start_np = np.empty_like(end_np) + _episode_start = 0 + for _episode_end in np.unique(end_np): + start_np[_episode_start:_episode_end] = _episode_start + _episode_start = int(_episode_end) + assert _episode_start == N + reward_metric_coordinate_scale_np = None + reward_metric_coordinate_weight_np = None + reward_metric_coordinate_diagonal_np = None + reward_metric_coordinate_inverse_np = None + reward_metric_coordinate_reader_meta = None + if reward_metric_target: + _, reward_metric_coordinate_reader_meta = ( + load_jax_reward_reader(reward_decoder)) + _metric_expected = { + "reader_model": "diag_metric", + "target": "index", + "pixels_only_latents": True, + "frozen_encoder": True, + "uses_coordinates_for_training": False, + "uses_coordinates_for_diagnostics": False, + "uses_reward_arrays": False, + "uses_td_or_bootstrap": False, + "label_source": + "trajectory_index_positive_and_far_negative_relabeling", + } + _metric_bad = { + key: ( + reward_metric_coordinate_reader_meta.get(key), expected) + for key, expected in _metric_expected.items() + if reward_metric_coordinate_reader_meta.get(key) != expected + } + assert not _metric_bad, ( + "reward-metric occupancy reader violates the frozen pixels-only " + f"index-relabel contract: {_metric_bad}") + assert int( + reward_metric_coordinate_reader_meta["zdim"]) == n_bits + reward_metric_coordinate_scale_np = np.asarray( + reward_metric_coordinate_reader_meta["metric_scale"], + np.float32) + reward_metric_coordinate_weight_np = np.asarray( + reward_metric_coordinate_reader_meta["metric_weight"], + np.float32) + reward_metric_coordinate_diagonal_np = ( + reader_metric_coordinate_diagonal( + reward_metric_coordinate_scale_np, + reward_metric_coordinate_weight_np)) + reward_metric_coordinate_inverse_np = ( + 1.0 / reward_metric_coordinate_diagonal_np) + # D already supplies the frozen reader's physical scale. A second + # data standardization would erase that geometry, so the conditional + # flow models u directly. + tgt_mu_np = np.zeros((n_bits,), np.float32) + tgt_raw_sd_np = np.ones((n_bits,), np.float32) + tgt_sd_np = np.ones((n_bits,), np.float32) + occupancy_target_standardization = ( + "identity_in_frozen_reader_metric_coordinates") + else: + tgt_mu_np = tgt_np.mean(0) + tgt_raw_sd_np = tgt_np.std(0) + tgt_sd_np = tgt_raw_sd_np + 1e-6 + occupancy_target_standardization = ( + "per_dimension_dataset_mean_std") + # The selected h256 artifact has many exact-dead ReLU units. Keep the full + # h256 actor/condition interface, but exclude only identically constant + # future coordinates from flow noise/loss and pin them to their dataset + # mean during sampling. This is a lossless support constraint, not a + # learned projection or completion model. + future_active_np = ( + tgt_raw_sd_np > 0.0 + if hidden_occupancy_future + else np.ones((n_bits,), dtype=bool)) + future_active_count = int(future_active_np.sum()) + assert future_active_count > 0 + + obs_d = jnp.asarray(obs_np) # ~300 MB device-resident dataset + act_d = jnp.asarray(act_np) + tgt_d = jnp.asarray(tgt_np) + reward_goal_d = jnp.asarray(reward_goal_np) + pixel_obs_d = ( + jnp.asarray(pixel_obs_np) if pixel_actor else None) + pixel_valid_indices_d = ( + jnp.asarray(pixel_valid_indices_np) if pixel_actor else None) + base_z_d = jnp.asarray(z_np) if latent_npz else None + base_adapter_np = ( + state_h_np if rich_joint_latent else z_np + if joint_latent else None) + base_adapter_d = ( + jnp.asarray(base_adapter_np) if base_adapter_np is not None else None) + adapter_sd_j = ( + jnp.asarray(base_adapter_np.std(0) + 1e-6) + if base_adapter_np is not None else None) + end_d = jnp.asarray(end_np.astype(np.int32)) + start_d = jnp.asarray(start_np.astype(np.int32)) + tgt_mu_j, tgt_sd_j = jnp.asarray(tgt_mu_np), jnp.asarray(tgt_sd_np) + future_active_j = jnp.asarray(future_active_np.astype(np.float32)) + future_active_den = jnp.asarray(float(future_active_count)) + # Keep the three goal roles separate. A rich visual arm may condition + # the actor and occupancy on the frozen encoder hidden feature h_g, while + # the modeled future remains frozen h and the reward read-out goal remains + # compact reward-predictive z. This prevents feeding h_g to R_psi. + if goal_hidden: + occ_goal_np = state_h_np + actor_goal_np = state_h_np + else: + occ_goal_np = tgt_np + actor_goal_np = tgt_np if latent_npz else obs_np + occ_goal_d = jnp.asarray(occ_goal_np) + gobs_d = jnp.asarray(actor_goal_np) + if actor_query_occ_contrast: + assert occ_goal_np.shape[1] == actor_goal_np.shape[1], ( + "actor-query occupancy contrast requires each occupancy tuple's " + "goal condition to be the actor's exact goal feature") + state_feature = ( + "joint_encoder_hidden_adapter" if rich_joint_latent + else "encoder_hidden" if state_hidden + else "joint_compact_z_adapter" if joint_latent + else "compact_z" if latent_npz else "state") + actor_goal_feature = ( + "raw_rgb_pixels" if pixel_actor + else "joint_encoder_hidden_adapter" if rich_joint_latent + else "encoder_hidden" if goal_hidden + else "joint_compact_z_adapter" if joint_latent + else "compact_z" if latent_npz else "state") + occupancy_goal_feature = ( + "joint_encoder_hidden_adapter" if rich_joint_latent + else "encoder_hidden" if goal_hidden + else "joint_compact_z_adapter" if joint_latent + else "compact_reward_predictive_z" if latent_npz + else "extracted_target") + future_feature = ( + "frozen_encoder_hidden_occupancy_state" + if hidden_occupancy_future + else "frozen_compact_reward_predictive_z" if rich_joint_latent + else "joint_compact_z_adapter" if joint_latent + else "compact_reward_predictive_z" if latent_npz + else "extracted_target") + reward_goal_feature = ( + "compact_reward_predictive_z" if latent_npz + else future_feature) + if reward_metric_target: + assert not hidden_occupancy_future + assert n_bits == reward_goal_dim + future_feature = "goal_relative_reader_metric_u" + + reward_metric_coordinate_j = ( + jnp.asarray(reward_metric_coordinate_diagonal_np) + if reward_metric_target else None) + reward_metric_coordinate_inverse_j = ( + jnp.asarray(reward_metric_coordinate_inverse_np) + if reward_metric_target else None) + reward_metric_target_meta = { + "occupancy_target_space": ( + "goal_relative_reader_metric" + if reward_metric_target else "absolute_future"), + "occupancy_target_formula": ( + "u_i=sqrt(reader_weight_i)/reader_scale_i*" + "(z_future_i-z_goal_i)" + if reward_metric_target else None), + "occupancy_target_decoder": ( + "z_future_i=z_goal_i+u_i*reader_scale_i/" + "sqrt(reader_weight_i)" + if reward_metric_target else None), + "occupancy_target_invertible": bool(reward_metric_target), + "occupancy_target_reader_frozen": bool(reward_metric_target), + "occupancy_target_reader_model": ( + reward_metric_coordinate_reader_meta["reader_model"] + if reward_metric_target else None), + "occupancy_target_reader_target": ( + reward_metric_coordinate_reader_meta["target"] + if reward_metric_target else None), + "occupancy_target_reader_index_delta": ( + int(reward_metric_coordinate_reader_meta["index_delta"]) + if reward_metric_target else None), + "occupancy_target_metric_scale": ( + reward_metric_coordinate_scale_np.tolist() + if reward_metric_target else None), + "occupancy_target_metric_weight": ( + reward_metric_coordinate_weight_np.tolist() + if reward_metric_target else None), + "occupancy_target_metric_diagonal": ( + reward_metric_coordinate_diagonal_np.tolist() + if reward_metric_target else None), + "occupancy_target_metric_inverse_diagonal": ( + reward_metric_coordinate_inverse_np.tolist() + if reward_metric_target else None), + "occupancy_target_goal_feature": ( + "compact_reward_predictive_z" + if reward_metric_target else None), + "occupancy_decoded_future_feature": ( + "compact_reward_predictive_z" + if reward_metric_target else future_feature), + "occupancy_target_uses_index_relabeling": bool( + reward_metric_target), + "occupancy_target_uses_reward_arrays": False, + "occupancy_target_uses_coordinates": False, + "occupancy_target_uses_td_or_bootstrap": False, + } + + # Optional reader-aligned optimization geometry. This never consumes a + # reward label: it uses only the frozen diagonal metric learned from + # trajectory-index relabeling. The ordinary flow loss remains present, + # while a normalized auxiliary emphasizes velocity error in the compact + # subspace that the frozen reader can distinguish. For recursive h256 + # futures the known encoder fc_1 is a fixed linear projection; for compact + # z futures the projection is identity. + occ_reader_metric_enabled = bool(occ_reader_metric_weight > 0.0) + occ_reader_hit_enabled = bool(occ_reader_hit_weight > 0.0) + occ_reader_geometry_enabled = bool( + occ_reader_metric_enabled or occ_reader_hit_enabled) + occ_reader_metric_model = None + occ_reader_metric_target = None + occ_reader_metric_projection_source = None + occ_reader_metric_scale_np = None + occ_reader_metric_weights_np = None + occ_reader_projection_np = None + occ_reader_metric_pullback_trace_np = None + if occ_reader_geometry_enabled: + _, _occ_metric_meta = load_jax_reward_reader(reward_decoder) + assert _occ_metric_meta["reader_model"] == "diag_metric", ( + "the flow metric auxiliary requires the canonical diagonal " + "index reader") + assert _occ_metric_meta["target"] == "index", ( + "the flow metric auxiliary may use index relabeling only") + assert _occ_metric_meta.get("pixels_only_latents") is True + assert _occ_metric_meta.get("frozen_encoder") is True + assert _occ_metric_meta.get("uses_coordinates_for_training") is False + assert _occ_metric_meta.get("uses_coordinates_for_diagnostics") is False + assert _occ_metric_meta.get("uses_reward_arrays") is False + assert _occ_metric_meta.get("uses_td_or_bootstrap") is False + reward_metric_dim = int(_occ_metric_meta["zdim"]) + occ_reader_metric_scale_np = np.asarray( + _occ_metric_meta["metric_scale"], np.float32) + occ_reader_metric_weights_np = np.asarray( + _occ_metric_meta["metric_weight"], np.float32) + assert float(occ_reader_metric_weights_np.sum()) > 0.0 + if n_bits == reward_metric_dim: + occ_reader_projection_np = np.eye(n_bits, dtype=np.float32) + occ_reader_metric_projection_source = ( + "identity_compact_reward_latent") + else: + assert ( + hidden_occupancy_future + and pixel_encoder is not None), ( + "a non-compact occupancy future needs the frozen encoder " + "fc_1 reader projection") + with np.load(pixel_encoder) as _metric_encoder: + occ_reader_projection_np = np.asarray( + _metric_encoder["fc_1.weight"], np.float32).T + assert occ_reader_projection_np.shape == ( + n_bits, reward_metric_dim) + occ_reader_metric_projection_source = ( + "frozen_pixel_encoder_fc1_linear_velocity_projection") + occ_reader_metric_model = _occ_metric_meta["reader_model"] + occ_reader_metric_target = _occ_metric_meta["target"] + occ_reader_metric_pullback_trace_np = float( + reader_metric_pullback_trace( + tgt_sd_np, + occ_reader_projection_np, + occ_reader_metric_scale_np, + occ_reader_metric_weights_np, + future_active_np, + )) + assert occ_reader_metric_pullback_trace_np > 0.0 + print( + "[rsm] occupancy frozen-reader geometry: " + f"global_weight={occ_reader_metric_weight:g} " + f"endpoint_hit_weight={occ_reader_hit_weight:g} " + f"projection={occ_reader_metric_projection_source} " + "normalization=pullback_trace " + f"trace={occ_reader_metric_pullback_trace_np:.6g}; " + "source=index relabeling only", + flush=True, + ) + occ_reader_metric_scale_j = ( + jnp.asarray(occ_reader_metric_scale_np) + if occ_reader_geometry_enabled else None) + occ_reader_metric_weights_j = ( + jnp.asarray(occ_reader_metric_weights_np) + if occ_reader_geometry_enabled else None) + occ_reader_projection_j = ( + jnp.asarray(occ_reader_projection_np) + if occ_reader_geometry_enabled else None) + occ_reader_metric_meta = { + "occ_reader_metric_weight": float(occ_reader_metric_weight), + "occ_reader_metric_enabled": occ_reader_metric_enabled, + "occ_reader_metric_model": occ_reader_metric_model, + "occ_reader_metric_target": occ_reader_metric_target, + "occ_reader_metric_projection": + occ_reader_metric_projection_source, + "occ_reader_metric_formula": ( + "sum(reader_weight*((raw_velocity_error@projection)" + "/reader_scale)^2)/" + "sum(active_dim[:,None]*(target_std[:,None]*projection/" + "reader_scale[None,:])^2*reader_weight[None,:])" + if occ_reader_metric_enabled else None), + "occ_reader_metric_normalization": ( + "active_standardized_coordinate_pullback_trace" + if occ_reader_metric_enabled else None), + "occ_reader_metric_pullback_trace": ( + occ_reader_metric_pullback_trace_np + if occ_reader_geometry_enabled else None), + "occ_reader_metric_loss_reduction": ( + "(base_flow_mse+lambda*reader_metric_mse)/(1+lambda)" + if occ_reader_metric_enabled else "base_flow_mse_only"), + "occ_reader_metric_scale": ( + occ_reader_metric_scale_np.tolist() + if occ_reader_geometry_enabled else None), + "occ_reader_metric_weights": ( + occ_reader_metric_weights_np.tolist() + if occ_reader_geometry_enabled else None), + "occ_reader_metric_uses_index_relabeling": bool( + occ_reader_geometry_enabled), + "occ_reader_metric_uses_reward_arrays": False, + "occ_reader_metric_uses_coordinates": False, + "occ_reader_metric_uses_td_or_bootstrap": False, + "occ_reader_geometry_enabled": occ_reader_geometry_enabled, + "occ_reader_hit_weight": float(occ_reader_hit_weight), + "occ_reader_hit_enabled": occ_reader_hit_enabled, + "occ_reader_hit_formula": ( + "lambda_hit*0.5*(mean(reader_metric_error|future_hit," + "discount=task_gamma)+mean(reader_metric_error|future_hit," + "discount=rec_beta))" + if occ_reader_hit_enabled else None), + "occ_reader_hit_reader_error_formula": ( + "sum(reader_weight*((raw_velocity_error@projection)" + "/reader_scale)^2)/active_standardized_coordinate_" + "pullback_trace" + if occ_reader_hit_enabled else None), + "occ_reader_hit_reader_error_normalization": ( + "active_standardized_coordinate_pullback_trace" + if occ_reader_hit_enabled else None), + "occ_reader_hit_mask": ( + "same_trajectory_and_goal_index_gt_t_and_take_hit" + if occ_reader_hit_enabled else None), + "occ_reader_hit_empty_endpoint_mean": ( + "zero" if occ_reader_hit_enabled else None), + "occ_reader_hit_importance_weighted": False, + "occ_reader_hit_endpoint_weights": ( + [0.5, 0.5] if occ_reader_hit_enabled else None), + "occ_reader_hit_base_mle_formula": ( + "E_q[w_IS*e_base]=" + "mean(hit_miss_importance_weight*base_flow_mse)" + if occ_reader_hit_enabled else None), + "occ_reader_hit_total_loss_formula": ( + "E_q[w_IS*e_base]+lambda_hit*0.5*" + "(mean_hit_task_gamma[e_reader]+mean_hit_rec_beta[e_reader])" + if occ_reader_hit_enabled else None), + "occ_reader_hit_take_hit_probability": ( + float(RT_ETA) if occ_reader_hit_enabled else None), + "occ_reader_hit_target_source": ( + "sampled_same_trajectory_future_index_relabel_take_hit" + if occ_reader_hit_enabled else None), + "occ_reader_hit_action_contrast_weights_changed": False, + "occ_reader_hit_uses_index_relabeling": bool( + occ_reader_hit_enabled), + "occ_reader_hit_uses_reward_arrays": False, + "occ_reader_hit_uses_coordinates": False, + "occ_reader_hit_uses_td_or_bootstrap": False, + } + + # =================================================================== + # 2. The occupancy model p(z | s, a, gamma~) + # =================================================================== + # One conditional diffusion MLP. Discrete goals: a masked DISCRETE + # diffusion over the bits (input = [current bits, mask]); continuous + # goals: a standard eps-prediction Gaussian diffusion over z. + # The condition is [s, a, goal-condition, enc(gamma~)]. goal-condition + # is compact z in the legacy path and frozen h_g with --goal_hidden. + g_cols = 2 * FOURIER_K if spec_on else 0 + cond_dim = obs_np.shape[1] + a_dim + occ_goal_np.shape[1] + g_cols + occ_x_dim = 2 * n_bits if is_bits else n_bits + + occ_model = make_model( + cond_dim, n_bits, occ_hidden, occ_layers, OCC_TIME_DIM) + key = jax.random.PRNGKey(seed) + key, ik = jax.random.split(key) + occ_params = occ_model.init(ik, jnp.zeros((1, occ_x_dim)), jnp.zeros((1,)), + jnp.zeros((1, cond_dim))) + occ_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(OCC_LR)) + occ_opt = occ_tx.init(occ_params) + occ_ema = jax.tree_util.tree_map(lambda x: x, occ_params) # read-outs use the EMA + + # Policy-extraction control: transplant only the trained occupancy state + # from another RSM checkpoint, while initializing a fresh actor below. + # This holds p(z'|s,a,g) exactly fixed when comparing AWR with the + # reference GCIQL DDPG+BC extraction recipe. + if init_occupancy_ckpt: + import pickle as _pickle + init_occupancy_ckpt = os.path.realpath( + os.path.abspath(init_occupancy_ckpt)) + if not os.path.isfile(init_occupancy_ckpt): + raise ValueError( + "source occupancy checkpoint does not exist: " + f"{init_occupancy_ckpt}") + if init_occupancy_ckpt_sha256 is not None: + actual_init_occupancy_sha256 = file_sha256( + init_occupancy_ckpt) + if ( + actual_init_occupancy_sha256 + != init_occupancy_ckpt_sha256): + raise ValueError( + "source occupancy checkpoint SHA-256 mismatch: " + f"expected={init_occupancy_ckpt_sha256} " + f"actual={actual_init_occupancy_sha256} " + f"path={init_occupancy_ckpt}") + with open(init_occupancy_ckpt, "rb") as f: + _source = _pickle.load(f) + _sm = _source.get("run_meta", {}) + if _sm: + _expected = { + "env": env_id, + "seed": int(seed), + "state_dim": int(obs_np.shape[1]), + "occupancy_goal_dim": int(occ_goal_d.shape[1]), + "future_feature": future_feature, + "occupancy_future_dim": int(n_bits), + "occupancy_target_space": ( + reward_metric_target_meta[ + "occupancy_target_space"]), + "occupancy_target_standardization": ( + occupancy_target_standardization), + "reward_reader_dim": int(reward_goal_dim), + "occupancy_active_future_dims": int( + future_active_count), + "occupancy_constant_future_dims": int( + n_bits - future_active_count), + "constant_future_masking": bool( + future_active_count < n_bits), + "drop_proprio": bool(drop_proprio), + "goal_hidden": bool(goal_hidden), + "gamma": float(gamma), + "gamma_spectrum_lo": float(gamma_spectrum_lo), + "discount_conditioned": bool(spec_on), + "gamma_sampler": resolved_gamma_sampler, + "gamma_task_fraction": effective_gamma_task_fraction, + "gamma_horizons": gamma_horizons_meta, + "gamma_normalization": gamma_normalization, + "condition_normalizer_goal_sampler": ( + condition_normalizer_goal_sampler), + "occupancy_actor_goal_fraction": float( + effective_occ_actor_goal_fraction), + "occ_reader_metric_weight": float( + occ_reader_metric_weight), + "occ_reader_hit_weight": float( + occ_reader_hit_weight), + "occ_reader_metric_projection": + occ_reader_metric_projection_source, + "occupancy_model": occupancy_model, + "occ_hidden": int(occ_hidden), + "occ_layers": int(occ_layers), + } + if protected_endpoint_mode: + _expected["rec_beta"] = float(rec_beta) + _sm = dict(_sm) + _sm.setdefault("occupancy_model", "diffusion") + _sm.setdefault("occ_hidden", OCC_HIDDEN) + _sm.setdefault("occ_layers", OCC_LAYERS) + _sm.setdefault("occupancy_goal_dim", _sm.get("goal_dim")) + _sm.setdefault( + "future_feature", "compact_reward_predictive_z") + _sm.setdefault( + "occupancy_target_space", "absolute_future") + _sm.setdefault( + "occupancy_target_standardization", + "per_dimension_dataset_mean_std") + _sm.setdefault( + "occupancy_future_dim", _sm.get("reward_goal_dim")) + _sm.setdefault( + "reward_reader_dim", _sm.get("reward_goal_dim")) + _sm.setdefault( + "occupancy_active_future_dims", + _sm.get("occupancy_future_dim")) + _sm.setdefault("occupancy_constant_future_dims", 0) + _sm.setdefault("constant_future_masking", False) + _sm.setdefault("goal_hidden", False) + _sm.setdefault("gamma_spectrum_lo", 0.0) + _sm.setdefault("discount_conditioned", False) + _sm.setdefault( + "gamma_sampler", + "legacy_log_uniform" + if _sm["discount_conditioned"] else "fixed_task_gamma") + _sm.setdefault( + "gamma_task_fraction", + GAMMA_TASK_FRACTION if _sm["discount_conditioned"] else 1.0) + _sm.setdefault("gamma_horizons", None) + _sm.setdefault( + "gamma_normalization", + "sample_standardized" + if _sm["discount_conditioned"] else "none") + _sm.setdefault( + "condition_normalizer_goal_sampler", + "legacy_same_trajectory_geometric") + _sm.setdefault("occupancy_actor_goal_fraction", 0.0) + _sm.setdefault("occ_reader_metric_weight", 0.0) + _sm.setdefault("occ_reader_hit_weight", 0.0) + _sm.setdefault("occ_reader_metric_projection", None) + _sm.setdefault("seed", int(_source.get("seed", -1))) + _bad = {k: (_sm.get(k), v) for k, v in _expected.items() + if _sm.get(k) != v} + if _bad: + raise ValueError( + "source occupancy checkpoint is incompatible with this run: " + f"{_bad}") + occ_params, occ_opt, occ_ema = jax.device_put(_source["carry"][:3]) + print(f"[rsm] initialized occupancy params/optimizer/EMA from " + f"{init_occupancy_ckpt}; fresh {actor_loss} actor", flush=True) + + # Optional jointly trained residual projection. The convolutional image + # backbone remains the selected pixels-only encoder. ``adapter`` operates + # on compact z; ``rich_adapter`` operates on cached h256 for both current + # and goal conditions while keeping occupancy futures in frozen h and + # reward-reader goals in frozen compact z. A zero output makes step zero + # exactly the + # corresponding frozen arm. The future side is stop-gradient below, while + # current/goal conditions, an immediate-index auxiliary, and a small + # identity anchor update the projection. + latent_params = latent_opt = latent_ema = None + _joint_rdec_logit_fn = None + _joint_reader_model = None + _joint_index_negative_contract = None + _joint_target = None + _joint_index_delta = 0 + _joint_neg_gap = 1 + _rich_to_z_w = _rich_to_z_b = None + if joint_latent: + key, kla0, kla1 = jax.random.split(key, 3) + adapter_dim = int(base_adapter_np.shape[1]) + latent_params = { + "a0.kernel": jax.random.normal( + kla0, (adapter_dim, latent_hidden)) * + np.sqrt(2.0 / adapter_dim), + "a0.bias": jnp.zeros((latent_hidden,)), + "a1.kernel": jnp.zeros((latent_hidden, adapter_dim)), + "a1.bias": jnp.zeros((adapter_dim,)), + } + latent_tx = optax.chain( + optax.clip_by_global_norm(1.0), optax.adamw(latent_lr)) + latent_opt = latent_tx.init(latent_params) + latent_ema = jax.tree_util.tree_map(lambda x: x, latent_params) + _rdj = np.load(reward_decoder) + assert int(_rdj["zdim"]) == int(z_np.shape[1]) + _joint_rdec_logit_fn, _joint_reader_meta = ( + load_jax_reward_reader(reward_decoder)) + _joint_reader_model = _joint_reader_meta["reader_model"] + _joint_target = ( + str(_rdj["target"]) if "target" in _rdj.files else "unknown") + assert _joint_target == "index", ( + "joint latent adaptation requires an immediate/index reader; " + "discounted-return supervision would double-count the horizon") + _joint_index_delta = int( + _rdj["index_delta"]) if "index_delta" in _rdj.files else 0 + _joint_neg_gap = int( + _rdj["neg_gap"]) if "neg_gap" in _rdj.files else ( + _joint_index_delta + 1) + assert _joint_neg_gap > _joint_index_delta, ( + "index-reader relabeling requires neg_gap > index_delta so " + "positive and negative horizon labels cannot overlap") + _joint_index_negative_contract = ( + "same_episode_far_only_cross_episode_excluded" + if _joint_reader_model == "diag_metric" + else "same_episode_far_or_cross_episode") + if rich_joint_latent: + _pe = np.load(pixel_encoder) + _rich_to_z_w = jnp.asarray( + np.asarray(_pe["fc_1.weight"], np.float32).T) + _rich_to_z_b = jnp.asarray( + np.asarray(_pe["fc_1.bias"], np.float32)) + assert _rich_to_z_w.shape == ( + adapter_dim, int(z_np.shape[1])) + print(f"[rsm] JOINT latent residual adapter: hidden={latent_hidden} " + f"space={'h256' if rich_joint_latent else 'z'} " + f"lr={latent_lr:g} goal_weight={latent_goal_weight:g} " + f"anchor_weight={latent_anchor_weight:g}; " + f"reader={_joint_reader_model}; " + f"aux=index(delta={_joint_index_delta},neg_gap={_joint_neg_gap}," + f"negative_contract={_joint_index_negative_contract}); " + f"future target stop-grad", + flush=True) + + def latent_apply(lp, z): + if not joint_latent: + return z + h = jax.nn.relu(z @ lp["a0.kernel"] + lp["a0.bias"]) + return z + h @ lp["a1.kernel"] + lp["a1.bias"] + + def joint_reader_z(adapted): + if rich_joint_latent: + return adapted @ _rich_to_z_w + _rich_to_z_b + return adapted + + def joint_rdec_logit(zs, zg): + assert _joint_rdec_logit_fn is not None + return _joint_rdec_logit_fn(zs, zg) + + abar = cosine_abar(OCC_T) # cosine noise schedule + abar_j = jnp.asarray(abar) + # per-bit unmasking timestep for the any-order discrete diffusion + kappas = np.arange(n_bits, dtype=np.float64) / n_bits + ts_frac = jnp.asarray(np.array( + [(1 + int(np.argmin(np.abs(abar - k)))) / OCC_T for k in kappas], dtype=np.float32)) + logg = float(np.log(gamma)) + + # ---- discount spectrum: sample gamma~, encode it with Fourier features ---- + # Every occupancy row carries an explicit gamma~. The legacy control draws + # auxiliary rows log-uniformly in horizon space. The prioritized recipe + # instead gives every batch near-exact balanced coverage of fixed short + # horizons, then shuffles those rows together with an exact task-gamma + # fraction. This changes only the supervised occupancy data curriculum: + # there is still no reward, next-state value, Bellman target, or TD update. + # + # The encoding is Fourier features of normalized log horizon. Its support + # is fixed by [gamma_spectrum_lo, gamma], independent of how often each + # conditioning discount is sampled. + lo_h = float(np.log(1.0 / (1.0 - gamma_spectrum_lo))) if spec_on else 0.0 + hi_h = float(np.log(1.0 / (1.0 - gamma))) + _fr_np = (np.pi * (2.0 ** np.arange(FOURIER_K))).astype(np.float32) + _fr_j = jnp.asarray(_fr_np) + + def g_enc(dv): + u = (jnp.log(1.0 / (1.0 - dv)) - lo_h) / max(hi_h - lo_h, 1e-8) + ang = u[:, None] * _fr_j[None, :] + return jnp.concatenate([jnp.sin(ang), jnp.cos(ang)], -1) + + def g_enc_np(dv): + u = (np.log(1.0 / (1.0 - dv)) - lo_h) / max(hi_h - lo_h, 1e-8) + ang = u[:, None] * _fr_np[None, :] + return np.concatenate([np.sin(ang), np.cos(ang)], -1).astype(np.float32) + + # Condition-normalization stats from a deterministic 20k-pair probe. + # New stratified runs probe the exact 20/50/30 GCIQL value-goal curriculum + # and exact gamma mixture. Legacy runs retain the old same-trajectory + # probe so historical checkpoints remain resumable. + rng_np = np.random.default_rng(seed) + t_p = rng_np.integers(0, N, 20000) + gi_traj_p = np.minimum( + t_p + rng_np.geometric(1 - gamma, 20000), end_np[t_p] - 1) + if spec_on and gamma_sampler in ( + "stratified_bins", "protected_endpoints", + "reward_metric_endpoints"): + gi_rand_p = rng_np.integers(0, N, 20000) + is_traj_p = rng_np.random(20000) < 0.5 / 0.8 + is_cur_p = rng_np.random(20000) < 0.2 + gi_p = np.where(is_traj_p, gi_traj_p, gi_rand_p) + gi_p = np.where(is_cur_p, t_p, gi_p) + else: + gi_p = gi_traj_p + protected_probe_discounts = None + protected_probe_actor_mask = None + reward_metric_probe_discounts = None + if protected_endpoint_mode: + _protected_probe_order = rng_np.permutation(20000) + protected_probe_discounts = ( + _protected_normalizer_plan["discounts"][ + _protected_probe_order]) + protected_probe_actor_mask = ( + _protected_normalizer_plan["actor_goal_mask"][ + _protected_probe_order]) + assert int(protected_probe_actor_mask.sum()) == ( + normalizer_actor_goal_rows) + elif reward_metric_endpoint_mode: + _reward_metric_probe_order = rng_np.permutation(20000) + reward_metric_probe_discounts = ( + _reward_metric_normalizer_plan["discounts"][ + _reward_metric_probe_order]) + if effective_occ_actor_goal_fraction > 0.0: + actor_uniform_p = rng_np.random(20000) + gi_actor_p = actor_uniform_goal_indices( + t_p, end_np[t_p], actor_uniform_p) + actor_goal_mask_p = ( + protected_probe_actor_mask + if protected_endpoint_mode + else exact_batch_fraction_mask( + 20000, + effective_occ_actor_goal_fraction, + rng_np.permutation(20000), + )) + assert int(actor_goal_mask_p.sum()) == normalizer_actor_goal_rows + gi_p = np.where(actor_goal_mask_p, gi_actor_p, gi_p) + + def _np_gammas(n): + if protected_endpoint_mode: + plan = protected_endpoint_batch_plan( + n, gamma, rec_beta, gamma_horizons) + return plan["discounts"][rng_np.permutation(n)] + if reward_metric_endpoint_mode: + plan = reward_metric_endpoint_batch_plan( + n, gamma, rec_beta, gamma_horizons, + effective_gamma_task_fraction, + effective_rec_beta_sample_prob, + reward_metric_aux_allocation) + return plan["discounts"][rng_np.permutation(n)] + if gamma_sampler == "stratified_bins": + task_count = int(round(effective_gamma_task_fraction * n)) + beta_count = ( + int(round(effective_rec_beta_sample_prob * n)) + if occupancy_rec_on else 0) + aux_count = n - task_count - beta_count + assert aux_count >= 0 + aux_values = np.asarray(_aux_gammas, np.float32) + aux = aux_values[np.arange(aux_count) % len(aux_values)] + draws = np.concatenate([ + np.full(task_count, gamma, np.float32), + np.full(beta_count, rec_beta, np.float32), + aux]) + return draws[rng_np.permutation(n)] + h = np.exp(rng_np.uniform(np.log(1.0 / (1.0 - gamma_spectrum_lo)), + np.log(1.0 / (1.0 - gamma)), n)) + gam = 1.0 - 1.0 / h + route = rng_np.random(n) + if occupancy_rec_on: + # Preserve the base sampler's task mass. Exact beta is an + # absolute-mass overlay inside the non-task portion; only the + # remaining auxiliary mass follows the base log-uniform sampler. + return np.where( + route >= 1.0 - effective_gamma_task_fraction, gamma, + np.where( + route < effective_rec_beta_sample_prob, rec_beta, gam)) + return np.where( + route >= 1.0 - effective_gamma_task_fraction, gamma, gam) + + normalizer_gammas = ( + protected_probe_discounts + if protected_endpoint_mode + else reward_metric_probe_discounts + if reward_metric_endpoint_mode + else _np_gammas(20000)) + gpart = [g_enc_np(normalizer_gammas)] if spec_on else [] + cond_p = np.concatenate( + [obs_np[t_p], act_np[t_p], occ_goal_np[gi_p]] + gpart, axis=1) + cond_mean_np = cond_p.mean(0).astype(np.float32) + cond_std_np = (cond_p.std(0) + 1e-6).astype(np.float32) + if gamma_normalization == "fixed_fourier_identity": + # Fourier features already have a fixed [-1, 1] scale. Leaving them + # unstandardized prevents the curriculum frequency from changing the + # meaning of a discount at inference and avoids off-support blow-ups. + cond_mean_np[-g_cols:] = 0.0 + cond_std_np[-g_cols:] = 1.0 + cond_mean = jnp.asarray(cond_mean_np) + cond_std = jnp.asarray(cond_std_np) + + actor_encoder = ( + GCEncoder( + concat_encoder=encoder_modules["impala_small"]()) + if pixel_actor else None) + actor_def = GCActor( + hidden_dims=tuple(config["actor_hidden_dims"]), + action_dim=a_dim, + state_dependent_std=False, + const_std=config["const_std"], + gc_encoder=actor_encoder, + ) + + def pixel_actor_batch(k, rows, goals, pixel_observations): + """Gather and augment an exact visual actor state/goal batch. + + This matches the reference augmentation semantics: one Bernoulli draw + decides whether the whole batch is augmented, and one shared crop + offset per row is applied to both that row's state and goal image. + """ + assert pixel_actor + states = pixel_observations[rows] + goal_images = pixel_observations[goals] + if pixel_actor_p_aug <= 0.0: + return states, goal_images + k_apply, k_crop = jax.random.split(k) + crop_xy = jax.random.randint( + k_crop, (rows.shape[0], 2), 0, 7) + apply_crop = ( + jax.random.uniform(k_apply, ()) + < pixel_actor_p_aug) + return visual_actor_shared_random_crop( + states, goal_images, crop_xy, apply_crop, + ) + + def pixel_actor_scorer_batch( + k, rows, value_goals, actor_goals, pixel_observations): + """Gather one shared visual-GCIQL crop for actor and scorer inputs. + + The reference image dataset applies one batch-level augmentation + decision and the same per-row crop offset to observations, value + goals, and actor goals. Keeping that alignment matters here because + the actor differentiates through the independently parameterized + pixel scorer at the actor-goal pair. + """ + assert pixel_scorer + states = pixel_observations[rows] + value_goal_images = pixel_observations[value_goals] + actor_goal_images = pixel_observations[actor_goals] + k_apply, k_crop = jax.random.split(k) + crop_xy = jax.random.randint( + k_crop, (rows.shape[0], 2), 0, 7) + apply_crop = ( + jax.random.uniform(k_apply, ()) + < pixel_actor_p_aug) + scorer_states, scorer_value_goals = ( + visual_actor_shared_random_crop( + states, value_goal_images, crop_xy, apply_crop)) + actor_states, scorer_actor_goals = ( + visual_actor_shared_random_crop( + states, actor_goal_images, crop_xy, apply_crop)) + # Both calls use the identical deterministic state crop. Return one + # copy so actor and scorer query exactly the same augmented pixels. + del actor_states + return ( + scorer_states, scorer_value_goals, scorer_actor_goals) + + # =================================================================== + # 3. Batch samplers (pure jnp; reference GCIQL goal-mix semantics) + # =================================================================== + def _geom(k, shape): + """k ~ Geom(1-gamma), the discounted-occupancy horizon.""" + u = jax.random.uniform(k, shape, minval=1e-6, maxval=1.0 - 1e-6) + return (jnp.floor(jnp.log1p(-u) / logg)).astype(jnp.int32) + 1 + + def _gammas(k, shape): + """Sample explicitly conditioned discounts for one occupancy batch.""" + if not spec_on: + return jnp.full(shape, gamma) + if protected_endpoint_mode: + n = int(np.prod(shape)) + assert n == int(occ_batch) + order = jax.random.permutation(k, n) + return jnp.asarray( + _protected_plan["discounts"])[order].reshape(shape) + if reward_metric_endpoint_mode: + n = int(np.prod(shape)) + assert n == int(occ_batch) + order = jax.random.permutation(k, n) + return jnp.asarray( + _reward_metric_plan["discounts"])[order].reshape(shape) + if gamma_sampler == "stratified_bins": + n = int(np.prod(shape)) + task_count = int(round(effective_gamma_task_fraction * n)) + beta_count = ( + int(round(effective_rec_beta_sample_prob * n)) + if occupancy_rec_on else 0) + base = jnp.arange(n) + aux_idx = jnp.mod( + jnp.maximum(base - task_count - beta_count, 0), + len(_aux_gammas)) + aux_values = jnp.asarray(_aux_gammas, jnp.float32) + unshuffled = jnp.where( + base < task_count, gamma, + jnp.where( + base < task_count + beta_count, + rec_beta, aux_values[aux_idx])) + order = jax.random.permutation(k, n) + return unshuffled[order].reshape(shape) + k1, k2 = jax.random.split(k) + h = jnp.exp(jax.random.uniform(k1, shape, minval=lo_h, maxval=hi_h)) + route = jax.random.uniform(k2, shape) + spectrum_gamma = 1.0 - 1.0 / h + if occupancy_rec_on: + return jnp.where( + route >= 1.0 - effective_gamma_task_fraction, gamma, + jnp.where( + route < effective_rec_beta_sample_prob, + rec_beta, spectrum_gamma)) + return jnp.where( + route >= 1.0 - effective_gamma_task_fraction, + gamma, spectrum_gamma) + + def _gammas_and_actor_mask(k, shape): + """Jointly shuffle protected discount and goal-source cells.""" + if not protected_endpoint_mode: + return _gammas(k, shape), None + n = int(np.prod(shape)) + assert n == int(occ_batch) + order = jax.random.permutation(k, n) + discounts = jnp.asarray( + _protected_plan["discounts"])[order].reshape(shape) + actor_mask = jnp.asarray( + _protected_plan["actor_goal_mask"])[order].reshape(shape) + return discounts, actor_mask + + def _ref_goals_and_values(k, t): + """GCIQL's 20/50/30 goal mix plus normalized index-return targets.""" + e1 = end_d[t] - 1 + k1, k2, k3, k4 = jax.random.split(k, 4) + gi_traj = jnp.minimum(t + _geom(k1, t.shape), e1) + if pixel_actor: + random_rows = jax.random.randint( + k2, t.shape, 0, pixel_valid_indices_d.shape[0]) + gi_rand = pixel_valid_indices_d[random_rows] + else: + gi_rand = jax.random.randint(k2, t.shape, 0, N) + is_traj = jax.random.uniform(k3, t.shape) < 0.5 / 0.8 + is_cur = jax.random.uniform(k4, t.shape) < 0.2 + gi = jnp.where(is_traj, gi_traj, gi_rand) + gi = jnp.where(is_cur, t, gi) + value = jnp.where( + is_cur, 1.0, + jnp.where(is_traj, jnp.power(gamma, jnp.maximum(gi_traj - t, 0)), 0.0)) + value = jnp.where(gi == t, 1.0, value).astype(jnp.float32) + return gi, value + + def _ref_goals(k, t): + return _ref_goals_and_values(k, t)[0] + + def _occupancy_goals(k, t, protected_actor_mask=None): + """Mix value goals with exact-count actor uniform-future goals.""" + if effective_occ_actor_goal_fraction <= 0.0: + return _ref_goals_and_values(k, t) + k_value, k_uniform, k_order = jax.random.split(k, 3) + value_goals, value = _ref_goals_and_values(k_value, t) + actor_goals = actor_uniform_goal_indices( + t, + end_d[t], + jax.random.uniform(k_uniform, t.shape), + array_module=jnp, + ) + actor_mask = ( + protected_actor_mask + if protected_actor_mask is not None + else exact_batch_fraction_mask( + t.shape[0], + effective_occ_actor_goal_fraction, + jax.random.permutation(k_order, t.shape[0]), + array_module=jnp, + )) + return jnp.where(actor_mask, actor_goals, value_goals), value + + def sample_pi_batch(k): + """States plus the exact reference value-goal and actor-goal draws.""" + k0, kv, ka, kd = jax.random.split(k, 4) + if pixel_actor: + valid_rows = jax.random.randint( + k0, (B_pi,), 0, pixel_valid_indices_d.shape[0]) + t = pixel_valid_indices_d[valid_rows] + else: + t = jax.random.randint(k0, (B_pi,), 0, N) + gi_v = _ref_goals(kv, t) + e1 = (end_d[t] - 1).astype(jnp.float32) + lo = jnp.minimum(t + 1, end_d[t] - 1).astype(jnp.float32) + dfrac = jax.random.uniform(ka, (B_pi,)) + gi_a = jnp.round(lo * dfrac + e1 * (1.0 - dfrac)).astype(jnp.int32) + return t, gi_v, gi_a + + def sample_occ_tuple(k, lp=None): + """One occupancy training tuple per row: condition, target z, weight. + + The future index j is drawn from the truncated geometric at gamma~ + with absorbing first-passage handling and reward-targeted + stratification: with prob RT_ETA take the goal index itself (a "hit"), + else a miss step — each branch importance-weighted exactly, so the + fit stays an unbiased MLE of the occupancy. + """ + ks = jax.random.split(k, 7) + t = jax.random.randint(ks[0], (occ_batch,), 0, N) + gam, protected_actor_mask = _gammas_and_actor_mask( + ks[6], t.shape) + gi, goal_value = _occupancy_goals( + ks[1], t, protected_actor_mask) + lgam = jnp.log(gam) + in_traj = (gi >= t) & (gi < end_d[t]) + L = (end_d[t] - t).astype(jnp.float32) + dd = jnp.clip((gi - t).astype(jnp.float32), 0.0, None) + gL = jnp.exp(L * lgam) + p_hit = jnp.where(in_traj, (jnp.exp(dd * lgam) - gL) / (1.0 - gL), 0.0) + take_hit = in_traj & ((jax.random.uniform(ks[2], t.shape) < RT_ETA) | (gi == t)) + future_hit = endpoint_future_hit_mask( + t, gi, end_d[t], take_hit, array_module=jnp) + u = jax.random.uniform(ks[3], t.shape, minval=1e-6, maxval=1.0 - 1e-6) + pd = 1.0 - jnp.exp(jnp.maximum(dd, 1.0) * lgam) + k_miss = jnp.ceil(jnp.log1p(-u * pd) / lgam).astype(jnp.int32) - 1 + k_miss = jnp.clip(k_miss, 0, jnp.maximum(gi - t - 1, 0)) + u2 = jax.random.uniform(ks[4], t.shape, minval=1e-6, maxval=1.0 - 1e-6) + Fmax = jnp.maximum(1.0 - gL, 1e-12) + k_pl = jnp.clip(jnp.ceil(jnp.log1p(-u2 * Fmax) / lgam).astype(jnp.int32) - 1, + 0, (end_d[t] - t) - 1) + j = jnp.where(take_hit, gi, jnp.where(in_traj, t + k_miss, t + k_pl)) + w = jnp.ones((occ_batch,)) + w = jnp.where(take_hit & (gi != t), p_hit / RT_ETA, w) + w = jnp.where(in_traj & ~take_hit, (1.0 - p_hit) / (1.0 - RT_ETA), w) + if joint_latent and lp is not None: + s_lat = latent_apply(lp, base_adapter_d[t]) + g_lat = latent_apply(lp, base_adapter_d[gi]) + z_future = ( + tgt_d[j] if rich_joint_latent + else latent_apply(lp, base_z_d[j])) + parts = [s_lat, act_d[t], g_lat] + ([g_enc(gam)] if spec_on else []) + else: + z_future = tgt_d[j] + if reward_metric_target: + z_future = encode_reader_metric_future( + z_future, + reward_goal_d[gi], + reward_metric_coordinate_j, + array_module=jnp, + ) + parts = [obs_d[t], act_d[t], occ_goal_d[gi]] + ( + [g_enc(gam)] if spec_on else []) + cond_raw = jnp.concatenate(parts, axis=1) + return ( + cond_raw, z_future, w, j, t, gi, goal_value, gam, future_hit) + + def occupancy_base_velocity_error(prediction, target): + """Ordinary per-row flow MSE in active standardized coordinates.""" + residual = prediction - target + if hidden_occupancy_future: + return ( + (jnp.square(residual) * future_active_j).sum(-1) + / future_active_den) + return jnp.mean(jnp.square(residual), axis=-1) + + def occupancy_reader_velocity_error(prediction, target): + """Frozen index-reader geometry for selected flow rows only.""" + assert occ_reader_geometry_enabled + return reader_metric_projected_errors( + prediction - target, + tgt_sd_j, + occ_reader_projection_j, + occ_reader_metric_scale_j, + occ_reader_metric_weights_j, + future_active_j, + array_module=jnp, + ) + + def occupancy_velocity_error(prediction, target): + """Legacy global geometry; defaults exactly to ordinary flow MSE.""" + if not occ_reader_metric_enabled: + return occupancy_base_velocity_error(prediction, target) + return reader_metric_flow_errors( + prediction - target, + tgt_sd_j, + occ_reader_projection_j, + occ_reader_metric_scale_j, + occ_reader_metric_weights_j, + future_active_j, + occ_reader_metric_weight, + array_module=jnp, + ) + + # =================================================================== + # 4. Occupancy training step (diffusion MLE) + # =================================================================== + def actor_query_negative_errors( + p, actor_params, cond_raw, zt, tf, target, rows, goals, k, + pixel_observations=None): + """Flow errors for detached actor-mode/local action relabelings. + + The recorded future, flow bridge, time, and base noise are shared + exactly with the behavior-action row. Only the action columns change. + This is an anti-exploitation likelihood comparison, not a claim that + the recorded future is a counterfactual sample from any negative + action. + """ + action_col = obs_np.shape[1] + goal_col = action_col + a_dim + if pixel_actor: + actor_state = jax.lax.stop_gradient( + pixel_observations[rows]) + actor_goal = jax.lax.stop_gradient( + pixel_observations[goals]) + else: + actor_state = jax.lax.stop_gradient( + cond_raw[:, :action_col]) + actor_goal = jax.lax.stop_gradient( + cond_raw[:, goal_col:goal_col + actor_goal_np.shape[1]]) + mode = actor_def.apply( + {"params": actor_params}, actor_state, actor_goal).mode() + local_noise = jax.random.normal( + k, (occ_action_negative_k, occ_batch, a_dim)) + negative_actions = actor_local_negative_actions( + mode, local_noise, occ_action_negative_sigma) + candidate_count = negative_actions.shape[0] + cond_negative = jnp.broadcast_to( + cond_raw[None, ...], + (candidate_count,) + cond_raw.shape) + cond_negative = cond_negative.at[ + :, :, action_col:action_col + a_dim].set(negative_actions) + cond_negative = ( + (cond_negative - cond_mean[None, None, :]) + / cond_std[None, None, :]) + flat_count = candidate_count * occ_batch + pred_negative = occ_model.apply( + p, + jnp.broadcast_to( + zt[None, ...], + (candidate_count,) + zt.shape).reshape( + flat_count, n_bits), + jnp.broadcast_to( + tf[None, :], (candidate_count, occ_batch)).reshape( + flat_count), + cond_negative.reshape(flat_count, cond_dim), + ).reshape(candidate_count, occ_batch, n_bits) + target_negative = target[None, ...] + return occupancy_velocity_error( + pred_negative, target_negative) + + def occ_step( + params, opt_state, ema, actor_params, k, + pixel_observations=None): + k1, k2, k3, k4 = jax.random.split(k, 4) + ( + cond_raw, z_data, w, _j, _t, _gi, _gv, _gam, _future_hit, + ) = sample_occ_tuple(k1) + t_int = jax.random.randint(k2, (occ_batch,), 1, OCC_T + 1) + + if is_bits: + # masked discrete diffusion: BCE on the masked bits + keep = abar_j[t_int - 1] + m = (jax.random.uniform(k3, (occ_batch, n_bits)) >= keep[:, None] + ).astype(jnp.float32) + + def loss_fn(p): + c = (cond_raw - cond_mean) / cond_std + tf = t_int.astype(jnp.float32) / OCC_T + xt = (2.0 * z_data - 1.0) * (1.0 - m) + pred = occ_model.apply(p, jnp.concatenate([xt, m], -1), tf, c) + bce = optax.sigmoid_binary_cross_entropy(pred, z_data) + return (w[:, None] * bce * m).sum() / jnp.maximum(m.sum(), 1.0) + else: + # Gaussian diffusion or conditional flow matching on standardized z. + eps_n = jax.random.normal(k3, (occ_batch, n_bits)) + if hidden_occupancy_future: + eps_n = eps_n * future_active_j[None, :] + + def loss_fn(p): + c = (cond_raw - cond_mean) / cond_std + z0 = (z_data - tgt_mu_j) / tgt_sd_j + if occupancy_model == "flow": + tf = jax.random.uniform(k2, (occ_batch,)) + zt = ((1.0 - tf[:, None]) * eps_n + + tf[:, None] * z0) + target = z0 - eps_n + else: + tf = t_int.astype(jnp.float32) / OCC_T + ab = abar_j[t_int - 1][:, None] + zt = (jnp.sqrt(ab) * z0 + + jnp.sqrt(1.0 - ab) * eps_n) + target = eps_n + pred = occ_model.apply(p, zt, tf, c) + if occupancy_model == "flow": + err = occupancy_velocity_error(pred, target) + elif hidden_occupancy_future: + err = ( + ((pred - target) ** 2 + * future_active_j[None, :]).sum(-1) + / future_active_den) + else: + err = jnp.mean((pred - target) ** 2, -1) + base = jnp.mean(w * err) + if occ_reader_hit_enabled: + reader_err = occupancy_reader_velocity_error( + pred, target) + base, _base_mle, _hit_reader = ( + occupancy_base_and_endpoint_hit_loss( + err, w, reader_err, _future_hit, _gam, + gamma, rec_beta, occ_reader_hit_weight, + array_module=jnp)) + if occ_action_contrast_weight <= 0: + return base + if actor_query_occ_contrast: + err_negative = actor_query_negative_errors( + p, actor_params, cond_raw, zt, tf, target, + _t, _gi, k4, pixel_observations) + rank = actor_query_contrast_loss( + err, err_negative, w, + occ_action_contrast_margin) + return base + occ_action_contrast_weight * rank + action_col = obs_np.shape[1] + if occ_action_negative == "shuffle": + neg_action = jnp.roll( + cond_raw[:, action_col:action_col + a_dim], 1, axis=0) + else: + neg_action = jnp.clip( + cond_raw[:, action_col:action_col + a_dim] + + occ_action_negative_sigma * jax.random.normal( + k4, (occ_batch, a_dim)), -1.0, 1.0) + cond_neg = cond_raw.at[ + :, action_col:action_col + a_dim].set(neg_action) + cond_neg = (cond_neg - cond_mean) / cond_std + pred_neg = occ_model.apply(p, zt, tf, cond_neg) + if occupancy_model == "flow": + err_neg = occupancy_velocity_error( + pred_neg, target) + elif hidden_occupancy_future: + err_neg = ( + ((pred_neg - target) ** 2 + * future_active_j[None, :]).sum(-1) + / future_active_den) + else: + err_neg = jnp.mean((pred_neg - target) ** 2, -1) + rank = jax.nn.softplus( + occ_action_contrast_margin + err - err_neg).mean() + return base + occ_action_contrast_weight * rank + + loss, grads = jax.value_and_grad(loss_fn)(params) + updates, opt_state = occ_tx.update(grads, opt_state, params) + params = optax.apply_updates(params, updates) + ema = jax.tree_util.tree_map(lambda e, p: e * (1 - OCC_TAU) + p * OCC_TAU, + ema, params) + return params, opt_state, ema, loss + + def occ_step_joint(params, opt_state, ema, lp, lp_opt, lp_ema, + actor_params, k, pixel_observations=None): + """Joint occupancy/projection update without a stale latent cache.""" + k1, k2, k3, k4 = jax.random.split(k, 4) + t_int = jax.random.randint(k2, (occ_batch,), 1, OCC_T + 1) + eps_n = jax.random.normal(k3, (occ_batch, n_bits)) + if hidden_occupancy_future: + eps_n = eps_n * future_active_j[None, :] + + def loss_fn(op, ap): + ( + cond_raw, z_data, w, _j, rows, goals, _goal_value, + discounts, future_hit, + ) = sample_occ_tuple(k1, ap) + c = (cond_raw - cond_mean) / cond_std + # Stop-gradient on the future side prevents the easy all-z collapse; + # the representation learns through current/goal conditioning. + z0 = (jax.lax.stop_gradient(z_data) - tgt_mu_j) / tgt_sd_j + if occupancy_model == "flow": + tf = jax.random.uniform(k2, (occ_batch,)) + zt = ((1.0 - tf[:, None]) * eps_n + tf[:, None] * z0) + target = z0 - eps_n + else: + tf = t_int.astype(jnp.float32) / OCC_T + ab = abar_j[t_int - 1][:, None] + zt = jnp.sqrt(ab) * z0 + jnp.sqrt(1.0 - ab) * eps_n + target = eps_n + pred = occ_model.apply(op, zt, tf, c) + if occupancy_model == "flow": + err = occupancy_velocity_error(pred, target) + elif hidden_occupancy_future: + err = ( + ((pred - target) ** 2 + * future_active_j[None, :]).sum(-1) + / future_active_den) + else: + err = jnp.mean((pred - target) ** 2, -1) + occ_loss = jnp.mean(w * err) + if occ_reader_hit_enabled: + reader_err = occupancy_reader_velocity_error( + pred, target) + occ_loss, _base_mle, _hit_reader = ( + occupancy_base_and_endpoint_hit_loss( + err, w, reader_err, future_hit, discounts, + gamma, rec_beta, occ_reader_hit_weight, + array_module=jnp)) + if occ_action_contrast_weight > 0: + if actor_query_occ_contrast: + err_negative = actor_query_negative_errors( + op, actor_params, cond_raw, zt, tf, target, + rows, goals, k4, pixel_observations) + rank = actor_query_contrast_loss( + err, err_negative, w, + occ_action_contrast_margin) + else: + action_col = obs_np.shape[1] + if occ_action_negative == "shuffle": + neg_action = jnp.roll( + cond_raw[:, action_col:action_col + a_dim], + 1, axis=0) + else: + neg_action = jnp.clip( + cond_raw[:, action_col:action_col + a_dim] + + occ_action_negative_sigma * jax.random.normal( + k4, (occ_batch, a_dim)), -1.0, 1.0) + cond_neg = cond_raw.at[ + :, action_col:action_col + a_dim].set(neg_action) + cond_neg = (cond_neg - cond_mean) / cond_std + pred_neg = occ_model.apply(op, zt, tf, cond_neg) + if occupancy_model == "flow": + err_neg = occupancy_velocity_error( + pred_neg, target) + elif hidden_occupancy_future: + err_neg = ( + ((pred_neg - target) ** 2 + * future_active_j[None, :]).sum(-1) + / future_active_den) + else: + err_neg = jnp.mean((pred_neg - target) ** 2, -1) + rank = jax.nn.softplus( + occ_action_contrast_margin + + err - err_neg).mean() + occ_loss = occ_loss + occ_action_contrast_weight * rank + + hs = latent_apply(ap, base_adapter_d[rows]) + hg = latent_apply(ap, base_adapter_d[goals]) + zs = joint_reader_z(hs) + zg = joint_reader_z(hg) + logit = joint_rdec_logit(zs, zg) + positive, negative = joint_index_pair_masks( + rows, goals, start_d[rows], end_d[rows], + _joint_index_delta, _joint_neg_gap, + _joint_reader_model, jnp) + valid_index_pair = positive | negative + index_label = positive.astype(jnp.float32) + per_pair = -( + index_label * jax.nn.log_sigmoid(logit) + + (1.0 - index_label) * jax.nn.log_sigmoid(-logit)) + goal_loss = ( + (valid_index_pair.astype(jnp.float32) * per_pair).sum() + / jnp.maximum( + valid_index_pair.astype(jnp.float32).sum(), 1.0)) + anchor = 0.5 * ( + jnp.mean( + ((hs - base_adapter_d[rows]) / adapter_sd_j) ** 2) + + jnp.mean( + ((hg - base_adapter_d[goals]) / adapter_sd_j) ** 2)) + total = (occ_loss + latent_goal_weight * goal_loss + + latent_anchor_weight * anchor) + return total + + loss, (op_grads, lp_grads) = jax.value_and_grad( + loss_fn, argnums=(0, 1))(params, lp) + updates, opt_state = occ_tx.update(op_grads, opt_state, params) + params = optax.apply_updates(params, updates) + lp_updates, lp_opt = latent_tx.update(lp_grads, lp_opt, lp) + lp = optax.apply_updates(lp, lp_updates) + ema = jax.tree_util.tree_map( + lambda e, p: e * (1 - OCC_TAU) + p * OCC_TAU, ema, params) + lp_ema = jax.tree_util.tree_map( + lambda e, p: e * (1 - OCC_TAU) + p * OCC_TAU, lp_ema, lp) + return params, opt_state, ema, lp, lp_opt, lp_ema, loss + + # =================================================================== + # 5. Q read-outs: occupancy -> value at the goal + # =================================================================== + def gl(ema, s, a, g, k, dv=None, n_ord=None, cond_goal=None): + """Exact goal likelihood (discrete goals): teacher-forced any-order + autoregressive unmasking of the goal's bits. Exact per order, averaged + over n_ord random orders; zero hit-variance; differentiable in `a`.""" + if spec_on and dv is None: + raise ValueError( + "discount-conditioned occupancy read-out requires an explicit " + "per-row discount") + n_o = N_ORDERS if n_ord is None else n_ord + cg = g if cond_goal is None else cond_goal + parts = [s, a, cg] + ([g_enc(dv)] if spec_on else []) + c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std + B = c.shape[0] + cc = jnp.repeat(c, n_o, axis=0) + BO = B * n_o + g01 = jnp.round(jnp.clip(jnp.repeat(g, n_o, axis=0), 0.0, 1.0)) + k, sub = jax.random.split(k) + orders = jnp.argsort(jax.random.uniform(sub, (BO, n_bits)), axis=-1) + rows = jnp.arange(BO) + + def step(carry, i): + x, m, logp = carry + out = occ_model.apply(ema, jnp.concatenate([x, m], -1), + jnp.full((BO,), ts_frac[i]), cc) + idx = orders[:, i] + logit = out[rows, idx] + gbit = g01[rows, idx] + logp = logp + gbit * jax.nn.log_sigmoid(logit) + \ + (1 - gbit) * jax.nn.log_sigmoid(-logit) + x = x.at[rows, idx].set(2.0 * gbit - 1.0) + m = m.at[rows, idx].set(0.0) + return (x, m, logp), None + + init = (jnp.zeros((BO, n_bits)), jnp.ones((BO, n_bits)), jnp.zeros((BO,))) + (_, _, logp), _ = jax.lax.scan(step, init, jnp.arange(n_bits)) + return jnp.exp(logp).reshape(B, n_o).mean(-1) + + def q_elbo(ema, s, a, g, k, dv=None, n_ord=None, log_out=False, + cond_goal=None): + """ELBO read-out (continuous goals): the denoising loss evaluated AT + the goal's z is a monotone surrogate of -log p(g | s,a); Q = + exp(-loss). Point evaluation like `gl` (nothing sampled), works in + any goal space, one network apply per draw; K stratified timesteps + for variance. Recursion ratios cancel the unknown normalizer. + + log_out=True returns -loss (log Q) directly — the --elbo_logspace + actor path uses it so no exp / floor-clip sits on the gradient. + --elbo_antithetic pairs the noise draws (+eps, -eps) sharing one + stratified t per pair (K draws = K/2 pairs, same total applies).""" + if spec_on and dv is None: + raise ValueError( + "discount-conditioned occupancy read-out requires an explicit " + "per-row discount") + K = elbo_K if n_ord is None else n_ord + cg = g if cond_goal is None else cond_goal + parts = [s, a, cg] + ([g_enc(dv)] if spec_on else []) + c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std + B = c.shape[0] + k1, k2 = jax.random.split(k) + if elbo_antithetic: + Kp = max(K // 2, 1) # antithetic: K = Kp pairs x 2 + u = jax.random.uniform(k1, (B, Kp)) + strat = (jnp.arange(Kp)[None, :] + u) / Kp + t_half = jnp.clip((strat * OCC_T).astype(jnp.int32) + 1, 1, OCC_T) + t_int = jnp.concatenate([t_half, t_half], -1).reshape(-1) # pair shares t + e_half = jax.random.normal(k2, (B, Kp, n_bits)) + eps = jnp.concatenate([e_half, -e_half], 1).reshape(B * 2 * Kp, n_bits) + K = 2 * Kp + else: + u = jax.random.uniform(k1, (B, K)) # stratified t: draw i covers + strat = (jnp.arange(K)[None, :] + u) / K # quantile band i/K..(i+1)/K + t_int = jnp.clip((strat.reshape(-1) * OCC_T).astype(jnp.int32) + 1, 1, OCC_T) + eps = jax.random.normal(k2, (B * K, n_bits)) + cc = jnp.repeat(c, K, axis=0) + zg = 2.0 * g - 1.0 if is_bits else (g - tgt_mu_j) / tgt_sd_j + zg = jnp.repeat(zg, K, axis=0) + ab = abar_j[t_int - 1][:, None] + zt = jnp.sqrt(ab) * zg + jnp.sqrt(1.0 - ab) * eps + pred = occ_model.apply(ema, zt, t_int.astype(jnp.float32) / OCC_T, cc) + loss = ((pred - eps) ** 2).mean(-1).reshape(B, K).mean(-1) + return -loss if log_out else jnp.exp(-loss) + + if not is_bits: + gl = q_elbo # every downstream call site is read-out-agnostic + + # =================================================================== + # 6. Occupancy SAMPLING (midpoints for the recursion chain) + # =================================================================== + def occ_bits(ema, s, a, g, k, dv, m_wide): + """Discrete goals: ancestral any-order sampling of the bits — the + sampling twin of `gl` (Bernoulli per bit instead of teacher-forced).""" + parts = [s, a, g] + ([g_enc(dv)] if spec_on else []) + c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std + B2 = c.shape[0] + cc = jnp.repeat(c, m_wide, axis=0) + BM = B2 * m_wide + k, sub = jax.random.split(k) + orders = jnp.argsort(jax.random.uniform(sub, (BM, n_bits)), axis=-1) + rows = jnp.arange(BM) + + def stepf(carry, i): + x, m, kk = carry + out = occ_model.apply(ema, jnp.concatenate([x, m], -1), + jnp.full((BM,), ts_frac[i]), cc) + idx = orders[:, i] + kk, sub2 = jax.random.split(kk) + b = jax.random.bernoulli(sub2, jax.nn.sigmoid(out[rows, idx])).astype( + jnp.float32) + x = x.at[rows, idx].set(2.0 * b - 1.0) + m = m.at[rows, idx].set(0.0) + return (x, m, kk), None + + init = (jnp.zeros((BM, n_bits)), jnp.ones((BM, n_bits)), k) + (x, _, _), _ = jax.lax.scan(stepf, init, jnp.arange(n_bits)) + return ((x + 1.0) / 2.0).reshape(B2, m_wide, n_bits) + + # 25-step deterministic DDIM schedule (continuous sampling + completion) + _ts_z = np.unique(np.linspace(OCC_T, 1, 25).round().astype(np.int32))[::-1].copy() + ts_z_now = jnp.asarray(_ts_z) + ts_z_nxt = jnp.asarray(np.concatenate([_ts_z[1:], [0]]).astype(np.int32)) + + def z_sample(ema, cond_norm, k): + """Continuous goals: DDIM or flow-ODE sample in normalized z space.""" + B2 = cond_norm.shape[0] + z = jax.random.normal(k, (B2, n_bits)) + if hidden_occupancy_future: + z = z * future_active_j[None, :] + + if occupancy_model == "flow": + dt = 1.0 / flow_steps + + def flow_step(z_now, i2): + tf = jnp.full( + (B2,), i2.astype(jnp.float32) / flow_steps) + velocity = occ_model.apply(ema, z_now, tf, cond_norm) + z_next = z_now + dt * velocity + if hidden_occupancy_future: + z_next = z_next * future_active_j[None, :] + return z_next, None + + z, _ = jax.lax.scan( + flow_step, z, jnp.arange(flow_steps)) + return z + + def stepf(z, i2): + tn, tx = ts_z_now[i2], ts_z_nxt[i2] + ab_n = abar_j[tn - 1] + ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0) + eps = jnp.clip(occ_model.apply( + ema, z, jnp.full((B2,), tn.astype(jnp.float32) / OCC_T), + cond_norm), -6.0, 6.0) + if hidden_occupancy_future: + eps = eps * future_active_j[None, :] + z0h = (z - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8)) + z_next = ( + jnp.sqrt(ab_x) * z0h + + jnp.sqrt(1.0 - ab_x) * eps) + if hidden_occupancy_future: + z_next = z_next * future_active_j[None, :] + return z_next, None + + z, _ = jax.lax.scan(stepf, z, jnp.arange(len(_ts_z))) + return z + + def z_bits(ema, s, a, g, k, dv, m_wide, decode_goal=None): + """Continuous occupancy draws decoded into the compact future space.""" + parts = [s, a, g] + ([g_enc(dv)] if spec_on else []) + c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std + B2 = c.shape[0] + cc = jnp.repeat(c, m_wide, axis=0) + z = z_sample(ema, cc, k) + z = jnp.clip((z + 1.0) / 2.0, 0.0, 1.0) if is_bits else z * tgt_sd_j + tgt_mu_j + if reward_metric_target: + if decode_goal is None: + raise ValueError( + "reader-metric occupancy sampling requires the compact " + "z_goal used by the invertible decoder") + repeated_decode_goal = jnp.repeat( + decode_goal, m_wide, axis=0) + z = decode_reader_metric_future( + z, + repeated_decode_goal, + reward_metric_coordinate_inverse_j, + array_module=jnp, + ) + if hidden_occupancy_future: + # state_h is the frozen encoder's ReLU feature. Projecting tiny + # generative negatives back onto this known support prevents + # recursive conditioning on impossible encoder states. + z = jnp.maximum(z, 0.0) + return z.reshape(B2, m_wide, n_bits) + + if not is_bits: + occ_bits = z_bits + + # ---- optional CLASSIFIER read-out (issue: fair image RSM) -------------- + # Q(s,a,g) = E_{z'~occ(s,a,g)}[ sigmoid(R_psi(z', z_g)) ] -- sample futures from the + # occupancy and score each with a learned goal classifier R_psi, INSTEAD of the + # mass-at-goal density (q_elbo). The density averages denoise error over all latent + # dims so the high-variance arm dims swamp the cube -> flat q_self~q_rand; a classifier + # keys only on the reward-relevant (cube) match. R_psi from genq/train_reward_decoder.py. + reward_decoder_model = None + reward_decoder_target = None + reward_decoder_features = None + reward_decoder_index_delta = None + reward_decoder_logit = False + _future_to_reward_w = _future_to_reward_b = None + fc1_cached_z_max_abs = None + fc1_cached_z_mean_abs = None + if hidden_occupancy_future: + # state_h is exactly the frozen encoder's fc_0 ReLU output. Its saved + # fc_1 is therefore an exact, frozen h->z read-out, not a learned + # completion/dynamics model. Reward sees only this compact z. + _pe_occ = np.load(pixel_encoder) + _fc1_w_np = np.asarray( + _pe_occ["fc_1.weight"], np.float32).T + _fc1_b_np = np.asarray( + _pe_occ["fc_1.bias"], np.float32) + _future_to_reward_w = jnp.asarray(_fc1_w_np) + _future_to_reward_b = jnp.asarray(_fc1_b_np) + assert _future_to_reward_w.shape == ( + n_bits, reward_goal_dim), ( + "pixel encoder fc_1 must map hidden occupancy futures to the " + "compact reward-reader latent") + # Preserve the cached compact-z contract used to train the reader. + # Cached z was produced on H100 with JAX's default matmul precision; + # reconstructing on CPU differs at TF32-scale (~1e-4), an inferred + # provenance effect. The same orientation is used by rich_adapter. + _fc1_probe_n = min(4096, N) + _fc1_probe = ( + state_h_np[:_fc1_probe_n] @ _fc1_w_np + _fc1_b_np) + _fc1_diff = np.abs( + z_np[:_fc1_probe_n] - _fc1_probe) + fc1_cached_z_max_abs = float(_fc1_diff.max()) + fc1_cached_z_mean_abs = float(_fc1_diff.mean()) + assert fc1_cached_z_max_abs < 2e-4, ( + "frozen fc_1 does not reproduce the cached compact reader latent: " + f"max_abs={fc1_cached_z_max_abs:.6g}") + print( + f"[rsm] hidden->reader fc1 audit: " + f"max_abs={fc1_cached_z_max_abs:.6g} " + f"mean_abs={fc1_cached_z_mean_abs:.6g} " + f"over {_fc1_probe_n} cached rows", flush=True) + + def _future_reward_feature(zf): + if _future_to_reward_w is None: + return zf + return zf @ _future_to_reward_w + _future_to_reward_b + + if not is_bits and reward_decoder is not None: + _rdec_logit, _rdec_meta = load_jax_reward_reader(reward_decoder) + assert int(_rdec_meta["zdim"]) == reward_goal_dim, ( + f"reward decoder zdim={int(_rdec_meta['zdim'])} does not match compact " + f"reward-goal dim={reward_goal_dim}") + reward_decoder_model = _rdec_meta["reader_model"] + reward_decoder_target = _rdec_meta["target"] + reward_decoder_index_delta = ( + int(_rdec_meta["index_delta"]) + if _rdec_meta["index_delta"] is not None + else 0 if reward_decoder_target == "index" else None) + reward_decoder_features = _rdec_meta["features"] + reward_decoder_activation = _rdec_meta["activation"] + if distill_empirical_index_weight > 0.0: + _empirical_reader_expected = { + "pixels_only_latents": True, + "frozen_encoder": True, + "uses_coordinates_for_training": False, + "uses_reward_arrays": False, + "uses_td_or_bootstrap": False, + } + _empirical_reader_bad = { + key: (_rdec_meta.get(key), expected) + for key, expected in _empirical_reader_expected.items() + if _rdec_meta.get(key) != expected + } + assert not _empirical_reader_bad, ( + "empirical index-successor reader violates the pixels-only " + f"non-TD contract: {_empirical_reader_bad}") + RDEC_M = int(rdec_samples) + print(f"[rsm] REWARD read-out: R_psi from {reward_decoder} " + f"(model={reward_decoder_model}, target={reward_decoder_target}, " + f"features={reward_decoder_features}, " + f"activation={reward_decoder_activation}, " + f"zdim={int(_rdec_meta['zdim'])}, " + f"future_dim={n_bits}, " + f"M={RDEC_M} occupancy samples)", flush=True) + + reward_decoder_logit = bool( + int(os.environ.get("RDEC_LOGIT", "0"))) + if actor_loss in ("awr_distill", "ddpgbc_distill"): + assert not reward_decoder_logit, ( + "distilled policies require the calibrated sigmoid expectation " + "of the index reader; RDEC_LOGIT=1 changes the target") + + def q_reward_dec(ema, s, a, g, k, dv=None, n_ord=None, + log_out=False, cond_goal=None): + # The occupancy may condition on rich h_g and sample rich h + # futures, but the frozen fc_1 projection always maps the sampled + # future to compact z before the reward reader. Never substitute + # h_g for the compact reward goal `g`. + cg = g if cond_goal is None else cond_goal + zt = z_bits( + ema, s, a, cg, k, dv, RDEC_M, + decode_goal=(g if reward_metric_target else None), + ) # (B, M, n_bits) compact z' + B = zt.shape[0] + zt = _future_reward_feature( + zt.reshape(B * RDEC_M, -1)).reshape( + B, RDEC_M, reward_goal_dim) + gg = jnp.repeat(g, RDEC_M, axis=0) # goal (raw z), per sample + logit = _rdec_logit(zt.reshape(B * RDEC_M, -1), gg).reshape(B, RDEC_M) + if reward_decoder_logit: + # raw-logit read-out: preserve R_psi's ranking range (avoids the sigmoid + # squashing to ~0.5 when the classifier's logits are small). Q = exp(mean + # logit); log_out returns the mean logit directly. + lm = logit.mean(-1) + return lm if log_out else jnp.exp(lm - jax.lax.stop_gradient(lm.max())) + q = jnp.clip(jax.nn.sigmoid(logit).mean(-1), 1e-6, 1.0) # reward-under-occupancy + return jnp.log(q) if log_out else q + + gl = q_reward_dec + + if actor_loss in ("awr_distill", "ddpgbc_distill"): + assert reward_decoder_target == "index", ( + "distilled extraction may only integrate an index reward reader; " + "a discounted-return reader would count the horizon twice") + assert reward_decoder_index_delta is not None + _distill_target_source = ( + "ema_occupancy_instant_index_reward_expectation" + if reward_decoder_index_delta == 0 + else "ema_occupancy_within_" + f"{reward_decoder_index_delta}_step_index_reward_expectation") + if occupancy_rec_on: + _distill_target_source = _distill_target_source.replace( + "ema_occupancy_", "ema_composed_occupancy_", 1) + else: + _distill_target_source = None + if occupancy_rec_on: + assert reward_decoder_target == "index", ( + "occupancy recursion may only terminate in an index reward " + "reader; a discounted-return reader would count the composed " + "horizon twice") + assert not reward_decoder_logit, ( + "occupancy recursion requires a calibrated local index-reward " + "expectation; RDEC_LOGIT=1 is not a probability read-out") + _distill_actor_action_target_source = ( + _distill_target_source if distill_actor_actions else None) + _distill_actor_action_policy = ( + "stop_gradient_current_actor_mode_plus_local_gaussian" + if distill_actor_actions else None) + _distill_actor_action_support_start = ( + 0 if distill_actor_actions else None) + _distill_empirical_index_target_source = ( + "observed_same_trajectory_absorbing_first_passage_geometric_" + "successor_compact_z_through_frozen_index_reader" + if distill_empirical_index_weight > 0.0 else None) + _distill_critic_target_source = ( + ( + "recorded_actions_only_observed_same_trajectory_absorbing_first_" + "passage_geometric_successor_compact_z_through_frozen_index_reader" + + ( + ";detached_actor_and_local_actions_only_discount_" + "conditioned_ema_occupancy_index_reader_expectation" + if distill_actor_actions else "")) + if pixel_scorer + else + "convex_blend_of_empirical_recorded_successor_index_expectation_and_" + + _distill_target_source + if distill_empirical_index_weight > 0.0 + else _distill_target_source) + if ( + distill_empirical_index_weight > 0.0 + and distill_actor_actions): + _distill_actor_action_target_source = ( + "behavior_reference_empirical_absorbing_index_return_only;" + "actor_mode_and_local_candidates_discount_conditioned_" + "occupancy_only" + if pixel_scorer + else + "behavior_reference_convex_blend_of_empirical_and_occupancy;" + "actor_mode_and_local_candidates_occupancy_only") + empirical_index_target = None + if distill_empirical_index_weight > 0.0: + assert reward_decoder_target == "index" + assert not reward_decoder_logit + + def empirical_index_target( + rows, goal_rows, goals, k, discounts): + """Direct non-TD reader expectation on recorded successors. + + This is the empirical counterpart of the fitted occupancy read: + it samples the same finite-trajectory geometric horizon with the + same absorbing first-passage goal convention, gathers the frozen + compact pixel latent actually observed after the dataset action, + and applies the same frozen index reader. It contains no reward + array, next-state value, or bootstrap. + """ + uniforms = jax.random.uniform( + k, (rows.shape[0], RDEC_M), + minval=1e-6, maxval=1.0 - 1e-6) + future_indices = truncated_geometric_future_indices( + rows, + end_d[rows], + discounts, + uniforms, + absorbing_goals=goal_rows, + array_module=jnp, + ) + future = reward_goal_d[future_indices] + repeated_goals = jnp.repeat( + goals, RDEC_M, axis=0) + logits = _rdec_logit( + future.reshape(-1, reward_goal_dim), + repeated_goals, + ).reshape(rows.shape[0], RDEC_M) + return jax.nn.sigmoid(logits).mean(axis=-1) + + distill_empirical_meta = { + "distill_empirical_index_weight": float( + distill_empirical_index_weight), + "distill_empirical_index_enabled": bool( + distill_empirical_index_weight > 0.0), + "distill_empirical_index_target_source": + _distill_empirical_index_target_source, + "distill_empirical_index_samples": ( + int(rdec_samples) + if distill_empirical_index_weight > 0.0 else 0), + "distill_empirical_index_horizon": + ( + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount" + if distill_empirical_index_weight > 0.0 else None), + "distill_empirical_index_blend_formula": + ( + "recorded_successor_reader_expectation_only" + if pixel_scorer + else "(1-weight)*ema_occupancy_reader_expectation" + "+weight*recorded_successor_reader_expectation" + if distill_empirical_index_weight > 0.0 else None), + "distill_empirical_index_behavior_action_only": bool( + distill_empirical_index_weight > 0.0), + "distill_empirical_index_counterfactual_action_source": + ( + "discount_conditioned_ema_occupancy" + if distill_actor_actions + else "none_awr_dataset_actions_only" + if pixel_scorer and actor_loss == "awr_distill" + else "none_behavior_only_scorer_supervision" + if pixel_scorer + else "discount_conditioned_ema_occupancy" + if distill_empirical_index_weight > 0.0 else None), + "distill_empirical_index_uses_reward_arrays": False, + "distill_empirical_index_uses_coordinates": False, + "distill_empirical_index_uses_td_or_bootstrap": False, + "distill_empirical_index_recorded_action_uses_occupancy": ( + False if pixel_scorer else None), + "distill_empirical_index_counterfactual_uses_empirical": ( + False + if pixel_scorer and distill_actor_actions else None), + } + + # =================================================================== + # 7. Beta-recursion carriers + # =================================================================== + # Legacy state recursion expands generated target coordinates with a + # completion diffusion. Fair visual ``recursion=occupancy`` never creates + # that module: its occupancy predicts the same frozen h256 (primary) or z + # (control) space used by actor/current-state conditioning, so a sample is + # already a valid recursive state. + obs_dim = obs_np.shape[1] + obs_mu_j = jnp.asarray(obs_np.mean(0)) + obs_sd_j = jnp.asarray(obs_np.std(0) + 1e-6) + _m_mu = jnp.full((n_bits,), 0.5) if is_bits else tgt_mu_j + _m_sd = jnp.full((n_bits,), 0.5) if is_bits else tgt_sd_j + c2_mean = jnp.concatenate([cond_mean, _m_mu]) + c2_std = jnp.concatenate([cond_std, _m_sd]) + key, ik3 = jax.random.split(key) + if not completion_rec_on: + cmpl_model = cmpl_tx = None + cmpl_params = cmpl_opt = cmpl_ema = None + else: + cmpl_model = make_model( + cond_dim + n_bits, obs_dim, OCC_HIDDEN, OCC_LAYERS, + OCC_TIME_DIM) + cmpl_params = cmpl_model.init( + ik3, jnp.zeros((1, obs_dim)), jnp.zeros((1,)), + jnp.zeros((1, cond_dim + n_bits))) + cmpl_tx = optax.chain( + optax.clip_by_global_norm(10.0), optax.adamw(OCC_LR)) + cmpl_opt = cmpl_tx.init(cmpl_params) + cmpl_ema = jax.tree_util.tree_map(lambda x: x, cmpl_params) + if pixel_actor: + assert cmpl_params is cmpl_opt is cmpl_ema is None, ( + "a pixel-policy RSM must not instantiate or checkpoint the legacy " + "completion/world-model carrier") + + def cmpl_step(cp, co, ce, k, cond_raw, j, w): + """One diffusion MLE step of the completion head.""" + k1, k2 = jax.random.split(k) + t_int = jax.random.randint(k1, (occ_batch,), 1, OCC_T + 1) + eps = jax.random.normal(k2, (occ_batch, obs_dim)) + c2 = (jnp.concatenate([cond_raw, tgt_d[j]], -1) - c2_mean) / c2_std + x0 = (obs_d[j] - obs_mu_j) / obs_sd_j + ab = abar_j[t_int - 1][:, None] + xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1.0 - ab) * eps + + def lf(pp): + pred = cmpl_model.apply(pp, xt, t_int.astype(jnp.float32) / OCC_T, c2) + return (w[:, None] * (pred - eps) ** 2).mean() + + cl, gr = jax.value_and_grad(lf)(cp) + upd, co = cmpl_tx.update(gr, co, cp) + cp = optax.apply_updates(cp, upd) + ce = jax.tree_util.tree_map(lambda e, q: e * (1 - OCC_TAU) + q * OCC_TAU, ce, cp) + return cp, co, ce, cl + + def cmpl_sample(ce, cond2_raw, k): + """25-step DDIM sample of a full observation from the completion head.""" + c2 = (cond2_raw - c2_mean) / c2_std + B2 = c2.shape[0] + x = jax.random.normal(k, (B2, obs_dim)) + + def stepf(x, i2): + tn, tx = ts_z_now[i2], ts_z_nxt[i2] + ab_n = abar_j[tn - 1] + ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0) + eps = jnp.clip(cmpl_model.apply( + ce, x, jnp.full((B2,), tn.astype(jnp.float32) / OCC_T), c2), -6.0, 6.0) + x0h = (x - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8)) + return jnp.sqrt(ab_x) * x0h + jnp.sqrt(1.0 - ab_x) * eps, None + + x, _ = jax.lax.scan(stepf, x, jnp.arange(len(_ts_z))) + return x * obs_sd_j + obs_mu_j + + def mk_cond2(s, a, gb, mids): + parts = [s, a, gb] + \ + ([g_enc(jnp.full((s.shape[0],), hop_disc))] if spec_on else []) + [mids] + return jnp.concatenate(parts, -1) + + def chain_prob(ema, ce, actor_params, s0, a0, gb, gobs, k): + """The splitting-identity estimator (root README 2.4): + + Q_gamma = (1-p) * gl_beta + p * E[ Q_gamma(next hop) ] + + run as a coin-terminated walk: each level, alive rows flip the coin + (p = continuation), sample ONE beta-horizon midpoint, complete it to + a full state, and let the live actor re-decide there; dead rows + freeze. Fixed depth keeps jit shapes static; ONE gl read at every + row's final node is the estimate. Expectation form — no max.""" + B2 = s0.shape[0] + dvh = jnp.full((B2,), hop_disc) + + def level(carry, _): + s_cur, a_cur, alive, kk = carry + kk, kc, ks_, kx = jax.random.split(kk, 4) + cont = alive & (jax.random.uniform(kc, (B2,)) < rec_p) + mids = occ_bits(ema, s_cur, a_cur, gb, ks_, dvh, 1)[:, 0, :] + x_new = cmpl_sample(ce, mk_cond2(s_cur, a_cur, gb, mids), kx) + a_new = jnp.clip(actor_def.apply({"params": actor_params}, + x_new, gobs).mode(), -1, 1) + s_cur = jnp.where(cont[:, None], x_new, s_cur) + a_cur = jnp.where(cont[:, None], a_new, a_cur) + return (s_cur, a_cur, cont, kk), None + + (s_f, a_f, _, k), _ = jax.lax.scan( + level, (s0, a0, jnp.ones((B2,), bool), k), None, length=rec_max_depth) + k, kg = jax.random.split(k) + return gl(ema, s_f, a_f, gb, kg, dvh) + + def occupancy_chain_prob(ema, recursive_actor_params, s0, a0, + reward_goal, occupancy_goal, actor_goal, k): + """Compose beta occupancies entirely in their generated latent space. + + Each continued macro-step samples h' (or compact-z in the control) + from d_beta(h' | h, a, h_g), then the actor re-decides directly from + h'. The terminal beta occupancy is mapped through the frozen encoder + fc_1 and local index-reward reader. There is no state completion, + one-step dynamics model, reward label in the occupancy fit, or + Bellman/bootstrap target. + + The geometric identity is exact for the actor's own action at s0: + a0=mu(s0,g), so a zero-length beta jump re-decides to the same action. + A scorer target queried at an off-policy dataset action has one extra + approximation: after a zero-length first jump it re-decides with the + recursive actor. The other environmental approximation is whether the + frozen visual latent is Markov-sufficient for composing occupancies. + """ + B2 = s0.shape[0] + dvh = jnp.full((B2,), rec_beta) + + def level(carry, _): + s_cur, a_cur, alive, kk = carry + kk, kc, ks_ = jax.random.split(kk, 3) + cont = alive & (jax.random.uniform(kc, (B2,)) < rec_p) + mids = occ_bits( + ema, s_cur, a_cur, occupancy_goal, ks_, dvh, 1)[:, 0, :] + a_new = jnp.clip(actor_def.apply( + {"params": recursive_actor_params}, + mids, actor_goal).mode(), -1.0, 1.0) + s_cur = jnp.where(cont[:, None], mids, s_cur) + a_cur = jnp.where(cont[:, None], a_new, a_cur) + return (s_cur, a_cur, cont, kk), None + + (s_f, a_f, _, k), _ = jax.lax.scan( + level, (s0, a0, jnp.ones((B2,), bool), k), None, + length=rec_max_depth) + k, kr = jax.random.split(k) + return gl( + ema, s_f, a_f, reward_goal, kr, dvh, + n_ord=N_ORDERS_PI, cond_goal=occupancy_goal) + + # =================================================================== + # 8. Actor: anchored gradient ascent through the read-out + # =================================================================== + # jitted deterministic actor apply for eval — the OGBench evaluate() loop + # acts ONE step at a time, so an un-jitted flax apply (re-traced per step, + # on CPU) dominates eval wall-clock: measured 22.3 ms/step un-jitted-CPU vs + # 3.7 ms/step jitted (~6x). params are passed as an arg so a fresh-params + # eval agent reuses the same compiled graph. eval uses temperature 0 + # (mode()), so no RNG needed. + @jax.jit + def _eval_act(params, observations, goals): + return jnp.clip(actor_def.apply({"params": params}, observations, goals).mode(), + -1, 1) + + class _EvalAgent: + """Minimal wrapper so the OGBench evaluate() loop can act (jitted).""" + + def __init__(self, params): + self.params = params + + def sample_actions(self, observations, goals=None, seed=None, temperature=0.0): + return _eval_act(self.params, observations, goals) + + key, ik2 = jax.random.split(key) + actor_init_observations = ( + pixel_obs_np[:2] if pixel_actor else obs_np[:2]) + actor_init_goals = ( + pixel_obs_np[:2] if pixel_actor else actor_goal_np[:2]) + actor_params = actor_def.init( + ik2, actor_init_observations, actor_init_goals)["params"] + pixel_actor_init_meta = None + if pixel_actor_init_ckpt is not None: + import pickle as _pixel_actor_pickle + + init_path = os.path.realpath( + os.path.abspath(pixel_actor_init_ckpt)) + if not os.path.isfile(init_path): + raise ValueError( + f"pixel actor initialization does not exist: {init_path}") + init_sha256 = file_sha256(init_path) + if init_sha256 != pixel_actor_init_ckpt_sha256: + raise ValueError( + "pixel actor initialization SHA-256 mismatch: " + f"expected={pixel_actor_init_ckpt_sha256} " + f"actual={init_sha256} path={init_path}") + with open(init_path, "rb") as file: + init_payload = _pixel_actor_pickle.load(file) + init_actor_params, pixel_actor_init_meta = ( + validate_visual_gcbc_actor_init( + init_payload, + env=env_id, + seed=seed, + observation_shape=pixel_actor_dataset_meta[ + "observation_shape"], + action_shape=pixel_actor_dataset_meta["action_shape"], + p_aug=pixel_actor_p_aug, + active_reference_root=ogbench_impls, + )) + if (jax.tree_util.tree_structure(init_actor_params) + != jax.tree_util.tree_structure(actor_params)): + raise ValueError( + "visual GCBC actor parameter tree does not match the exact " + "IMPALA-small RSM actor") + shape_errors = [ + (loaded.shape, expected.shape) + for loaded, expected in zip( + jax.tree_util.tree_leaves(init_actor_params), + jax.tree_util.tree_leaves(actor_params)) + if loaded.shape != expected.shape + ] + if shape_errors: + raise ValueError( + "visual GCBC actor parameter shapes do not match the RSM " + f"actor: {shape_errors}") + actor_params = jax.tree_util.tree_map( + lambda value: jnp.asarray(value), init_actor_params) + pixel_actor_init_meta.update({ + "path": init_path, + "sha256": init_sha256, + "optimizer_state_loaded": False, + "actor_remains_trainable": True, + }) + print( + "[rsm] initialized trainable IMPALA-small pixel actor from " + f"strict non-TD GCBC step={pixel_actor_init_meta['step']} " + f"sha256={init_sha256}; optimizer=fresh actor_trainable=true", + flush=True, + ) + actor_tx = optax.adam(learning_rate=config["lr"]) + if actor_loss in ("awr", "awr_distill", "ddpgbc_distill"): + value_encoder = ( + GCEncoder( + concat_encoder=encoder_modules["impala_small"]()) + if pixel_scorer else None) + value_def = GCValue( + hidden_dims=tuple(config["value_hidden_dims"]), + layer_norm=config["layer_norm"], ensemble=False, + gc_encoder=value_encoder) + key, ikv = jax.random.split(key) + value_init_observations = ( + pixel_obs_np[:2] if pixel_scorer else obs_np[:2]) + value_init_goals = ( + pixel_obs_np[:2] if pixel_scorer + else actor_goal_np[:2]) + value_params = value_def.init( + ikv, value_init_observations, + value_init_goals)["params"] + value_tx = optax.adam(learning_rate=config["lr"]) + # Keep actor params/optimizer first so eval and old checkpoint helpers + # retain their existing agent[0]/agent[1] contract. + if actor_loss in ("awr_distill", "ddpgbc_distill"): + # The optional pixel scorer is the reference visual GCIQL critic + # architecture exactly: an independent IMPALA-small early-fusion + # encoder followed by twin 512x3 MLP heads. Its recorded-action + # regression labels are empirical absorbing index returns only; + # occupancy labels are restricted to detached actor/local action + # support. The historical scorer remains a latent twin MLP. + # Neither path has a next-state value or a Bellman/TD bootstrap. + if pixel_scorer: + assert tuple(config["value_hidden_dims"]) == ( + 512, 512, 512), ( + "the raw-pixel scorer must retain the reference 512x3 " + "value-network width") + critic_encoder = ( + GCEncoder( + concat_encoder=encoder_modules["impala_small"]()) + if pixel_scorer else None) + critic_def = GCValue( + hidden_dims=tuple(config["value_hidden_dims"]), + layer_norm=config["layer_norm"], ensemble=True, + gc_encoder=critic_encoder) + key, ikq = jax.random.split(key) + critic_init_observations = ( + pixel_obs_np[:2] if pixel_scorer else obs_np[:2]) + critic_init_goals = ( + pixel_obs_np[:2] if pixel_scorer + else actor_goal_np[:2]) + critic_params = critic_def.init( + ikq, critic_init_observations, critic_init_goals, + act_np[:2])["params"] + critic_tx = optax.adam(learning_rate=config["lr"]) + critic_ema = jax.tree_util.tree_map(lambda x: x, critic_params) + agent = ( + actor_params, actor_tx.init(actor_params), + value_params, value_tx.init(value_params), + critic_params, critic_tx.init(critic_params), critic_ema, + ) + else: + critic_def = None + critic_tx = None + agent = (actor_params, actor_tx.init(actor_params), + value_params, value_tx.init(value_params)) + else: + value_def = None + value_tx = None + critic_def = None + critic_tx = None + agent = (actor_params, actor_tx.init(actor_params)) + actor_of = lambda ag: ag[0] + eval_wrap = lambda ag: _EvalAgent(ag[0] if isinstance(ag, tuple) else ag) + scorer_input_meta = { + "distill_scorer_input": distill_scorer_input, + "supervised_scalar_scorer_input": ( + "raw_rgb_pixels" if pixel_scorer + else state_feature + if actor_loss in ("awr_distill", "ddpgbc_distill") + else None), + "supervised_scalar_scorer_goal_input": ( + "raw_rgb_pixels" if pixel_scorer + else actor_goal_feature + if actor_loss in ("awr_distill", "ddpgbc_distill") + else None), + "supervised_scalar_scorer_architecture": ( + "GCValue_IMPALA_small_early_fusion_twin_MLP_512x3" + if pixel_scorer + else "GCValue_twin_MLP_512x3" + if actor_loss in ("awr_distill", "ddpgbc_distill") + else None), + "supervised_scalar_scorer_encoder": ( + "impala_small" if pixel_scorer else None), + "supervised_scalar_scorer_encoder_trainable": bool( + pixel_scorer), + "supervised_scalar_scorer_ensemble_size": ( + 2 if actor_loss in ( + "awr_distill", "ddpgbc_distill") else 0), + "supervised_scalar_scorer_target_update_source": ( + PIXEL_SCORER_TARGET_UPDATE_SOURCE + if pixel_scorer else None), + "supervised_scalar_scorer_target_update_timing": ( + PIXEL_SCORER_TARGET_UPDATE_TIMING + if pixel_scorer else None), + "supervised_scalar_scorer_target_update_tau": ( + float(DISTILL_EMA_TAU) if pixel_scorer else None), + "supervised_scalar_scorer_recorded_action_target_source": ( + _distill_empirical_index_target_source + if pixel_scorer else None), + "supervised_scalar_scorer_recorded_action_uses_occupancy": ( + False if pixel_scorer else None), + "supervised_scalar_scorer_counterfactual_target_source": ( + "discount_conditioned_ema_occupancy_index_reader_expectation" + if pixel_scorer and distill_actor_actions else None), + "supervised_scalar_scorer_counterfactual_uses_empirical": ( + False + if pixel_scorer and distill_actor_actions else None), + "supervised_scalar_scorer_target_discount": ( + "explicit_task_gamma" if pixel_scorer else None), + "supervised_scalar_scorer_receives_discount_feature": ( + False if pixel_scorer else None), + "supervised_scalar_scorer_training_augmentation": ( + "batch_probability_shared_per_row_across_state_value_goal_" + "actor_goal_edge_padded_random_crop" + if pixel_scorer else None), + "supervised_scalar_scorer_uses_proprio": ( + False if pixel_scorer else None), + "supervised_scalar_scorer_uses_coordinates": ( + False if pixel_scorer else None), + "supervised_scalar_scorer_uses_reward_arrays": ( + False if pixel_scorer else None), + "supervised_scalar_scorer_uses_td_or_bootstrap": ( + False if pixel_scorer else None), + "supervised_expectile_value_input": ( + "raw_rgb_pixels" if pixel_scorer else None), + "supervised_expectile_value_architecture": ( + "GCValue_IMPALA_small_early_fusion_single_MLP_512x3" + if pixel_scorer else None), + "supervised_expectile_value_target_source": ( + "stop_gradient_ema_twin_pixel_scorer_empirical_absorbing_" + "index_return_expectile" + if pixel_scorer else None), + "supervised_expectile_value_target_discount": ( + "explicit_task_gamma" if pixel_scorer else None), + "supervised_expectile_value_uses_next_state": ( + False if pixel_scorer else None), + "supervised_expectile_value_uses_td_or_bootstrap": ( + False if pixel_scorer else None), + "supervised_expectile_value_uses_reward_arrays": ( + False if pixel_scorer else None), + "pixel_scorer_policy_extraction": ( + "awr_dataset_action_weighted_log_likelihood" + if pixel_scorer and actor_loss == "awr_distill" + else "ddpgbc_actor_gradient_control" + if pixel_scorer else None), + "pixel_scorer_actor_advantage_source": ( + "stop_gradient_live_twin_min_q_minus_preupdate_expectile_v" + if pixel_scorer and actor_loss == "awr_distill" + else None), + "pixel_scorer_actor_weight_formula": ( + "min(exp(alpha*(Q-V)),100)" + if pixel_scorer and actor_loss == "awr_distill" + else None), + "pixel_scorer_actor_uses_dataset_actions_only": ( + True + if pixel_scorer and actor_loss == "awr_distill" + else False if pixel_scorer else None), + "pixel_scorer_supervision_regime": ( + "empirical_recorded_actions_plus_discount_conditioned_" + "occupancy_counterfactuals" + if pixel_scorer and distill_actor_actions + else "empirical_recorded_actions_only" + if pixel_scorer else None), + "pixel_scorer_and_occupancy_same_fused_step": bool( + pixel_scorer and not freeze_occupancy), + "pixel_scorer_and_actor_same_fused_step": bool(pixel_scorer), + "pixel_scorer_gradient_updates_occupancy": False, + "occupancy_gradient_updates_pixel_scorer": False, + "reader_metric_pixel_scorer_combined": bool( + reward_metric_target and pixel_scorer), + "reader_metric_pixel_scorer_update_semantics": ( + "same_fused_step_separate_gradients" + if reward_metric_target and pixel_scorer else None), + } + actor_input_meta = { + "actor_input": actor_input, + "actor_state_feature": ( + "raw_rgb_pixels" if pixel_actor else state_feature), + "final_actor_consumes_pixels": bool(pixel_actor), + "policy_observation": ( + "rendered_pixels_only" if pixel_actor + else "frozen_pixel_encoder_latent" + if latent_npz else "state"), + "actor_architecture": ( + "GCActor_IMPALA_small_early_fusion_MLP_512x3" + if pixel_actor else "GCActor_MLP_512x3"), + "actor_encoder": ( + "impala_small" if pixel_actor else None), + "actor_encoder_trainable": bool(pixel_actor), + "actor_encoder_initialization": ( + "strict_non_td_gcbc_then_jointly_trainable" + if pixel_actor_init_meta is not None + else "fresh_jointly_trainable" + if pixel_actor else None), + "actor_pixel_augmentation_probability": ( + float(pixel_actor_p_aug) if pixel_actor else 0.0), + "actor_training_augmentation": ( + "batch_probability_shared_per_row_edge_padded_random_crop" + if pixel_actor else None), + "actor_goal_relabeling": ( + "uniform_future_same_trajectory"), + "actor_pixel_state_shape": ( + pixel_actor_dataset_meta["observation_shape"] + if pixel_actor else None), + "actor_pixel_goal_shape": ( + pixel_actor_dataset_meta["observation_shape"] + if pixel_actor else None), + "actor_goal_dim_semantics": ( + "raw_rgb_pixel_scorer_goal_shape" + if pixel_scorer + else "latent_supervised_scorer_goal_width" + if pixel_actor else "actor_goal_width"), + "actor_transition_sampling": ( + "uniform_over_dataset_valid_indices" + if pixel_actor else "uniform_over_all_cached_rows"), + "pixel_actor_dataset": ( + pixel_actor_dataset_meta if pixel_actor else None), + "pixel_dataset_device_transport": ( + "dynamic_jit_dispatch_argument_not_xla_constant" + if pixel_actor else None), + "pixel_actor_init": pixel_actor_init_meta, + "pixel_artifact_provenance": pixel_artifact_provenance, + "occupancy_consumes_raw_pixels": False, + "raw_pixels_update_actor_only": bool( + pixel_actor and not pixel_scorer), + "occupancy_state_for_pixel_actor": ( + state_feature if pixel_actor else None), + "occupancy_goal_for_pixel_actor": ( + occupancy_goal_feature if pixel_actor else None), + "supervised_scalar_scorer_state_for_pixel_actor": ( + "raw_rgb_pixels" if pixel_scorer + else state_feature if pixel_actor else None), + "pixel_actor_occupancy_discount_required": bool(pixel_actor), + "pixel_actor_recursion_supported": False, + "pixel_actor_generated_midpoint_policy": None, + "pixel_actor_uses_image_or_world_model_reconstruction": False, + "completion_or_world_model_carrier_instantiated": ( + bool(completion_rec_on) if pixel_actor else None), + "pixel_actor_and_occupancy_same_fused_step": bool( + pixel_actor and not freeze_occupancy), + **scorer_input_meta, + } + + def pi_step(ag, k, t, gi_v, gi_a, ema, rec_aux, compose, step, + lp_ema=None, recursive_actor_params=None, + pixel_observations=None): + """Update the actor from the occupancy read-out. + + DDPG+BC differentiates -log Q(s,mu(s),g) through the occupancy. AWR + instead evaluates Q(s,a_data,g) once, stop-gradients that target, fits + an expectile V(s,g), and performs weighted behavior cloning. The AWR + path therefore neither differentiates through diffusion sampling nor + depends on an already-useful proposal actor. ``awr_distill`` first + regresses a twin scalar scorer onto current occupancy expectations, + then applies the reference expectile-value plus AWR extraction. The + scalar target contains no next-state value or bootstrap. DDPG + distillation also supervises this scorer at detached actor/local + actions from the same direct occupancy read-out; only the actor's + scorer gradient is delayed by ``actor_after``. Optionally, the + behavior-action point is blended with the same frozen reader evaluated + on recorded geometric successors, while every counterfactual action + remains occupancy-derived. + + With recursion on (DDPG+BC only), Q is the chain estimate: the coin's + tails branch is a differentiated first-hop read; the heads branch + multiplies the stop-gradient tail value by a likelihood ratio.""" + params, opt_state = ag[:2] + dv_t = jnp.full((B_pi,), gamma) + dv_h = jnp.full((B_pi,), hop_disc) + if joint_latent and lp_ema is not None: + state_b = latent_apply(lp_ema, base_adapter_d[t]) + actor_goal_b = latent_apply( + lp_ema, base_adapter_d[gi_a]) + value_actor_goal_b = latent_apply( + lp_ema, base_adapter_d[gi_v]) + if rich_joint_latent: + # The occupancy conditions on adapted h_goal and models + # frozen h futures, but the frozen index reader's goal stays + # in its compact z space. + goal_b = reward_goal_d[gi_a] + value_goal_b = reward_goal_d[gi_v] + occ_goal_b = actor_goal_b + value_occ_goal_b = value_actor_goal_b + else: + goal_b = actor_goal_b + value_goal_b = value_actor_goal_b + occ_goal_b = actor_goal_b + value_occ_goal_b = value_actor_goal_b + else: + state_b = obs_d[t] + goal_b = reward_goal_d[gi_a] + occ_goal_b = occ_goal_d[gi_a] + actor_goal_b = gobs_d[gi_a] + value_goal_b = reward_goal_d[gi_v] + value_occ_goal_b = occ_goal_d[gi_v] + value_actor_goal_b = gobs_d[gi_v] + if pixel_actor: + k, k_actor_input = jax.random.split(k) + if pixel_scorer: + ( + policy_state_b, + scorer_value_goal_b, + policy_goal_b, + ) = pixel_actor_scorer_batch( + k_actor_input, t, gi_v, gi_a, + pixel_observations) + scorer_value_state_b = policy_state_b + scorer_actor_state_b = policy_state_b + scorer_actor_goal_b = policy_goal_b + else: + policy_state_b, policy_goal_b = pixel_actor_batch( + k_actor_input, t, gi_a, pixel_observations) + else: + policy_state_b, policy_goal_b = state_b, actor_goal_b + if not pixel_scorer: + scorer_value_state_b = state_b + scorer_value_goal_b = value_actor_goal_b + scorer_actor_state_b = state_b + scorer_actor_goal_b = actor_goal_b + + if actor_loss == "awr": + value_params, value_opt = ag[2:] + kq, _ = jax.random.split(k) + q_data = jax.lax.stop_gradient( + gl(ema, state_b, act_d[t], goal_b, kq, dv_t, + n_ord=N_ORDERS_PI, cond_goal=occ_goal_b)) + + def value_loss_fn(vp): + v = value_def.apply({"params": vp}, state_b, actor_goal_b) + adv = q_data - v + weight = jnp.where(adv >= 0, expectile, 1.0 - expectile) + return (weight * adv ** 2).mean() + + value_loss, value_grads = jax.value_and_grad(value_loss_fn)(value_params) + value_updates, value_opt = value_tx.update( + value_grads, value_opt, value_params) + value_params = optax.apply_updates(value_params, value_updates) + value = jax.lax.stop_gradient( + value_def.apply({"params": value_params}, state_b, actor_goal_b)) + advantage = q_data - value + if adv_norm: + advantage = ((advantage - advantage.mean()) + / (advantage.std() + 1e-6)) + # Before actor_after, learn a stable behavior proposal while the + # occupancy and V are still calibrating. Afterwards this becomes + # standard clipped AWR. + log_weight = jnp.minimum(alpha * advantage, jnp.log(100.0)) + awr_weight = jnp.where(step >= actor_after, jnp.exp(log_weight), + jnp.ones_like(log_weight)) + awr_weight = jax.lax.stop_gradient(awr_weight) + + def actor_loss_fn(pp): + dist = actor_def.apply( + {"params": pp}, policy_state_b, policy_goal_b) + return -(awr_weight * dist.log_prob(act_d[t])).mean() + + loss, grads = jax.value_and_grad(actor_loss_fn)(params) + updates, opt_state = actor_tx.update(grads, opt_state, params) + params = optax.apply_updates(params, updates) + diag = jnp.stack([ + value_loss, + q_data.mean(), + advantage.std(), + awr_weight.mean(), + awr_weight.max(), + ]) + return (params, opt_state, value_params, value_opt), loss, diag + + if actor_loss in ("awr_distill", "ddpgbc_distill"): + (value_params, value_opt, critic_params, critic_opt, + critic_ema) = ag[2:] + # Preserve the established four-way scorer RNG stream exactly so + # weight-zero runs and historical resumes remain bitwise matched. + kqv, kqa, k_local, kq_support = jax.random.split(k, 4) + k_empirical_v, k_empirical_a = jax.random.split( + jax.random.fold_in(k, 0xE17)) + + # Supervision is a Monte Carlo reward expectation under the fitted + # occupancy, integrated against the frozen local index-reward reader. + # With occupancy recursion active, the target is the stop-gradient + # beta-chain expectation; otherwise it is a direct gamma query. + # The optional empirical blend replaces part of the behavior-action + # target with that same reader evaluated on recorded geometric + # successors; actor/local counterfactuals remain occupancy reads. + # Occupancy itself is still fitted only to offline geometric + # futures. This is never r + gamma*V(s'), a Bellman target, or a + # learned bootstrap. + def _distill_target(action, reward_g, occupancy_g, actor_g, kk): + if not occupancy_rec_on: + return gl( + ema, state_b, action, reward_g, kk, dv_t, + n_ord=N_ORDERS_PI, cond_goal=occupancy_g) + target_actor_params = ( + recursive_actor_params + if rec_guard == "ema" else params) + + def _composed(_): + return occupancy_chain_prob( + ema, target_actor_params, state_b, action, + reward_g, occupancy_g, actor_g, kk) + + def _direct(_): + return gl( + ema, state_b, action, reward_g, kk, dv_t, + n_ord=N_ORDERS_PI, cond_goal=occupancy_g) + + return jax.lax.cond( + compose, _composed, _direct, operand=None) + + # In the raw-pixel scorer arm, recorded actions bypass the fitted + # occupancy completely: Q labels are finite-trajectory absorbing + # Monte Carlo index returns. Thus behavior-only DDPG+BC and AWR + # cannot inherit occupancy action-ranking error. The historical + # latent arm keeps its optional convex blend. + if pixel_scorer: + empirical_v = jax.lax.stop_gradient( + empirical_index_target( + t, gi_v, value_goal_b, k_empirical_v, dv_t)) + empirical_a = jax.lax.stop_gradient( + empirical_index_target( + t, gi_a, goal_b, k_empirical_a, dv_t)) + q_target_v = empirical_v + q_target_a = empirical_a + zero = jnp.asarray(0.0, q_target_v.dtype) + empirical_target_mean = 0.5 * ( + empirical_v.mean() + empirical_a.mean()) + # No occupancy behavior-action read is made in this arm, so + # the old empirical-vs-occupancy diagnostic is inapplicable. + empirical_occupancy_abs_gap = zero + else: + q_target_v = jax.lax.stop_gradient(_distill_target( + act_d[t], + value_goal_b, value_occ_goal_b, + value_actor_goal_b, kqv)) + if distill_actor_goals: + q_target_a = jax.lax.stop_gradient(_distill_target( + act_d[t], + goal_b, occ_goal_b, actor_goal_b, kqa)) + else: + q_target_a = jnp.zeros_like(q_target_v) + + zero = jnp.asarray(0.0, q_target_v.dtype) + empirical_target_mean = zero + empirical_occupancy_abs_gap = zero + if distill_empirical_index_weight > 0.0: + empirical_v = jax.lax.stop_gradient( + empirical_index_target( + t, gi_v, value_goal_b, + k_empirical_v, dv_t)) + empirical_a = jax.lax.stop_gradient( + empirical_index_target( + t, gi_a, goal_b, + k_empirical_a, dv_t)) + empirical_target_mean = 0.5 * ( + empirical_v.mean() + empirical_a.mean()) + empirical_occupancy_abs_gap = 0.5 * ( + jnp.abs(empirical_v - q_target_v).mean() + + jnp.abs(empirical_a - q_target_a).mean()) + q_target_v = ( + (1.0 - distill_empirical_index_weight) * q_target_v + + distill_empirical_index_weight * empirical_v) + if distill_actor_goals: + q_target_a = ( + (1.0 - distill_empirical_index_weight) + * q_target_a + + distill_empirical_index_weight * empirical_a) + + if distill_actor_actions: + # DDPG queries the scalar scorer at mu(s,g), not only at + # behavior actions. Anchor that exact query and K nearby + # actions to a direct, stop-gradient occupancy/read-out + # expectation. The actor mode and local actions are detached: + # this is scorer supervision, never an actor gradient through + # the occupancy. All candidates are vmapped with the SAME + # occupancy key, hence the same base flow/diffusion noise; this + # common-random-number construction makes action gaps much less + # noisy than independent Monte-Carlo reads. + support_mode = jax.lax.stop_gradient(jnp.clip( + actor_def.apply( + {"params": params}, + policy_state_b, policy_goal_b).mode(), + -1.0, 1.0)) + local_noise = jax.random.normal( + k_local, + (distill_actor_action_k,) + support_mode.shape) + support_local = jax.lax.stop_gradient(jnp.clip( + support_mode[None, :, :] + + distill_actor_action_sigma * local_noise, + -1.0, 1.0)) + # Candidate zero is the paired behavior action, used as the + # reference in the pairwise-gap objective. Point anchors are + # applied to mode + local candidates only because the behavior + # point is already supervised above when actor goals are on. + support_actions = jnp.concatenate([ + act_d[t][None, :, :], + support_mode[None, :, :], + support_local, + ], axis=0) + + def direct_support_target(action): + return _distill_target( + action, goal_b, occ_goal_b, actor_goal_b, kq_support) + + if pixel_scorer: + # Do not even query the occupancy at the recorded action. + # Candidate zero is empirical; only detached mode/local + # counterfactuals use the occupancy model. + counterfactual_targets = jax.lax.stop_gradient( + jax.vmap(direct_support_target)( + support_actions[1:])) + q_target_support = jnp.concatenate([ + empirical_a[None, :], + counterfactual_targets, + ], axis=0) + else: + q_target_support = jax.lax.stop_gradient(jax.vmap( + direct_support_target)(support_actions)) + if ( + not pixel_scorer + and distill_empirical_index_weight > 0.0): + # Candidate zero is the recorded behavior action. Ground + # only that on-support point in observed successors; mode + # and local counterfactual candidates must still be + # supplied by the discount-conditioned occupancy. + q_target_support = q_target_support.at[0].set( + (1.0 - distill_empirical_index_weight) + * q_target_support[0] + + distill_empirical_index_weight * empirical_a) + + def critic_loss_fn(qp): + qv1, qv2 = critic_def.apply( + {"params": qp}, + scorer_value_state_b, scorer_value_goal_b, act_d[t]) + critic_loss_sum = ( + (qv1 - q_target_v) ** 2 + + (qv2 - q_target_v) ** 2).mean() + critic_loss_count = 1.0 + if distill_actor_goals: + qa1, qa2 = critic_def.apply( + {"params": qp}, + scorer_actor_state_b, scorer_actor_goal_b, act_d[t]) + critic_loss_a = ( + (qa1 - q_target_a) ** 2 + + (qa2 - q_target_a) ** 2).mean() + critic_loss_sum = critic_loss_sum + critic_loss_a + critic_loss_count += 1.0 + + support_diag = (zero, zero, zero, zero, zero, zero) + if distill_actor_actions: + # out_axes=1 preserves the twin-ensemble axis first: + # (2, candidate, batch). + support_heads = jax.vmap( + lambda action: critic_def.apply( + {"params": qp}, + scorer_actor_state_b, + scorer_actor_goal_b, action), + out_axes=1)(support_actions) + qs1, qs2 = support_heads + point_loss = ( + (qs1[1:] - q_target_support[1:]) ** 2 + + (qs2[1:] - q_target_support[1:]) ** 2 + ).mean() + + direct_gaps = ( + q_target_support[:, None, :] + - q_target_support[None, :, :]) + gap1 = qs1[:, None, :] - qs1[None, :, :] + gap2 = qs2[:, None, :] - qs2[None, :, :] + candidate_count = support_actions.shape[0] + pair_mask = jnp.triu(jnp.ones( + (candidate_count, candidate_count), + q_target_v.dtype), k=1) + pair_count = candidate_count * (candidate_count - 1) / 2 + pairwise_loss = ( + ((gap1 - direct_gaps) ** 2 + + (gap2 - direct_gaps) ** 2) + * pair_mask[:, :, None] + ).sum() / (pair_count * q_target_v.shape[0]) + # Point anchors and action-gap matching are one support + # source. Normalize by their configured weights, then + # average that source with the pre-existing value/data + # sources. Thus enabling support does not multiply the + # scorer's effective learning rate. + support_loss = ( + point_loss + + distill_actor_action_pairwise_weight * pairwise_loss + ) / (1.0 + distill_actor_action_pairwise_weight) + critic_loss_sum = critic_loss_sum + support_loss + critic_loss_count += 1.0 + support_diag = ( + point_loss, + pairwise_loss, + support_loss, + q_target_support[1].mean(), + q_target_support[2:].mean(), + jnp.minimum(qs1[1], qs2[1]).mean(), + ) + return critic_loss_sum / critic_loss_count, support_diag + + (critic_loss, support_diag), critic_grads = jax.value_and_grad( + critic_loss_fn, has_aux=True)(critic_params) + critic_updates, critic_opt = critic_tx.update( + critic_grads, critic_opt, critic_params) + new_critic_params = optax.apply_updates( + critic_params, critic_updates) + + # Match the reference extractor's update semantics: V sees a + # smoothed supervised scorer at value goals; the actor sees the + # current scorer at actor goals. Both are evaluated before this + # step's scorer update, as in a simultaneous module update. + qv1, qv2 = critic_def.apply( + {"params": critic_ema}, + scorer_value_state_b, scorer_value_goal_b, act_d[t]) + q_value = jax.lax.stop_gradient(jnp.minimum(qv1, qv2)) + if distill_actor_goals: + qav1, qav2 = critic_def.apply( + {"params": critic_ema}, + scorer_actor_state_b, scorer_actor_goal_b, act_d[t]) + q_actor_value = jax.lax.stop_gradient( + jnp.minimum(qav1, qav2)) + + def value_loss_fn(vp): + vv = value_def.apply( + {"params": vp}, + scorer_value_state_b, scorer_value_goal_b) + adv_v = q_value - vv + weight_v = jnp.where( + adv_v >= 0, expectile, 1.0 - expectile) + value_loss = (weight_v * adv_v ** 2).mean() + if distill_actor_goals: + va = value_def.apply( + {"params": vp}, + scorer_actor_state_b, scorer_actor_goal_b) + adv_a = q_actor_value - va + weight_a = jnp.where( + adv_a >= 0, expectile, 1.0 - expectile) + value_loss_a = ( + weight_a * adv_a ** 2).mean() + value_loss = 0.5 * (value_loss + value_loss_a) + return value_loss + + actor_value_params = value_params + value_loss, value_grads = jax.value_and_grad( + value_loss_fn)(value_params) + value_updates, value_opt = value_tx.update( + value_grads, value_opt, value_params) + value_params = optax.apply_updates(value_params, value_updates) + + if actor_loss == "awr_distill": + # Actor advantage uses the pre-update value and scorer, + # matching the joint reference optimizer rather than adding a + # hidden extra policy-improvement step. + qa1, qa2 = critic_def.apply( + {"params": critic_params}, + scorer_actor_state_b, + scorer_actor_goal_b, act_d[t]) + q_data = jax.lax.stop_gradient(jnp.minimum(qa1, qa2)) + value_actor = jax.lax.stop_gradient( + value_def.apply( + {"params": actor_value_params}, + scorer_actor_state_b, + scorer_actor_goal_b)) + advantage = q_data - value_actor + if adv_norm: + advantage = ((advantage - advantage.mean()) + / (advantage.std() + 1e-6)) + log_weight = jnp.minimum( + alpha * advantage, jnp.log(100.0)) + awr_weight = jnp.where( + step >= actor_after, jnp.exp(log_weight), + jnp.ones_like(log_weight)) + awr_weight = jax.lax.stop_gradient(awr_weight) + + def actor_loss_fn(pp): + dist = actor_def.apply( + {"params": pp}, policy_state_b, policy_goal_b) + return -(awr_weight * dist.log_prob(act_d[t])).mean() + + loss, actor_grads = jax.value_and_grad( + actor_loss_fn)(params) + policy_diag = ( + q_data.mean(), advantage.std(), + awr_weight.mean(), awr_weight.max()) + else: + # Exact continuous-action DDPG+BC extraction used by the + # reproduced visual control, with the sole difference that Q + # is the supervised occupancy scorer rather than a TD critic. + def actor_loss_fn(pp): + dist = actor_def.apply( + {"params": pp}, policy_state_b, policy_goal_b) + mu = jnp.clip(dist.mode(), -1.0, 1.0) + q1, q2 = critic_def.apply( + {"params": critic_params}, + scorer_actor_state_b, + scorer_actor_goal_b, mu) + q_mode = jnp.minimum(q1, q2) + q_loss = -q_mode.mean() / jax.lax.stop_gradient( + jnp.abs(q_mode).mean() + 1e-6) + bc_loss = -alpha * dist.log_prob(act_d[t]).mean() + q_weight = (step >= actor_after).astype(q_loss.dtype) + return q_weight * q_loss + bc_loss, ( + q_mode.mean(), q_loss, bc_loss, + jnp.abs(q_mode).mean()) + + (loss, policy_diag), actor_grads = jax.value_and_grad( + actor_loss_fn, has_aux=True)(params) + + actor_updates, opt_state = actor_tx.update( + actor_grads, opt_state, params) + params = optax.apply_updates(params, actor_updates) + # Match reference GCIQL target timing exactly: all current-step + # losses read the pre-update target, then the target incorporates + # the just-updated live scorer for consumption on the next fused + # step. + critic_ema = jax.tree_util.tree_map( + lambda e, p: ( + e * (1.0 - DISTILL_EMA_TAU) + + p * DISTILL_EMA_TAU), + critic_ema, new_critic_params) + diag = jnp.stack([ + value_loss, + policy_diag[0], + policy_diag[1], + policy_diag[2], + policy_diag[3], + critic_loss, + q_target_v.mean(), + q_target_v.std(), + support_diag[0], + support_diag[1], + support_diag[2], + support_diag[3], + support_diag[4], + support_diag[5], + empirical_target_mean, + empirical_occupancy_abs_gap, + ]) + return ( + params, opt_state, value_params, value_opt, + new_critic_params, critic_opt, critic_ema, + ), loss, diag + + def loss_fn(pp): + dist = actor_def.apply( + {"params": pp}, policy_state_b, policy_goal_b) + mu = jnp.clip(dist.mode(), -1, 1) + k1, k2, k3 = jax.random.split(k, 3) + lg = {"log_out": True} if elbo_logspace else {} + if occupancy_rec_on: + chain_params = ( + recursive_actor_params + if rec_guard == "ema" else pp) + + def _composed_q(_): + return occupancy_chain_prob( + ema, chain_params, state_b, mu, goal_b, + occ_goal_b, actor_goal_b, k1) + + def _direct_q(_): + return gl( + ema, state_b, mu, goal_b, k1, dv_t, + n_ord=N_ORDERS_PI, cond_goal=occ_goal_b) + + qv = jax.lax.cond( + compose, _composed_q, _direct_q, operand=None) + elif completion_rec_on: + c1, den, v1 = rec_aux + # one goal-read serves both branches: hop discount while + # composing, task discount before rec_after kicks in + dv_sel = jnp.where(compose, dv_h, dv_t) + glb = gl(ema, state_b, mu, goal_b, k1, dv_sel, + n_ord=N_ORDERS_PI, cond_goal=occ_goal_b, **lg) + num = gl(ema, state_b, mu, c1, k2, dv_h, n_ord=N_ORDERS_PI, **lg) + # continuous-goal stability guards (unguarded chains collapse + # ~25k steps after composition, regardless of occupancy + # maturity — DESIGN.md section 3). Levels: + # "ratio": (a) common random numbers — the denominator + # re-reads with the SAME key as the numerator so the + # (t, eps) draws cancel in the ratio instead of being + # exploitable; (b) clip the ratio at 1 — the actor can + # never look better than the DATA action at reaching a + # generated midpoint. MEASURED INSUFFICIENT (collapsed + # at 125k like unguarded) — kept for the record. + # "tails": ratio guards + stop-gradient on the whole heads + # term, so the actor's gradient flows ONLY through the + # beta tails read at the true goal. MEASURED: first + # composing arm to SURVIVE on continuous goals (band + # intact 50k+ past the switch where all others died) — + # the heads gradient was the collapse mechanism (the + # clip bounds the ratio's value, not its gradient below + # 1). The stop-gradded heads value still shapes credit: + # it sits inside log(qv), damping the tails gradient on + # rows the chain already reaches. + # "ema": NO stop-grad anywhere — the composed objective is + # fully differentiated like the puzzle-record form. The + # collapse loop is instead broken TEMPORALLY: every + # policy evaluation inside the chain (the midpoint + # re-decisions a1 and chain_prob's per-level actions, + # computed in one_step) uses the banking EMA actor, so + # the chain's internal values lag the live actor by + # ~1/ACTOR_EMA_TAU updates and cannot co-adapt with it + # within an update. + if rec_guard in ("ratio", "tails"): + den = jax.lax.stop_gradient( + gl(ema, state_b, act_d[t], c1, k2, dv_h, + n_ord=N_ORDERS_PI, **lg)) + if elbo_logspace: # log-ratio, clipped at log 1 = 0 + lratio = jnp.minimum(num - den, 0.0) + else: + ratio = jnp.minimum(num / jnp.maximum(den, 1e-6), 1.0) + else: + if elbo_logspace: # den precomputed in prob space (const) + lratio = num - jnp.log(jnp.maximum(den, 1e-6)) + else: + ratio = num / jnp.maximum(den, 1e-6) + if elbo_logspace: + # log-space splitting identity: no exp / floor-clip on + # the differentiated path (v1 is a constant here) + heads_l = jnp.log(rec_p) + lratio + \ + jnp.log(jnp.maximum(v1, 1e-30)) + if rec_guard == "tails": + heads_l = jax.lax.stop_gradient(heads_l) + q_rec_l = jnp.logaddexp(jnp.log(1.0 - rec_p) + glb, heads_l) + q = jnp.where(compose, q_rec_l, glb) + else: + heads = rec_p * ratio * v1 + if rec_guard == "tails": + heads = jax.lax.stop_gradient(heads) + q_rec = (1.0 - rec_p) * glb + heads + qv = jnp.where(compose, q_rec, glb) + else: + qv = gl(ema, state_b, mu, goal_b, k1, dv_t, + n_ord=N_ORDERS_PI, cond_goal=occ_goal_b, **lg) + if elbo_logspace: + q = qv + if not elbo_logspace: + q = (qv if actor_q_transform == "raw" + else jnp.log(jnp.maximum(qv, 1e-9))) + q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6) + bc = -dist.log_prob(act_d[t]).mean() + # A generative occupancy can be unreliable far from data actions + # even after its on-support distribution fit is calibrated. A + # BC-only warm start places the proposal inside the locally + # audited action region before differentiated Q extraction begins. + q_weight = (step >= actor_after).astype(q_loss.dtype) + return q_weight * q_loss + alpha * bc + + loss, grads = jax.value_and_grad(loss_fn)(params) + updates, opt_state = actor_tx.update(grads, opt_state, params) + diag = jnp.zeros((8,), dtype=loss.dtype) + return (optax.apply_updates(params, updates), opt_state), loss, diag + + # =================================================================== + # 9. One fused training step (occupancy -> completion -> actor -> EMAs) + # =================================================================== + def one_step(carry, _, pixel_observations=None): + occ_p, occ_o, ema, cm_p, cm_o, cm_e, ag, ema_actor, k, step = carry + # 9-way split kept from the multi-variant era so RNG streams (and + # therefore trained parameters) stay reproducible across versions + k, k1, k2, k3, k4, k5, k6, k7, k8 = jax.random.split(k, 9) + compose = (step > rec_after) & ((step % REC_EVERY) == 0) + + if freeze_occupancy: + occ_l = jnp.asarray(0.0) + else: + occ_p, occ_o, ema, occ_l = occ_step( + occ_p, occ_o, ema, actor_of(ag), k1, + pixel_observations) + if completion_rec_on: + ( + cond2, _z, w2, j2, _t2, _g2, _gv2, _gam2, _hit2, + ) = sample_occ_tuple(k5) + cm_p, cm_o, cm_e, _cl = cmpl_step(cm_p, cm_o, cm_e, k6, cond2, j2, w2) + + t, gi_v, gi_a = sample_pi_batch(k2) + rec_aux = () + if completion_rec_on: + # pre-compute the (non-differentiated) chain quantities: first + # midpoint c1, its density under the DATA action (the IS + # denominator), and the chain value from the first hop onward. + # This is the expensive part (chain_prob = a rec_max_depth scan of + # DDIM completions), and pi_step DISCARDS it whenever compose is + # False (qv = where(compose, q_rec, glb)). So gate it behind + # lax.cond(compose): during the pre-composition warmup we return a + # cheap zero placeholder of the same shape and skip the chain + # entirely — a large speedup on high-dim envs (e.g. antmaze's 29-D + # completion, or the visual latent-z chain), correctness-preserving + # because the value is unused until step > rec_after. (The + # completion head keeps TRAINING above so it is ready when + # composition switches on.) + dv_h = jnp.full((B_pi,), hop_disc) + + def _chain(_): + c1 = occ_bits(ema, obs_d[t], act_d[t], tgt_d[gi_a], k7, dv_h, 1)[:, 0, :] + k8a, k8b, k8c = jax.random.split(k8, 3) + den = gl(ema, obs_d[t], act_d[t], c1, k8a, dv_h) + x1 = cmpl_sample(cm_e, mk_cond2(obs_d[t], act_d[t], tgt_d[gi_a], c1), k8b) + # rec_guard="ema": ALL chain-internal policy evaluations (the + # first-hop re-decision a1 and every level inside chain_prob) + # come from the lagged EMA actor, not the live one — see the + # guard notes in pi_step. gobs_d[gi_a] == obs_d[gi_a] on state + # envs, and is the latent goal on the visual (latent_npz) path. + chain_pi = ema_actor if rec_guard == "ema" else actor_of(ag) + a1 = jnp.clip(actor_def.apply({"params": chain_pi}, + x1, gobs_d[gi_a]).mode(), -1, 1) + v1 = jnp.clip(chain_prob(ema, cm_e, chain_pi, x1, a1, + tgt_d[gi_a], gobs_d[gi_a], k8c), 0.0, 1.0) + return (c1, jax.lax.stop_gradient(den), v1) + + def _skip(_): + return (jnp.zeros((B_pi, n_bits)), jnp.zeros((B_pi,)), + jnp.zeros((B_pi,))) + + rec_aux = jax.lax.cond(compose, _chain, _skip, operand=None) + + ag, pi_l, pi_diag = pi_step( + ag, k4, t, gi_v, gi_a, ema, rec_aux, compose, step, + recursive_actor_params=ema_actor, + pixel_observations=pixel_observations) + ema_actor = jax.tree_util.tree_map( + lambda e, p: e * (1 - ACTOR_EMA_TAU) + p * ACTOR_EMA_TAU, + ema_actor, actor_of(ag)) + return (occ_p, occ_o, ema, cm_p, cm_o, cm_e, ag, ema_actor, k, step + 1), \ + (occ_l, pi_l, pi_diag) + + if joint_latent: + def one_step_joint(carry, _, pixel_observations=None): + (occ_p, occ_o, ema, cm_p, cm_o, cm_e, ag, ema_actor, k, step, + lp, lp_opt, lp_ema) = carry + k, k1, k2, _k3, k4, _k5, _k6, _k7, _k8 = jax.random.split(k, 9) + occ_p, occ_o, ema, lp, lp_opt, lp_ema, occ_l = occ_step_joint( + occ_p, occ_o, ema, lp, lp_opt, lp_ema, actor_of(ag), k1, + pixel_observations) + t, gi_v, gi_a = sample_pi_batch(k2) + ag, pi_l, pi_diag = pi_step( + ag, k4, t, gi_v, gi_a, ema, (), jnp.asarray(False), step, + lp_ema, pixel_observations=pixel_observations) + ema_actor = jax.tree_util.tree_map( + lambda e, p: e * (1 - ACTOR_EMA_TAU) + p * ACTOR_EMA_TAU, + ema_actor, actor_of(ag)) + return ( + occ_p, occ_o, ema, cm_p, cm_o, cm_e, ag, ema_actor, k, step + 1, + lp, lp_opt, lp_ema, + ), (occ_l, pi_l, pi_diag) + + if pixel_actor: + dispatch = jax.jit( + lambda carry, pixel_observations: jax.lax.scan( + lambda scan_carry, scan_x: one_step_joint( + scan_carry, scan_x, pixel_observations), + carry, None, length=STEPS_PER_DISPATCH)) + else: + dispatch = jax.jit( + lambda carry: jax.lax.scan( + one_step_joint, carry, None, + length=STEPS_PER_DISPATCH)) + else: + if pixel_actor: + dispatch = jax.jit( + lambda carry, pixel_observations: jax.lax.scan( + lambda scan_carry, scan_x: one_step( + scan_carry, scan_x, pixel_observations), + carry, None, length=STEPS_PER_DISPATCH)) + else: + dispatch = jax.jit( + lambda carry: jax.lax.scan( + one_step, carry, None, + length=STEPS_PER_DISPATCH)) + + # =================================================================== + # 10. Train / evaluate / bank + # =================================================================== + ema_actor = jax.tree_util.tree_map(lambda x: x, actor_of(agent)) + vtag = f"_{variant_tag}" if variant_tag else "" + run = wandb.init(project="gen-q-policy-improvement", + name=f"rsm{vtag}-{env_id}-s{seed}", mode=wandb_mode, + tags=["rsm", env_id], + config=dict(method="rsm", env=env_id, seed=seed, + readout=readout, actor_loss=actor_loss, + alpha=alpha, expectile=expectile, + actor_after=actor_after, adv_norm=adv_norm, + actor_q_transform=actor_q_transform, + distill_actor_goals=bool( + distill_actor_goals), + distill_goal_loss_reduction=( + distill_goal_loss_reduction), + distill_actor_actions=bool( + distill_actor_actions), + distill_actor_action_local_k=( + distill_actor_action_k + if distill_actor_actions else 0), + distill_actor_action_sigma=( + distill_actor_action_sigma + if distill_actor_actions else None), + distill_actor_action_pairwise_weight=( + distill_actor_action_pairwise_weight + if distill_actor_actions else 0.0), + distill_actor_action_pointwise_weight=( + 1.0 if distill_actor_actions else 0.0), + distill_actor_action_candidate_count=( + distill_actor_action_candidate_count), + distill_actor_action_pairwise_candidate_count=( + distill_actor_action_pairwise_candidate_count), + distill_actor_action_common_random_numbers=bool( + distill_actor_actions), + distill_actor_action_policy=( + _distill_actor_action_policy), + distill_actor_action_target_source=( + _distill_actor_action_target_source), + distill_actor_action_composed_occupancy=bool( + distill_actor_actions + and occupancy_rec_on), + distill_actor_action_support_start_step=( + _distill_actor_action_support_start), + actor_q_gradient_start_step=( + actor_after + if actor_loss in ( + "ddpgbc", "ddpgbc_distill") + else None), + distill_actor_action_loss_reduction=( + distill_actor_action_loss_reduction), + distill_actor_action_updates_occupancy=False, + **distill_empirical_meta, + policy_extraction=( + "supervised_occupancy_q_distillation_awr" + if actor_loss == "awr_distill" + else "supervised_occupancy_q_distillation_ddpgbc" + if actor_loss == "ddpgbc_distill" + else actor_loss), + uses_td_or_bootstrap=False, + critic_target_source=( + _distill_critic_target_source), + occupancy_supervision=( + occupancy_supervision_kind), + occupancy_uses_reward_labels=False, + occupancy_uses_simulator_coordinates=False, + uses_completion_or_forward_model=bool( + completion_rec_on), + occupancy_and_actor_jointly_updated=bool( + not freeze_occupancy), + joint_update_semantics=( + joint_update_semantics), + occupancy_training_policy=( + occupancy_training_policy), + actor_gradient_updates_occupancy=False, + occupancy_gradient_updates_actor=False, + gamma=gamma, + discount_conditioned=bool(spec_on), + discount_feature=( + "fourier_log_horizon" if spec_on else "none"), + recursion=( + "occupancy_latent" if occupancy_rec_on + else "prob" + if completion_rec_on else "off"), + rec_beta=rec_beta, rec_after=rec_after, + rec_guard=str(rec_guard), + rec_max_depth=int(rec_max_depth), + rec_continuation_probability=( + float(rec_p) if rec_on else 0.0), + rec_cap_mass=( + occupancy_recursion_tail_mass( + gamma, rec_beta, rec_max_depth) + if rec_on else 0.0), + rec_beta_sample_prob=( + effective_rec_beta_sample_prob + if ( + occupancy_rec_on + or protected_endpoint_mode + or reward_metric_endpoint_mode) + else 0.0), + recursion_state=( + recursion_state + if occupancy_rec_on else None), + recursion_intermediate_actor=( + "ema_actor" if rec_guard == "ema" + else "live_actor" + if occupancy_rec_on else None), + offpolicy_zero_horizon_boundary_approximation=bool( + occupancy_rec_on + and actor_loss == "ddpgbc_distill"), + elbo_logspace=elbo_logspace, + elbo_antithetic=elbo_antithetic, + gamma_spectrum_lo=gamma_spectrum_lo, + **gamma_sampling_meta, + **occ_reader_metric_meta, + **reward_metric_target_meta, + occupancy_model=occupancy_model, + occupancy_learning_rate=OCC_LR, + occ_hidden=occ_hidden, + occ_layers=occ_layers, + flow_steps=flow_steps, + occ_action_contrast_weight=( + occ_action_contrast_weight), + occ_action_contrast_margin=( + occ_action_contrast_margin), + occ_action_negative=occ_action_negative, + occ_action_negative_sigma=( + occ_action_negative_sigma), + occ_action_negative_local_k=( + effective_occ_action_negative_k), + occ_action_negative_candidate_count=( + occ_action_negative_candidate_count), + occ_action_negative_policy=( + occ_action_negative_policy), + occ_action_negative_actor_source=( + occ_action_negative_actor_source), + occ_action_negative_support_start_step=( + 0 if actor_query_occ_contrast else None), + occ_action_negative_actions_stop_gradient=bool( + actor_query_occ_contrast), + occ_action_negative_common_random_numbers=bool( + occ_action_contrast_weight > 0), + occ_action_negative_updates_actor=False, + occ_action_negative_counterfactual_target=False, + occ_action_negative_interpretation=( + occ_action_negative_interpretation), + batch_size=B_pi, occ_batch=occ_batch, + eval_episodes_periodic=eval_episodes_periodic, + latent=bool(latent_npz), + drop_proprio=bool(drop_proprio), + goal_hidden=bool(goal_hidden), + state_feature=state_feature, + actor_goal_feature=actor_goal_feature, + occupancy_goal_feature=occupancy_goal_feature, + future_feature=future_feature, + reward_goal_feature=reward_goal_feature, + occupancy_future_dim=int(n_bits), + reward_reader_dim=int(reward_goal_dim), + occupancy_target_standardization=( + occupancy_target_standardization), + frozen_encoder_fc1_reward_projection=bool( + _future_to_reward_w is not None), + occupancy_active_future_dims=int( + future_active_count), + occupancy_constant_future_dims=int( + n_bits - future_active_count), + constant_future_masking=bool( + future_active_count < n_bits), + recursive_state_support_projection=( + "relu_nonnegative_plus_constant_mean" + if ( + occupancy_rec_on + and recursion_state == "hidden") + else None), + fc1_cached_z_max_abs=fc1_cached_z_max_abs, + fc1_cached_z_mean_abs=fc1_cached_z_mean_abs, + latent_update=latent_update, + latent_lr=latent_lr, + latent_hidden=latent_hidden, + latent_goal_weight=latent_goal_weight, + latent_anchor_weight=latent_anchor_weight, + latent_aux_target=( + _joint_target if joint_latent else None), + latent_index_delta=( + _joint_index_delta + if joint_latent else None), + latent_index_neg_gap=( + _joint_neg_gap + if joint_latent else None), + latent_reader_model=( + _joint_reader_model + if joint_latent else None), + latent_index_negative_contract=( + _joint_index_negative_contract + if joint_latent else None), + reward_decoder_model=reward_decoder_model, + reward_decoder_target=reward_decoder_target, + reward_decoder_features=reward_decoder_features, + reward_decoder_logit=bool( + reward_decoder_logit), + **actor_input_meta, + init_occupancy_ckpt=( + os.path.abspath(init_occupancy_ckpt) + if init_occupancy_ckpt else None), + init_occupancy_ckpt_sha256=( + init_occupancy_ckpt_sha256), + freeze_occupancy=bool(freeze_occupancy), + train_steps=train_steps), + settings=wandb.Settings(start_method="thread")) + print(f"[fast] WANDB_URL {run.get_url()}", flush=True) + _eval_latent = [latent_ema] + _eval_latent_transform = None + _eval_state_transform = None + if joint_latent: + @jax.jit + def _eval_adapter_apply(lp, feature): + return latent_apply(lp, feature) + + def _eval_adapter_transform(feature): + return np.asarray(_eval_adapter_apply( + _eval_latent[0], jnp.asarray(feature, jnp.float32))) + + if rich_joint_latent: + _eval_state_transform = _eval_adapter_transform + else: + _eval_latent_transform = _eval_adapter_transform + if latent_npz: + _lazy_eval = [] + + def eval_success(ag, n_ep): + if not _lazy_eval: + if pixel_actor: + import ogbench + + # Exact GCIQL deployment diet: raw rendered state pixels and + # raw rendered goal pixels, with no latent/proprio wrapper. + eval_env = ogbench.make_env_and_datasets( + env_id, env_only=True) + else: + # Legacy latent actor: visual env + frozen pixel->latent + # wrapper. Created only when evaluation is requested. + from ogbench_genq.pixel_eval import make_latent_eval_env + eval_env = make_latent_eval_env( + env_id, pixel_encoder, + drop_proprio=drop_proprio, + latent_transform=_eval_latent_transform, + state_hidden=state_hidden, + goal_hidden=goal_hidden, + state_transform=_eval_state_transform, + ) + _lazy_eval.append(_make_eval_fn( + eval_env, config, evaluate, jax, wrap=eval_wrap)) + return _lazy_eval[0](ag, n_ep) + else: + eval_success = _make_eval_fn(env, config, evaluate, jax, wrap=eval_wrap) + # ---- always-on read-out calibration probe (mirrors genq_joint.py's + # elbo/q_self-vs-q_rand diagnostic): Q at the row's OWN target (d=0 — + # absorbing first-passage calibration says ~1) vs a permuted random + # target, data actions, task gamma. A collapsing self/rand log-gap is + # the flat-Q pathology; logged every eval, costs one 256-row read. + _calib_read = jax.jit(lambda em, s, a, g, cg, kk: gl( + em, s, a, g, kk, jnp.full((s.shape[0],), gamma), + cond_goal=cg)) + calib_key = jax.random.PRNGKey(seed + 777) # separate stream: training + # RNG chain stays untouched + out = os.path.join(_result_dir(env_id, seed), f"rsm{vtag}.json") + curve = [] + best = {"sr": -1.0, "agent": None} + best_saved = [-1.0] + final_info = {} + + def dump(sr, per): + json.dump({"method": "rsm", "readout": readout, "env": env_id, + "seed": seed, "actor_loss": actor_loss, + "alpha": alpha, "expectile": expectile, + "actor_after": actor_after, "adv_norm": bool(adv_norm), + "actor_q_transform": actor_q_transform, + "distill_actor_goals": bool(distill_actor_goals), + "distill_goal_loss_reduction": ( + distill_goal_loss_reduction), + "distill_actor_actions": bool(distill_actor_actions), + "distill_actor_action_local_k": ( + distill_actor_action_k + if distill_actor_actions else 0), + "distill_actor_action_sigma": ( + distill_actor_action_sigma + if distill_actor_actions else None), + "distill_actor_action_pairwise_weight": ( + distill_actor_action_pairwise_weight + if distill_actor_actions else 0.0), + "distill_actor_action_pointwise_weight": ( + 1.0 if distill_actor_actions else 0.0), + "distill_actor_action_candidate_count": ( + distill_actor_action_candidate_count), + "distill_actor_action_pairwise_candidate_count": ( + distill_actor_action_pairwise_candidate_count), + "distill_actor_action_common_random_numbers": bool( + distill_actor_actions), + "distill_actor_action_policy": ( + _distill_actor_action_policy), + "distill_actor_action_target_source": ( + _distill_actor_action_target_source), + "distill_actor_action_composed_occupancy": bool( + distill_actor_actions and occupancy_rec_on), + "distill_actor_action_support_start_step": ( + _distill_actor_action_support_start), + "actor_q_gradient_start_step": ( + actor_after + if actor_loss in ("ddpgbc", "ddpgbc_distill") + else None), + "distill_actor_action_loss_reduction": ( + distill_actor_action_loss_reduction), + "distill_actor_action_updates_occupancy": False, + **distill_empirical_meta, + "policy_extraction": ( + "supervised_occupancy_q_distillation_awr" + if actor_loss == "awr_distill" + else "supervised_occupancy_q_distillation_ddpgbc" + if actor_loss == "ddpgbc_distill" + else actor_loss), + "uses_td_or_bootstrap": False, + "occupancy_supervision": occupancy_supervision_kind, + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": bool( + completion_rec_on), + "critic_target_source": _distill_critic_target_source, + "occupancy_and_actor_jointly_updated": bool( + not freeze_occupancy), + "joint_update_semantics": joint_update_semantics, + "occupancy_training_policy": occupancy_training_policy, + "actor_gradient_updates_occupancy": False, + "occupancy_gradient_updates_actor": False, + "gamma": gamma, + "discount_conditioned": bool(spec_on), + "discount_feature": ( + "fourier_log_horizon" if spec_on else "none"), + "recursion": ( + "occupancy_latent" if occupancy_rec_on + else "prob" + if completion_rec_on else "off"), + "rec_after": rec_after, "rec_beta": rec_beta, + "rec_guard": str(rec_guard), + "rec_max_depth": int(rec_max_depth), + "rec_continuation_probability": ( + float(rec_p) if rec_on else 0.0), + "rec_cap_mass": ( + occupancy_recursion_tail_mass( + gamma, rec_beta, rec_max_depth) + if rec_on else 0.0), + "rec_beta_sample_prob": ( + effective_rec_beta_sample_prob + if ( + occupancy_rec_on + or protected_endpoint_mode + or reward_metric_endpoint_mode) + else 0.0), + "recursion_state": ( + recursion_state if occupancy_rec_on else None), + "recursion_intermediate_actor": ( + "ema_actor" if rec_guard == "ema" + else "live_actor" if occupancy_rec_on else None), + "offpolicy_zero_horizon_boundary_approximation": bool( + occupancy_rec_on + and actor_loss == "ddpgbc_distill"), + "elbo_logspace": elbo_logspace, + "elbo_antithetic": elbo_antithetic, + "gamma_spectrum_lo": gamma_spectrum_lo, + **gamma_sampling_meta, + **occ_reader_metric_meta, + **reward_metric_target_meta, + "occupancy_model": occupancy_model, + "occupancy_learning_rate": OCC_LR, + "occ_hidden": occ_hidden, + "occ_layers": occ_layers, + "flow_steps": flow_steps, + "occ_action_contrast_weight": occ_action_contrast_weight, + "occ_action_contrast_margin": occ_action_contrast_margin, + "occ_action_negative": occ_action_negative, + "occ_action_negative_sigma": occ_action_negative_sigma, + "occ_action_negative_local_k": + effective_occ_action_negative_k, + "occ_action_negative_candidate_count": + occ_action_negative_candidate_count, + "occ_action_negative_policy": occ_action_negative_policy, + "occ_action_negative_actor_source": + occ_action_negative_actor_source, + "occ_action_negative_support_start_step": ( + 0 if actor_query_occ_contrast else None), + "occ_action_negative_actions_stop_gradient": bool( + actor_query_occ_contrast), + "occ_action_negative_common_random_numbers": bool( + occ_action_contrast_weight > 0), + "occ_action_negative_updates_actor": False, + "occ_action_negative_counterfactual_target": False, + "occ_action_negative_interpretation": + occ_action_negative_interpretation, + "latent": bool(latent_npz), + "drop_proprio": bool(drop_proprio), + "goal_hidden": bool(goal_hidden), + "state_feature": state_feature, + "actor_goal_feature": actor_goal_feature, + "occupancy_goal_feature": occupancy_goal_feature, + "future_feature": future_feature, + "reward_goal_feature": reward_goal_feature, + "occupancy_future_dim": int(n_bits), + "reward_reader_dim": int(reward_goal_dim), + "occupancy_target_standardization": + occupancy_target_standardization, + "frozen_encoder_fc1_reward_projection": bool( + _future_to_reward_w is not None), + "occupancy_active_future_dims": int( + future_active_count), + "occupancy_constant_future_dims": int( + n_bits - future_active_count), + "constant_future_masking": bool( + future_active_count < n_bits), + "recursive_state_support_projection": ( + "relu_nonnegative_plus_constant_mean" + if ( + occupancy_rec_on + and recursion_state == "hidden") else None), + "fc1_cached_z_max_abs": fc1_cached_z_max_abs, + "fc1_cached_z_mean_abs": fc1_cached_z_mean_abs, + "latent_update": latent_update, + "latent_lr": latent_lr, + "latent_hidden": latent_hidden, + "latent_goal_weight": latent_goal_weight, + "latent_anchor_weight": latent_anchor_weight, + "latent_aux_target": ( + _joint_target if joint_latent else None), + "latent_index_delta": ( + _joint_index_delta if joint_latent else None), + "latent_index_neg_gap": ( + _joint_neg_gap if joint_latent else None), + "latent_reader_model": ( + _joint_reader_model if joint_latent else None), + "latent_index_negative_contract": ( + _joint_index_negative_contract + if joint_latent else None), + "readout_kind": ("classifier" if reward_decoder else readout), + "reward_decoder_model": reward_decoder_model, + "reward_decoder_target": reward_decoder_target, + "reward_decoder_index_delta": reward_decoder_index_delta, + "reward_decoder_features": reward_decoder_features, + "reward_decoder_logit": bool(reward_decoder_logit), + "rdec_samples": int(rdec_samples), + **actor_input_meta, + "eval_episodes_periodic": eval_episodes_periodic, + "success_rate": sr, + "best_sr": (max(v for _, v in curve) if curve else sr), **final_info, + "per_task": per, "curve": curve, "train_steps": train_steps, + "wall_clock_sec": round(wall_offset + time.time() - t0, 1), + "wandb_url": run.get_url()}, open(out, "w"), indent=2) + + carry = (occ_params, occ_opt, occ_ema, cmpl_params, cmpl_opt, cmpl_ema, + agent, ema_actor, key, jnp.asarray(0)) + if joint_latent: + carry = carry + (latent_params, latent_opt, latent_ema) + n_disp = train_steps // STEPS_PER_DISPATCH + + # ---- resumable full-state checkpointing (preemptable GPUs) ---------- + # rsm.py runs one-cell-per-GPU on the preemptable queue, so training must + # survive a kill at any moment and relaunch where it left off. We + # periodically pickle the ENTIRE fused-loop carry (all params + optimizer + # states + EMAs + RNG key + step) plus host-side progress (eval curve, + # banked best). On restart with the same --ckpt we device_put it back and + # skip completed dispatches. The write is atomic (tmp + rename) so a + # preemption mid-write never corrupts the checkpoint. Separate from + # --save_best (which only banks the actor snapshot for offline eval); + # --ckpt banks EVERYTHING needed to continue training. (Ported from Dan's + # PR #68 / origin/visual-antmaze onto the recursive rsm.py.) + import pickle + ckpt_every = ckpt_every if ckpt_every else eval_interval + assert ckpt_every % STEPS_PER_DISPATCH == 0, "ckpt_every must be a STEPS_PER_DISPATCH multiple" + if ckpt_archive_every is not None: + assert ckpt and ckpt_archive_every > 0, ( + "--ckpt_archive_every requires --ckpt and must be positive") + assert ckpt_archive_every % STEPS_PER_DISPATCH == 0, ( + "ckpt_archive_every must be a STEPS_PER_DISPATCH multiple") + start_di = 1 + wall_offset = 0.0 + checkpoint_load_path, requested_resume_source = resolve_checkpoint_load( + ckpt, resume_ckpt, resume_ckpt_sha256) + resume_source = None + run_meta = { + "schema_version": ( + 13 if reward_metric_target or pixel_scorer + else 12 if distill_empirical_index_weight > 0.0 + else 11 if protected_endpoint_mode or occ_reader_hit_enabled + else 10 if pixel_actor + else 9 if actor_query_occ_contrast + else 8 if occupancy_rec_on + else 7 if spec_on and gamma_sampler == "stratified_bins" + else 6 if rich_joint_latent + else 5 if actor_loss in ("awr_distill", "ddpgbc_distill") + else 4 if goal_hidden else 3 if joint_latent else 2), + "env": env_id, + "seed": int(seed), + "state_dim": int(obs_np.shape[1]), + "goal_dim": int(gobs_d.shape[1]), + "actor_goal_dim": int(gobs_d.shape[1]), + "occupancy_goal_dim": int(occ_goal_d.shape[1]), + "reward_goal_dim": int(reward_goal_d.shape[1]), + "drop_proprio": bool(drop_proprio), + "goal_hidden": bool(goal_hidden), + "state_feature": state_feature, + "actor_goal_feature": actor_goal_feature, + "occupancy_goal_feature": occupancy_goal_feature, + "future_feature": future_feature, + "reward_goal_feature": reward_goal_feature, + "occupancy_future_dim": int(n_bits), + "reward_reader_dim": int(reward_goal_dim), + "frozen_encoder_fc1_reward_projection": bool( + _future_to_reward_w is not None), + "occupancy_active_future_dims": int(future_active_count), + "occupancy_constant_future_dims": int( + n_bits - future_active_count), + "constant_future_masking": bool( + future_active_count < n_bits), + "recursive_state_support_projection": ( + "relu_nonnegative_plus_constant_mean" + if ( + occupancy_rec_on + and recursion_state == "hidden") else None), + "fc1_cached_z_max_abs": fc1_cached_z_max_abs, + "fc1_cached_z_mean_abs": fc1_cached_z_mean_abs, + "actor_loss": actor_loss, + "alpha": float(alpha), + "expectile": float(expectile), + "actor_after": int(actor_after), + "adv_norm": bool(adv_norm), + "actor_q_transform": actor_q_transform, + "distill_actor_goals": bool(distill_actor_goals), + "distill_goal_loss_reduction": distill_goal_loss_reduction, + "distill_actor_actions": bool(distill_actor_actions), + "distill_actor_action_local_k": ( + distill_actor_action_k if distill_actor_actions else 0), + "distill_actor_action_sigma": ( + float(distill_actor_action_sigma) + if distill_actor_actions else None), + "distill_actor_action_pairwise_weight": ( + float(distill_actor_action_pairwise_weight) + if distill_actor_actions else 0.0), + "distill_actor_action_pointwise_weight": ( + 1.0 if distill_actor_actions else 0.0), + "distill_actor_action_candidate_count": ( + int(distill_actor_action_candidate_count)), + "distill_actor_action_pairwise_candidate_count": ( + int(distill_actor_action_pairwise_candidate_count)), + "distill_actor_action_common_random_numbers": bool( + distill_actor_actions), + "distill_actor_action_policy": _distill_actor_action_policy, + "distill_actor_action_target_source": ( + _distill_actor_action_target_source), + "distill_actor_action_composed_occupancy": bool( + distill_actor_actions and occupancy_rec_on), + "distill_actor_action_support_start_step": ( + _distill_actor_action_support_start), + "actor_q_gradient_start_step": ( + int(actor_after) + if actor_loss in ("ddpgbc", "ddpgbc_distill") else None), + "distill_actor_action_loss_reduction": ( + distill_actor_action_loss_reduction), + "distill_actor_action_updates_occupancy": False, + **distill_empirical_meta, + "policy_extraction": ( + "supervised_occupancy_q_distillation_awr" + if actor_loss == "awr_distill" + else "supervised_occupancy_q_distillation_ddpgbc" + if actor_loss == "ddpgbc_distill" + else actor_loss), + "uses_td_or_bootstrap": False, + "occupancy_supervision": occupancy_supervision_kind, + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": bool(completion_rec_on), + "critic_target_source": _distill_critic_target_source, + "distill_ema_tau": ( + float(DISTILL_EMA_TAU) + if actor_loss in ( + "awr_distill", "ddpgbc_distill") else None), + "occupancy_and_actor_jointly_updated": bool(not freeze_occupancy), + "joint_update_semantics": joint_update_semantics, + "occupancy_training_policy": occupancy_training_policy, + "actor_gradient_updates_occupancy": False, + "occupancy_gradient_updates_actor": False, + "gamma": float(gamma), + "gamma_spectrum_lo": float(gamma_spectrum_lo), + "discount_conditioned": bool(spec_on), + "discount_feature": ( + "fourier_log_horizon" if spec_on else "none"), + "occupancy_model": occupancy_model, + "occupancy_learning_rate": float(OCC_LR), + "occ_hidden": int(occ_hidden), + "occ_layers": int(occ_layers), + "flow_steps": int(flow_steps), + "occ_action_contrast_weight": float(occ_action_contrast_weight), + "occ_action_contrast_margin": float(occ_action_contrast_margin), + "occ_action_negative": occ_action_negative, + "occ_action_negative_sigma": float(occ_action_negative_sigma), + "occ_action_negative_local_k": int( + effective_occ_action_negative_k), + "occ_action_negative_candidate_count": int( + occ_action_negative_candidate_count), + "occ_action_negative_policy": occ_action_negative_policy, + "occ_action_negative_actor_source": + occ_action_negative_actor_source, + "occ_action_negative_support_start_step": ( + 0 if actor_query_occ_contrast else None), + "occ_action_negative_actions_stop_gradient": bool( + actor_query_occ_contrast), + "occ_action_negative_common_random_numbers": bool( + occ_action_contrast_weight > 0), + "occ_action_negative_updates_actor": False, + "occ_action_negative_counterfactual_target": False, + "occ_action_negative_interpretation": + occ_action_negative_interpretation, + "batch_size": int(B_pi), + "occ_batch": int(occ_batch), + "recursion": ( + "occupancy_latent" if occupancy_rec_on + else "prob" if completion_rec_on else "off"), + "rec_beta": float(rec_beta), + "rec_after": int(rec_after), + "rec_guard": str(rec_guard), + "rec_max_depth": int(rec_max_depth), + "rec_continuation_probability": ( + float(rec_p) if rec_on else 0.0), + "rec_cap_mass": ( + occupancy_recursion_tail_mass( + gamma, rec_beta, rec_max_depth) + if rec_on else 0.0), + "rec_beta_sample_prob": ( + float(effective_rec_beta_sample_prob) + if ( + occupancy_rec_on + or protected_endpoint_mode + or reward_metric_endpoint_mode) + else 0.0), + "recursion_state": ( + recursion_state if occupancy_rec_on else None), + "recursion_intermediate_actor": ( + "ema_actor" if rec_guard == "ema" + else "live_actor" if occupancy_rec_on else None), + "offpolicy_zero_horizon_boundary_approximation": bool( + occupancy_rec_on and actor_loss == "ddpgbc_distill"), + "occupancy_target_standardization": ( + occupancy_target_standardization), + "reward_decoder_model": reward_decoder_model, + "reward_decoder_target": reward_decoder_target, + "reward_decoder_index_delta": reward_decoder_index_delta, + "reward_decoder_logit": bool(reward_decoder_logit), + "rdec_samples": int(rdec_samples), + "latent_npz": os.path.abspath(latent_npz) if latent_npz else None, + "pixel_encoder": os.path.abspath(pixel_encoder) if pixel_encoder else None, + "reward_decoder": os.path.abspath(reward_decoder) if reward_decoder else None, + "init_occupancy_ckpt": ( + os.path.abspath(init_occupancy_ckpt) + if init_occupancy_ckpt else None), + "init_occupancy_ckpt_sha256": init_occupancy_ckpt_sha256, + "freeze_occupancy": bool(freeze_occupancy), + } + run_meta.update(actor_input_meta) + run_meta.update(gamma_sampling_meta) + run_meta.update(occ_reader_metric_meta) + run_meta.update(reward_metric_target_meta) + if joint_latent: + run_meta.update({ + "latent_update": latent_update, + "latent_lr": float(latent_lr), + "latent_hidden": int(latent_hidden), + "latent_goal_weight": float(latent_goal_weight), + "latent_anchor_weight": float(latent_anchor_weight), + "latent_aux_target": _joint_target, + "latent_index_delta": int(_joint_index_delta), + "latent_index_neg_gap": int(_joint_neg_gap), + "latent_reader_model": _joint_reader_model, + "latent_index_negative_contract": ( + _joint_index_negative_contract), + "adapter_feature_dim": int(base_adapter_np.shape[1]), + }) + + def save_ckpt(carry, di): + blob = {"carry": jax.device_get(carry), "curve": curve, + "best_sr": best["sr"], + "best_agent": (jax.device_get(best["agent"]) + if best["agent"] is not None else None), + "best_saved": best_saved[0], "next_di": di + 1, + "wall": wall_offset + (time.time() - t0), "train_steps": train_steps, + "seed": seed, "env": env_id, "run_meta": run_meta, + "resume_source": resume_source, + # Diagnostics must query exactly the normalization used by the + # trained occupancy. Persist it instead of reconstructing a + # seed-dependent Monte-Carlo probe (which would silently + # diverge when prioritized discount sampling changes). + "occupancy_normalization": { + "cond_mean": np.asarray(jax.device_get(cond_mean)), + "cond_std": np.asarray(jax.device_get(cond_std)), + "target_mean": np.asarray(tgt_mu_np), + "target_std": np.asarray(tgt_sd_np), + }} + def _atomic_pickle(path): + with open(path + ".tmp", "wb") as f: + pickle.dump(blob, f) + os.replace(path + ".tmp", path) # atomic on POSIX + + _atomic_pickle(ckpt) + step_now = di * STEPS_PER_DISPATCH + if (ckpt_archive_every is not None + and step_now % ckpt_archive_every == 0): + stem, ext = os.path.splitext(ckpt) + archive = f"{stem}_step{step_now}{ext or '.pkl'}" + _atomic_pickle(archive) + print(f"[fast] archived full checkpoint at step {step_now} -> " + f"{archive}", flush=True) + + if checkpoint_load_path: + with open(checkpoint_load_path, "rb") as f: + blob = pickle.load(f) + loaded_resume_source = blob.get("resume_source") + if requested_resume_source is not None: + if checkpoint_load_path == requested_resume_source["path"]: + source_step = int(np.asarray(blob["carry"][9])) + resume_source = { + **requested_resume_source, + "checkpoint_step": source_step, + } + else: + expected_resume_source = { + **requested_resume_source, + "checkpoint_step": int( + (loaded_resume_source or {}).get( + "checkpoint_step", -1)), + } + if loaded_resume_source != expected_resume_source: + raise ValueError( + "continuation checkpoint provenance mismatch:\n" + f"saved={loaded_resume_source}\n" + f"requested={expected_resume_source}") + resume_source = loaded_resume_source + elif loaded_resume_source is not None: + raise ValueError( + "checkpoint was created from an immutable --resume_ckpt; " + "resume it with the same --resume_ckpt and " + "--resume_ckpt_sha256 arguments") + saved_agent = blob["carry"][6] + saved_meta = dict(blob.get("run_meta") or {}) + saved_has_pixel_encoder = "gc_encoder" in saved_agent[0] + if saved_has_pixel_encoder != pixel_actor: + raise ValueError( + "checkpoint actor architecture does not match " + f"--actor_input {actor_input}: checkpoint has " + f"{'a trainable image encoder' if saved_has_pixel_encoder else 'no image encoder'}") + saved_actor_in = int( + saved_agent[0]["actor_net"]["Dense_0"]["kernel"].shape[0]) + expected_actor_in = int(obs_np.shape[1] + gobs_d.shape[1]) + if pixel_actor: + expected_actor_in = int( + actor_params["actor_net"]["Dense_0"]["kernel"].shape[0]) + if saved_actor_in != expected_actor_in: + raise ValueError( + f"checkpoint actor input width {saved_actor_in} does not match " + f"requested state+goal width {expected_actor_in}. This usually " + "means --drop_proprio does not match the checkpoint; do not reuse " + "a proprioceptive checkpoint for a pixels-only result.") + saved_actor_loss = { + 2: "ddpgbc", + 4: "awr", + 7: saved_meta.get("actor_loss"), + }.get(len(saved_agent)) + if saved_actor_loss != actor_loss: + raise ValueError( + f"checkpoint actor_loss={saved_actor_loss or 'unknown'} " + f"does not match requested actor_loss={actor_loss}") + saved_has_pixel_scorer = ( + len(saved_agent) == 7 + and "gc_encoder" in saved_agent[4]) + saved_has_pixel_value = ( + len(saved_agent) >= 4 + and "gc_encoder" in saved_agent[2]) + if ( + saved_has_pixel_scorer != pixel_scorer + or saved_has_pixel_value != pixel_scorer): + raise ValueError( + "checkpoint scorer/value architecture does not match " + f"--distill_scorer_input {distill_scorer_input}: " + f"pixel_scorer={saved_has_pixel_scorer} " + f"pixel_value={saved_has_pixel_value}") + saved_seed = int(blob.get("seed", saved_meta.get("seed", seed))) + if saved_seed != seed: + raise ValueError( + f"checkpoint seed={saved_seed} does not match requested " + f"seed={seed}; the occupancy conditioning normalizer is " + "seed-dependent") + # Schema-2 checkpoints predate the selective-occupancy extraction + # control; its implicit behavior was no transplant and live updates. + saved_meta.setdefault("init_occupancy_ckpt", None) + saved_meta.setdefault("init_occupancy_ckpt_sha256", None) + saved_meta.setdefault("freeze_occupancy", False) + saved_meta = backfill_actor_input_metadata( + saved_meta, actor_input_meta) + if not pixel_scorer: + # Schema <=12 predates the opt-in raw-pixel scorer. Backfill only + # the historical latent-scorer interpretation; never infer the + # schema-13 pixel safety contract. + for key, value in scorer_input_meta.items(): + saved_meta.setdefault(key, value) + saved_meta.setdefault("actor_q_transform", "log") + saved_meta.setdefault("occupancy_model", "diffusion") + saved_meta.setdefault("occupancy_learning_rate", float(OCC_LR)) + saved_meta.setdefault("occ_hidden", OCC_HIDDEN) + saved_meta.setdefault("occ_layers", OCC_LAYERS) + saved_meta.setdefault("flow_steps", 25) + saved_meta.setdefault("occ_action_contrast_weight", 0.0) + saved_meta.setdefault("occ_action_contrast_margin", 0.1) + saved_meta.setdefault("occ_action_negative", "shuffle") + saved_meta.setdefault("occ_action_negative_sigma", 0.3) + _saved_action_contrast = ( + float(saved_meta["occ_action_contrast_weight"]) > 0.0) + _saved_action_negative = saved_meta["occ_action_negative"] + saved_meta.setdefault("occ_action_negative_local_k", 0) + saved_meta.setdefault( + "occ_action_negative_candidate_count", + 1 if _saved_action_contrast else 0) + saved_meta.setdefault( + "occ_action_negative_policy", + "behavior_action_plus_local_gaussian" + if _saved_action_contrast + and _saved_action_negative == "local" + else "batch_rolled_behavior_action" + if _saved_action_contrast else None) + saved_meta.setdefault("occ_action_negative_actor_source", None) + saved_meta.setdefault( + "occ_action_negative_support_start_step", None) + saved_meta.setdefault( + "occ_action_negative_actions_stop_gradient", False) + saved_meta.setdefault( + "occ_action_negative_common_random_numbers", + _saved_action_contrast) + saved_meta.setdefault("occ_action_negative_updates_actor", False) + saved_meta.setdefault( + "occ_action_negative_counterfactual_target", False) + saved_meta.setdefault( + "occ_action_negative_interpretation", None) + saved_meta.setdefault("occupancy_gradient_updates_actor", False) + _saved_spec = bool(saved_meta.get( + "discount_conditioned", + float(saved_meta.get("gamma_spectrum_lo", 0.0)) > 0.0)) + saved_meta.setdefault( + "gamma_sampler", + "legacy_log_uniform" if _saved_spec else "fixed_task_gamma") + saved_meta.setdefault( + "gamma_task_fraction", + GAMMA_TASK_FRACTION if _saved_spec else 1.0) + saved_meta.setdefault("gamma_horizons", None) + saved_meta.setdefault("gamma_aux_discounts", None) + saved_meta.setdefault( + "gamma_batch_allocation", + "independent_task_vs_log_uniform_aux" + if _saved_spec else "all_task_gamma") + saved_meta.setdefault("gamma_task_rows_per_occ_batch", None) + saved_meta.setdefault("gamma_beta_rows_per_occ_batch", None) + saved_meta.setdefault("gamma_aux_rows_per_occ_batch", None) + saved_meta.setdefault("gamma_sampling_importance_weighted", False) + saved_meta.setdefault( + "gamma_normalization", + "sample_standardized" if _saved_spec else "none") + saved_meta.setdefault( + "gamma_encoding_lo", + float(saved_meta.get("gamma_spectrum_lo", 0.0)) + if _saved_spec else None) + saved_meta.setdefault( + "gamma_encoding_hi", + float(saved_meta.get("gamma", gamma)) if _saved_spec else None) + saved_meta.setdefault("condition_normalizer_probe_size", 20000) + saved_meta.setdefault("condition_normalizer_seed", saved_seed) + saved_meta.setdefault( + "condition_normalizer_goal_sampler", + "legacy_same_trajectory_geometric") + saved_meta.setdefault("occupancy_actor_goal_fraction", 0.0) + saved_meta.setdefault("occupancy_actor_goal_rows_per_batch", 0) + saved_meta.setdefault("condition_normalizer_actor_goal_rows", 0) + for _key, _value in { + "reward_metric_endpoint_sampler": False, + "reward_metric_endpoint_task_fraction": None, + "reward_metric_endpoint_beta_fraction": None, + "reward_metric_endpoint_aux_fraction": None, + "reward_metric_endpoint_aux_allocation": None, + "reward_metric_endpoint_horizons": None, + "reward_metric_endpoint_normalizer_discount_rows": None, + }.items(): + saved_meta.setdefault(_key, _value) + saved_meta.setdefault("occ_reader_metric_weight", 0.0) + saved_meta.setdefault("occ_reader_metric_enabled", False) + saved_meta.setdefault("occ_reader_metric_model", None) + saved_meta.setdefault("occ_reader_metric_target", None) + saved_meta.setdefault("occ_reader_metric_projection", None) + saved_meta.setdefault("occ_reader_metric_formula", None) + saved_meta.setdefault("occ_reader_metric_normalization", None) + saved_meta.setdefault("occ_reader_metric_pullback_trace", None) + saved_meta.setdefault( + "occ_reader_metric_loss_reduction", "base_flow_mse_only") + saved_meta.setdefault("occ_reader_metric_scale", None) + saved_meta.setdefault("occ_reader_metric_weights", None) + saved_meta.setdefault( + "occ_reader_metric_uses_index_relabeling", False) + saved_meta.setdefault("occ_reader_metric_uses_reward_arrays", False) + saved_meta.setdefault("occ_reader_metric_uses_coordinates", False) + saved_meta.setdefault( + "occ_reader_metric_uses_td_or_bootstrap", False) + saved_meta = backfill_protected_endpoint_metadata(saved_meta) + for _key, _value in { + "occupancy_target_space": "absolute_future", + "occupancy_target_formula": None, + "occupancy_target_decoder": None, + "occupancy_target_invertible": False, + "occupancy_target_reader_frozen": False, + "occupancy_target_reader_model": None, + "occupancy_target_reader_target": None, + "occupancy_target_reader_index_delta": None, + "occupancy_target_metric_scale": None, + "occupancy_target_metric_weight": None, + "occupancy_target_metric_diagonal": None, + "occupancy_target_metric_inverse_diagonal": None, + "occupancy_target_goal_feature": None, + "occupancy_decoded_future_feature": + saved_meta.get( + "future_feature", + "compact_reward_predictive_z"), + "occupancy_target_uses_index_relabeling": False, + "occupancy_target_uses_reward_arrays": False, + "occupancy_target_uses_coordinates": False, + "occupancy_target_uses_td_or_bootstrap": False, + }.items(): + saved_meta.setdefault(_key, _value) + saved_meta.setdefault( + "distill_goal_loss_reduction", + "sum_value_and_actor_goals" + if saved_meta.get("distill_actor_goals", False) + else "value_goals_only") + # Checkpoints predating actor-action scorer support trained exclusively + # on dataset actions. Infer that historical behavior as OFF rather + # than silently turning the new production default on during resume. + # An enabled request therefore fails the exact metadata comparison + # below; users must start a new run or explicitly request the legacy + # --no_distill_actor_actions control. + saved_meta.setdefault("distill_actor_actions", False) + saved_meta.setdefault("distill_actor_action_local_k", 0) + saved_meta.setdefault("distill_actor_action_sigma", None) + saved_meta.setdefault("distill_actor_action_pairwise_weight", 0.0) + saved_meta.setdefault("distill_actor_action_pointwise_weight", 0.0) + saved_meta.setdefault("distill_actor_action_candidate_count", 0) + saved_meta.setdefault( + "distill_actor_action_pairwise_candidate_count", 0) + saved_meta.setdefault( + "distill_actor_action_common_random_numbers", False) + saved_meta.setdefault("distill_actor_action_policy", None) + saved_meta.setdefault("distill_actor_action_target_source", None) + saved_meta.setdefault( + "distill_actor_action_composed_occupancy", False) + saved_meta.setdefault("distill_actor_action_support_start_step", None) + saved_meta.setdefault( + "actor_q_gradient_start_step", + int(saved_meta.get("actor_after", actor_after)) + if actor_loss in ("ddpgbc", "ddpgbc_distill") else None) + saved_meta.setdefault( + "distill_actor_action_loss_reduction", "disabled") + saved_meta.setdefault( + "distill_actor_action_updates_occupancy", False) + saved_meta.setdefault("distill_empirical_index_weight", 0.0) + saved_meta.setdefault("distill_empirical_index_enabled", False) + saved_meta.setdefault( + "distill_empirical_index_target_source", None) + saved_meta.setdefault("distill_empirical_index_samples", 0) + saved_meta.setdefault("distill_empirical_index_horizon", None) + saved_meta.setdefault( + "distill_empirical_index_blend_formula", None) + saved_meta.setdefault( + "distill_empirical_index_behavior_action_only", False) + saved_meta.setdefault( + "distill_empirical_index_counterfactual_action_source", None) + saved_meta.setdefault( + "distill_empirical_index_uses_reward_arrays", False) + saved_meta.setdefault( + "distill_empirical_index_uses_coordinates", False) + saved_meta.setdefault( + "distill_empirical_index_uses_td_or_bootstrap", False) + saved_meta.setdefault( + "distill_empirical_index_recorded_action_uses_occupancy", + None) + saved_meta.setdefault( + "distill_empirical_index_counterfactual_uses_empirical", + None) + if (saved_meta.get("critic_target_source") + == "ema_occupancy_immediate_reward_expectation" + and actor_loss in ("awr_distill", "ddpgbc_distill")): + # Schema-5/6 initially used "immediate" as a generic name even + # for a nonzero index window. The reader artifact/path is part of + # the compatibility contract, so canonicalize only that stale + # label to the exact saved reader semantics. + saved_meta["critic_target_source"] = _distill_target_source + # Representation-role fields were added when rich h_goal conditioning + # was introduced. Legacy checkpoints implicitly used the current + # request's compact/default roles; only fill genuinely absent fields. + for _new_key in ( + "actor_goal_dim", "occupancy_goal_dim", "reward_goal_dim", + "goal_hidden", "state_feature", "actor_goal_feature", + "occupancy_goal_feature", "future_feature", + "reward_goal_feature", "gamma_spectrum_lo", + "discount_conditioned", "discount_feature", + "distill_actor_goals", "policy_extraction", + "uses_td_or_bootstrap", "critic_target_source", + "distill_ema_tau", + "occupancy_and_actor_jointly_updated", + "joint_update_semantics", "occupancy_training_policy", + "actor_gradient_updates_occupancy", + "reward_decoder_model", + "reward_decoder_index_delta", + "reward_decoder_logit", + "occupancy_supervision", + "occupancy_uses_reward_labels", + "occupancy_uses_simulator_coordinates", + "uses_completion_or_forward_model", + "rec_beta", "rec_after", "rec_guard", "rec_max_depth", + "rec_continuation_probability", "rec_cap_mass", + "rec_beta_sample_prob", "recursion_state", + "recursion_intermediate_actor", + "offpolicy_zero_horizon_boundary_approximation", + "occupancy_target_standardization", + "occupancy_future_dim", "reward_reader_dim", + "frozen_encoder_fc1_reward_projection", + "occupancy_active_future_dims", + "occupancy_constant_future_dims", + "constant_future_masking", + "recursive_state_support_projection", + "fc1_cached_z_max_abs", "fc1_cached_z_mean_abs"): + saved_meta.setdefault(_new_key, run_meta[_new_key]) + if joint_latent: + for _new_key in ( + "latent_reader_model", + "latent_index_negative_contract"): + saved_meta.setdefault(_new_key, run_meta[_new_key]) + saved_meta.setdefault("seed", saved_seed) + if saved_meta and saved_meta != run_meta: + raise ValueError( + "checkpoint run metadata mismatch:\n" + f"saved={saved_meta}\nrequested={run_meta}") + carry = jax.device_put(blob["carry"]) + curve = blob["curve"] + best["sr"] = blob["best_sr"] + best["agent"] = (jax.device_put(blob["best_agent"]) + if blob["best_agent"] is not None else None) + best_saved[0] = blob["best_saved"] + start_di = blob["next_di"] + wall_offset = blob["wall"] + print(f"[fast] RESUMED from {checkpoint_load_path}: " + f"step {(start_di - 1) * STEPS_PER_DISPATCH}" + f"/{train_steps}, best periodic {best['sr']:.3f}", flush=True) + if resume_source is not None: + print( + "[fast] immutable continuation source " + f"step={resume_source['checkpoint_step']} " + f"sha256={resume_source['sha256']} " + f"path={resume_source['path']} -> {os.path.abspath(ckpt)}", + flush=True, + ) + + if eval_only: + # ---- deployment-time Q-FILTER eval on the loaded REWARD-FREE occupancy (no + # training). Candidates = actor mode + sigma*Gaussian (mode kept); execute the + # argmax of the occupancy read-out gl (the classifier read-out when + # --reward_decoder is set). CLAUDE.md's third policy-improvement recipe: training + # is two supervised fits (occupancy + R_psi), improvement is search at eval. ---- + # gl is the classifier read-out when --reward_decoder is set, else the (cheap) + # density read-out q_elbo — Q-filter works with either; density is ~10x faster. + occ_ema_l = carry[2] + actor_params_l = carry[7] if eval_actor == "ema" else carry[6][0] + if joint_latent: + _eval_latent[0] = carry[12] + final_info["eval_only"] = True + final_info["eval_actor"] = eval_actor + final_info["checkpoint_step"] = int(np.asarray( + jax.device_get(carry[9]))) + final_info["checkpoint_path"] = ( + os.path.abspath(ckpt) if ckpt else None) + if qfilter <= 0: + eval_agent = (actor_params_l, carry[6][1]) + sr, per = eval_success(eval_agent, eval_episodes) + print(f"[fast] EVAL-ONLY ({eval_actor}) {env_id} FINAL sr={sr:.3f} " + f"per-task={per}", flush=True) + dump(sr, per) + wandb.finish() + return out + + _qk = [jax.random.PRNGKey(seed + 7)] + + def _genq_q(obs_b, goal_b, acts): + _qk[0], sub = jax.random.split(_qk[0]) + dv = jnp.full((len(obs_b),), gamma) + return np.asarray(gl(occ_ema_l, jnp.asarray(obs_b, jnp.float32), + jnp.asarray(acts, jnp.float32), + jnp.asarray(goal_b, jnp.float32), sub, dv)) + + _qrng = np.random.default_rng(seed + 4242) + + class _QFilterEval: + def sample_actions(self, observations, goals=None, seed=None, temperature=0.0): + o = np.asarray(observations, np.float32); g = np.asarray(goals, np.float32) + single = (o.ndim == 1) + ob = o[None] if single else o + gb = g[None] if single else g + mode = np.asarray(_eval_act(actor_params_l, jnp.asarray(ob), jnp.asarray(gb))) + out_acts = [] + for bi in range(len(ob)): + cand = mode[bi][None] + qfilter_sigma * _qrng.standard_normal( + (qfilter, mode.shape[-1])).astype(np.float32) + cand[0] = mode[bi] + cand = np.clip(cand, -1.0, 1.0) + ok = np.repeat(ob[bi][None], qfilter, 0) + gk = np.repeat(gb[bi][None], qfilter, 0) + sc = np.log(np.maximum(_genq_q(ok, gk, cand), 1e-9)) + if qfilter_bc > 0: + sc = sc - qfilter_bc * ((cand - mode[bi][None]) ** 2).sum(-1) / 2.0 + out_acts.append(cand[int(np.argmax(sc))]) + out_acts = np.stack(out_acts) + return out_acts[0] if single else out_acts + + from ogbench_genq.pixel_eval import make_latent_eval_env + qenv = (make_latent_eval_env( + env_id, pixel_encoder, drop_proprio=drop_proprio, + latent_transform=_eval_latent_transform) + if latent_npz else env) + tinfos = (qenv.unwrapped.task_infos if hasattr(qenv.unwrapped, "task_infos") + else qenv.task_infos) + per = [] + for tid in range(1, len(tinfos) + 1): + ei, _, _ = evaluate(agent=_QFilterEval(), env=qenv, task_id=tid, config=config, + num_eval_episodes=eval_episodes, num_video_episodes=0, + video_frame_skip=3, eval_temperature=0.0, eval_gaussian=None) + per.append(float(ei.get("success", 0.0))) + sr = float(np.mean(per)) + final_info["qfilter_k"] = qfilter + final_info["qfilter_sigma"] = qfilter_sigma + print(f"[fast] Q-FILTER (K={qfilter}, sigma={qfilter_sigma}) {env_id} " + f"FINAL sr={sr:.3f} per-task={per}", flush=True) + dump(sr, per) + wandb.finish() + return out + + tw = time.time() + for di in tqdm.trange(start_di, n_disp + 1, smoothing=0.05, dynamic_ncols=True): + if pixel_actor: + carry, (occ_ls, pi_ls, pi_diags) = dispatch( + carry, pixel_obs_d) + else: + carry, (occ_ls, pi_ls, pi_diags) = dispatch(carry) + i = di * STEPS_PER_DISPATCH + if di == start_di + 2: + jax.block_until_ready(carry[0]) + rate = 3 * STEPS_PER_DISPATCH / (time.time() - tw) + print(f"[fast] throughput ~{rate:.1f} steps/s " + f"({train_steps / rate / 3600:.1f} h for {train_steps} steps)", + flush=True) + if i % 1000 == 0: + train_log = {"occ/loss": float(occ_ls.mean()), + "train/pi_loss": float(pi_ls.mean())} + if actor_loss in ( + "awr", "awr_distill", "ddpgbc_distill"): + d = np.asarray(pi_diags).mean(0) + if actor_loss in ("awr", "awr_distill"): + train_log.update({ + "train/value_loss": float(d[0]), + "train/q_data": float(d[1]), + "train/adv_std": float(d[2]), + "train/awr_weight_mean": float(d[3]), + "train/awr_weight_max": float(d[4]), + }) + else: + train_log.update({ + "train/value_loss": float(d[0]), + "train/q_mode": float(d[1]), + "train/q_loss": float(d[2]), + "train/bc_loss": float(d[3]), + "train/q_abs_mean": float(d[4]), + }) + if actor_loss in ( + "awr_distill", "ddpgbc_distill"): + train_log.update({ + "train/occupancy_q_regression_loss": float(d[5]), + "train/occupancy_q_target_mean": float(d[6]), + "train/occupancy_q_target_std": float(d[7]), + "train/empirical_index_target_mean": float(d[14]), + "train/empirical_occupancy_abs_gap": float(d[15]), + }) + if distill_actor_actions: + train_log.update({ + "train/actor_action_point_regression_loss": float( + d[8]), + "train/actor_action_pairwise_gap_loss": float( + d[9]), + "train/actor_action_support_loss": float(d[10]), + "train/actor_action_direct_mode_q": float(d[11]), + "train/actor_action_direct_local_q": float(d[12]), + "train/actor_action_scorer_mode_q": float(d[13]), + }) + wandb.log(train_log, step=i) + # full-state checkpoint on its own cadence (survives preemption) — save + # AFTER any eval below so the banked best is current, hence deferred to + # the end of the eval block; here we only handle the eval-free case. + do_ckpt = ckpt and checkpoint_due( + i, ckpt_every, ckpt_archive_every) + if train_only: + if do_ckpt: + save_ckpt(carry, di) + continue + if i % eval_interval != 0: + if do_ckpt: + save_ckpt(carry, di) + continue + # ---- periodic eval: live actor AND the EMA actor; bank the winner ---- + ag = carry[6] + if joint_latent: + _eval_latent[0] = carry[12] + sr, per = eval_success(ag, eval_episodes_periodic) + if sr >= best["sr"]: + best["sr"], best["agent"] = sr, ag + ema_ag = (carry[7], ag[1]) + sr_e, per_e = eval_success(ema_ag, eval_episodes_periodic) + if sr_e >= best["sr"]: + best["sr"], best["agent"] = sr_e, ema_ag + wandb.log({"eval/success_rate_ema": sr_e}, step=i) + curve.append((i, sr)) + wandb.log({"eval/success_rate": sr, + "eval/peak": max(v for _, v in curve)}, step=i) + # ---- calibration probe (always on) ---- + nD = 256 + iD = rng_np.integers(0, N, nD) + calib_key, ck1, ck2 = jax.random.split(calib_key, 3) + if joint_latent: + rand_iD = rng_np.permutation(iD) + s_cal = latent_apply(carry[12], base_adapter_d[iD]) + cg_self = latent_apply( + carry[12], base_adapter_d[iD]) + cg_rand = latent_apply( + carry[12], base_adapter_d[rand_iD]) + if rich_joint_latent: + g_self, g_rand = ( + reward_goal_d[iD], reward_goal_d[rand_iD]) + else: + g_self, g_rand = cg_self, cg_rand + else: + s_cal, g_self = obs_d[iD], reward_goal_d[iD] + rand_iD = rng_np.permutation(iD) + g_rand = reward_goal_d[rand_iD] + cg_self = occ_goal_d[iD] + cg_rand = occ_goal_d[rand_iD] + q_self = np.asarray(_calib_read( + carry[2], s_cal, act_d[iD], g_self, cg_self, ck1)) + q_rand = np.asarray(_calib_read( + carry[2], s_cal, act_d[iD], g_rand, cg_rand, ck2)) + log_gap = float(np.log(np.maximum(q_self, 1e-12)).mean() + - np.log(np.maximum(q_rand, 1e-12)).mean()) + wandb.log({"calib/q_self": float(q_self.mean()), + "calib/q_rand": float(q_rand.mean()), + "calib/log_gap": log_gap}, step=i) + print(f"[fast] step {i} sr={sr:.3f} ema={sr_e:.3f} " + f"(peak {max(v for _, v in curve):.3f}) occ_loss={float(occ_ls.mean()):.4f} " + f"calib q_self={q_self.mean():.4f} q_rand={q_rand.mean():.4f} " + f"log_gap={log_gap:.3f}" + + (f" awr_q={np.asarray(pi_diags).mean(0)[1]:.4f}" + f" adv_std={np.asarray(pi_diags).mean(0)[2]:.4f}" + f" w_mean={np.asarray(pi_diags).mean(0)[3]:.3f}" + + (f" qreg_loss={np.asarray(pi_diags).mean(0)[5]:.5f}" + if actor_loss == "awr_distill" else "") + if actor_loss in ("awr", "awr_distill") + else (f" q_mode={np.asarray(pi_diags).mean(0)[1]:.4f}" + f" q_loss={np.asarray(pi_diags).mean(0)[2]:.4f}" + f" bc_loss={np.asarray(pi_diags).mean(0)[3]:.4f}" + f" qreg_loss={np.asarray(pi_diags).mean(0)[5]:.5f}" + + ( + f" asup_loss={np.asarray(pi_diags).mean(0)[10]:.5f}" + f" gapreg={np.asarray(pi_diags).mean(0)[9]:.5f}" + if distill_actor_actions else "") + if actor_loss == "ddpgbc_distill" else "")), + flush=True) + dump(sr, per) + if save_best and best["agent"] is not None and best["sr"] > best_saved[0]: + # bank the best snapshot so it can be 50-ep evaluated offline + bp = {"modules_actor": (best["agent"][0] + if isinstance(best["agent"], tuple) + else best["agent"])} + with open(save_best, "wb") as fbest: + pickle.dump({"params": jax.device_get(bp), + "config": dict(config), "step": i, + "periodic_sr": best["sr"]}, fbest) + best_saved[0] = best["sr"] + print(f"[fast] best snapshot (periodic {best['sr']:.3f}) saved -> " + f"{save_best}", flush=True) + if do_ckpt: + save_ckpt(carry, di) + + if train_only: + if ckpt: + save_ckpt(carry, n_disp) + final_info["status"] = "train_only_complete" + dump(None, []) + print(f"[fast] {env_id} TRAIN-ONLY complete at {train_steps} steps " + f"(drop_proprio={drop_proprio}, actor_loss={actor_loss}) -> {ckpt}", + flush=True) + wandb.finish() + return out + + # ---- final: 50-episode officials of the last-step AND banked agents ---- + ag = carry[6] + if joint_latent: + _eval_latent[0] = carry[12] + sr_last, per = eval_success(ag, eval_episodes) + curve.append((train_steps, sr_last)) + sr = sr_last + final_info["final_last_step"] = sr_last + if best["agent"] is not None: + sr_b, per_b = eval_success(best["agent"], eval_episodes) + final_info["final_best_ckpt"] = sr_b + final_info["best_ckpt_periodic_sr"] = best["sr"] + print(f"[fast] best-ckpt (periodic {best['sr']:.3f}) 50-ep FINAL sr={sr_b:.3f} " + f"vs last-step {sr_last:.3f}", flush=True) + if sr_b > sr: + sr, per = sr_b, per_b + dump(sr, per) + print(f"[fast] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}", + flush=True) + wandb.finish() + return out + + +def main(): + import argparse + ap = argparse.ArgumentParser( + description="RSM (Recursive Successor Model): occupancy + actor, no " + "Bellman/TD learning. Read-out auto-selected by goal space: exact " + "likelihood (discrete) / diffusion-ELBO (continuous). " + "Settled recipe values are constants in rsm.py, not flags.") + ap.add_argument("--env", required=True, help="OGBench env id") + ap.add_argument("--goal_space", default="auto", + choices=["auto", "discrete", "continuous"], + help="auto: puzzle-* -> discrete (gl read-out), otherwise " + "continuous (ELBO read-out)") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--ckpt", default=None, + help="path for resumable full-state checkpoint (preemptable " + "queue). Pickled every --ckpt_every steps; if it already " + "exists, training RESUMES from it. One-cell-per-GPU jobs " + "should always pass this so preemption doesn't restart.") + ap.add_argument("--ckpt_every", type=int, default=None, + help="steps between --ckpt writes (default: eval_interval; " + "must be a multiple of STEPS_PER_DISPATCH).") + ap.add_argument( + "--ckpt_archive_every", type=int, default=None, + help="also retain immutable full checkpoints at this step cadence, " + "named _stepN.pkl; useful for fair post-hoc selection " + "with an offline diagnostic before official evaluation") + ap.add_argument( + "--resume_ckpt", default=None, + help="read-only full-state checkpoint used to begin a gated " + "continuation. New and preemptable state is always written to " + "the distinct --ckpt path.") + ap.add_argument( + "--resume_ckpt_sha256", default=None, + help="required SHA-256 digest for --resume_ckpt; revalidated on every " + "launch so the gated source cannot drift") + ap.add_argument("--init_occupancy_ckpt", default=None, + help="initialize only occupancy params/optimizer/EMA from " + "this full RSM checkpoint; the actor starts fresh. " + "Used for controlled policy-extraction comparisons.") + ap.add_argument( + "--init_occupancy_ckpt_sha256", default=None, + help="immutable SHA-256 for --init_occupancy_ckpt; required for " + "strict pixel-policy runs") + ap.add_argument("--freeze_occupancy", action="store_true", + help="do not update the occupancy loaded by " + "--init_occupancy_ckpt") + ap.add_argument("--train_steps", type=int, default=2000000) + ap.add_argument("--actor_loss", default="ddpgbc", + choices=[ + "ddpgbc", "awr", "awr_distill", + "ddpgbc_distill"], + help="ddpgbc differentiates the occupancy read-out through " + "the actor. awr uses stop-gradient occupancy Q on " + "dataset actions plus an expectile V baseline. " + "awr_distill first supervises a twin scalar scorer on " + "current occupancy expectations, then matches the " + "reference expectile-value and AWR extraction; it has " + "no next-state value or TD bootstrap. ddpgbc_distill " + "uses the same supervised scorer with the reproduced " + "visual DDPG+BC extraction.") + ap.add_argument("--alpha", type=float, default=None, + help="DDPG+BC behavior-cloning weight, or AWR inverse " + "temperature. DDPG+BC default: 1.0 discrete / 0.03 " + "continuous. AWR must pass an explicit value; cube's " + "validated Gen-Q extraction uses 30.") + ap.add_argument("--expectile", type=float, default=0.7, + help="expectile for the AWR V(s,g) baseline") + ap.add_argument("--actor_after", type=int, default=0, + help="actor warmup: use plain behavior cloning before this " + "step; afterward enable DDPG occupancy gradients or " + "AWR advantage weights") + ap.add_argument("--adv_norm", action="store_true", + help="standardize AWR advantages per batch before exponentiation") + actor_goal_group = ap.add_mutually_exclusive_group() + actor_goal_group.add_argument( + "--distill_actor_goals", dest="distill_actor_goals", + action="store_true", + help="supervise the occupancy-Q scorer and value at the actor's " + "uniform-future goals (default for distilled extraction)") + actor_goal_group.add_argument( + "--no_distill_actor_goals", "--no-distill_actor_goals", + dest="distill_actor_goals", action="store_false", + help="historical control: supervise only the reference value-goal " + "mixture, despite querying the scorer at uniform-future actor goals") + ap.set_defaults(distill_actor_goals=True) + actor_action_group = ap.add_mutually_exclusive_group() + actor_action_group.add_argument( + "--distill_actor_actions", "--distill-actor-actions", + dest="distill_actor_actions", action="store_true", + help="also supervise the DDPG+BC twin scorer on the detached current " + "actor mode and local actor-neighborhood actions, with direct EMA " + "occupancy/index-reader expectations and pairwise action-gap " + "matching (default for ddpgbc_distill; inert for AWR)") + actor_action_group.add_argument( + "--no_distill_actor_actions", "--no-distill-actor-actions", + dest="distill_actor_actions", action="store_false", + help="legacy control: supervise the distilled scorer only on dataset " + "actions") + ap.set_defaults(distill_actor_actions=None) + ap.add_argument( + "--distill_actor_action_k", type=int, default=2, + help="number of Gaussian local actions around the detached actor mode " + "for DDPG+BC scorer support (default: 2)") + ap.add_argument( + "--distill_actor_action_sigma", type=float, default=0.3, + help="local actor-action support standard deviation (default: 0.3)") + ap.add_argument( + "--distill_actor_action_pairwise_weight", type=float, default=1.0, + help="weight of action-gap regression relative to point regression " + "inside the normalized actor-action support loss (default: 1)") + ap.add_argument( + "--distill_empirical_index_weight", type=float, default=0.0, + help="blend weight for a direct non-TD behavior-action target made " + "by applying the frozen index reader to recorded geometric " + "successors (0 disables; actor/local action targets remain " + "occupancy-derived)") + ap.add_argument( + "--distill_scorer_input", + choices=["latent", "pixels"], default="latent", + help="input representation for the supervised twin scalar scorer. " + "pixels enables the strict visual-GCIQL-matched IMPALA-small " + "twin 512x3 scorer and independent IMPALA-small expectile V. " + "It requires empirical weight 1. AWR uses recorded actions " + "only; matched DDPG+BC may use behavior-only " + "supervision or opt into detached mode/local targets from " + "occupancy.") + ap.add_argument("--actor_q_transform", choices=["log", "raw"], default="log", + help="DDPG+BC objective transform. log preserves the RSM " + "density recipe; raw matches GCIQL's direct normalized " + "critic-value maximization and is appropriate for a " + "classifier reward-under-occupancy read-out.") + ap.add_argument( + "--recursion", default="auto", + choices=["auto", "on", "off", "occupancy"], + help="beta-recursion. occupancy is the fair visual path: recursively " + "compose discount-conditioned occupancies in their own frozen " + "pixel-latent state space, with no completion/forward model. " + "on is the legacy state-space completion path and is rejected " + "for visual latent runs. auto is off for visual runs.") + ap.add_argument("--rec_beta", type=float, default=0.98) + ap.add_argument( + "--rec_beta_sample_prob", type=float, default=0.25, + help="occupancy-recursion only: absolute training-mixture mass placed " + "on the exact beta query (default .25; gamma keeps .50 and the " + "remaining .25 is the continuous log-horizon spectrum)") + ap.add_argument( + "--recursion_state", choices=["hidden", "compact"], default="hidden", + help="occupancy-recursion latent. hidden (primary) models frozen h256 " + "futures and maps h->compact z with the frozen encoder fc_1 only " + "at local index-reward read-out. compact is the information-" + "bottleneck control.") + ap.add_argument("--rec_after", type=int, default=100000) + ap.add_argument("--rec_max_depth", type=int, default=REC_MAX_DEPTH, + help="beta-chain depth cap (settled default 10; P(depth>10)" + "~1e-3 at beta=0.98). Raise ONLY to test whether a " + "longer-horizon env (antmaze-large) wants a deeper " + "composed chain — document any change.") + ap.add_argument("--rec_guard", default="auto", + choices=["auto", "off", "none", "ratio", "tails", "ema"], + help="recursion guard level. auto: off on discrete " + "(fully differentiated heads — the puzzle records) " + "/ tails on continuous (stop-grad heads — the only " + "form that survives there; ratio-only was measured " + "insufficient). ema: fully differentiated heads, " + "but all chain-internal policy evaluations use the " + "lagged banking-EMA actor (temporal break of the " + "self-amplifying loop instead of a gradient stop). " + "occupancy recursion supports off or ema; auto uses " + "ema for that path. " + "none = off.") + ap.add_argument("--gamma", type=float, default=GAMMA, + help=f"target policy/read-out discount and occupancy-spectrum " + f"upper edge (default {GAMMA}; unset it is " + f"bit-identical to the settled recipe). The official " + f"GCIQL uses 0.995 for humanoidmaze — pass --gamma 0.995 " + f"to match that horizon.") + ap.add_argument("--gamma_spectrum_lo", type=float, default=None, + help="discount-spectrum lower edge (default 0.95 when " + "recursion is on, the shortest bin's discount for " + "stratified_bins, 0 otherwise)") + ap.add_argument( + "--gamma_sampler", + choices=[ + "legacy_log_uniform", "stratified_bins", + "protected_endpoints", "reward_metric_endpoints"], + default="legacy_log_uniform", + help="auxiliary discount curriculum. stratified_bins allocates an " + "exact task-gamma count and near-balanced fixed horizon bins in " + "every occupancy batch; protected_endpoints fixes 60%% task " + "gamma, 30%% beta, and sqrt(h)-prioritized 10%% auxiliary rows " + "with an exact 50/50 goal-source cross-stratification; " + "reward_metric_endpoints uses the requested exact task/beta " + "fractions (defaults 50%%/25%%) and allocates the remainder by " + "--reward_metric_aux_allocation; " + "legacy_log_uniform preserves old runs") + ap.add_argument( + "--gamma_task_fraction", type=float, default=GAMMA_TASK_FRACTION, + help="fraction of every stratified occupancy batch conditioned on the " + "task gamma (legacy sampler uses the same mixture probability)") + ap.add_argument( + "--gamma_horizons", type=_parse_gamma_horizons, + default=GAMMA_STRATIFIED_HORIZONS, + help="comma-separated auxiliary horizons for stratified_bins " + "(default: 2,4,8,16,32,64)") + ap.add_argument("--elbo_K", type=int, default=16, + help="ELBO read-out draws (continuous goals)") + ap.add_argument("--elbo_logspace", action="store_true", + help="actor objective uses -L (log Q) from the ELBO read " + "directly — no exp, no 1e-9 floor-clip on the " + "gradient path; value/target-side exp(-L) unchanged " + "(continuous goals only)") + ap.add_argument("--elbo_antithetic", action="store_true", + help="ELBO reads use antithetic +/-eps pairs sharing a " + "stratified t per pair (K draws = K/2 pairs; " + "continuous goals only)") + ap.add_argument("--occupancy_model", choices=["diffusion", "flow"], + default="diffusion", + help="conditional occupancy family. flow uses linear-path " + "conditional flow matching and Euler ODE sampling.") + ap.add_argument("--occ_hidden", type=int, default=OCC_HIDDEN) + ap.add_argument("--occ_layers", type=int, default=OCC_LAYERS) + ap.add_argument("--flow_steps", type=int, default=25, + help="Euler integration steps for --occupancy_model flow") + ap.add_argument("--occ_action_contrast_weight", type=float, default=0.0, + help="reward-free likelihood ranking weight: the observed " + "future must fit better under its recorded action " + "than a relabeled negative action") + ap.add_argument("--occ_action_contrast_margin", type=float, default=0.1) + ap.add_argument( + "--occ_action_negative", + choices=["shuffle", "local", "actor_local"], + default="shuffle", + help="negative action source for occupancy likelihood ranking. " + "actor_local uses the detached live pre-update actor mode plus " + "K local actions at each exact offline tuple state/goal; this is " + "anti-exploitation ranking, not counterfactual supervision") + ap.add_argument("--occ_action_negative_sigma", type=float, default=0.3) + ap.add_argument( + "--occ_action_negative_k", type=int, default=2, + help="number of local Gaussian negatives around the actor mode for " + "--occ_action_negative actor_local (the mode is an additional " + "candidate)") + ap.add_argument( + "--occ_actor_goal_fraction", type=float, default=0.0, + help="exact fraction of each occupancy batch whose goal is sampled " + "uniformly from the same future trajectory, matching actor-goal " + "queries. The remaining rows retain the reference GCIQL value-" + "goal mix. Default 0 preserves historical runs.") + ap.add_argument( + "--occ_reader_metric_weight", type=float, default=0.0, + help="normalized auxiliary weight on conditional-flow velocity error " + "in the frozen diagonal index reader's metric. Compact futures " + "use identity; h256 futures use frozen encoder fc_1. Uses no " + "reward arrays, coordinates, TD, or bootstrap. Default 0.") + ap.add_argument( + "--occ_reader_hit_weight", type=float, default=0.0, + help="separate unweighted frozen-reader flow error on sampled " + "same-trajectory future hits at exact task gamma and beta. " + "The base importance-weighted MLE and action contrast stay " + "unchanged. Requires protected_endpoints; proposed value 0.25, " + "default 0 preserves historical runs.") + ap.add_argument( + "--occ_target_space", + choices=["absolute_future", "goal_relative_reader_metric"], + default="absolute_future", + help="conditional-flow random variable. goal_relative_reader_metric " + "models the invertible coordinate " + "u_i=sqrt(reader_weight_i)/reader_scale_i*(z_future_i-z_goal_i), " + "then decodes samples back to compact z before frozen-reader " + "evaluation. It is the strict h_state256/action5/h_goal256 " + "pixels-only arm.") + ap.add_argument( + "--reward_metric_aux_allocation", + choices=["uniform", "sqrt_h"], + default="uniform", + help="allocation of non-task/non-beta reward-metric endpoint mass " + "over horizons 8,16,32,64. uniform is the control; sqrt_h " + "prioritizes longer auxiliary horizons with deterministic " + "largest-remainder counts.") + ap.add_argument("--batch_size", type=int, default=4096) + ap.add_argument("--occ_batch", type=int, default=2048) + ap.add_argument("--eval_interval", type=int, default=25000) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--eval_episodes_periodic", type=int, + default=EVAL_EPISODES_PERIODIC, + help="episodes per task for in-training live/EMA checks") + ap.add_argument("--train_only", action="store_true", + help="fit and checkpoint without constructing the visual " + "evaluation renderer. Use a separate --eval_only job " + "on a verified EGL host.") + ap.add_argument("--latent_npz", default=None, + help="pixel path: precomputed frozen-encoder latents " + "(genq/precompute_pixel_latents.py). Standard runs " + "model compact z futures; hidden occupancy recursion " + "models state_h futures. Requires --pixel_encoder.") + ap.add_argument("--pixel_encoder", default=None, + help="frozen pixel encoder npz (genq/train_pixel_encoder" + "_jax.py) for encoding eval pixels/goals") + ap.add_argument( + "--latent_npz_sha256", default=None, + help="pixel-actor path: required immutable SHA-256 for --latent_npz") + ap.add_argument( + "--pixel_encoder_sha256", default=None, + help="pixel-actor path: required immutable SHA-256 for " + "--pixel_encoder") + ap.add_argument( + "--pixel_dataset", default=None, + help="pixel-actor path: explicit OGBench training NPZ; no implicit " + "cache lookup is accepted") + ap.add_argument( + "--pixel_dataset_sha256", default=None, + help="pixel-actor path: required immutable SHA-256 for " + "--pixel_dataset") + ap.add_argument("--drop_proprio", action="store_true", + help="strictly-pixels-only: state = E(pixels) alone, no " + "proprio channel (matches GCIQL's input diet). Pixel " + "path only.") + ap.add_argument("--goal_hidden", action="store_true", + help="strict pixels-only rich-goal arm: actor and occupancy " + "condition on the frozen encoder's state_h goal feature, " + "while reward read-out goals remain compact reward-" + "predictive z. Requires --drop_proprio, state_h in " + "--latent_npz, explicit positive --gamma_spectrum_lo, " + "and either --recursion off or hidden occupancy recursion.") + ap.add_argument( + "--actor_input", choices=["latent", "pixels"], default="latent", + help="latent preserves the historical actor. pixels gives the final " + "policy an exact trainable IMPALA-small encoder over channel-" + "concatenated state/goal RGB, while occupancy remains in the " + "reward-predictive latent. The initial rigorous implementation is " + "one-hop only and jointly updates actor plus occupancy.") + ap.add_argument( + "--pixel_actor_p_aug", type=float, default=0.5, + help="pixel actor batch-level probability of the reference shared " + "edge-padded random crop (default 0.5, matching visual GCIQL)") + ap.add_argument( + "--pixel_actor_init_ckpt", default=None, + help="optional strict non-TD visual GCBC params export used only to " + "initialize the trainable pixel actor. GCIQL exports are rejected; " + "the actor optimizer starts fresh and remains jointly trainable.") + ap.add_argument( + "--pixel_actor_init_ckpt_sha256", default=None, + help="required immutable SHA-256 for --pixel_actor_init_ckpt") + ap.add_argument("--reward_decoder", default=None, + help="CLASSIFIER read-out: npz from genq/train_reward_decoder.py. " + "Q=E_{z'~occ}[sigmoid(R_psi(z',g))] instead of the mass-at-goal " + "density (q_elbo). Continuous/pixel path only.") + ap.add_argument("--rdec_samples", type=int, default=8, + help="occupancy samples per classifier read-out call") + ap.add_argument( + "--latent_update", + choices=["frozen", "adapter", "rich_adapter"], + default="frozen", + help="frozen uses cached encoder latents unchanged; adapter jointly " + "trains a compact-z residual projection; rich_adapter jointly " + "trains a shared residual projection on cached h256 current/goal " + "features while future/reward z stays frozen. Both adapters use " + "the immediate-index auxiliary and no TD target.") + ap.add_argument("--latent_lr", type=float, default=3e-5) + ap.add_argument("--latent_hidden", type=int, default=64) + ap.add_argument("--latent_goal_weight", type=float, default=0.1) + ap.add_argument("--latent_anchor_weight", type=float, default=0.01) + ap.add_argument("--eval_only", action="store_true", + help="skip training: load --ckpt occupancy+actor and run a " + "plain-actor or deployment-time Q-filter eval.") + ap.add_argument("--eval_actor", default="ema", choices=["live", "ema"], + help="actor snapshot used by --eval_only (default: EMA)") + ap.add_argument("--qfilter", type=int, default=0, + help="Q-filter K: candidate actions per state (mode + K-1 Gaussian); " + "execute argmax occupancy-Q. 0 = plain actor.") + ap.add_argument("--qfilter_sigma", type=float, default=0.3, + help="Gaussian std for Q-filter candidate actions") + ap.add_argument("--qfilter_bc", type=float, default=0.0, + help="trust-region: subtract qfilter_bc*||a-mode||^2/2 from the score") + ap.add_argument("--variant_tag", default=None) + ap.add_argument("--save_best", default=None, + help="bank the best (live-or-EMA) actor snapshot here") + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + + is_discrete = (a.env.startswith("puzzle") if a.goal_space == "auto" + else a.goal_space == "discrete") + assert not (is_discrete and not a.env.startswith("puzzle")), \ + "discrete goal space currently implies a puzzle-* extractor" + assert bool(a.latent_npz) == bool(a.pixel_encoder), \ + "--latent_npz and --pixel_encoder go together (train on latents, eval on pixels)" + assert not (a.latent_npz and is_discrete), \ + "the pixel path is a continuous goal space (goal-z, ELBO read-out)" + if a.actor_loss in ("awr", "awr_distill", "ddpgbc_distill"): + assert a.alpha is not None, ( + f"--actor_loss {a.actor_loss} requires an explicit --alpha") + alpha = a.alpha if a.alpha is not None else (1.0 if is_discrete else 0.03) + # Visual recursion must be explicit because the legacy completion path is + # outside the pixels-only gate. State tasks retain their historical + # auto-on behavior. + recursion = ( + a.recursion if a.recursion != "auto" + else "off" if a.latent_npz else "on") + if recursion == "occupancy": + assert a.alpha is not None, ( + "--recursion occupancy requires an explicit DDPG+BC --alpha") + rec_guard = ( + a.rec_guard if a.rec_guard != "auto" + else "ema" if recursion == "occupancy" + else "off" if is_discrete else "tails") + if a.gamma_spectrum_lo is not None: + spec_lo = a.gamma_spectrum_lo + elif a.gamma_sampler in ( + "stratified_bins", "protected_endpoints", + "reward_metric_endpoints"): + spec_lo = 1.0 - 1.0 / min(a.gamma_horizons) + else: + spec_lo = ( + 0.90 if recursion == "occupancy" + else 0.95 if recursion == "on" else 0.0) + + run_rsm(a.env, seed=a.seed, train_steps=a.train_steps, alpha=alpha, + actor_loss=a.actor_loss, expectile=a.expectile, + actor_after=a.actor_after, adv_norm=a.adv_norm, + actor_q_transform=a.actor_q_transform, + distill_actor_goals=a.distill_actor_goals, + distill_actor_actions=a.distill_actor_actions, + distill_actor_action_k=a.distill_actor_action_k, + distill_actor_action_sigma=a.distill_actor_action_sigma, + distill_actor_action_pairwise_weight=( + a.distill_actor_action_pairwise_weight), + distill_empirical_index_weight=( + a.distill_empirical_index_weight), + distill_scorer_input=a.distill_scorer_input, + recursion=recursion, rec_beta=a.rec_beta, rec_after=a.rec_after, + rec_guard=rec_guard, rec_max_depth=a.rec_max_depth, + rec_beta_sample_prob=a.rec_beta_sample_prob, + recursion_state=a.recursion_state, + gamma_spectrum_lo=spec_lo, gamma_sampler=a.gamma_sampler, + gamma_task_fraction=a.gamma_task_fraction, + gamma_horizons=a.gamma_horizons, elbo_K=a.elbo_K, + elbo_logspace=a.elbo_logspace, elbo_antithetic=a.elbo_antithetic, + occupancy_model=a.occupancy_model, occ_hidden=a.occ_hidden, + occ_layers=a.occ_layers, flow_steps=a.flow_steps, + occ_action_contrast_weight=a.occ_action_contrast_weight, + occ_action_contrast_margin=a.occ_action_contrast_margin, + occ_action_negative=a.occ_action_negative, + occ_action_negative_sigma=a.occ_action_negative_sigma, + occ_action_negative_k=a.occ_action_negative_k, + occ_actor_goal_fraction=a.occ_actor_goal_fraction, + occ_reader_metric_weight=a.occ_reader_metric_weight, + occ_reader_hit_weight=a.occ_reader_hit_weight, + occ_target_space=a.occ_target_space, + reward_metric_aux_allocation=( + a.reward_metric_aux_allocation), + batch_size=a.batch_size, occ_batch=a.occ_batch, + eval_interval=a.eval_interval, eval_episodes=a.eval_episodes, + eval_episodes_periodic=a.eval_episodes_periodic, + latent_npz=a.latent_npz, pixel_encoder=a.pixel_encoder, + drop_proprio=a.drop_proprio, + goal_hidden=a.goal_hidden, + actor_input=a.actor_input, + pixel_actor_p_aug=a.pixel_actor_p_aug, + latent_npz_sha256=a.latent_npz_sha256, + pixel_encoder_sha256=a.pixel_encoder_sha256, + pixel_dataset=a.pixel_dataset, + pixel_dataset_sha256=a.pixel_dataset_sha256, + pixel_actor_init_ckpt=a.pixel_actor_init_ckpt, + pixel_actor_init_ckpt_sha256=( + a.pixel_actor_init_ckpt_sha256), + reward_decoder=a.reward_decoder, rdec_samples=a.rdec_samples, + latent_update=a.latent_update, latent_lr=a.latent_lr, + latent_hidden=a.latent_hidden, + latent_goal_weight=a.latent_goal_weight, + latent_anchor_weight=a.latent_anchor_weight, + train_only=a.train_only, eval_only=a.eval_only, + eval_actor=a.eval_actor, qfilter=a.qfilter, + qfilter_sigma=a.qfilter_sigma, qfilter_bc=a.qfilter_bc, + variant_tag=a.variant_tag, save_best=a.save_best, + gamma=a.gamma, wandb_mode=a.wandb_mode, + ckpt=a.ckpt, ckpt_every=a.ckpt_every, + ckpt_archive_every=a.ckpt_archive_every, + resume_ckpt=a.resume_ckpt, + resume_ckpt_sha256=a.resume_ckpt_sha256, + init_occupancy_ckpt=a.init_occupancy_ckpt, + init_occupancy_ckpt_sha256=( + a.init_occupancy_ckpt_sha256), + freeze_occupancy=a.freeze_occupancy) + if a.latent_npz: + # Visual (pixel) path only: the MuJoCo EGL eval env's renderer raises a + # fatal EGLError in its __del__ during interpreter shutdown (a known + # PyOpenGL/EGL teardown bug), core-dumping the process AFTER all results + # are computed and dumped — corrupting only the exit code. The env is + # created once and reused for every periodic eval, so this fires solely + # at final GC. Hard-exit before that GC runs so the run reports success. + # (Verified: env create + reset + step + proprio all work; only teardown + # aborts.) State-based runs have no renderer and skip this. + import sys as _sys + _sys.stdout.flush(); _sys.stderr.flush() + os._exit(0) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/rsm_goalfree.py b/gen_q_rsm/ogbench_genq/rsm_goalfree.py new file mode 100644 index 0000000000000000000000000000000000000000..9f36cb8551b1d5b69c528691011ed8ecf4b46338 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/rsm_goalfree.py @@ -0,0 +1,1209 @@ +"""RSM-GF — the GOAL-FREE RSM variant for the LeWM fairness comparison (#65). + +LeWM (latent world model, misc/lewm) trains with NO goals: JEPA on frames + +actions; the goal only enters at test time as a CEM cost. The maintained RSM +(rsm.py) conditions its occupancy AND its actor on the goal during training, +so the comparison is confounded. This variant removes every goal from +TRAINING so the two methods consume the same information: + + * GOAL-FREE OCCUPANCY: conditional diffusion p(z_future | s, a) over the + reward-relevant coordinates z (cube xyz via target_extractors), condition + = [obs, act] ONLY — no goal-z, no gamma spectrum (single gamma 0.99, no + recursion; the minimal honest v1). Same continuous Gaussian + eps-prediction path, geometric-horizon pair sampling (the plain + trajectory-truncated branch — the reward-targeted stratification of + rsm.py NEEDS a goal index and is therefore dropped, weights are 1), and + batch/optimizer constants as rsm.py. + * GOAL-FREE BC PRIOR: GCActor applied with goals=None (it degrades cleanly + to a state-only MLP: inputs = [observations] when goals is None), trained + by max-likelihood on dataset actions. No Q gradient, no goal anywhere. + * TEST-TIME Q-FILTER (the LeWM-comparable deployment): at each env step, + K candidate actions from the BC prior (trust region: mode + sigma*N(0,1), + mode always candidate 0 — eval_plan.py's kept machinery; the prior's own + temperature-1 std of 1.0 is near-uniform and lets argmax exploit model + error), each scored by the diffusion-ELBO read-out of the TEST goal's z + under the goal-free occupancy (rsm.py's q_elbo with the goal ABSENT from + the condition), executed action = argmax of the density-penalized score + log q(s, a_i; g_z) - PLAN_BC * ||a_i - mode||^2 / 2 . + The penalty is the documented fix for the optimizer's curse (raw argmax + 0.760 -> 0.224 with more candidates; lambda=10 restored parity and the + matched-occupancy K-ladder went monotone UP to 0.832 — see + unused/docs/EXPERIMENTS.md B6). It transfers verbatim to the goal-free + setting because it never touches the goal: it is the log-density of the + candidate under the goal-free proposal Gaussian itself, i.e. exactly the + BC anchor of the training objective re-applied at test time. + + Goal information used, per phase: TRAIN: none. TEST: goal observation + -> extract_target -> z_g, entering ONLY as the point where the occupancy + ELBO is evaluated (the analogue of LeWM's CEM cost point). + +RECURSION + GAMMA-SPECTRUM (the goal-free port of rsm.py's machinery, #65). +`--recursion on` turns the v1 into a recursion-trained goal-free occupancy — +still conditioned on [s, a] ONLY (no goal; that invariant is what makes it +"unconditional"), but now ALSO on the discount gamma~ drawn from a spectrum: + + * SPECTRUM CONDITIONING: the occupancy becomes p(z | s, a, enc(gamma~)), + Fourier-encoding gamma~ EXACTLY as rsm.py does (normalized log-horizon, + FOURIER_K sin/cos pairs). gamma~ is drawn log-uniformly in horizon space + over [gamma_spectrum_lo, GAMMA] w.p. GAMMA_SPECTRUM_P, else the task GAMMA. + This is goal-free — gamma is a discount knob, not a goal — and it teaches + ONE model the beta-horizon occupancy AND the gamma-horizon occupancy so the + recursion can query either from the same network. + * BETA-RECURSION AT TRAINING TIME: the occupancy composition identity + d_gamma = (1-p) d_beta + p * E[ d_gamma(hop) ], p = (g-b)/(g(1-b)), + does NOT reference the goal (the goal only enters at read-out), so the + machinery ports verbatim. A COMPLETION HEAD (rsm.py's cmpl_model, a small + conditional Gaussian diffusion) is co-trained on the same (s,a)->z tuples + with the beta-hop midpoint z teacher-forced; it expands a sampled midpoint + z_mid to a full next observation to re-condition the next hop. The BC prior + re-decides the hop action there (goal-free — no goal anywhere in the chain). + * RECURSIVE READ-OUT: at test time the Q at the goal z_g is the coin-gated + fixed-depth chain (rsm.py's chain_prob): each level flips the p-coin, samples + ONE beta-hop midpoint, completes it, re-decides, and the surviving node is + read with exp(-ELBO at z_g). The read-out point z_g is unchanged; it now + reads a recursively-COMPOSED occupancy instead of a single beta-read. With + the chain disabled the read-out is the plain gamma-conditioned ELBO. + + EQUIVALENCE: `--recursion off` with no spectrum is byte-identical to the v1 + (the spectrum columns, the completion head, and the chain are all gated off; + the occupancy/BC RNG streams are untouched). + +TEST-TIME STEERING (#65 ladder — `--steer`, checkpoint-only, NO retraining). +All modes share the anchor a0 = BC mode and the SAME density-penalized +objective the filter argmaxes, + + score(a) = log q_elbo_gf(s, a; g_z) - PLAN_BC * ||a - a0||^2 / 2 , + +they differ only in how hard they optimize it per env step: + + filter argmax score over K = a0 + PLAN_SIGMA*N(0,1) candidates (a0 + first) — bit-exact the original control (RNG streams preserved). + grad N steps (`--grad_n`, up to 64) of clipped gradient ascent on + score starting at a0, step size `--grad_eta`. score is pathwise + differentiable in a (a enters only the diffusion condition); the + stratified-t/eps key is FIXED for the whole ascent of one env + step — rsm.py's actor-gradient pattern — so the ascent climbs a + deterministic surface. Single start from the BC mode. + cem R rounds of action-space CEM: round 0 = the filter candidates; + refit a diagonal Gaussian on the top-`cem_elites` by score (std + floored at `cem_std_floor`); resample K; executed action = best + score seen across all rounds. One scoring key per env step, so + scores are comparable across rounds. + grad_cem cem winner, then N grad steps (same anchored objective). + +Higher-compute modes (#65 test-time-compute sweep): + + multistart Sample S=`--n_start` starts from the goal-free BC prior + (a0 + PLAN_SIGMA*N(0,1), each clipped to [-1,1]); grad-ascend + EACH start `--grad_n` steps under the SAME density penalty + (anchor = the SHARED BC mode a0, so every ascent stays in the + one trust region the BC prior defines); execute the ascended + action with the best penalized score. Keeps each ascent local + (the optimizer's-curse fix — one wide search over the noisy + generative estimate collapses; S independent local climbs do + not) while spending ~S x the grad compute. One scoring/gradient + key per env step (all starts share it — scores comparable). + pi Test-time policy improvement (the headline lever): `--pi_rounds` + rounds of {sample `--pi_k` candidates from the CURRENT proposal + (round 0 = the BC prior a0 + PLAN_SIGMA*N; later rounds = + Gaussian refit on the top-`--pi_elites` penalized elites, std + floored `--pi_std_floor`), take `--pi_grad_n` grad steps on the + round's best under the penalty, refit the proposal around that + improved action}. A few steps of policy iteration in action + space, all inside the density trust region (penalty anchored to + the fixed BC mode a0 throughout). Executed action = the best + penalized-score action ever seen. Reports its displacement from + the BC mode. + softmax EXPECTATION-form test-time SELECTION (this campaign's core move — + "expectation beats max" — applied at the final action pick). Same + multistart candidate machinery (S=`--n_start` starts ~ BC prior, + each grad-ascended `--grad_n` steps under the SAME density + penalty), but instead of executing the single argmax penalized-Q + candidate it executes the SOFTMAX-WEIGHTED MEAN action + a_exec = sum_i w_i a_i, w_i = softmax(score_i / `--softmax_temp`), + score = penalized log-q, clipped to [-1,1]. The optimizer's-curse + failure is argmax over a noisy generative Q̂; averaging a set of + high-Q near-manifold candidates is the low-variance alternative + (the same reason the occupancy read-out itself is an expectation, + not a max). `--softmax_temp` brackets sharp (->argmax) to soft + (->uniform mean). `--softmax_over_grad_traj` widens the pool to + every intermediate grad iterate (all penalty-kept near the data + manifold). Reports mean ||a_exec - a0||. + +The penalty is NEVER dropped: raw argmax over the noisy generative estimate +collapses (0.760 -> 0.224 measured; EXPERIMENTS.md B6). If grad steering +overshoots (score up, success down), that is the optimizer's-curse signature +and is reported, not tuned around. + +Run (official, one GPU): + python ogbench_genq/rsm_goalfree.py --env cube-single-play-v0 \ + --save_ckpt ogbench_genq/checkpoints/rsm_goalfree_cube_single.pkl +Steered eval from the checkpoint (appends one entry to +experiments/{env}/results/{seed}/rsm_uncond_steer.json): + python ogbench_genq/rsm_goalfree.py --env cube-single-play-v0 \ + --load_ckpt ogbench_genq/checkpoints/rsm_goalfree_cube_single_500k.pkl \ + --steer grad --grad_n 16 --grad_eta 0.02 +CPU smoke (login node): + JAX_PLATFORMS=cpu python ogbench_genq/rsm_goalfree.py --env cube-single-play-v0 \ + --train_steps 200 --episodes 2 --max_tasks 2 --wandb_mode disabled +""" +import json +import os +import pickle +import time + +import numpy as np + +if __package__ in (None, ""): # allow direct `python ogbench_genq/rsm_goalfree.py` + import sys as _sys + _sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from ogbench_genq._runner import OGBENCH_IMPLS, _result_dir, _setup_paths + +# ===================== RECIPE CONSTANTS (from rsm.py) ===================== +GAMMA = 0.99 # task discount (OGBench standard) +OCC_LR = 3e-4 # occupancy AdamW learning rate +OCC_HIDDEN = 256 # occupancy MLP width +OCC_LAYERS = 3 +OCC_TIME_DIM = 64 +OCC_T = 100 # diffusion timesteps +OCC_TAU = 0.005 # occupancy Polyak rate (the read-out uses the EMA) +ELBO_K = 16 # stratified-t draws per ELBO read-out +STEPS_PER_DISPATCH = 100 # fused lax.scan window per host dispatch +# ---- gamma-spectrum + beta-recursion (rsm.py port; --recursion on only) ---- +GAMMA_SPECTRUM_P = 0.5 # P(spectrum draw) vs task gamma, per occupancy tuple +FOURIER_K = 4 # sin/cos pairs of the log-horizon gamma encoding +REC_MAX_DEPTH = 10 # chain cap; P(depth > 10) ~ 1e-3 at beta = 0.98 +REC_CHAIN_M = 8 # chains averaged per recursive read-out (variance) +# ---- test-time Q-filter (eval_plan.py's kept density-penalized variant) ---- +PLAN_SIGMA = 0.2 # candidate trust region: mode + sigma * N(0,1) +PLAN_BC = 10.0 # density penalty lambda (EXPERIMENTS.md B6: the + # documented optimizer's-curse fix; do not drop) + + +def run_rsm_goalfree(env_id, seed=0, train_steps=500000, plan_k=32, + recursion="off", gamma_spectrum_lo=0.0, rec_beta=0.98, + rec_depth=REC_MAX_DEPTH, + batch_size=4096, occ_batch=2048, + episodes=50, max_tasks=0, save_ckpt=None, load_ckpt=None, + steer=None, read="elbo", + grad_n=16, grad_eta=0.02, grad_lam=PLAN_BC, + cem_rounds=2, cem_elites=8, cem_std_floor=0.05, + n_start=8, pi_rounds=3, pi_k=32, pi_elites=8, + pi_grad_n=4, pi_std_floor=0.05, + softmax_temp=0.1, softmax_over_grad_traj=False, + steer_out="rsm_uncond_steer.json", + wandb_mode="online", ogbench_impls=OGBENCH_IMPLS): + """Train the goal-free occupancy + BC prior, then Q-filter eval. + + steer=None keeps the original behavior (BC anchor + K-filter -> + rsm_goalfree.json). steer in {filter,grad,cem,grad_cem} evaluates ONE + steered policy and appends an entry to results/{seed}/{steer_out}. + + Returns the result-JSON path.""" + _setup_paths(ogbench_impls) + from functools import partial + + import jax + import jax.numpy as jnp + import optax + import tqdm + import wandb + from utils.env_utils import make_env_and_datasets + from utils.evaluation import evaluate + from utils.networks import GCActor + import target_extractors + from train_genq_jax import build_ends, cosine_abar, make_model + from agents.gciql import get_config + + assert not env_id.startswith("puzzle"), \ + "v1 of the goal-free variant is the continuous (Gaussian eps) branch only" + t0 = time.time() + config = get_config() # reference GCActor sizes / lr / const_std + B_pi = int(batch_size) + + # ---- recursion / spectrum resolution (all gated OFF for the exact v1) ---- + # rec_on turns on the gamma-spectrum occupancy + the co-trained completion + # head + the recursive read-out. spec_on requires a positive spectrum edge. + # rec_p is the beta-hop continuation probability from the splitting identity + # d_gamma = (1-p) d_beta + p E[d_gamma(hop)]. The chain hops at beta, so the + # occupancy is read at beta while composing (hop_disc) and at gamma at leaves. + rec_on = recursion == "on" + spec_on = rec_on and gamma_spectrum_lo > 0.0 + rec_p = (GAMMA - rec_beta) / (GAMMA * (1.0 - rec_beta)) if rec_on else 0.0 + hop_disc = rec_beta if spec_on else GAMMA + # rec_depth: the number of coin-gated composition hops in the chain read + # (each hop = one more beta-horizon composition, i.e. a longer effective + # horizon in the splitting identity d_gamma = (1-p) d_beta + p E[d_gamma]). + # Static python int -> lax.scan `length`; clamped to a sane [1, 64]. + rec_depth = int(max(1, min(64, rec_depth))) + assert read in ("elbo", "chain") + assert not (read == "chain" and not rec_on), \ + "read=chain needs the recursion machinery (--recursion on)" + + # =================================================================== + # 1. Dataset -> device arrays (no goals sampled anywhere) + # =================================================================== + env, train_dataset, _ = make_env_and_datasets(env_id, + frame_stack=config["frame_stack"]) + obs_np = np.asarray(train_dataset["observations"], dtype=np.float32) + act_np = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1.0, 1.0) + end_np = build_ends(train_dataset["terminals"]) + tgt_np = target_extractors.extract_target(env_id, obs_np).astype(np.float32) + N = len(obs_np) + a_dim = act_np.shape[1] + n_bits = tgt_np.shape[1] + tgt_mu_np, tgt_sd_np = tgt_np.mean(0), tgt_np.std(0) + 1e-6 + + obs_d = jnp.asarray(obs_np) + act_d = jnp.asarray(act_np) + tgt_d = jnp.asarray(tgt_np) + end_d = jnp.asarray(end_np.astype(np.int32)) + tgt_mu_j, tgt_sd_j = jnp.asarray(tgt_mu_np), jnp.asarray(tgt_sd_np) + logg = float(np.log(GAMMA)) + + # =================================================================== + # 2. The goal-free occupancy p(z | s, a[, enc(gamma~)]) + # =================================================================== + # [obs, act] ONLY — no goal-z. With the spectrum on, the Fourier gamma + # encoding is appended (rsm.py's g_cols): the ONE extra conditioning axis + # is the discount, not a goal — the invariant that keeps this unconditional. + g_cols = 2 * FOURIER_K if spec_on else 0 + cond_dim = obs_np.shape[1] + a_dim + g_cols + occ_model = make_model(cond_dim, n_bits, OCC_HIDDEN, OCC_LAYERS, OCC_TIME_DIM) + key = jax.random.PRNGKey(seed) + key, ik = jax.random.split(key) + occ_params = occ_model.init(ik, jnp.zeros((1, n_bits)), jnp.zeros((1,)), + jnp.zeros((1, cond_dim))) + occ_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(OCC_LR)) + occ_opt = occ_tx.init(occ_params) + occ_ema = jax.tree_util.tree_map(lambda x: x, occ_params) + + abar_j = jnp.asarray(cosine_abar(OCC_T)) + + # ---- discount spectrum: Fourier features of the normalized log-horizon ---- + # EXACTLY rsm.py's g_enc: a raw gamma column cannot resolve a horizon that + # triples while gamma moves 0.04, so the encoding is sin/cos of the log + # horizon u(gamma~) rescaled to [gamma_spectrum_lo, GAMMA]. All gated off + # (g_cols=0, spec_on=False) for the exact v1. + lo_h = float(np.log(1.0 / (1.0 - gamma_spectrum_lo))) if spec_on else 0.0 + hi_h = float(np.log(1.0 / (1.0 - GAMMA))) + _fr_j = jnp.asarray((np.pi * (2.0 ** np.arange(FOURIER_K))).astype(np.float32)) + + def g_enc(dv): + u = (jnp.log(1.0 / (1.0 - dv)) - lo_h) / max(hi_h - lo_h, 1e-8) + ang = u[:, None] * _fr_j[None, :] + return jnp.concatenate([jnp.sin(ang), jnp.cos(ang)], -1) + + def _gammas(k, shape): + """gamma~ per tuple: task GAMMA w.p. 1-P, else a horizon-space draw.""" + if not spec_on: + return jnp.full(shape, GAMMA) + k1, k2 = jax.random.split(k) + h = jnp.exp(jax.random.uniform(k1, shape, minval=lo_h, maxval=hi_h)) + return jnp.where(jax.random.uniform(k2, shape) >= GAMMA_SPECTRUM_P, + GAMMA, 1.0 - 1.0 / h) + + # condition stats: [obs, act] moments are exact full-dataset; the Fourier + # gamma columns are bounded in [-1,1] so we standardize them with 0-mean / + # unit-scale (matches the sin/cos range; keeps the v1 stats byte-identical + # when spec is off). + cond_mean = jnp.concatenate( + [jnp.asarray(obs_np.mean(0)), jnp.asarray(act_np.mean(0))] + + ([jnp.zeros((g_cols,))] if spec_on else [])) + cond_std = jnp.concatenate( + [jnp.asarray(obs_np.std(0) + 1e-6), jnp.asarray(act_np.std(0) + 1e-6)] + + ([jnp.ones((g_cols,))] if spec_on else [])) + + def sample_occ_tuple(k): + """(s_t, a_t[, gamma~]) -> z_{t+k}, k ~ Geom(1-gamma~) truncated at + trajectory end. + + rsm.py's plain (not-in-trajectory-goal) branch; there is no goal, so no + reward-targeted stratification and all weights are 1 — a plain unbiased + MLE of the behavior occupancy. With the spectrum on, gamma~ is drawn + per row and the geometric horizon uses its log (so ONE model fits the + occupancy across the discount spectrum); the drawn gamma~ is Fourier- + encoded into the condition. With it off this is byte-identical to v1 + (gamma~ == GAMMA, logg constant, no extra columns, RNG stream is k1/k2 + only via the guarded split ordering).""" + if spec_on: + k1, k2, kg = jax.random.split(k, 3) + gam = _gammas(kg, (occ_batch,)) + else: + k1, k2 = jax.random.split(k) + gam = jnp.full((occ_batch,), GAMMA) + lgam = jnp.log(gam) + t = jax.random.randint(k1, (occ_batch,), 0, N) + L = (end_d[t] - t).astype(jnp.float32) + u = jax.random.uniform(k2, (occ_batch,), minval=1e-6, maxval=1.0 - 1e-6) + Fmax = jnp.maximum(1.0 - jnp.exp(L * lgam), 1e-12) + kh = jnp.clip(jnp.ceil(jnp.log1p(-u * Fmax) / lgam).astype(jnp.int32) - 1, + 0, (end_d[t] - t) - 1) + j = t + kh + parts = [obs_d[t], act_d[t]] + ([g_enc(gam)] if spec_on else []) + return jnp.concatenate(parts, axis=1), tgt_d[j], j + + def occ_step(params, opt_state, ema, k): + """One Gaussian eps-prediction diffusion MLE step (rsm.py continuous).""" + k1, k2, k3 = jax.random.split(k, 3) + cond_raw, z_data, _j = sample_occ_tuple(k1) + t_int = jax.random.randint(k2, (occ_batch,), 1, OCC_T + 1) + eps_n = jax.random.normal(k3, (occ_batch, n_bits)) + + def loss_fn(p): + c = (cond_raw - cond_mean) / cond_std + tf = t_int.astype(jnp.float32) / OCC_T + z0 = (z_data - tgt_mu_j) / tgt_sd_j + ab = abar_j[t_int - 1][:, None] + zt = jnp.sqrt(ab) * z0 + jnp.sqrt(1.0 - ab) * eps_n + pred = occ_model.apply(p, zt, tf, c) + return ((pred - eps_n) ** 2).mean() + + loss, grads = jax.value_and_grad(loss_fn)(params) + updates, opt_state = occ_tx.update(grads, opt_state, params) + params = optax.apply_updates(params, updates) + ema = jax.tree_util.tree_map(lambda e, p: e * (1 - OCC_TAU) + p * OCC_TAU, + ema, params) + return params, opt_state, ema, loss + + # =================================================================== + # 3. The goal-free BC prior pi(a | s) + # =================================================================== + # GCActor with goals=None degrades cleanly to a state-only Gaussian MLP + # (inputs = [observations]); reusing it keeps the eval action interface + # identical to the maintained scripts. + actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]), + action_dim=a_dim, state_dependent_std=False, + const_std=config["const_std"]) + key, ik2 = jax.random.split(key) + bc_params = actor_def.init(ik2, obs_np[:2])["params"] + bc_tx = optax.adam(learning_rate=config["lr"]) + bc_opt = bc_tx.init(bc_params) + + def bc_step(params, opt_state, k): + t = jax.random.randint(k, (B_pi,), 0, N) + + def loss_fn(p): + dist = actor_def.apply({"params": p}, obs_d[t]) + return -dist.log_prob(act_d[t]).mean() + + loss, grads = jax.value_and_grad(loss_fn)(params) + updates, opt_state = bc_tx.update(grads, opt_state, params) + return optax.apply_updates(params, updates), opt_state, loss + + # =================================================================== + # 3b. Completion head + occupancy sampler (recursion only) + # =================================================================== + # The chain hops through GENERATED states: the occupancy proposes the next + # reward-relevant coordinates z_mid (a beta-hop midpoint), the completion + # head (a small conditional Gaussian diffusion, co-trained on the same + # tuples with z teacher-forced) expands z_mid to a full observation, and the + # BC prior re-decides there. Goal-free throughout — nothing conditions on a + # goal. All of this is dead weight (never built / never dispatched) for the + # exact v1: cmpl_* only initialize when rec_on. + obs_dim = obs_np.shape[1] + obs_mu_j = jnp.asarray(obs_np.mean(0)) + obs_sd_j = jnp.asarray(obs_np.std(0) + 1e-6) + # 25-step deterministic DDIM schedule (occupancy z + completion sampling) + _ts_z = np.unique(np.linspace(OCC_T, 1, 25).round().astype(np.int32))[::-1].copy() + ts_z_now = jnp.asarray(_ts_z) + ts_z_nxt = jnp.asarray(np.concatenate([_ts_z[1:], [0]]).astype(np.int32)) + + def z_bits(ema, s, a, k, dv, m_wide): + """Deterministic DDIM sample of m_wide beta-hop midpoints z per row, + back in the raw z scale. Goal-free condition [s, a, enc(dv)].""" + parts = [s, a] + ([g_enc(dv)] if spec_on else []) + c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std + B2 = c.shape[0] + cc = jnp.repeat(c, m_wide, axis=0) + BM = B2 * m_wide + z = jax.random.normal(k, (BM, n_bits)) + + def stepf(z, i2): + tn, tx = ts_z_now[i2], ts_z_nxt[i2] + ab_n = abar_j[tn - 1] + ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0) + eps = jnp.clip(occ_model.apply( + ema, z, jnp.full((BM,), tn.astype(jnp.float32) / OCC_T), cc), + -6.0, 6.0) + z0h = (z - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8)) + return jnp.sqrt(ab_x) * z0h + jnp.sqrt(1.0 - ab_x) * eps, None + + z, _ = jax.lax.scan(stepf, z, jnp.arange(len(_ts_z))) + return (z * tgt_sd_j + tgt_mu_j).reshape(B2, m_wide, n_bits) + + # completion head: p(x_next | s, a[, enc(gamma~)], z_mid) -> full obs + _m_mu = jnp.concatenate([cond_mean, tgt_mu_j]) + _m_sd = jnp.concatenate([cond_std, tgt_sd_j]) + cmpl_model = make_model(cond_dim + n_bits, obs_dim, OCC_HIDDEN, OCC_LAYERS, + OCC_TIME_DIM) + if rec_on: + key, ik3 = jax.random.split(key) + cmpl_params = cmpl_model.init(ik3, jnp.zeros((1, obs_dim)), jnp.zeros((1,)), + jnp.zeros((1, cond_dim + n_bits))) + cmpl_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(OCC_LR)) + cmpl_opt = cmpl_tx.init(cmpl_params) + cmpl_ema = jax.tree_util.tree_map(lambda x: x, cmpl_params) + else: + cmpl_params = cmpl_opt = cmpl_ema = None + + def cmpl_step(cp, co, ce, k): + """One diffusion MLE step of the completion head on fresh occupancy + tuples (cond -> z teacher-forced -> full next obs).""" + k0, k1, k2 = jax.random.split(k, 3) + cond_raw, z_data, j = sample_occ_tuple(k0) + t_int = jax.random.randint(k1, (occ_batch,), 1, OCC_T + 1) + eps = jax.random.normal(k2, (occ_batch, obs_dim)) + c2 = (jnp.concatenate([cond_raw, z_data], -1) - _m_mu) / _m_sd + x0 = (obs_d[j] - obs_mu_j) / obs_sd_j + ab = abar_j[t_int - 1][:, None] + xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1.0 - ab) * eps + + def lf(pp): + pred = cmpl_model.apply(pp, xt, t_int.astype(jnp.float32) / OCC_T, c2) + return ((pred - eps) ** 2).mean() + + cl, gr = jax.value_and_grad(lf)(cp) + upd, co = cmpl_tx.update(gr, co, cp) + cp = optax.apply_updates(cp, upd) + ce = jax.tree_util.tree_map(lambda e, q: e * (1 - OCC_TAU) + q * OCC_TAU, + ce, cp) + return cp, co, ce, cl + + def mk_cond2(s, a, mids): + parts = [s, a] \ + + ([g_enc(jnp.full((s.shape[0],), hop_disc))] if spec_on else []) \ + + [mids] + return jnp.concatenate(parts, -1) + + def cmpl_sample(ce, cond2_raw, k): + """25-step DDIM sample of a full observation from the completion head.""" + c2 = (cond2_raw - _m_mu) / _m_sd + B2 = c2.shape[0] + x = jax.random.normal(k, (B2, obs_dim)) + + def stepf(x, i2): + tn, tx = ts_z_now[i2], ts_z_nxt[i2] + ab_n = abar_j[tn - 1] + ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0) + eps = jnp.clip(cmpl_model.apply( + ce, x, jnp.full((B2,), tn.astype(jnp.float32) / OCC_T), c2), + -6.0, 6.0) + x0h = (x - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8)) + return jnp.sqrt(ab_x) * x0h + jnp.sqrt(1.0 - ab_x) * eps, None + + x, _ = jax.lax.scan(stepf, x, jnp.arange(len(_ts_z))) + return x * obs_sd_j + obs_mu_j + + # =================================================================== + # 4. One fused training step + dispatch + # =================================================================== + def one_step(carry, _): + occ_p, occ_o, ema, bc_p, bc_o, cm_p, cm_o, cm_e, k = carry + if rec_on: + k, k1, k2, k3 = jax.random.split(k, 4) + else: + k, k1, k2 = jax.random.split(k, 3) + occ_p, occ_o, ema, occ_l = occ_step(occ_p, occ_o, ema, k1) + bc_p, bc_o, bc_l = bc_step(bc_p, bc_o, k2) + if rec_on: + cm_p, cm_o, cm_e, _cl = cmpl_step(cm_p, cm_o, cm_e, k3) + return (occ_p, occ_o, ema, bc_p, bc_o, cm_p, cm_o, cm_e, k), (occ_l, bc_l) + + dispatch = jax.jit( + lambda carry: jax.lax.scan(one_step, carry, None, length=STEPS_PER_DISPATCH)) + + # =================================================================== + # 5. Goal-free ELBO read-out + the density-penalized Q-filter policy + # =================================================================== + def q_elbo_gf(ema, s, a, gz, k, dv=None): + """rsm.py's q_elbo with the goal ABSENT from the condition: the + denoising loss at the TEST goal's z under p(z | s, a[, gamma~]); Q = + exp(-loss). K stratified timesteps; nothing sampled from the model. + `dv` is the discount to condition on when the spectrum is on (defaults + to GAMMA); ignored when the spectrum is off (v1 signature preserved).""" + parts = [s, a] + if spec_on: + dvv = jnp.full((s.shape[0],), GAMMA) if dv is None else dv + parts.append(g_enc(dvv)) + c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std + B = c.shape[0] + cc = jnp.repeat(c, ELBO_K, axis=0) + BO = B * ELBO_K + zg = jnp.repeat((gz - tgt_mu_j) / tgt_sd_j, ELBO_K, axis=0) + k1, k2 = jax.random.split(k) + u = jax.random.uniform(k1, (B, ELBO_K)) # stratified t: draw i covers + strat = (jnp.arange(ELBO_K)[None, :] + u) / ELBO_K # band i/K..(i+1)/K + t_int = jnp.clip((strat.reshape(-1) * OCC_T).astype(jnp.int32) + 1, 1, OCC_T) + eps = jax.random.normal(k2, (BO, n_bits)) + ab = abar_j[t_int - 1][:, None] + zt = jnp.sqrt(ab) * zg + jnp.sqrt(1.0 - ab) * eps + pred = occ_model.apply(ema, zt, t_int.astype(jnp.float32) / OCC_T, cc) + loss = ((pred - eps) ** 2).mean(-1).reshape(B, ELBO_K).mean(-1) + return jnp.exp(-loss) + + q_gf = jax.jit(q_elbo_gf) + mode_fn = jax.jit(lambda p, o: jnp.clip( + actor_def.apply({"params": p}, o).mode(), -1, 1)) + + def chain_prob_gf(ema, ce, bc_p, s0, a0, gz, k): + """The splitting-identity read-out (goal-free port of rsm.py chain_prob): + + Q_gamma(s,a;g) = (1-p) * q_beta(s,a;g) + p * E[ Q_gamma(next hop) ] + + run as a coin-terminated fixed-depth walk. Each level, alive rows flip + the p-coin: continuing rows sample ONE beta-horizon midpoint z_mid from + the goal-free occupancy, the completion head expands it to a full obs, + the BC prior re-decides there, and the walk moves; dead rows freeze. + The surviving node of every row is read at the goal z_g with the beta + (hop_disc) ELBO — one goal-free read. REC_CHAIN_M independent chains are + averaged for variance. No goal enters the chain; g enters ONLY as the + final ELBO evaluation point z_g. Expectation form — no max anywhere.""" + B0 = s0.shape[0] + # widen to M chains per row + s = jnp.repeat(s0, REC_CHAIN_M, axis=0) + a = jnp.repeat(a0, REC_CHAIN_M, axis=0) + gzr = jnp.repeat(gz, REC_CHAIN_M, axis=0) + B2 = s.shape[0] + dvh = jnp.full((B2,), hop_disc) + + def level(carry, _): + s_cur, a_cur, alive, kk = carry + kk, kc, ks_, kx = jax.random.split(kk, 4) + cont = alive & (jax.random.uniform(kc, (B2,)) < rec_p) + mids = z_bits(ema, s_cur, a_cur, ks_, dvh, 1)[:, 0, :] + x_new = cmpl_sample(ce, mk_cond2(s_cur, a_cur, mids), kx) + a_new = jnp.clip(actor_def.apply({"params": bc_p}, x_new).mode(), -1, 1) + s_cur = jnp.where(cont[:, None], x_new, s_cur) + a_cur = jnp.where(cont[:, None], a_new, a_cur) + return (s_cur, a_cur, cont, kk), None + + (s_f, a_f, _, k), _ = jax.lax.scan( + level, (s, a, jnp.ones((B2,), bool), k), None, length=rec_depth) + k, kg = jax.random.split(k) + q = q_elbo_gf(ema, s_f, a_f, gzr, kg, dvh) # (B2,) + return q.reshape(B0, REC_CHAIN_M).mean(-1) + + q_chain = jax.jit(chain_prob_gf) if rec_on else None + + def chain_q_single(ema, ce, bc_p, s, a, gz, k): + """chain_prob_gf for ONE (s,a,gz) row, returning a scalar composed Q. + + Pathwise-differentiable in `a`: `a` enters the first beta-hop midpoint + sample z_bits(...,s,a,...) and the surviving leaf read q_elbo_gf(...,a + of the un-hopped rows). The coins / DDIM noise / stratified-t key are + FIXED by `k` (rsm.py's actor-gradient pattern) so the composed surface + is deterministic in `a` — the gradient ascends a frozen chain. Used by + `--read chain --steer {grad,multistart}` so the ascent climbs the + recursively-COMPOSED Q, not the plain beta-ELBO (the owner's lever).""" + return chain_prob_gf(ema, ce, bc_p, s[None], a[None], gz[None], k)[0] + + def to_goal_z(goal_obs): + """TEST-TIME goal read: env goal observation -> reward-relevant z.""" + return target_extractors.extract_target( + env_id, np.asarray(goal_obs)).astype(np.float32) + + class _BCPolicy: + """Plain BC prior (K=1 anchor).""" + + def __init__(self, params): + self.params = params + + def sample_actions(self, observations, goals=None, seed=None, + temperature=0.0): + return np.asarray(mode_fn(self.params, jnp.asarray( + np.asarray(observations, dtype=np.float32)))) + + @partial(jax.jit, static_argnums=(6,)) + def grad_ascent(ema, s, a_init, a0, gz, k, n_steps, eta, lam): + """`--steer grad`: n_steps of clipped gradient ascent on + J(a) = log q_elbo_gf(s,a;gz) - lam/2 ||a - a0||^2, the SAME penalized + objective the filter argmaxes. J is pathwise differentiable in a (a + enters only the diffusion condition); k — the stratified-t/eps draw — + is FIXED across the whole ascent (rsm.py's actor-gradient key + pattern), so J is a deterministic surface. log q = -ELBO loss, so we + ascend -loss directly (identical to log(exp(-loss)), no clamp kink).""" + + def J(a): + q = q_elbo_gf(ema, s[None], a[None], gz[None], k)[0] + return jnp.log(q) - lam * ((a - a0) ** 2).sum() / 2.0 + + gJ = jax.grad(J) + + def body(a, _): + return jnp.clip(a + eta * gJ(a), -1.0, 1.0), None + + a_fin, _ = jax.lax.scan(body, a_init, None, length=n_steps) + return a_fin + + grad_ascent_batch = jax.vmap( + grad_ascent, in_axes=(None, None, 0, None, None, None, None, None, None)) + # ema s a_init a0 gz k n eta lam + # vmap over a_init ONLY: S starts ascended in parallel, SAME (s, a0, gz, k) + # so every start climbs the one deterministic penalized surface of this env + # step, anchored to the shared BC mode a0 (multistart / pi inner loop). + + @partial(jax.jit, static_argnums=(6,)) + def grad_ascent_traj(ema, s, a_init, a0, gz, k, n_steps, eta, lam): + """As grad_ascent, but return every iterate: the start plus each + post-step point -> (n_steps+1, a_dim). Used by `--steer softmax` + softmax_over_grad_traj so the softmax MEAN can average over all the + near-manifold points along each ascent, not only the S final ones. + Same fixed key -> the same deterministic penalized surface.""" + + def J(a): + q = q_elbo_gf(ema, s[None], a[None], gz[None], k)[0] + return jnp.log(q) - lam * ((a - a0) ** 2).sum() / 2.0 + + gJ = jax.grad(J) + + def body(a, _): + a_next = jnp.clip(a + eta * gJ(a), -1.0, 1.0) + return a_next, a_next + + _, steps = jax.lax.scan(body, a_init, None, length=n_steps) + return jnp.concatenate([a_init[None], steps], axis=0) + + grad_ascent_traj_batch = jax.vmap( + grad_ascent_traj, + in_axes=(None, None, 0, None, None, None, None, None, None)) + + # ---- chain-Q gradient ascent (the owner's #65 lever) -------------------- + # When read=chain the ascent objective is the recursively-COMPOSED Q, not + # the plain beta-ELBO: grad-ascend log chain_q_single(s,a;gz) - penalty. + # The chain integrates a longer effective horizon (rec_depth beta-hops), so + # its action-gradient is expected sharper than the single-read ELBO. cm_e is + # the completion-head EMA (needed to expand hop midpoints); bc_p the BC prior + # that re-decides each hop. Same fixed key -> deterministic composed surface. + if rec_on: + @partial(jax.jit, static_argnums=(8,)) + def grad_ascent_chain(ema, ce, bc_p, s, a_init, a0, gz, k, n_steps, + eta, lam): + def J(a): + q = chain_q_single(ema, ce, bc_p, s, a, gz, k) + return jnp.log(jnp.maximum(q, 1e-9)) \ + - lam * ((a - a0) ** 2).sum() / 2.0 + + gJ = jax.grad(J) + + def body(a, _): + return jnp.clip(a + eta * gJ(a), -1.0, 1.0), None + + a_fin, _ = jax.lax.scan(body, a_init, None, length=n_steps) + return a_fin + + grad_ascent_chain_batch = jax.vmap( + grad_ascent_chain, + in_axes=(None, None, None, None, 0, None, None, None, None, None, + None)) + # ema ce bc_p s a_in a0 gz k n eta lam + else: + grad_ascent_chain = grad_ascent_chain_batch = None + + def penalized_score_np(q_np, cand, a0, lam): + """log q - lam/2 ||a - a0||^2 for a batch of candidates (host side).""" + return np.log(np.maximum(q_np, 1e-9)) - lam * ((cand - a0[None]) ** 2).sum(-1) / 2.0 + + class _SteerGF: + """Test-time steering over the goal-free read-out (#65 ladder). + + Every mode optimizes the SAME density-penalized score + score(a) = log q_elbo_gf(s,a;g_z) - lam * ||a - a0||^2 / 2, + anchor a0 = BC mode (the optimizer's-curse fix; never dropped): + filter argmax over K = a0 + PLAN_SIGMA*N(0,1) candidates (a0 + first) — RNG-stream-exact the original _QFilterGF. + cem cem_rounds rounds; round 0 = the filter candidates, then + refit a diagonal Gaussian on the top-cem_elites (std + floored), resample K; action = best score ever seen. + grad grad_n ascent steps on score from a0. + grad_cem cem winner, then grad_n ascent steps. + multistart n_start starts ~ BC prior, grad-ascend EACH grad_n steps + (shared BC-mode anchor), execute the best-scoring one. + softmax multistart candidates, but EXECUTE the softmax-weighted + MEAN action (w_i = softmax(score_i / softmax_temp)) — + expectation-form selection, not argmax. Optionally + (softmax_over_grad_traj) average over every grad iterate. + pi pi_rounds of {sample pi_k from the current proposal, + grad-step the round's best, refit the proposal around it} + — policy iteration in action space inside the trust + region; execute the best-scoring action ever seen. + ONE stratified-t key per env step serves every score/gradient in the + step (scores comparable across rounds; ascent surface deterministic). + The goal enters ONLY through gz, the ELBO evaluation point. + Tracks mean ||a_executed - a0|| (how far steering leaves the BC mode).""" + + def __init__(self, bc_p, ema, k, mode="filter", cm_e=None, read="elbo"): + self.bc_p, self.ema, self.k, self.mode = bc_p, ema, k, mode + self.cm_e, self.read = cm_e, read + self.lam = float(grad_lam) + self.rng = np.random.default_rng(seed + 4242) + self.key = jax.random.PRNGKey(seed + 999) + self.disp_sum, self.disp_n = 0.0, 0 + + def _q(self, obs_rep, cand, gz_rep, sub): + """Selection-time Q for a batch of candidates. read=elbo is the + plain gamma-conditioned ELBO; read=chain is the recursively-composed + occupancy (the coin-gated beta-hop chain). Used for SELECTION over + candidates in every mode. When read=chain the gradient ascent ALSO + differentiates the composed chain (see _ascend_*), so the ascended + candidates already climbed the same recursive surface they are + selected on — the owner's '#65 gradient ascent on the recursively- + composed Q' lever.""" + if self.read == "chain": + return np.asarray(q_chain(self.ema, self.cm_e, self.bc_p, + obs_rep, cand, gz_rep, sub)) + return np.asarray(q_gf(self.ema, obs_rep, cand, gz_rep, sub)) + + def _ascend_single(self, obs, a_init, a0, gz, sub): + """Grad-ascend ONE action. read=chain climbs the recursively- + composed Q (grad_ascent_chain, longer effective horizon); read=elbo + climbs the plain gamma-ELBO (grad_ascent). Same fixed key `sub`.""" + if self.read == "chain": + return np.asarray(grad_ascent_chain( + self.ema, self.cm_e, self.bc_p, jnp.asarray(obs), + jnp.asarray(a_init), jnp.asarray(a0), jnp.asarray(gz), sub, + grad_n, grad_eta, self.lam)) + return np.asarray(grad_ascent( + self.ema, jnp.asarray(obs), jnp.asarray(a_init), + jnp.asarray(a0), jnp.asarray(gz), sub, grad_n, grad_eta, + self.lam)) + + def _ascend_batch(self, obs, starts, a0, gz, sub): + """Grad-ascend S starts in parallel (multistart). Chain or ELBO + objective per self.read; shared BC-mode anchor a0, one fixed key.""" + if self.read == "chain": + return np.asarray(grad_ascent_chain_batch( + self.ema, self.cm_e, self.bc_p, jnp.asarray(obs), + jnp.asarray(starts), jnp.asarray(a0), jnp.asarray(gz), sub, + grad_n, grad_eta, self.lam)) + return np.asarray(grad_ascent_batch( + self.ema, jnp.asarray(obs), jnp.asarray(starts), + jnp.asarray(a0), jnp.asarray(gz), sub, grad_n, grad_eta, + self.lam)) + + def _score(self, obs, cand, gz, a0, sub): + m = cand.shape[0] # score however many candidates are passed (pi + # uses a variable count; filter/cem use self.k) + q = self._q(jnp.repeat(jnp.asarray(obs)[None], m, axis=0), + jnp.asarray(cand), + jnp.repeat(jnp.asarray(gz)[None], m, axis=0), sub) + return np.log(np.maximum(q, 1e-9)) \ + - self.lam * ((cand - a0[None]) ** 2).sum(-1) / 2.0 + + def sample_actions(self, observations, goals=None, seed=None, + temperature=0.0): + obs = np.asarray(observations, dtype=np.float32) + gz = to_goal_z(goals) + a0 = np.asarray(mode_fn(self.bc_p, jnp.asarray(obs))) + self.key, sub = jax.random.split(self.key) # ONE key per env step + a = a0 + if self.mode in ("filter", "cem", "grad_cem"): + rounds = 1 if self.mode == "filter" else cem_rounds + cand = a0[None] + PLAN_SIGMA * self.rng.standard_normal( + (self.k, a_dim)).astype(np.float32) + cand[0] = a0 + cand = np.clip(cand, -1, 1) + best_s = -np.inf + for r in range(rounds): + if r > 0: + mu = elites.mean(0) + sd = np.maximum(elites.std(0), cem_std_floor) + cand = np.clip(mu[None] + sd[None] + * self.rng.standard_normal( + (self.k, a_dim)).astype(np.float32), + -1.0, 1.0) + score = self._score(obs, cand, gz, a0, sub) + order = np.argsort(-score) + elites = cand[order[:cem_elites]] + if score[order[0]] > best_s: + best_s, a = float(score[order[0]]), cand[order[0]] + if self.mode in ("grad", "grad_cem"): + a = self._ascend_single(obs, a, a0, gz, sub) + if self.mode == "multistart": + # S starts ~ BC prior (start 0 = a0), grad-ascend EACH under the + # SHARED BC-mode anchor, execute the best penalized score. Each + # climb stays local (optimizer's-curse fix) while spending ~S x. + # read=chain -> ascend the recursively-composed Q (the owner's + # lever); the final SELECTION also re-scores with the chain. + starts = a0[None] + PLAN_SIGMA * self.rng.standard_normal( + (n_start, a_dim)).astype(np.float32) + starts[0] = a0 + starts = np.clip(starts, -1, 1) + asc = self._ascend_batch(obs, starts, a0, gz, sub) + q = self._q(jnp.repeat(jnp.asarray(obs)[None], n_start, axis=0), + jnp.asarray(asc), + jnp.repeat(jnp.asarray(gz)[None], n_start, axis=0), sub) + sc = penalized_score_np(q, asc, a0, self.lam) + a = asc[int(np.argmax(sc))] + if self.mode == "softmax": + # EXPECTATION-form test-time selection (the campaign's core + # "expectation beats max" move, applied to action selection). + # Generate candidates the multistart way: S starts ~ BC prior + # (start 0 = a0), grad-ascend EACH under the shared BC-mode + # anchor. Then, instead of argmax penalized-Q, execute the + # SOFTMAX-WEIGHTED MEAN action a_exec = sum_i w_i a_i, + # w_i = softmax(score_i / temp), score = penalized log-q. This + # averages a set of near-manifold high-Q candidates rather than + # committing to the single noisiest argmax (the optimizer's + # curse). softmax_over_grad_traj widens the candidate pool to + # every intermediate grad iterate (all penalty-kept near the + # data manifold), so the weighted mean draws on more points. + starts = a0[None] + PLAN_SIGMA * self.rng.standard_normal( + (n_start, a_dim)).astype(np.float32) + starts[0] = a0 + starts = np.clip(starts, -1, 1) + if softmax_over_grad_traj: + traj = np.asarray(grad_ascent_traj_batch( + self.ema, jnp.asarray(obs), jnp.asarray(starts), + jnp.asarray(a0), jnp.asarray(gz), sub, + grad_n, grad_eta, self.lam)) # (S, n+1, a_dim) + cand = traj.reshape(-1, a_dim) # (S*(n+1), a_dim) + else: + cand = np.asarray(grad_ascent_batch( + self.ema, jnp.asarray(obs), jnp.asarray(starts), + jnp.asarray(a0), jnp.asarray(gz), sub, + grad_n, grad_eta, self.lam)) # (S, a_dim) + m = cand.shape[0] + q = self._q(jnp.repeat(jnp.asarray(obs)[None], m, axis=0), + jnp.asarray(cand), + jnp.repeat(jnp.asarray(gz)[None], m, axis=0), sub) + sc = penalized_score_np(q, cand, a0, self.lam) + w = sc / max(softmax_temp, 1e-6) + w = np.exp(w - w.max()) + w = w / w.sum() + a = np.clip((w[:, None] * cand).sum(0), -1, 1).astype(np.float32) + if self.mode == "pi": + # Test-time policy iteration in action space: refit a proposal + # Gaussian around a grad-improved elite each round, all anchored + # to the fixed BC mode a0 (trust region never moves). + mu, sd = a0.copy(), np.full(a_dim, PLAN_SIGMA, dtype=np.float32) + best_s, best_a = -np.inf, a0 + for r in range(pi_rounds): + cand = mu[None] + sd[None] * self.rng.standard_normal( + (pi_k, a_dim)).astype(np.float32) + if r == 0: + cand[0] = a0 + cand = np.clip(cand, -1, 1) + sc = self._score(obs, cand, gz, a0, sub) + order = np.argsort(-sc) + # grad-improve the round's best candidate, then re-score it + top = cand[order[0]] + imp = np.asarray(grad_ascent( + self.ema, jnp.asarray(obs), jnp.asarray(top), + jnp.asarray(a0), jnp.asarray(gz), sub, + pi_grad_n, grad_eta, self.lam)) + imp_s = self._score(obs, imp[None], gz, a0, sub)[0] + if imp_s > sc[order[0]]: + cand = np.concatenate([cand, imp[None]], 0) + sc = np.append(sc, imp_s) + order = np.argsort(-sc) + if sc[order[0]] > best_s: + best_s, best_a = float(sc[order[0]]), cand[order[0]] + # refit the proposal on the penalized elites (trust region + # anchored to a0: mean can drift but std is floored) + elites = cand[order[:pi_elites]] + mu = elites.mean(0) + sd = np.maximum(elites.std(0), pi_std_floor) + a = best_a + self.disp_sum += float(np.linalg.norm(a - a0)) + self.disp_n += 1 + return a + + def mean_disp(self): + return self.disp_sum / max(self.disp_n, 1) + + # =================================================================== + # 6. Train (or reload) -> save -> Q-filter eval + # =================================================================== + # ---- steering config (test-time only; recorded everywhere) ---- + steer_cfg = {} + if steer is not None: + steer_cfg = {"steer": steer, "lam": float(grad_lam)} + if read == "chain": # composed-Q read-out: record the chain depth used + # (read is already carried by the wandb config + output JSON, so + # only rec_depth is added here to avoid a duplicate keyword) + steer_cfg.update(rec_depth=rec_depth) + if steer in ("grad", "grad_cem", "multistart"): + steer_cfg.update(grad_n=grad_n, grad_eta=grad_eta) + if steer in ("cem", "grad_cem"): + steer_cfg.update(cem_rounds=cem_rounds, cem_elites=cem_elites, + cem_std_floor=cem_std_floor) + if steer == "multistart": + steer_cfg.update(n_start=n_start) + if steer == "softmax": + steer_cfg.update(grad_n=grad_n, grad_eta=grad_eta, n_start=n_start, + softmax_temp=softmax_temp, + softmax_over_grad_traj=softmax_over_grad_traj) + if steer == "pi": + steer_cfg.update(pi_rounds=pi_rounds, pi_k=pi_k, pi_elites=pi_elites, + pi_grad_n=pi_grad_n, pi_std_floor=pi_std_floor, + grad_eta=grad_eta) + steer_tag = "" if steer is None else "-" + "-".join( + str(v) for v in steer_cfg.values()) + + run = wandb.init(project="gen-q-policy-improvement", + name=f"rsm_goalfree{steer_tag}-{env_id}-s{seed}", + mode=wandb_mode, + tags=["rsm_goalfree", env_id] + + (["steer", steer] if steer else []), + config=dict(method="rsm_goalfree", env=env_id, seed=seed, + gamma=GAMMA, plan_k=plan_k, + plan_sigma=PLAN_SIGMA, plan_bc=PLAN_BC, + elbo_K=ELBO_K, batch_size=B_pi, + occ_batch=occ_batch, train_steps=train_steps, + recursion=recursion, + gamma_spectrum_lo=gamma_spectrum_lo, + rec_beta=rec_beta, read=read, + **steer_cfg), + settings=wandb.Settings(start_method="thread")) + print(f"[gf] WANDB_URL {run.get_url()}", flush=True) + + if load_ckpt: + with open(load_ckpt, "rb") as f: + blob = pickle.load(f) + occ_ema = jax.device_put(blob["occ_ema"]) + bc_params = jax.device_put(blob["bc_params"]) + if rec_on and blob.get("cmpl_ema") is not None: + cmpl_ema = jax.device_put(blob["cmpl_ema"]) + train_steps = int(blob.get("train_steps", train_steps)) + print(f"[gf] reloaded occupancy EMA + BC prior" + f"{' + completion head' if rec_on else ''} from {load_ckpt}", + flush=True) + else: + assert train_steps % STEPS_PER_DISPATCH == 0 + carry = (occ_params, occ_opt, occ_ema, bc_params, bc_opt, + cmpl_params, cmpl_opt, cmpl_ema, key) + n_disp = train_steps // STEPS_PER_DISPATCH + tw = time.time() + for di in tqdm.trange(1, n_disp + 1, smoothing=0.05, dynamic_ncols=True): + carry, (occ_ls, bc_ls) = dispatch(carry) + i = di * STEPS_PER_DISPATCH + if di == 3: + jax.block_until_ready(carry[0]) + rate = 3 * STEPS_PER_DISPATCH / (time.time() - tw) + print(f"[gf] throughput ~{rate:.1f} steps/s " + f"({train_steps / rate / 3600:.1f} h for {train_steps})", + flush=True) + if i % 1000 == 0 or di == 1 or di == n_disp: + ol, bl = float(occ_ls.mean()), float(bc_ls.mean()) + wandb.log({"occ/loss": ol, "bc/loss": bl}, step=i) + if di == 1 or di == n_disp: + print(f"[gf] step {i} occ_loss={ol:.4f} bc_loss={bl:.4f}", + flush=True) + occ_ema, bc_params, cmpl_ema = carry[2], carry[3], carry[7] + + if save_ckpt: + os.makedirs(os.path.dirname(os.path.abspath(save_ckpt)), exist_ok=True) + with open(save_ckpt, "wb") as f: + pickle.dump({"occ_ema": jax.device_get(occ_ema), + "bc_params": jax.device_get(bc_params), + "cmpl_ema": (jax.device_get(cmpl_ema) + if rec_on else None), + "cond_mean": np.asarray(cond_mean), + "cond_std": np.asarray(cond_std), + "tgt_mu": tgt_mu_np, "tgt_sd": tgt_sd_np, + "config": dict(config), "env": env_id, "seed": seed, + "train_steps": train_steps, + "recursion": recursion, + "gamma_spectrum_lo": gamma_spectrum_lo, + "rec_beta": rec_beta, + "constants": dict(gamma=GAMMA, occ_hidden=OCC_HIDDEN, + occ_layers=OCC_LAYERS, + occ_time_dim=OCC_TIME_DIM, + occ_T=OCC_T, elbo_K=ELBO_K, + plan_sigma=PLAN_SIGMA, + plan_bc=PLAN_BC)}, f) + print(f"[gf] occupancy+BC" + f"{'+completion' if rec_on else ''} snapshot -> {save_ckpt}", + flush=True) + + # ---- official eval: K=1 BC anchor, then the K=plan_k Q-filter ---- + task_infos = env.unwrapped.task_infos if hasattr(env.unwrapped, "task_infos") \ + else env.task_infos + n_tasks = len(task_infos) if max_tasks <= 0 else min(max_tasks, len(task_infos)) + + def eval_policy(policy, tag): + per, te = [], time.time() + for tid in range(1, n_tasks + 1): + ei, _, _ = evaluate(agent=policy, env=env, task_id=tid, config=config, + num_eval_episodes=episodes, num_video_episodes=0, + video_frame_skip=3, eval_temperature=0.0, + eval_gaussian=None) + per.append(float(ei.get("success", 0.0))) + spe = (time.time() - te) / (n_tasks * episodes) + sr = float(np.mean(per)) + print(f"[gf] {tag}: sr={sr:.3f} per-task={[round(p, 3) for p in per]} " + f"({spe:.2f} s/episode)", flush=True) + return sr, per, spe + + if steer is None: + # -------- original behavior: BC anchor + filter -> rsm_goalfree.json + sr_bc, per_bc, spe_bc = eval_policy(_BCPolicy(bc_params), "K=1 BC anchor") + sr, per, spe = eval_policy( + _SteerGF(bc_params, occ_ema, plan_k, "filter", + cm_e=cmpl_ema if rec_on else None, read=read), + f"K={plan_k} Q-filter") + wandb.log({"eval/success_rate": sr, "eval/success_rate_bc": sr_bc, + "eval/s_per_episode": spe}, step=train_steps) + + out = os.path.join(_result_dir(env_id, seed), "rsm_goalfree.json") + json.dump({"method": "rsm_goalfree", "env": env_id, "seed": seed, + "success_rate": sr, "per_task": per, "s_per_episode": round(spe, 3), + "bc_success_rate": sr_bc, "bc_per_task": per_bc, + "bc_s_per_episode": round(spe_bc, 3), + "K": plan_k, "plan_sigma": PLAN_SIGMA, "plan_bc": PLAN_BC, + "elbo_K": ELBO_K, "gamma": GAMMA, "episodes": episodes, + "n_tasks": n_tasks, "train_steps": train_steps, + "batch_size": B_pi, "occ_batch": occ_batch, + "recursion": recursion, "gamma_spectrum_lo": gamma_spectrum_lo, + "rec_beta": rec_beta, "read": read, + "goal_in_training": False, + "wall_clock_sec": round(time.time() - t0, 1), + "wandb_url": run.get_url()}, open(out, "w"), indent=2) + print(f"[gf] {env_id} FINAL sr={sr:.3f} (BC anchor {sr_bc:.3f}) -> {out}", + flush=True) + else: + # -------- steered eval: ONE config -> append to {steer_out} + pol = _SteerGF(bc_params, occ_ema, plan_k, steer, + cm_e=cmpl_ema if rec_on else None, read=read) + tag = " ".join(f"{kk}={vv}" for kk, vv in steer_cfg.items()) + sr, per, spe = eval_policy(pol, tag) + disp = pol.mean_disp() + print(f"[gf] {tag}: mean ||a_exec - a0|| = {disp:.4f}", flush=True) + wandb.log({"eval/success_rate": sr, "eval/s_per_episode": spe, + "eval/mean_disp": disp}, step=train_steps) + + out = os.path.join(_result_dir(env_id, seed), steer_out) + entries = json.load(open(out)) if os.path.exists(out) else [] + entries.append({"method": "rsm_goalfree", "env": env_id, "seed": seed, + **steer_cfg, + "success_rate": sr, "per_task": per, + "s_per_episode": round(spe, 3), + "mean_disp": round(disp, 4), + "K": plan_k, "plan_sigma": PLAN_SIGMA, + "elbo_K": ELBO_K, "gamma": GAMMA, "episodes": episodes, + "n_tasks": n_tasks, "train_steps": train_steps, + "recursion": recursion, + "gamma_spectrum_lo": gamma_spectrum_lo, + "rec_beta": rec_beta, "read": read, + "rec_depth": (rec_depth if read == "chain" else None), + "config": dict(steer_cfg), + "ckpt": load_ckpt, "goal_in_training": False, + "wall_clock_sec": round(time.time() - t0, 1), + "wandb_url": run.get_url()}) + json.dump(entries, open(out, "w"), indent=2) + print(f"[gf] {env_id} STEER {tag} sr={sr:.3f} disp={disp:.4f} -> {out}", + flush=True) + wandb.finish() + return out + + +def main(): + import argparse + ap = argparse.ArgumentParser( + description="RSM-GF: goal-free occupancy + goal-free BC prior; goal " + "enters ONLY at test time as the ELBO evaluation point of " + "a density-penalized Q-filter (LeWM fairness variant, #65).") + ap.add_argument("--env", required=True, help="OGBench env id (continuous target)") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=500000) + ap.add_argument("--plan_k", type=int, default=32, + help="Q-filter candidate count (1 = plain BC everywhere)") + # ---- recursion + gamma-spectrum (rsm.py port; #65 unconditional RSM) ---- + ap.add_argument("--recursion", default="off", choices=["off", "on"], + help="off (default) = exact v1 (single gamma, no spectrum, " + "no completion head). on = gamma-spectrum-conditioned " + "goal-free occupancy + co-trained completion head + " + "recursive read-out available") + ap.add_argument("--gamma_spectrum_lo", type=float, default=None, + help="discount-spectrum lower edge (default 0.95 when " + "--recursion on, 0 otherwise = no spectrum)") + ap.add_argument("--rec_beta", type=float, default=0.98, + help="beta-hop discount for the recursion chain") + ap.add_argument("--read", default="elbo", choices=["elbo", "chain"], + help="test-time Q read-out: elbo (plain gamma-conditioned " + "ELBO at z_g) or chain (recursively-composed occupancy; " + "needs --recursion on)") + ap.add_argument("--rec_depth", type=int, default=REC_MAX_DEPTH, + help="number of coin-gated beta-hop composition hops in the " + "chain read-out (more hops = longer effective horizon; " + "read=chain only). Grad ascent with read=chain also " + "differentiates through this many hops. Default " + f"{REC_MAX_DEPTH}; clamped to [1,64].") + ap.add_argument("--batch_size", type=int, default=4096, help="BC batch") + ap.add_argument("--occ_batch", type=int, default=2048) + ap.add_argument("--episodes", type=int, default=50, help="episodes per task") + ap.add_argument("--max_tasks", type=int, default=0, + help="evaluate only the first N tasks (0 = all; smoke aid)") + ap.add_argument("--save_ckpt", default=None, + help="save the occupancy-EMA + BC pkl here after training") + ap.add_argument("--load_ckpt", default=None, + help="skip training; reload a saved pkl and eval only") + ap.add_argument("--steer", default=None, + choices=["filter", "grad", "cem", "grad_cem", + "multistart", "pi", "softmax"], + help="test-time steering mode (#65); omit for the " + "original BC-anchor + filter eval") + ap.add_argument("--grad_n", type=int, default=16, + help="gradient-ascent steps per env step " + "(grad/grad_cem/multistart; up to 64)") + ap.add_argument("--grad_eta", type=float, default=0.02, + help="gradient-ascent step size (grad/multistart/pi)") + ap.add_argument("--grad_lam", type=float, default=PLAN_BC, + help="density-penalty lambda for ALL steer scores " + "(default: the documented PLAN_BC fix; do not drop)") + ap.add_argument("--cem_rounds", type=int, default=2, + help="CEM rounds incl. the filter round 0 (cem/grad_cem)") + ap.add_argument("--cem_elites", type=int, default=8) + ap.add_argument("--cem_std_floor", type=float, default=0.05) + # ---- higher-compute modes (#65 test-time-compute sweep) ---- + ap.add_argument("--n_start", type=int, default=8, + help="multistart/softmax: number of BC-prior starts to " + "grad-ascend") + ap.add_argument("--softmax_temp", type=float, default=0.1, + help="softmax: temperature for the Boltzmann action-mean " + "weight w_i = softmax(penalized_score_i / temp); " + "sharp (->argmax) as temp->0, soft (->uniform mean) " + "as temp->inf") + ap.add_argument("--softmax_over_grad_traj", action="store_true", + help="softmax: weight ALL intermediate grad-ascent iterates " + "(S*(grad_n+1) candidates), not just the S final ones") + ap.add_argument("--pi_rounds", type=int, default=3, + help="pi: rounds of action-space policy iteration") + ap.add_argument("--pi_k", type=int, default=32, + help="pi: candidates sampled from the proposal per round") + ap.add_argument("--pi_elites", type=int, default=8, + help="pi: top-e penalized elites the proposal refits on") + ap.add_argument("--pi_grad_n", type=int, default=4, + help="pi: grad steps on the round's best candidate") + ap.add_argument("--pi_std_floor", type=float, default=0.05, + help="pi: proposal std floor (keeps the trust region open)") + ap.add_argument("--steer_out", default="rsm_uncond_steer.json", + help="results/{seed}/ filename steered entries append to") + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + # spectrum default: 0.95 when recursion is on, 0 (off) otherwise + spec_lo = a.gamma_spectrum_lo if a.gamma_spectrum_lo is not None else \ + (0.95 if a.recursion == "on" else 0.0) + run_rsm_goalfree(a.env, seed=a.seed, train_steps=a.train_steps, + plan_k=a.plan_k, + recursion=a.recursion, gamma_spectrum_lo=spec_lo, + rec_beta=a.rec_beta, rec_depth=a.rec_depth, read=a.read, + batch_size=a.batch_size, + occ_batch=a.occ_batch, episodes=a.episodes, + max_tasks=a.max_tasks, save_ckpt=a.save_ckpt, + load_ckpt=a.load_ckpt, steer=a.steer, grad_n=a.grad_n, + grad_eta=a.grad_eta, grad_lam=a.grad_lam, + cem_rounds=a.cem_rounds, cem_elites=a.cem_elites, + cem_std_floor=a.cem_std_floor, + n_start=a.n_start, pi_rounds=a.pi_rounds, pi_k=a.pi_k, + pi_elites=a.pi_elites, pi_grad_n=a.pi_grad_n, + pi_std_floor=a.pi_std_floor, + softmax_temp=a.softmax_temp, + softmax_over_grad_traj=a.softmax_over_grad_traj, + steer_out=a.steer_out, wandb_mode=a.wandb_mode) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/rsm_recipe.py b/gen_q_rsm/ogbench_genq/rsm_recipe.py new file mode 100644 index 0000000000000000000000000000000000000000..c70ba803ecbddae1442cf77f86d576e9ca1cdacc --- /dev/null +++ b/gen_q_rsm/ogbench_genq/rsm_recipe.py @@ -0,0 +1,227 @@ +"""RSM — the single recipe. + +One occupancy model, one DDPG+BC actor, no critic / no TD / no max. This module +is the *one clean entry point*: it resolves the settled recipe from the +environment and delegates to the validated engine in ``rsm.py`` (``run_rsm``). +Nothing here re-derives the math — it fixes the one recipe and hides the ~40 +experimental flags that ``rsm.py`` still carries for ablations. + +THE RECIPE (shared core, everywhere) +------------------------------------ +* Occupancy = a conditional generative model of the discounted future-state + occupancy, trained by maximum likelihood on geometric-horizon (s,a)->s_{t+k} + pairs. No reward, no bootstrap in the fit. +* Q is a *read-out* (an expectation under the occupancy at the goal), so reward + enters only at read-out time. +* Actor = deterministic policy trained by anchored gradient ascent through the + read-out (DDPG+BC). No critic network, no target copies, no max. +* Settled constants: gamma 0.99, EMA tau 0.005, Fourier gamma-spectrum, + beta 0.98 recursion. + +The one part that is NOT yet unified is the *read-out*, which auto-resolves from +the observation/goal space (see ``resolve_recipe``): + + state, discrete goals (puzzle-*) -> exact ``gl`` likelihood + + differentiated recursion, alpha 1.0 + state, continuous goals (mazes) -> diffusion ``elbo`` read-out + + no recursion, alpha 0.03 + visual (pixels) -> goal-relative reader-metric flow in a + FROZEN reward-predictive latent, + one-hop, alpha 1.0 (fair, pixels-only) + +Run +--- + python -m ogbench_genq.rsm_recipe --env puzzle-3x3-play-v0 --seed 0 + python -m ogbench_genq.rsm_recipe --env pointmaze-medium-navigate-v0 --seed 0 + python -m ogbench_genq.rsm_recipe --env visual-cube-single-play-v0 --seed 0 \ + --latent_npz --pixel_encoder \ + --reward_decoder + +Merge/acceptance bar: this single recipe must beat the GCIQL baseline on +puzzle-3x3, pointmaze-medium, and visual-cube-single (official 50-episode eval). +See RECIPE.md. +""" +from __future__ import annotations + +import argparse +import os + +from ogbench_genq.rsm import run_rsm, file_sha256 + + +# --------------------------------------------------------------------------- # +# The three settled configurations. Only the read-out block differs; the core +# (DDPG+BC actor, gamma-spectrum occupancy, beta 0.98) is shared via run_rsm's +# settled defaults. +# --------------------------------------------------------------------------- # +def _is_visual(env_id: str) -> bool: + return env_id.startswith("visual-") + + +def _is_discrete(env_id: str) -> bool: + return env_id.startswith("puzzle") + + +# Frozen stage-1 visual artifacts (reward-predictive latent encoder + precomputed +# latents + reader-metric diagonal index reader). Named per env; override the +# directory with RSM_VISUAL_CKPT_DIR and the rendered-pixel dataset root with +# RSM_OGBENCH_DATA. +_VISUAL_CKPT_DIR = os.environ.get( + "RSM_VISUAL_CKPT_DIR", + "/proj/dmfexp/zwhong/projs/gen_q/.claude/worktrees/" + "ogbench-pixel-validation/ckpt", +) +_OGBENCH_DATA = os.environ.get( + "RSM_OGBENCH_DATA", os.path.expanduser("~/.ogbench/data")) + + +def _env_safe(env_id: str) -> str: + return env_id.replace("-", "_") + + +def visual_artifacts(env_id: str, args) -> dict: + """Resolve the frozen stage-1 artifacts + rendered-pixel dataset for an env. + + CLI values win; otherwise derive the standard per-env filenames. + """ + safe = _env_safe(env_id) + d = _VISUAL_CKPT_DIR + return dict( + pixel_encoder=args.pixel_encoder + or os.path.join(d, f"valenc_{safe}.npz"), + latent_npz=args.latent_npz + or os.path.join(d, f"vallat_{safe}.npz"), + reward_decoder=args.reward_decoder + or os.path.join(d, f"valrdec_diag_{safe}.npz"), + pixel_dataset=args.pixel_dataset + or os.path.join(_OGBENCH_DATA, f"{env_id}.npz"), + ) + + +def resolve_recipe(env_id: str, args) -> dict: + """Map an env id to the settled run_rsm kwargs for THE recipe.""" + if _is_visual(env_id): + # Fair, pixels-only reader-metric flow. Occupancy is a conditional flow + # over the goal-relative reader-metric coordinate in a FROZEN + # reward-predictive latent; read-out is the reader-metric density at the + # goal. One-hop (recursion off won the official visual comparison). + art = visual_artifacts(env_id, args) + + # The strict pixels-only contract pins every frozen input by an + # immutable SHA-256; auto-compute from the resolved files. + def _sha(path): + return file_sha256(path) if path and os.path.isfile(path) else None + + pixel_dataset_sha256 = args.pixel_dataset_sha256 or _sha( + art["pixel_dataset"]) + latent_npz_sha256 = _sha(art["latent_npz"]) + pixel_encoder_sha256 = _sha(art["pixel_encoder"]) + return dict( + occupancy_model="flow", + occ_hidden=256, occ_layers=4, flow_steps=25, + # The reader-metric mechanism IS the goal-relative target transform + # (u = sqrt(w)/s * (z_future - z_goal)), fed by the frozen index + # reader (reward_decoder). It pairs with the reward-metric endpoint + # sampler (50% task gamma / 25% beta / 25% aux, sqrt-h priority over + # horizons 8/16/32/64) and an encoded discount spectrum down to + # 0.875. The two auxiliary reader losses are mutually exclusive + # add-ons and are OFF here (the transform alone is the winner). + occ_target_space="goal_relative_reader_metric", + gamma_sampler="reward_metric_endpoints", + gamma_spectrum_lo=0.875, + gamma_horizons=(8.0, 16.0, 32.0, 64.0), + reward_metric_aux_allocation="sqrt_h", + occ_reader_metric_weight=0.0, + occ_reader_hit_weight=0.0, + reward_decoder=art["reward_decoder"], + rdec_samples=4, + latent_npz=art["latent_npz"], + latent_npz_sha256=latent_npz_sha256, + pixel_encoder=art["pixel_encoder"], + pixel_encoder_sha256=pixel_encoder_sha256, + pixel_dataset=art["pixel_dataset"], + pixel_dataset_sha256=pixel_dataset_sha256, + drop_proprio=True, + # condition the flow on the frozen 256-d encoder hidden state + + # goal features (rich context, compact reader-metric future). + goal_hidden=True, + # reader-metric occupancy is restricted to the strict raw-pixel + # actor path (IMPALA-small early fusion over rendered pixels). + actor_input="pixels", + # DDPG+BC actor over a supervised occupancy-Q scorer (occupancy, + # scorer, and raw-pixel actor share one fused step). + actor_loss="ddpgbc_distill", actor_q_transform="raw", + # anchor the recorded behavior action with the non-TD absorbing + # empirical index-successor return (reader-metric actor extraction). + distill_empirical_index_weight=1.0, + alpha=1.0, expectile=0.9, + recursion="off", + batch_size=256, occ_batch=2048, + train_steps=args.train_steps or 500_000, + eval_interval=100_000, + # archive permanent snapshots for banked eval (train renders nothing; + # eval is a separate --eval_only job on a render node). + ckpt_every=10_000, + ckpt_archive_every=20_000, + ) + if _is_discrete(env_id): + # State, discrete goals: exact likelihood read-out + differentiated + # recursion. run_rsm auto-selects gl + recursion for puzzle-*. + return dict( + occupancy_model="diffusion", + alpha=1.0, + recursion="auto", # -> on (differentiated) for discrete + rec_beta=0.98, + batch_size=4096, + train_steps=args.train_steps or 1_000_000, + ) + # State, continuous goals: diffusion ELBO read-out, no recursion, alpha 0.03. + return dict( + occupancy_model="diffusion", + alpha=0.03, + recursion="off", + batch_size=4096, + train_steps=args.train_steps or 1_000_000, + ) + + +def main(): + ap = argparse.ArgumentParser( + description="RSM — the single recipe (state + visual). One command, " + "read-out auto-resolved from the env.") + ap.add_argument("--env", required=True, help="OGBench env id") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=None, + help="override the per-recipe default") + # Visual stage-1 artifacts (only used for visual-* envs). Default None -> + # derived per-env by visual_artifacts(). Override to point elsewhere. + ap.add_argument("--latent_npz", default=None) + ap.add_argument("--pixel_encoder", default=None) + ap.add_argument("--reward_decoder", default=None) + ap.add_argument("--pixel_dataset", default=None, + help="rendered-pixel dataset (default ~/.ogbench/data/.npz)") + ap.add_argument("--pixel_dataset_sha256", default=None, + help="digest; auto-computed from --pixel_dataset if omitted") + ap.add_argument("--ckpt", default=None, help="checkpoint path (optional)") + # Visual pixel path renders at eval, so train and eval are separate jobs. + ap.add_argument("--train_only", action="store_true") + ap.add_argument("--eval_only", action="store_true") + a = ap.parse_args() + + cfg = resolve_recipe(a.env, a) + # train_only/eval_only apply everywhere (visual eval renders separately; a + # state eval_only gives an official 50-ep read of a saved snapshot). + if a.train_only: + cfg["train_only"] = True + if a.eval_only: + cfg["eval_only"] = True + readout = ("reader-metric flow" if _is_visual(a.env) + else "gl" if _is_discrete(a.env) else "elbo") + print(f"[rsm-recipe] env={a.env} seed={a.seed} read-out={readout}") + print(f"[rsm-recipe] config={cfg}") + + run_rsm(a.env, seed=a.seed, ckpt=a.ckpt, **cfg) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/run_combined.sh b/gen_q_rsm/ogbench_genq/run_combined.sh new file mode 100644 index 0000000000000000000000000000000000000000..2ae5354cc184ea06f3d638d8f33f759657a9eb05 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/run_combined.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Train the COMBINED CompPlan (audited td-hc GHM on the VERIFIED reference GC-BC) +# then eval: zero-shot (must reproduce the GC-BC baseline) + GSP composition. +# run_combined.sh +set -uo pipefail +ENVN="$1"; TAG="$2"; GCBC_DIR="$3"; GCBC_EP="$4" +SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +R=$(cd -- "$SCRIPT_DIR/.." && pwd) +PY=${PYTHON:-"$R/.ogbench_venv/bin/python"} +CKPT_ROOT=${GENQ_CKPT_ROOT:-/proj/inf-scaling/zwhong/gen_q/ckpt} +OUT=$CKPT_ROOT/comp_combined/${TAG}.pkl +export XLA_PYTHON_CLIENT_PREALLOCATE=false PYTHONUNBUFFERED=1 MUJOCO_GL=egl +export OGBENCH_IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +cd "$R" || exit 1 +mkdir -p "$R/ckpt/comp_combined" "$R/results/comp_combined" + +echo "[run_combined] TRAIN env=$ENVN base=$GCBC_DIR@$GCBC_EP -> $OUT" +# STABLE td-hc config (the debug ledger: gamma_max 0.997 + ema 0.999 + ramp 300k +# DIVERGED to 5e9; gamma_max 0.995 + ema 0.9995 + ramp 600k + cons_weight 0.5 is stable). +"$PY" -u ogbench_genq/comp_plan_combined.py \ + --env "$ENVN" --gcbc_ckpt "$GCBC_DIR" --gcbc_epoch "$GCBC_EP" \ + --out "$OUT" --train_steps 2000000 --save_every 500000 \ + --gamma_max 0.995 --ema 0.9995 --cons_after 100000 --cons_ramp 600000 \ + --cons_weight 0.5 --grad_clip 0.5 --x_clip 4.0 || { echo "TRAIN FAILED"; exit 1; } + +echo "[run_combined] EVAL zero-shot (expect ~= GC-BC baseline)" +"$PY" -u ogbench_genq/comp_plan_combined_eval.py --ckpt "$OUT" \ + --zero_shot --episodes 50 --out "$R/results/comp_combined/${TAG}_zeroshot.json" + +echo "[run_combined] EVAL GSP composition n=4 m=1024" +"$PY" -u ogbench_genq/comp_plan_combined_eval.py --ckpt "$OUT" \ + --plan_n 4 --plan_m 1024 --episodes 50 --gamma_eval 0.99 --replan_every 25 \ + --out "$R/results/comp_combined/${TAG}_gsp_n4.json" + +echo "[run_combined] EVAL oracle-score n=4 (isolates Lemma-1 scoring)" +"$PY" -u ogbench_genq/comp_plan_combined_eval.py --ckpt "$OUT" \ + --plan_n 4 --plan_m 1024 --episodes 50 --oracle_score \ + --out "$R/results/comp_combined/${TAG}_oracle_n4.json" +echo "[run_combined] ALL DONE $TAG" diff --git a/gen_q_rsm/ogbench_genq/run_rsm_rec_planning.sh b/gen_q_rsm/ogbench_genq/run_rsm_rec_planning.sh new file mode 100644 index 0000000000000000000000000000000000000000..23e8ca0ec064af6cca4383a46cdfeec2655bf6f6 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/run_rsm_rec_planning.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# One-cell GPU driver for #65 recursive-Q test-time planning on unconditional +# RSM (cube-single-play-v0). Runs a fast 5-ep GPU PRE-SCREEN +# (-> rsm_uncond_rec_prescreen.json) then, if it did not error, the full 50-ep +# run (-> rsm_uncond_rec.json). Submit ONE bsub per cell so the (heavy, +# host-driven, per-step chain-grad) cells run on separate GPUs in parallel. +# +# Usage: bash run_rsm_rec_planning.sh +# ckpt_kind: rec | v1 +set -u +cd "$(dirname "$0")/.." || exit 1 +source .env 2>/dev/null || true +export OGBENCH_IMPLS="$HOME/ogbench_ref/impls" +PY=.ogbench_venv/bin/python +ENV=cube-single-play-v0 +REC=ogbench_genq/checkpoints/rsm_goalfree_cube_single_rec_500k.pkl +V1=ogbench_genq/checkpoints/rsm_goalfree_cube_single_500k.pkl + +KIND="$1"; shift +REC_FLAG="$1"; shift +READ="$1"; shift +if [ "$KIND" = "rec" ]; then CKPT="$REC"; else CKPT="$V1"; fi + +echo "===== CELL kind=$KIND rec=$REC_FLAG read=$READ args=$* =====" +echo "----- prescreen (5 ep x 5 tasks) -----" +$PY ogbench_genq/rsm_goalfree.py --env "$ENV" --load_ckpt "$CKPT" \ + --recursion "$REC_FLAG" --read "$READ" "$@" \ + --episodes 5 --wandb_mode disabled \ + --steer_out rsm_uncond_rec_prescreen.json +rc=$? +if [ $rc -ne 0 ]; then + echo "!!! PRESCREEN FAILED (rc=$rc) — skipping full run"; exit 1 +fi +echo "----- full (50 ep x 5 tasks) -----" +$PY ogbench_genq/rsm_goalfree.py --env "$ENV" --load_ckpt "$CKPT" \ + --recursion "$REC_FLAG" --read "$READ" "$@" \ + --episodes 50 --wandb_mode online \ + --steer_out rsm_uncond_rec.json +echo "===== CELL DONE =====" diff --git a/gen_q_rsm/ogbench_genq/run_tdfree.sh b/gen_q_rsm/ogbench_genq/run_tdfree.sh new file mode 100644 index 0000000000000000000000000000000000000000..39b51f0ca2227dbbc52d6a76331be1185fdf6aa3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/run_tdfree.sh @@ -0,0 +1,34 @@ +#!/bin/bash +# TD-FREE CompPlan: our Gen-Q/RSM Monte-Carlo successor measure (no bootstrap) on the +# VERIFIED reference GC-BC base, then eval: zero-shot + GSP composition + oracle. +# run_tdfree.sh +set -uo pipefail +ENVN="$1"; TAG="$2"; GCBC_DIR="$3"; GCBC_EP="$4" +SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +R=$(cd -- "$SCRIPT_DIR/.." && pwd) +PY=${PYTHON:-"$R/.ogbench_venv/bin/python"} +CKPT_ROOT=${GENQ_CKPT_ROOT:-/proj/inf-scaling/zwhong/gen_q/ckpt} +OUT=$CKPT_ROOT/comp_tdfree/${TAG}.pkl +export XLA_PYTHON_CLIENT_PREALLOCATE=false PYTHONUNBUFFERED=1 MUJOCO_GL=egl +cd "$R" || exit 1 +mkdir -p "$R/ckpt/comp_tdfree" "$R/results/comp_tdfree" + +echo "[run_tdfree] TRAIN env=$ENVN base=$GCBC_DIR@$GCBC_EP -> $OUT" +"$PY" -u ogbench_genq/comp_plan_tdfree.py \ + --env "$ENVN" --gcbc_ckpt "$GCBC_DIR" --gcbc_epoch "$GCBC_EP" \ + --out "$OUT" --train_steps 2000000 --save_every 500000 || { echo "TRAIN FAILED"; exit 1; } + +echo "[run_tdfree] EVAL zero-shot" +"$PY" -u ogbench_genq/comp_plan_combined_eval.py --ckpt "$OUT" \ + --zero_shot --episodes 50 --out "$R/results/comp_tdfree/${TAG}_zeroshot.json" + +echo "[run_tdfree] EVAL GSP composition n=4 m=1024" +"$PY" -u ogbench_genq/comp_plan_combined_eval.py --ckpt "$OUT" \ + --plan_n 4 --plan_m 1024 --episodes 50 --gamma_eval 0.99 --replan_every 25 \ + --out "$R/results/comp_tdfree/${TAG}_gsp_n4.json" + +echo "[run_tdfree] EVAL oracle-score n=4" +"$PY" -u ogbench_genq/comp_plan_combined_eval.py --ckpt "$OUT" \ + --plan_n 4 --plan_m 1024 --episodes 50 --oracle_score \ + --out "$R/results/comp_tdfree/${TAG}_oracle_n4.json" +echo "[run_tdfree] ALL DONE $TAG" diff --git a/gen_q_rsm/ogbench_genq/test_actor_query_occupancy_contrast.py b/gen_q_rsm/ogbench_genq/test_actor_query_occupancy_contrast.py new file mode 100644 index 0000000000000000000000000000000000000000..f67f7ee8bf1492475c29a0eff099a5f99e4f4091 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_actor_query_occupancy_contrast.py @@ -0,0 +1,99 @@ +"""CPU gates for detached actor-query occupancy contrast. + +These tests import no OGBench environment and launch no accelerator work. +They verify the two safety-critical pure pieces of the alternate visual +occupancy recipe: every actor/local negative is stop-gradient, and the +behavior-vs-negative ranking keeps the offline tuple importance weights. +""" +import os +import unittest + +os.environ.setdefault("JAX_PLATFORMS", "cpu") +os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") + +import jax +import jax.numpy as jnp +import numpy as np + +from ogbench_genq.rsm import ( + actor_local_negative_actions, + actor_query_contrast_loss, +) + + +class ActorQueryOccupancyContrastTest(unittest.TestCase): + def test_actor_mode_and_local_cloud_are_clipped_and_detached(self): + mode = jnp.asarray([ + [0.9, -0.9], + [0.2, -0.1], + ], dtype=jnp.float32) + noise = jnp.asarray([ + [[1.0, -1.0], [0.5, 0.5]], + [[-0.5, 0.25], [4.0, -4.0]], + ], dtype=jnp.float32) + + cloud = actor_local_negative_actions(mode, noise, 0.3) + self.assertEqual(cloud.shape, (3, 2, 2)) + np.testing.assert_allclose(np.asarray(cloud[0]), np.asarray(mode)) + np.testing.assert_allclose( + np.asarray(cloud[1:]), + np.clip( + np.asarray(mode)[None, ...] + + 0.3 * np.asarray(noise), + -1.0, + 1.0), + ) + + mode_grad = jax.grad( + lambda m: actor_local_negative_actions( + m, noise, 0.3).sum())(mode) + noise_grad = jax.grad( + lambda n: actor_local_negative_actions( + mode, n, 0.3).sum())(noise) + np.testing.assert_array_equal( + np.asarray(mode_grad), np.zeros_like(np.asarray(mode))) + np.testing.assert_array_equal( + np.asarray(noise_grad), np.zeros_like(np.asarray(noise))) + + def test_importance_weighted_ranking_matches_manual_formula(self): + positive = jnp.asarray([0.2, 0.8, 1.4], dtype=jnp.float32) + negative = jnp.asarray([ + [0.6, 0.4, 2.0], + [1.1, 1.0, 1.8], + [0.3, 2.2, 1.5], + ], dtype=jnp.float32) + weights = jnp.asarray([0.25, 2.0, 0.75], dtype=jnp.float32) + margin = 0.1 + + got = actor_query_contrast_loss( + positive, negative, weights, margin) + logits = ( + margin + + np.asarray(positive)[None, :] + - np.asarray(negative)) + expected = ( + np.logaddexp(0.0, logits) + * np.asarray(weights)[None, :]).sum() + expected /= weights.size * negative.shape[0] + self.assertAlmostEqual(float(got), float(expected), places=6) + + def test_ranking_rewards_higher_negative_error(self): + positive = jnp.asarray([1.0, 1.0], dtype=jnp.float32) + weights = jnp.ones((2,), dtype=jnp.float32) + near = jnp.full((3, 2), 1.0, dtype=jnp.float32) + far = jnp.full((3, 2), 3.0, dtype=jnp.float32) + near_loss = actor_query_contrast_loss( + positive, near, weights, 0.1) + far_loss = actor_query_contrast_loss( + positive, far, weights, 0.1) + self.assertLess(float(far_loss), float(near_loss)) + + def test_helpers_jit_on_cpu(self): + mode = jnp.zeros((4, 2), dtype=jnp.float32) + noise = jnp.ones((2, 4, 2), dtype=jnp.float32) + cloud = jax.jit(actor_local_negative_actions)(mode, noise, 0.3) + self.assertEqual(cloud.shape, (3, 4, 2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_goal_relabel.py b/gen_q_rsm/ogbench_genq/test_goal_relabel.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed1f4a8e01cc9fb62d0c1e81dba573b2683b95c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_goal_relabel.py @@ -0,0 +1,67 @@ +import os +import sys + +import numpy as np + + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "genq")) +from train_latent_variants_jax import _sample_gciql_goals +from train_reward_decoder import build_ends, sample_gciql + + +def test_gciql_goal_mix_and_soft_return_targets(): + episode_len = 1000 + n_episodes = 20 + n_frames = episode_len * n_episodes + end_of = np.repeat( + np.arange(episode_len, n_frames + 1, episode_len), episode_len) + rng = np.random.default_rng(11) + # Avoid terminal states so geometrically sampled trajectory goals are + # strictly downstream rather than terminal-clipped to the current index. + episode = rng.integers(0, n_episodes, 100_000) + offset = rng.integers(0, episode_len - 1, 100_000) + t = episode * episode_len + offset + + goal, value, exact, kind = _sample_gciql_goals( + rng, t, 0, n_frames, end_of, + p_curgoal=0.2, p_trajgoal=0.5, discount=0.99) + + proportions = np.bincount(kind, minlength=3) / len(kind) + np.testing.assert_allclose(proportions, [0.2, 0.5, 0.3], atol=0.005) + + current = kind == 0 + trajectory = kind == 1 + random = kind == 2 + assert np.all(goal[current] == t[current]) + assert np.all(value[current] == 1.0) + assert np.all(goal[trajectory] > t[trajectory]) + assert np.all(goal[trajectory] < end_of[t[trajectory]]) + np.testing.assert_allclose( + value[trajectory], + 0.99 ** (goal[trajectory] - t[trajectory]), + rtol=1e-6, + ) + assert np.all((goal[random] >= 0) & (goal[random] < n_frames)) + assert np.all(value[random & ~exact.astype(bool)] == 0.0) + assert np.all(value[exact.astype(bool)] == 1.0) + + +def test_reward_reader_uses_same_gciql_relabel_contract(): + terminals = np.zeros(20_000, dtype=bool) + terminals[999::1000] = True + end_of = build_ends(terminals) + np.testing.assert_array_equal( + end_of[:1001], + np.concatenate([np.full(1000, 1000), np.asarray([2000])]), + ) + + rng = np.random.default_rng(17) + t, goal, value = sample_gciql( + rng, end_of, 100_000, 0, len(terminals), + discount=0.99, p_curgoal=0.2, p_trajgoal=0.5) + exact = goal == t + assert np.all(value[exact] == 1.0) + assert np.all((value >= 0.0) & (value <= 1.0)) + # Current goals alone account for 20%; terminal clipping and random exact + # matches can only increase this slightly. + assert 0.195 < exact.mean() < 0.23 diff --git a/gen_q_rsm/ogbench_genq/test_occupancy_recursion.py b/gen_q_rsm/ogbench_genq/test_occupancy_recursion.py new file mode 100644 index 0000000000000000000000000000000000000000..e23b6f97b1a21ad7c2ec4ba7b68aa8aeb0569e37 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_occupancy_recursion.py @@ -0,0 +1,86 @@ +"""Unit gates for the TD-free occupancy-only visual recursion. + +These tests are CPU-only and import no OGBench environment. They verify the +geometric probability-generating-function identity used to turn independently +tunable beta jumps into a target-gamma occupancy, including the fixed-depth +tail accounting stored in result metadata. +""" +import unittest + +import numpy as np + +from ogbench_genq.rsm import ( + occupancy_recursion_continuation, + occupancy_recursion_tail_mass, +) + + +class OccupancyRecursionIdentityTest(unittest.TestCase): + def test_geometric_pgf_identity(self): + for gamma, beta in ( + (0.985, 0.970), + (0.990, 0.970), + (0.990, 0.980), + (0.990, 0.985), + (0.995, 0.990)): + continuation = occupancy_recursion_continuation(gamma, beta) + self.assertGreater(continuation, 0.0) + self.assertLess(continuation, 1.0) + for z in np.linspace(0.0, 0.999, 101): + beta_pgf = (1.0 - beta) / (1.0 - beta * z) + composed = ( + (1.0 - continuation) * beta_pgf + / (1.0 - continuation * beta_pgf)) + gamma_pgf = (1.0 - gamma) / (1.0 - gamma * z) + self.assertAlmostEqual(composed, gamma_pgf, places=12) + + def test_depth_tail(self): + gamma, beta, depth = 0.99, 0.98, 10 + continuation = occupancy_recursion_continuation(gamma, beta) + self.assertAlmostEqual( + occupancy_recursion_tail_mass(gamma, beta, depth), + continuation ** depth, + places=15) + self.assertLess( + occupancy_recursion_tail_mass(gamma, beta, depth), 0.002) + + def test_visual_sweep_depths_cap_tail_below_five_e_minus_four(self): + candidates = ( + (0.99, 0.985, 8, 0.00016517655554808348), + (0.99, 0.98, 12, 0.0002754341063237226), + (0.99, 0.97, 20, 0.0003676807788245077), + (0.98, 0.96, 12, 0.00031111943662680107), + ) + for gamma, beta, depth, expected_tail in candidates: + with self.subTest(gamma=gamma, beta=beta, depth=depth): + actual_tail = occupancy_recursion_tail_mass( + gamma, beta, depth) + self.assertAlmostEqual(actual_tail, expected_tail, places=15) + self.assertLessEqual(actual_tail, 5e-4) + # The three deeper candidates are the smallest depths that + # pass. The depth-8 short-hop arm deliberately keeps one extra + # level because depth 7 lands only 1.9% below the cap. + shallower_depth = ( + depth - 2 if (gamma, beta) == (0.99, 0.985) + else depth - 1 + ) + self.assertGreater( + occupancy_recursion_tail_mass( + gamma, beta, shallower_depth), + 5e-4, + ) + + def test_invalid_discount_order_is_rejected(self): + for gamma, beta in ( + (0.99, 0.99), + (0.98, 0.99), + (1.00, 0.98), + (0.99, 0.00)): + with self.assertRaises(ValueError): + occupancy_recursion_continuation(gamma, beta) + with self.assertRaises(ValueError): + occupancy_recursion_tail_mass(0.99, 0.98, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_reward_reader.py b/gen_q_rsm/ogbench_genq/test_reward_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..2d0dee109db30486cf26d481b84eb523b9714799 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_reward_reader.py @@ -0,0 +1,188 @@ +"""CPU unit gates for visual MLP and diagonal-metric reward readers.""" + +import os +import tempfile +import unittest + +import numpy as np + +os.environ.setdefault("JAX_PLATFORMS", "cpu") +os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") + +from ogbench_genq.genq.reward_reader import ( + joint_index_pair_masks, + load_jax_reward_reader, + load_numpy_reward_reader, +) +from ogbench_genq.genq.train_reward_decoder import ( + sample_index_same_episode, +) + + +def _save_metric(path, scale, weight, bias): + np.savez( + path, + reader_model=np.asarray("diag_metric"), + target=np.asarray("index"), + index_delta=np.asarray(2), + neg_gap=np.asarray(4), + zdim=np.asarray(len(scale)), + features=np.asarray("symmetric"), + activation=np.asarray("tanh"), + metric_scale=np.asarray(scale, np.float32), + metric_weight=np.asarray(weight, np.float32), + metric_bias=np.asarray(bias, np.float32), + pixels_only_latents=np.asarray(True), + uses_coordinates_for_training=np.asarray(False), + uses_reward_arrays=np.asarray(False), + uses_td_or_bootstrap=np.asarray(False), + ) + + +class RewardReaderTest(unittest.TestCase): + def test_vectorized_metric_sampler_stays_in_episode_and_respects_gap(self): + episodes = [(0, 199), (200, 499), (500, 899)] + rows, positives, negatives = sample_index_same_episode( + episodes, np.random.default_rng(17), 20000, + index_delta=4, neg_gap=64) + starts = np.select( + [rows < 200, rows < 500], [0, 200], default=500) + ends = np.select( + [rows < 200, rows < 500], [199, 499], default=899) + self.assertTrue(np.all(positives >= rows)) + self.assertTrue(np.all(positives <= np.minimum(rows + 4, ends))) + self.assertTrue(np.all(negatives >= starts)) + self.assertTrue(np.all(negatives <= ends)) + self.assertTrue(np.all(np.abs(negatives - rows) >= 64)) + + def test_diagonal_metric_is_symmetric_and_affine_scale_invariant(self): + rng = np.random.default_rng(5) + future = rng.normal(size=(32, 3)).astype(np.float32) + goal = rng.normal(size=(32, 3)).astype(np.float32) + scale = np.asarray([0.5, 2.0, 4.0], np.float32) + weight = np.asarray([0.0, 0.7, 1.3], np.float32) + bias = np.float32(1.25) + coordinate_scale = np.asarray([3.0, 0.25, 2.0], np.float32) + offset = np.asarray([-7.0, 11.0, 0.5], np.float32) + + with tempfile.TemporaryDirectory( + prefix="diag_reward_reader_", dir="/tmp") as directory: + base_path = os.path.join(directory, "base.npz") + transformed_path = os.path.join(directory, "transformed.npz") + _save_metric(base_path, scale, weight, bias) + _save_metric( + transformed_path, scale * coordinate_scale, weight, bias) + + base, metadata = load_numpy_reward_reader(base_path) + transformed, _ = load_numpy_reward_reader(transformed_path) + base_logits = base(future, goal) + np.testing.assert_allclose( + base_logits, base(goal, future), atol=0.0, rtol=0.0) + np.testing.assert_allclose( + base_logits, + transformed( + future * coordinate_scale + offset, + goal * coordinate_scale + offset), + atol=5e-6, + rtol=5e-6, + ) + np.testing.assert_allclose( + base(future, future), + np.full(len(future), bias, np.float32), + atol=0.0, + rtol=0.0, + ) + self.assertEqual(metadata["reader_model"], "diag_metric") + self.assertTrue(metadata["metric_weight_nonnegative"]) + self.assertFalse(metadata["uses_coordinates_for_training"]) + self.assertFalse(metadata["uses_td_or_bootstrap"]) + + jax_reader, _ = load_jax_reward_reader(base_path) + np.testing.assert_allclose( + np.asarray(jax_reader(future, goal)), + base_logits, + atol=2e-6, + rtol=2e-6, + ) + + def test_legacy_artifact_without_model_is_bit_exact(self): + rng = np.random.default_rng(9) + zdim, hidden = 3, 5 + future = rng.normal(size=(17, zdim)).astype(np.float32) + goal = rng.normal(size=(17, zdim)).astype(np.float32) + parameters = { + "g0.kernel": rng.normal( + size=(4 * zdim, hidden)).astype(np.float32), + "g0.bias": rng.normal(size=hidden).astype(np.float32), + "g1.kernel": rng.normal( + size=(hidden, hidden)).astype(np.float32), + "g1.bias": rng.normal(size=hidden).astype(np.float32), + "g2.kernel": rng.normal(size=(hidden, 1)).astype(np.float32), + "g2.bias": rng.normal(size=1).astype(np.float32), + } + with tempfile.TemporaryDirectory( + prefix="legacy_reward_reader_", dir="/tmp") as directory: + legacy_path = os.path.join(directory, "legacy.npz") + explicit_path = os.path.join(directory, "explicit.npz") + common = { + "target": np.asarray("index"), + "index_delta": np.asarray(8), + "neg_gap": np.asarray(64), + "zdim": np.asarray(zdim), + "features": np.asarray("symmetric"), + "activation": np.asarray("tanh"), + **parameters, + } + np.savez(legacy_path, **common) + np.savez( + explicit_path, reader_model=np.asarray("mlp"), **common) + legacy, legacy_meta = load_numpy_reward_reader(legacy_path) + explicit, explicit_meta = load_numpy_reward_reader(explicit_path) + + pair = np.concatenate( + [future, goal, np.abs(future - goal), future * goal], + axis=-1) + hidden_value = np.tanh( + pair @ parameters["g0.kernel"] + parameters["g0.bias"]) + hidden_value = np.tanh( + hidden_value @ parameters["g1.kernel"] + + parameters["g1.bias"]) + expected = ( + hidden_value @ parameters["g2.kernel"] + + parameters["g2.bias"])[:, 0] + np.testing.assert_array_equal(legacy(future, goal), expected) + np.testing.assert_array_equal( + explicit(future, goal), expected) + self.assertEqual(legacy_meta["reader_model"], "mlp") + self.assertEqual(explicit_meta["reader_model"], "mlp") + + def test_metric_joint_auxiliary_excludes_cross_episode_negatives(self): + rows = np.asarray([1, 0, 1, 6]) + goals = np.asarray([2, 4, 7, 1]) + starts = np.asarray([0, 0, 0, 5]) + ends = np.asarray([5, 5, 5, 10]) + + metric_positive, metric_negative = joint_index_pair_masks( + rows, goals, starts, ends, 2, 4, "diag_metric") + mlp_positive, mlp_negative = joint_index_pair_masks( + rows, goals, starts, ends, 2, 4, "mlp") + + np.testing.assert_array_equal( + metric_positive, [True, False, False, False]) + np.testing.assert_array_equal( + metric_negative, [False, True, False, False]) + np.testing.assert_array_equal(metric_positive, mlp_positive) + np.testing.assert_array_equal( + mlp_negative, [False, True, True, True]) + + def test_negative_metric_weight_is_rejected(self): + with tempfile.TemporaryDirectory( + prefix="invalid_reward_reader_", dir="/tmp") as directory: + path = os.path.join(directory, "invalid.npz") + _save_metric(path, [1.0, 1.0], [0.5, -0.1], 0.0) + with self.assertRaisesRegex(ValueError, "nonnegative"): + load_numpy_reward_reader(path) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_rsm_checkpoint_schedule.py b/gen_q_rsm/ogbench_genq/test_rsm_checkpoint_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..92cbfa2639efbd7efaf2132207830f67ffa3a7bb --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_rsm_checkpoint_schedule.py @@ -0,0 +1,65 @@ +"""CPU tests for independent resumability and archive checkpoint cadences.""" + +import hashlib +import os +import tempfile +import unittest + +from ogbench_genq.rsm import checkpoint_due, resolve_checkpoint_load + + +class RsmCheckpointScheduleTest(unittest.TestCase): + def test_union_of_primary_and_archive_cadences(self): + due = [ + step + for step in range(100, 50_001, 100) + if checkpoint_due(step, 10_000, 25_000) + ] + self.assertEqual(due, [10_000, 20_000, 25_000, 30_000, 40_000, 50_000]) + + def test_primary_cadence_without_archives(self): + self.assertTrue(checkpoint_due(10_000, 10_000)) + self.assertFalse(checkpoint_due(5_000, 10_000)) + + def test_immutable_resume_source_then_destination(self): + with tempfile.TemporaryDirectory() as tmp: + source = os.path.join(tmp, "source.pkl") + destination = os.path.join(tmp, "continuation.pkl") + payload = b"exact gated checkpoint" + with open(source, "wb") as handle: + handle.write(payload) + digest = hashlib.sha256(payload).hexdigest() + + load_path, provenance = resolve_checkpoint_load( + destination, source, digest) + self.assertEqual(load_path, os.path.realpath(source)) + self.assertEqual( + provenance, + {"path": os.path.realpath(source), "sha256": digest}, + ) + + with open(destination, "wb") as handle: + handle.write(b"new continuation state") + load_path, provenance_again = resolve_checkpoint_load( + destination, source, digest) + self.assertEqual(load_path, os.path.realpath(destination)) + self.assertEqual(provenance_again, provenance) + + def test_immutable_resume_rejects_unpinned_or_overlapping_source(self): + with tempfile.TemporaryDirectory() as tmp: + source = os.path.join(tmp, "source.pkl") + with open(source, "wb") as handle: + handle.write(b"checkpoint") + digest = hashlib.sha256(b"checkpoint").hexdigest() + with self.assertRaisesRegex(ValueError, "requires.*sha256"): + resolve_checkpoint_load( + os.path.join(tmp, "out.pkl"), source, None) + with self.assertRaisesRegex(ValueError, "SHA-256 mismatch"): + resolve_checkpoint_load( + os.path.join(tmp, "out.pkl"), source, "0" * 64) + with self.assertRaisesRegex(ValueError, "distinct"): + resolve_checkpoint_load(source, source, digest) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_occupancy_gate.py b/gen_q_rsm/ogbench_genq/test_visual_occupancy_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..0389335a8079002b76f5c39b2cc29b8d03953b64 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_occupancy_gate.py @@ -0,0 +1,1380 @@ +"""CPU unit tests for the fair visual occupancy checkpoint gate.""" + +import copy +import os +import tempfile +import unittest + +import numpy as np + +os.environ.setdefault("JAX_PLATFORMS", "cpu") +os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") + +from ogbench_genq.genq.gate_visual_occupancy import ( + _assert_checkpoint_contract, + _assert_protected_endpoint_contract, + _assert_reward_metric_endpoint_contract, + _energy_distance, + _exact_absorbing_occupancy, + _hidden_future_support_contract, + _load_pinned_pixel_actor_dataset, + _load_pinned_pixel_source, + _pairwise_rank_agreement, + _pixel_actor_definition, + _pixel_actor_mode, + _project_hidden_support, + _sha256_file, + _visual_actor_reference_sha256, + PIXEL_SCORER_TARGET_UPDATE_SOURCE, + PIXEL_SCORER_TARGET_UPDATE_TIMING, + PIXEL_SCORER_TARGET_UPDATE_TAU, + VISUAL_ACTOR_REFERENCE_FILES, + VISUAL_GCIQL_BATCH_SIZE, +) +from ogbench_genq.rsm import reward_metric_endpoint_batch_plan + + +def _valid_contract(): + meta = { + "env": "visual-cube-single-play-v0", + "drop_proprio": True, + "discount_conditioned": True, + "discount_feature": "fourier_log_horizon", + "gamma_spectrum_lo": 0.5, + "gamma": 0.99, + "occupancy_model": "flow", + "recursion": "off", + "uses_td_or_bootstrap": False, + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": False, + "occupancy_and_actor_jointly_updated": True, + "freeze_occupancy": False, + "joint_update_semantics": + "same_fused_step_separate_supervised_losses", + "actor_gradient_updates_occupancy": False, + "occupancy_gradient_updates_actor": False, + "occupancy_supervision": "monte_carlo_geometric_futures", + "occupancy_training_policy": "offline_behavior_data", + "reward_decoder_target": "index", + "reward_decoder_logit": False, + "reward_decoder_model": "diag_metric", + "reward_decoder_index_delta": 4, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "latent_npz": "/tmp/latent.npz", + "pixel_encoder": "/tmp/encoder.npz", + "reward_decoder": "/tmp/reader.npz", + "occupancy_future_dim": 3, + "occ_action_contrast_weight": 0.0, + } + reader = { + "reader_model": "diag_metric", + "target": "index", + "index_delta": 4, + "zdim": 3, + "pixels_only_latents": True, + "frozen_encoder": True, + "uses_coordinates_for_training": False, + "uses_coordinates_for_diagnostics": False, + "uses_reward_arrays": False, + "uses_td_or_bootstrap": False, + "label_source": + "trajectory_index_positive_and_far_negative_relabeling", + } + return meta, reader + + +def _valid_hidden_contract(): + meta, reader = _valid_contract() + meta.update({ + "recursion": "occupancy_latent", + "recursion_state": "hidden", + "rec_after": 50, + "goal_hidden": True, + "latent_update": "frozen", + "state_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "occupancy_future_dim": 256, + "reward_reader_dim": 3, + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "frozen_encoder_hidden_occupancy_state", + "reward_goal_feature": "compact_reward_predictive_z", + "frozen_encoder_fc1_reward_projection": True, + "occupancy_active_future_dims": 109, + "occupancy_constant_future_dims": 147, + "constant_future_masking": True, + "recursive_state_support_projection": + "relu_nonnegative_plus_constant_mean", + "occupancy_target_standardization": + "per_dimension_dataset_mean_std", + }) + return meta, reader + + +def _valid_pixel_hidden_contract( + latent_update="frozen", protected=False, hit_weight=0.0): + """Schema-10/11 raw-RGB actor with h256 occupancy and z8 reader.""" + meta, reader = _valid_contract() + reader.update({ + "zdim": 8, + "index_delta": 4, + }) + latent_path = "/tmp/pixel_hidden_latents.npz" + encoder_path = "/tmp/pixel_hidden_encoder.npz" + dataset_path = "/tmp/pixel_actor_dataset.npz" + meta.update({ + "schema_version": 11 if protected else 10, + "state_dim": 256, + "goal_dim": 256, + "actor_goal_dim": 256, + "occupancy_goal_dim": 256, + "reward_goal_dim": 8, + "occupancy_future_dim": 256, + "reward_reader_dim": 8, + "goal_hidden": True, + "latent_update": latent_update, + "state_feature": "encoder_hidden", + "actor_goal_feature": "raw_rgb_pixels", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "frozen_encoder_hidden_occupancy_state", + "reward_goal_feature": "compact_reward_predictive_z", + "frozen_encoder_fc1_reward_projection": True, + "occupancy_active_future_dims": 109, + "occupancy_constant_future_dims": 147, + "constant_future_masking": True, + "recursive_state_support_projection": None, + "occupancy_target_standardization": + "per_dimension_dataset_mean_std", + "reward_decoder_index_delta": 4, + "latent_npz": latent_path, + "pixel_encoder": encoder_path, + "actor_input": "pixels", + "actor_state_feature": "raw_rgb_pixels", + "final_actor_consumes_pixels": True, + "policy_observation": "rendered_pixels_only", + "actor_architecture": + "GCActor_IMPALA_small_early_fusion_MLP_512x3", + "actor_encoder": "impala_small", + "actor_encoder_trainable": True, + "actor_encoder_initialization": "fresh_jointly_trainable", + "actor_pixel_augmentation_probability": 0.5, + "actor_training_augmentation": + "batch_probability_shared_per_row_edge_padded_random_crop", + "actor_goal_relabeling": "uniform_future_same_trajectory", + "actor_pixel_state_shape": [64, 64, 3], + "actor_pixel_goal_shape": [64, 64, 3], + "actor_goal_dim_semantics": + "latent_supervised_scorer_goal_width", + "actor_transition_sampling": + "uniform_over_dataset_valid_indices", + "pixel_dataset_device_transport": + "dynamic_jit_dispatch_argument_not_xla_constant", + "occupancy_consumes_raw_pixels": False, + "raw_pixels_update_actor_only": True, + "occupancy_state_for_pixel_actor": "encoder_hidden", + "occupancy_goal_for_pixel_actor": "encoder_hidden", + "supervised_scalar_scorer_state_for_pixel_actor": + "encoder_hidden", + "pixel_actor_occupancy_discount_required": True, + "pixel_actor_recursion_supported": False, + "pixel_actor_generated_midpoint_policy": None, + "pixel_actor_uses_image_or_world_model_reconstruction": False, + "completion_or_world_model_carrier_instantiated": False, + "pixel_actor_and_occupancy_same_fused_step": True, + "pixel_actor_dataset": { + "path": dataset_path, + "sha256": "c" * 64, + "dataset_keys": [ + "actions", "observations", "terminals", "valids"], + "excluded_keys": [ + "button_states", "coordinates", "qpos", "qvel", + "rewards"], + "observation_shape": [64, 64, 3], + "observation_dtype": "uint8", + "action_shape": [2], + "row_count": 12, + "valid_transition_count": 10, + "actions_match_latent_cache": True, + "source_terminals_match_latent_cache": True, + "compact_terminals_match_reconstructed": True, + "terminal_alignment_contract": + "latent_source_endpoints_equal_pixel_valids_zero_and_" + "compact_terminals_equal_source_plus_shifted_source", + }, + "pixel_artifact_provenance": { + "latent_npz": { + "path": latent_path, + "sha256": "a" * 64, + }, + "pixel_encoder": { + "path": encoder_path, + "sha256": "b" * 64, + }, + "pixel_dataset": { + "path": dataset_path, + "sha256": "c" * 64, + }, + }, + }) + if latent_update == "rich_adapter": + meta.update({ + "state_feature": "joint_encoder_hidden_adapter", + "occupancy_goal_feature": "joint_encoder_hidden_adapter", + "occupancy_state_for_pixel_actor": + "joint_encoder_hidden_adapter", + "occupancy_goal_for_pixel_actor": + "joint_encoder_hidden_adapter", + "supervised_scalar_scorer_state_for_pixel_actor": + "joint_encoder_hidden_adapter", + "latent_aux_target": "index", + "latent_reader_model": "diag_metric", + "latent_index_delta": 4, + "latent_index_neg_gap": 16, + "latent_index_negative_contract": + "same_episode_far_only_cross_episode_excluded", + "adapter_feature_dim": 256, + "latent_hidden": 256, + "latent_lr": 3e-4, + "latent_goal_weight": 1.0, + "latent_anchor_weight": 0.1, + }) + if protected: + meta.update({ + "gamma_sampler": "protected_endpoints", + "gamma_task_fraction": 0.60, + "rec_beta": 0.98, + "rec_beta_sample_prob": 0.30, + "occ_batch": 2048, + "gamma_horizons": [8.0, 16.0, 32.0, 64.0], + "gamma_aux_discounts": [ + 0.875, 0.9375, 0.96875, 0.984375], + "gamma_batch_allocation": + "exact_60pct_task_30pct_beta_10pct_sqrt_h_aux_then_" + "joint_discount_goal_source_shuffle", + "gamma_task_rows_per_occ_batch": 1229, + "gamma_beta_rows_per_occ_batch": 614, + "gamma_aux_rows_per_occ_batch": [28, 40, 57, 80], + "gamma_sampling_importance_weighted": False, + "gamma_normalization": "fixed_fourier_identity", + "condition_normalizer_probe_size": 20000, + "condition_normalizer_goal_sampler": + "exact_mixture_actor_uniform_future_0.5_plus_" + "gciql_value_goals_20_current_50_trajectory_30_random", + "occupancy_actor_goal_fraction": 0.50, + "occupancy_actor_goal_rows_per_batch": 1024, + "condition_normalizer_actor_goal_rows": 10000, + "protected_endpoint_sampler": True, + "protected_endpoint_task_fraction": 0.60, + "protected_endpoint_beta_fraction": 0.30, + "protected_endpoint_aux_fraction": 0.10, + "protected_endpoint_aux_allocation": + "deterministic_largest_remainder_sqrt_h", + "protected_endpoint_overrides_legacy_fraction_flags": True, + "protected_endpoint_requested_horizons": [ + 8.0, 16.0, 32.0, 50.0, 64.0], + "protected_endpoint_excluded_beta_horizons": [50.0], + "protected_endpoint_goal_source_fraction": 0.50, + "protected_endpoint_actor_rows_by_discount": [ + 615, 307, 14, 20, 28, 40], + "protected_endpoint_value_rows_by_discount": [ + 614, 307, 14, 20, 29, 40], + "protected_endpoint_cross_stratification": + "exact_global_50pct_each_source_largest_remainder_by_" + "discount", + "protected_endpoint_normalizer_discount_rows": [ + 12000, 6000, 276, 391, 552, 781], + "protected_endpoint_normalizer_actor_rows_by_discount": [ + 6000, 3000, 138, 196, 276, 390], + "protected_endpoint_normalizer_value_rows_by_discount": [ + 6000, 3000, 138, 195, 276, 391], + "occ_reader_metric_weight": 0.0, + "occ_reader_metric_enabled": False, + "occ_reader_metric_model": ( + "diag_metric" if hit_weight > 0.0 else None), + "occ_reader_metric_target": ( + "index" if hit_weight > 0.0 else None), + "occ_reader_metric_uses_index_relabeling": + bool(hit_weight > 0.0), + "occ_reader_metric_uses_reward_arrays": False, + "occ_reader_metric_uses_coordinates": False, + "occ_reader_metric_uses_td_or_bootstrap": False, + "occ_reader_geometry_enabled": bool(hit_weight > 0.0), + "occ_reader_hit_weight": float(hit_weight), + "occ_reader_hit_enabled": bool(hit_weight > 0.0), + "occ_reader_hit_importance_weighted": False, + "occ_reader_hit_action_contrast_weights_changed": False, + "occ_reader_hit_uses_index_relabeling": + bool(hit_weight > 0.0), + "occ_reader_hit_uses_reward_arrays": False, + "occ_reader_hit_uses_coordinates": False, + "occ_reader_hit_uses_td_or_bootstrap": False, + }) + if hit_weight > 0.0: + meta.update({ + "occ_reader_hit_endpoint_weights": [0.5, 0.5], + "occ_reader_hit_mask": + "same_trajectory_and_goal_index_gt_t_and_take_hit", + "occ_reader_hit_base_mle_formula": + "E_q[w_IS*e_base]=" + "mean(hit_miss_importance_weight*base_flow_mse)", + "occ_reader_hit_take_hit_probability": 0.5, + "occ_reader_hit_target_source": + "sampled_same_trajectory_future_index_relabel_take_hit", + }) + return meta, reader + + +def _valid_pixel_compact_contract(protected=False, hit_weight=0.0): + """Raw-RGB actor with h256 state and compact z8 goal/future.""" + meta, reader = _valid_pixel_hidden_contract( + "frozen", protected=protected, hit_weight=hit_weight) + meta.update({ + "goal_dim": 8, + "actor_goal_dim": 8, + "occupancy_goal_dim": 8, + "reward_goal_dim": 8, + "occupancy_future_dim": 8, + "reward_reader_dim": 8, + "goal_hidden": False, + "latent_update": None, + "state_feature": "encoder_hidden", + "occupancy_goal_feature": "compact_reward_predictive_z", + "future_feature": "compact_reward_predictive_z", + "reward_goal_feature": "compact_reward_predictive_z", + "frozen_encoder_fc1_reward_projection": False, + "occupancy_active_future_dims": 8, + "occupancy_constant_future_dims": 0, + "constant_future_masking": False, + "recursive_state_support_projection": None, + "occupancy_state_for_pixel_actor": "encoder_hidden", + "occupancy_goal_for_pixel_actor": + "compact_reward_predictive_z", + "supervised_scalar_scorer_state_for_pixel_actor": + "encoder_hidden", + }) + return meta, reader + + +def _valid_reward_metric_endpoint_meta(aux_allocation="uniform"): + allocation_meta = { + "uniform": + "deterministic_largest_remainder_uniform_horizon", + "sqrt_h": + "deterministic_largest_remainder_sqrt_h", + }[aux_allocation] + horizons = (8.0, 16.0, 32.0, 64.0) + train = reward_metric_endpoint_batch_plan( + 2048, 0.99, 0.98, horizons, + 0.50, 0.25, aux_allocation) + normalizer = reward_metric_endpoint_batch_plan( + 20000, 0.99, 0.98, horizons, + 0.50, 0.25, aux_allocation) + return { + "schema_version": 13, + "gamma_sampler": "reward_metric_endpoints", + "reward_metric_endpoint_sampler": True, + "protected_endpoint_sampler": False, + "gamma": 0.99, + "rec_beta": 0.98, + "gamma_spectrum_lo": 0.875, + "gamma_task_fraction": 0.50, + "rec_beta_sample_prob": 0.25, + "reward_metric_endpoint_task_fraction": 0.50, + "reward_metric_endpoint_beta_fraction": 0.25, + "reward_metric_endpoint_aux_fraction": 0.25, + "reward_metric_endpoint_aux_allocation": allocation_meta, + "gamma_batch_allocation": + "exact_configurable_task_beta_remaining_aux_" + f"{aux_allocation}_then_shuffle", + "gamma_sampling_importance_weighted": False, + "gamma_normalization": "fixed_fourier_identity", + "gamma_horizons": list(horizons), + "reward_metric_endpoint_horizons": list(horizons), + "gamma_aux_discounts": [ + 1.0 - 1.0 / horizon for horizon in horizons], + "occ_batch": 2048, + "gamma_task_rows_per_occ_batch": train["task_rows"], + "gamma_beta_rows_per_occ_batch": train["beta_rows"], + "gamma_aux_rows_per_occ_batch": + list(train["aux_rows_by_horizon"]), + "condition_normalizer_probe_size": 20000, + "reward_metric_endpoint_normalizer_discount_rows": [ + normalizer["task_rows"], + normalizer["beta_rows"], + *normalizer["aux_rows_by_horizon"], + ], + "occupancy_actor_goal_fraction": 0.50, + "occupancy_actor_goal_rows_per_batch": 1024, + "condition_normalizer_actor_goal_rows": 10000, + "condition_normalizer_goal_sampler": + "exact_mixture_actor_uniform_future_0.5_plus_" + "gciql_value_goals_20_current_50_trajectory_30_random", + } + + +def _valid_pixel_reward_metric_contract(aux_allocation="uniform"): + meta, reader = _valid_pixel_hidden_contract( + "frozen", protected=True, hit_weight=0.0) + meta.update(_valid_reward_metric_endpoint_meta(aux_allocation)) + scale = np.linspace(0.1, 0.17, 8, dtype=np.float32) + weight = np.linspace(0.5, 2.0, 8, dtype=np.float32) + diagonal = np.sqrt(weight) / scale + reader.update({ + "metric_scale": scale, + "metric_weight": weight, + }) + meta.update({ + "schema_version": 13, + "occupancy_future_dim": 8, + "reward_reader_dim": 8, + "future_feature": "goal_relative_reader_metric_u", + "frozen_encoder_fc1_reward_projection": False, + "occupancy_active_future_dims": 8, + "occupancy_constant_future_dims": 0, + "constant_future_masking": False, + "occupancy_target_standardization": + "identity_in_frozen_reader_metric_coordinates", + "occupancy_target_space": "goal_relative_reader_metric", + "occupancy_target_formula": + "u_i=sqrt(reader_weight_i)/reader_scale_i*" + "(z_future_i-z_goal_i)", + "occupancy_target_decoder": + "z_future_i=z_goal_i+u_i*reader_scale_i/" + "sqrt(reader_weight_i)", + "occupancy_target_invertible": True, + "occupancy_target_reader_frozen": True, + "occupancy_target_reader_model": "diag_metric", + "occupancy_target_reader_target": "index", + "occupancy_target_reader_index_delta": 4, + "occupancy_target_metric_scale": scale.tolist(), + "occupancy_target_metric_weight": weight.tolist(), + "occupancy_target_metric_diagonal": + diagonal.astype(np.float32).tolist(), + "occupancy_target_metric_inverse_diagonal": + (1.0 / diagonal).astype(np.float32).tolist(), + "occupancy_target_goal_feature": + "compact_reward_predictive_z", + "occupancy_decoded_future_feature": + "compact_reward_predictive_z", + "occupancy_target_uses_index_relabeling": True, + "occupancy_target_uses_reward_arrays": False, + "occupancy_target_uses_coordinates": False, + "occupancy_target_uses_td_or_bootstrap": False, + "occ_hidden": 256, + "occ_layers": 4, + "occupancy_learning_rate": 3e-4, + "distill_empirical_index_enabled": True, + "distill_empirical_index_weight": 1.0, + "distill_empirical_index_behavior_action_only": True, + "distill_empirical_index_counterfactual_action_source": + "discount_conditioned_ema_occupancy", + "distill_empirical_index_target_source": + "observed_same_trajectory_absorbing_first_passage_geometric_" + "successor_compact_z_through_frozen_index_reader", + "distill_empirical_index_horizon": + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount", + "distill_empirical_index_samples": 16, + "distill_empirical_index_blend_formula": + "(1-weight)*ema_occupancy_reader_expectation" + "+weight*recorded_successor_reader_expectation", + "distill_empirical_index_uses_reward_arrays": False, + "distill_empirical_index_uses_coordinates": False, + "distill_empirical_index_uses_td_or_bootstrap": False, + }) + return meta, reader + + +def _valid_pixel_scorer_contract( + actor_loss="ddpgbc_distill", counterfactual_support=False): + meta, reader = _valid_pixel_hidden_contract( + "frozen", protected=True, hit_weight=0.25) + awr = actor_loss == "awr_distill" + meta.update({ + "schema_version": 13, + "actor_loss": actor_loss, + "alpha": 30.0 if awr else 1.0, + "expectile": 0.9, + "actor_goal_dim_semantics": "raw_rgb_pixel_scorer_goal_shape", + "raw_pixels_update_actor_only": False, + "supervised_scalar_scorer_state_for_pixel_actor": + "raw_rgb_pixels", + "distill_scorer_input": "pixels", + "supervised_scalar_scorer_input": "raw_rgb_pixels", + "supervised_scalar_scorer_goal_input": "raw_rgb_pixels", + "supervised_scalar_scorer_architecture": + "GCValue_IMPALA_small_early_fusion_twin_MLP_512x3", + "supervised_scalar_scorer_encoder": "impala_small", + "supervised_scalar_scorer_encoder_trainable": True, + "supervised_scalar_scorer_ensemble_size": 2, + "supervised_scalar_scorer_target_update_source": + PIXEL_SCORER_TARGET_UPDATE_SOURCE, + "supervised_scalar_scorer_target_update_timing": + PIXEL_SCORER_TARGET_UPDATE_TIMING, + "supervised_scalar_scorer_target_update_tau": + PIXEL_SCORER_TARGET_UPDATE_TAU, + "supervised_scalar_scorer_recorded_action_target_source": + "observed_same_trajectory_absorbing_first_passage_geometric_" + "successor_compact_z_through_frozen_index_reader", + "supervised_scalar_scorer_recorded_action_uses_occupancy": False, + "supervised_scalar_scorer_counterfactual_target_source": ( + "discount_conditioned_ema_occupancy_index_reader_expectation" + if counterfactual_support else None), + "supervised_scalar_scorer_counterfactual_uses_empirical": ( + False if counterfactual_support else None), + "supervised_scalar_scorer_target_discount": + "explicit_task_gamma", + "supervised_scalar_scorer_receives_discount_feature": False, + "supervised_scalar_scorer_training_augmentation": + "batch_probability_shared_per_row_across_state_value_goal_" + "actor_goal_edge_padded_random_crop", + "supervised_scalar_scorer_uses_proprio": False, + "supervised_scalar_scorer_uses_coordinates": False, + "supervised_scalar_scorer_uses_reward_arrays": False, + "supervised_scalar_scorer_uses_td_or_bootstrap": False, + "supervised_expectile_value_input": "raw_rgb_pixels", + "supervised_expectile_value_architecture": + "GCValue_IMPALA_small_early_fusion_single_MLP_512x3", + "supervised_expectile_value_target_source": + "stop_gradient_ema_twin_pixel_scorer_empirical_absorbing_" + "index_return_expectile", + "supervised_expectile_value_target_discount": + "explicit_task_gamma", + "supervised_expectile_value_uses_next_state": False, + "supervised_expectile_value_uses_td_or_bootstrap": False, + "supervised_expectile_value_uses_reward_arrays": False, + "pixel_scorer_policy_extraction": ( + "awr_dataset_action_weighted_log_likelihood" + if awr else "ddpgbc_actor_gradient_control"), + "pixel_scorer_actor_advantage_source": ( + "stop_gradient_live_twin_min_q_minus_preupdate_expectile_v" + if awr else None), + "pixel_scorer_actor_weight_formula": ( + "min(exp(alpha*(Q-V)),100)" if awr else None), + "pixel_scorer_actor_uses_dataset_actions_only": awr, + "pixel_scorer_supervision_regime": ( + "empirical_recorded_actions_plus_discount_conditioned_" + "occupancy_counterfactuals" + if counterfactual_support + else "empirical_recorded_actions_only"), + "pixel_scorer_and_occupancy_same_fused_step": True, + "pixel_scorer_and_actor_same_fused_step": True, + "pixel_scorer_gradient_updates_occupancy": False, + "occupancy_gradient_updates_pixel_scorer": False, + "batch_size": VISUAL_GCIQL_BATCH_SIZE, + "distill_ema_tau": PIXEL_SCORER_TARGET_UPDATE_TAU, + "distill_actor_actions": bool(counterfactual_support), + "distill_empirical_index_enabled": True, + "distill_empirical_index_weight": 1.0, + "distill_empirical_index_behavior_action_only": True, + "distill_empirical_index_counterfactual_action_source": ( + "none_awr_dataset_actions_only" + if awr + else "discount_conditioned_ema_occupancy" + if counterfactual_support + else "none_behavior_only_scorer_supervision"), + "distill_empirical_index_target_source": + "observed_same_trajectory_absorbing_first_passage_geometric_" + "successor_compact_z_through_frozen_index_reader", + "distill_empirical_index_horizon": + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount", + "distill_empirical_index_samples": 16, + "distill_empirical_index_blend_formula": + "recorded_successor_reader_expectation_only", + "distill_empirical_index_uses_reward_arrays": False, + "distill_empirical_index_uses_coordinates": False, + "distill_empirical_index_uses_td_or_bootstrap": False, + "distill_empirical_index_recorded_action_uses_occupancy": False, + "distill_empirical_index_counterfactual_uses_empirical": ( + False if counterfactual_support else None), + }) + return meta, reader + + +def _valid_metric_pixel_scorer_contract( + aux_allocation="uniform", counterfactual_support=False): + """Schema-13 reader-metric flow with the independent raw-pixel scorer.""" + meta, reader = _valid_pixel_reward_metric_contract(aux_allocation) + scorer_meta, _ = _valid_pixel_scorer_contract( + "ddpgbc_distill", counterfactual_support) + exact_keys = { + "actor_loss", + "alpha", + "expectile", + "actor_goal_dim_semantics", + "raw_pixels_update_actor_only", + "distill_scorer_input", + "distill_ema_tau", + "distill_actor_actions", + "batch_size", + "occupancy_gradient_updates_pixel_scorer", + } + meta.update({ + key: value + for key, value in scorer_meta.items() + if ( + key in exact_keys + or key.startswith("supervised_") + or key.startswith("pixel_scorer_") + or key.startswith("distill_empirical_index_") + ) + }) + meta.update({ + "reader_metric_pixel_scorer_combined": True, + "reader_metric_pixel_scorer_update_semantics": + "same_fused_step_separate_gradients", + }) + return meta, reader + + +class VisualOccupancyGateTest(unittest.TestCase): + def test_absorbing_geometric_target_is_exact(self): + # Raw future indices are [0, 1, 2], but first passage at goal=1 maps + # them to [0, 1, 1]. At gamma=.5 their normalized masses are 4/7, + # 2/7, 1/7, hence E[z] = 3/7. + latent = np.arange(3, dtype=np.float32)[:, None] + exact = _exact_absorbing_occupancy( + latent, + rows=np.asarray([0]), + goal_indices=np.asarray([1]), + ends=np.asarray([3, 3, 3]), + discount=0.5, + sample_count=8, + reader_probability=lambda future, goal: future[:, 0] / 2.0, + ) + np.testing.assert_allclose(exact["mean"], [[3.0 / 7.0]]) + np.testing.assert_allclose( + exact["reward_mean"], [3.0 / 14.0]) + + def test_hidden_exact_target_uses_h_for_distribution_cached_z_for_reward(self): + hidden = np.stack( + [np.arange(3), 100.0 + np.arange(3)], axis=1 + ).astype(np.float32) + cached_z = (10.0 * np.arange(3, dtype=np.float32))[:, None] + exact = _exact_absorbing_occupancy( + hidden, + rows=np.asarray([0]), + goal_indices=np.asarray([1]), + ends=np.asarray([3, 3, 3]), + discount=0.5, + sample_count=8, + reader_probability=lambda future, goal: future[:, 0] / 20.0, + reward_latents=cached_z, + ) + np.testing.assert_allclose( + exact["mean"], [[3.0 / 7.0, 100.0 + 3.0 / 7.0]]) + np.testing.assert_allclose( + exact["reward_mean"], [3.0 / 14.0]) + self.assertEqual(exact["samples"].shape[-1], 2) + + def test_energy_distance_is_zero_for_identical_samples(self): + rng = np.random.default_rng(3) + samples = rng.normal(size=(4, 8, 3)) + distance, ratio, spread = _energy_distance( + samples, samples, np.ones(3)) + np.testing.assert_allclose(distance, 0.0, atol=1e-12) + np.testing.assert_allclose(ratio, 0.0, atol=1e-12) + self.assertTrue(np.all(spread > 0.0)) + + def test_rank_agreement_detects_reversal(self): + left = np.asarray([[0.0, 1.0, 2.0], [2.0, 1.0, 0.0]]) + self.assertEqual(_pairwise_rank_agreement(left, left), 1.0) + self.assertEqual( + _pairwise_rank_agreement(left, -left), 0.0) + + def test_contract_requires_joint_pixels_only_non_td_flow(self): + meta, reader = _valid_contract() + contract = _assert_checkpoint_contract(meta, reader) + self.assertTrue(contract["pixels_only"]) + self.assertTrue(contract["occupancy_and_actor_jointly_updated"]) + self.assertFalse(contract["uses_td_or_bootstrap"]) + + mutations = ( + ("drop_proprio", False), + ("uses_td_or_bootstrap", True), + ("occupancy_and_actor_jointly_updated", False), + ("freeze_occupancy", True), + ("occupancy_model", "diffusion"), + ) + for key, value in mutations: + invalid = dict(meta) + invalid[key] = value + with self.subTest(key=key): + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_contract_accepts_only_precomposition_hidden_recursion(self): + meta, reader = _valid_hidden_contract() + contract = _assert_checkpoint_contract( + meta, reader, checkpoint_step=50) + self.assertEqual( + contract["checkpoint_mode"], + "staged_hidden_precomposition") + self.assertEqual( + contract["future_distribution_space"], + "frozen_encoder_hidden_h256") + self.assertFalse(contract["composition_has_activated"]) + + with self.assertRaisesRegex( + AssertionError, "not safely pre-composition"): + _assert_checkpoint_contract( + meta, reader, checkpoint_step=51) + + invalid = dict(meta) + invalid["latent_update"] = "adapter" + with self.assertRaisesRegex( + AssertionError, "frozen pixel representation"): + _assert_checkpoint_contract( + invalid, reader, checkpoint_step=50) + + invalid = dict(meta) + invalid["frozen_encoder_fc1_reward_projection"] = False + with self.assertRaises(AssertionError): + _assert_checkpoint_contract( + invalid, reader, checkpoint_step=50) + + def test_hidden_support_reconstructs_exact_mask_and_projection(self): + hidden = np.zeros((4, 256), np.float32) + hidden[:, 0] = np.arange(4, dtype=np.float32) + hidden[:, 1] = 1.0 + np.arange(4, dtype=np.float32) + hidden[:, 2] = 2.0 + meta, _ = _valid_hidden_contract() + meta.update({ + "occupancy_active_future_dims": 2, + "occupancy_constant_future_dims": 254, + }) + active, audit = _hidden_future_support_contract(hidden, meta) + self.assertEqual(int(active.sum()), 2) + self.assertEqual(audit["constant_dimensions"], 254) + + generated = np.full((1, 256), -5.0, np.float32) + generated[0, 1] = 3.0 + projected = _project_hidden_support( + generated, hidden.mean(axis=0), active) + self.assertEqual(float(projected[0, 0]), 0.0) + self.assertEqual(float(projected[0, 1]), 3.0) + self.assertEqual(float(projected[0, 2]), 2.0) + np.testing.assert_allclose( + projected[0, 3:], hidden.mean(axis=0)[3:]) + + invalid = dict(meta) + invalid["occupancy_active_future_dims"] = 3 + with self.assertRaisesRegex( + AssertionError, "active-future count"): + _hidden_future_support_contract(hidden, invalid) + + def test_raw_pixel_frozen_hidden_one_hop_contract(self): + meta, reader = _valid_pixel_hidden_contract("frozen") + contract = _assert_checkpoint_contract(meta, reader) + self.assertEqual( + contract["checkpoint_mode"], "pixel_hidden_one_hop") + self.assertTrue(contract["raw_pixel_actor"]) + self.assertTrue(contract["hidden_future"]) + self.assertEqual( + contract["future_distribution_space"], + "frozen_encoder_hidden_h256") + self.assertEqual( + contract["generated_hidden_support_projection"], + "relu_nonnegative_plus_constant_mean") + self.assertIsNone( + contract["saved_recursive_state_support_projection"]) + + for key, value in ( + ("schema_version", 9), + ("actor_state_feature", "encoder_hidden"), + ("actor_goal_feature", "encoder_hidden"), + ("final_actor_consumes_pixels", False), + ("actor_encoder_trainable", False), + ("occupancy_consumes_raw_pixels", True), + ("uses_td_or_bootstrap", True), + ("occupancy_uses_reward_labels", True), + ("occupancy_uses_simulator_coordinates", True), + ("uses_completion_or_forward_model", True)): + invalid = copy.deepcopy(meta) + invalid[key] = value + with self.subTest(key=key): + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + compact_pixel = copy.deepcopy(meta) + compact_pixel.update({ + "goal_hidden": False, + "future_feature": "compact_reward_predictive_z", + "occupancy_future_dim": 8, + "frozen_encoder_fc1_reward_projection": False, + }) + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(compact_pixel, reader) + + def test_raw_pixel_compact_reward_latent_one_hop_contract(self): + meta, reader = _valid_pixel_compact_contract() + contract = _assert_checkpoint_contract(meta, reader) + self.assertEqual( + contract["checkpoint_mode"], "pixel_compact_one_hop") + self.assertTrue(contract["raw_pixel_actor"]) + self.assertFalse(contract["hidden_future"]) + self.assertEqual( + contract["future_distribution_space"], + "compact_reward_predictive_z") + self.assertIsNone( + contract["generated_hidden_support_projection"]) + + for key, value in ( + ("state_feature", "compact_z"), + ("occupancy_goal_feature", "encoder_hidden"), + ("future_feature", "frozen_encoder_hidden_occupancy_state"), + ("occupancy_future_dim", 256), + ("occupancy_constant_future_dims", 1), + ("frozen_encoder_fc1_reward_projection", True)): + invalid = copy.deepcopy(meta) + invalid[key] = value + with self.subTest(key=key): + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_raw_pixel_reward_metric_one_hop_contract(self): + for allocation in ("uniform", "sqrt_h"): + with self.subTest(allocation=allocation): + meta, reader = _valid_pixel_reward_metric_contract( + allocation) + contract = _assert_checkpoint_contract(meta, reader) + self.assertEqual( + contract["checkpoint_mode"], + "pixel_reward_metric_one_hop") + self.assertTrue(contract["reward_metric_future"]) + self.assertFalse(contract["hidden_future"]) + self.assertEqual( + contract["future_distribution_space"], + "decoded_compact_reward_predictive_z_from_reader_metric_u", + ) + invalid = copy.deepcopy(meta) + invalid["occupancy_target_metric_diagonal"][0] *= 2.0 + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_schema12_empirical_anchor_is_absorbing_and_non_td(self): + meta, reader = _valid_pixel_hidden_contract( + "frozen", protected=True, hit_weight=0.25) + meta.update({ + "schema_version": 12, + "distill_empirical_index_enabled": True, + "distill_empirical_index_weight": 1.0, + "distill_empirical_index_behavior_action_only": True, + "distill_empirical_index_counterfactual_action_source": + "discount_conditioned_ema_occupancy", + "distill_empirical_index_target_source": + "observed_same_trajectory_absorbing_first_passage_" + "geometric_successor_compact_z_through_frozen_index_reader", + "distill_empirical_index_horizon": + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount", + "distill_empirical_index_samples": 16, + "distill_empirical_index_blend_formula": + "(1-weight)*ema_occupancy_reader_expectation" + "+weight*recorded_successor_reader_expectation", + "distill_empirical_index_uses_reward_arrays": False, + "distill_empirical_index_uses_coordinates": False, + "distill_empirical_index_uses_td_or_bootstrap": False, + }) + contract = _assert_checkpoint_contract(meta, reader) + self.assertEqual(contract["checkpoint_mode"], + "pixel_hidden_one_hop") + + for key, value in ( + ("distill_empirical_index_enabled", False), + ("distill_empirical_index_weight", 0.0), + ("distill_empirical_index_behavior_action_only", False), + ("distill_empirical_index_target_source", + "raw_unabsorbed_geometric_successor"), + ("distill_empirical_index_uses_reward_arrays", True), + ("distill_empirical_index_uses_coordinates", True), + ("distill_empirical_index_uses_td_or_bootstrap", True)): + invalid = copy.deepcopy(meta) + invalid[key] = value + with self.subTest(key=key): + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_schema13_pixel_scorer_is_empirical_non_td_and_fail_closed(self): + for actor_loss, counterfactual_support in ( + ("ddpgbc_distill", False), + ("ddpgbc_distill", True), + ("awr_distill", False)): + with self.subTest( + actor_loss=actor_loss, + counterfactual_support=counterfactual_support): + meta, reader = _valid_pixel_scorer_contract( + actor_loss, counterfactual_support) + contract = _assert_checkpoint_contract(meta, reader) + self.assertTrue(contract["raw_pixel_actor"]) + + mutations = ( + ("distill_empirical_index_weight", 0.5), + ("distill_empirical_index_recorded_action_uses_occupancy", True), + ("supervised_scalar_scorer_uses_proprio", True), + ("supervised_scalar_scorer_uses_coordinates", True), + ("supervised_scalar_scorer_uses_reward_arrays", True), + ("supervised_scalar_scorer_uses_td_or_bootstrap", True), + ("supervised_expectile_value_uses_next_state", True), + ("supervised_expectile_value_uses_td_or_bootstrap", True), + ("pixel_scorer_and_occupancy_same_fused_step", False), + ("pixel_scorer_and_actor_same_fused_step", False), + ("batch_size", 4096), + ("distill_ema_tau", 0.01), + ("supervised_scalar_scorer_target_update_source", + "preupdate_live_twin_pixel_scorer"), + ("supervised_scalar_scorer_target_update_timing", + "before_current_gradient_update"), + ("supervised_scalar_scorer_target_update_tau", 0.01), + ) + meta, reader = _valid_pixel_scorer_contract() + for key, value in mutations: + with self.subTest(key=key): + invalid = copy.deepcopy(meta) + invalid[key] = value + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_schema13_combines_reader_metric_flow_and_pixel_scorer(self): + for allocation, counterfactual_support in ( + ("uniform", False), + ("sqrt_h", True)): + with self.subTest( + allocation=allocation, + counterfactual_support=counterfactual_support): + meta, reader = _valid_metric_pixel_scorer_contract( + allocation, counterfactual_support) + contract = _assert_checkpoint_contract(meta, reader) + self.assertEqual( + contract["checkpoint_mode"], + "pixel_reward_metric_one_hop") + self.assertTrue(contract["reward_metric_future"]) + self.assertTrue(contract["raw_pixel_scorer"]) + self.assertTrue( + contract["reader_metric_pixel_scorer_combined"]) + + meta, reader = _valid_metric_pixel_scorer_contract() + for key, value in ( + ("reader_metric_pixel_scorer_combined", False), + ("reader_metric_pixel_scorer_update_semantics", "coupled"), + ("occupancy_target_uses_td_or_bootstrap", True), + ("supervised_scalar_scorer_uses_td_or_bootstrap", True)): + with self.subTest(key=key): + invalid = copy.deepcopy(meta) + invalid[key] = value + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_strict_gcbc_actor_reference_and_checkpoint_are_pinned(self): + meta, reader = _valid_pixel_hidden_contract("frozen") + with tempfile.TemporaryDirectory() as directory: + reference_root = os.path.join(directory, "impls") + for index, relative_path in enumerate( + VISUAL_ACTOR_REFERENCE_FILES): + path = os.path.join(reference_root, relative_path) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as file: + file.write(f"reference-{index}".encode()) + init_path = os.path.join(directory, "gcbc.pkl") + with open(init_path, "wb") as file: + file.write(b"strict-non-td-gcbc") + meta.update({ + "actor_encoder_initialization": + "strict_non_td_gcbc_then_jointly_trainable", + "pixel_actor_init": { + "format": "visual_gcbc_params_v1", + "step": 300000, + "reference_root": reference_root, + "reference_sha256": + _visual_actor_reference_sha256(reference_root), + "uses_td_or_bootstrap": False, + "path": init_path, + "sha256": _sha256_file(init_path), + "optimizer_state_loaded": False, + "actor_remains_trainable": True, + }, + }) + contract = _assert_checkpoint_contract( + meta, reader, active_reference_root=reference_root) + actor_reference = contract["pixel_actor_reference"] + self.assertTrue( + actor_reference["init_checkpoint_sha256_verified"]) + self.assertTrue( + actor_reference["active_reference_sha256_verified"]) + + wrong_hash = copy.deepcopy(meta) + wrong_hash["pixel_actor_init"]["reference_sha256"] = "0" * 64 + with self.assertRaisesRegex( + AssertionError, "reference SHA-256"): + _assert_checkpoint_contract( + wrong_hash, reader, + active_reference_root=reference_root) + + other_root = os.path.join(directory, "other_impls") + os.makedirs(other_root) + with self.assertRaisesRegex( + AssertionError, "reference root"): + _assert_checkpoint_contract( + meta, reader, active_reference_root=other_root) + + def test_raw_pixel_rich_adapter_keeps_frozen_hidden_future(self): + meta, reader = _valid_pixel_hidden_contract("rich_adapter") + contract = _assert_checkpoint_contract(meta, reader) + self.assertEqual( + contract["future_distribution_space"], + "frozen_encoder_hidden_h256") + self.assertEqual(meta["reward_goal_feature"], + "compact_reward_predictive_z") + self.assertEqual(meta["reward_reader_dim"], reader["zdim"]) + + mutations = ( + ("future_feature", "joint_encoder_hidden_adapter"), + ("reward_goal_feature", "joint_encoder_hidden_adapter"), + ("occupancy_future_dim", 8), + ("reward_reader_dim", 256), + ("latent_aux_target", "coordinates"), + ("latent_reader_model", "mlp"), + ("latent_index_negative_contract", + "cross_episode_random_negatives"), + ("adapter_feature_dim", 8), + ) + for key, value in mutations: + invalid = copy.deepcopy(meta) + invalid[key] = value + with self.subTest(key=key): + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_raw_pixel_hidden_support_is_applied_with_recursion_off(self): + hidden = np.zeros((5, 256), np.float32) + hidden[:, 0] = np.arange(5, dtype=np.float32) + hidden[:, 1] = 2.0 + np.arange(5, dtype=np.float32) + hidden[:, 2:] = 3.0 + meta, _ = _valid_pixel_hidden_contract() + meta.update({ + "occupancy_active_future_dims": 2, + "occupancy_constant_future_dims": 254, + }) + active, audit = _hidden_future_support_contract(hidden, meta) + self.assertEqual(int(active.sum()), 2) + self.assertEqual( + audit["projection_source"], + "schema10_hidden_future_sampling_contract_recursion_off") + self.assertIsNone( + audit["saved_recursive_state_support_projection"]) + + generated = np.full((2, 256), -7.0, np.float32) + projected = _project_hidden_support( + generated, hidden.mean(axis=0), active) + np.testing.assert_array_equal(projected[:, :2], 0.0) + np.testing.assert_allclose(projected[:, 2:], 3.0) + + invalid = copy.deepcopy(meta) + invalid["recursive_state_support_projection"] = ( + "relu_nonnegative_plus_constant_mean") + with self.assertRaises(AssertionError): + _hidden_future_support_contract(hidden, invalid) + + def test_protected_gamma_beta_contract_reconstructs_all_allocations(self): + meta, reader = _valid_pixel_hidden_contract( + "frozen", protected=True) + _assert_protected_endpoint_contract(meta) + contract = _assert_checkpoint_contract(meta, reader) + self.assertEqual( + contract["checkpoint_mode"], "pixel_hidden_one_hop") + + mutations = ( + ("gamma_sampler", "stratified_bins"), + ("gamma_sampling_importance_weighted", True), + ("gamma_task_rows_per_occ_batch", 1228), + ("gamma_aux_rows_per_occ_batch", [29, 39, 57, 80]), + ("protected_endpoint_actor_rows_by_discount", + [614, 308, 14, 20, 28, 40]), + ("protected_endpoint_normalizer_discount_rows", + [11999, 6001, 276, 391, 552, 781]), + ("occ_reader_metric_uses_reward_arrays", True), + ("occ_reader_metric_uses_coordinates", True), + ("occ_reader_metric_uses_td_or_bootstrap", True), + ("occ_reader_hit_importance_weighted", True), + ("occ_reader_hit_uses_reward_arrays", True), + ("occ_reader_hit_uses_coordinates", True), + ("occ_reader_hit_uses_td_or_bootstrap", True), + ) + for key, value in mutations: + invalid = copy.deepcopy(meta) + invalid[key] = value + with self.subTest(key=key): + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_reward_metric_gate_reconstructs_uniform_and_sqrt_allocations(self): + for allocation in ("uniform", "sqrt_h"): + with self.subTest(allocation=allocation): + meta = _valid_reward_metric_endpoint_meta(allocation) + _assert_reward_metric_endpoint_contract(meta) + invalid = copy.deepcopy(meta) + invalid["gamma_aux_rows_per_occ_batch"][0] += 1 + with self.assertRaises(AssertionError): + _assert_reward_metric_endpoint_contract(invalid) + + def test_reward_metric_gate_audits_configurable_task_beta_masses(self): + meta = _valid_reward_metric_endpoint_meta("uniform") + meta["gamma_task_fraction"] = 0.40 + meta["rec_beta_sample_prob"] = 0.20 + meta["reward_metric_endpoint_task_fraction"] = 0.40 + meta["reward_metric_endpoint_beta_fraction"] = 0.20 + meta["reward_metric_endpoint_aux_fraction"] = 0.40 + train = reward_metric_endpoint_batch_plan( + 2048, 0.99, 0.98, (8, 16, 32, 64), + 0.40, 0.20, "uniform") + normalizer = reward_metric_endpoint_batch_plan( + 20000, 0.99, 0.98, (8, 16, 32, 64), + 0.40, 0.20, "uniform") + meta["gamma_task_rows_per_occ_batch"] = train["task_rows"] + meta["gamma_beta_rows_per_occ_batch"] = train["beta_rows"] + meta["gamma_aux_rows_per_occ_batch"] = list( + train["aux_rows_by_horizon"]) + meta["reward_metric_endpoint_normalizer_discount_rows"] = [ + normalizer["task_rows"], + normalizer["beta_rows"], + *normalizer["aux_rows_by_horizon"], + ] + _assert_reward_metric_endpoint_contract(meta) + + def test_protected_endpoint_hit_is_index_only_and_unweighted(self): + meta, reader = _valid_pixel_hidden_contract( + "rich_adapter", protected=True, hit_weight=0.25) + _assert_checkpoint_contract(meta, reader) + self.assertTrue(meta["occ_reader_hit_enabled"]) + self.assertFalse(meta["occ_reader_metric_enabled"]) + + for key, value in ( + ("occ_reader_metric_weight", 0.1), + ("occ_reader_metric_enabled", True), + ("occ_reader_geometry_enabled", False), + ("occ_reader_metric_model", "mlp"), + ("occ_reader_metric_target", "reward"), + ("occ_reader_hit_endpoint_weights", [0.4, 0.6]), + ("occ_reader_hit_take_hit_probability", 0.4), + ("occ_reader_hit_uses_index_relabeling", False), + ("occ_reader_hit_action_contrast_weights_changed", True)): + invalid = copy.deepcopy(meta) + invalid[key] = value + with self.subTest(key=key): + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + def test_pinned_pixel_source_reads_three_arrays_and_derives_view(self): + rng = np.random.default_rng(91) + observations = rng.integers( + 0, 256, size=(6, 12, 12, 3), dtype=np.uint8) + actions = rng.normal(size=(6, 2)).astype(np.float32) + actions = np.clip(actions, -1.0, 1.0) + terminals = np.asarray( + [False, False, True, False, False, True]) + with tempfile.TemporaryDirectory() as directory: + dataset_path = os.path.join(directory, "pixels.npz") + np.savez_compressed( + dataset_path, + observations=observations, + actions=actions, + terminals=terminals, + qpos=np.zeros((6, 9), np.float32), + qvel=np.zeros((6, 9), np.float32), + ) + digest = _sha256_file(dataset_path) + meta, _ = _valid_pixel_hidden_contract() + meta["pixel_actor_dataset"].update({ + "path": dataset_path, + "sha256": digest, + "observation_shape": [12, 12, 3], + "action_shape": [2], + "row_count": 6, + "valid_transition_count": 4, + }) + meta["pixel_artifact_provenance"]["pixel_dataset"] = { + "path": dataset_path, + "sha256": digest, + } + loaded, valid_indices, audit = ( + _load_pinned_pixel_actor_dataset( + meta, actions, terminals)) + np.testing.assert_array_equal(loaded, observations) + np.testing.assert_array_equal(valid_indices, [0, 1, 3, 4]) + self.assertEqual( + audit["physical_arrays_read"], + ["actions", "observations", "terminals"]) + self.assertEqual(audit["forbidden_arrays_read"], []) + self.assertEqual( + audit["physical_arrays_available"], + ["actions", "observations", "qpos", "qvel", "terminals"]) + self.assertEqual( + audit["forbidden_arrays_available"], ["qpos", "qvel"]) + self.assertEqual( + audit["processed_dataset_view_arrays"], + ["actions", "observations", "terminals", "valids"]) + self.assertTrue(audit["processed_valids_reconstructed"]) + self.assertTrue( + audit["processed_compact_terminals_reconstructed"]) + self.assertTrue( + audit["duplicate_latent_action_or_terminal_arrays_read"]) + + ( + strict_loaded, + strict_actions, + strict_terminals, + strict_valid_indices, + strict_audit, + ) = _load_pinned_pixel_source(meta) + np.testing.assert_array_equal(strict_loaded, observations) + np.testing.assert_array_equal(strict_actions, actions) + np.testing.assert_array_equal(strict_terminals, terminals) + np.testing.assert_array_equal( + strict_valid_indices, [0, 1, 3, 4]) + self.assertEqual( + strict_audit["physical_arrays_read"], + ["actions", "observations", "terminals"]) + self.assertEqual(strict_audit["forbidden_arrays_read"], []) + self.assertFalse( + strict_audit[ + "duplicate_latent_action_or_terminal_arrays_read"]) + + misaligned = actions.copy() + misaligned[0, 0] = np.nextafter( + misaligned[0, 0], np.float32(np.inf)) + with self.assertRaisesRegex( + AssertionError, "actions are not row-aligned"): + _load_pinned_pixel_actor_dataset( + meta, misaligned, terminals) + + invalid = copy.deepcopy(meta) + invalid["pixel_artifact_provenance"][ + "pixel_dataset"]["sha256"] = "0" * 64 + invalid["pixel_actor_dataset"]["sha256"] = "0" * 64 + with self.assertRaisesRegex( + AssertionError, "SHA-256 does not match"): + _load_pinned_pixel_actor_dataset( + invalid, actions, terminals) + + extra_path = os.path.join(directory, "pixels_with_mystery.npz") + np.savez_compressed( + extra_path, + observations=observations, + actions=actions, + terminals=terminals, + qpos=np.zeros((6, 9), np.float32), + qvel=np.zeros((6, 9), np.float32), + mystery=np.zeros((6, 1), np.float32), + ) + extra = copy.deepcopy(meta) + extra_digest = _sha256_file(extra_path) + extra["pixel_actor_dataset"].update({ + "path": extra_path, + "sha256": extra_digest, + }) + extra["pixel_artifact_provenance"]["pixel_dataset"] = { + "path": extra_path, + "sha256": extra_digest, + } + with self.assertRaisesRegex( + AssertionError, "unexpected array"): + _load_pinned_pixel_actor_dataset( + extra, actions, terminals) + + def test_exact_impala_pixel_actor_params_are_queryable_on_cpu(self): + import jax + import jax.numpy as jnp + + actor = _pixel_actor_definition(action_dim=2) + observations = np.zeros((2, 16, 16, 3), np.uint8) + goals = np.full((2, 16, 16, 3), 127, np.uint8) + params = actor.init( + jax.random.PRNGKey(3), + jnp.asarray(observations), + jnp.asarray(goals), + )["params"] + expected = actor.apply( + {"params": params}, + jnp.asarray(observations), + jnp.asarray(goals), + ).mode() + actual = jax.jit( + lambda p, s, g: _pixel_actor_mode(p, s, g, 2))( + params, + jnp.asarray(observations), + jnp.asarray(goals), + ) + self.assertEqual(actual.shape, (2, 2)) + self.assertTrue(np.all(np.isfinite(np.asarray(actual)))) + np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=1e-8) + + def test_sha256_file(self): + with tempfile.NamedTemporaryFile() as file: + file.write(b"abc") + file.flush() + self.assertEqual( + _sha256_file(file.name), + "ba7816bf8f01cfea414140de5dae2223b00361a396" + "177a9cb410ff61f20015ad") + + def test_contract_requires_canonical_coordinate_free_metric(self): + meta, reader = _valid_contract() + invalid_reader = dict(reader) + invalid_reader["reader_model"] = "mlp" + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(meta, invalid_reader) + + invalid_reader = dict(reader) + invalid_reader["uses_coordinates_for_training"] = True + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(meta, invalid_reader) + + invalid_reader = dict(reader) + invalid_reader["uses_reward_arrays"] = True + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(meta, invalid_reader) + + def test_actor_query_contrast_contract_is_fail_closed(self): + meta, reader = _valid_contract() + meta.update({ + "occ_action_contrast_weight": 0.5, + "occ_action_negative": "actor_local", + "occ_action_negative_local_k": 2, + "occ_action_negative_candidate_count": 3, + "occ_action_negative_policy": + "stop_gradient_live_preupdate_actor_mode_plus_local_gaussian", + "occ_action_negative_actor_source": "live_preupdate_actor", + "occ_action_negative_support_start_step": 0, + "occ_action_negative_actions_stop_gradient": True, + "occ_action_negative_common_random_numbers": True, + "occ_action_negative_updates_actor": False, + "occ_action_negative_counterfactual_target": False, + "occ_action_negative_interpretation": + "anti_exploitation_likelihood_ranking_not_counterfactual_" + "occupancy", + "occupancy_supervision": + "monte_carlo_geometric_futures_plus_detached_actor_query_" + "likelihood_ranking", + "occupancy_training_policy": + "offline_behavior_futures_with_detached_live_actor_query_" + "negatives", + }) + contract = _assert_checkpoint_contract(meta, reader) + self.assertTrue(contract["actor_query_contrast_trained"]) + + invalid = dict(meta) + invalid["occ_action_negative_actions_stop_gradient"] = False + with self.assertRaises(AssertionError): + _assert_checkpoint_contract(invalid, reader) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_occupancy_recipe.py b/gen_q_rsm/ogbench_genq/test_visual_occupancy_recipe.py new file mode 100644 index 0000000000000000000000000000000000000000..10e8902836b9376f2c46a734209b2458b817b921 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_occupancy_recipe.py @@ -0,0 +1,352 @@ +"""Focused tests for the visual occupancy goal and reader-metric recipe.""" + +import unittest + +import numpy as np + +from ogbench_genq.rsm import ( + actor_uniform_goal_indices, + backfill_protected_endpoint_metadata, + endpoint_future_hit_mask, + endpoint_hit_reader_loss, + exact_batch_fraction_count, + exact_batch_fraction_mask, + occupancy_base_and_endpoint_hit_loss, + protected_endpoint_batch_plan, + decode_reader_metric_future, + encode_reader_metric_future, + reader_metric_coordinate_diagonal, + reader_metric_flow_errors, + reader_metric_pullback_trace, + reward_metric_endpoint_batch_plan, +) + + +class OccupancyGoalMixtureTest(unittest.TestCase): + def test_exact_batch_fraction_has_requested_count(self): + permutation = np.asarray([7, 1, 5, 3, 9, 0, 8, 2, 6, 4]) + mask = exact_batch_fraction_mask( + 10, 0.5, permutation, array_module=np) + self.assertEqual(exact_batch_fraction_count(10, 0.5), 5) + self.assertEqual(int(mask.sum()), 5) + self.assertEqual(mask.dtype, np.dtype(bool)) + + def test_zero_fraction_preserves_all_value_goal_rows(self): + mask = exact_batch_fraction_mask( + 8, 0.0, np.arange(8)[::-1], array_module=np) + np.testing.assert_array_equal(mask, np.zeros(8, dtype=bool)) + + def test_actor_uniform_goals_are_inclusive_future_indices(self): + rows = np.asarray([0, 5, 9], np.int32) + ends = np.asarray([10, 10, 10], np.int32) + uniforms = np.asarray([1.0, 0.5, 0.0], np.float32) + goals = actor_uniform_goal_indices( + rows, ends, uniforms, array_module=np) + np.testing.assert_array_equal(goals, np.asarray([1, 8, 9])) + self.assertTrue(np.all(goals >= np.minimum(rows + 1, ends - 1))) + self.assertTrue(np.all(goals < ends)) + + def test_invalid_fraction_fails_closed(self): + with self.assertRaises(ValueError): + exact_batch_fraction_count(32, 1.01) + + +class ReaderMetricFlowErrorTest(unittest.TestCase): + def test_compact_identity_matches_normalized_weighted_error(self): + residual = np.asarray([ + [1.0, 2.0, 3.0], + [-2.0, 1.0, 0.5], + ], np.float32) + target_scale = np.asarray([2.0, 3.0, 4.0], np.float32) + metric_scale = target_scale.copy() + metric_weight = np.asarray([1.0, 2.0, 3.0], np.float32) + auxiliary_weight = 0.5 + actual = reader_metric_flow_errors( + residual, + target_scale, + np.eye(3, dtype=np.float32), + metric_scale, + metric_weight, + np.ones(3, np.float32), + auxiliary_weight, + array_module=np, + ) + base = np.mean(np.square(residual), axis=-1) + metric = np.sum( + np.square(residual) * metric_weight, axis=-1 + ) / metric_weight.sum() + expected = ( + base + auxiliary_weight * metric + ) / (1.0 + auxiliary_weight) + np.testing.assert_allclose(actual, expected, rtol=1e-6) + + def test_reader_weight_global_scale_does_not_change_loss(self): + residual = np.asarray([[0.5, -1.5]], np.float32) + kwargs = dict( + residual=residual, + target_scale=np.asarray([0.2, 0.4], np.float32), + reward_projection=np.eye(2, dtype=np.float32), + metric_scale=np.asarray([0.1, 0.3], np.float32), + active_mask=np.ones(2, np.float32), + auxiliary_weight=1.0, + array_module=np, + ) + first = reader_metric_flow_errors( + metric_weight=np.asarray([1.0, 4.0], np.float32), + **kwargs, + ) + second = reader_metric_flow_errors( + metric_weight=np.asarray([7.0, 28.0], np.float32), + **kwargs, + ) + np.testing.assert_allclose(first, second, rtol=1e-6) + + def test_hidden_projection_uses_raw_velocity_units(self): + residual = np.asarray([[1.0, -2.0]], np.float32) + target_scale = np.asarray([2.0, 0.5], np.float32) + projection = np.asarray([[1.0], [3.0]], np.float32) + metric_scale = np.asarray([0.25], np.float32) + actual = reader_metric_flow_errors( + residual, + target_scale, + projection, + metric_scale, + np.asarray([2.0], np.float32), + np.ones(2, np.float32), + 1.0, + array_module=np, + ) + base = np.mean(np.square(residual), axis=-1) + projected = ( + (residual * target_scale) @ projection + )[:, 0] / metric_scale[0] + pullback_trace = reader_metric_pullback_trace( + target_scale, + projection, + metric_scale, + np.asarray([2.0], np.float32), + np.ones(2, np.float32), + array_module=np, + ) + metric = 2.0 * np.square(projected) / pullback_trace + expected = 0.5 * (base + metric) + np.testing.assert_allclose(actual, expected, rtol=1e-6) + + def test_hidden_pullback_normalization_has_unit_isotropic_mean(self): + # These rows have empirical second moment I, so both the ordinary + # standardized-coordinate MSE and any positive-semidefinite reader + # pullback metric must average exactly one after trace normalization. + residual = np.sqrt(2.0) * np.asarray([ + [1.0, 0.0], + [-1.0, 0.0], + [0.0, 1.0], + [0.0, -1.0], + ], np.float32) + actual = reader_metric_flow_errors( + residual, + np.asarray([2.0, 0.5], np.float32), + np.asarray([[1.0, -0.5], [3.0, 2.0]], np.float32), + np.asarray([0.25, 1.5], np.float32), + np.asarray([2.0, 7.0], np.float32), + np.ones(2, np.float32), + 3.0, + array_module=np, + ) + np.testing.assert_allclose(actual.mean(), 1.0, rtol=1e-6) + + def test_zero_auxiliary_is_exact_base_masked_mse(self): + residual = np.asarray([[1.0, 99.0, 3.0]], np.float32) + actual = reader_metric_flow_errors( + residual, + np.ones(3, np.float32), + np.eye(3, dtype=np.float32), + np.ones(3, np.float32), + np.ones(3, np.float32), + np.asarray([1.0, 0.0, 1.0], np.float32), + 0.0, + array_module=np, + ) + np.testing.assert_allclose(actual, np.asarray([5.0])) + + +class ProtectedEndpointSamplerTest(unittest.TestCase): + def test_exact_2048_allocation_and_cross_stratification(self): + plan = protected_endpoint_batch_plan( + 2048, 0.99, 0.98, (8, 16, 32, 64)) + self.assertEqual( + (plan["task_rows"], plan["beta_rows"], plan["aux_rows"]), + (1229, 614, 205), + ) + self.assertEqual( + plan["aux_rows_by_horizon"], (28, 40, 57, 80)) + self.assertEqual( + plan["actor_rows_by_discount"], + (615, 307, 14, 20, 28, 40), + ) + self.assertEqual( + plan["value_rows_by_discount"], + (614, 307, 14, 20, 29, 40), + ) + self.assertEqual(plan["actor_rows"], 1024) + self.assertEqual(plan["value_rows"], 1024) + for count, actor, value in zip( + plan["discount_group_rows"], + plan["actor_rows_by_discount"], + plan["value_rows_by_discount"]): + self.assertEqual(actor + value, count) + self.assertLessEqual(abs(actor - value), 1) + + def test_beta_duplicate_is_excluded_before_aux_allocation(self): + plan = protected_endpoint_batch_plan( + 2048, 0.99, 0.98, (8, 16, 32, 50, 64)) + self.assertEqual(plan["excluded_beta_horizons"], (50.0,)) + self.assertEqual(plan["aux_horizons"], (8.0, 16.0, 32.0, 64.0)) + self.assertEqual( + plan["aux_rows_by_horizon"], (28, 40, 57, 80)) + self.assertEqual( + int(np.isclose(plan["discounts"], 0.98).sum()), 614) + + +class RewardMetricCoordinateTest(unittest.TestCase): + def test_reader_coordinate_round_trip_is_exact(self): + scale = np.asarray([0.5, 2.0, 0.25], np.float32) + weight = np.asarray([4.0, 9.0, 0.25], np.float32) + diagonal = reader_metric_coordinate_diagonal(scale, weight) + np.testing.assert_allclose( + diagonal, np.asarray([4.0, 1.5, 2.0], np.float32)) + goal = np.asarray([[1.0, -2.0, 0.5]], np.float32) + future = np.asarray([ + [2.0, 0.0, -1.0], + [-3.0, 4.0, 2.5], + ], np.float32) + coordinate = encode_reader_metric_future( + future, goal, diagonal) + decoded = decode_reader_metric_future( + coordinate, goal, 1.0 / diagonal) + np.testing.assert_allclose(decoded, future, rtol=1e-6, atol=1e-6) + + def test_noninvertible_reader_metric_fails_closed(self): + with self.assertRaisesRegex(ValueError, "strictly positive"): + reader_metric_coordinate_diagonal( + np.ones(3, np.float32), + np.asarray([1.0, 0.0, 2.0], np.float32)) + + def test_default_and_sqrt_h_endpoint_allocations(self): + uniform = reward_metric_endpoint_batch_plan( + 2048, 0.99, 0.98, (8, 16, 32, 64)) + self.assertEqual( + (uniform["task_rows"], uniform["beta_rows"], + uniform["aux_rows_by_horizon"]), + (1024, 512, (128, 128, 128, 128))) + self.assertEqual(uniform["aux_allocation"], "uniform") + + prioritized = reward_metric_endpoint_batch_plan( + 2048, 0.99, 0.98, (8, 16, 32, 64), + 0.50, 0.25, "sqrt_h") + self.assertEqual( + prioritized["aux_rows_by_horizon"], + (71, 100, 141, 200)) + self.assertEqual(prioritized["aux_allocation"], "sqrt_h") + self.assertEqual(sum(prioritized["aux_rows_by_horizon"]), 512) + + def test_task_and_beta_masses_are_configurable_exact_counts(self): + plan = reward_metric_endpoint_batch_plan( + 1000, 0.99, 0.98, (8, 16, 32, 64), + task_fraction=0.40, + beta_fraction=0.20, + aux_allocation="uniform", + ) + self.assertEqual(plan["task_rows"], 400) + self.assertEqual(plan["beta_rows"], 200) + self.assertEqual(plan["aux_rows_by_horizon"], (100, 100, 100, 100)) + with self.assertRaises(ValueError): + reward_metric_endpoint_batch_plan( + 100, 0.99, 0.98, (8, 16), 0.8, 0.2) + + +class EndpointFutureHitReaderTest(unittest.TestCase): + def test_mask_excludes_current_past_cross_and_miss_rows(self): + rows = np.asarray([2, 2, 2, 2, 2, 7], np.int32) + goals = np.asarray([4, 2, 1, 6, 4, 8], np.int32) + row_ends = np.asarray([6, 6, 6, 6, 6, 9], np.int32) + take_hit = np.asarray([1, 1, 1, 1, 0, 1], bool) + actual = endpoint_future_hit_mask( + rows, goals, row_ends, take_hit, array_module=np) + np.testing.assert_array_equal( + actual, np.asarray([1, 0, 0, 0, 0, 1], bool)) + + def test_mask_shape_mismatch_fails_closed(self): + with self.assertRaises(ValueError): + endpoint_future_hit_mask( + np.arange(2), np.arange(3), np.arange(2), + np.ones(2, bool)) + + def test_endpoint_loss_is_unweighted_and_excludes_aux(self): + errors = np.asarray([2.0, 6.0, 10.0, 100.0]) + discounts = np.asarray([0.99, 0.99, 0.98, 0.875]) + hit = np.ones(4, bool) + actual = endpoint_hit_reader_loss( + errors, hit, discounts, 0.99, 0.98, array_module=np) + self.assertEqual(float(actual), 7.0) + missing_beta = endpoint_hit_reader_loss( + errors, hit & (discounts != 0.98), discounts, + 0.99, 0.98, array_module=np) + self.assertEqual(float(missing_beta), 2.0) + no_hits = endpoint_hit_reader_loss( + errors, np.zeros(4, bool), discounts, + 0.99, 0.98, array_module=np) + self.assertEqual(float(no_hits), 0.0) + + def test_base_mle_is_invariant_and_auxiliary_is_additive(self): + base_errors = np.asarray([1.0, 2.0, 4.0, 8.0]) + importance_weights = np.asarray([0.5, 2.0, 0.25, 1.0]) + reader_errors = np.asarray([2.0, 6.0, 10.0, 100.0]) + discounts = np.asarray([0.99, 0.99, 0.98, 0.875]) + hit = np.ones(4, bool) + control, base0, hit0 = occupancy_base_and_endpoint_hit_loss( + base_errors, importance_weights, reader_errors, hit, + discounts, 0.99, 0.98, 0.0, array_module=np) + treated, base1, hit1 = occupancy_base_and_endpoint_hit_loss( + base_errors, importance_weights, reader_errors, hit, + discounts, 0.99, 0.98, 0.25, array_module=np) + self.assertEqual(float(control), 3.375) + self.assertEqual(float(base0), 3.375) + self.assertEqual(float(hit0), 0.0) + self.assertEqual(float(base1), 3.375) + self.assertEqual(float(hit1), 7.0) + self.assertEqual(float(treated), 5.125) + with self.assertRaises(ValueError): + occupancy_base_and_endpoint_hit_loss( + base_errors, importance_weights, reader_errors, hit, + discounts, 0.99, 0.98, -0.1, array_module=np) + + +class ProtectedEndpointResumeMetadataTest(unittest.TestCase): + def test_legacy_metadata_backfills_disabled_recipe(self): + actual = backfill_protected_endpoint_metadata( + {"occ_reader_metric_enabled": False}) + self.assertFalse(actual["protected_endpoint_sampler"]) + self.assertIsNone(actual["protected_endpoint_aux_allocation"]) + self.assertFalse(actual["occ_reader_geometry_enabled"]) + self.assertEqual(actual["occ_reader_hit_weight"], 0.0) + self.assertFalse(actual["occ_reader_hit_enabled"]) + self.assertFalse(actual["occ_reader_hit_importance_weighted"]) + self.assertFalse(actual["occ_reader_hit_uses_reward_arrays"]) + self.assertFalse(actual["occ_reader_hit_uses_coordinates"]) + self.assertFalse(actual["occ_reader_hit_uses_td_or_bootstrap"]) + + def test_nondefault_saved_provenance_is_not_overwritten(self): + saved = { + "protected_endpoint_sampler": True, + "protected_endpoint_aux_allocation": "kept", + "occ_reader_hit_weight": 0.25, + "occ_reader_hit_enabled": True, + "occ_reader_geometry_enabled": True, + } + actual = backfill_protected_endpoint_metadata(saved) + for key, value in saved.items(): + self.assertEqual(actual[key], value) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_pixel_actor.py b/gen_q_rsm/ogbench_genq/test_visual_pixel_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..e79ba65a63aa6f397676635f2389bbb0db01094a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_pixel_actor.py @@ -0,0 +1,911 @@ +"""CPU-only contract tests for the trainable visual RSM pixel actor. + +These tests exercise the two fail-closed boundaries without loading OGBench, +MuJoCo, an accelerator, or the full visual dataset: + +* raw RGB rows must be exactly aligned with the latent occupancy artifact; +* an optional actor warm start must be the dedicated non-TD visual GCBC + export, never a structurally compatible GCIQL actor. +""" + +import ast +import inspect +import os +from pathlib import Path +import subprocess +import sys +import textwrap +import unittest + +os.environ.setdefault("JAX_PLATFORMS", "cpu") +os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") + +import jax +import jax.numpy as jnp +import numpy as np + +from ogbench_genq.rsm import ( + PIXEL_ACTOR_FORBIDDEN_KEYS, + audit_visual_pixel_actor_dataset, + backfill_actor_input_metadata, + run_rsm, + truncated_geometric_future_indices, + validate_visual_gcbc_actor_init, + validate_visual_pixel_actor_run_contract, + validate_visual_pixel_scorer_run_contract, + visual_actor_shared_random_crop, +) + + +ENV = "visual-cube-single-play-v0" + + +def _pixel_dataset(): + actions = np.asarray([ + [-1.5, 0.25], + [0.5, -0.75], + [1.0, 0.0], + [0.1, 0.2], + ], np.float32) + return { + "observations": np.zeros((4, 8, 8, 3), np.uint8), + "actions": actions, + # Compact OGBench convention marks both the last valid transition and + # the trailing state. Original trajectory endpoints are valids == 0. + "terminals": np.asarray([1, 1, 1, 1], bool), + "valids": np.asarray([1, 0, 1, 0], np.float32), + } + + +def _latent_terminals(dataset): + return np.asarray(dataset["valids"] <= 0, bool) + + +def _gcbc_payload(params=None): + return { + "format": "visual_gcbc_params_v1", + "step": 100_000, + "params": { + "modules_actor": ( + {"dummy": np.asarray([1.0], np.float32)} + if params is None else params), + }, + "config": { + "agent_name": "gcbc", + "lr": 3e-4, + "batch_size": 256, + "actor_hidden_dims": (512, 512, 512), + "const_std": True, + "discrete": False, + "encoder": "impala_small", + "p_aug": 0.5, + "frame_stack": None, + "actor_p_curgoal": 0.0, + "actor_p_trajgoal": 1.0, + "actor_p_randomgoal": 0.0, + "actor_geom_sample": False, + }, + "run_meta": { + "method": "GCBC", + "env": ENV, + "seed": 0, + "pixels_only": True, + "drop_proprio": True, + "simulator_state_used": False, + "coordinate_used": False, + "reward_used": False, + "uses_td_or_bootstrap": False, + "uses_occupancy": False, + "goal_relabeling": "uniform_future_same_trajectory", + "network_input_contract": ( + "IMPALA-small over channel-concatenated state and goal RGB"), + "training_augmentation": ( + "probability_0.5_shared_edge_padded_random_crop"), + "observation_shape": [8, 8, 3], + "action_shape": [2], + "dataset_keys": [ + "actions", "observations", "terminals", "valids"], + "excluded_keys": sorted(PIXEL_ACTOR_FORBIDDEN_KEYS), + "reference_root": "/read-only/reference", + "reference_sha256": "abc123", + }, + } + + +class PixelActorDatasetAuditTest(unittest.TestCase): + def test_accepts_exact_aligned_rgb_dataset(self): + dataset = _pixel_dataset() + observations, valid_indices, meta = ( + audit_visual_pixel_actor_dataset( + dataset, + np.clip(dataset["actions"], -1.0, 1.0), + _latent_terminals(dataset), + )) + self.assertIs(observations, dataset["observations"]) + np.testing.assert_array_equal( + valid_indices, np.asarray([0, 2], np.int32)) + self.assertEqual(meta["dataset_keys"], [ + "actions", "observations", "terminals", "valids"]) + self.assertTrue(meta["actions_match_latent_cache"]) + self.assertTrue(meta["source_terminals_match_latent_cache"]) + self.assertTrue(meta["compact_terminals_match_reconstructed"]) + + def test_rejects_forbidden_or_unexpected_dataset_fields(self): + dataset = _pixel_dataset() + dataset["qpos"] = np.zeros((4, 2), np.float32) + with self.assertRaisesRegex(ValueError, "keys must be exactly"): + audit_visual_pixel_actor_dataset( + dataset, + np.clip(dataset["actions"], -1.0, 1.0), + _latent_terminals(dataset), + ) + + def test_rejects_action_or_terminal_misalignment(self): + dataset = _pixel_dataset() + latent_actions = np.clip( + dataset["actions"], -1.0, 1.0).copy() + latent_actions[[0, 1]] = latent_actions[[1, 0]] + with self.assertRaisesRegex(ValueError, "actions are not row-aligned"): + audit_visual_pixel_actor_dataset( + dataset, latent_actions, _latent_terminals(dataset)) + + latent_terminals = _latent_terminals(dataset) + latent_terminals[[0, 1]] = latent_terminals[[1, 0]] + with self.assertRaisesRegex( + ValueError, "trajectory endpoints.*not row-aligned"): + audit_visual_pixel_actor_dataset( + dataset, + np.clip(dataset["actions"], -1.0, 1.0), + latent_terminals, + ) + + malformed_compact = _pixel_dataset() + malformed_compact["terminals"][0] = False + with self.assertRaisesRegex( + ValueError, "compact terminals do not match"): + audit_visual_pixel_actor_dataset( + malformed_compact, + np.clip(malformed_compact["actions"], -1.0, 1.0), + _latent_terminals(malformed_compact), + ) + + def test_rejects_non_rgb_or_empty_valid_rows(self): + dataset = _pixel_dataset() + dataset["observations"] = np.zeros((4, 8, 8, 4), np.uint8) + with self.assertRaisesRegex(ValueError, "three RGB channels"): + audit_visual_pixel_actor_dataset( + dataset, + np.clip(dataset["actions"], -1.0, 1.0), + _latent_terminals(dataset), + ) + + dataset = _pixel_dataset() + dataset["valids"][:] = 0 + with self.assertRaisesRegex(ValueError, "no valid transition"): + audit_visual_pixel_actor_dataset( + dataset, + np.clip(dataset["actions"], -1.0, 1.0), + _latent_terminals(dataset), + ) + + +class PixelActorInitializationAuditTest(unittest.TestCase): + def _validate(self, payload): + return validate_visual_gcbc_actor_init( + payload, + env=ENV, + seed=0, + observation_shape=(8, 8, 3), + action_shape=(2,), + p_aug=0.5, + ) + + def test_accepts_actor_only_non_td_gcbc_export(self): + actor_params, provenance = self._validate(_gcbc_payload()) + np.testing.assert_array_equal( + actor_params["dummy"], np.asarray([1.0], np.float32)) + self.assertEqual(provenance["format"], "visual_gcbc_params_v1") + self.assertEqual(provenance["step"], 100_000) + self.assertFalse(provenance["uses_td_or_bootstrap"]) + + def test_rejects_td_gciql_export_even_if_actor_is_compatible(self): + payload = _gcbc_payload() + payload["format"] = "visual_gciql_params_v1" + payload["run_meta"]["method"] = "GCIQL" + payload["run_meta"]["uses_td_or_bootstrap"] = True + with self.assertRaisesRegex( + ValueError, "TD-trained GCIQL exports are forbidden"): + self._validate(payload) + + def test_rejects_critic_or_occupancy_parameters(self): + payload = _gcbc_payload() + payload["params"]["modules_critic"] = {"dummy": np.asarray([2.0])} + with self.assertRaisesRegex( + ValueError, "params must contain only modules_actor"): + self._validate(payload) + + def test_rejects_mismatched_architecture_or_data_contract(self): + payload = _gcbc_payload() + payload["config"]["encoder"] = "impala_large" + payload["run_meta"]["coordinate_used"] = True + with self.assertRaisesRegex(ValueError, "config.encoder"): + self._validate(payload) + + def test_rejects_malformed_payload_and_step(self): + with self.assertRaisesRegex(ValueError, "payload must be a dictionary"): + self._validate(None) + + payload = _gcbc_payload() + payload["step"] = "not-an-integer" + with self.assertRaisesRegex(ValueError, "step must be an integer"): + self._validate(payload) + + payload = _gcbc_payload() + payload["step"] = 0 + with self.assertRaisesRegex(ValueError, "step must be positive"): + self._validate(payload) + + def test_rejects_nonfinite_actor_parameters(self): + payload = _gcbc_payload( + params={"dummy": np.asarray([np.nan], np.float32)}) + with self.assertRaisesRegex(ValueError, "finite numeric array"): + self._validate(payload) + + +class PixelActorRunContractTest(unittest.TestCase): + def _validate(self, **updates): + kwargs = { + "actor_input": "pixels", + "latent_npz": "/artifact/latents.npz", + "pixel_encoder": "/artifact/encoder.npz", + "drop_proprio": True, + "discount_conditioned": True, + "recursion_enabled": False, + "freeze_occupancy": False, + "actor_loss": "ddpgbc_distill", + "actor_q_transform": "raw", + "reward_decoder": "/artifact/index_reader.npz", + "qfilter": 0, + "latent_npz_sha256": "1" * 64, + "pixel_encoder_sha256": "2" * 64, + "pixel_dataset": "/artifact/visual-cube.npz", + "pixel_dataset_sha256": "3" * 64, + "pixel_actor_p_aug": 0.5, + "pixel_actor_init_ckpt": None, + "pixel_actor_init_ckpt_sha256": None, + } + kwargs.update(updates) + return validate_visual_pixel_actor_run_contract(**kwargs) + + def test_accepts_one_hop_joint_discount_conditioned_arm(self): + self.assertTrue(self._validate()) + + def test_recursion_requires_a_separately_audited_latent_proxy(self): + with self.assertRaisesRegex(ValueError, "latent proxy actor"): + self._validate(recursion_enabled=True) + + def test_requires_discount_conditioning_and_joint_occupancy(self): + with self.assertRaisesRegex(ValueError, "discount-conditioned"): + self._validate(discount_conditioned=False) + with self.assertRaisesRegex(ValueError, "jointly updated"): + self._validate(freeze_occupancy=True) + + def test_requires_immutable_latent_encoder_and_pixel_dataset(self): + for key in ( + "latent_npz_sha256", + "pixel_encoder_sha256", + "pixel_dataset_sha256"): + with self.subTest(key=key): + with self.assertRaisesRegex( + ValueError, "lowercase SHA-256"): + self._validate(**{key: None}) + with self.assertRaisesRegex(ValueError, "explicit --pixel_dataset"): + self._validate(pixel_dataset=None) + + def test_warm_start_requires_exact_crop_and_immutable_digest(self): + with self.assertRaisesRegex(ValueError, "(?i)sha"): + self._validate(pixel_actor_init_ckpt="/artifact/gcbc.pkl") + with self.assertRaisesRegex(ValueError, "p_aug=0.5"): + self._validate( + pixel_actor_p_aug=0.25, + pixel_actor_init_ckpt="/artifact/gcbc.pkl", + pixel_actor_init_ckpt_sha256="0" * 64, + ) + + +class PixelScorerRunContractTest(unittest.TestCase): + def _validate(self, **updates): + kwargs = { + "scorer_input": "pixels", + "pixel_actor": True, + "actor_loss": "awr_distill", + "distill_empirical_index_weight": 1.0, + "distill_actor_goals": True, + "distill_actor_actions": False, + "discount_conditioned": True, + "recursion": "off", + "freeze_occupancy": False, + "drop_proprio": True, + "pixel_actor_p_aug": 0.5, + "alpha": 30.0, + "expectile": 0.9, + "batch_size": 256, + } + kwargs.update(updates) + return validate_visual_pixel_scorer_run_contract(**kwargs) + + def test_accepts_primary_awr_and_ddpg_control(self): + self.assertTrue(self._validate()) + self.assertTrue(self._validate( + actor_loss="ddpgbc_distill", + alpha=1.0, + distill_actor_actions=True, + )) + self.assertTrue(self._validate( + actor_loss="ddpgbc_distill", + alpha=1.0, + distill_actor_actions=False, + )) + + def test_recorded_action_target_must_be_pure_empirical(self): + for weight in (0.0, 0.5, 0.999): + with self.subTest(weight=weight): + with self.assertRaisesRegex( + ValueError, "recorded-action label is empirical"): + self._validate( + distill_empirical_index_weight=weight) + + def test_awr_forbids_counterfactuals_and_ddpg_may_disable_them(self): + with self.assertRaisesRegex( + ValueError, "dataset actions only"): + self._validate(distill_actor_actions=True) + self.assertTrue(self._validate( + actor_loss="ddpgbc_distill", + alpha=1.0, + distill_actor_actions=False, + )) + + def test_matches_reference_expectile_and_ddpg_alpha(self): + with self.assertRaisesRegex(ValueError, "expectile=0.9"): + self._validate(expectile=0.7) + with self.assertRaisesRegex(ValueError, "alpha=1.0"): + self._validate( + actor_loss="ddpgbc_distill", + alpha=0.3, + distill_actor_actions=False, + ) + for batch_size in (4096, 256.0, True, "256"): + with self.subTest(batch_size=batch_size): + with self.assertRaisesRegex(ValueError, "batch_size=256"): + self._validate(batch_size=batch_size) + + def test_exact_reference_twin_impala_512x3_is_queryable(self): + reference_root = os.environ.get( + "OGBENCH_IMPLS", "/u/zwhong/ogbench_ref/impls") + sys.path.insert(0, reference_root) + try: + from utils.encoders import GCEncoder, encoder_modules + from utils.networks import GCValue + + scorer = GCValue( + hidden_dims=(512, 512, 512), + layer_norm=True, + ensemble=True, + gc_encoder=GCEncoder( + concat_encoder=encoder_modules["impala_small"]()), + ) + observations = jnp.zeros( + (2, 64, 64, 3), dtype=jnp.uint8) + goals = jnp.full_like(observations, 127) + actions = jnp.zeros((2, 5), dtype=jnp.float32) + params = scorer.init( + jax.random.PRNGKey(17), + observations, goals, actions)["params"] + values = scorer.apply( + {"params": params}, + observations, goals, actions) + finally: + sys.path.remove(reference_root) + + self.assertEqual(set(params), {"gc_encoder", "value_net"}) + self.assertEqual(values.shape, (2, 2)) + self.assertTrue(np.all(np.isfinite(np.asarray(values)))) + kernels = params["value_net"] + self.assertEqual(kernels["Dense_0"]["kernel"].shape[-1], 512) + self.assertEqual(kernels["Dense_1"]["kernel"].shape[-1], 512) + self.assertEqual(kernels["Dense_2"]["kernel"].shape[-1], 512) + self.assertEqual(kernels["Dense_3"]["kernel"].shape[-1], 1) + + def test_requires_pixel_only_joint_discounted_one_hop_recipe(self): + invalid = ( + ("pixel_actor", False, "actor_input pixels"), + ("discount_conditioned", False, "discount-conditioned"), + ("recursion", "occupancy", "one-hop"), + ("freeze_occupancy", True, "jointly updated"), + ("drop_proprio", False, "drop_proprio"), + ("pixel_actor_p_aug", 0.25, "p_aug=0.5"), + ) + for key, value, message in invalid: + with self.subTest(key=key): + with self.assertRaisesRegex(ValueError, message): + self._validate(**{key: value}) + + +class PixelActorAugmentationTest(unittest.TestCase): + def test_state_and_goal_use_identical_per_row_crop(self): + observations = np.arange( + 2 * 5 * 5 * 3, dtype=np.uint8).reshape(2, 5, 5, 3) + # A constant offset makes shared spatial alignment directly testable. + goals = observations.astype(np.int16) + 1000 + crop_xy = np.asarray([[0, 6], [6, 0]], np.int32) + cropped_observations, cropped_goals = ( + visual_actor_shared_random_crop( + observations, goals, crop_xy, True)) + cropped_observations = np.asarray(cropped_observations) + cropped_goals = np.asarray(cropped_goals) + np.testing.assert_array_equal( + cropped_goals - cropped_observations, 1000) + + expected = [] + for image, xy in zip(observations, crop_xy): + padded = np.pad( + image, ((3, 3), (3, 3), (0, 0)), mode="edge") + expected.append( + padded[xy[0]:xy[0] + 5, xy[1]:xy[1] + 5]) + np.testing.assert_array_equal( + cropped_observations, np.stack(expected)) + + def test_crop_helper_jits_and_noop_branch_is_exact(self): + observations = jnp.arange( + 2 * 4 * 4 * 3, dtype=jnp.uint8).reshape(2, 4, 4, 3) + goals = observations + jnp.asarray(2, jnp.uint8) + crop_xy = jnp.asarray([[1, 2], [4, 5]], jnp.int32) + crop_fn = jax.jit(visual_actor_shared_random_crop) + got_observations, got_goals = crop_fn( + observations, goals, crop_xy, False) + np.testing.assert_array_equal( + np.asarray(got_observations), np.asarray(observations)) + np.testing.assert_array_equal( + np.asarray(got_goals), np.asarray(goals)) + + +class EmpiricalIndexSuccessorTargetTest(unittest.TestCase): + def test_truncated_geometric_sampler_matches_finite_cdf(self): + got = truncated_geometric_future_indices( + np.asarray([10], np.int32), + np.asarray([14], np.int32), + np.asarray([0.5], np.float32), + np.asarray([[0.10, 0.60, 0.85, 0.98]], np.float32), + ) + np.testing.assert_array_equal( + got, np.asarray([[10, 11, 12, 13]], np.int32)) + + def test_sampler_jits_and_never_crosses_trajectory_end(self): + sample = jax.jit( + lambda rows, ends, discounts, uniforms: + truncated_geometric_future_indices( + rows, ends, discounts, uniforms, array_module=jnp)) + rows = jnp.asarray([3, 10], jnp.int32) + ends = jnp.asarray([4, 15], jnp.int32) + discounts = jnp.asarray([0.99, 0.75], jnp.float32) + uniforms = jnp.asarray( + [[1e-6, 0.5, 1.0 - 1e-6], + [1e-6, 0.5, 1.0 - 1e-6]], + jnp.float32, + ) + got = np.asarray(sample(rows, ends, discounts, uniforms)) + self.assertTrue(np.all(got >= np.asarray(rows)[:, None])) + self.assertTrue(np.all(got < np.asarray(ends)[:, None])) + np.testing.assert_array_equal(got[0], np.asarray([3, 3, 3])) + + def test_same_trajectory_goal_is_absorbing_first_passage(self): + got = truncated_geometric_future_indices( + np.asarray([10, 20, 30], np.int32), + np.asarray([16, 26, 36], np.int32), + np.asarray([0.5, 0.5, 0.5], np.float32), + np.asarray([ + [0.10, 0.60, 0.85, 0.98], + [0.10, 0.60, 0.85, 0.98], + [0.10, 0.60, 0.85, 0.98], + ], np.float32), + absorbing_goals=np.asarray([12, 19, 40], np.int32), + ) + # The first goal lies ahead in the same trajectory, so draws that + # would pass it accumulate exactly at the first-passage row. A past + # goal and a cross-trajectory goal leave the raw geometric draw alone. + np.testing.assert_array_equal( + got[0], np.asarray([10, 11, 12, 12], np.int32)) + np.testing.assert_array_equal( + got[1], np.asarray([20, 21, 22, 24], np.int32)) + np.testing.assert_array_equal( + got[2], np.asarray([30, 31, 32, 34], np.int32)) + + +class PixelActorSourceContractTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.source = inspect.getsource(run_rsm) + cls.tree = ast.parse(textwrap.dedent(cls.source)) + + def _calls(self, function_name): + return [ + node for node in ast.walk(self.tree) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == function_name + ] + + def test_every_occupancy_read_or_sample_supplies_a_discount(self): + calls = self._calls("gl") + self._calls("occ_bits") + self.assertGreater(len(calls), 5) + for call in calls: + with self.subTest(line=call.lineno, function=call.func.id): + self.assertTrue( + len(call.args) >= 6 + or any(key.arg == "dv" for key in call.keywords)) + self.assertIn("[g_enc(gam)] if spec_on else []", self.source) + self.assertIn( + "discount-conditioned occupancy read-out requires an explicit", + self.source, + ) + + def test_scorer_input_selector_preserves_latent_control(self): + # The historical arm still gathers only the actor pair. The opt-in + # pixel scorer gathers value and actor goals with one shared crop. + actor_batch_calls = self._calls("pixel_actor_batch") + self.assertEqual(len(actor_batch_calls), 1) + self.assertEqual( + [argument.id for argument in actor_batch_calls[0].args[1:]], + ["t", "gi_a", "pixel_observations"], + ) + scorer_batch_calls = self._calls("pixel_actor_scorer_batch") + self.assertEqual(len(scorer_batch_calls), 1) + self.assertIn( + 'distill_scorer_input="latent"', + self.source, + ) + self.assertIn( + "scorer_actor_state_b = state_b", + self.source, + ) + self.assertIn( + "scorer_actor_state_b = policy_state_b", + self.source, + ) + self.assertIn( + '"occupancy_consumes_raw_pixels": False', + self.source, + ) + self.assertIn( + "pixel_actor and not pixel_scorer", + self.source, + ) + + def test_pixel_actor_final_eval_uses_raw_visual_environment(self): + raw_eval_calls = [ + call for call in ast.walk(self.tree) + if isinstance(call, ast.Call) + and isinstance(call.func, ast.Attribute) + and call.func.attr == "make_env_and_datasets" + and isinstance(call.func.value, ast.Name) + and call.func.value.id == "ogbench" + and any( + keyword.arg == "env_only" + and isinstance(keyword.value, ast.Constant) + and keyword.value.value is True + for keyword in call.keywords) + ] + self.assertEqual(len(raw_eval_calls), 1) + self.assertIn('"rendered_pixels_only"', self.source) + + def test_full_pixel_dataset_is_a_dynamic_jit_dispatch_argument(self): + dispatch_calls = self._calls("dispatch") + pixel_dispatch_calls = [ + call for call in dispatch_calls + if len(call.args) == 2 + and isinstance(call.args[1], ast.Name) + and call.args[1].id == "pixel_obs_d" + ] + self.assertEqual(len(pixel_dispatch_calls), 1) + self.assertNotIn("pixel_obs_d[", self.source) + self.assertIn( + '"dynamic_jit_dispatch_argument_not_xla_constant"', + self.source, + ) + + # Representative CPU/JAX lowering: an explicit dataset argument is a + # jaxpr input and does not enter the closed constant table. + def gather(pixel_dataset, rows): + return pixel_dataset[rows] + + closed = jax.make_jaxpr(gather)( + jnp.zeros((8, 4, 4, 3), jnp.uint8), + jnp.asarray([1, 6], jnp.int32), + ) + self.assertEqual(len(closed.consts), 0) + self.assertEqual(len(closed.jaxpr.invars), 2) + + def test_pixel_arm_never_builds_a_completion_carrier(self): + self.assertIn("if not completion_rec_on:", self.source) + self.assertIn( + "a pixel-policy RSM must not instantiate or checkpoint the legacy", + self.source, + ) + self.assertIn( + "completion/world-model carrier", + self.source, + ) + self.assertIn( + '"completion_or_world_model_carrier_instantiated": (', + self.source, + ) + self.assertIn( + "bool(completion_rec_on) if pixel_actor else None", + self.source, + ) + + def test_hidden_goal_keeps_hidden_future_except_metric_coordinate_arm(self): + self.assertIn( + "goal_hidden and not reward_metric_target", + self.source, + ) + self.assertIn( + "tgt_np = state_h_np if hidden_occupancy_future else z_np", + self.source, + ) + self.assertIn( + '"future_feature": future_feature', + self.source, + ) + self.assertIn( + '"occupancy_future_dim": int(n_bits)', + self.source, + ) + self.assertIn( + "goal_b = reward_goal_d[gi_a]", + self.source, + ) + self.assertIn( + "value_goal_b = reward_goal_d[gi_v]", + self.source, + ) + + def test_empirical_index_anchor_is_non_td_and_keeps_offsupport_occupancy(self): + self.assertIn( + "observed_same_trajectory_absorbing_first_passage_geometric_", + self.source, + ) + self.assertIn( + '"distill_empirical_index_uses_reward_arrays": False', + self.source, + ) + self.assertIn( + '"distill_empirical_index_uses_coordinates": False', + self.source, + ) + self.assertIn( + '"distill_empirical_index_uses_td_or_bootstrap": False', + self.source, + ) + self.assertIn( + '"actor_mode_and_local_candidates_discount_conditioned_"', + self.source, + ) + self.assertIn( + "q_target_v = empirical_v", + self.source, + ) + self.assertIn( + "q_target_a = empirical_a", + self.source, + ) + self.assertIn( + "counterfactual_targets = jax.lax.stop_gradient", + self.source, + ) + self.assertIn( + "support_actions[1:]", + self.source, + ) + + def test_pixel_scorer_target_tracks_just_updated_live_scorer(self): + self.assertIn( + "critic_ema, new_critic_params)", + self.source, + ) + self.assertNotIn( + "critic_ema, critic_params)", + self.source, + ) + + +class ActorInputMetadataCompatibilityTest(unittest.TestCase): + def test_legacy_checkpoint_backfills_latent_without_overwriting_claims(self): + requested = { + "actor_input": "latent", + "final_actor_consumes_pixels": False, + "actor_architecture": "GCActor_MLP_512x3", + } + got = backfill_actor_input_metadata( + {"actor_architecture": "historical_architecture"}, requested) + self.assertEqual(got["actor_input"], "latent") + self.assertFalse(got["final_actor_consumes_pixels"]) + self.assertEqual( + got["actor_architecture"], "historical_architecture") + + def test_pixel_metadata_must_be_complete_and_is_not_inferred(self): + requested = { + "actor_input": "pixels", + "final_actor_consumes_pixels": True, + } + got = backfill_actor_input_metadata( + {"actor_input": "pixels"}, requested) + self.assertEqual(got, {"actor_input": "pixels"}) + self.assertNotIn("final_actor_consumes_pixels", got) + + self.assertEqual( + backfill_actor_input_metadata(requested, requested), + requested, + ) + + +class PixelActorLauncherContractTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.path = ( + Path(__file__).parent + / "experiments" + / "train_visual_rsm_pixel_actor.sh") + cls.source = cls.path.read_text() + + def test_launcher_is_valid_shell_and_exposes_both_latent_arms(self): + subprocess.run( + ["bash", "-n", str(self.path)], + check=True, + capture_output=True, + text=True, + ) + self.assertIn("LATENT_UPDATE=frozen", self.source) + self.assertIn("joint|rich_adapter)", self.source) + self.assertIn("--latent_update rich_adapter", self.source) + self.assertIn("GOAL_HIDDEN=${GOAL_HIDDEN:-1}", self.source) + self.assertIn("GOAL_ARGS=(--goal_hidden)", self.source) + self.assertIn("FUTURE_TAG=z8", self.source) + self.assertIn( + "compact z8 future requires LATENT_UPDATE=frozen", + self.source, + ) + + def test_launcher_pins_pixel_non_td_one_hop_contract(self): + required = ( + "--actor_input pixels", + "--latent_npz_sha256", + "--pixel_encoder_sha256", + "--pixel_dataset", + "--pixel_dataset_sha256", + "--drop_proprio", + "--actor_loss ddpgbc_distill", + "--actor_q_transform raw", + "--occupancy_model flow", + "--occ_actor_goal_fraction", + "--occ_reader_hit_weight", + "--distill_empirical_index_weight", + "--distill_scorer_input", + "--gamma_spectrum_lo", + "--gamma_sampler", + "--gamma_horizons", + "--rec_beta", + "--recursion off", + "--train_only", + ) + for literal in required: + with self.subTest(literal=literal): + self.assertIn(literal, self.source) + self.assertIn( + "GAMMA_HORIZONS=${GAMMA_HORIZONS:-2,4,8,16,32,50,64}", + self.source, + ) + self.assertIn( + "GAMMA_SAMPLER=${GAMMA_SAMPLER:-stratified_bins}", + self.source, + ) + self.assertIn("BETA=${BETA:-0.98}", self.source) + self.assertIn( + "OCC_READER_HIT_WEIGHT=${OCC_READER_HIT_WEIGHT:-0.0}", + self.source, + ) + self.assertIn( + "_rh${OCC_READER_HIT_WEIGHT}_" + "ei${DISTILL_EMPIRICAL_INDEX_WEIGHT}_gs${GAMMA_SAMPLER}_" + "gt${GAMMA_TASK_FRACTION}_bp${REC_BETA_SAMPLE_PROB}_" + "g${GAMMA}_b${BETA}_s${SEED}", + self.source, + ) + + def test_launcher_exposes_paired_reward_metric_priority_cells(self): + required = ( + "OCC_TARGET_SPACE=${OCC_TARGET_SPACE:-absolute_future}", + "goal_relative_reader_metric)", + "REWARD_METRIC_AUX_ALLOCATION=" + "${REWARD_METRIC_AUX_ALLOCATION:-uniform}", + "uniform|sqrt_h)", + "--occ_target_space goal_relative_reader_metric", + "--reward_metric_aux_allocation", + "GAMMA_TASK_FRACTION=${GAMMA_TASK_FRACTION:-0.5}", + "REC_BETA_SAMPLE_PROB=${REC_BETA_SAMPLE_PROB:-0.25}", + "GAMMA_HORIZONS=${GAMMA_HORIZONS:-8,16,32,64}", + "GAMMA_SAMPLER=${GAMMA_SAMPLER:-reward_metric_endpoints}", + "TARGET_TAG=metricu_${REWARD_METRIC_AUX_ALLOCATION}", + ) + for literal in required: + with self.subTest(literal=literal): + self.assertIn(literal, self.source) + + def test_launcher_exposes_combined_pixel_scorer_support_modes(self): + required = ( + "DISTILL_SCORER_INPUT=${DISTILL_SCORER_INPUT:-latent}", + "DISTILL_ACTOR_ACTIONS=${DISTILL_ACTOR_ACTIONS:-1}", + "SCORER_ARGS=(--distill_scorer_input pixels)", + "SCORER_SUPPORT_ARGS=(--distill_actor_actions)", + "SCORER_SUPPORT_ARGS=(--no_distill_actor_actions)", + "reader_metric", + "--batch_size 256", + ) + for literal in required: + with self.subTest(literal=literal): + self.assertIn(literal, self.source) + + +class ProtectedEndpointAblationLauncherTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.path = ( + Path(__file__).parent + / "experiments" + / "pack_visual_rsm_protected_endpoint_ablation.sh") + cls.source = cls.path.read_text() + + def test_launcher_is_shell_valid_and_permanently_dry_run(self): + subprocess.run( + ["bash", "-n", str(self.path)], + check=True, + capture_output=True, + text=True, + ) + self.assertNotIn("bsub", self.source) + self.assertNotIn("--execute", self.source) + self.assertNotIn("--freeze_occupancy", self.source) + rejected = subprocess.run( + ["bash", str(self.path), "--dry-run"], + env={**os.environ, "PACK_DRY_RUN": "0"}, + capture_output=True, + text=True, + ) + self.assertEqual(rejected.returncode, 2) + self.assertIn("dry-run only", rejected.stderr) + + def test_prints_exact_four_cell_joint_actor_occupancy_plan(self): + result = subprocess.run( + ["bash", str(self.path), "--dry-run"], + check=True, + capture_output=True, + text=True, + ) + output = result.stdout + self.assertEqual(output.count(" command="), 4) + self.assertEqual(output.count("LATENT_UPDATE=frozen"), 2) + self.assertEqual(output.count("LATENT_UPDATE=joint"), 2) + self.assertEqual(output.count("OCC_READER_HIT_WEIGHT=0.0"), 2) + self.assertEqual(output.count("OCC_READER_HIT_WEIGHT=0.25"), 2) + self.assertEqual( + output.count("GAMMA_SAMPLER=protected_endpoints"), 4) + self.assertEqual(output.count("BETA=0.98"), 4) + self.assertEqual(output.count("GAMMA_HORIZONS=8\\,16\\,32\\,64"), 4) + self.assertEqual(output.count("ACTOR_AFTER=0"), 4) + self.assertIn("occupancy_actor_joint_update=true", output) + self.assertIn( + "dry-run complete no_training=true no_submission=true", output) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_pixel_scorer_diagnostic.py b/gen_q_rsm/ogbench_genq/test_visual_pixel_scorer_diagnostic.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3501fb14cdd8847105c3570192c22dc7ef35ca --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_pixel_scorer_diagnostic.py @@ -0,0 +1,211 @@ +"""CPU unit tests for the strict schema-13 raw-RGB scorer diagnostic.""" + +import os +import tempfile +import unittest +from types import SimpleNamespace + +import numpy as np + +os.environ.setdefault("JAX_PLATFORMS", "cpu") +os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") + +from ogbench_genq.genq.diagnose_visual_pixel_scorer import ( + _configure_strict_pixel_scorer, +) +from ogbench_genq.genq.gate_visual_occupancy import ( + _load_pinned_latent_occupancy_source, + _pixel_scorer_definition, + _raw_pixel_scorer_metrics, + _repeat_pixel_pairs_for_actions, +) + + +class VisualPixelScorerDiagnosticTest(unittest.TestCase): + + def test_strict_wrapper_enables_required_fail_closed_contract(self): + args = SimpleNamespace() + returned = _configure_strict_pixel_scorer(args) + self.assertIs(returned, args) + self.assertTrue(args.require_pixel_scorer) + self.assertTrue(args.strict_pixel_scorer_data_diet) + + def test_pixel_pairs_are_shared_across_every_action_candidate(self): + observations = np.arange( + 2 * 8 * 8 * 3, dtype=np.uint8).reshape(2, 8, 8, 3) + goals = observations[::-1].copy() + actions = np.arange(2 * 4 * 3, dtype=np.float32).reshape(2, 4, 3) + flat_observations, flat_goals, flat_actions = ( + _repeat_pixel_pairs_for_actions( + observations, goals, actions)) + self.assertEqual(flat_observations.shape, (8, 8, 8, 3)) + self.assertEqual(flat_goals.shape, (8, 8, 8, 3)) + self.assertEqual(flat_actions.shape, (8, 3)) + for row in range(2): + begin = row * 4 + end = begin + 4 + np.testing.assert_array_equal( + flat_observations[begin:end], + np.repeat(observations[row][None], 4, axis=0), + ) + np.testing.assert_array_equal( + flat_goals[begin:end], + np.repeat(goals[row][None], 4, axis=0), + ) + np.testing.assert_array_equal( + flat_actions[begin:end], actions[row]) + + def test_strict_latent_loader_opens_only_z_and_state_h(self): + z = np.arange(12, dtype=np.float32).reshape(4, 3) + state_h = np.arange(20, dtype=np.float32).reshape(4, 5) + # Object arrays fail under allow_pickle=False if they are indexed. + # Their presence therefore makes accidental reads observable. + sentinel = np.asarray([{"must_not_load": True}], dtype=object) + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "latents.npz") + np.savez( + path, + z=z, + state_h=state_h, + actions=sentinel, + terminals=sentinel, + encoder_npz=sentinel, + proprio=sentinel, + coordinates=sentinel, + rewards=sentinel, + ) + source = _load_pinned_latent_occupancy_source( + path, strict_pixel_data_diet=True) + np.testing.assert_array_equal(source["z"], z) + np.testing.assert_array_equal(source["state_h"], state_h) + self.assertIsNone(source["actions"]) + self.assertIsNone(source["terminals"]) + self.assertIsNone(source["encoder_npz"]) + self.assertEqual(source["arrays_read"], ["z", "state_h"]) + self.assertEqual(source["metadata_arrays_read"], []) + self.assertEqual(source["forbidden_arrays_read"], []) + with self.assertRaisesRegex(ValueError, "Object arrays"): + _load_pinned_latent_occupancy_source( + path, strict_pixel_data_diet=False) + + def test_exact_twin_impala_scorer_is_queryable_on_cpu(self): + import jax + import jax.numpy as jnp + + scorer = _pixel_scorer_definition() + observations = np.zeros((2, 16, 16, 3), np.uint8) + goals = np.full((2, 16, 16, 3), 127, np.uint8) + actions = np.asarray([[0.1, -0.2], [-0.3, 0.4]], np.float32) + params = scorer.init( + jax.random.PRNGKey(13), + jnp.asarray(observations), + jnp.asarray(goals), + jnp.asarray(actions), + )["params"] + heads = jax.jit(lambda p, s, g, a: scorer.apply( + {"params": p}, s, g, a))( + params, + jnp.asarray(observations), + jnp.asarray(goals), + jnp.asarray(actions), + ) + self.assertEqual(heads.shape, (2, 2)) + self.assertTrue(np.all(np.isfinite(np.asarray(heads)))) + self.assertEqual(set(params), {"gc_encoder", "value_net"}) + + def test_metrics_cover_fidelity_ranking_twins_support_drift_and_crop(self): + rows = np.asarray([0, 2, 4], np.int64) + labels = ["data", "data_local_0", "actor", "actor_local_0"] + direct = np.asarray([ + [0.20, 0.30, 0.55, 0.45], + [0.80, 0.65, 0.40, 0.50], + [0.35, 0.25, 0.70, 0.60], + ], np.float32) + sample_offsets = np.asarray( + [-0.03, -0.02, -0.01, 0.0, 0.0, 0.01, 0.02, 0.03], + np.float32) + direct_samples = direct[:, :, None] + sample_offsets[None, None] + live_heads = np.stack([direct + 0.02, direct - 0.02]) + ema_heads = np.stack([direct + 0.01, direct - 0.01]) + crop_live = np.stack([ + live_heads + 0.005, + live_heads - 0.005, + ]) + crop_ema = np.stack([ + ema_heads + 0.003, + ema_heads - 0.003, + ]) + dataset_actions = np.asarray([ + [0.0, 0.0], + [0.1, -0.1], + [0.2, 0.1], + [-0.2, 0.2], + [0.4, -0.3], + [-0.5, 0.5], + ], np.float32) + evaluation_actions = np.zeros((3, 4, 2), np.float32) + evaluation_actions[:, 0] = dataset_actions[rows] + evaluation_actions[:, 1] = dataset_actions[rows] + 0.05 + evaluation_actions[:, 2] = np.asarray([ + [0.25, 0.20], + [-0.25, 0.35], + [0.95, -0.95], + ]) + evaluation_actions[:, 3] = evaluation_actions[:, 2] - 0.05 + support = { + "row_outside_dataset_p01_p99_rate": 1.0 / 3.0, + "reference_action_count": 6, + } + + metrics = _raw_pixel_scorer_metrics( + direct_samples, + live_heads, + ema_heads, + labels, + evaluation_actions, + dataset_actions, + rows, + support, + crop_live_heads=crop_live, + crop_ema_heads=crop_ema, + ) + + self.assertEqual(metrics["schema_version"], 1) + self.assertEqual(metrics["candidate_labels"], labels) + self.assertFalse(metrics["counterfactual_ground_truth_available"]) + self.assertEqual( + metrics["live_scorer"]["all_candidates_ranking"][ + "top1_agreement"], + 1.0, + ) + self.assertEqual( + metrics["ema_scorer"]["all_candidates_ranking"][ + "pairwise_agreement"], + 1.0, + ) + self.assertGreater( + metrics["twin_disagreement"]["live_all_candidates"][ + "absolute_mean"], + metrics["twin_disagreement"]["ema_all_candidates"][ + "absolute_mean"], + ) + self.assertIs(metrics["action_support"], support) + self.assertIn( + "live_scorer_only_actor_preference_and_ood_rate", + metrics["actor_drift"], + ) + crop = metrics["shared_crop_stress"] + self.assertTrue(crop["enabled"]) + self.assertTrue(crop["shared_state_goal_offset_per_row"]) + self.assertTrue( + crop["same_cropped_pair_reused_across_action_candidates"]) + self.assertEqual(crop["live"]["trial_count"], 2) + self.assertEqual( + crop["live"][ + "pairwise_rank_agreement_with_unaugmented_mean"], + 1.0, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_pixel_scorer_launcher.py b/gen_q_rsm/ogbench_genq/test_visual_pixel_scorer_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..529f837a6b0e9dc1e322ba637762b83ec7fe9407 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_pixel_scorer_launcher.py @@ -0,0 +1,275 @@ +"""Focused shell-contract tests for the raw-pixel scorer launcher.""" + +import os +from pathlib import Path +import stat +import subprocess +import tempfile +import textwrap +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +LAUNCHER = ( + ROOT / "ogbench_genq" / "experiments" + / "train_visual_rsm_pixel_scorer.sh" +) + +LAT_SHA = "8b19aa38a9df797fdbef230506e18357efa6622b6fe6b2b011e8af5f90908f2d" +ENC_SHA = "c81cfa6048673706a3842e58d36cc2ecff999e51d2a897dd8ba099c8447e39b2" +RDEC_SHA = "9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7" +DATA_SHA = "8de92b80f0c11d32b8621a98c473006313771a32da11a333b5d473db197d95c0" +GCBC_SHA = "95ee8d65769dc1da91d06de38801d588ca6446ff8a73fea340af752d5627f89b" +OCC_SHA = "ebd13c6963c3b8905cd1bf4fde4f618095e955c791292d507ce6c5280f919279" +PROTECTED_OCCUPANCY = Path( + "/proj/inf-scaling/zwhong/visual_rsm_protected_frozen_s0/" + "rsm_fair_visual_rsm_protected_frozen_hit025_jointtrain50k_" + "h256_s0_step50000.pkl" +) + + +class PixelScorerLauncherContractTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.source = LAUNCHER.read_text() + + def setUp(self): + self.tempdir = tempfile.TemporaryDirectory() + root = Path(self.tempdir.name) + self.artifacts = root / "artifacts" + self.artifacts.mkdir() + self.latent = self.artifacts / ( + "latents_fair_px_gpred_gciql_z8_w003_gciqlret_stateh256.npz" + ) + self.encoder = self.artifacts / ( + "pixel_enc_visual_cube_single_play_v0_gpred_gciql_z8_w003.npz" + ) + self.reader = self.artifacts / ( + "rdec_fair_px_gpred_gciql_z8_w003_gciqlret_" + "indexd4_diagmetric.npz" + ) + self.dataset = self.artifacts / "visual-cube-single-play-v0.npz" + self.gcbc = self.artifacts / "params_300000.pkl" + for path in ( + self.latent, self.encoder, self.reader, self.dataset, self.gcbc + ): + path.write_bytes(b"x") + + fake_bin = root / "bin" + fake_bin.mkdir() + sha256sum = fake_bin / "sha256sum" + sha256sum.write_text(textwrap.dedent( + f"""\ + #!/bin/sh + case "$1" in + *latents_*_stateh256.npz) digest={LAT_SHA} ;; + *pixel_enc_*.npz) digest={ENC_SHA} ;; + *rdec_*_indexd4_diagmetric.npz) digest={RDEC_SHA} ;; + *visual-cube-single-play-v0.npz) digest={DATA_SHA} ;; + *params_300000.pkl) digest={GCBC_SHA} ;; + *protected_frozen_hit025_jointtrain50k_h256_s0_step50000.pkl) + digest={OCC_SHA} + ;; + *) exit 9 ;; + esac + printf '%s %s\\n' "$digest" "$1" + """ + )) + sha256sum.chmod( + sha256sum.stat().st_mode | stat.S_IXUSR + | stat.S_IXGRP | stat.S_IXOTH + ) + self.base_env = { + **os.environ, + "PATH": f"{fake_bin}:{os.environ['PATH']}", + "PY": "/bin/true", + "OGBENCH_IMPLS": str(root), + "LAT": str(self.latent), + "ENC": str(self.encoder), + "RDEC": str(self.reader), + "PIXEL_DATASET": str(self.dataset), + "PIXEL_ACTOR_INIT_CKPT": str(self.gcbc), + "OUTPUT_ROOT": str( + Path("/proj/inf-scaling/zwhong") + / f"pixel-scorer-launcher-test-{os.getpid()}" + ), + "TRAIN_STEPS": "100", + } + + def tearDown(self): + self.tempdir.cleanup() + + def run_launcher(self, **updates): + env = {**self.base_env, **updates} + return subprocess.run( + ["bash", str(LAUNCHER), "--dry-run"], + cwd=ROOT, + env=env, + capture_output=True, + text=True, + ) + + def test_shell_is_valid_and_source_pins_scientific_contract(self): + subprocess.run( + ["bash", "-n", str(LAUNCHER)], + check=True, + capture_output=True, + text=True, + ) + required = ( + "--drop_proprio", + "--goal_hidden", + "--actor_input pixels", + "--pixel_actor_p_aug 0.5", + "--distill_empirical_index_weight 1.0", + "--distill_scorer_input pixels", + "--gamma 0.99", + "--rec_beta 0.98", + "--gamma_sampler protected_endpoints", + "--gamma_horizons 8,16,32,64", + "--occupancy_model flow", + "--occ_hidden 512", + "--occ_layers 4", + "--batch_size 256", + "--occ_batch 2048", + "--rdec_samples 64", + "--actor_after 10000", + "--recursion off", + "reject_flag --freeze_occupancy", + LAT_SHA, + ENC_SHA, + RDEC_SHA, + DATA_SHA, + GCBC_SHA, + ) + for literal in required: + with self.subTest(literal=literal): + self.assertIn(literal, self.source) + self.assertNotIn( + "\n --freeze_occupancy", + self.source, + ) + + def test_frozen_behavior_ddpgbc_dry_run(self): + result = self.run_launcher( + LATENT_UPDATE="frozen", + SUPPORT_MODE="behavior", + ACTOR_LOSS="ddpgbc_distill", + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("--latent_update frozen", result.stdout) + self.assertIn("--no_distill_actor_actions", result.stdout) + self.assertNotIn("--distill_actor_actions", result.stdout) + self.assertIn("--actor_loss ddpgbc_distill", result.stdout) + self.assertIn("--alpha 1.0", result.stdout) + self.assertIn("--gamma_spectrum_lo 0.875", result.stdout) + self.assertIn("--occ_reader_hit_weight 0.25", result.stdout) + self.assertIn("joint_occupancy_scorer_actor=true", result.stdout) + self.assertIn("no training or submission", result.stdout) + + def test_joint_behavior_awr_maps_to_rich_adapter(self): + result = self.run_launcher( + LATENT_UPDATE="joint", + SUPPORT_MODE="behavior", + ACTOR_LOSS="awr_distill", + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("--latent_update rich_adapter", result.stdout) + self.assertIn("--no_distill_actor_actions", result.stdout) + self.assertIn("--actor_loss awr_distill", result.stdout) + self.assertIn("--alpha 10.0", result.stdout) + self.assertIn("--gamma_spectrum_lo 0.875", result.stdout) + + def test_occupancy_support_emits_exact_local_support(self): + result = self.run_launcher( + LATENT_UPDATE="joint", + SUPPORT_MODE="occupancy", + ACTOR_LOSS="ddpgbc_distill", + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("--distill_actor_actions", result.stdout) + self.assertIn("--distill_actor_action_k 2", result.stdout) + self.assertIn("--distill_actor_action_sigma 0.3", result.stdout) + self.assertIn( + "--distill_actor_action_pairwise_weight 1.0", + result.stdout, + ) + self.assertNotIn("--no_distill_actor_actions", result.stdout) + + def test_awr_rejects_occupancy_support(self): + result = self.run_launcher( + SUPPORT_MODE="occupancy", + ACTOR_LOSS="awr_distill", + ) + self.assertEqual(result.returncode, 2) + self.assertIn("incompatible with awr_distill", result.stderr) + + def test_protected_init_is_frozen_support_only_and_pins_gamma_lo(self): + if not PROTECTED_OCCUPANCY.is_file(): + self.skipTest("campaign protected checkpoint is unavailable") + result = self.run_launcher( + LATENT_UPDATE="frozen", + SUPPORT_MODE="occupancy", + ACTOR_LOSS="ddpgbc_distill", + INIT_OCCUPANCY_CKPT=str(PROTECTED_OCCUPANCY), + INIT_OCCUPANCY_CKPT_SHA256=OCC_SHA, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("--init_occupancy_ckpt", result.stdout) + self.assertIn("--gamma_spectrum_lo 0.5", result.stdout) + self.assertIn("--occ_reader_hit_weight 0.25", result.stdout) + self.assertIn("occupancy_init=protected50k", result.stdout) + + for updates, message in ( + ( + { + "LATENT_UPDATE": "joint", + "SUPPORT_MODE": "occupancy", + }, + "requires LATENT_UPDATE=frozen", + ), + ( + { + "LATENT_UPDATE": "frozen", + "SUPPORT_MODE": "behavior", + }, + "restricted to SUPPORT_MODE=occupancy", + ), + ): + rejected = self.run_launcher( + ACTOR_LOSS="ddpgbc_distill", + INIT_OCCUPANCY_CKPT=str(PROTECTED_OCCUPANCY), + INIT_OCCUPANCY_CKPT_SHA256=OCC_SHA, + **updates, + ) + self.assertEqual(rejected.returncode, 2) + self.assertIn(message, rejected.stderr) + + protected_seed = self.run_launcher( + LATENT_UPDATE="frozen", + SUPPORT_MODE="occupancy", + ACTOR_LOSS="ddpgbc_distill", + SEED="1", + INIT_OCCUPANCY_CKPT=str(PROTECTED_OCCUPANCY), + INIT_OCCUPANCY_CKPT_SHA256=OCC_SHA, + ) + self.assertEqual(protected_seed.returncode, 2) + self.assertIn("requires SEED=0", protected_seed.stderr) + + def test_invalid_axis_and_unsafe_tag_fail_closed(self): + invalid_cases = ( + ({"LATENT_UPDATE": "rich_adapter"}, "LATENT_UPDATE"), + ({"SUPPORT_MODE": "model"}, "SUPPORT_MODE"), + ({"ACTOR_LOSS": "ddpgbc"}, "ACTOR_LOSS"), + ({"TAG": "../escape"}, "TAG"), + ({"GAMMA_LO": "0.5"}, "GAMMA_LO must be 0.875"), + ) + for updates, message in invalid_cases: + with self.subTest(updates=updates): + result = self.run_launcher(**updates) + self.assertEqual(result.returncode, 2) + self.assertIn(message, result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_recursion_equivalence.py b/gen_q_rsm/ogbench_genq/test_visual_recursion_equivalence.py new file mode 100644 index 0000000000000000000000000000000000000000..438d24112623f83c83a0193fe1334166269a04a8 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_recursion_equivalence.py @@ -0,0 +1,154 @@ +"""Visual-recursion graft equivalence gate (#68 stacked on rsm-ogbench-matrix). + +The STATE path must stay BIT-IDENTICAL to our HEAD-before-graft when the pixel +/latent + ckpt features are off. We grafted Dan's PR #68 deltas onto our +recursive rsm.py: the `lax.cond` recursion-warmup gate, resumable `--ckpt`, a +jitted eval actor, `--rec_max_depth`, and the pixel proprio-key generalization. +None of these may perturb the trained occupancy when unused. + +The proof: run the CURRENT (grafted) rsm.py with all new features OFF and the +BASELINE (pre-graft) rsm.py loaded from git, with the same seed/steps, and +assert their occ_loss trajectories match to all printed digits at steps 100/200 +on puzzle-3x3-play-v0 (discrete/gl path) AND pointmaze-medium-navigate-v0 +(continuous/elbo path). Both are CPU-only (no renderer): train_steps=200, +eval_interval=100000 so no periodic eval fires, and the _occ_probe_out hook +captures occ_loss WITHOUT the final renderer-dependent eval — we raise inside a +sentinel to abort right after the last dispatch we care about. + +BASELINE_REF is pinned to the commit that is HEAD of rsm-visual-recursion at +graft time (the last commit before this port). Neither the baseline nor the +current rsm.py has the _occ_probe_out hook, so we textually inject the SAME +passive 2-line capture into BOTH — it touches neither RNG nor params, so it +cannot change computed occ_loss; it only exposes it without the renderer eval. + +Run (from repo root): + OGBENCH_IMPLS=/u/zwhong/ogbench_ref/impls \ + MUJOCO_GL=egl JAX_PLATFORMS=cpu \ + .ogbench_venv/bin/python ogbench_genq/test_visual_recursion_equivalence.py + +Exit 0 = PASS (all digits matched). Non-zero = FAIL. +""" +import importlib.util +import os +import subprocess +import sys + +os.environ.setdefault("JAX_PLATFORMS", "cpu") +os.environ.setdefault("CUDA_VISIBLE_DEVICES", "") + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.dirname(HERE) +ENVS = ["puzzle-3x3-play-v0", "pointmaze-medium-navigate-v0"] +STEPS = 200 # two 100-step dispatches -> occ_loss@100, @200 + +# The pre-graft HEAD of rsm-visual-recursion (last commit before Dan's #68 port +# landed). This is the true "state path before the graft" reference. +BASELINE_REF = "88d05ce" + + +def _inject_probe(src, tag): + """Textually add the passive 2-line occ_loss capture. The current rsm.py + signature has `gamma=GAMMA,` on its own line; the baseline is the same. The + dispatch call is identical in both. Each anchor must hit exactly once.""" + sig_anchor = " gamma=GAMMA,\n" + assert src.count(sig_anchor) == 1, f"{tag}: signature anchor drift" + src = src.replace(sig_anchor, " gamma=GAMMA, _occ_probe_out=None,\n") + disp_anchors = [ + " carry, (occ_ls, pi_ls, pi_diags) = dispatch(carry)\n", + " carry, (occ_ls, pi_ls) = dispatch(carry)\n", + ] + matches = [anchor for anchor in disp_anchors if src.count(anchor) == 1] + assert len(matches) == 1, f"{tag}: dispatch anchor drift" + disp_anchor = matches[0] + src = src.replace( + disp_anchor, + disp_anchor + + " if _occ_probe_out is not None:\n" + " _occ_probe_out.append(float(occ_ls.mean()))\n") + return src + + +def _load_module(src, name): + path = os.path.join(HERE, f"_{name}.py") + with open(path, "w") as f: + f.write(src) + spec = importlib.util.spec_from_file_location(name, path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod, path + + +def _load_baseline(): + src = subprocess.check_output( + ["git", "-C", REPO, "show", f"{BASELINE_REF}:ogbench_genq/rsm.py"]).decode() + print(f"[gate] baseline ref = {BASELINE_REF} (pre-graft HEAD rsm.py)") + return _load_module(_inject_probe(src, "baseline"), "rsm_baseline_ref") + + +def _load_current(): + with open(os.path.join(HERE, "rsm.py")) as f: + src = f.read() + return _load_module(_inject_probe(src, "current"), "rsm_current_probe") + + +class _Done(Exception): + pass + + +class _StopAfter(list): + """A probe list that raises once N entries are collected, so run_rsm aborts + BEFORE its renderer-dependent final eval (this is CPU-only).""" + + def __init__(self, n): + super().__init__() + self._n = n + + def append(self, x): + super().append(x) + if len(self) >= self._n: + raise _Done() + + +def _probe(run_rsm, env_id, **kw): + probe = _StopAfter(2) + try: + run_rsm(env_id, seed=0, train_steps=STEPS, eval_interval=100000, + eval_episodes=1, wandb_mode="offline", _occ_probe_out=probe, **kw) + except _Done: + pass + return list(probe) + + +def main(): + cur, cur_path = _load_current() + base, base_path = _load_baseline() + ok = True + print(f"[gate] STEPS={STEPS}, comparing current(features off) vs baseline\n") + for env_id in ENVS: + # current: all new features off (no latent_npz, no ckpt, default depth) + cur_p = _probe(cur.run_rsm, env_id) + base_p = _probe(base.run_rsm, env_id) + n = min(len(cur_p), len(base_p)) + print(f"=== {env_id} ===") + env_ok = True + for i in range(n): + step = (i + 1) * 100 + c, h = cur_p[i], base_p[i] + match = (f"{c:.6f}" == f"{h:.6f}") + env_ok &= match + print(f" step {step:4d} current occ_loss={c:.6f} " + f"baseline occ_loss={h:.6f} {'MATCH' if match else 'MISMATCH'}") + ok &= env_ok and n >= 2 + print(f" -> {'PASS' if (env_ok and n >= 2) else 'FAIL'}\n") + for p in (cur_path, base_path): + try: + os.remove(p) + except OSError: + pass + print("[gate] RESULT:", "PASS" if ok else "FAIL") + sys.exit(0 if ok else 1) + + +if __name__ == "__main__": + sys.path.insert(0, HERE) + main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_recursion_sweep_contract.py b/gen_q_rsm/ogbench_genq/test_visual_recursion_sweep_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..b5be7620b2e5ab6bbdc83a47875b74358f219764 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_recursion_sweep_contract.py @@ -0,0 +1,538 @@ +"""CPU/static gates for the post-one-hop visual RSM recursion sweep.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from ogbench_genq.genq.visual_recursion_sweep_contract import ( + CALIBRATION_STEPS, + CONTINUATION_STEPS, + EXPECTED_RECIPES, + NO_COMPOSITION_AFTER, + PINNED_READER_SHA256, + TAIL_CAP, + load_manifest, + validate_continuation_gate, + validate_onehop_gate, +) +from ogbench_genq.rsm import occupancy_recursion_tail_mass + + +ROOT = Path(__file__).resolve().parents[1] +EXPERIMENTS = ROOT / "ogbench_genq" / "experiments" +MANIFEST = EXPERIMENTS / "visual_rsm_recursion_sweep_manifest.tsv" +PACK = EXPERIMENTS / "pack_visual_rsm_recursion_sweep.sh" +SUBMIT = EXPERIMENTS / "submit_visual_rsm_recursion_sweep.sh" +TRAIN = EXPERIMENTS / "train_visual_rsm_occupancy_recursion.sh" +CONTINUATION_PACK = ( + EXPERIMENTS / "pack_visual_rsm_recursion_continuation.sh" +) +CONTINUATION_SUBMIT = ( + EXPERIMENTS / "submit_visual_rsm_recursion_continuation.sh" +) + + +def _passing_continuation_gate( + directory: str | Path, cell +) -> tuple[Path, Path, str]: + """Write a synthetic passing gate with a real immutable source file.""" + directory = Path(directory) + source = directory / f"rsm_fixture_{cell.cell}_step50000.pkl" + source.write_bytes(f"checkpoint:{cell.cell}".encode()) + source_sha256 = hashlib.sha256(source.read_bytes()).hexdigest() + reader_path = directory / "pinned_reader_not_materialized.npz" + encoder_path = directory / "frozen_pixel_encoder.npz" + active_dimensions = 109 + constant_dimensions = 256 - active_dimensions + payload = { + "schema_version": 2, + "audit": "fair_visual_rsm_one_hop_occupancy_checkpoint_gate", + "pass": True, + "checkpoint": str(source), + "checkpoint_sha256": source_sha256, + "checkpoint_step": CALIBRATION_STEPS, + "checkpoint_run_contract": { + "env": "visual-cube-single-play-v0", + "seed": 0, + "recursion": "occupancy_latent", + "recursion_state": "hidden", + }, + "fairness_and_training_contract": { + "pixels_only": True, + "drop_proprio": True, + "conditional_flow": True, + "discount_conditioned": True, + "discount_support": [0.5, cell.gamma], + "checkpoint_mode": "staged_hidden_precomposition", + "future_distribution_space": "frozen_encoder_hidden_h256", + "reward_reader_space": "cached_compact_z", + "checkpoint_step": CALIBRATION_STEPS, + "rec_after": int(cell.rec_after), + "composition_has_activated": False, + "composition_activation_rule": + "training_step_strictly_greater_than_rec_after", + "uses_td_or_bootstrap": False, + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": False, + "occupancy_and_actor_jointly_updated": True, + "separate_stop_gradient_losses": True, + "canonical_reader_model": "diag_metric", + "reader_index_delta": 4, + "actor_query_contrast_trained": True, + }, + "artifact_contract": { + "pixel_encoder": { + "path": str(encoder_path), + "sha256": "a" * 64, + "latent_artifact_binding_verified": True, + "hidden_dim": 256, + "compact_z_dim": 8, + "cube_coordinate_training": False, + "arrays_read": [ + "hidden", + "z_dim", + "cube_coordinate_training", + "fc_1.weight", + "fc_1.bias", + ], + }, + "reward_reader_path": str(reader_path), + "reward_reader_sha256": PINNED_READER_SHA256, + "forbidden_arrays_read": [], + "proprioception_arrays_read": [], + "simulator_coordinate_arrays_read": [], + "reward_arrays_read": [], + "reward_reader": { + "reader_model": "diag_metric", + "target": "index", + "index_delta": 4, + "zdim": 8, + "pixels_only_latents": True, + "frozen_encoder": True, + "uses_coordinates_for_training": False, + "uses_coordinates_for_diagnostics": False, + "uses_reward_arrays": False, + "uses_td_or_bootstrap": False, + "label_source": + "trajectory_index_positive_and_far_negative_relabeling", + }, + }, + "representation": { + "latent_update": "frozen", + "state_feature": "encoder_hidden", + "actor_goal_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "frozen_encoder_hidden_occupancy_state", + "reward_goal_feature": "compact_reward_predictive_z", + "state_dim": 256, + "occupancy_goal_dim": 256, + "future_distribution_space": "frozen_encoder_hidden_h256", + "future_dim": 256, + "reward_reader_space": "cached_compact_z", + "reward_reader_dim": 8, + "hidden_future_support": { + "rule": "exact_cached_future_std_greater_than_zero", + "total_dimensions": 256, + "active_dimensions": active_dimensions, + "constant_dimensions": constant_dimensions, + "mask_sha256": "b" * 64, + "relu_nonnegative_cached_support_verified": True, + "projection": "relu_nonnegative_plus_constant_mean", + }, + "generated_future_reward_projection": + "frozen_pixel_encoder_fc_1_affine_only", + "fc1_cached_z_error": { + "passed": True, + }, + }, + "occupancy": { + "model": "conditional_flow", + "gamma_sampler": "stratified_bins", + "gamma_task_fraction": 0.5, + "gamma_horizons": [ + float(value) for value in cell.gamma_horizons.split(",") + ], + "task_gamma": cell.gamma, + "candidate_recursion_beta": cell.beta, + "candidate_recursion_depth": cell.depth, + "candidate_recursion_beta_mass": cell.beta_mass, + "active_future_dimensions": active_dimensions, + "constant_future_dimensions": constant_dimensions, + "active_dimension_mask_applied_to_noise_flow_and_loss": True, + "raw_future_support_projection": + "relu_nonnegative_plus_constant_mean", + }, + "decision": { + "one_hop_value_ready": True, + "recursive_state_ready": True, + "ready_for_recursion_experiment": True, + }, + } + gate_path = directory / f"{cell.cell}.json" + gate_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") + return gate_path, source, source_sha256 + + +class VisualRecursionSweepContractTest(unittest.TestCase): + def test_manifest_is_exact_and_tail_bounded(self): + cells = load_manifest(MANIFEST) + self.assertEqual(len(cells), 6) + self.assertEqual({cell.recipe for cell in cells}, EXPECTED_RECIPES) + for cell in cells: + with self.subTest(cell=cell.cell): + self.assertLessEqual( + occupancy_recursion_tail_mass( + cell.gamma, cell.beta, cell.depth + ), + TAIL_CAP, + ) + self.assertEqual(cell.reader_sha256, PINNED_READER_SHA256) + + no_composition = [ + cell for cell in cells if cell.composition == "off" + ] + self.assertEqual(len(no_composition), 1) + self.assertEqual( + int(no_composition[0].rec_after), NO_COMPOSITION_AFTER) + for cell in cells: + self.assertGreaterEqual( + int(cell.rec_after), CALIBRATION_STEPS) + beta_ablation = [cell for cell in cells if cell.beta_mass == 0.40] + self.assertEqual(len(beta_ablation), 1) + self.assertEqual( + (beta_ablation[0].gamma, beta_ablation[0].beta), + (0.99, 0.98), + ) + + def test_onehop_gate_requires_strict_boolean_true_and_can_pin_sha(self): + with tempfile.TemporaryDirectory() as directory: + good = Path(directory) / "good.json" + good.write_text(json.dumps({"pass": True}), encoding="utf-8") + _, digest = validate_onehop_gate(good) + _, pinned_digest = validate_onehop_gate(good, digest) + self.assertEqual(pinned_digest, digest) + with self.assertRaisesRegex(ValueError, "SHA-256 mismatch"): + validate_onehop_gate(good, "0" * 64) + + for name, payload in ( + ("false", {"pass": False}), + ("integer", {"pass": 1}), + ("string", {"pass": "true"}), + ("nested", {"gates": {"pass": True}}), + ): + path = Path(directory) / f"{name}.json" + path.write_text(json.dumps(payload), encoding="utf-8") + with self.subTest(payload=payload): + with self.assertRaisesRegex(ValueError, "gate is closed"): + validate_onehop_gate(path) + + def test_continuation_gate_binds_hidden_step50k_cell_and_artifacts(self): + cell = next( + item for item in load_manifest(MANIFEST) + if item.composition == "on" + ) + with tempfile.TemporaryDirectory() as directory: + gate_path, source, source_sha256 = _passing_continuation_gate( + directory, cell) + validated = validate_continuation_gate(gate_path, cell) + self.assertEqual(validated.cell, cell.cell) + self.assertEqual(validated.source_checkpoint, str(source)) + self.assertEqual( + validated.source_checkpoint_sha256, source_sha256) + self.assertEqual( + validated.source_checkpoint_step, CALIBRATION_STEPS) + self.assertEqual( + validated.reader_sha256, PINNED_READER_SHA256) + + payload = json.loads(gate_path.read_text(encoding="utf-8")) + mutations = ( + ( + "relative checkpoint", + ("checkpoint",), + source.name, + "absolute path", + ), + ( + "wrong checkpoint step", + ("checkpoint_step",), + CALIBRATION_STEPS - 1, + "checkpoint_step mismatch", + ), + ( + "wrong recursion mode", + ("checkpoint_run_contract", "recursion"), + "off", + "recursion mismatch", + ), + ( + "wrong precomposition boundary", + ("fairness_and_training_contract", "rec_after"), + int(cell.rec_after) + 1, + "rec_after mismatch", + ), + ( + "wrong hidden dimension", + ("representation", "future_dim"), + 8, + "future_dim mismatch", + ), + ( + "wrong task gamma", + ("occupancy", "task_gamma"), + cell.gamma - 0.01, + "task_gamma mismatch", + ), + ( + "wrong recursion beta", + ("occupancy", "candidate_recursion_beta"), + cell.beta - 0.01, + "candidate_recursion_beta mismatch", + ), + ( + "wrong reader digest", + ("artifact_contract", "reward_reader_sha256"), + "0" * 64, + "reader SHA-256", + ), + ( + "nested decision closed", + ("decision", "ready_for_recursion_experiment"), + False, + "ready_for_recursion_experiment mismatch", + ), + ) + for name, keys, value, message in mutations: + mutated = copy.deepcopy(payload) + target = mutated + for key in keys[:-1]: + target = target[key] + target[keys[-1]] = value + mutated_path = Path(directory) / f"{name}.json" + mutated_path.write_text( + json.dumps(mutated), encoding="utf-8") + with self.subTest(name=name): + with self.assertRaisesRegex(ValueError, message): + validate_continuation_gate(mutated_path, cell) + + def test_continuation_pack_requires_explicit_passing_cells(self): + cells = load_manifest(MANIFEST) + enabled = next(cell for cell in cells if cell.composition == "on") + control = next(cell for cell in cells if cell.composition == "off") + with tempfile.TemporaryDirectory() as directory: + _, enabled_source, enabled_sha = _passing_continuation_gate( + directory, enabled) + _passing_continuation_gate(directory, control) + destination_root = Path(directory) / "destinations" + log_root = Path(directory) / "logs" + env = os.environ.copy() + env.update( + { + "CF": str(ROOT), + "PY": sys.executable, + "PYTHONPATH": str(ROOT), + "CELL_FILTER": f"{enabled.cell},{control.cell}", + "GATE_DIR": directory, + "CKPT_ROOT": str(destination_root), + "LOG_ROOT": str(log_root), + } + ) + result = subprocess.run( + ["bash", str(CONTINUATION_PACK), "--dry-run"], + cwd=ROOT, + env=env, + check=True, + capture_output=True, + text=True, + ) + output = result.stdout + self.assertEqual( + output.count("[visual-rsm-rec-cont] command="), 2) + self.assertIn(f"RESUME_CKPT={enabled_source}", output) + self.assertIn( + f"RESUME_CKPT_SHA256={enabled_sha}", output) + self.assertIn("TRAIN_STEPS=100000", output) + self.assertIn("first_composed_update=50001", output) + self.assertIn( + "first_composed_update=none_through_step100000", output) + self.assertIn("REC_AFTER=50000", output) + self.assertIn("REC_AFTER=1000000000", output) + self.assertIn("gate_sha256=", output) + self.assertIn("source_sha256=", output) + self.assertIn("no_training=true no_submission=true", output) + self.assertFalse(destination_root.exists()) + self.assertFalse(log_root.exists()) + + missing_filter_env = dict(env) + missing_filter_env.pop("CELL_FILTER") + rejected = subprocess.run( + ["bash", str(CONTINUATION_PACK), "--dry-run"], + cwd=ROOT, + env=missing_filter_env, + capture_output=True, + text=True, + ) + self.assertNotEqual(rejected.returncode, 0) + self.assertIn( + "CELL_FILTER is required", rejected.stderr) + + def test_continuation_scheduler_is_preemptable_and_dry_by_default(self): + cell = next( + item for item in load_manifest(MANIFEST) + if item.composition == "on" + ) + with tempfile.TemporaryDirectory() as directory: + _passing_continuation_gate(directory, cell) + env = os.environ.copy() + env.update( + { + "CF": str(ROOT), + "PY": sys.executable, + "PYTHONPATH": str(ROOT), + "CELL_FILTER": cell.cell, + "GATE_DIR": directory, + "CKPT_ROOT": str(Path(directory) / "destinations"), + "LOG_ROOT": str(Path(directory) / "logs"), + } + ) + result = subprocess.run( + ["bash", str(CONTINUATION_SUBMIT)], + cwd=ROOT, + env=env, + check=True, + capture_output=True, + text=True, + ) + output = result.stdout + self.assertEqual( + output.count("num=1:mode=shared:j_exclusive=yes"), 1) + self.assertIn("-q preemptable", output) + self.assertIn("-G grp_preemptable", output) + self.assertIn("PACK_DRY_RUN=0", output) + self.assertIn(f"CELL_FILTER={cell.cell}", output) + self.assertIn("dry-run only; no submission", output) + + def test_pack_dry_run_expands_all_explicit_recursion_parameters(self): + env = os.environ.copy() + env.update( + { + "CF": str(ROOT), + "PY": sys.executable, + "PYTHONPATH": str(ROOT), + "RDEC": str(ROOT / "does-not-exist-reader.npz"), + } + ) + result = subprocess.run( + ["bash", str(PACK), "--dry-run"], + cwd=ROOT, + env=env, + check=True, + capture_output=True, + text=True, + ) + output = result.stdout + self.assertEqual( + output.count("[visual-rsm-rec-sweep] command="), 6 + ) + self.assertIn("GAMMA=0.99", output) + self.assertIn("BETA=0.985", output) + self.assertIn("REC_DEPTH=8", output) + self.assertIn("BETA_SAMPLE_PROB=0.4", output) + self.assertIn("TRAIN_STEPS=50000", output) + self.assertIn("REC_AFTER=50000", output) + self.assertIn("REC_AFTER=1000000000", output) + self.assertIn("OCC_ACTION_NEGATIVE=actor_local", output) + self.assertIn("ACTOR_AFTER=0", output) + self.assertIn("occupancy_actor_joint_update=true", output) + + def test_scheduler_dry_run_requests_exactly_one_gpu(self): + env = os.environ.copy() + env.update( + { + "PY": sys.executable, + "PYTHONPATH": str(ROOT), + } + ) + result = subprocess.run( + ["bash", str(SUBMIT)], + cwd=ROOT, + env=env, + check=True, + capture_output=True, + text=True, + ) + output = result.stdout + self.assertEqual( + output.count("num=1:mode=shared:j_exclusive=yes"), 1 + ) + self.assertNotIn("/task", output) + self.assertIn("exactly one preemptable GPU allocation", output) + self.assertIn("composition remains inactive", output) + + def test_shell_and_static_method_contracts(self): + for script in ( + PACK, + SUBMIT, + TRAIN, + CONTINUATION_PACK, + CONTINUATION_SUBMIT, + ): + subprocess.run(["bash", "-n", str(script)], check=True) + train_source = TRAIN.read_text(encoding="utf-8") + pack_source = PACK.read_text(encoding="utf-8") + submit_source = SUBMIT.read_text(encoding="utf-8") + continuation_pack_source = CONTINUATION_PACK.read_text( + encoding="utf-8") + continuation_submit_source = CONTINUATION_SUBMIT.read_text( + encoding="utf-8") + for literal in ( + "--drop_proprio", + "--latent_update frozen", + "--occupancy_model flow", + "--gamma \"$GAMMA\"", + "--recursion occupancy", + "--rec_beta \"$BETA\"", + "--rec_beta_sample_prob \"$BETA_SAMPLE_PROB\"", + "--rec_max_depth \"$REC_DEPTH\"", + ): + self.assertIn(literal, train_source) + self.assertNotIn("--freeze_occupancy", train_source) + self.assertIn('ACTOR_AFTER=0', pack_source) + self.assertIn('REC_STATE=hidden', pack_source) + self.assertIn('READER_TAG=indexd4_diagmetric', pack_source) + self.assertIn( + '-gpu "num=1:mode=shared:j_exclusive=yes"', submit_source + ) + self.assertIn("PACK_DRY_RUN=0", submit_source) + self.assertNotIn("num=1/task", submit_source) + self.assertIn( + '--resume_ckpt "$RESUME_CKPT"', train_source) + self.assertIn( + '--resume_ckpt_sha256 "$RESUME_CKPT_SHA256"', + train_source, + ) + self.assertIn( + "CELL_FILTER is required", continuation_pack_source) + self.assertIn( + "TRAIN_STEPS=100000", continuation_pack_source) + self.assertIn( + "gate_sha256=%s", continuation_pack_source) + self.assertIn( + "source_sha256=%s", continuation_pack_source) + self.assertIn( + '-q "$QUEUE"', continuation_submit_source) + self.assertIn( + "PACK_DRY_RUN=0", continuation_submit_source) + self.assertEqual(CONTINUATION_STEPS, 100_000) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_reward_semantics.py b/gen_q_rsm/ogbench_genq/test_visual_reward_semantics.py new file mode 100644 index 0000000000000000000000000000000000000000..165cfbd8e8456d65b098fefbe83ae6a38599685b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_reward_semantics.py @@ -0,0 +1,149 @@ +"""CPU unit gates for the standalone visual reward-semantics audit.""" + +import os +import tempfile +import unittest + +import numpy as np + +from ogbench_genq.genq.diagnose_visual_reward_semantics import ( + episode_layout, + load_reader, + sample_far_same_episode, +) +from ogbench_genq.genq.reward_reader import load_numpy_reward_reader + + +def _save_production_metric(path): + """Write the exact schema emitted by train_reward_decoder.py.""" + np.savez( + path, + zdim=np.asarray(3), + hidden=np.asarray(256), + reader_model=np.asarray("diag_metric"), + activation=np.asarray("tanh"), + features=np.asarray("symmetric"), + target=np.asarray("index"), + index_delta=np.asarray(4), + neg_gap=np.asarray(64), + cross_neg_frac=np.asarray(0.5), + gciql_discount=np.asarray(0.99), + gciql_p_curgoal=np.asarray(0.2), + gciql_p_trajgoal=np.asarray(0.5), + gciql_p_randomgoal=np.asarray(0.3), + pixels_only_latents=np.asarray(True), + frozen_encoder=np.asarray(True), + uses_coordinates_for_training=np.asarray(False), + uses_coordinates_for_diagnostics=np.asarray(False), + uses_reward_arrays=np.asarray(False), + uses_td_or_bootstrap=np.asarray(False), + label_source=np.asarray( + "trajectory_index_positive_and_far_negative_relabeling"), + metric_scale=np.asarray([0.5, 2.0, 4.0], np.float32), + metric_weight=np.asarray([1.0, 2.0, 3.0], np.float32), + metric_bias=np.asarray(2.0, np.float32), + ) + + +class VisualRewardSemanticsTest(unittest.TestCase): + def test_diag_metric_reader_is_exactly_symmetric(self): + with tempfile.TemporaryDirectory( + prefix="visual_reward_semantics_", dir="/tmp") as directory: + reader = os.path.join(directory, "diag_metric.npz") + _save_production_metric(reader) + probability, metadata = load_reader(reader) + first = np.asarray( + [[0.0, 1.0, 2.0], [3.0, -1.0, 0.5]], np.float32) + second = np.asarray( + [[0.5, -1.0, 1.5], [2.0, 0.0, 0.0]], np.float32) + np.testing.assert_allclose( + probability(first, second), + probability(second, first), + rtol=0.0, + atol=0.0, + ) + self.assertEqual(metadata["reader_model"], "diag_metric") + self.assertEqual(metadata["index_delta"], 4) + + def test_far_sampler_respects_episode_and_gap(self): + terminals = np.zeros(400, bool) + terminals[199::200] = True + _, _, start_of, end_of, episode_of = episode_layout(terminals) + rows = np.asarray([0, 63, 64, 100, 135, 199, 200, 263, 399]) + negatives = sample_far_same_episode( + np.random.default_rng(7), rows, start_of, end_of, 64) + self.assertTrue(np.all( + episode_of[rows] == episode_of[negatives])) + self.assertTrue(np.all(np.abs(rows - negatives) >= 64)) + + def test_production_diag_metric_schema_uses_metric_scale(self): + with tempfile.TemporaryDirectory( + prefix="visual_reward_semantics_", dir="/tmp") as directory: + reader = os.path.join(directory, "production_diag_metric.npz") + _save_production_metric(reader) + standalone, metadata = load_reader(reader) + canonical, canonical_metadata = load_numpy_reward_reader( + reader, probability=True) + future = np.asarray( + [[0.5, 4.0, 8.0], [1.0, -2.0, 0.0]], np.float32) + goal = np.zeros_like(future) + scale = np.asarray([0.5, 2.0, 4.0], np.float32) + weight = np.asarray([1.0, 2.0, 3.0], np.float32) + logits = 2.0 - np.sum( + weight * np.square((future - goal) / scale), axis=-1) + expected = 1.0 / ( + 1.0 + np.exp(-np.clip(logits, -30.0, 30.0))) + np.testing.assert_allclose( + standalone(future, goal), expected, rtol=0.0, atol=0.0) + np.testing.assert_array_equal( + standalone(future, goal), canonical(future, goal)) + np.testing.assert_array_equal( + metadata["metric_scale"], scale) + np.testing.assert_array_equal( + metadata["metric_weight"], weight) + self.assertEqual( + metadata["reader_model"], + canonical_metadata["reader_model"]) + self.assertFalse(metadata["uses_coordinates_for_training"]) + self.assertFalse(metadata["uses_coordinates_for_diagnostics"]) + self.assertFalse(metadata["uses_reward_arrays"]) + self.assertFalse(metadata["uses_td_or_bootstrap"]) + + def test_legacy_mlp_without_reader_model_remains_supported(self): + with tempfile.TemporaryDirectory( + prefix="visual_reward_semantics_", dir="/tmp") as directory: + reader = os.path.join(directory, "legacy_mlp.npz") + np.savez( + reader, + target=np.asarray("index"), + index_delta=np.asarray(0), + neg_gap=np.asarray(2), + zdim=np.asarray(1), + features=np.asarray("concat"), + activation=np.asarray("tanh"), + **{ + "g0.kernel": np.asarray([[1.0], [-1.0]], np.float32), + "g0.bias": np.asarray([0.0], np.float32), + "g1.kernel": np.asarray([[2.0]], np.float32), + "g1.bias": np.asarray([0.0], np.float32), + "g2.kernel": np.asarray([[0.5]], np.float32), + "g2.bias": np.asarray([0.25], np.float32), + }, + ) + probability, metadata = load_reader(reader) + first = np.asarray([[1.0], [2.0]], np.float32) + second = np.asarray([[0.5], [-1.0]], np.float32) + hidden = np.tanh(np.concatenate( + [first, second], axis=-1) + @ np.asarray([[1.0], [-1.0]], np.float32)) + hidden = np.tanh(hidden * np.float32(2.0)) + logits = hidden[:, 0] * np.float32(0.5) + np.float32(0.25) + expected = 1.0 / ( + 1.0 + np.exp(-np.clip(logits, -30.0, 30.0))) + np.testing.assert_array_equal( + probability(first, second), expected) + self.assertEqual(metadata["reader_model"], "mlp") + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/test_visual_rsm_actor_eval.py b/gen_q_rsm/ogbench_genq/test_visual_rsm_actor_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..90c0788d8c4ada588dc6f6620a994c790bb813d0 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/test_visual_rsm_actor_eval.py @@ -0,0 +1,575 @@ +"""CPU-only contracts for the official raw-pixel RSM actor evaluator.""" + +import copy +import hashlib +import os +import tempfile +import unittest +from pathlib import Path + +import numpy as np + +from ogbench_genq.genq.eval_visual_rsm_pixel_actor import ( + ACTION_SHAPE, + ACTOR_ARCHITECTURE, + CheckpointContractError, + ENV, + FORBIDDEN_DATASET_KEYS, + OBSERVATION_SHAPE, + PIXEL_SCORER_TARGET_UPDATE_SOURCE, + PIXEL_SCORER_TARGET_UPDATE_TIMING, + PIXEL_SCORER_TARGET_UPDATE_TAU, + PIXEL_DATASET_KEYS, + REFERENCE_PROVENANCE_FILES, + TERMINAL_ALIGNMENT_CONTRACT, + VISUAL_GCIQL_BATCH_SIZE, + _reference_sha256, + actor_parameter_sha256, + validate_actor_parameter_tree, + validate_rsm_checkpoint_contract, +) + + +def _actor(value): + return { + "actor_net": {"kernel": np.full((2, 2), value, np.float32)}, + "gc_encoder": {"kernel": np.full((2, 3), value, np.float32)}, + "mean_net": {"kernel": np.full((2, 5), value, np.float32)}, + } + + +def _pixel_value(value): + return { + "gc_encoder": { + "kernel": np.full((2, 3), value, np.float32)}, + "value_net": { + "kernel": np.full((2, 2), value, np.float32)}, + } + + +def _payload(): + live = _actor(1.0) + ema = _actor(2.0) + dataset_sha = "3" * 64 + meta = { + "schema_version": 10, + "env": ENV, + "seed": 0, + "drop_proprio": True, + "actor_input": "pixels", + "actor_state_feature": "raw_rgb_pixels", + "actor_goal_feature": "raw_rgb_pixels", + "final_actor_consumes_pixels": True, + "policy_observation": "rendered_pixels_only", + "actor_architecture": ACTOR_ARCHITECTURE, + "actor_encoder": "impala_small", + "actor_encoder_trainable": True, + "actor_encoder_initialization": "fresh_jointly_trainable", + "actor_pixel_augmentation_probability": 0.5, + "actor_training_augmentation": + "batch_probability_shared_per_row_edge_padded_random_crop", + "actor_goal_relabeling": "uniform_future_same_trajectory", + "actor_pixel_state_shape": list(OBSERVATION_SHAPE), + "actor_pixel_goal_shape": list(OBSERVATION_SHAPE), + "actor_goal_dim_semantics": + "latent_supervised_scorer_goal_width", + "actor_transition_sampling": "uniform_over_dataset_valid_indices", + "occupancy_consumes_raw_pixels": False, + "raw_pixels_update_actor_only": True, + "pixel_dataset_device_transport": + "dynamic_jit_dispatch_argument_not_xla_constant", + "pixel_actor_init": None, + "pixel_actor_occupancy_discount_required": True, + "pixel_actor_recursion_supported": False, + "pixel_actor_generated_midpoint_policy": None, + "pixel_actor_uses_image_or_world_model_reconstruction": False, + "completion_or_world_model_carrier_instantiated": False, + "uses_td_or_bootstrap": False, + "occupancy_uses_reward_labels": False, + "occupancy_uses_simulator_coordinates": False, + "uses_completion_or_forward_model": False, + "occ_reader_metric_uses_reward_arrays": False, + "occ_reader_metric_uses_coordinates": False, + "occ_reader_metric_uses_td_or_bootstrap": False, + "discount_conditioned": True, + "discount_feature": "fourier_log_horizon", + "gamma": 0.99, + "gamma_spectrum_lo": 0.5, + "occupancy_and_actor_jointly_updated": True, + "pixel_actor_and_occupancy_same_fused_step": True, + "freeze_occupancy": False, + "actor_gradient_updates_occupancy": False, + "occupancy_gradient_updates_actor": False, + "reward_decoder_model": "diag_metric", + "reward_decoder_target": "index", + "recursion": "off", + "state_feature": "encoder_hidden", + "occupancy_goal_feature": "encoder_hidden", + "future_feature": "frozen_encoder_hidden_occupancy_state", + "reward_goal_feature": "compact_reward_predictive_z", + "actor_loss": "ddpgbc_distill", + "pixel_actor_dataset": { + "dataset_keys": sorted(PIXEL_DATASET_KEYS), + "excluded_keys": sorted(FORBIDDEN_DATASET_KEYS), + "observation_shape": list(OBSERVATION_SHAPE), + "observation_dtype": "uint8", + "action_shape": list(ACTION_SHAPE), + "row_count": 100, + "valid_transition_count": 90, + "actions_match_latent_cache": True, + "source_terminals_match_latent_cache": True, + "compact_terminals_match_reconstructed": True, + "terminal_alignment_contract": TERMINAL_ALIGNMENT_CONTRACT, + "path": "/artifact/pixels.npz", + "sha256": dataset_sha, + }, + "pixel_artifact_provenance": { + "latent_npz": { + "path": "/artifact/latents.npz", "sha256": "1" * 64}, + "pixel_encoder": { + "path": "/artifact/encoder.npz", "sha256": "2" * 64}, + "pixel_dataset": { + "path": "/artifact/pixels.npz", "sha256": dataset_sha}, + }, + } + carry = ( + {}, (), {}, None, None, None, + (live, object(), {}, object(), {}, object(), {}), + ema, np.zeros(2, np.uint32), np.asarray(100, np.int32), + ) + return { + "carry": carry, + "next_di": 2, + "train_steps": 1000, + "seed": 0, + "env": ENV, + "run_meta": meta, + } + + +def _pixel_scorer_payload( + actor_loss="ddpgbc_distill", counterfactual_support=False): + payload = _payload() + meta = payload["run_meta"] + awr = actor_loss == "awr_distill" + assert awr or actor_loss == "ddpgbc_distill" + meta.update({ + "schema_version": 13, + "actor_loss": actor_loss, + "alpha": 30.0 if awr else 1.0, + "expectile": 0.9, + "actor_goal_dim_semantics": + "raw_rgb_pixel_scorer_goal_shape", + "raw_pixels_update_actor_only": False, + "supervised_scalar_scorer_state_for_pixel_actor": + "raw_rgb_pixels", + "distill_scorer_input": "pixels", + "supervised_scalar_scorer_input": "raw_rgb_pixels", + "supervised_scalar_scorer_goal_input": "raw_rgb_pixels", + "supervised_scalar_scorer_architecture": + "GCValue_IMPALA_small_early_fusion_twin_MLP_512x3", + "supervised_scalar_scorer_encoder": "impala_small", + "supervised_scalar_scorer_encoder_trainable": True, + "supervised_scalar_scorer_ensemble_size": 2, + "supervised_scalar_scorer_target_update_source": + PIXEL_SCORER_TARGET_UPDATE_SOURCE, + "supervised_scalar_scorer_target_update_timing": + PIXEL_SCORER_TARGET_UPDATE_TIMING, + "supervised_scalar_scorer_target_update_tau": + PIXEL_SCORER_TARGET_UPDATE_TAU, + "supervised_scalar_scorer_recorded_action_target_source": + "observed_same_trajectory_absorbing_first_passage_geometric_" + "successor_compact_z_through_frozen_index_reader", + "supervised_scalar_scorer_recorded_action_uses_occupancy": False, + "supervised_scalar_scorer_counterfactual_target_source": ( + "discount_conditioned_ema_occupancy_index_reader_expectation" + if counterfactual_support else None), + "supervised_scalar_scorer_counterfactual_uses_empirical": ( + False if counterfactual_support else None), + "supervised_scalar_scorer_target_discount": + "explicit_task_gamma", + "supervised_scalar_scorer_receives_discount_feature": False, + "supervised_scalar_scorer_training_augmentation": + "batch_probability_shared_per_row_across_state_value_goal_" + "actor_goal_edge_padded_random_crop", + "supervised_scalar_scorer_uses_proprio": False, + "supervised_scalar_scorer_uses_coordinates": False, + "supervised_scalar_scorer_uses_reward_arrays": False, + "supervised_scalar_scorer_uses_td_or_bootstrap": False, + "supervised_expectile_value_input": "raw_rgb_pixels", + "supervised_expectile_value_architecture": + "GCValue_IMPALA_small_early_fusion_single_MLP_512x3", + "supervised_expectile_value_target_source": + "stop_gradient_ema_twin_pixel_scorer_empirical_absorbing_" + "index_return_expectile", + "supervised_expectile_value_target_discount": + "explicit_task_gamma", + "supervised_expectile_value_uses_next_state": False, + "supervised_expectile_value_uses_td_or_bootstrap": False, + "supervised_expectile_value_uses_reward_arrays": False, + "pixel_scorer_policy_extraction": ( + "awr_dataset_action_weighted_log_likelihood" + if awr else "ddpgbc_actor_gradient_control"), + "pixel_scorer_actor_advantage_source": ( + "stop_gradient_live_twin_min_q_minus_preupdate_expectile_v" + if awr else None), + "pixel_scorer_actor_weight_formula": ( + "min(exp(alpha*(Q-V)),100)" if awr else None), + "pixel_scorer_actor_uses_dataset_actions_only": awr, + "pixel_scorer_supervision_regime": ( + "empirical_recorded_actions_plus_discount_conditioned_" + "occupancy_counterfactuals" + if counterfactual_support + else "empirical_recorded_actions_only"), + "pixel_scorer_and_occupancy_same_fused_step": True, + "pixel_scorer_and_actor_same_fused_step": True, + "pixel_scorer_gradient_updates_occupancy": False, + "occupancy_gradient_updates_pixel_scorer": False, + "batch_size": VISUAL_GCIQL_BATCH_SIZE, + "distill_ema_tau": PIXEL_SCORER_TARGET_UPDATE_TAU, + "distill_actor_actions": bool(counterfactual_support), + "distill_empirical_index_enabled": True, + "distill_empirical_index_weight": 1.0, + "distill_empirical_index_behavior_action_only": True, + "distill_empirical_index_counterfactual_action_source": ( + "none_awr_dataset_actions_only" + if awr + else "discount_conditioned_ema_occupancy" + if counterfactual_support + else "none_behavior_only_scorer_supervision"), + "distill_empirical_index_target_source": + "observed_same_trajectory_absorbing_first_passage_geometric_" + "successor_compact_z_through_frozen_index_reader", + "distill_empirical_index_horizon": + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount", + "distill_empirical_index_blend_formula": + "recorded_successor_reader_expectation_only", + "distill_empirical_index_samples": 16, + "distill_empirical_index_uses_reward_arrays": False, + "distill_empirical_index_uses_coordinates": False, + "distill_empirical_index_uses_td_or_bootstrap": False, + "distill_empirical_index_recorded_action_uses_occupancy": False, + "distill_empirical_index_counterfactual_uses_empirical": ( + False if counterfactual_support else None), + }) + carry = list(payload["carry"]) + agent = list(carry[6]) + agent[2] = _pixel_value(3.0) + agent[4] = _pixel_value(4.0) + carry[6] = tuple(agent) + payload["carry"] = tuple(carry) + return payload + + +def _reader_metric_pixel_scorer_payload(counterfactual_support=False): + payload = _pixel_scorer_payload( + "ddpgbc_distill", counterfactual_support) + payload["run_meta"].update({ + "future_feature": "goal_relative_reader_metric_u", + "occupancy_target_space": "goal_relative_reader_metric", + "occupancy_target_invertible": True, + "occupancy_target_reader_frozen": True, + "occupancy_target_reader_model": "diag_metric", + "occupancy_target_reader_target": "index", + "occupancy_target_goal_feature": + "compact_reward_predictive_z", + "occupancy_decoded_future_feature": + "compact_reward_predictive_z", + "occupancy_target_uses_index_relabeling": True, + "occupancy_target_uses_reward_arrays": False, + "occupancy_target_uses_coordinates": False, + "occupancy_target_uses_td_or_bootstrap": False, + "reader_metric_pixel_scorer_combined": True, + "reader_metric_pixel_scorer_update_semantics": + "same_fused_step_separate_gradients", + }) + return payload + + +class CheckpointContractTest(unittest.TestCase): + def test_selects_live_and_ema_actor(self): + payload = _payload() + live = validate_rsm_checkpoint_contract(payload, "live") + ema = validate_rsm_checkpoint_contract(payload, "ema") + self.assertIs(live["actor_params"], payload["carry"][6][0]) + self.assertIs(ema["actor_params"], payload["carry"][7]) + self.assertEqual(ema["checkpoint_step"], 100) + + def test_rejects_every_forbidden_training_channel(self): + cases = { + "proprioception": ("drop_proprio", False), + "latent_actor_input": ("actor_input", "latent"), + "not_rendered": ("policy_observation", "latent"), + "coordinate": ("occupancy_uses_simulator_coordinates", True), + "reward_array": ("occupancy_uses_reward_labels", True), + "td_bootstrap": ("uses_td_or_bootstrap", True), + "completion": ("uses_completion_or_forward_model", True), + "undiscounted": ("discount_conditioned", False), + "not_joint": ("occupancy_and_actor_jointly_updated", False), + } + for name, (key, value) in cases.items(): + with self.subTest(name=name): + payload = _payload() + payload["run_meta"][key] = value + with self.assertRaisesRegex( + CheckpointContractError, key): + validate_rsm_checkpoint_contract(payload) + + def test_rejects_privileged_or_misaligned_dataset(self): + payload = _payload() + payload["run_meta"]["pixel_actor_dataset"]["dataset_keys"].append( + "qpos") + payload["run_meta"]["pixel_actor_dataset"][ + "source_terminals_match_latent_cache"] = False + with self.assertRaises(CheckpointContractError) as caught: + validate_rsm_checkpoint_contract(payload) + self.assertIn("dataset_keys", str(caught.exception)) + self.assertIn( + "source_terminals_match_latent_cache", str(caught.exception)) + + def test_rejects_completion_state_even_if_metadata_claims_none(self): + payload = _payload() + carry = list(payload["carry"]) + carry[3] = {"completion": np.zeros(1)} + payload["carry"] = tuple(carry) + with self.assertRaisesRegex( + CheckpointContractError, "completion/world-model"): + validate_rsm_checkpoint_contract(payload) + + def test_empirical_index_anchor_must_remain_pixels_only_and_non_td(self): + payload = _payload() + payload["run_meta"].update({ + "schema_version": 12, + "distill_empirical_index_enabled": True, + "distill_empirical_index_weight": 1.0, + "distill_empirical_index_behavior_action_only": True, + "distill_empirical_index_counterfactual_action_source": + "discount_conditioned_ema_occupancy", + "distill_empirical_index_target_source": + "observed_same_trajectory_absorbing_first_passage_" + "geometric_successor_compact_z_through_frozen_index_reader", + "distill_empirical_index_horizon": + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount", + "distill_empirical_index_blend_formula": + "(1-weight)*ema_occupancy_reader_expectation" + "+weight*recorded_successor_reader_expectation", + "distill_empirical_index_samples": 16, + "distill_empirical_index_uses_reward_arrays": False, + "distill_empirical_index_uses_coordinates": False, + "distill_empirical_index_uses_td_or_bootstrap": False, + }) + validate_rsm_checkpoint_contract(payload) + for key in ( + "distill_empirical_index_uses_reward_arrays", + "distill_empirical_index_uses_coordinates", + "distill_empirical_index_uses_td_or_bootstrap"): + with self.subTest(key=key): + invalid = copy.deepcopy(payload) + invalid["run_meta"][key] = True + with self.assertRaisesRegex( + CheckpointContractError, key): + validate_rsm_checkpoint_contract(invalid) + invalid = copy.deepcopy(payload) + invalid["run_meta"]["distill_empirical_index_target_source"] = ( + "raw_unabsorbed_geometric_successor") + with self.assertRaisesRegex( + CheckpointContractError, + "distill_empirical_index_target_source"): + validate_rsm_checkpoint_contract(invalid) + invalid = copy.deepcopy(payload) + invalid["run_meta"]["distill_empirical_index_enabled"] = False + with self.assertRaisesRegex( + CheckpointContractError, "schema_version >= 12"): + validate_rsm_checkpoint_contract(invalid) + + def test_schema13_metric_target_is_allowed_only_with_fair_provenance(self): + payload = _payload() + payload["run_meta"].update({ + "schema_version": 13, + "future_feature": "goal_relative_reader_metric_u", + "distill_empirical_index_enabled": True, + "distill_empirical_index_weight": 1.0, + "distill_empirical_index_behavior_action_only": True, + "distill_empirical_index_counterfactual_action_source": + "discount_conditioned_ema_occupancy", + "distill_empirical_index_target_source": + "observed_same_trajectory_absorbing_first_passage_" + "geometric_successor_compact_z_through_frozen_index_reader", + "distill_empirical_index_horizon": + "finite_trajectory_truncated_geometric_absorbing_first_" + "passage_explicit_task_discount", + "distill_empirical_index_blend_formula": + "(1-weight)*ema_occupancy_reader_expectation" + "+weight*recorded_successor_reader_expectation", + "distill_empirical_index_samples": 16, + "distill_empirical_index_uses_reward_arrays": False, + "distill_empirical_index_uses_coordinates": False, + "distill_empirical_index_uses_td_or_bootstrap": False, + "occupancy_target_space": "goal_relative_reader_metric", + "occupancy_target_invertible": True, + "occupancy_target_reader_frozen": True, + "occupancy_target_reader_model": "diag_metric", + "occupancy_target_reader_target": "index", + "occupancy_target_goal_feature": + "compact_reward_predictive_z", + "occupancy_decoded_future_feature": + "compact_reward_predictive_z", + "occupancy_target_uses_index_relabeling": True, + "occupancy_target_uses_reward_arrays": False, + "occupancy_target_uses_coordinates": False, + "occupancy_target_uses_td_or_bootstrap": False, + }) + validate_rsm_checkpoint_contract(payload) + invalid = copy.deepcopy(payload) + invalid["run_meta"]["occupancy_target_uses_coordinates"] = True + with self.assertRaisesRegex( + CheckpointContractError, + "occupancy_target_uses_coordinates"): + validate_rsm_checkpoint_contract(invalid) + + def test_schema13_accepts_behavior_only_ddpg_and_awr_pixel_scorers(self): + validate_rsm_checkpoint_contract( + _pixel_scorer_payload( + "ddpgbc_distill", counterfactual_support=False)) + validate_rsm_checkpoint_contract( + _pixel_scorer_payload( + "ddpgbc_distill", counterfactual_support=True)) + validate_rsm_checkpoint_contract( + _pixel_scorer_payload("awr_distill")) + + def test_schema13_rejects_occupancy_recorded_target_and_missing_encoder(self): + payload = _pixel_scorer_payload() + payload["run_meta"][ + "supervised_scalar_scorer_recorded_action_uses_occupancy" + ] = True + with self.assertRaisesRegex( + CheckpointContractError, + "recorded_action_uses_occupancy"): + validate_rsm_checkpoint_contract(payload) + + payload = _pixel_scorer_payload() + del payload["carry"][6][4]["gc_encoder"] + with self.assertRaisesRegex( + CheckpointContractError, + "twin scorer parameter groups"): + validate_rsm_checkpoint_contract(payload) + + def test_schema13_rejects_next_state_or_td_value_claims(self): + for key in ( + "supervised_expectile_value_uses_next_state", + "supervised_expectile_value_uses_td_or_bootstrap", + "supervised_scalar_scorer_uses_td_or_bootstrap"): + with self.subTest(key=key): + payload = _pixel_scorer_payload("awr_distill") + payload["run_meta"][key] = True + with self.assertRaisesRegex( + CheckpointContractError, key): + validate_rsm_checkpoint_contract(payload) + + def test_schema13_rejects_nonreference_batch_or_target_update(self): + cases = ( + ("batch_size", 4096), + ("distill_ema_tau", 0.01), + ("supervised_scalar_scorer_target_update_source", + "preupdate_live_twin_pixel_scorer"), + ("supervised_scalar_scorer_target_update_timing", + "before_current_gradient_update"), + ("supervised_scalar_scorer_target_update_tau", 0.01), + ) + for key, value in cases: + with self.subTest(key=key): + payload = _pixel_scorer_payload() + payload["run_meta"][key] = value + with self.assertRaisesRegex( + CheckpointContractError, key): + validate_rsm_checkpoint_contract(payload) + + def test_schema13_accepts_combined_metric_flow_and_pixel_scorer(self): + for counterfactual_support in (False, True): + with self.subTest( + counterfactual_support=counterfactual_support): + validate_rsm_checkpoint_contract( + _reader_metric_pixel_scorer_payload( + counterfactual_support)) + + for key, value in ( + ("reader_metric_pixel_scorer_combined", False), + ("reader_metric_pixel_scorer_update_semantics", "coupled"), + ("occupancy_target_uses_td_or_bootstrap", True), + ("supervised_scalar_scorer_uses_td_or_bootstrap", True)): + with self.subTest(key=key): + payload = _reader_metric_pixel_scorer_payload() + payload["run_meta"][key] = value + with self.assertRaisesRegex( + CheckpointContractError, key): + validate_rsm_checkpoint_contract(payload) + + def test_rejects_inconsistent_step(self): + payload = _payload() + payload["next_di"] = 3 + with self.assertRaisesRegex( + CheckpointContractError, "next_di"): + validate_rsm_checkpoint_contract(payload) + + +class ActorTreeContractTest(unittest.TestCase): + def test_actor_digest_is_deterministic_and_value_sensitive(self): + first, count = actor_parameter_sha256(_actor(1.0)) + second, second_count = actor_parameter_sha256(_actor(1.0)) + changed, _ = actor_parameter_sha256(_actor(2.0)) + self.assertEqual(first, second) + self.assertEqual(count, second_count) + self.assertNotEqual(first, changed) + + def test_tree_validator_rejects_shape_and_nonfinite(self): + expected = _actor(1.0) + actual = copy.deepcopy(expected) + actual["mean_net"]["kernel"] = np.zeros((3, 5), np.float32) + with self.assertRaisesRegex( + CheckpointContractError, "parameter tree"): + validate_actor_parameter_tree(actual, expected) + actual = copy.deepcopy(expected) + actual["mean_net"]["kernel"][0, 0] = np.nan + with self.assertRaisesRegex( + CheckpointContractError, "non-finite"): + validate_actor_parameter_tree(actual, expected) + + +class ReferenceAndLauncherContractTest(unittest.TestCase): + def test_saved_reference_hash_covers_exact_four_files(self): + with tempfile.TemporaryDirectory() as temporary: + for index, relative_path in enumerate( + REFERENCE_PROVENANCE_FILES): + path = Path(temporary, relative_path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(f"file-{index}".encode()) + expected = hashlib.sha256() + for index, relative_path in enumerate( + REFERENCE_PROVENANCE_FILES): + expected.update(relative_path.encode()) + expected.update(f"file-{index}".encode()) + self.assertEqual( + _reference_sha256( + temporary, REFERENCE_PROVENANCE_FILES), + expected.hexdigest(), + ) + + def test_launcher_pins_cpu_policy_and_egl_renderer(self): + launcher = Path(__file__).parent / ( + "experiments/eval_visual_rsm_pixel_actor.sh") + source = launcher.read_text() + for contract in ( + "JAX_PLATFORMS=cpu", + "MUJOCO_GL=egl", + "OMP_NUM_THREADS", + "--expected_checkpoint_sha256", + "--actor", + "--episodes", + ): + self.assertIn(contract, source) + + +if __name__ == "__main__": + unittest.main() diff --git a/gen_q_rsm/ogbench_genq/train_compplan_gcbc.sh b/gen_q_rsm/ogbench_genq/train_compplan_gcbc.sh new file mode 100644 index 0000000000000000000000000000000000000000..c1833755384457648dd9f1f90c5cf97c32cb663c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/train_compplan_gcbc.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Faithful CompPlan GC-BC (paper Table 10): GEOMETRIC ("gamma-distributed") goal +# sampling + longer training, NOT OGBench-standard uniform-future GCBC. For cube-3: +# discount {0.96,0.97,0.98}, 2M gradient steps. This is what makes their base 0.09 +# vs OGBench-standard 0.01 (uniform-future goals struggle on manipulation). +# train_compplan_gcbc.sh +set -uo pipefail +ENVN="$1"; DISC="$2"; STEPS="$3"; TAG="$4" +SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +R=$(cd -- "$SCRIPT_DIR/.." && pwd) +IMPLS=${OGBENCH_IMPLS:-/u/zwhong/ogbench_ref/impls} +PY=${PYTHON:-"$R/.ogbench_venv/bin/python"} +CKPT_ROOT=${GENQ_CKPT_ROOT:-/proj/inf-scaling/zwhong/gen_q/ckpt} +SAVE=$CKPT_ROOT/gcbc_compplan/${TAG} +export XLA_PYTHON_CLIENT_PREALLOCATE=false PYTHONUNBUFFERED=1 WANDB_MODE=offline +cd "$IMPLS" || exit 1 +mkdir -p "$SAVE" +echo "[compplan-gcbc] env=$ENVN geom_sample=True discount=$DISC steps=$STEPS save=$SAVE" +# GC-BC with GEOMETRIC actor-goal sampling at the paper's discount (nearby goals), +# 2M steps. actor_geom_sample=True + actor.discount sets the Geom(1-discount) horizon. +exec "$PY" -u main.py --env_name="$ENVN" --agent=agents/gcbc.py \ + --agent.actor_geom_sample=True --agent.discount="$DISC" \ + --train_steps="$STEPS" --eval_interval="$STEPS" --save_interval="$STEPS" \ + --eval_episodes=50 --video_episodes=0 --eval_on_cpu=1 \ + --save_dir="$SAVE" --run_group="gcbc_compplan" --seed=0 \ + 2>&1 | tee "$SAVE/train.log" diff --git a/gen_q_rsm/ogbench_genq/unused/README.md b/gen_q_rsm/ogbench_genq/unused/README.md new file mode 100644 index 0000000000000000000000000000000000000000..794299e5b3f6171c3a6e8b3dac9465642a2cf15d --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/README.md @@ -0,0 +1,30 @@ +# unused/ — archived designs (reference only) + +Everything in here was superseded by the RSM trainer (`../rsm.py`). It is kept +so the designs we tried remain inspectable — **why** each was dropped is +written up in [`../DESIGN.md`](../DESIGN.md), with the numbers in +[`../RESULTS.md`](../RESULTS.md) and [`../ABLATION.md`](../ABLATION.md). + +**These files are not maintained.** They may import modules that have moved +(e.g. drivers under `experiments/` still reference `ogbench_genq.genq_joint*` +at their old paths, and `_runner.py`'s legacy baseline entrypoints lazily +import `genq_jax` / `genq_discrete_jax` from here). If you need to actually +re-run one, either fix its imports or check out a commit from before the +2026-07-15 cleanup. + +| path | what it was | +|---|---| +| `rsm_graft.py` | experimental fork of `../rsm.py` for racing extra ELBO/guard levers (`--elbo_logspace`, `--elbo_antithetic`, `--rec_guard ema`) without touching the maintained trainer; unreferenced except by `scripts/run_pm_graft.sh`. The final algorithm is `../rsm.py`. | +| `genq_joint_fast.py` | the fused multi-variant trainer RSM was distilled from — all read-outs, 3-network carrier, cert/max recursion, kernel read-out behind flags | +| `genq_joint.py` | host-loop predecessor of `genq_joint_fast.py` | +| `genq_factored.py`, `genq_factored_dp.py` | factored per-coordinate occupancy (incoherent joint samples) | +| `genq_gliql.py` | GLIQL-style extraction carrier | +| `bc.py`, `gciql.py` | behavior-cloning and GCIQL baselines (numbers already recorded in `experiments/*/results/`) | +| `gciql_genq.py`, `gciql_ablate.py` | GCIQL with preloaded Gen-Q critic; step-by-step GCIQL→GenQ ablation harness | +| `make_figure.py` | figure generator for the legacy result JSON schema | +| `genq/` | staged-era occupancy modules: `genq_jax.py` (staged trainer), `genq_discrete_jax.py`, `genq_inpaint_jax.py` + `run_inpaint_eval.py`, `genq_recursive_jax.py` (value-distillation recursion) | +| `diagnostics/` | one-off Q-comparison / recursion-stitching diagnostics from the puzzle campaign | +| `experiments//train_*.py` | per-env driver scripts — replaced by `python ogbench_genq/rsm.py --env ` | +| `docs/` | campaign-era documentation: `EXPERIMENTS.md` (arm-by-arm ledger with job IDs and live curves), `VARIANTS.md` (puzzle-era equations + result ladder), `ABLATIONS.md` (original matrix + pseudocode), `BETA_RECURSION.md` (full runtime walkthrough), `DESIGN_HISTORY.md`, `BRANCHING.md` — all consolidated into the four docs at the package root | +| `scripts/` | LSF/SLURM launch scripts from the campaign (job-specific, stale paths) | +| `viz_goto_variant.py`, `goto_variant.gif` | earlier 3-scene explainer animation, superseded by the README figures | diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/aggregate_puzzle_sweep.py b/gen_q_rsm/ogbench_genq/unused/diagnostics/aggregate_puzzle_sweep.py new file mode 100644 index 0000000000000000000000000000000000000000..57269ff4b26383669b3ba267bf52c4471695b584 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/aggregate_puzzle_sweep.py @@ -0,0 +1,98 @@ +"""Aggregate the puzzle-3x3 Gen-Q fix-sweep results into a markdown table + curve figure. + +Reads every results/0/gciql_genq*.json / gciql*.json variant of puzzle-3x3-play-v0 and +emits: + - diagnostics/puzzle_sweep_table.md (variant, key config, best_sr, final sr) + - experiments/puzzle-3x3-play-v0/figures/fix_sweep.png (curves of the key cells) + +Run: .ogbench_venv/bin/python ogbench_genq/diagnostics/aggregate_puzzle_sweep.py +""" +import glob +import json +import os + +HERE = os.path.dirname(os.path.abspath(__file__)) +PKG = os.path.dirname(HERE) +RES = os.path.join(PKG, "experiments", "puzzle-3x3-play-v0", "results", "0") +FIGDIR = os.path.join(PKG, "experiments", "puzzle-3x3-play-v0", "figures") + + +def label(d, name): + m = d.get("method", "?") + if m == "gciql": + return f"GCIQL TD ({d.get('actor_loss')} α={d.get('alpha')})" + bits = [d.get("actor_loss", "?"), f"α={d.get('alpha')}"] + if d.get("sigma") not in (None, 0.5): + bits.append(f"σ={d['sigma']}") + if d.get("n_occ") not in (None, 64) and m != "gciql_genq_rec": + bits.append(f"n={d['n_occ']}") + if d.get("adv_norm"): + bits.append("advnorm") + if d.get("q_filter_k"): + bits.append(f"Qfilter{d['q_filter_k']}") + if m == "gciql_genq_rec": + bits.append(f"rec β={d.get('beta')}") + if d.get("midpoint_awr_alpha"): + bits.append(f"midAWR{d['midpoint_awr_alpha']}") + if d.get("greedy_k"): + bits.append(f"greedy{d['greedy_k']}") + return f"Gen-Q ({', '.join(bits)})" + + +def main(): + rows = [] + curves = {} + for f in sorted(glob.glob(os.path.join(RES, "*.json"))): + name = os.path.basename(f)[:-5] + if name in ("gcbc",): + continue + d = json.load(open(f)) + if d.get("method") not in ("gciql", "gciql_genq", "gciql_genq_rec"): + continue + cur = d.get("curve", []) + rows.append(dict(name=name, label=label(d, name), best=d.get("best_sr", 0.0), + final=d.get("success_rate", 0.0), + steps=(cur[-1][0] if cur else 0))) + curves[name] = cur + rows.sort(key=lambda r: -r["best"]) + + lines = ["| variant (results/0/*.json) | config | best sr | final sr | steps |", + "|---|---|---|---|---|"] + for r in rows: + lines.append(f"| `{r['name']}` | {r['label']} | **{r['best']:.3f}** | " + f"{r['final']:.3f} | {r['steps']//1000}k |") + table = "\n".join(lines) + out_md = os.path.join(HERE, "puzzle_sweep_table.md") + open(out_md, "w").write(table + "\n") + print(table) + print(f"\nwrote {out_md}") + + try: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + os.makedirs(FIGDIR, exist_ok=True) + key = [r["name"] for r in rows[:8]] + fig, ax = plt.subplots(figsize=(9, 5.5)) + for n in key: + c = curves.get(n) or [] + if not c: + continue + xs, ys = zip(*[(s / 1000, v) for s, v in c]) + style = dict(lw=2.5) if n.startswith("gciql_ref") else dict(lw=1.4, alpha=0.9) + ax.plot(xs, ys, marker="o", ms=3, label=n, **style) + ax.set_xlabel("train steps (k)") + ax.set_ylabel("success rate") + ax.set_title("puzzle-3x3-play-v0 — Gen-Q fix sweep (seed 0) vs TD baseline") + ax.legend(fontsize=7, loc="upper left") + ax.grid(alpha=0.3) + out_png = os.path.join(FIGDIR, "fix_sweep.png") + fig.tight_layout() + fig.savefig(out_png, dpi=140) + print(f"wrote {out_png}") + except Exception as e: # matplotlib may be absent on the login node + print(f"figure skipped: {e}") + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_puzzle_q.py b/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_puzzle_q.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc641ac51b101732ce323726683ba14798ed796 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_puzzle_q.py @@ -0,0 +1,163 @@ +"""Diagnose why the Gen-Q occupancy critic fails on puzzle-3x3 but works on cube. + +For each env, loads the trained occupancy ckpt (the exact one the failing PI run used) and +measures, at GCDataset-style (s, a, g) queries: + + 1. sample geometry — how close diffusion samples are to {0,1} vertices (puzzle), and how + far they wander vs REAL Geom(1-gamma) futures from the dataset; + 2. occupancy fit — rank corr of Q = mean_i exp(-||x_i-g||^2/2s^2) against the + in-trajectory discounted MC return of the SAME reward (the exact + quantity the occupancy Q estimates, so corr ~ fit quality); + 3. action SNR — spread of Q across actions at fixed (s,g) [signal AWR needs] + vs spread across independent occupancy draws [MC noise floor]; + 4. sigma sweep — all of the above readout metrics as a function of sigma. + +Run (CPU is fine): .ogbench_venv/bin/python ogbench_genq/diagnostics/diag_puzzle_q.py +""" +import json +import os +import sys + +import numpy as np + +HERE = os.path.dirname(os.path.abspath(__file__)) +PKG = os.path.dirname(HERE) +sys.path.insert(0, os.path.join(PKG, "genq")) +OGB = os.environ.get("OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls")) +sys.path.insert(0, OGB) + +import jax +import jax.numpy as jnp +from scipy import stats + +import target_extractors +from genq_jax import load_genq_params, sample as genq_sample +from train_genq_jax import build_ends, future_idx, sample_goal_after + +GAMMA = 0.99 +B = 1024 # query points +N_OCC = 64 # occupancy samples per query (matches failing run) +SIGMAS = [0.25, 0.5, 1.0, 1.5, 2.0, 3.0] + + +def mc_return(bits, t, g, end_of, gamma, sigma, horizon=600): + """Renormalized in-trajectory discounted return of r=exp(-||bits-g||^2/2s^2) from t.""" + out = np.zeros(len(t), dtype=np.float64) + for n, (ti, gi) in enumerate(zip(t, g)): + e = min(end_of[ti], ti + horizon) + seg = bits[ti:e] # [L, d] + d2 = ((seg - gi[None]) ** 2).sum(-1) + w = (1 - gamma) * gamma ** np.arange(len(seg)) + r = np.exp(-d2 / (2 * sigma * sigma)) + out[n] = (w * r).sum() / max(w.sum(), 1e-9) # renormalize truncation + return out + + +def run_env(env_id, ckpt, n_dataset=None): + import ogbench + print(f"\n{'='*80}\n{env_id} ckpt={os.path.basename(ckpt)}\n{'='*80}", flush=True) + _, ds, _ = ogbench.make_env_and_datasets(env_id, compact_dataset=False) + obs = np.asarray(ds["observations"], dtype=np.float32) + act = np.clip(np.asarray(ds["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(ds["terminals"]) + tgt = target_extractors.extract_target(env_id, obs).astype(np.float32) + N = len(obs) + print(f"N={N} obs_dim={obs.shape[1]} tgt_dim={tgt.shape[1]}", flush=True) + + P, meta = load_genq_params(ckpt) + is_maze = "maze" in env_id and not env_id.startswith(("antmaze", "humanoidmaze", "antsoccer")) + s_of = (lambda o: o[:, :2]) if is_maze else (lambda o: o) + + rng = np.random.default_rng(0) + t = rng.integers(0, N - 1, B) + # hindsight goals: from a Geom future within the trajectory (the training distribution) + j = future_idx(t, end_of, GAMMA, rng) + gi = sample_goal_after(j, end_of, rng) + g = tgt[gi] + + s = s_of(obs)[t] + a = act[t] + + key = jax.random.PRNGKey(0) + cond = jnp.concatenate([jnp.asarray(s), jnp.asarray(a), jnp.asarray(g)], axis=-1) + + def draw(key): + return np.asarray(genq_sample(P, meta, cond, N_OCC, key)) # [B, N_OCC, d] + + key, k1, k2 = jax.random.split(key, 3) + x1, x2 = draw(k1), draw(k2) + + res = {"env": env_id, "ckpt": os.path.basename(ckpt)} + + # ---- 1. sample geometry ---- + xr = np.round(np.clip(x1, 0, 1)) + bitness = np.abs(x1 - np.round(x1)).mean() + # how far do samples wander from the current target vs how far REAL futures wander + d_model = np.linalg.norm(x1 - tgt[t][:, None, :], axis=-1).mean() + y_true = tgt[j] # one real Geom-future draw per query + d_true = np.linalg.norm(y_true - tgt[t], axis=-1).mean() + res["sample/mean_dist_to_binary"] = float(bitness) + res["sample/mean_dist_model_future_from_s"] = float(d_model) + res["sample/mean_dist_true_future_from_s"] = float(d_true) + print(f"[geometry] dist-to-binary={bitness:.3f} model-future wander={d_model:.3f} " + f"true-future wander={d_true:.3f}", flush=True) + if "puzzle" in env_id: + # per-bit marginal calibration: P(bit flips) model vs truth + flip_model = (np.abs(xr - tgt[t][:, None, :]) > 0.5).mean() + flip_true = (np.abs(y_true - tgt[t]) > 0.5).mean() + res["sample/flip_rate_model"] = float(flip_model) + res["sample/flip_rate_true"] = float(flip_true) + print(f"[geometry] bit-flip rate: model={flip_model:.3f} true={flip_true:.3f}", flush=True) + + # ---- 2+4. occupancy fit + sigma sweep ---- + d2_1 = ((x1 - g[:, None, :]) ** 2).sum(-1) # [B, N_OCC] + d2_2 = ((x2 - g[:, None, :]) ** 2).sum(-1) + res["sweep"] = {} + for sig in SIGMAS: + q1 = np.exp(-d2_1 / (2 * sig * sig)).mean(1) + q2 = np.exp(-d2_2 / (2 * sig * sig)).mean(1) + q_mc = mc_return(tgt, t, g, end_of, GAMMA, sig) + rho = stats.spearmanr(q1, q_mc).statistic + noise = np.abs(q1 - q2).mean() + spread = q1.std() + res["sweep"][sig] = dict(q_mean=float(q1.mean()), q_std=float(spread), + corr_mc=float(rho), draw_noise=float(noise), + mc_mean=float(q_mc.mean()), mc_std=float(q_mc.std())) + print(f"[sigma={sig:4}] Q mean={q1.mean():.4f} std={spread:.4f} " + f"corr(Q, MC-return)={rho:+.3f} draw-noise={noise:.4f} " + f"MC mean={q_mc.mean():.4f} std={q_mc.std():.4f}", flush=True) + + # ---- 3. action SNR at the failing run's sigma ---- + sig = 0.5 + a_rand = np.clip(rng.standard_normal(a.shape).astype(np.float32), -1, 1) + a_perm = a[rng.permutation(B)] + key, k3, k4 = jax.random.split(key, 3) + for name, aa, kk in [("rand", a_rand, k3), ("perm", a_perm, k4)]: + cond_a = jnp.concatenate([jnp.asarray(s), jnp.asarray(aa), jnp.asarray(g)], axis=-1) + xa = np.asarray(genq_sample(P, meta, cond_a, N_OCC, kk)) + qa = np.exp(-((xa - g[:, None, :]) ** 2).sum(-1) / (2 * sig * sig)).mean(1) + q1s = np.exp(-d2_1 / (2 * sig * sig)).mean(1) + q2s = np.exp(-d2_2 / (2 * sig * sig)).mean(1) + signal = np.abs(q1s - qa).mean() + noise = np.abs(q1s - q2s).mean() + res[f"action_snr/{name}"] = dict(signal=float(signal), noise=float(noise), + snr=float(signal / max(noise, 1e-12))) + print(f"[action ] |Q(a_data)-Q(a_{name})|={signal:.5f} draw-noise={noise:.5f} " + f"SNR={signal/max(noise,1e-12):.2f}", flush=True) + return res + + +def main(): + ck = os.path.join(PKG, "checkpoints") + out = [] + out.append(run_env("puzzle-3x3-play-v0", + os.path.join(ck, "m9_genq_puzzle_3x3_play_v0.genqjax.npz"))) + out.append(run_env("cube-single-play-v0", + os.path.join(ck, "m9_genq_cube_single_play_v0.genqjax.npz"))) + dst = os.path.join(HERE, "diag_results.json") + json.dump(out, open(dst, "w"), indent=2, default=float) + print(f"\nwrote {dst}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_q_compare.py b/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_q_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9a7d215ea9ec56c98f053ab9d8c643dcafe43b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_q_compare.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python +"""Compare the Gen-Q occupancy Q against a trained reference GCIQL TD critic head-to-head +(issue #57, owner directive: 'Compare with GCIQL's implementation and the learned +Q-function outputs'). + +For probe states drawn from the dataset, and goals drawn separately by TYPE (current / +within-trajectory geometric / random cross-trajectory — the GCDataset value-goal mix the +PI critic is trained and queried on), computes: + + * Spearman rank correlation between TD-Q (min ensemble) and Gen-Q Q, per goal type. + (The two are monotone transforms of steps-to-goal if both are right; rank corr is + the scale-free comparison.) + * ACTION-RANKING agreement: for each (s, g), rank K candidate actions (the dataset + action + Gaussian perturbations + random actions) under both critics; report top-1 + agreement and the fraction where the dataset action beats a random action under + each critic (the contrast policy extraction actually consumes). + * Gen-Q Q calibration per type: mean/std (a healthy critic must NOT be flat at the + random goals that carry the stitching signal). + +Usage (GPU or CPU): + python ogbench_genq/diagnostics/diag_q_compare.py \ + --ref_agent ogbench_genq/checkpoints/gciql_ref_puzzle.pkl \ + --genq_npz ogbench_genq/checkpoints/m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz \ + [--genq_npz2 ...gm variant for side-by-side] [--sigma -1] +""" +import argparse +import json +import os +import pickle +import sys + +import numpy as np + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "genq")) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls"))) + + +def spearman(a, b): + ra = np.argsort(np.argsort(a)).astype(np.float64) + rb = np.argsort(np.argsort(b)).astype(np.float64) + ra -= ra.mean(); rb -= rb.mean() + d = np.sqrt((ra * ra).sum() * (rb * rb).sum()) + return float((ra * rb).sum() / (d + 1e-12)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--env", default="puzzle-3x3-play-v0") + ap.add_argument("--ref_agent", required=True, help="pickle from run_gciql --save_agent") + ap.add_argument("--genq_npz", required=True) + ap.add_argument("--genq_npz2", default=None, help="optional second occupancy (e.g. goal-mix)") + ap.add_argument("--sigma", type=float, default=0.5) + ap.add_argument("--n_occ", type=int, default=64) + ap.add_argument("--n_probe", type=int, default=2048) + ap.add_argument("--n_cand", type=int, default=8, help="candidate actions per (s,g)") + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--out", default=None) + args = ap.parse_args() + + import jax + import jax.numpy as jnp + from utils.env_utils import make_env_and_datasets + from utils.networks import GCActor, GCValue + from utils.flax_utils import ModuleDict + import target_extractors + from genq_jax import load_genq_params, genq_q as genq_q_jax + from train_genq_jax import build_ends + + _env, ds, _ = make_env_and_datasets(args.env, frame_stack=None) + obs = np.asarray(ds["observations"], np.float32) + act = np.clip(np.asarray(ds["actions"], np.float32), -1, 1) + end_of = build_ends(ds["terminals"]) + N, a_dim = len(obs), act.shape[1] + rng = np.random.default_rng(args.seed) + + # ---- rebuild the reference GCIQL critic from the saved pickle ---- + with open(args.ref_agent, "rb") as f: + saved = pickle.load(f) + cfg = saved["config"] + value_def = GCValue(hidden_dims=tuple(cfg["value_hidden_dims"]), layer_norm=cfg["layer_norm"], + ensemble=False) + critic_def = GCValue(hidden_dims=tuple(cfg["value_hidden_dims"]), layer_norm=cfg["layer_norm"], + ensemble=True) + actor_def = GCActor(hidden_dims=tuple(cfg["actor_hidden_dims"]), action_dim=a_dim, + state_dependent_std=False, const_std=cfg["const_std"]) + net = ModuleDict(dict(value=value_def, critic=critic_def, + target_critic=critic_def, actor=actor_def)) + params = {"params": saved["params"]} + + def td_q(s, g, a): + q1, q2 = net.apply(params, s, g, a, name="critic") + return np.asarray(jnp.minimum(q1, q2)) + + def td_v(s, g): + return np.asarray(net.apply(params, s, g, name="value")) + + # ---- occupancy models ---- + models = {os.path.basename(args.genq_npz): load_genq_params(args.genq_npz)} + if args.genq_npz2: + models[os.path.basename(args.genq_npz2)] = load_genq_params(args.genq_npz2) + + def gq(Pm, meta, s, g_t, a, key): + return np.asarray(genq_q_jax(Pm, meta, jnp.asarray(s), jnp.asarray(a), + jnp.asarray(g_t), key, n_occ=args.n_occ, + sigma=args.sigma)) + + tgt = lambda o: target_extractors.extract_target(args.env, o).astype(np.float32) + + # ---- probe sets by goal type (mirrors GCDataset.sample_goals components) ---- + idx = rng.integers(0, N, args.n_probe) + goal_types = {} + goal_types["cur"] = idx.copy() + off = rng.geometric(0.01, size=args.n_probe) + goal_types["traj_geom"] = np.minimum(idx + off, end_of[idx] - 1) + goal_types["random"] = rng.integers(0, N, args.n_probe) + + report = {"env": args.env, "sigma": args.sigma, "n_occ": args.n_occ, + "ref_agent": os.path.basename(args.ref_agent), "types": {}} + key = jax.random.PRNGKey(args.seed) + for tname, gidx in goal_types.items(): + s, a, gobs = obs[idx], act[idx], obs[gidx] + g_t = tgt(gobs) + qt = td_q(s, gobs, a) + row = {"td_q_mean": float(qt.mean()), "td_q_std": float(qt.std())} + for mname, (Pm, meta) in models.items(): + key, sub = jax.random.split(key) + qg = gq(Pm, meta, s, g_t, a, sub) + row[mname] = {"genq_q_mean": float(qg.mean()), "genq_q_std": float(qg.std()), + "spearman_vs_td": spearman(qt, qg)} + report["types"][tname] = row + print(f"[{tname}] td_q {qt.mean():.3f}+-{qt.std():.3f} | " + + " | ".join(f"{m}: genq {row[m]['genq_q_mean']:.4f}+-{row[m]['genq_q_std']:.4f} " + f"rho={row[m]['spearman_vs_td']:.3f}" for m in models), flush=True) + + # ---- action-ranking agreement (the contrast extraction consumes) ---- + M = min(512, args.n_probe) + s, a0 = obs[idx[:M]], act[idx[:M]] + for tname, gidx in goal_types.items(): + gobs = obs[gidx[:M]] + g_t = tgt(gobs) + # candidates: dataset action, n_cand-2 perturbations (sigma 0.3), 1 uniform random + cands = [a0] + for _ in range(args.n_cand - 2): + cands.append(np.clip(a0 + 0.3 * rng.standard_normal(a0.shape).astype(np.float32), -1, 1)) + cands.append(rng.uniform(-1, 1, a0.shape).astype(np.float32)) + C = np.stack(cands, 1) # [M, K, a] + K = C.shape[1] + sK = np.repeat(s, K, 0); gK = np.repeat(gobs, K, 0); gtK = np.repeat(g_t, K, 0) + aK = C.reshape(M * K, a_dim) + qt = td_q(sK, gK, aK).reshape(M, K) + row = report["types"][tname] + row["action_rank"] = {} + for mname, (Pm, meta) in models.items(): + key, sub = jax.random.split(key) + qg = gq(Pm, meta, sK, gtK, aK, sub).reshape(M, K) + top1 = float((qt.argmax(1) == qg.argmax(1)).mean()) + # does each critic put the dataset action above the random action? + td_ds_gt_rand = float((qt[:, 0] > qt[:, -1]).mean()) + gq_ds_gt_rand = float((qg[:, 0] > qg[:, -1]).mean()) + row["action_rank"][mname] = {"top1_agree": top1, + "td_data_gt_rand": td_ds_gt_rand, + "genq_data_gt_rand": gq_ds_gt_rand} + print(f"[{tname}/rank] {mname}: top1_agree={top1:.3f} " + f"data>rand: td={td_ds_gt_rand:.3f} genq={gq_ds_gt_rand:.3f}", flush=True) + + out = args.out or os.path.join(os.path.dirname(os.path.abspath(__file__)), + "q_compare_report.json") + json.dump(report, open(out, "w"), indent=2) + print(f"[diag_q_compare] wrote {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_rec_stitch.py b/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_rec_stitch.py new file mode 100644 index 0000000000000000000000000000000000000000..e39072948fb94951a5ebf06366e2d1b11282d106 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_rec_stitch.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python +"""Does RECURSION fix stitching? Rank-correlate recursive-gl against the trained TD critic +at cross-trajectory goals (the stitching regime where frozen gl collapses to rho~0.44). + +Estimator (pure MC + recursion + dataset retrieval, no policy model): + Q1(s,a,g) = gl(s,a,g) [direct first-passage] + Qh+1 = Qh + (1-Qh) * mean_c[ gl(s_c, a_c, g) ] [compose one more window] +where c ~ occupancy endpoint configs from the previous hop, (s_c, a_c) retrieved from +the DATASET by exact config match (full-obs conditioning, behavior action).""" +import argparse, json, os, pickle, sys +from collections import defaultdict + +import numpy as np + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "genq")) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls"))) + + +def spearman(a, b): + ra = np.argsort(np.argsort(a)).astype(np.float64) + rb = np.argsort(np.argsort(b)).astype(np.float64) + ra -= ra.mean(); rb -= rb.mean() + return float((ra * rb).sum() / (np.sqrt((ra * ra).sum() * (rb * rb).sum()) + 1e-12)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--env", default="puzzle-3x3-play-v0") + ap.add_argument("--ref_agent", required=True) + ap.add_argument("--genq_npz", required=True) + ap.add_argument("--n_probe", type=int, default=1024) + ap.add_argument("--m_mid", type=int, default=8, help="retrieved midpoints per hop") + ap.add_argument("--hops", type=int, default=3) + ap.add_argument("--n_orders", type=int, default=16) + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--midpoint_actor", default=None, + help="agent pkl: goal-directed midpoint actions mu(s_c, g_obs) instead of dataset actions") + ap.add_argument("--agg", default="mean", choices=["mean", "max"], + help="midpoint aggregation: mean (expected composition) or max (best-waypoint)") + ap.add_argument("--out", default=None) + args = ap.parse_args() + + import jax + import jax.numpy as jnp + from utils.env_utils import make_env_and_datasets + from utils.networks import GCActor, GCValue + from utils.flax_utils import ModuleDict + import target_extractors + from genq_jax import load_genq_params, genq_q_goal_likelihood, sample as occ_sample + from train_genq_jax import build_ends + + _env, ds, _ = make_env_and_datasets(args.env, frame_stack=None) + obs = np.asarray(ds["observations"], np.float32) + act = np.clip(np.asarray(ds["actions"], np.float32), -1, 1) + end_of = build_ends(ds["terminals"]) + N, a_dim = len(obs), act.shape[1] + rng = np.random.default_rng(args.seed) + tgt = lambda o: target_extractors.extract_target(args.env, o).astype(np.float32) + + P, meta = load_genq_params(args.genq_npz) + n_bits = meta["n_bits"] + pow2 = (1 << np.arange(n_bits)).astype(np.int64) + cfg_all = np.round(np.clip(tgt(obs), 0, 1)).astype(np.int64) @ pow2 + buckets = defaultdict(list) + for i in range(N): + buckets[int(cfg_all[i])].append(i) + + with open(args.ref_agent, "rb") as f: + saved = pickle.load(f) + cfg = saved["config"] + critic_def = GCValue(hidden_dims=tuple(cfg["value_hidden_dims"]), + layer_norm=cfg["layer_norm"], ensemble=True) + value_def = GCValue(hidden_dims=tuple(cfg["value_hidden_dims"]), + layer_norm=cfg["layer_norm"], ensemble=False) + actor_def = GCActor(hidden_dims=tuple(cfg["actor_hidden_dims"]), action_dim=a_dim, + state_dependent_std=False, const_std=cfg["const_std"]) + net = ModuleDict(dict(value=value_def, critic=critic_def, target_critic=critic_def, + actor=actor_def)) + params = {"params": saved["params"]} + td_q = lambda s, g, a: np.asarray(jnp.minimum(*net.apply(params, s, g, a, name="critic"))) + + gl_fn = jax.jit(lambda s, a, g, k: genq_q_goal_likelihood(P, meta, s, a, g, k, + n_orders=args.n_orders)) + key = [jax.random.PRNGKey(args.seed + 7)] + + def gl_np(s, a, g, _chunk=512): + outs = [] + for i in range(0, len(s), _chunk): + key[0], sub = jax.random.split(key[0]) + outs.append(np.asarray(gl_fn(jnp.asarray(s[i:i + _chunk]), + jnp.asarray(a[i:i + _chunk]), + jnp.asarray(g[i:i + _chunk]), sub))) + return np.concatenate(outs) + + mid_mu = None + if args.midpoint_actor: + with open(args.midpoint_actor, "rb") as f: + asaved = pickle.load(f) + acfg = asaved["config"] + mact_def = GCActor(hidden_dims=tuple(acfg["actor_hidden_dims"]), action_dim=a_dim, + state_dependent_std=False, const_std=acfg["const_std"]) + mparams = {"params": asaved["params"]["modules_actor"]} + mid_mu = jax.jit(lambda o, gobs: jnp.clip( + mact_def.apply(mparams, o, gobs).mode(), -1, 1)) + + samp_fn = jax.jit(lambda c, k: occ_sample(P, meta, c, args.m_mid, k)) + + def endpoints(s, a, g): + c = jnp.asarray(np.concatenate([s, a, g], axis=1)) + key[0], sub = jax.random.split(key[0]) + x = np.asarray(samp_fn(c, sub)) # [B, M, 9] exact bits + return (np.round(np.clip(x, 0, 1)).astype(np.int64) @ pow2) # [B, M] + + B = args.n_probe + idx = rng.integers(0, N, B) + report = {} + for tname, gidx in [("traj_geom", np.minimum(idx + rng.geometric(0.01, B), end_of[idx] - 1)), + ("random", rng.integers(0, N, B))]: + s, a, g = obs[idx], act[idx], tgt(obs[gidx]) + qt = td_q(s, obs[gidx], a) + Q = gl_np(s, a, g) + rhos = {"hop1": spearman(qt, Q)} + cur_s, cur_a = s, a + for h in range(2, args.hops + 1): + cfgs = endpoints(cur_s, cur_a, g) # [B, M] midpoint configs + hopq = np.zeros(B) + Sm, Am, Gm, back = [], [], [], [] + for b in range(B): + for m in range(args.m_mid): + j = int(rng.choice(buckets[int(cfgs[b, m])])) + Sm.append(obs[j]); Am.append(act[j]); Gm.append(g[b]); back.append(b) + Sm = np.asarray(Sm, np.float32) + Am = np.asarray(Am, np.float32) + Gm = np.asarray(Gm, np.float32) + if mid_mu is not None: + gobs_m = obs[np.repeat(gidx, args.m_mid)] # goal OBS for the actor + Am = np.concatenate([np.asarray(mid_mu(jnp.asarray(Sm[i:i + 512]), + jnp.asarray(gobs_m[i:i + 512]))) + for i in range(0, len(Sm), 512)]) + pr = gl_np(Sm, Am, Gm) + if args.agg == "max": + for k2, b in enumerate(back): + hopq[b] = max(hopq[b], pr[k2]) + else: + for k2, b in enumerate(back): + hopq[b] += pr[k2] / args.m_mid + Q = Q + (1 - Q) * hopq + rhos[f"hop{h}"] = spearman(qt, Q) + # next hop chains from a random retrieved midpoint per row + pick = rng.integers(0, args.m_mid, B) + nidx = np.array([int(rng.choice(buckets[int(cfgs[b, pick[b]])])) for b in range(B)]) + cur_s, cur_a = obs[nidx], act[nidx] + report[tname] = rhos + print(f"[{tname}] " + " ".join(f"{k}={v:.3f}" for k, v in rhos.items()), flush=True) + + out = args.out or os.path.join(os.path.dirname(os.path.abspath(__file__)), + "rec_stitch_report.json") + json.dump(report, open(out, "w"), indent=2) + print(f"[diag_rec_stitch] wrote {out}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_results.json b/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_results.json new file mode 100644 index 0000000000000000000000000000000000000000..4696afe56e95d83f35a3e971aabf79827469808c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/diag_results.json @@ -0,0 +1,138 @@ +[ + { + "env": "puzzle-3x3-play-v0", + "ckpt": "m9_genq_puzzle_3x3_play_v0.genqjax.npz", + "sample/mean_dist_to_binary": 0.0048172008246183395, + "sample/mean_dist_model_future_from_s": 1.6170740127563477, + "sample/mean_dist_true_future_from_s": 1.605639934539795, + "sample/flip_rate_model": 0.3694220648871528, + "sample/flip_rate_true": 0.3753255208333333, + "sweep": { + "0.25": { + "q_mean": 0.04997465759515762, + "q_std": 0.1423320174217224, + "corr_mc": 0.3854969359593083, + "draw_noise": 0.014405339024960995, + "mc_mean": 0.11927786496091643, + "mc_std": 0.18199671877866735 + }, + "0.5": { + "q_mean": 0.05897827446460724, + "q_std": 0.14352001249790192, + "corr_mc": 0.3798358215183887, + "draw_noise": 0.015937237069010735, + "mc_mean": 0.12161131656962973, + "mc_std": 0.1811058182014838 + }, + "1.0": { + "q_mean": 0.22170759737491608, + "q_std": 0.13291603326797485, + "corr_mc": 0.5153714931563044, + "draw_noise": 0.02331133373081684, + "mc_mean": 0.2405053474884869, + "mc_std": 0.1645088666553131 + }, + "1.5": { + "q_mean": 0.46669745445251465, + "q_std": 0.1008758544921875, + "corr_mc": 0.5829374809950324, + "draw_noise": 0.021935585886240005, + "mc_mean": 0.4657605069192291, + "mc_std": 0.1271890700762525 + }, + "2.0": { + "q_mean": 0.6397253274917603, + "q_std": 0.071995310485363, + "corr_mc": 0.602684764775715, + "draw_noise": 0.01694326475262642, + "mc_mean": 0.6347352954422463, + "mc_std": 0.09214108728585331 + }, + "3.0": { + "q_mean": 0.815272331237793, + "q_std": 0.038696035742759705, + "corr_mc": 0.6127386795659565, + "draw_noise": 0.009625921957194805, + "mc_mean": 0.8109230143166604, + "mc_std": 0.050218905638162455 + } + }, + "action_snr/rand": { + "signal": 0.03189718723297119, + "noise": 0.015937237069010735, + "snr": 2.001425266265869 + }, + "action_snr/perm": { + "signal": 0.023365074768662453, + "noise": 0.015937237069010735, + "snr": 1.466068148612976 + } + }, + { + "env": "cube-single-play-v0", + "ckpt": "m9_genq_cube_single_play_v0.genqjax.npz", + "sample/mean_dist_to_binary": 0.23680679500102997, + "sample/mean_dist_model_future_from_s": 1.8569566011428833, + "sample/mean_dist_true_future_from_s": 1.7629954814910889, + "sweep": { + "0.25": { + "q_mean": 0.15182124078273773, + "q_std": 0.2405737340450287, + "corr_mc": 0.6327955893113082, + "draw_noise": 0.029153238981962204, + "mc_mean": 0.1503251978396522, + "mc_std": 0.24719418858110326 + }, + "0.5": { + "q_mean": 0.20219552516937256, + "q_std": 0.24770735204219818, + "corr_mc": 0.6499293987219823, + "draw_noise": 0.03321189805865288, + "mc_mean": 0.19105967081553388, + "mc_std": 0.25154015494612114 + }, + "1.0": { + "q_mean": 0.3342295289039612, + "q_std": 0.23730607330799103, + "corr_mc": 0.7259574201914409, + "draw_noise": 0.03863431513309479, + "mc_mean": 0.31573214088587886, + "mc_std": 0.2481244436680137 + }, + "1.5": { + "q_mean": 0.47764575481414795, + "q_std": 0.21055923402309418, + "corr_mc": 0.7589795907690227, + "draw_noise": 0.03881801664829254, + "mc_mean": 0.4593206208736197, + "mc_std": 0.2317093759263906 + }, + "2.0": { + "q_mean": 0.5990447998046875, + "q_std": 0.17907391488552094, + "corr_mc": 0.7581588119894591, + "draw_noise": 0.03486104682087898, + "mc_mean": 0.5834819258059407, + "mc_std": 0.20578718899703705 + }, + "3.0": { + "q_mean": 0.7594205141067505, + "q_std": 0.12274908274412155, + "corr_mc": 0.7442061147706143, + "draw_noise": 0.024486085399985313, + "mc_mean": 0.7493196716424362, + "mc_std": 0.147871457148268 + } + }, + "action_snr/rand": { + "signal": 0.07847072184085846, + "noise": 0.03321189805865288, + "snr": 2.36272931098938 + }, + "action_snr/perm": { + "signal": 0.06145443767309189, + "noise": 0.03321189805865288, + "snr": 1.8503741025924683 + } + } +] \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/puzzle_sweep_table.md b/gen_q_rsm/ogbench_genq/unused/diagnostics/puzzle_sweep_table.md new file mode 100644 index 0000000000000000000000000000000000000000..07d2ce5eeda50063f6882bf3905ad0034c214973 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/puzzle_sweep_table.md @@ -0,0 +1,71 @@ +| variant (results/0/*.json) | config | best sr | final sr | steps | +|---|---|---|---|---| +| `gciql_ref_a1` | GCIQL TD (ddpgbc α=1.0) | **0.960** | 0.948 | 500k | +| `gciql_ref_a1_saved` | GCIQL TD (ddpgbc α=1.0) | **0.947** | 0.928 | 500k | +| `gciql` | GCIQL TD (ddpgbc α=0.3) | **0.880** | 0.756 | 500k | +| `gciql_genq_s20_a300` | Gen-Q (awr, α=300.0, σ=2.0) | **0.187** | 0.132 | 300k | +| `gciql_genq_mixb_sp_a3` | Gen-Q (awr, α=3.0, σ=-1.0, advnorm) | **0.187** | 0.076 | 300k | +| `gciql_genq_mixb_sp_a2` | Gen-Q (awr, α=2.0, σ=-1.0, advnorm) | **0.173** | 0.104 | 300k | +| `gciql_genq_s15_a300` | Gen-Q (awr, α=300.0, σ=1.5) | **0.173** | 0.120 | 300k | +| `gciql_genq_flow_abs_s05_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.173** | 0.116 | 300k | +| `gciql_genq_s15_a100_n64` | Gen-Q (awr, α=100.0, σ=1.5) | **0.160** | 0.100 | 300k | +| `gciql_genq_tau095_a300` | Gen-Q (awr, α=300.0) | **0.160** | 0.120 | 300k | +| `gciql_genq_mixbe_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.160** | 0.084 | 300k | +| `gciql_genq_abs_s05_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.147** | 0.056 | 300k | +| `gciql_genq_bits_eff_tau09_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.147** | 0.096 | 300k | +| `gciql_genq_mixbeFL_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.147** | 0.088 | 300k | +| `gciql_genq_mixbeL_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.147** | 0.088 | 300k | +| `gciql_genq_rec_b095_rxb095_gk6_t09_a3` | Gen-Q (awr, α=3.0, advnorm, rec β=0.95, midAWR2.0, greedy6) | **0.147** | 0.108 | 150k | +| `gciql_genq_rec_b09_rxb09_gk6_t08_a3` | Gen-Q (awr, α=3.0, advnorm, rec β=0.9, midAWR2.0, greedy6) | **0.147** | 0.140 | 150k | +| `gciql_genq_a300_n256` | Gen-Q (awr, α=300.0, n=256) | **0.133** | 0.096 | 150k | +| `gciql_genq_a300_qf32` | Gen-Q (awr, α=300.0, Qfilter32) | **0.133** | 0.048 | 300k | +| `gciql_genq_big_abs_hifi` | Gen-Q (awr, α=2.0, n=128, advnorm) | **0.133** | 0.133 | 50k | +| `gciql_genq_bits_eff_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.133** | 0.068 | 300k | +| `gciql_genq_disc_mean_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.133** | 0.044 | 300k | +| `gciql_genq_full_tau09_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.133** | 0.040 | 300k | +| `gciql_genq_latfull_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.133** | 0.068 | 300k | +| `gciql_genq_mixfull_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.133** | 0.084 | 300k | +| `gciql_genq_tau095_a100` | Gen-Q (awr, α=100.0) | **0.128** | 0.128 | 300k | +| `gciql_genq_bits_eff_advn_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.124** | 0.124 | 300k | +| `gciql_genq_a1000_n64` | Gen-Q (awr, α=1000.0) | **0.120** | 0.096 | 300k | +| `gciql_genq_a300_ageom` | Gen-Q (awr, α=300.0) | **0.120** | 0.100 | 300k | +| `gciql_genq_a300_n64` | Gen-Q (awr, α=300.0) | **0.120** | 0.056 | 300k | +| `gciql_genq_advn_a10` | Gen-Q (awr, α=10.0, advnorm) | **0.120** | 0.088 | 300k | +| `gciql_genq_big_abs_s05_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.120** | 0.088 | 300k | +| `gciql_genq_mixb_s05_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.120** | 0.088 | 300k | +| `gciql_genq_mixfullF_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.120** | 0.088 | 300k | +| `gciql_genq_rec_b09_rxb09_gk6_a3` | Gen-Q (awr, α=3.0, advnorm, rec β=0.9, midAWR2.0, greedy6) | **0.120** | 0.028 | 150k | +| `gciql_genq_a100_n64` | Gen-Q (awr, α=100.0) | **0.107** | 0.084 | 300k | +| `gciql_genq_abs_sparse_advn_a2` | Gen-Q (awr, α=2.0, σ=0.0, advnorm) | **0.107** | 0.036 | 300k | +| `gciql_genq_disc_abs_s05_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.107** | 0.040 | 300k | +| `gciql_genq_full_advn_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.107** | 0.064 | 300k | +| `gciql_genq_mixbeF_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.107** | 0.096 | 300k | +| `gciql_genq_mixfullFL_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.107** | 0.052 | 300k | +| `gciql_genq_rec_b095_rxb095_gk6_a3` | Gen-Q (awr, α=3.0, advnorm, rec β=0.95, midAWR2.0, greedy6) | **0.107** | 0.080 | 150k | +| `gciql_genq_rec_b09_mawr3_a300` | Gen-Q (awr, α=300.0, rec β=0.9, midAWR3.0) | **0.107** | 0.104 | 300k | +| `gciql_genq_rec_b09_rxb09_gk6_a2` | Gen-Q (awr, α=2.0, advnorm, rec β=0.9, midAWR2.0, greedy6) | **0.107** | 0.068 | 150k | +| `gciql_genq_rec_b09_rxb09_gk6_t09_a3` | Gen-Q (awr, α=3.0, advnorm, rec β=0.9, midAWR2.0, greedy6) | **0.107** | 0.060 | 150k | +| `gciql_genq_disc_abs_sparse_a100` | Gen-Q (awr, α=100.0, σ=0.0) | **0.093** | 0.068 | 300k | +| `gciql_genq_disc_mean_a100` | Gen-Q (awr, α=100.0) | **0.093** | 0.036 | 300k | +| `gciql_genq_latfull_tau09_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.093** | 0.076 | 300k | +| `gciql_genq_rec_b085_rxb085_gk6_a3` | Gen-Q (awr, α=3.0, advnorm, rec β=0.85, midAWR2.0, greedy6) | **0.093** | 0.056 | 150k | +| `gciql_genq_rec_b095_a300` | Gen-Q (awr, α=300.0, rec β=0.95) | **0.093** | 0.036 | 300k | +| `gciql_genq_rec_b09_a300` | Gen-Q (awr, α=300.0, rec β=0.9) | **0.093** | 0.084 | 300k | +| `gciql_genq_rec_b09_rxb09_gk6_a10` | Gen-Q (awr, α=10.0, advnorm, rec β=0.9, midAWR2.0, greedy6) | **0.093** | 0.056 | 150k | +| `gciql_genq_rec_b09_rxb09_nog_a3` | Gen-Q (awr, α=3.0, advnorm, rec β=0.9, midAWR2.0) | **0.093** | 0.076 | 150k | +| `gciql_genq_full_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.093** | 0.032 | 300k | +| `gciql_genq_disc_tau09_advn_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.092** | 0.092 | 300k | +| `gciql_genq_a100_n256` | Gen-Q (awr, α=100.0, n=256) | **0.080** | 0.068 | 150k | +| `gciql_genq_advn_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.080** | 0.072 | 300k | +| `gciql_genq_ddpgbc_a1` | Gen-Q (ddpgbc, α=1.0) | **0.067** | 0.032 | 300k | +| `gciql_genq_disc_abs_sparse_advn_a2` | Gen-Q (awr, α=2.0, σ=0.0, advnorm) | **0.067** | 0.032 | 300k | +| `gciql_genq_disc_tau09_a100` | Gen-Q (awr, α=100.0) | **0.067** | 0.064 | 300k | +| `gciql_genq_disc_tau09_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.067** | 0.032 | 300k | +| `gciql_genq_mixfullL_a3` | Gen-Q (awr, α=3.0, advnorm) | **0.067** | 0.032 | 300k | +| `gciql_genq` | Gen-Q (awr, α=30.0) | **0.053** | 0.032 | 300k | +| `gciql_genq_rec_b09_mawr3_gk4_a300` | Gen-Q (awr, α=300.0, rec β=0.9, midAWR3.0, greedy4) | **0.052** | 0.052 | 150k | +| `gciql_genq_a30_n256` | Gen-Q (awr, α=30.0, n=256) | **0.048** | 0.048 | 150k | +| `gciql_genq_ddpgbc_a03` | Gen-Q (ddpgbc, α=0.3) | **0.040** | 0.020 | 300k | +| `gciql_genq_ddpgbc_a01` | Gen-Q (ddpgbc, α=0.1) | **0.027** | 0.024 | 300k | +| `gciql_genq_disc_tau099_a100` | Gen-Q (awr, α=100.0) | **0.027** | 0.008 | 300k | +| `gciql_genq_disc_tau099_advn_a2` | Gen-Q (awr, α=2.0, advnorm) | **0.020** | 0.020 | 300k | diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_gmst.json b/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_gmst.json new file mode 100644 index 0000000000000000000000000000000000000000..c7dfce7ae344ebb78dceaf0857db353d537b1a87 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_gmst.json @@ -0,0 +1,86 @@ +{ + "env": "puzzle-3x3-play-v0", + "sigma": 0.5, + "n_occ": 64, + "ref_agent": "gciql_ref_puzzle_3x3_agent.pkl", + "types": { + "cur": { + "td_q_mean": 0.09765346348285675, + "td_q_std": 0.10217799246311188, + "m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.984878659248352, + "genq_q_std": 0.01704266481101513, + "spearman_vs_td": -0.04937616050271046 + }, + "m9_genq_mixb_gmst_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.9754948616027832, + "genq_q_std": 0.020431391894817352, + "spearman_vs_td": -0.01044019793410848 + }, + "action_rank": { + "m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.126953125, + "td_data_gt_rand": 0.806640625, + "genq_data_gt_rand": 0.43359375 + }, + "m9_genq_mixb_gmst_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.1328125, + "td_data_gt_rand": 0.806640625, + "genq_data_gt_rand": 0.478515625 + } + } + }, + "traj_geom": { + "td_q_mean": -30.120248794555664, + "td_q_std": 17.16423225402832, + "m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.5011446475982666, + "genq_q_std": 0.3521053194999695, + "spearman_vs_td": 0.9243472149901902 + }, + "m9_genq_mixb_gmst_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.4984756410121918, + "genq_q_std": 0.33196118474006653, + "spearman_vs_td": 0.9158870060621515 + }, + "action_rank": { + "m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.169921875, + "td_data_gt_rand": 0.728515625, + "genq_data_gt_rand": 0.568359375 + }, + "m9_genq_mixb_gmst_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.166015625, + "td_data_gt_rand": 0.728515625, + "genq_data_gt_rand": 0.61328125 + } + } + }, + "random": { + "td_q_mean": -56.67393493652344, + "td_q_std": 8.565766334533691, + "m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.08963783085346222, + "genq_q_std": 0.10821247845888138, + "spearman_vs_td": 0.46598894595463775 + }, + "m9_genq_mixb_gmst_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.11398522555828094, + "genq_q_std": 0.10718546062707901, + "spearman_vs_td": 0.5099329809125914 + }, + "action_rank": { + "m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.1171875, + "td_data_gt_rand": 0.458984375, + "genq_data_gt_rand": 0.505859375 + }, + "m9_genq_mixb_gmst_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.146484375, + "td_data_gt_rand": 0.458984375, + "genq_data_gt_rand": 0.505859375 + } + } + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_s05.json b/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_s05.json new file mode 100644 index 0000000000000000000000000000000000000000..a482301014fa755f7d2413fc705ccb795f415819 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_s05.json @@ -0,0 +1,86 @@ +{ + "env": "puzzle-3x3-play-v0", + "sigma": 0.5, + "n_occ": 64, + "ref_agent": "gciql_ref_puzzle_3x3_agent.pkl", + "types": { + "cur": { + "td_q_mean": 0.09765346348285675, + "td_q_std": 0.10217799246311188, + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.895279049873352, + "genq_q_std": 0.08746425807476044, + "spearman_vs_td": -0.07314605054016127 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.9829213619232178, + "genq_q_std": 0.01838907040655613, + "spearman_vs_td": -0.016842541575143713 + }, + "action_rank": { + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.103515625, + "td_data_gt_rand": 0.806640625, + "genq_data_gt_rand": 0.49609375 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.16796875, + "td_data_gt_rand": 0.806640625, + "genq_data_gt_rand": 0.427734375 + } + } + }, + "traj_geom": { + "td_q_mean": -30.120248794555664, + "td_q_std": 17.16423225402832, + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.46420374512672424, + "genq_q_std": 0.32361388206481934, + "spearman_vs_td": 0.9128387781667776 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.49474653601646423, + "genq_q_std": 0.3442823886871338, + "spearman_vs_td": 0.9225395286177465 + }, + "action_rank": { + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.166015625, + "td_data_gt_rand": 0.728515625, + "genq_data_gt_rand": 0.609375 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.189453125, + "td_data_gt_rand": 0.728515625, + "genq_data_gt_rand": 0.56640625 + } + } + }, + "random": { + "td_q_mean": -56.67393493652344, + "td_q_std": 8.565766334533691, + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.10860735177993774, + "genq_q_std": 0.09397382289171219, + "spearman_vs_td": 0.43633191026837476 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.09072688221931458, + "genq_q_std": 0.10719823092222214, + "spearman_vs_td": 0.5033743776044256 + }, + "action_rank": { + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.12109375, + "td_data_gt_rand": 0.458984375, + "genq_data_gt_rand": 0.548828125 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.166015625, + "td_data_gt_rand": 0.458984375, + "genq_data_gt_rand": 0.48828125 + } + } + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_sparse.json b/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_sparse.json new file mode 100644 index 0000000000000000000000000000000000000000..1fdfdfb0c7f0f9f51b1f8b598a5a58baec0a21bd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/q_compare_sparse.json @@ -0,0 +1,86 @@ +{ + "env": "puzzle-3x3-play-v0", + "sigma": -1.0, + "n_occ": 64, + "ref_agent": "gciql_ref_puzzle_3x3_agent.pkl", + "types": { + "cur": { + "td_q_mean": 0.09765428304672241, + "td_q_std": 0.10217828303575516, + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.8949813842773438, + "genq_q_std": 0.08771127462387085, + "spearman_vs_td": -0.07710161268526022 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.9828567504882812, + "genq_q_std": 0.018463434651494026, + "spearman_vs_td": -0.025494504744739473 + }, + "action_rank": { + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.11328125, + "td_data_gt_rand": 0.806640625, + "genq_data_gt_rand": 0.447265625 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.171875, + "td_data_gt_rand": 0.806640625, + "genq_data_gt_rand": 0.375 + } + } + }, + "traj_geom": { + "td_q_mean": -30.120250701904297, + "td_q_std": 17.164230346679688, + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.4624481201171875, + "genq_q_std": 0.32477691769599915, + "spearman_vs_td": 0.9132264147381878 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.4929351806640625, + "genq_q_std": 0.3455716073513031, + "spearman_vs_td": 0.9231120797960949 + }, + "action_rank": { + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.16796875, + "td_data_gt_rand": 0.728515625, + "genq_data_gt_rand": 0.580078125 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.17578125, + "td_data_gt_rand": 0.728515625, + "genq_data_gt_rand": 0.529296875 + } + } + }, + "random": { + "td_q_mean": -56.67393493652344, + "td_q_std": 8.565766334533691, + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.10445404052734375, + "genq_q_std": 0.09446687251329422, + "spearman_vs_td": 0.43553548538785825 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "genq_q_mean": 0.08640289306640625, + "genq_q_std": 0.10779641568660736, + "spearman_vs_td": 0.5051274810104027 + }, + "action_rank": { + "m9_genq_mixb_abs_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.1171875, + "td_data_gt_rand": 0.458984375, + "genq_data_gt_rand": 0.4765625 + }, + "m9_genq_mixb_gm_puzzle_3x3_play_v0.genqjax.npz": { + "top1_agree": 0.162109375, + "td_data_gt_rand": 0.458984375, + "genq_data_gt_rand": 0.40625 + } + } + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report.json b/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report.json new file mode 100644 index 0000000000000000000000000000000000000000..3240274d0562d3aa48f420ae8811d2ceb94cde9b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report.json @@ -0,0 +1,12 @@ +{ + "traj_geom": { + "hop1": 0.9338752816322151, + "hop2": 0.921215131249553, + "hop3": 0.8734991908661756 + }, + "random": { + "hop1": 0.5304954380051499, + "hop2": 0.5229584905407338, + "hop3": 0.4734613381553537 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report_gmst.json b/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report_gmst.json new file mode 100644 index 0000000000000000000000000000000000000000..7e76b0ca389652e89bf7d414df87fb47450b083e --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report_gmst.json @@ -0,0 +1,12 @@ +{ + "traj_geom": { + "hop1": 0.933481555325084, + "hop2": 0.9168681938881339, + "hop3": 0.844877165885845 + }, + "random": { + "hop1": 0.603256517774122, + "hop2": 0.5504979861061441, + "hop3": 0.4512921218975753 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report_v2.json b/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report_v2.json new file mode 100644 index 0000000000000000000000000000000000000000..249de337e48d287547a9ab40598b96ffb134de31 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics/rec_stitch_report_v2.json @@ -0,0 +1,12 @@ +{ + "traj_geom": { + "hop1": 0.9338816742364637, + "hop2": 0.899487518775481, + "hop3": 0.8650225864566197 + }, + "random": { + "hop1": 0.5369789356984479, + "hop2": 0.36260858486517417, + "hop3": 0.4094515771404048 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/chain_depth.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/chain_depth.json new file mode 100644 index 0000000000000000000000000000000000000000..db184519001cbbd5fe2c3dc1a23cc892ff81fce2 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/chain_depth.json @@ -0,0 +1,88 @@ +{ + "depths": { + "1": { + "binariness": 0.020147502422332764, + "range_viol": 0.012859552556818182, + "nn_dist": 4.463259696960449, + "fliprate": 0.3183864951133728, + "data_fliprate": 0.24124999344348907 + }, + "2": { + "binariness": 0.01954806223511696, + "range_viol": 0.013538707386363636, + "nn_dist": 4.591675281524658, + "fliprate": 0.3960774838924408, + "data_fliprate": 0.41147223114967346 + }, + "4": { + "binariness": 0.019230924546718597, + "range_viol": 0.013862748579545454, + "nn_dist": 4.583155632019043, + "fliprate": 0.4526638388633728, + "data_fliprate": 0.4735833406448364 + }, + "8": { + "binariness": 0.01899934560060501, + "range_viol": 0.014093572443181818, + "nn_dist": 4.516853332519531, + "fliprate": 0.48779296875, + "data_fliprate": 0.4850277900695801 + }, + "16": { + "binariness": 0.01894175447523594, + "range_viol": 0.014723899147727273, + "nn_dist": 4.554107666015625, + "fliprate": 0.4981825053691864, + "data_fliprate": 0.48597222566604614 + }, + "26": { + "binariness": 0.019271396100521088, + "range_viol": 0.01473721590909091, + "nn_dist": 4.525835037231445, + "fliprate": 0.4989420473575592, + "data_fliprate": 0.4857499897480011 + } + }, + "nocc_sweep": { + "d1_n16": { + "gap": 0.009219754487276077, + "sem": 0.003978982102125883, + "q_mean": 0.028703248128294945 + }, + "d1_n64": { + "gap": 0.010928343050181866, + "sem": 0.003315940499305725, + "q_mean": 0.03140183538198471 + }, + "d1_n256": { + "gap": 0.010405236855149269, + "sem": 0.003260453464463353, + "q_mean": 0.03118044324219227 + }, + "d1_n1024": { + "gap": 0.010381104424595833, + "sem": 0.003228966146707535, + "q_mean": 0.03126678615808487 + }, + "d26_n16": { + "gap": -0.002188846468925476, + "sem": 0.0012808191822841763, + "q_mean": 0.009789016097784042 + }, + "d26_n64": { + "gap": 0.00041247636545449495, + "sem": 0.0008427983266301453, + "q_mean": 0.011851879768073559 + }, + "d26_n256": { + "gap": 0.00012115346908103675, + "sem": 0.00033528500352986157, + "q_mean": 0.011144501157104969 + }, + "d26_n1024": { + "gap": 0.0002476181834936142, + "sem": 0.00017267503426410258, + "q_mean": 0.011491254903376102 + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_chain_depth.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_chain_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..cf267caed67152060510305eaf08189cc98b26cf --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_chain_depth.py @@ -0,0 +1,168 @@ +"""#57 follow-up: is the recursive chain's failure on puzzle COMPOUNDING ERROR (bias +that grows with depth) or SAMPLING NOISE (variance reducible with n_occ)? + +Uses the full-state puzzle occupancy (state==target==55-d obs). Chains are run at +FORCED depth d (no geometric stop) so depth is isolated. Metrics per depth: + + * off-manifold drift: mean per-dim-normalized NN distance of chain endpoints to + dataset states (baseline: NN distance of real states to the rest of the data); + * bit binariness: mean |bits - round(bits)| (0 = perfectly binary); + * range violations: fraction of endpoint dims outside the dataset min/max; + * bits flip-rate from the chain start vs the DATA flip-rate at the matched + expected horizon d * E[K] = d/(1-beta). + +And the action-signal question, per depth and per n_occ: + * gap = E[Q(s, a_data) - Q(s, a_rand)] with the bits-sharp read-out, and its + SNR = gap / std(Q-difference)/sqrt(n_pairs). If gap -> 0 as n_occ grows, the + failure is BIAS/absence of signal; if SNR grows ~sqrt(n_occ) toward usable, + it is variance and more samples would fix it. + +Run (fermion): + OGBENCH_IMPLS=ogbench_ref/impls .venv/bin/python ogbench_genq/diagnostics/diag_chain_depth.py +""" +import json +import os +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +import jax +import jax.numpy as jnp + +import target_extractors +from genq_jax import load_genq_params, sample +from genq_recursive_jax import fit_midpoint_actor +from train_genq_jax import build_ends + +ENV = "puzzle-3x3-play-v0" +BETA = 0.95 +CKPT = os.path.join(PKG, "checkpoints", "m9_genq_rec_full_puzzle_3x3_play_v0_b095.genqjax.npz") +DEPTHS = [1, 2, 4, 8, 16, 26] +N_PAIRS = 256 +SEED = 0 + + +def main(): + from utils.env_utils import make_env_and_datasets + _env, ds, _ = make_env_and_datasets(ENV, frame_stack=None) + obs = np.asarray(ds["observations"], dtype=np.float32) + act = np.clip(np.asarray(ds["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(ds["terminals"]) + N, obs_dim = obs.shape + a_dim = act.shape[1] + rng = np.random.default_rng(SEED) + + P, meta = load_genq_params(CKPT) + assert meta["y_dim"] == obs_dim + + probe = np.arange(obs_dim, dtype=np.float32)[None] + bit_idx = target_extractors.extract_target(ENV, probe)[0].astype(np.int64) + sig_vec = np.full(obs_dim, 1e6, dtype=np.float32) + sig_vec[bit_idx] = 0.5 + sig_j = jnp.asarray(sig_vec) + + actor_fn, bcl = fit_midpoint_actor(obs, act, end_of, goal_of=lambda gi: obs[gi], + steps=30000, seed=SEED, log_every=0) + print(f"[depth-diag] midpoint actor fit loss={bcl:.4f}", flush=True) + + # anchors: (s, a_data, a_rand, hindsight goal) + t = rng.integers(0, N - 1, N_PAIRS) + span = np.maximum(end_of[t] - 1 - t, 1) + gi = np.clip(t + (rng.random(N_PAIRS) * span).astype(np.int64), 0, N - 1) + s0 = jnp.asarray(obs[t]) + a_data = jnp.asarray(act[t]) + a_rand = jnp.asarray(rng.uniform(-1, 1, (N_PAIRS, a_dim)).astype(np.float32)) + g = jnp.asarray(obs[gi]) + + # dataset stats for drift metrics + dmin, dmax = obs.min(0), obs.max(0) + dstd = obs.std(0) + 1e-6 + bank = obs[rng.integers(0, N, 20000)] + bank_j = jnp.asarray(bank / dstd) + + def nn_dist(x): + xn = jnp.asarray(np.asarray(x) / dstd) + d = jnp.linalg.norm(xn[:, None, :] - bank_j[None, :5000, :], axis=-1) + return float(jnp.mean(jnp.min(d, axis=1))) + + real_nn = nn_dist(obs[rng.integers(0, N, 512)]) + print(f"[depth-diag] baseline NN dist of real states: {real_nn:.3f}", flush=True) + + def run_chain(s, a, gg, depth, n_rep, key): + """forced-depth chain, n_rep independent chains per anchor -> endpoints [B*n_rep, obs]""" + M = s.shape[0] * n_rep + z = jnp.repeat(s, n_rep, axis=0) + a_cur = jnp.repeat(a, n_rep, axis=0) + gM = jnp.repeat(gg, n_rep, axis=0) + for _ in range(depth): + key, ks = jax.random.split(key) + c = jnp.concatenate([z, a_cur, gM], axis=-1) + z = sample(P, meta, c, 1, ks, steps=10)[:, 0, :] + a_cur = actor_fn(z, gM) + return z + + key = jax.random.PRNGKey(SEED) + run_j = {d: jax.jit(lambda s, a, gg, k, d=d, n=16: run_chain(s, a, gg, d, n, k)) for d in DEPTHS} + + # --- data flip-rate at matched horizons --- + def data_fliprate(h): + tt = rng.integers(0, N - 1, 4000) + jj = np.minimum(tt + h, end_of[tt] - 1) + b0 = np.round(obs[tt][:, bit_idx]); b1 = np.round(obs[jj][:, bit_idx]) + return float(np.mean(np.abs(b0 - b1))) + + res = {"depths": {}, "nocc_sweep": {}} + EK = 1.0 / (1.0 - BETA) # expected steps per jump = 20 + for d in DEPTHS: + key, sub = jax.random.split(key) + ep = np.asarray(run_j[d](s0, a_data, g, sub)) # [256*16, 55] + bits = ep[:, bit_idx] + binariness = float(np.mean(np.abs(bits - np.round(bits)))) + viol = float(np.mean((ep < dmin[None] - 0.05 * dstd[None]) | + (ep > dmax[None] + 0.05 * dstd[None]))) + nn = nn_dist(ep[:512]) + b0 = np.round(np.asarray(jnp.repeat(s0, 16, axis=0))[:, bit_idx]) + flips = float(np.mean(np.abs(np.round(bits) - b0))) + dflips = data_fliprate(int(EK * d)) + res["depths"][d] = dict(binariness=binariness, range_viol=viol, nn_dist=nn, + fliprate=flips, data_fliprate=dflips) + print(f"[depth-diag] d={d:2d} (≈{int(EK*d):3d} steps): bit-ness={binariness:.4f} " + f"range-viol={viol:.4f} NN={nn:.3f} (real {real_nn:.3f}) " + f"flips={flips:.3f} vs data {dflips:.3f}", flush=True) + + # --- per-action gap vs n_occ at composed depth (26 jumps ~ gamma=0.998 window) --- + def q_at(depth, n_rep, a, key): + outs = [] + chunk = max(1, 4096 // n_rep) + for i in range(0, N_PAIRS, chunk): + sl = slice(i, min(i + chunk, N_PAIRS)) + key, sub = jax.random.split(key) + ep = run_chain(s0[sl], a[sl], g[sl], depth, n_rep, sub) + ep = ep.reshape(-1, n_rep, obs_dim) + d2 = jnp.sum(((ep - g[sl][:, None, :]) / sig_j) ** 2, axis=-1) + outs.append(np.asarray(jnp.exp(-0.5 * d2).mean(axis=1))) + return np.concatenate(outs), key + + for depth in [1, 26]: + for n_occ in [16, 64, 256, 1024]: + qd, key = q_at(depth, n_occ, a_data, key) + qr, key = q_at(depth, n_occ, a_rand, key) + diff = qd - qr + gap = float(diff.mean()) + sem = float(diff.std() / np.sqrt(len(diff))) + res["nocc_sweep"][f"d{depth}_n{n_occ}"] = dict(gap=gap, sem=sem, + q_mean=float(qd.mean())) + print(f"[depth-diag] depth={depth:2d} n_occ={n_occ:4d}: gap(data-rand)={gap:+.5f} " + f"± {sem:.5f} (Q mean {qd.mean():.4f})", flush=True) + + out = os.path.join(PKG, "diagnostics", "chain_depth.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_gap_source.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_gap_source.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5b245d3711c934ea46e2a554e847206a8f28d1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_gap_source.py @@ -0,0 +1,286 @@ +"""#57: WHERE does the tau=0.5 GCIQL critic's far-goal action ordering come from? + +Known (diag_td_gap.py): the trained tau=0.5 TD critic has rel-gap +76% at 20-step +goals and a coherent +3.6% (5-sigma) at far goals where the TRUE behavior-Q is +statistically flat. Candidate ingredients: (a) the near-concentrated training-goal +mix, (b) bootstrap chaining, (c) parametric smoothing of the regression. Cells: + + gciql_near tau=0.5 GCIQL, value goals NEAR-ONLY (cur 0.2 / traj-geom 0.8 / + random 0.0) — never trained on far random goals. Far-gap persists + => generalization from near-goal structure suffices (bootstrap + ferries it); far-gap dies => random-goal training is load-bearing. + gciql_random tau=0.5 GCIQL, value goals RANDOM-ONLY (0/0/1) — near-goal + supervision removed, bootstrap intact. Tests necessity of (a). + mc NO-BOOTSTRAP control: same-size MLP critic regressed directly on + the trajectory-bounded absorbing first-passage target + gamma^{T_g} (the exact tau=0.5 functional, computed from data, 0 + if never reached), same default goal mix. Isolates (c)+(a) vs (b). + genq_near the Gen-Q transfer: gciql_genq (direct occupancy critic targets, + AWR alpha=300) with NEAR-ONLY value goals — never regressing on + far/random goals where the occupancy target is provably flat + (does removing flat-target 'poisoning' let near-goal + generalization win, as it appears to for TD?). + genq_default same but default goal mix — the trained-critic gap baseline. + +Every cell ends with the SAME gap measurement on the SAME anchors (seed 0, same +rng call order as diag_chain_depth.py): near (t+20), far-hindsight (uniform +in-trajectory future), and random-state goals; plus a 50-episode/task rollout +eval where an actor exists. + +Run: OGBENCH_IMPLS=... python diag_gap_source.py --mode [--train_steps N] +""" +import argparse +import json +import os +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, PKG) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +ENV = "puzzle-3x3-play-v0" +SEED = 0 +N_PAIRS = 256 +GAMMA = 0.99 + + +def build_anchors(obs, act, end_of): + rng = np.random.default_rng(SEED) + N = len(obs) + t = rng.integers(0, N - 1, N_PAIRS) + span = np.maximum(end_of[t] - 1 - t, 1) + gi_far = np.clip(t + (rng.random(N_PAIRS) * span).astype(np.int64), 0, N - 1) + a_rand = rng.uniform(-1, 1, (N_PAIRS, act.shape[1])).astype(np.float32) + gi_near = np.minimum(t + 20, end_of[t] - 1) + gi_rand = rng.integers(0, N, N_PAIRS) + return t, gi_near, gi_far, gi_rand, a_rand + + +def gap_eval(q_fn, obs, act, t, gi_near, gi_far, gi_rand, a_rand, fp_fn=None): + out = {} + for name, gi in [("near_20step", gi_near), ("far_hindsight", gi_far), ("random_goal", gi_rand)]: + qd = np.asarray(q_fn(obs[t], act[t], obs[gi])) + qr = np.asarray(q_fn(obs[t], a_rand, obs[gi])) + diff = qd - qr + out[name] = dict(gap=float(diff.mean()), sem=float(diff.std() / np.sqrt(len(diff))), + p_data_wins=float((diff > 0).mean()), + rel_gap=float(diff.mean() / (np.abs(qd).mean() + 1e-9)), + q_absmean=float(np.abs(qd).mean())) + if fp_fn is not None: + y = fp_fn(t, gi) + c = float(np.corrcoef(qd, y)[0, 1]) if y.std() > 0 else float("nan") + rk = _spearman(qd, y) + out[name]["corr_true_fp"] = c + out[name]["spearman_true_fp"] = rk + extra = f" corr(truth)={c:+.3f} rank={rk:+.3f}" + else: + extra = "" + print(f"[gap] {name:14s}: gap={diff.mean():+.4f}±{diff.std()/np.sqrt(len(diff)):.4f} " + f"P(win)={(diff>0).mean():.3f} rel={out[name]['rel_gap']:+.4f}{extra}", flush=True) + return out + + +def _spearman(a, b): + ra = np.argsort(np.argsort(a)).astype(np.float64) + rb = np.argsort(np.argsort(b)).astype(np.float64) + if ra.std() == 0 or rb.std() == 0: + return float("nan") + return float(np.corrcoef(ra, rb)[0, 1]) + + +def rollout_eval(agent, env, config, n_ep=50): + import jax + from utils.evaluation import evaluate + task_infos = env.unwrapped.task_infos if hasattr(env.unwrapped, "task_infos") else env.task_infos + eag = jax.device_put(agent, device=jax.devices("cpu")[0]) + per = [] + for tid in range(1, len(task_infos) + 1): + ei, _, _ = evaluate(agent=eag, env=env, task_id=tid, config=config, + num_eval_episodes=n_ep, num_video_episodes=0, + video_frame_skip=3, eval_temperature=0.0, eval_gaussian=None) + per.append(float(ei.get("success", 0.0))) + return float(np.mean(per)), per + + +GOAL_MIXES = { + "default": {}, + "near": dict(value_p_curgoal=0.2, value_p_trajgoal=0.8, value_p_randomgoal=0.0), + "random": dict(value_p_curgoal=0.0, value_p_trajgoal=0.0, value_p_randomgoal=1.0), +} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--mode", required=True, + choices=["gciql_near", "gciql_random", "mc", "genq_near", "genq_default", "genq_near_ddpg"]) + ap.add_argument("--train_steps", type=int, default=None) + ap.add_argument("--eval_episodes", type=int, default=50) + a = ap.parse_args() + + import jax + import jax.numpy as jnp + import tqdm + from utils.datasets import Dataset, GCDataset + from utils.env_utils import make_env_and_datasets + from train_genq_jax import build_ends + import target_extractors + + env, train_dataset, _ = make_env_and_datasets(ENV, frame_stack=None) + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(train_dataset["terminals"]) + N = len(obs) + anchors = build_anchors(obs, act, end_of) + _bit_idx = target_extractors.extract_target(ENV, np.arange(obs.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + _bits = np.round(obs[:, _bit_idx]).astype(np.int8) + + def fp_fn(tt, gg): + out = np.zeros(len(tt), dtype=np.float32) + for i, (ti, gi_) in enumerate(zip(tt, gg)): + if ti == gi_: + out[i] = 1.0; continue + fut = _bits[ti + 1:end_of[ti]] + hits = np.where(np.all(fut == _bits[gi_][None], axis=1))[0] + if len(hits): + out[i] = GAMMA ** (hits[0] + 1) + return out + + res = {"mode": a.mode} + + if a.mode.startswith("gciql"): + import gciql as gciql_mod + steps = a.train_steps or 500000 + config = gciql_mod.get_config() + config["actor_loss"] = "ddpgbc"; config["alpha"] = 1.0; config["expectile"] = 0.5 + config.update(GOAL_MIXES[a.mode.split("_")[1]]) + train_ds = GCDataset(Dataset.create(**train_dataset), config) + ex = train_ds.sample(2) + agent = gciql_mod.GCIQLAgent.create(SEED, ex["observations"], ex["actions"], config) + print(f"[{a.mode}] training {steps} steps, value goal mix " + f"cur={config['value_p_curgoal']} traj={config['value_p_trajgoal']} " + f"rand={config['value_p_randomgoal']}", flush=True) + for i in tqdm.trange(1, steps + 1, smoothing=0.1, dynamic_ncols=True, mininterval=30): + agent, _ = agent.update(train_ds.sample(config["batch_size"])) + + def q_fn(s, aa, g): + q = np.asarray(agent.network.select("critic")(s, g, actions=aa)) + return q.min(axis=0) if q.ndim == 2 else q + res["gaps"] = gap_eval(q_fn, obs, act, *anchors, fp_fn=fp_fn) + sr, per = rollout_eval(agent, env, config, n_ep=a.eval_episodes) + res["success_rate"] = sr; res["per_task"] = per + print(f"[{a.mode}] eval sr={sr:.3f}", flush=True) + + elif a.mode == "mc": + # no-bootstrap control: regress gamma^{T_g} (first passage within trajectory) + import flax.linen as fnn + import optax + steps = a.train_steps or 300000 + bit_idx = target_extractors.extract_target(ENV, np.arange(obs.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + bits = np.round(obs[:, bit_idx]).astype(np.int8) + + # precompute, per state, the NEXT index at which each visited config occurs is + # expensive; instead compute first-passage lazily per sampled (t, g) pair. + def fp_target(tt, gg): + out = np.zeros(len(tt), dtype=np.float32) + for i, (ti, gi_) in enumerate(zip(tt, gg)): + fut = bits[ti + 1:end_of[ti]] + hits = np.where(np.all(fut == bits[gi_][None], axis=1))[0] + if ti == gi_: + out[i] = 1.0 + elif len(hits): + out[i] = GAMMA ** (hits[0] + 1) + return out + + class QNet(fnn.Module): + @fnn.compact + def __call__(self, s, g, aa): + h = jnp.concatenate([s, g, aa], -1) + for _ in range(3): + h = fnn.gelu(fnn.Dense(512)(h)) + return fnn.Dense(1)(h)[..., 0] + + net = QNet() + params = net.init(jax.random.PRNGKey(SEED), jnp.zeros((1, obs.shape[1])), + jnp.zeros((1, obs.shape[1])), jnp.zeros((1, act.shape[1]))) + tx = optax.adam(3e-4); opt = tx.init(params) + + @jax.jit + def update(p, o, s, g, aa, y): + def loss(p): + return jnp.mean((net.apply(p, s, g, aa) - y) ** 2) + l, gr = jax.value_and_grad(loss)(p) + u, o = tx.update(gr, o, p) + return optax.apply_updates(p, u), o, l + + # default GCDataset value mix: 20% cur, 50% traj-geom, 30% random + rng = np.random.default_rng(SEED + 1) + print(f"[mc] regressing first-passage targets for {steps} steps", flush=True) + for i in tqdm.trange(1, steps + 1, smoothing=0.1, dynamic_ncols=True, mininterval=30): + t = rng.integers(0, N - 1, 256) + u = rng.random(256) + offs = rng.geometric(1 - GAMMA, 256) + gi = np.where(u < 0.2, t, np.minimum(t + offs, end_of[t] - 1)) + gi = np.where(u >= 0.7, rng.integers(0, N, 256), gi) + y = fp_target(t, gi) + params, opt, l = update(params, opt, jnp.asarray(obs[t]), jnp.asarray(obs[gi]), + jnp.asarray(act[t]), jnp.asarray(y)) + if i % 50000 == 0: + print(f"[mc] step {i} loss {float(l):.5f}", flush=True) + + def q_fn(s, aa, g): + return np.asarray(net.apply(params, jnp.asarray(s), jnp.asarray(g), jnp.asarray(aa))) + res["gaps"] = gap_eval(q_fn, obs, act, *anchors, fp_fn=fp_fn) + + else: # genq_near / genq_default + from genq_jax import load_genq_params, genq_q as genq_q_jax + from gciql_genq import GCIQLGenQAgent, get_config + steps = a.train_steps or 300000 + config = get_config() + config["actor_loss"] = "awr"; config["alpha"] = 300.0; config["expectile"] = 0.9 + if a.mode == "genq_near_ddpg": + config["actor_loss"] = "ddpgbc"; config["alpha"] = 1.0 + config.update(GOAL_MIXES["default" if a.mode.endswith("default") else "near"]) + P, meta = load_genq_params(os.path.join(PKG, "checkpoints", + "m9_genq_puzzle_3x3_play_v0.genqjax.npz")) + sig = 0.5 + genq_q_fn = jax.jit(lambda s, aa, g, k: genq_q_jax(P, meta, s, aa, g, k, n_occ=64, sigma=sig)) + gkey = [jax.random.PRNGKey(SEED + 999)] + + def to_tgt(gobs): + return target_extractors.extract_target(ENV, gobs).astype(np.float32) + + def genq_batch(o, go, aa): + gkey[0], sub = jax.random.split(gkey[0]) + return np.asarray(genq_q_fn(jnp.asarray(o), jnp.asarray(np.clip(aa, -1, 1)), + jnp.asarray(to_tgt(go)), sub)) + + train_ds = GCDataset(Dataset.create(**train_dataset), config) + ex = train_ds.sample(2) + agent = GCIQLGenQAgent.create(SEED, ex["observations"], ex["actions"], config) + print(f"[{a.mode}] training {steps} steps, value goal mix " + f"cur={config['value_p_curgoal']} traj={config['value_p_trajgoal']} " + f"rand={config['value_p_randomgoal']}, awr alpha=300", flush=True) + for i in tqdm.trange(1, steps + 1, smoothing=0.1, dynamic_ncols=True, mininterval=30): + batch = train_ds.sample(config["batch_size"]) + batch["genq_q_value"] = genq_batch(batch["observations"], batch["value_goals"], + batch["actions"]) + agent, _ = agent.update(batch) + + def q_fn(s, aa, g): + q = np.asarray(agent.network.select("critic")(s, g, actions=aa)) + return q.min(axis=0) if q.ndim == 2 else q + res["gaps"] = gap_eval(q_fn, obs, act, *anchors, fp_fn=fp_fn) + sr, per = rollout_eval(agent, env, config, n_ep=a.eval_episodes) + res["success_rate"] = sr; res["per_task"] = per + print(f"[{a.mode}] eval sr={sr:.3f}", flush=True) + + out = os.path.join(PKG, "diagnostics", f"gap_source_{a.mode}.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_goal_coverage.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_goal_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..e97279c393d8f248ba79ab411eeb3a0de2505a7c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_goal_coverage.py @@ -0,0 +1,136 @@ +"""Model-free goal-coverage diagnostic (#57 follow-up): why puzzle-3x3 starves a +behavior-occupancy critic while TD survives. + +For (state s_t, goal g) pairs drawn like GCIQL's value-goal sampler (hindsight +in-trajectory futures vs random-state goals), compute — exactly, from the raw +trajectories, no model anywhere: + + * TD's absorbing target Q_TD = gamma^{T_g}, T_g = first time the future + (within the trajectory) reaches g (0 if never: zero bootstrap-free support); + * the occupancy functional Q_occ = (1-gamma) sum_k gamma^k 1[s_{t+k} reaches g] + (what a perfect non-absorbing behavior-occupancy read-out reports); + * support fraction P(T_g < inf) — pairs where the behavior future + EVER reaches the goal, i.e. where any sample-based behavior read-out can be + nonzero at all. + +"Reach" per env: puzzle = all 9 button bits equal; mazes = xy within tol; +cube = cube xyz (scaled) within tol. + +The punchline this quantifies: with random (non-hindsight) goals — the pairs +where policy improvement has to come from — a combinatorial target space gives +zero-support futures almost everywhere, so ANY behavior-occupancy critic is +exactly 0 there (no gradient, no ranking); TD still trains those (s,a,g) via +bootstrap generalization. Continuous target spaces degrade gracefully instead +(distance shrinks smoothly), which is why pointmaze/cube work. + +Run (fermion): + OGBENCH_IMPLS=ogbench_ref/impls .venv/bin/python ogbench_genq/diagnostics/diag_goal_coverage.py +""" +import argparse +import json +import os +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +import target_extractors + + +def build_ends(term): + ends = np.where(np.asarray(term) > 0)[0] + end_of = np.zeros(len(term), dtype=np.int64) + prev = 0 + for e in ends: + end_of[prev:e + 1] = e + 1 + prev = e + 1 + if prev < len(term): + end_of[prev:] = len(term) + return end_of + + +def reach_mask(tgt_future, g, env): + """[L] bool: does target-state x reach goal g? puzzle: exact 9-bit match; + continuous: within tol (pointmaze xy tol=0.5 [oGBench success radius]; + cube scaled-xyz tol=0.4 [= 4cm]).""" + if env.startswith("puzzle"): + return np.all(np.round(tgt_future) == np.round(g)[None], axis=1) + tol = 0.5 if "maze" in env else 0.4 + return np.linalg.norm(tgt_future - g[None], axis=1) < tol + + +def analyze(env, n_pairs=20000, gamma=0.99, seed=0): + from utils.env_utils import make_env_and_datasets + _env, ds, _ = make_env_and_datasets(env, frame_stack=None) + obs = np.asarray(ds["observations"], dtype=np.float32) + end_of = build_ends(ds["terminals"]) + tgt = target_extractors.extract_target(env, obs).astype(np.float32) + N = len(obs) + rng = np.random.default_rng(seed) + + out = {} + for mode in ["hindsight", "random"]: + t = rng.integers(0, N - 1, n_pairs) + if mode == "hindsight": # in-trajectory future goal (GCDataset trajgoal branch) + span = np.maximum(end_of[t] - 1 - t, 1) + gi = np.clip(t + (rng.random(n_pairs) * span).astype(np.int64), 0, N - 1) + else: # random dataset state (GCDataset randomgoal branch) + gi = rng.integers(0, N, n_pairs) + q_td, q_occ, support, dmin = [], [], [], [] + for i in range(n_pairs): + fut = tgt[t[i] + 1:end_of[t[i]]] + if len(fut) == 0: + q_td.append(0.0); q_occ.append(0.0); support.append(False); dmin.append(np.inf) + continue + g = tgt[gi[i]] + m = reach_mask(fut, g, env) + hits = np.where(m)[0] + if len(hits): + q_td.append(gamma ** (hits[0] + 1)) + ks = np.arange(1, len(fut) + 1) + q_occ.append(float((1 - gamma) * np.sum((gamma ** ks) * m))) + support.append(True) + else: + q_td.append(0.0); q_occ.append(0.0); support.append(False) + if not env.startswith("puzzle"): + dmin.append(float(np.min(np.linalg.norm(fut - g[None], axis=1)))) + else: # hamming distance of the closest future config + dmin.append(float(np.min(np.sum(np.round(fut) != np.round(g)[None], axis=1)))) + out[mode] = dict( + support_frac=float(np.mean(support)), + q_td_mean=float(np.mean(q_td)), + q_td_mean_on_support=float(np.mean(np.asarray(q_td)[np.asarray(support)])) if any(support) else 0.0, + q_occ_mean=float(np.mean(q_occ)), + min_dist_median=float(np.median(dmin)), + ) + # play-data diversity of the target space (puzzle: distinct configs visited) + if env.startswith("puzzle"): + cfgs = np.unique(np.round(tgt).astype(np.int8), axis=0) + out["distinct_configs_visited"] = int(len(cfgs)) + out["config_space_size"] = 2 ** tgt.shape[1] + return out + + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--envs", default="pointmaze-medium-navigate-v0,cube-single-play-v0,puzzle-3x3-play-v0") + ap.add_argument("--n_pairs", type=int, default=20000) + ap.add_argument("--gamma", type=float, default=0.99) + a = ap.parse_args() + res = {} + for env in a.envs.split(","): + res[env] = analyze(env, n_pairs=a.n_pairs, gamma=a.gamma) + print(f"== {env}") + for mode in ["hindsight", "random"]: + r = res[env][mode] + print(f" {mode:9s} support={r['support_frac']:.3f} Q_td={r['q_td_mean']:.4f} " + f"(on-support {r['q_td_mean_on_support']:.4f}) Q_occ={r['q_occ_mean']:.5f} " + f"min-dist median={r['min_dist_median']:.3f}") + if "distinct_configs_visited" in res[env]: + print(f" configs visited: {res[env]['distinct_configs_visited']}/{res[env]['config_space_size']}") + out = os.path.join(PKG, "diagnostics", "goal_coverage.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out) diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_midpoint_competence.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_midpoint_competence.py new file mode 100644 index 0000000000000000000000000000000000000000..f3bdcf4851fef0cb1f7bcacd0ea9ecc762532a50 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_midpoint_competence.py @@ -0,0 +1,243 @@ +"""#57 Option-B keystone probe: how much first-action value signal does a COMPETENT +continuation (midpoint) policy create, as a function of goal horizon (in presses)? + +Theory (puzzle_why.md): Q^pi(s,a,g) - Q^pi(s,a',g) ~ E[gamma^{T_pi after a}] - +E[gamma^{T_pi after a'}]. Under the behavior continuation, T is high-variance and +start-insensitive => gaps die past ~1 press (oracle-verified). Under a competent +goal-directed continuation, one saved press = ~50 steps = a ~gamma^50 value ratio at +ANY horizon within the continuation's competence. This probe measures that curve with +the sim oracle and ZERO learning: + + continuation in {behavior-BC + noise, scripted-competent} x goal horizon in + {1, 2, 3, 5 presses} -> first-action oracle gap (policy action vs random action). + +The scripted-competent continuation is diagnostic-only (privileged): solve 3x3 +Lights-Out exactly over GF(2) (flip matrix is invertible), then drive the arm with the +env oracle's own phase logic (move above -> press -> release). If competence keeps the +gap alive at all horizons, the policy-iteration curriculum has a measured target +signal at every round. + +Run (fermion): OGBENCH_IMPLS=ogbench_ref/impls .venv/bin/python diag_midpoint_competence.py +""" +import argparse +import json +import os +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +ENV = "puzzle-3x3-play-v0" +SEED = 0 +GAMMA = 0.99 +NOISE = 0.1 +H = 400 +XYZ_CENTER = np.array([0.425, 0.0, 0.0]) +XYZ_SCALER = 10.0 +EFF_SLICE = slice(12, 15) + +FLIP = np.zeros((9, 9), dtype=np.int8) +for i in range(9): + r, c = divmod(i, 3) + for dr, dc in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)]: + rr, cc = r + dr, c + dc + if 0 <= rr < 3 and 0 <= cc < 3: + FLIP[i, rr * 3 + cc] = 1 + + +def gf2_inv(M): + n = len(M) + A = np.concatenate([M.copy() % 2, np.eye(n, dtype=int)], 1) + for col in range(n): + piv = next(r for r in range(col, n) if A[r, col]) + A[[col, piv]] = A[[piv, col]] + for r in range(n): + if r != col and A[r, col]: + A[r] = (A[r] + A[col]) % 2 + return A[:, n:] + + +FLIP_INV = gf2_inv(FLIP.astype(int)) + + +def presses_needed(sbits, gbits): + """exact Lights-Out solution: which buttons to press (any order).""" + diff = (np.asarray(sbits, dtype=int) ^ np.asarray(gbits, dtype=int)) % 2 + x = (FLIP_INV @ diff) % 2 + return [i for i in range(9) if x[i]] + + +def bits_of(ob, bit_idx): + return np.round(np.asarray(ob)[..., bit_idx]).astype(np.int8) + + +def shape_diff(diff, min_norm=0.4): + """MarkovOracle.shape_diff: scale small diffs UP to min_norm (direction saturation).""" + n = np.linalg.norm(diff) + return diff if n >= min_norm else diff / (n + 1e-6) * min_norm + + +class CompetentPress: + """Scripted goal-directed continuation: press the exact Lights-Out solution set, + one button at a time — a faithful port of ButtonMarkovOracle's phase logic + (approach above -> press to bottom -> rise -> next button).""" + + GAIN = 5.0 + ABOVE = 0.16 + + def __init__(self, btn_top_pos, bit_idx): + self.btn = btn_top_pos # [9,3] btntop_i site world positions + self.bit_idx = bit_idx + + def action(self, ob, gbits, rng): + sbits = bits_of(ob, self.bit_idx) + todo = presses_needed(sbits, gbits) + a = np.zeros(5, dtype=np.float32) + eff = np.asarray(ob)[EFF_SLICE] / XYZ_SCALER + XYZ_CENTER + if not todo: + return a + b = min(todo, key=lambda i: np.linalg.norm(self.btn[i][:2] - eff[:2])) + top = self.btn[b] + np.array([0, 0, 0.06]) + bottom = self.btn[b] - np.array([0, 0, 0.022]) + xy_aligned = np.linalg.norm(top[:2] - eff[:2]) <= 0.04 + above = eff[2] > self.ABOVE + if xy_aligned: + diff = bottom - eff # press + elif above: + diff = top - eff # approach above the button + else: + diff = np.array([eff[0], eff[1], self.ABOVE * 2]) - eff # rise first + a[:3] = np.clip(shape_diff(diff) * self.GAIN, -1, 1) + a[4] = 1.0 + return np.clip(a + rng.normal(0, 0.02, 5).astype(np.float32), -1, 1) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--n_anchors", type=int, default=48) + ap.add_argument("--reps", type=int, default=4) + ap.add_argument("--bc_steps", type=int, default=30000) + a = ap.parse_args() + + import ogbench + from utils.env_utils import make_env_and_datasets + from train_genq_jax import build_ends + from genq_recursive_jax import fit_midpoint_actor + import target_extractors + + _env, ds, _ = make_env_and_datasets(ENV, frame_stack=None) + obs_d = np.asarray(ds["observations"], dtype=np.float32) + act_d = np.clip(np.asarray(ds["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(ds["terminals"]) + bit_idx = target_extractors.extract_target( + ENV, np.arange(obs_d.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + + bc_fn, bcl = fit_midpoint_actor(obs_d, act_d, end_of, goal_of=lambda gi: obs_d[gi], + steps=a.bc_steps, seed=SEED, log_every=0) + print(f"[mid] BC fit loss={bcl:.4f}", flush=True) + + env = ogbench.make_env_and_datasets(ENV, env_only=True) + env.reset(options=dict(task_id=1)) + u = env.unwrapped + btn_pos = np.asarray([u._data.site_xpos[u._model.site(f"btntop_{i}").id].copy() + for i in range(9)]) + comp = CompetentPress(btn_pos, bit_idx) + rng = np.random.default_rng(SEED) + + def snapshot(): + return (u._data.qpos.copy(), u._data.qvel.copy(), u._cur_button_states.copy()) + + # sanity: can the scripted presser actually solve k-press goals from reset? + ok = 0 + for trial in range(10): + ob, _ = env.reset(options=dict(task_id=1)) + gbits = (bits_of(ob, bit_idx) ^ np.array(FLIP[rng.integers(0, 9)])) % 2 + for k in range(300): + ob, *_ = u.step(comp.action(ob, gbits, rng)) + if np.all(bits_of(ob, bit_idx) == gbits): + ok += 1 + break + print(f"[mid] scripted presser sanity: {ok}/10 one-press goals solved", flush=True) + + def rollout_q(snap, first_action, gbits, policy): + """oracle first-passage gamma^T under the given continuation policy.""" + u.set_state(*snap) + ob, *_ = u.step(np.clip(first_action, -1, 1)) + gob = None + if policy == "bc": + # BC conditions on a full goal obs; build one by copying the anchor obs + # and setting its bits — crude but matches how BC consumes goals. + gob = np.asarray(ob, dtype=np.float32).copy() + gob[bit_idx] = gbits.astype(np.float32) + for k in range(1, H + 1): + if np.all(bits_of(ob, bit_idx) == gbits): + return GAMMA ** k + if policy == "bc": + act = np.asarray(bc_fn(np.asarray(ob, dtype=np.float32)[None], gob[None]))[0] + act = np.clip(act + rng.normal(0, NOISE, act.shape), -1, 1) + elif policy == "semi": + # semi-competent: competent controller degraded by noise + random actions + if rng.random() < 0.10: + act = rng.uniform(-1, 1, 5).astype(np.float32) + else: + act = np.clip(comp.action(ob, gbits, rng) + rng.normal(0, 0.25, 5), -1, 1) + else: + act = comp.action(ob, gbits, rng) + ob, *_ = u.step(act) + return 0.0 + + # anchors: roll BC from resets (behavior-like states), goals at exact press-distances + res = {} + HORIZONS = [1, 2, 3, 5] + anchors = [] + while len(anchors) < a.n_anchors: + ob, info = env.reset(options=dict(task_id=int(rng.integers(1, 6)))) + gob0 = np.asarray(info["goal"], dtype=np.float32) + for _ in range(int(rng.integers(0, 300))): + act = np.asarray(bc_fn(np.asarray(ob, dtype=np.float32)[None], gob0[None]))[0] + ob, *_ = u.step(np.clip(act + rng.normal(0, NOISE, act.shape), -1, 1)) + anchors.append((snapshot(), np.asarray(ob, dtype=np.float32))) + print(f"[mid] {len(anchors)} anchors", flush=True) + + for policy in ["bc", "semi", "competent"]: + res[policy] = {} + for hz in HORIZONS: + gaps, qps = [], [] + for snap, aob in anchors: + sbits = bits_of(aob, bit_idx) + # goal exactly hz presses away: XOR of hz distinct random button flips + bsel = rng.choice(9, size=hz, replace=False) + gbits = sbits.copy() + for b in bsel: + gbits = (gbits ^ FLIP[b]) % 2 + if len(presses_needed(sbits, gbits)) != hz: + continue # rare degeneracy + if policy == "bc": + a_pol = np.asarray(bc_fn(aob[None], aob[None]))[0] + else: + a_pol = comp.action(aob, gbits, rng) + a_rnd = rng.uniform(-1, 1, 5).astype(np.float32) + qp = np.mean([rollout_q(snap, a_pol, gbits, policy) for _ in range(a.reps)]) + qr = np.mean([rollout_q(snap, a_rnd, gbits, policy) for _ in range(a.reps)]) + gaps.append(qp - qr) + qps.append(qp) + gaps, qps = np.asarray(gaps), np.asarray(qps) + res[policy][hz] = dict(gap=float(gaps.mean()), + sem=float(gaps.std() / np.sqrt(len(gaps))), + q=float(qps.mean()), + rel=float(gaps.mean() / (abs(qps.mean()) + 1e-9)), + nnz=float(np.mean(qps > 0)), n=len(gaps)) + r = res[policy][hz] + print(f"[mid] {policy:10s} {hz}-press: gap={r['gap']:+.4f}±{r['sem']:.4f} " + f"Q={r['q']:.4f} rel={r['rel']:+.3f} nnz={r['nnz']:.2f}", flush=True) + + out = os.path.join(PKG, "diagnostics", "midpoint_competence.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_oracle_q.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_oracle_q.py new file mode 100644 index 0000000000000000000000000000000000000000..05011f80570c427e5ba361f0352d074ae32bb168 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_oracle_q.py @@ -0,0 +1,248 @@ +"""#57: ORACLE behavior-Q on puzzle-3x3 — is the TRUE behavior Q useful for control? + +Ground-truth Monte-Carlo oracle with NO learned estimator in the value loop: +snapshot the simulator (qpos, qvel, button_states — the env's public set_state API), +execute a candidate action, then roll the behavior policy in the TRUE simulator and +score the true first-passage value gamma^{T_g} (and the occupancy-mass functional). +The behavior policy is the full-state gc-BC actor (fit loss ~0.019) + the dataset's +action noise (0.1), standing in for the non-Markovian ButtonPlanOracle whose plan +state is undefined at a mid-episode snapshot. + +Part A — oracle action gaps: on-distribution anchor states; oracle-Q gap between the +policy action and a random action, at NEAR goals (30 steps down the anchor's own +future), the FAR eval task goal, and a random dataset goal. This is the true-Q +flatness measurement with zero model error. + +Part B — oracle-argmax control: evaluate an argmax policy over the oracle Q (K +candidate actions, M rollouts each, horizon H, replan every R steps) on the real +eval tasks, against the plain BC baseline. If the oracle argmax cannot beat BC, the +true behavior Q is per-action uninformative at eval goals and NO faithful estimator +of it (occupancy, MC, or otherwise) can drive improvement on this env; if it wins, +the true Q is valuable and the estimators were the problem. + +Run (fermion, CPU-heavy): + OGBENCH_IMPLS=ogbench_ref/impls .venv/bin/python ogbench_genq/diagnostics/diag_oracle_q.py +""" +import argparse +import json +import os +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +ENV = "puzzle-3x3-play-v0" +SEED = 0 +GAMMA = 0.99 +NOISE = 0.1 # dataset-generation action noise +H = 300 # rollout horizon (gamma^300 ~ 0.05 tail) + + +def bits_of(ob, bit_idx): + return np.round(np.asarray(ob)[..., bit_idx]).astype(np.int8) + + +class SimPool: + """E lockstep clones of the puzzle env with snapshot/restore + batched BC policy.""" + + def __init__(self, n_env, actor_fn, bit_idx, rng): + import ogbench + self.envs = [ogbench.make_env_and_datasets(ENV, env_only=True) for _ in range(n_env)] + for e in self.envs: + e.reset(options=dict(task_id=1)) + self.actor_fn = actor_fn + self.bit_idx = bit_idx + self.rng = rng + self.n = n_env + + @staticmethod + def snapshot(env): + u = env.unwrapped + return (u._data.qpos.copy(), u._data.qvel.copy(), u._cur_button_states.copy()) + + def rollout_batch(self, snaps, first_actions, goals, horizon): + """Restore snaps[i], apply first_actions[i], then roll BC+noise toward goals[i]. + Returns (fp_value [B], occ_mass [B]) — true first-passage gamma^T and + (1-gamma) sum gamma^k 1[bits==goal_bits].""" + B = len(snaps) + assert B <= self.n + obs = [] + for i in range(B): + u = self.envs[i].unwrapped + u.set_state(*snaps[i]) + ob, *_ = u.step(np.clip(first_actions[i], -1, 1)) + obs.append(ob) + obs = np.asarray(obs, dtype=np.float32) + g = np.asarray(goals, dtype=np.float32) + gbits = bits_of(g, self.bit_idx) + fp = np.zeros(B) + occ = np.zeros(B) + done = np.zeros(B, dtype=bool) + hit0 = np.all(bits_of(obs, self.bit_idx) == gbits, axis=1) + fp[hit0] = GAMMA + occ[hit0] += (1 - GAMMA) * GAMMA + done |= hit0 + for k in range(2, horizon + 1): + acts = np.asarray(self.actor_fn(obs, g)) + acts = np.clip(acts + self.rng.normal(0, NOISE, acts.shape), -1, 1).astype(np.float32) + for i in range(B): + ob, *_ = self.envs[i].unwrapped.step(acts[i]) + obs[i] = ob + hits = np.all(bits_of(obs, self.bit_idx) == gbits, axis=1) + occ[hits] += (1 - GAMMA) * GAMMA ** k + new = hits & ~done + fp[new] = GAMMA ** k + done |= new + return fp, occ + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--n_env", type=int, default=16) + ap.add_argument("--n_anchors", type=int, default=64) + ap.add_argument("--reps", type=int, default=6) + ap.add_argument("--episodes", type=int, default=4, help="eval episodes per task per arm") + ap.add_argument("--K", type=int, default=8, help="candidate actions per replan") + ap.add_argument("--M", type=int, default=2, help="oracle rollouts per candidate") + ap.add_argument("--replan", type=int, default=5) + ap.add_argument("--plan_h", type=int, default=150) + ap.add_argument("--bc_steps", type=int, default=30000) + a = ap.parse_args() + + import jax + from utils.env_utils import make_env_and_datasets + from train_genq_jax import build_ends + from genq_recursive_jax import fit_midpoint_actor + import target_extractors + + _env, ds, _ = make_env_and_datasets(ENV, frame_stack=None) + obs_d = np.asarray(ds["observations"], dtype=np.float32) + act_d = np.clip(np.asarray(ds["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(ds["terminals"]) + bit_idx = target_extractors.extract_target( + ENV, np.arange(obs_d.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + + actor_fn, bcl = fit_midpoint_actor(obs_d, act_d, end_of, goal_of=lambda gi: obs_d[gi], + steps=a.bc_steps, seed=SEED, log_every=0) + print(f"[oracle] BC rollout policy fit, loss={bcl:.4f}", flush=True) + + rng = np.random.default_rng(SEED) + pool = SimPool(a.n_env, actor_fn, bit_idx, rng) + print(f"[oracle] {a.n_env} sim clones ready", flush=True) + + # ---------------- Part A: oracle action gaps at anchor states ---------------- + # anchors: roll BC from task resets for random durations; goals: near = 30 steps + # further down the SAME rollout; far = the task goal; random = random dataset state. + anchors, near_goals, far_goals = [], [], [] + env0 = pool.envs[0] + while len(anchors) < a.n_anchors: + tid = int(rng.integers(1, 6)) + ob, info = env0.reset(options=dict(task_id=tid)) + gob = np.asarray(info["goal"], dtype=np.float32) + T0 = int(rng.integers(0, 400)) + for _ in range(T0): + act = np.asarray(pool.actor_fn(ob[None], gob[None]))[0] + ob, *_ = env0.unwrapped.step(np.clip(act + rng.normal(0, NOISE, act.shape), -1, 1)) + snap = SimPool.snapshot(env0) + anchor_ob = np.asarray(ob, dtype=np.float32) + # near goal = a few steps past the NEXT bit flip on this rollout (a genuine + # 1-press goal; a fixed +30 steps usually has identical bits -> trivial). + b0 = bits_of(anchor_ob, bit_idx) + flip_k, flip_ob = None, None + for k in range(120): + act = np.asarray(pool.actor_fn(ob[None], gob[None]))[0] + ob, *_ = env0.unwrapped.step(np.clip(act + rng.normal(0, NOISE, act.shape), -1, 1)) + if flip_k is None and not np.all(bits_of(np.asarray(ob), bit_idx) == b0): + flip_k = k + if flip_k is not None and k >= flip_k + 5: + flip_ob = np.asarray(ob, dtype=np.float32) + break + if flip_ob is None: + continue # no press within 120 steps; resample anchor + anchors.append((snap, anchor_ob)) + near_goals.append(flip_ob) + far_goals.append(gob) + rand_goals = obs_d[rng.integers(0, len(obs_d), a.n_anchors)] + print(f"[oracle] {len(anchors)} anchors collected", flush=True) + + res = {"bc_loss": bcl, "gaps": {}} + for gname, goals in [("near_30step", near_goals), ("far_taskgoal", far_goals), + ("random_goal", rand_goals)]: + qs = {"pol": [], "rand": []} + for aname in ["pol", "rand"]: + fp_acc = np.zeros(a.n_anchors) + for rep in range(a.reps): + for i0 in range(0, a.n_anchors, a.n_env): + sl = slice(i0, min(i0 + a.n_env, a.n_anchors)) + snaps = [anchors[i][0] for i in range(sl.start, sl.stop)] + aobs = np.asarray([anchors[i][1] for i in range(sl.start, sl.stop)]) + gg = np.asarray([goals[i] for i in range(sl.start, sl.stop)]) + if aname == "pol": + fa = np.asarray(pool.actor_fn(aobs, gg)) + else: + fa = rng.uniform(-1, 1, (sl.stop - sl.start, act_d.shape[1])) + fp, _ = pool.rollout_batch(snaps, fa, gg, H) + fp_acc[sl] += fp + qs[aname] = fp_acc / a.reps + diff = qs["pol"] - qs["rand"] + res["gaps"][gname] = dict(gap=float(diff.mean()), + sem=float(diff.std() / np.sqrt(len(diff))), + p_pol_wins=float((diff > 0).mean()), + q_mean=float(qs["pol"].mean()), + nnz_frac=float(np.mean((qs["pol"] > 0) | (qs["rand"] > 0))), + rel_gap=float(diff.mean() / (abs(qs["pol"].mean()) + 1e-9))) + r = res["gaps"][gname] + print(f"[oracle] gap {gname:13s}: {r['gap']:+.4f}±{r['sem']:.4f} " + f"P(win)={r['p_pol_wins']:.3f} Q={r['q_mean']:.4f} rel={r['rel_gap']:+.3f} " + f"nnz={r['nnz_frac']:.2f}", flush=True) + + # ---------------- Part B: oracle-argmax control vs BC baseline ---------------- + def run_episode(tid, use_oracle): + ob, info = env0.reset(options=dict(task_id=tid)) + gob = np.asarray(info["goal"], dtype=np.float32) + succ = 0.0 + chosen = None + for t in range(500): + if use_oracle and t % a.replan == 0: + snap = SimPool.snapshot(env0) + a_bc = np.asarray(pool.actor_fn(np.asarray(ob)[None], gob[None]))[0] + cands = [a_bc] + for _ in range(a.K - 3): + cands.append(np.clip(a_bc + rng.normal(0, 0.3, a_bc.shape), -1, 1)) + for _ in range(2): + cands.append(rng.uniform(-1, 1, a_bc.shape)) + cands = np.asarray(cands, dtype=np.float32) + scores = np.zeros(len(cands)) + snaps = [snap] * len(cands) + gg = np.repeat(gob[None], len(cands), axis=0) + for m in range(a.M): + fp, _ = pool.rollout_batch(snaps, cands, gg, a.plan_h) + scores += fp + chosen = cands[int(np.argmax(scores))] + act = chosen + elif use_oracle: + act = np.asarray(pool.actor_fn(np.asarray(ob)[None], gob[None]))[0] + else: + act = np.asarray(pool.actor_fn(np.asarray(ob)[None], gob[None]))[0] + ob, _, _, _, info = env0.step(np.clip(act, -1, 1)) + succ = max(succ, float(info.get("success", 0.0))) + return succ + + for arm in ["bc", "oracle_argmax"]: + srs = [] + for tid in range(1, 6): + for ep in range(a.episodes): + srs.append(run_episode(tid, arm == "oracle_argmax")) + res[f"sr_{arm}"] = float(np.mean(srs)) + print(f"[oracle] ARM {arm}: success={np.mean(srs):.3f} over {len(srs)} episodes", flush=True) + + out = os.path.join(PKG, "diagnostics", "oracle_q.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_ordering_content.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_ordering_content.py new file mode 100644 index 0000000000000000000000000000000000000000..8bad614f396b3f4cf68b53ad33e7310c608eebd2 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_ordering_content.py @@ -0,0 +1,233 @@ +"""#57 final probe: is Gen-Q's far-goal action ordering WRONG IN CONTENT, or just +too small in magnitude? + +Trains the two matched critics (TD tau=0.5 near-goals / Gen-Q near-goals — the +0.84-vs-0.05 pair from diag_gap_source) and, on identical candidate-action sets at +identical anchors, measures: + + 1. cross-critic ranking agreement — Spearman(rank_TD, rank_GenQ) per anchor; + 2. ranking vs a geometric PROGRESS ORACLE — on puzzle the ground-truth usefulness + of an action is computable analytically: Lights-Out algebra says which buttons + reduce Hamming distance to the goal bits, and action[:3] is the commanded + effector displacement, so progress(a) = max over useful buttons of the cosine + alignment of a[:3] with the direction from the effector to that button's top. + (Approximate — ignores the go-above-then-press phasing — but identical for + both critics, so differences are attributable.) + +Readout: TD-far tracks progress while GenQ-far doesn't => ordering CONTENT differs +(TD's chained targets encode realizable progress; Gen-Q's far ordering is an +extrapolation artifact). Both track progress equally => the delta is magnitude/ +noise. Near-goal versions serve as the calibration where both critics have signal. + +Run: OGBENCH_IMPLS=... python diag_ordering_content.py [--gciql_steps N --genq_steps N] +""" +import argparse +import json +import os +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, PKG) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +ENV = "puzzle-3x3-play-v0" +SEED = 0 +N_PAIRS = 256 +K = 16 + +# Lights-Out 3x3 flip matrix: pressing button i toggles i and von-Neumann neighbors. +FLIP = np.zeros((9, 9), dtype=np.int8) +for i in range(9): + r, c = divmod(i, 3) + for dr, dc in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)]: + rr, cc = r + dr, c + dc + if 0 <= rr < 3 and 0 <= cc < 3: + FLIP[i, rr * 3 + cc] = 1 + +XYZ_CENTER = np.array([0.425, 0.0, 0.0]) +XYZ_SCALER = 10.0 +EFF_SLICE = slice(12, 15) + + +def spearman(a, b): + ra = np.argsort(np.argsort(a)).astype(float) + rb = np.argsort(np.argsort(b)).astype(float) + if ra.std() == 0 or rb.std() == 0: + return np.nan + return float(np.corrcoef(ra, rb)[0, 1]) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--gciql_steps", type=int, default=500000) + ap.add_argument("--genq_steps", type=int, default=300000) + a = ap.parse_args() + + import jax + import jax.numpy as jnp + import tqdm + from utils.datasets import Dataset, GCDataset + from utils.env_utils import make_env_and_datasets + from train_genq_jax import build_ends + import target_extractors + + env, train_dataset, _ = make_env_and_datasets(ENV, frame_stack=None) + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(train_dataset["terminals"]) + N = len(obs) + bit_idx = target_extractors.extract_target( + ENV, np.arange(obs.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + + # button top world positions from the model (geom names containing 'button') + u = env.unwrapped + import mujoco + btn_pos = [] + for i in range(9): + gid = None + for cand in (f"buttonbox_{i}", f"button_{i}", f"buttonbox_geom_{i}"): + try: + gid = u._model.geom(cand).id + break + except KeyError: + continue + if gid is None: + body = u._model.body(f"buttonbox_{i}") + btn_pos.append(u._data.xpos[body.id].copy()) + else: + btn_pos.append(u._data.geom_xpos[gid].copy()) + btn_pos = np.asarray(btn_pos) # [9, 3] world positions + print(f"[probe] button positions:\n{np.round(btn_pos, 3)}", flush=True) + + # anchors (same seed/order as prior diagnostics) + goal sets + rng = np.random.default_rng(SEED) + t = rng.integers(0, N - 1, N_PAIRS) + span = np.maximum(end_of[t] - 1 - t, 1) + _gi_far_hind = np.clip(t + (rng.random(N_PAIRS) * span).astype(np.int64), 0, N - 1) + _a_rand = rng.uniform(-1, 1, (N_PAIRS, act.shape[1])) + gi_near = np.minimum(t + 20, end_of[t] - 1) + # far TASK goals: the 5 eval goals, round-robin + task_goals = [] + for tid in range(1, 6): + _, info = env.reset(options=dict(task_id=tid)) + task_goals.append(np.asarray(info["goal"], dtype=np.float32)) + g_task = np.asarray([task_goals[i % 5] for i in range(N_PAIRS)]) + + # candidate sets: data action + 7 perturbed + 8 uniform + cands = np.zeros((N_PAIRS, K, act.shape[1]), dtype=np.float32) + cands[:, 0] = act[t] + for j in range(1, 8): + cands[:, j] = np.clip(act[t] + rng.normal(0, 0.3, act[t].shape), -1, 1) + cands[:, 8:] = rng.uniform(-1, 1, (N_PAIRS, 8, act.shape[1])) + + def progress_scores(s_obs, goal_obs): + """[N_PAIRS, K] geometric progress oracle.""" + sbits = np.round(s_obs[:, bit_idx]).astype(np.int8) + gbits = np.round(goal_obs[:, bit_idx]).astype(np.int8) + eff = s_obs[:, EFF_SLICE] / XYZ_SCALER + XYZ_CENTER[None] + out = np.full((len(s_obs), K), np.nan) + for i in range(len(s_obs)): + d0 = np.sum(sbits[i] != gbits[i]) + useful = [b for b in range(9) + if np.sum(((sbits[i] + FLIP[b]) % 2) != gbits[i]) < d0] + if not useful: + continue + dirs = btn_pos[useful] + np.array([0, 0, 0.06]) - eff[i][None] # [U,3] + dirs = dirs / (np.linalg.norm(dirs, axis=1, keepdims=True) + 1e-9) + av = cands[i, :, :3] + avn = av / (np.linalg.norm(av, axis=1, keepdims=True) + 1e-9) + out[i] = np.max(avn @ dirs.T, axis=1) + return out + + # ---------------- train the two critics ---------------- + NEAR = dict(value_p_curgoal=0.2, value_p_trajgoal=0.8, value_p_randomgoal=0.0) + + import gciql as gciql_mod + cfg1 = gciql_mod.get_config() + cfg1["actor_loss"] = "ddpgbc"; cfg1["alpha"] = 1.0; cfg1["expectile"] = 0.5 + cfg1.update(NEAR) + ds1 = GCDataset(Dataset.create(**train_dataset), cfg1) + ex = ds1.sample(2) + td_agent = gciql_mod.GCIQLAgent.create(SEED, ex["observations"], ex["actions"], cfg1) + print(f"[probe] training TD tau=0.5 near critic {a.gciql_steps} steps", flush=True) + for i in tqdm.trange(1, a.gciql_steps + 1, smoothing=0.1, dynamic_ncols=True, mininterval=30): + td_agent, _ = td_agent.update(ds1.sample(cfg1["batch_size"])) + + from genq_jax import load_genq_params, genq_q as genq_q_jax + from gciql_genq import GCIQLGenQAgent, get_config + cfg2 = get_config() + cfg2["actor_loss"] = "awr"; cfg2["alpha"] = 300.0; cfg2["expectile"] = 0.9 + cfg2.update(NEAR) + P, meta = load_genq_params(os.path.join(PKG, "checkpoints", "m9_genq_puzzle_3x3_play_v0.genqjax.npz")) + gq = jax.jit(lambda s, aa, g, k: genq_q_jax(P, meta, s, aa, g, k, n_occ=64, sigma=0.5)) + gkey = [jax.random.PRNGKey(SEED + 999)] + + def to_tgt(gobs): + return target_extractors.extract_target(ENV, gobs).astype(np.float32) + + def genq_batch(o, go, aa): + gkey[0], sub = jax.random.split(gkey[0]) + return np.asarray(gq(jnp.asarray(o), jnp.asarray(np.clip(aa, -1, 1)), + jnp.asarray(to_tgt(go)), sub)) + + ds2 = GCDataset(Dataset.create(**train_dataset), cfg2) + ex = ds2.sample(2) + gq_agent = GCIQLGenQAgent.create(SEED, ex["observations"], ex["actions"], cfg2) + print(f"[probe] training Gen-Q near critic {a.genq_steps} steps", flush=True) + for i in tqdm.trange(1, a.genq_steps + 1, smoothing=0.1, dynamic_ncols=True, mininterval=30): + batch = ds2.sample(cfg2["batch_size"]) + batch["genq_q_value"] = genq_batch(batch["observations"], batch["value_goals"], batch["actions"]) + gq_agent, _ = gq_agent.update(batch) + + def q_of(agent): + def q_fn(s, aa, g): + q = np.asarray(agent.network.select("critic")(s, g, actions=aa)) + return q.min(axis=0) if q.ndim == 2 else q + return q_fn + + # ---------------- rank analysis ---------------- + res = {} + for gname, goals in [("far_task", g_task), ("near_20step", obs[gi_near])]: + prog = progress_scores(obs[t], goals) + ranks = {} + for cname, q_fn in [("td", q_of(td_agent)), ("genq", q_of(gq_agent))]: + qs = np.zeros((N_PAIRS, K)) + for j in range(K): + qs[:, j] = q_fn(obs[t], cands[:, j], goals) + ranks[cname] = qs + agree, td_vs_prog, gq_vs_prog = [], [], [] + top1 = {"td": [], "genq": [], "prog_best": []} + for i in range(N_PAIRS): + if np.isnan(prog[i]).any(): + continue + agree.append(spearman(ranks["td"][i], ranks["genq"][i])) + td_vs_prog.append(spearman(ranks["td"][i], prog[i])) + gq_vs_prog.append(spearman(ranks["genq"][i], prog[i])) + top1["td"].append(prog[i][np.argmax(ranks["td"][i])]) + top1["genq"].append(prog[i][np.argmax(ranks["genq"][i])]) + top1["prog_best"].append(prog[i].max()) + res[gname] = dict( + n=len(agree), + rank_agreement_td_genq=float(np.nanmean(agree)), + td_vs_progress=float(np.nanmean(td_vs_prog)), + genq_vs_progress=float(np.nanmean(gq_vs_prog)), + td_top1_progress=float(np.mean(top1["td"])), + genq_top1_progress=float(np.mean(top1["genq"])), + best_possible_progress=float(np.mean(top1["prog_best"])), + ) + r = res[gname] + print(f"[probe] {gname:12s}: agree(TD,GenQ)={r['rank_agreement_td_genq']:+.3f} " + f"TDvsProg={r['td_vs_progress']:+.3f} GenQvsProg={r['genq_vs_progress']:+.3f} " + f"top1prog TD={r['td_top1_progress']:+.3f} GenQ={r['genq_top1_progress']:+.3f} " + f"(best {r['best_possible_progress']:+.3f})", flush=True) + + out = os.path.join(PKG, "diagnostics", "ordering_content.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_press_planner.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_press_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..30659f99c75a27d568d4a941d965e35157bae374 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_press_planner.py @@ -0,0 +1,174 @@ +"""#57 Option-B phase 1: does the SAMPLED CHAIN REACH-SCORE discriminate between +candidate one-press midpoints? (feasibility gate for the press-scale planner) + +Scorer (no TD, no distance oracle, sparse-equality only): for a candidate midpoint +z (a one-press future sampled from the full-state occupancy), run n_r composed +chains of L hops from z (behavior midpoint actor) and score + reach(z) = fraction of chains whose BITS EXACTLY EQUAL the goal bits at any hop. +The press-scale argument: a candidate one press closer to g multiplies the random- +walk hit probability by ~the press branching factor — large relative differences, +unlike the ~2% arm-tick ceiling. + +Measures per anchor (dataset states, goals = eval task goals): + * candidate score spread (max/mean/min over distinct candidate configs); + * discrimination: is the spread >> sampling noise (binomial sem)? + * DIAGNOSTIC-ONLY validation (not used by the method): does the top-scored + candidate reduce the exact GF(2) presses-needed vs the anchor? + +Run (fermion): OGBENCH_IMPLS=ogbench_ref/impls .venv/bin/python diag_press_planner.py +""" +import argparse +import json +import os +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +ENV = "puzzle-3x3-play-v0" +SEED = 0 +CKPT = os.path.join(PKG, "checkpoints", "m9_genq_rec_full_puzzle_3x3_play_v0_b095.genqjax.npz") + +FLIP = np.zeros((9, 9), dtype=np.int8) +for i in range(9): + r, c = divmod(i, 3) + for dr, dc in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)]: + rr, cc = r + dr, c + dc + if 0 <= rr < 3 and 0 <= cc < 3: + FLIP[i, rr * 3 + cc] = 1 + + +def gf2_inv(M): + n = len(M) + A = np.concatenate([M.copy() % 2, np.eye(n, dtype=int)], 1) + for col in range(n): + piv = next(r for r in range(col, n) if A[r, col]) + A[[col, piv]] = A[[piv, col]] + for r in range(n): + if r != col and A[r, col]: + A[r] = (A[r] + A[col]) % 2 + return A[:, n:] + + +FLIP_INV = gf2_inv(FLIP.astype(int)) + + +def n_presses(sbits, gbits): + return int((( FLIP_INV @ ((np.asarray(sbits, int) ^ np.asarray(gbits, int)) % 2)) % 2).sum()) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--n_anchors", type=int, default=32) + ap.add_argument("--n_cand", type=int, default=24, help="midpoint samples per anchor") + ap.add_argument("--n_chains", type=int, default=256, help="chains per distinct candidate") + ap.add_argument("--hops", type=int, default=8) + ap.add_argument("--steps_per_jump", type=int, default=10) + ap.add_argument("--bc_steps", type=int, default=30000) + a = ap.parse_args() + + import jax + import jax.numpy as jnp + from utils.env_utils import make_env_and_datasets + from train_genq_jax import build_ends + from genq_jax import load_genq_params, sample + from genq_recursive_jax import fit_midpoint_actor + import target_extractors + import ogbench + + _env, ds, _ = make_env_and_datasets(ENV, frame_stack=None) + obs = np.asarray(ds["observations"], dtype=np.float32) + act = np.clip(np.asarray(ds["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(ds["terminals"]) + N, obs_dim = obs.shape + bit_idx = target_extractors.extract_target( + ENV, np.arange(obs_dim, dtype=np.float32)[None])[0].astype(np.int64) + + P, meta = load_genq_params(CKPT) + actor_fn, bcl = fit_midpoint_actor(obs, act, end_of, goal_of=lambda gi: obs[gi], + steps=a.bc_steps, seed=SEED, log_every=0) + print(f"[plan] BC fit {bcl:.4f}", flush=True) + + env = ogbench.make_env_and_datasets(ENV, env_only=True) + task_goals = [] + for tid in range(1, 6): + _, info = env.reset(options=dict(task_id=tid)) + task_goals.append(np.asarray(info["goal"], dtype=np.float32)) + + rng = np.random.default_rng(SEED) + key = jax.random.PRNGKey(SEED) + + def sample_midpoints(s, aa, g, n, k): + c = jnp.concatenate([jnp.asarray(s), jnp.asarray(aa), jnp.asarray(g)], -1)[None] + return np.asarray(sample(P, meta, c, n, k, steps=a.steps_per_jump)[0]) # [n, obs] + + def chain_reach(z0_batch, g, gbits, k): + """z0_batch [B, obs] -> fraction of chains from each z0 hitting gbits within hops. + One batched chain over all B*n_chains; behavior midpoints; sparse equality only.""" + B = len(z0_batch) + M = B * a.n_chains + z = jnp.asarray(np.repeat(z0_batch, a.n_chains, axis=0)) + gM = jnp.asarray(np.repeat(g[None], M, axis=0)) + hit = np.zeros(M, dtype=bool) + zb = np.asarray(z) + hit |= np.all(np.round(zb[:, bit_idx]) == gbits[None], axis=1) + for _ in range(a.hops): + k, ks = jax.random.split(k) + aM = actor_fn(z, gM) + c = jnp.concatenate([z, aM, gM], -1) + z = sample(P, meta, c, 1, ks, steps=a.steps_per_jump)[:, 0, :] + zb = np.asarray(z) + hit |= np.all(np.round(zb[:, bit_idx]) == gbits[None], axis=1) + return hit.reshape(B, a.n_chains).mean(axis=1), k + + t = rng.integers(0, N, a.n_anchors) + spreads, top_press_delta, rand_press_delta, scores_all = [], [], [], [] + discrim = 0 + for i in range(a.n_anchors): + s = obs[t[i]] + g = task_goals[i % 5] + gbits = np.round(g[bit_idx]).astype(np.int8) + sbits = np.round(s[bit_idx]).astype(np.int8) + key, ks = jax.random.split(key) + mids = sample_midpoints(s, act[t[i]], g, a.n_cand, ks) + mbits = np.round(mids[:, bit_idx]).astype(np.int8) + # distinct candidate configs (dedupe by bits), keep one representative each + uniq, idx = np.unique(mbits, axis=0, return_index=True) + reps = mids[idx] + key, ks = jax.random.split(key) + sc, key = chain_reach(reps, g, gbits, ks) + sem = np.sqrt(np.maximum(sc * (1 - sc), 1e-9) / a.n_chains) + spread = sc.max() - sc.min() + noise = float(np.median(sem)) * 2 + spreads.append(spread) + scores_all.append(float(sc.mean())) + if spread > 3 * noise and sc.max() > 0: + discrim += 1 + # diagnostic-only: press-distance change of top-scored vs random candidate + p0 = n_presses(sbits, gbits) + top_press_delta.append(n_presses(uniq[int(np.argmax(sc))], gbits) - p0) + rand_press_delta.append(n_presses(uniq[int(rng.integers(0, len(uniq)))], gbits) - p0) + print(f"[plan] anchor {i:2d}: {len(uniq):2d} distinct cands, presses0={p0}, " + f"scores [{sc.min():.4f},{sc.max():.4f}] spread={spread:.4f} (noise~{noise:.4f}) " + f"topΔpress={top_press_delta[-1]:+d} randΔpress={rand_press_delta[-1]:+d}", flush=True) + + res = dict(bc_loss=bcl, n_anchors=a.n_anchors, hops=a.hops, n_chains=a.n_chains, + mean_score=float(np.mean(scores_all)), + mean_spread=float(np.mean(spreads)), + discriminating_frac=discrim / a.n_anchors, + top_press_delta_mean=float(np.mean(top_press_delta)), + rand_press_delta_mean=float(np.mean(rand_press_delta))) + print(f"[plan] SUMMARY: mean score={res['mean_score']:.4f} mean spread={res['mean_spread']:.4f} " + f"discriminating anchors={res['discriminating_frac']:.2f} " + f"top-cand Δpresses={res['top_press_delta_mean']:+.2f} vs random {res['rand_press_delta_mean']:+.2f}", + flush=True) + out = os.path.join(PKG, "diagnostics", "press_planner_feasibility.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_td_gap.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_td_gap.py new file mode 100644 index 0000000000000000000000000000000000000000..f4d6c0322d732d0563d670f9f00d452822237df3 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/diag_td_gap.py @@ -0,0 +1,98 @@ +"""#57: where does TD's action ordering come from, if the true long-horizon behavior-Q +is action-flat (diag_chain_depth.py: gap +0.00025 ± 0.00017 at n_occ=1024)? + +Train the tau=0.5 reference GCIQL (pure behavior-policy TD evaluation, ddpgbc alpha=1.0 +— the configuration that scores 0.96 on puzzle) and measure ITS per-action gap +Q(s, a_data, g) - Q(s, a_rand, g) on the SAME anchor (s, a_data, a_rand, g) tuples the +chain diagnostic used (same rng seed + call order). If the trained critic shows a large, +sign-consistent gap where the true functional is ~0, TD's action signal is generated by +function-approximation generalization (near-goal structure propagated by the bootstrap), +not by the true values — closing the mechanism question. + +Also reports the gap at NEAR goals (20 steps downstream), where the true signal is real +(depth-1 chain gap +0.0104), as the calibration point. + +Run (fermion): + OGBENCH_IMPLS=ogbench_ref/impls .venv/bin/python ogbench_genq/diagnostics/diag_td_gap.py +""" +import json +import os +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, PKG) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +ENV = "puzzle-3x3-play-v0" +N_PAIRS = 256 +SEED = 0 +TRAIN_STEPS = 500000 + + +def main(): + import jax + import tqdm + from utils.datasets import Dataset, GCDataset + from utils.env_utils import make_env_and_datasets + import gciql as gciql_mod + from train_genq_jax import build_ends + + config = gciql_mod.get_config() + config["actor_loss"] = "ddpgbc" + config["alpha"] = 1.0 + config["expectile"] = 0.5 + env, train_dataset, _ = make_env_and_datasets(ENV, frame_stack=config["frame_stack"]) + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(train_dataset["terminals"]) + N = len(obs) + train_ds = GCDataset(Dataset.create(**train_dataset), config) + + ex = train_ds.sample(2) + agent = gciql_mod.GCIQLAgent.create(SEED, ex["observations"], ex["actions"], config) + print(f"[td-gap] training tau=0.5 GCIQL for {TRAIN_STEPS} steps ...", flush=True) + for i in tqdm.trange(1, TRAIN_STEPS + 1, smoothing=0.1, dynamic_ncols=True, mininterval=30): + agent, _ = agent.update(train_ds.sample(config["batch_size"])) + + # ---- identical anchors to diag_chain_depth.py (same seed, same rng call order) ---- + rng = np.random.default_rng(SEED) + t = rng.integers(0, N - 1, N_PAIRS) + span = np.maximum(end_of[t] - 1 - t, 1) + gi = np.clip(t + (rng.random(N_PAIRS) * span).astype(np.int64), 0, N - 1) + a_rand = rng.uniform(-1, 1, (N_PAIRS, act.shape[1])).astype(np.float32) + s0, a_data, g_far = obs[t], act[t], obs[gi] + # near goals: 20 steps downstream (the depth-1 horizon) + gi_near = np.minimum(t + 20, end_of[t] - 1) + g_near = obs[gi_near] + horiz = (gi - t) + + def td_q(s, a, g): + q = agent.network.select("critic")(s, g, actions=a) + q = np.asarray(q) + return q.min(axis=0) if q.ndim == 2 else q # ensemble min, matching the agent + + res = {} + for name, g in [("far_hindsight", g_far), ("near_20step", g_near)]: + qd = td_q(s0, a_data, g) + qr = td_q(s0, a_rand, g) + diff = qd - qr + res[name] = dict( + gap=float(diff.mean()), sem=float(diff.std() / np.sqrt(len(diff))), + p_data_wins=float((diff > 0).mean()), + q_mean=float(qd.mean()), q_std_across_anchors=float(qd.std()), + rel_gap=float(diff.mean() / (np.abs(qd).mean() + 1e-9)), + ) + print(f"[td-gap] {name:14s}: gap={diff.mean():+.4f} ± {diff.std()/np.sqrt(len(diff)):.4f} " + f"P(data wins)={(diff>0).mean():.3f} |Q| mean={np.abs(qd).mean():.3f} " + f"rel-gap={res[name]['rel_gap']:+.4f}", flush=True) + res["median_far_horizon_steps"] = int(np.median(horiz)) + out = os.path.join(PKG, "diagnostics", "td_gap.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_gciql_near.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_gciql_near.json new file mode 100644 index 0000000000000000000000000000000000000000..4b9fbf13bcfd2af10e549f58fb879805965e991c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_gciql_near.json @@ -0,0 +1,40 @@ +{ + "mode": "gciql_near", + "gaps": { + "near_20step": { + "gap": 17.74597930908203, + "sem": 1.1446067094802856, + "p_data_wins": 0.86328125, + "rel_gap": 0.7788953185081482, + "q_absmean": 22.783523559570312, + "corr_true_fp": 0.05036394823062235, + "spearman_true_fp": 0.008114700160219729 + }, + "far_hindsight": { + "gap": 3.151750087738037, + "sem": 0.7652956247329712, + "p_data_wins": 0.60546875, + "rel_gap": 0.033465299755334854, + "q_absmean": 94.17964172363281, + "corr_true_fp": 0.8933109903952903, + "spearman_true_fp": 0.7684166857404439 + }, + "random_goal": { + "gap": -1.4387223720550537, + "sem": 0.5873849987983704, + "p_data_wins": 0.46875, + "rel_gap": -0.011426885612308979, + "q_absmean": 125.90677642822266, + "corr_true_fp": 0.27395287298764703, + "spearman_true_fp": 0.03902924010070954 + } + }, + "success_rate": 0.8400000000000001, + "per_task": [ + 1.0, + 0.9, + 0.72, + 0.64, + 0.94 + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_gciql_random.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_gciql_random.json new file mode 100644 index 0000000000000000000000000000000000000000..dd11ef1a8b7aac91cd7ade6b41f72aa060b771a7 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_gciql_random.json @@ -0,0 +1,34 @@ +{ + "mode": "gciql_random", + "gaps": { + "near_20step": { + "gap": -5.960464477539063e-08, + "sem": 5.670156042469898e-07, + "p_data_wins": 0.3359375, + "rel_gap": -5.956245496818724e-10, + "q_absmean": 100.07083129882812 + }, + "far_hindsight": { + "gap": 2.9802322387695312e-08, + "sem": 5.289354589876893e-07, + "p_data_wins": 0.3515625, + "rel_gap": 2.978122748409362e-10, + "q_absmean": 100.07083129882812 + }, + "random_goal": { + "gap": -9.5367431640625e-07, + "sem": 5.462856051963172e-07, + "p_data_wins": 0.30859375, + "rel_gap": -9.529992794909958e-09, + "q_absmean": 100.07083129882812 + } + }, + "success_rate": 0.012, + "per_task": [ + 0.04, + 0.0, + 0.0, + 0.0, + 0.02 + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_default.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_default.json new file mode 100644 index 0000000000000000000000000000000000000000..ab65f340452d894af60cb92d3495c912208f2725 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_default.json @@ -0,0 +1,34 @@ +{ + "mode": "genq_default", + "gaps": { + "near_20step": { + "gap": 0.1018153503537178, + "sem": 0.00713178189471364, + "p_data_wins": 0.87890625, + "rel_gap": 0.28603076934814453, + "q_absmean": 0.355959415435791 + }, + "far_hindsight": { + "gap": 0.015866125002503395, + "sem": 0.0043139150366187096, + "p_data_wins": 0.57421875, + "rel_gap": 0.21344693005084991, + "q_absmean": 0.07433287799358368 + }, + "random_goal": { + "gap": 0.0003081397735513747, + "sem": 0.0007308213389478624, + "p_data_wins": 0.51171875, + "rel_gap": 0.023776467889547348, + "q_absmean": 0.012959862127900124 + } + }, + "success_rate": 0.11599999999999999, + "per_task": [ + 0.58, + 0.0, + 0.0, + 0.0, + 0.0 + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_near.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_near.json new file mode 100644 index 0000000000000000000000000000000000000000..95b18d6ad68c3a13d000ee90d5b533de4e8b7e27 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_near.json @@ -0,0 +1,40 @@ +{ + "mode": "genq_near", + "gaps": { + "near_20step": { + "gap": 0.10057753324508667, + "sem": 0.007165998220443726, + "p_data_wins": 0.875, + "rel_gap": 0.27819153666496277, + "q_absmean": 0.3615405857563019, + "corr_true_fp": 0.8365843268821046, + "spearman_true_fp": 0.8501781013962004 + }, + "far_hindsight": { + "gap": 0.015718702226877213, + "sem": 0.004309632815420628, + "p_data_wins": 0.58203125, + "rel_gap": 0.20187638700008392, + "q_absmean": 0.07786300778388977, + "corr_true_fp": 0.6768743448942838, + "spearman_true_fp": 0.5804581998168916 + }, + "random_goal": { + "gap": -0.00017551099881529808, + "sem": 0.000763835443649441, + "p_data_wins": 0.51171875, + "rel_gap": -0.010755632072687149, + "q_absmean": 0.016318053007125854, + "corr_true_fp": 0.453783485429274, + "spearman_true_fp": 0.13610165369649804 + } + }, + "success_rate": 0.076, + "per_task": [ + 0.36, + 0.0, + 0.0, + 0.0, + 0.02 + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_near_ddpg.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_near_ddpg.json new file mode 100644 index 0000000000000000000000000000000000000000..43d25bf689f0f9d3328f7d2453d333e64c133732 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_genq_near_ddpg.json @@ -0,0 +1,40 @@ +{ + "mode": "genq_near_ddpg", + "gaps": { + "near_20step": { + "gap": 0.10463771224021912, + "sem": 0.007371374871581793, + "p_data_wins": 0.8671875, + "rel_gap": 0.28597819805145264, + "q_absmean": 0.36589401960372925, + "corr_true_fp": 0.838145093681329, + "spearman_true_fp": 0.849103770885786 + }, + "far_hindsight": { + "gap": 0.01705823838710785, + "sem": 0.0044959005899727345, + "p_data_wins": 0.6015625, + "rel_gap": 0.22078947722911835, + "q_absmean": 0.07726019620895386, + "corr_true_fp": 0.6839756505360262, + "spearman_true_fp": 0.580797236209659 + }, + "random_goal": { + "gap": -6.1284517869353294e-06, + "sem": 0.0007737400592304766, + "p_data_wins": 0.484375, + "rel_gap": -0.00042914392543025315, + "q_absmean": 0.014280643314123154, + "corr_true_fp": 0.4721562270875672, + "spearman_true_fp": 0.11133053902494848 + } + }, + "success_rate": 0.052000000000000005, + "per_task": [ + 0.26, + 0.0, + 0.0, + 0.0, + 0.0 + ] +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_mc.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_mc.json new file mode 100644 index 0000000000000000000000000000000000000000..6e6b45caec5ec1e81816c676b1eb347a3c38e319 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/gap_source_mc.json @@ -0,0 +1,26 @@ +{ + "mode": "mc", + "gaps": { + "near_20step": { + "gap": 0.08888839185237885, + "sem": 0.008396120741963387, + "p_data_wins": 0.6875, + "rel_gap": 0.09555656462907791, + "q_absmean": 0.9302175641059875 + }, + "far_hindsight": { + "gap": 0.020211797207593918, + "sem": 0.006051748525351286, + "p_data_wins": 0.56640625, + "rel_gap": 0.059731077402830124, + "q_absmean": 0.3383799195289612 + }, + "random_goal": { + "gap": -0.008473950438201427, + "sem": 0.0042031933553516865, + "p_data_wins": 0.4296875, + "rel_gap": -0.09388046711683273, + "q_absmean": 0.09026318788528442 + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/goal_coverage.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/goal_coverage.json new file mode 100644 index 0000000000000000000000000000000000000000..d4d23d864e11e34cf0f3f9850888d7f582526747 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/goal_coverage.json @@ -0,0 +1,52 @@ +{ + "pointmaze-medium-navigate-v0": { + "hindsight": { + "support_frac": 0.99815, + "q_td_mean": 0.40692715548922226, + "q_td_mean_on_support": 0.4076813660163525, + "q_occ_mean": 0.09857561139007127, + "min_dist_median": 0.0 + }, + "random": { + "support_frac": 0.35015, + "q_td_mean": 0.0905067595157471, + "q_td_mean_on_support": 0.2584799643459863, + "q_occ_mean": 0.005194040598586024, + "min_dist_median": 1.4070466756820679 + } + }, + "cube-single-play-v0": { + "hindsight": { + "support_frac": 0.99815, + "q_td_mean": 0.380735338121669, + "q_td_mean_on_support": 0.3814410039790302, + "q_occ_mean": 0.10843838813647512, + "min_dist_median": 0.0 + }, + "random": { + "support_frac": 0.22065, + "q_td_mean": 0.05844488105225364, + "q_td_mean_on_support": 0.26487596216747633, + "q_occ_mean": 0.012699477470875596, + "min_dist_median": 0.7638753354549408 + } + }, + "puzzle-3x3-play-v0": { + "hindsight": { + "support_frac": 0.9981, + "q_td_mean": 0.3513170113443988, + "q_td_mean_on_support": 0.3519857843346346, + "q_occ_mean": 0.09564193148668776, + "min_dist_median": 0.0 + }, + "random": { + "support_frac": 0.02875, + "q_td_mean": 0.0068852847236611356, + "q_td_mean_on_support": 0.23948816430125694, + "q_occ_mean": 0.0017720229204181799, + "min_dist_median": 2.0 + }, + "distinct_configs_visited": 512, + "config_space_size": 512 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/midpoint_competence.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/midpoint_competence.json new file mode 100644 index 0000000000000000000000000000000000000000..ce61ad513dbcd91806b2bc0b61fa9a948a50cca6 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/midpoint_competence.json @@ -0,0 +1,104 @@ +{ + "bc": { + "1": { + "gap": 0.0011071867118163405, + "sem": 0.033695512885529286, + "q": 0.1261391515669139, + "rel": 0.008777502379596245, + "nnz": 0.4583333333333333, + "n": 48 + }, + "2": { + "gap": -0.0026814910932196068, + "sem": 0.003503124704958924, + "q": 0.001723325081078507, + "rel": -1.555997511243753, + "nnz": 0.041666666666666664, + "n": 48 + }, + "3": { + "gap": -0.0015676204582237825, + "sem": 0.003277620203053034, + "q": 0.0020601649434409943, + "rel": -0.7609195090398703, + "nnz": 0.041666666666666664, + "n": 48 + }, + "5": { + "gap": 0.0, + "sem": 0.0, + "q": 0.0, + "rel": 0.0, + "nnz": 0.0, + "n": 48 + } + }, + "semi": { + "1": { + "gap": 0.01625443413362129, + "sem": 0.0023363827311480277, + "q": 0.8933314055769298, + "rel": 0.018195301333807444, + "nnz": 1.0, + "n": 48 + }, + "2": { + "gap": 0.013777998066292804, + "sem": 0.0042093563817764005, + "q": 0.7821252931586868, + "rel": 0.017616100859023442, + "nnz": 1.0, + "n": 48 + }, + "3": { + "gap": 0.0011599428374778169, + "sem": 0.007620905246735323, + "q": 0.6831080019578053, + "rel": 0.00169803725392669, + "nnz": 1.0, + "n": 48 + }, + "5": { + "gap": 0.007067086901181325, + "sem": 0.006419519403677684, + "q": 0.5302007575014235, + "rel": 0.013329077312442872, + "nnz": 1.0, + "n": 48 + } + }, + "competent": { + "1": { + "gap": 0.019162883488216518, + "sem": 0.007831260942945178, + "q": 0.9165995726989321, + "rel": 0.02090649400030246, + "nnz": 1.0, + "n": 48 + }, + "2": { + "gap": 0.011349562331024245, + "sem": 0.002214188228266863, + "q": 0.8248198854552368, + "rel": 0.013760049336104592, + "nnz": 1.0, + "n": 48 + }, + "3": { + "gap": 0.017087124756492753, + "sem": 0.004290845361390138, + "q": 0.7469817708545294, + "rel": 0.02287488851845822, + "nnz": 1.0, + "n": 48 + }, + "5": { + "gap": 0.0038964961816657187, + "sem": 0.010837048303894807, + "q": 0.6047256630663219, + "rel": 0.006443411307310383, + "nnz": 1.0, + "n": 48 + } + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/oracle_q.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/oracle_q.json new file mode 100644 index 0000000000000000000000000000000000000000..5bd9ced261d6d26c6aa8066cb4c752d137e8ba2c --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/oracle_q.json @@ -0,0 +1,31 @@ +{ + "bc_loss": 0.01898938976228237, + "gaps": { + "near_30step": { + "gap": 0.09349559930807029, + "sem": 0.036759637774952406, + "p_pol_wins": 0.46875, + "q_mean": 0.25370721833969734, + "nnz_frac": 0.859375, + "rel_gap": 0.368517693550083 + }, + "far_taskgoal": { + "gap": -0.00045767526429993697, + "sem": 0.0004540855989612717, + "p_pol_wins": 0.0, + "q_mean": 0.0, + "nnz_frac": 0.015625, + "rel_gap": -457675.26429993694 + }, + "random_goal": { + "gap": -0.0011815652122912504, + "sem": 0.0015200765219517103, + "p_pol_wins": 0.015625, + "q_mean": 0.0007337484675885442, + "nnz_frac": 0.0625, + "rel_gap": -1.6103115088784261 + } + }, + "sr_bc": 0.0, + "sr_oracle_argmax": 0.0 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/ordering_content.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/ordering_content.json new file mode 100644 index 0000000000000000000000000000000000000000..c4b76b88b831aedcf672ed8cd8e1b07c3545a8bd --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/ordering_content.json @@ -0,0 +1,20 @@ +{ + "far_task": { + "n": 228, + "rank_agreement_td_genq": -0.0502063983488132, + "td_vs_progress": -0.04992260061919503, + "genq_vs_progress": 0.36791795665634675, + "td_top1_progress": 0.4310974510371918, + "genq_top1_progress": 0.6989662502845098, + "best_possible_progress": 0.9357589905385991 + }, + "near_20step": { + "n": 156, + "rank_agreement_td_genq": 0.6777337858220212, + "td_vs_progress": 0.42549019607843136, + "genq_vs_progress": 0.5829185520361991, + "td_top1_progress": 0.7842470294445284, + "genq_top1_progress": 0.8293490378204442, + "best_possible_progress": 0.9439738238865709 + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/pi_loop.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/pi_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..f768156515cb22039691fed648b221c56cfb5580 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/pi_loop.py @@ -0,0 +1,723 @@ +"""#57: Gen-Q POLICY ITERATION on puzzle-3x3 — the repo's own closing-the-loop story, +run for real. No TD anywhere: each round = MLE occupancy fit + sampled read-out + one +AWR extraction; env interaction is data COLLECTION by a fixed policy (PI's defining +move), not bootstrapping. + +Round 0 (known): behavior occupancy -> Q^beta == 0 at far goals (oracle-proven) -> +best extraction pi_1 ~ 0.12-0.19. +Round 1 (this script): roll pi_1 -> re-fit the occupancy on its data -> Q^{pi_1} +should lift off zero at far goals (midpoint-competence probe predicts ~pi_1's reach +rate, state-informative) -> extract pi_2 -> eval. Iterate if SR(pi_2) > SR(pi_1). + +Stages (run in order; state shared in diagnostics/pi_state/): + train_pi1 train the campaign-best Gen-Q extraction (AWR alpha=300, sigma=2.0, + n_occ=64) on the ORIGINAL data + behavior occupancy; SAVE agent params; + quick SR eval. [GPU, ~3.5h] + collect roll pi_1 in the env: episodes conditioned on task goals (50%) and + random dataset-state goals (50%); save trajectories. [CPU/GPU, ~1h] + refit train occupancies on ORIGINAL+COLLECTED union: bits-target gamma=0.99 + (for extraction) and full-state gamma=0.99 (for probes). [GPU, ~40min] + probe far-goal Q of the refit occupancy on the standard anchors vs round-0 + (0.0000); action gaps; per-press-distance monotonicity. GO/NO-GO. + extract_pi2 gciql_genq-style AWR on the union data + refit occupancy; save params; + SR eval; compare to pi_1. [GPU, ~4h] + +Run: OGBENCH_IMPLS=... python pi_loop.py --stage +""" +import argparse +import json +import os +import pickle +import sys + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, PKG) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +ENV = "puzzle-3x3-play-v0" +SEED = 0 +STATE = os.path.join(PKG, "diagnostics", "pi_state") +os.makedirs(STATE, exist_ok=True) +BITS_CKPT0 = os.path.join(PKG, "checkpoints", "m9_genq_puzzle_3x3_play_v0.genqjax.npz") + + +def load_data(): + from utils.env_utils import make_env_and_datasets + env, train_dataset, _ = make_env_and_datasets(ENV, frame_stack=None) + return env, train_dataset + + +def union_dataset(train_dataset): + """original + collected transitions, GCDataset-compatible dict.""" + coll = np.load(os.path.join(STATE, "collected.npz")) + out = {} + for k in ["observations", "actions", "terminals"]: + out[k] = np.concatenate([np.asarray(train_dataset[k]), coll[k]], axis=0) + print(f"[pi] union dataset: {len(out['observations'])} transitions " + f"({len(coll['observations'])} collected)", flush=True) + return out + + +def train_genq_agent(train_dict, genq_npz, steps, out_pkl, eval_env=None, eval_eps=10): + """gciql_genq-style training (AWR alpha=300 sigma=2.0 n64) with param saving.""" + import jax + import jax.numpy as jnp + import tqdm + import flax + from utils.datasets import Dataset, GCDataset + from genq_jax import load_genq_params, genq_q as genq_q_jax + from gciql_genq import GCIQLGenQAgent, get_config + import target_extractors + + config = get_config() + config["actor_loss"] = "awr" + config["alpha"] = 300.0 + config["expectile"] = 0.9 + P, meta = load_genq_params(genq_npz) + gq = jax.jit(lambda s, aa, g, k: genq_q_jax(P, meta, s, aa, g, k, n_occ=64, sigma=2.0)) + gkey = [jax.random.PRNGKey(SEED + 999)] + + def to_tgt(gobs): + return target_extractors.extract_target(ENV, gobs).astype(np.float32) + + def gq_batch(o, go, aa): + gkey[0], sub = jax.random.split(gkey[0]) + return np.asarray(gq(jnp.asarray(o), jnp.asarray(np.clip(aa, -1, 1)), + jnp.asarray(to_tgt(go)), sub)) + + ds = GCDataset(Dataset.create(**train_dict), config) + ex = ds.sample(2) + agent = GCIQLGenQAgent.create(SEED, ex["observations"], ex["actions"], config) + print(f"[pi] training agent {steps} steps (awr a=300 sigma=2 n64) on " + f"{len(train_dict['observations'])} transitions", flush=True) + for i in tqdm.trange(1, steps + 1, mininterval=30, dynamic_ncols=True): + batch = ds.sample(config["batch_size"]) + batch["genq_q_value"] = gq_batch(batch["observations"], batch["value_goals"], + batch["actions"]) + agent, _ = agent.update(batch) + with open(out_pkl, "wb") as f: + pickle.dump({"params": flax.serialization.to_bytes(agent.network), + "config": dict(config)}, f) + print(f"[pi] saved agent -> {out_pkl}", flush=True) + sr = None + if eval_env is not None: + sr, per = eval_agent(agent, eval_env, config, eval_eps) + print(f"[pi] SR = {sr:.3f} per-task {per}", flush=True) + return agent, config, sr + + +def eval_agent(agent, env, config, n_ep): + import jax + from utils.evaluation import evaluate + task_infos = env.unwrapped.task_infos if hasattr(env.unwrapped, "task_infos") else env.task_infos + eag = jax.device_put(agent, device=jax.devices("cpu")[0]) + per = [] + for tid in range(1, len(task_infos) + 1): + ei, _, _ = evaluate(agent=eag, env=env, task_id=tid, config=config, + num_eval_episodes=n_ep, num_video_episodes=0, + video_frame_skip=3, eval_temperature=0.0, eval_gaussian=None) + per.append(float(ei.get("success", 0.0))) + return float(np.mean(per)), per + + +def load_agent(pkl_path, train_dict): + import flax + from utils.datasets import Dataset, GCDataset + from gciql_genq import GCIQLGenQAgent + import ml_collections + with open(pkl_path, "rb") as f: + blob = pickle.load(f) + config = ml_collections.ConfigDict(blob["config"]) + ds = GCDataset(Dataset.create(**{k: np.asarray(v) for k, v in train_dict.items() + if k in ["observations", "actions", "terminals"]}), config) + ex = ds.sample(2) + agent = GCIQLGenQAgent.create(SEED, ex["observations"], ex["actions"], config) + network = flax.serialization.from_bytes(agent.network, blob["params"]) + agent = agent.replace(network=network) + return agent, config + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--stage", required=True, + choices=["train_pi1", "collect", "refit", "probe", "extract_pi2", + "offline_probe", "offline_extract", "wm_round"]) + ap.add_argument("--betas", default="0.5,0.8,0.95") + ap.add_argument("--extract_beta", type=float, default=0.5) + ap.add_argument("--n_buffer", type=int, default=200000) + ap.add_argument("--probe_task", type=int, default=0, help="restrict offline_probe goals to this task id (0=round-robin)") + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--episodes", type=int, default=1500) + ap.add_argument("--occ_steps", type=int, default=600000) + a = ap.parse_args() + env, train_dataset = load_data() + + if a.stage == "train_pi1": + train_genq_agent({k: np.asarray(train_dataset[k]) for k in + ["observations", "actions", "terminals"]}, + BITS_CKPT0, a.train_steps, + os.path.join(STATE, "pi1_agent.pkl"), eval_env=env) + + elif a.stage == "collect": + import jax + agent, config = load_agent(os.path.join(STATE, "pi1_agent.pkl"), train_dataset) + obs_d = np.asarray(train_dataset["observations"], dtype=np.float32) + rng = np.random.default_rng(SEED + 1) + O, A, T = [], [], [] + succ = [] + for ep in range(a.episodes): + tid = int(rng.integers(1, 6)) + ob, info = env.reset(options=dict(task_id=tid)) + if rng.random() < 0.5: + gob = np.asarray(info["goal"], dtype=np.float32) + else: + gob = obs_d[rng.integers(0, len(obs_d))] + s_ep = 0.0 + for t in range(500): + aa = np.asarray(agent.sample_actions(observations=np.asarray(ob, dtype=np.float32), + goals=gob, temperature=1.0, + seed=jax.random.PRNGKey(rng.integers(1 << 31)))) + aa = np.clip(aa, -1, 1) + O.append(np.asarray(ob, dtype=np.float32)) + A.append(aa.astype(np.float32)) + T.append(0.0) + ob, _, _, _, info = env.step(aa) + s_ep = max(s_ep, float(info.get("success", 0.0))) + T[-1] = 1.0 + succ.append(s_ep) + if (ep + 1) % 100 == 0: + print(f"[pi] collected {ep+1}/{a.episodes} episodes " + f"(running success {np.mean(succ):.3f})", flush=True) + np.savez(os.path.join(STATE, "collected.npz"), + observations=np.asarray(O), actions=np.asarray(A), + terminals=np.asarray(T, dtype=np.float32)) + print(f"[pi] collection success rate: {np.mean(succ):.3f}", flush=True) + + elif a.stage == "refit": + import subprocess + union = union_dataset(train_dataset) + np.savez(os.path.join(STATE, "union.npz"), **union) + # train two occupancies on the union via train_genq_jax with a dataset override: + # simplest robust path — temporary loader shim not needed; train inline here. + sys.argv = ["x"] + from train_genq_jax import (build_ends, future_idx, sample_goal_after, cosine_abar, + make_model, flax_params_to_npz_arrays) + import jax, jax.numpy as jnp, optax, tqdm + import target_extractors + obs = union["observations"].astype(np.float32) + act = np.clip(union["actions"].astype(np.float32), -1, 1) + end_of = build_ends(union["terminals"]) + N = len(obs) + for tag, full_state in [("bits", False), ("full", True)]: + if full_state: + s = obs + tgt = obs + goal_in = lambda g_obs: g_obs.astype(np.float32) + else: + s = obs + tgt = target_extractors.extract_target(ENV, obs).astype(np.float32) + goal_in = lambda g_obs: target_extractors.extract_target(ENV, g_obs).astype(np.float32) + y_dim = tgt.shape[1] + cond_dim = s.shape[1] + act.shape[1] + y_dim + rng_np = np.random.default_rng(SEED) + + def make_cond(t, j): + gi = sample_goal_after(j, end_of, rng_np) + return np.concatenate([s[t], act[t], goal_in(obs[gi])], 1).astype(np.float32) + + t0 = rng_np.integers(0, N, 20000) + j0 = future_idx(t0, end_of, 0.99, rng_np) + c0, y0 = make_cond(t0, j0), tgt[j0] + cm, cs = c0.mean(0), c0.std(0) + 1e-6 + ym, ys = y0.mean(0), y0.std(0) + 1e-6 + abar = cosine_abar(100) + model = make_model(cond_dim, y_dim, 256, 3, 64) + key = jax.random.PRNGKey(SEED) + params = model.init(key, jnp.zeros((1, y_dim)), jnp.zeros((1,)), jnp.zeros((1, cond_dim))) + tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(3e-4)) + ost = tx.init(params) + abar_j, cmj, csj, ymj, ysj = map(jnp.asarray, (abar, cm, cs, ym, ys)) + + def loss_fn(p, c, y, ti, nz): + cn = (c - cmj) / csj + x0 = (y - ymj) / ysj + ab = abar_j[ti - 1][:, None] + xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1 - ab) * nz + pred = model.apply(p, xt, ti.astype(jnp.float32) / 100, cn) + return jnp.mean((pred - nz) ** 2) + + @jax.jit + def upd(p, o, c, y, ti, nz): + l, g = jax.value_and_grad(loss_fn)(p, c, y, ti, nz) + u, o = tx.update(g, o, p) + return optax.apply_updates(p, u), o, l + + print(f"[pi] refit occupancy ({tag}) {a.occ_steps} steps on union", flush=True) + for i in tqdm.trange(1, a.occ_steps + 1, mininterval=30, dynamic_ncols=True): + t = rng_np.integers(0, N, 256) + j = future_idx(t, end_of, 0.99, rng_np) + c = make_cond(t, j) + y = tgt[j] + ti = rng_np.integers(1, 101, 256).astype(np.int32) + nz = rng_np.standard_normal((256, y_dim)).astype(np.float32) + params, ost, l = upd(params, ost, jnp.asarray(c), jnp.asarray(y), + jnp.asarray(ti), jnp.asarray(nz)) + arrs, nl = flax_params_to_npz_arrays(params) + arrs.update(dict(abar=abar, abar_prev=np.concatenate([np.ones(1, np.float32), abar[:-1]]), + cond_mean=cm.astype(np.float32), cond_std=cs.astype(np.float32), + y_mean=ym.astype(np.float32), y_std=ys.astype(np.float32))) + meta = dict(meta_cond_dim=np.asarray(cond_dim), meta_y_dim=np.asarray(y_dim), + meta_num_layers=np.asarray(nl), meta_diffusion_T=np.asarray(100), + meta_sample_steps=np.asarray(30)) + out = os.path.join(STATE, f"occ_pi1_{tag}.genqjax.npz") + np.savez(out, **arrs, **meta) + print(f"[pi] saved {out} (final loss {float(l):.4f})", flush=True) + + elif a.stage == "probe": + import jax, jax.numpy as jnp + from genq_jax import load_genq_params, sample as occ_sample + from train_genq_jax import build_ends + import target_extractors, ogbench + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(train_dataset["terminals"]) + bit_idx = target_extractors.extract_target( + ENV, np.arange(obs.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + rng = np.random.default_rng(SEED) + t = rng.integers(0, len(obs) - 1, 256) + a_rand = rng.uniform(-1, 1, (256, act.shape[1])).astype(np.float32) + e2 = ogbench.make_env_and_datasets(ENV, env_only=True) + tg = [] + for tid in range(1, 6): + _, info = e2.reset(options=dict(task_id=tid)) + tg.append(np.asarray(info["goal"], dtype=np.float32)) + g_task = np.asarray([tg[i % 5] for i in range(256)]) + res = {} + for name, ckpt, is_full in [("round0_full", os.path.join( + PKG, "checkpoints", "m9_genq_rec_full_puzzle_3x3_play_v0_b0998.genqjax.npz"), True), + ("round1_full", os.path.join(STATE, "occ_pi1_full.genqjax.npz"), True)]: + if not os.path.exists(ckpt): + print(f"[pi] probe skip {name} (missing {ckpt})", flush=True) + continue + P, meta = load_genq_params(ckpt) + sig = np.full(meta["y_dim"], 1e6, dtype=np.float32) + sig[bit_idx] = 0.5 + + @jax.jit + def qf(s, aa, g, k, P=P, meta=meta, sig=jnp.asarray(sig)): + c = jnp.concatenate([s, aa, g], -1) + x = occ_sample(P, meta, c, 128, k, steps=10) + d2 = jnp.sum(((x - g[:, None, :]) / sig) ** 2, -1) + return jnp.exp(-0.5 * d2).mean(1) + + key = jax.random.PRNGKey(SEED) + key, k1 = jax.random.split(key) + qd = np.asarray(qf(jnp.asarray(obs[t]), jnp.asarray(act[t]), jnp.asarray(g_task), k1)) + key, k2 = jax.random.split(key) + qr = np.asarray(qf(jnp.asarray(obs[t]), jnp.asarray(a_rand), jnp.asarray(g_task), k2)) + res[name] = dict(q_mean=float(qd.mean()), q_nnz=float(np.mean(qd > 1e-3)), + gap=float((qd - qr).mean()), + sem=float((qd - qr).std() / 16)) + r = res[name] + print(f"[pi] {name}: far-task Q={r['q_mean']:.4f} nnz={r['q_nnz']:.2f} " + f"gap={r['gap']:+.4f}±{r['sem']:.4f}", flush=True) + json.dump(res, open(os.path.join(STATE, "probe.json"), "w"), indent=2) + + elif a.stage == "offline_probe": + # STRICT-OFFLINE round-1 go/no-go: composed Q^{pi_1} via the low-beta chain + # (pi_1 steers every hop's first tick; beta->small => mostly-pi_1 rollouts, + # spliced across trajectories, zero env interaction). Controls: same chain + # with the behavior (BC) midpoint actor isolates the pi_1 effect per beta. + import jax, jax.numpy as jnp + from genq_jax import load_genq_params + from genq_recursive_jax import genq_q_recursive, stop_prob, fit_midpoint_actor + from train_genq_jax import build_ends + import target_extractors, ogbench, math + agent, aconfig = load_agent(os.path.join(STATE, "pi1_agent.pkl"), train_dataset) + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(train_dataset["terminals"]) + bit_idx = target_extractors.extract_target( + ENV, np.arange(obs.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + sig = np.full(obs.shape[1], 1e6, dtype=np.float32) + sig[bit_idx] = 0.5 + bc_fn, _ = fit_midpoint_actor(obs, act, end_of, goal_of=lambda gi: obs[gi], + steps=30000, seed=SEED, log_every=0) + + def pi1_fn(z, g): + dist = agent.network.select("actor")(z, g) + return jnp.clip(dist.mode(), -1, 1) + + rng = np.random.default_rng(SEED) + t = rng.integers(0, len(obs) - 1, 128) + a_rand = rng.uniform(-1, 1, (128, act.shape[1])).astype(np.float32) + e2 = ogbench.make_env_and_datasets(ENV, env_only=True) + tg = [] + for tid in range(1, 6): + _, info = e2.reset(options=dict(task_id=tid)) + tg.append(np.asarray(info["goal"], dtype=np.float32)) + g_task = np.asarray([tg[(a.probe_task - 1) if a.probe_task else (i % 5)] for i in range(128)]) + res = {} + key = jax.random.PRNGKey(SEED) + for b in [float(x) for x in a.betas.split(",")]: + tagb = f"b{str(b).replace('.', '')}" + ck = os.path.join(PKG, "checkpoints", + f"m9_genq_rec_full_puzzle_3x3_play_v0_{tagb}.genqjax.npz") + if not os.path.exists(ck): + print(f"[pi] offline_probe skip beta={b} (missing {ck})", flush=True) + continue + P, meta = load_genq_params(ck) + md = int(math.ceil(3.0 / stop_prob(b, 0.99))) + for aname, afn in [("pi1", pi1_fn), ("bc", bc_fn)]: + qfn = jax.jit(lambda s_, aa_, g_, k_, P=P, meta=meta, b=b, md=md, afn=afn: + genq_q_recursive(P, meta, s_, aa_, g_, k_, afn, n_occ=32, + beta=b, gamma=0.99, max_depth=md, + sigma=jnp.asarray(sig), steps=10)) + key, k1 = jax.random.split(key) + qd = np.asarray(qfn(jnp.asarray(obs[t]), jnp.asarray(act[t]), + jnp.asarray(g_task), k1)) + key, k2 = jax.random.split(key) + qr = np.asarray(qfn(jnp.asarray(obs[t]), jnp.asarray(a_rand), + jnp.asarray(g_task), k2)) + r = dict(q_mean=float(qd.mean()), q_nnz=float(np.mean(qd > 1e-3)), + gap=float((qd - qr).mean()), + sem=float((qd - qr).std() / np.sqrt(len(qd)))) + res[f"beta{b}_{aname}"] = r + print(f"[pi] beta={b} mid={aname:3s} maxD={md:3d}: far-task Q={r['q_mean']:.4f} " + f"nnz={r['q_nnz']:.2f} gap={r['gap']:+.4f}±{r['sem']:.4f}", flush=True) + json.dump(res, open(os.path.join(STATE, "offline_probe.json"), "w"), indent=2) + + elif a.stage == "wm_round": + # Dyna-style offline round: (1) train one-step dynamics p(s'|s,a) supervised on + # the data; (2) imagine pi_1 rollouts (pi_1 picks EVERY tick); (3) fit the + # full-state gamma=0.99 occupancy on imagined data; (4) probe far-task Q vs a + # BC-imagination control. No TD; no env interaction. + import jax, jax.numpy as jnp + import tqdm, flax, optax + import flax.linen as fnn + from genq_recursive_jax import fit_midpoint_actor + from train_genq_jax import (build_ends, future_idx, sample_goal_after, cosine_abar, + make_model, flax_params_to_npz_arrays) + from genq_jax import load_genq_params, sample as occ_sample + import target_extractors, ogbench + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(train_dataset["terminals"]) + N, D = obs.shape + bit_idx = target_extractors.extract_target( + ENV, np.arange(D, dtype=np.float32)[None])[0].astype(np.int64) + agent1, _ = load_agent(os.path.join(STATE, "pi1_agent.pkl"), train_dataset) + bc_fn, _ = fit_midpoint_actor(obs, act, end_of, goal_of=lambda gi: obs[gi], + steps=30000, seed=SEED, log_every=0) + + # ---- (1) HYBRID one-step dynamics ---- + # continuous dims (everything except the 9 bit dims): MLP normalized-delta; + # bits: per-tick 10-way flip classifier (no-press or one of the 9 flip patterns + # OBSERVED in the data), applied discretely => bits stay binary by construction. + mu, sd = obs.mean(0), obs.std(0) + 1e-6 + lo = jnp.asarray(obs.min(0) - 0.5 * sd) + hi = jnp.asarray(obs.max(0) + 0.5 * sd) + cont_idx = np.array([i for i in range(D) if i not in set(bit_idx.tolist())], dtype=np.int64) + Dc = len(cont_idx) + # data-observed flip patterns (bits XOR at change ticks) + bits_all = np.round(obs[:, bit_idx]).astype(np.int8) + POW9 = 2 ** np.arange(9) + codes = bits_all @ POW9 + okmask = np.asarray(train_dataset["terminals"])[:-1] == 0 + chg = np.where(okmask & (codes[:-1] != codes[1:]))[0] + pats, counts = np.unique((bits_all[chg] ^ bits_all[chg + 1]), axis=0, return_counts=True) + pats = pats[np.argsort(-counts)][:9] + print(f"[pi] observed flip patterns: {len(pats)}", flush=True) + pat_code = {int(p_ @ POW9): k for k, p_ in enumerate(pats)} + flip_lab = np.zeros(len(obs) - 1, dtype=np.int64) # 0 = no flip, 1..9 = pattern + for i in chg: + c = int((bits_all[i] ^ bits_all[i + 1]) @ POW9) + flip_lab[i] = pat_code.get(c, 0) + 1 if c in pat_code else 0 + pats_j = jnp.asarray(np.concatenate([np.zeros((1, 9), np.int8), pats], 0)) # [10, 9] + + class Dyn(fnn.Module): + @fnn.compact + def __call__(self, s, aa): + h = jnp.concatenate([(s - mu) / sd, aa], -1) + for _ in range(4): + h = fnn.gelu(fnn.Dense(1024)(h)) + return fnn.Dense(Dc)(h), fnn.Dense(10)(h) # cont delta (normed), flip logits + + dyn = Dyn() + dparams = dyn.init(jax.random.PRNGKey(SEED + 21), jnp.zeros((1, D)), jnp.zeros((1, act.shape[1]))) + dtx = optax.adam(3e-4) + dopt = dtx.init(dparams) + sd_c = jnp.asarray(sd[cont_idx]) + ci_j = jnp.asarray(cont_idx) + bi_j = jnp.asarray(bit_idx) + + @jax.jit + def dyn_update(pp, oo, s, aa, sn, fl): + def loss(pp): + dpred, logits = dyn.apply(pp, s, aa) + lc = jnp.mean((dpred - (sn[:, ci_j] - s[:, ci_j]) / sd_c) ** 2) + # UNWEIGHTED CE: sampled-from probabilities must stay calibrated + # (class weighting inflates imagined press rates ~25x; wm_round3). + lf = jnp.mean(optax.softmax_cross_entropy_with_integer_labels(logits, fl)) + return lc + lf + l, g = jax.value_and_grad(loss)(pp) + u, oo = dtx.update(g, oo, pp) + return optax.apply_updates(pp, u), oo, l + + ok = np.where(okmask)[0] + rng = np.random.default_rng(SEED) + print(f"[pi] training hybrid dynamics ({a.occ_steps//3} steps)", flush=True) + for i in tqdm.trange(1, a.occ_steps // 3 + 1, mininterval=30, dynamic_ncols=True): + b = rng.choice(ok, 512) + dparams, dopt, dl = dyn_update(dparams, dopt, jnp.asarray(obs[b]), + jnp.asarray(act[b]), jnp.asarray(obs[b + 1]), + jnp.asarray(flip_lab[b])) + print(f"[pi] dynamics loss {float(dl):.5f}", flush=True) + # one-step + multi-step calibration + b = rng.choice(ok, 2000) + dpred, logits = dyn.apply(dparams, jnp.asarray(obs[b]), jnp.asarray(act[b])) + pred_c = np.asarray(dpred) * np.asarray(sd_c) + obs[b][:, cont_idx] + err1 = float(np.mean(np.abs(pred_c - obs[b + 1][:, cont_idx]) / sd[cont_idx][None])) + fl_pred = np.asarray(jnp.argmax(logits, -1)) + fl_true = flip_lab[b] + press_recall = float(np.mean(fl_pred[fl_true > 0] == fl_true[fl_true > 0])) if (fl_true > 0).any() else float("nan") + print(f"[pi] one-step cont L1: {err1:.4f}; flip acc(all)={np.mean(fl_pred == fl_true):.3f} " + f"press-recall={press_recall:.3f}", flush=True) + + # ---- (2) imagination + (3) occupancy fit on imagined data, per policy ---- + e2 = ogbench.make_env_and_datasets(ENV, env_only=True) + tg = [] + for tid in range(1, 6): + _, info = e2.reset(options=dict(task_id=tid)) + tg.append(np.asarray(info["goal"], dtype=np.float32)) + res = {} + for pname in ["pi1", "bc"]: + if pname == "pi1": + def pol(z, g): + return jnp.clip(agent1.network.select("actor")(z, g).mode(), -1, 1) + else: + pol = bc_fn + + @jax.jit + def imagine_step(z, g, k): + aa = pol(z, g) + k1, k2 = jax.random.split(k) + aa = jnp.clip(aa + 0.1 * jax.random.normal(k1, aa.shape), -1, 1) + dpred, logits = dyn.apply(dparams, z, aa) + zc = z.at[:, ci_j].add(dpred * sd_c) + fl = jax.random.categorical(k2, logits, axis=-1) # sampled flip event + new_bits = jnp.mod(jnp.round(z[:, bi_j]).astype(jnp.int32) + pats_j[fl], 2) + zn = zc.at[:, bi_j].set(new_bits.astype(jnp.float32)) + zn = jnp.clip(zn, lo, hi) + zn = jnp.where(jnp.isfinite(zn), zn, z) + return zn, aa + + M = 2000 + T_im = 400 + starts = obs[rng.integers(0, N, M)] + gsel = np.where(rng.random(M) < 0.5, + rng.integers(0, 5, M), -1) + goals = np.asarray([tg[g] if g >= 0 else obs[rng.integers(0, N)] for g in gsel], + dtype=np.float32) + z = jnp.asarray(starts) + gj = jnp.asarray(goals) + IO, IA = [], [] + key = jax.random.PRNGKey(SEED + 5) + print(f"[pi] imagining {M}x{T_im} ticks under {pname}", flush=True) + for t in range(T_im): + key, ks = jax.random.split(key) + zn, aa = imagine_step(z, gj, ks) + IO.append(np.asarray(z)) + IA.append(np.asarray(aa)) + z = zn + # drift instrumentation: fraction of clamped dims at the final tick + zf = np.asarray(z) + clamp_frac = float(np.mean((zf <= np.asarray(lo) + 1e-6) | (zf >= np.asarray(hi) - 1e-6))) + ib0 = np.round(starts[:, bit_idx]).astype(np.int8) + ibT = np.round(np.stack(IO, 1)[:, :, bit_idx]).astype(np.int8) + n_press = float(np.mean(np.sum(np.any(ibT[:, 1:] != ibT[:, :-1], axis=2), axis=1))) + print(f"[pi] imagination drift ({pname}): clamped-dim frac at t={T_im}: {clamp_frac:.3f}; " + f"presses/{T_im}ticks: {n_press:.1f} (data ~{400/62:.1f})", flush=True) + im_obs = np.stack(IO, 1).reshape(M * T_im, D).astype(np.float32) + im_act = np.stack(IA, 1).reshape(M * T_im, -1).astype(np.float32) + im_term = np.zeros(M * T_im, dtype=np.float32) + im_term[np.arange(T_im - 1, M * T_im, T_im)] = 1.0 + # imagined-state sanity: bits-ness + manifold distance scale + bmiss = float(np.mean(np.abs(im_obs[:, bit_idx] - np.round(im_obs[:, bit_idx])))) + print(f"[pi] imagined bits-ness {bmiss:.4f} (real ~0.02)", flush=True) + + # fit full-state gamma=0.99 occupancy on imagined data (inline trainer) + io_end = build_ends(im_term) + Ni = len(im_obs) + y_dim = D + cond_dim = D + im_act.shape[1] + D + rng2 = np.random.default_rng(SEED) + + def mk_cond(t_, j_): + gi_ = sample_goal_after(j_, io_end, rng2) + return np.concatenate([im_obs[t_], im_act[t_], im_obs[gi_]], 1).astype(np.float32) + + t0 = rng2.integers(0, Ni, 20000) + j0 = future_idx(t0, io_end, 0.99, rng2) + c0, y0 = mk_cond(t0, j0), im_obs[j0] + cm, cs = c0.mean(0), c0.std(0) + 1e-6 + ym, ys = y0.mean(0), y0.std(0) + 1e-6 + abar = cosine_abar(100) + om = make_model(cond_dim, y_dim, 256, 3, 64) + okey = jax.random.PRNGKey(SEED) + op = om.init(okey, jnp.zeros((1, y_dim)), jnp.zeros((1,)), jnp.zeros((1, cond_dim))) + otx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(3e-4)) + oo = otx.init(op) + abar_j, cmj, csj, ymj, ysj = map(jnp.asarray, (abar, cm, cs, ym, ys)) + + def oloss(p, c, y, ti, nz): + cn = (c - cmj) / csj + x0 = (y - ymj) / ysj + ab = abar_j[ti - 1][:, None] + xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1 - ab) * nz + return jnp.mean((om.apply(p, xt, ti.astype(jnp.float32) / 100, cn) - nz) ** 2) + + @jax.jit + def oupd(p, o, c, y, ti, nz): + l, g = jax.value_and_grad(oloss)(p, c, y, ti, nz) + u, o = otx.update(g, o, p) + return optax.apply_updates(p, u), o, l + + print(f"[pi] fitting occupancy on imagined-{pname} ({a.occ_steps} steps)", flush=True) + for i in tqdm.trange(1, a.occ_steps + 1, mininterval=30, dynamic_ncols=True): + t_ = rng2.integers(0, Ni, 256) + j_ = future_idx(t_, io_end, 0.99, rng2) + c_ = mk_cond(t_, j_) + y_ = im_obs[j_] + ti = rng2.integers(1, 101, 256).astype(np.int32) + nz = rng2.standard_normal((256, y_dim)).astype(np.float32) + op, oo, ol = oupd(op, oo, jnp.asarray(c_), jnp.asarray(y_), + jnp.asarray(ti), jnp.asarray(nz)) + arrs, nl = flax_params_to_npz_arrays(op) + arrs.update(dict(abar=abar, abar_prev=np.concatenate([np.ones(1, np.float32), abar[:-1]]), + cond_mean=cm.astype(np.float32), cond_std=cs.astype(np.float32), + y_mean=ym.astype(np.float32), y_std=ys.astype(np.float32))) + meta_d = dict(meta_cond_dim=np.asarray(cond_dim), meta_y_dim=np.asarray(y_dim), + meta_num_layers=np.asarray(nl), meta_diffusion_T=np.asarray(100), + meta_sample_steps=np.asarray(30)) + ckpt_out = os.path.join(STATE, f"occ_wm_{pname}.genqjax.npz") + np.savez(ckpt_out, **arrs, **meta_d) + + # ---- (4) probe: far-task Q on standard anchors ---- + P2, meta2 = load_genq_params(ckpt_out) + sig = np.full(D, 1e6, dtype=np.float32) + sig[bit_idx] = 0.5 + + @jax.jit + def qf(s_, aa_, g_, k_): + c = jnp.concatenate([s_, aa_, g_], -1) + x = occ_sample(P2, meta2, c, 128, k_, steps=10) + d2 = jnp.sum(((x - g_[:, None, :]) / jnp.asarray(sig)) ** 2, -1) + return jnp.exp(-0.5 * d2).mean(1) + + t_ = rng.integers(0, N - 1, 128) + a_rand = rng.uniform(-1, 1, (128, act.shape[1])).astype(np.float32) + g_task = np.asarray([tg[i % 5] for i in range(128)]) + key, k1 = jax.random.split(key) + qd = np.asarray(qf(jnp.asarray(obs[t_]), jnp.asarray(act[t_]), jnp.asarray(g_task), k1)) + key, k2 = jax.random.split(key) + qr = np.asarray(qf(jnp.asarray(obs[t_]), jnp.asarray(a_rand), jnp.asarray(g_task), k2)) + res[pname] = dict(q_mean=float(qd.mean()), q_nnz=float(np.mean(qd > 1e-3)), + gap=float((qd - qr).mean()), + sem=float((qd - qr).std() / np.sqrt(len(qd))), + bits_ness=bmiss, dyn_l1=err1, press_recall=press_recall) + r = res[pname] + print(f"[pi] WM-{pname}: far-task Q={r['q_mean']:.4f} nnz={r['q_nnz']:.2f} " + f"gap={r['gap']:+.4f}±{r['sem']:.4f}", flush=True) + json.dump(res, open(os.path.join(STATE, "wm_round.json"), "w"), indent=2) + + elif a.stage == "offline_extract": + # precompute a Q^{pi_1} buffer with the composed chain (one-shot), then train + # the standard GCIQLGenQ agent against buffer targets (legacy m47 pattern). + import jax, jax.numpy as jnp + import tqdm, math, flax + from utils.datasets import Dataset, GCDataset + from genq_jax import load_genq_params + from genq_recursive_jax import genq_q_recursive, stop_prob + from gciql_genq import GCIQLGenQAgent, get_config + from train_genq_jax import build_ends + import target_extractors + agent1, _ = load_agent(os.path.join(STATE, "pi1_agent.pkl"), train_dataset) + obs = np.asarray(train_dataset["observations"], dtype=np.float32) + act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1) + end_of = build_ends(train_dataset["terminals"]) + bit_idx = target_extractors.extract_target( + ENV, np.arange(obs.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + sig = np.full(obs.shape[1], 1e6, dtype=np.float32) + sig[bit_idx] = 0.5 + b = a.extract_beta + tagb = f"b{str(b).replace('.', '')}" + P, meta = load_genq_params(os.path.join( + PKG, "checkpoints", f"m9_genq_rec_full_puzzle_3x3_play_v0_{tagb}.genqjax.npz")) + md = int(math.ceil(3.0 / stop_prob(b, 0.99))) + + def pi1_fn(z, g): + return jnp.clip(agent1.network.select("actor")(z, g).mode(), -1, 1) + + qfn = jax.jit(lambda s_, aa_, g_, k_: genq_q_recursive( + P, meta, s_, aa_, g_, k_, pi1_fn, n_occ=16, beta=b, gamma=0.99, + max_depth=md, sigma=jnp.asarray(sig), steps=10)) + # buffer anchors: GCDataset-like goal mix (cur/near-geom/random) + rng = np.random.default_rng(SEED + 3) + N = len(obs) + t = rng.integers(0, N - 1, a.n_buffer) + u = rng.random(a.n_buffer) + offs = rng.geometric(0.01, a.n_buffer) + gi = np.where(u < 0.2, t, np.minimum(t + offs, end_of[t] - 1)) + gi = np.where(u >= 0.7, rng.integers(0, N, a.n_buffer), gi).astype(np.int64) + q = np.zeros(a.n_buffer, dtype=np.float32) + key = jax.random.PRNGKey(SEED) + B = 512 + print(f"[pi] precomputing Q^pi1 buffer: {a.n_buffer} anchors, beta={b}, maxD={md}", flush=True) + for i in tqdm.trange(0, a.n_buffer, B, mininterval=30, dynamic_ncols=True): + sl = slice(i, min(i + B, a.n_buffer)) + key, ks = jax.random.split(key) + q[sl] = np.asarray(qfn(jnp.asarray(obs[t[sl]]), jnp.asarray(act[t[sl]]), + jnp.asarray(obs[gi[sl]]), ks)) + print(f"[pi] buffer Q: mean={q.mean():.4f} nnz={np.mean(q > 1e-3):.2f}", flush=True) + np.savez(os.path.join(STATE, "q_pi1_buffer.npz"), t=t, gi=gi, q=q) + + config = get_config() + config["actor_loss"] = "awr"; config["alpha"] = 300.0; config["expectile"] = 0.9 + tdict = {k: np.asarray(train_dataset[k]) for k in ["observations", "actions", "terminals"]} + ds = GCDataset(Dataset.create(**tdict), config) + ex = ds.sample(2) + agent = GCIQLGenQAgent.create(SEED, ex["observations"], ex["actions"], config) + print(f"[pi] extracting pi_2 from the Q^pi1 buffer ({a.train_steps} steps)", flush=True) + for i in tqdm.trange(1, a.train_steps + 1, mininterval=30, dynamic_ncols=True): + bidx = rng.integers(0, a.n_buffer, config["batch_size"]) + batch = {"observations": obs[t[bidx]], "actions": act[t[bidx]], + "value_goals": obs[gi[bidx]], "actor_goals": obs[gi[bidx]], + "genq_q_value": q[bidx]} + base = ds.sample(config["batch_size"]) + for kk in base: + if kk not in batch: + batch[kk] = base[kk] + agent, _ = agent.update(batch) + with open(os.path.join(STATE, "pi2_agent.pkl"), "wb") as f: + pickle.dump({"params": flax.serialization.to_bytes(agent.network), + "config": dict(config)}, f) + sr, per = eval_agent(agent, env, config, 10) + print(f"[pi] pi_2 SR = {sr:.3f} per-task {per}", flush=True) + json.dump({"sr_pi2": sr, "per_task": per}, + open(os.path.join(STATE, "pi2_eval.json"), "w"), indent=2) + + elif a.stage == "extract_pi2": + union = {k: np.asarray(v) for k, v in + np.load(os.path.join(STATE, "union.npz")).items()} + _, config, sr = train_genq_agent(union, os.path.join(STATE, "occ_pi1_bits.genqjax.npz"), + a.train_steps, os.path.join(STATE, "pi2_agent.pkl"), + eval_env=env) + json.dump({"sr_pi2": sr}, open(os.path.join(STATE, "pi2_eval.json"), "w")) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_eval.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..8e21f34e0a9f20a8c6015d5b87793e20258c7d90 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_eval.json @@ -0,0 +1,35 @@ +{ + "bc": { + "sr": 0.0, + "n": 50, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "plan": { + "sr": 0.0, + "n": 50, + "per_task": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ] + }, + "plan_qf": { + "sr": 0.56, + "n": 50, + "per_task": [ + 0.6, + 0.6, + 0.5, + 0.6, + 0.5 + ] + } +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_eval.py b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..164f58e5e7da933cd9b5c0d31961a3d09d420e40 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_eval.py @@ -0,0 +1,421 @@ +"""#57 Option-B phase 2: press-scale planner — control evaluation on puzzle-3x3. + +Method (no TD, no env oracle, sparse goal-equality only, everything data/model-derived): + * MACRO model: the dataset's own bit-change transitions form a config graph over the + 512 button configs (measured: complete, 100% single-press edges, all pairs reachable). + * PLAN: BFS on that graph from the current config to the goal config; take the first + hop as the next subgoal config. + * ACT: condition the gc-BC reacher on a dataset EXEMPLAR observation of the subgoal + config (nearest in effector position); optionally Q-filter its action against the + one-hop occupancy Q toward the exemplar (the hindsight-real short-horizon signal). + * REPLAN on every bit change (or every `replan` steps as a fallback). + +Arms evaluated on the 5 eval tasks: + bc plain gc-BC toward the final goal (floor) + plan planner + BC reacher + plan_qf planner + BC reacher + one-hop Q-filter (K candidate actions) + +Run (fermion): OGBENCH_IMPLS=ogbench_ref/impls .venv/bin/python press_planner_eval.py +""" +import argparse +import json +import os +import sys +from collections import deque + +import numpy as np + +PKG = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(PKG, "genq")) +sys.path.insert(0, os.environ.get("OGBENCH_IMPLS", "ogbench_ref/impls")) + +ENV = "puzzle-3x3-play-v0" +SEED = 0 +CKPT = os.path.join(PKG, "checkpoints", "m9_genq_rec_full_puzzle_3x3_play_v0_b095.genqjax.npz") +EFF_SLICE = slice(12, 15) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--episodes", type=int, default=10, help="episodes per task per arm") + ap.add_argument("--arms", default="bc,plan,plan_qf") + ap.add_argument("--bc_steps", type=int, default=30000) + ap.add_argument("--qf_k", type=int, default=16) + ap.add_argument("--n_occ", type=int, default=64) + ap.add_argument("--replan", type=int, default=60, help="fallback replan period (steps)") + ap.add_argument("--clf_steps", type=int, default=0, help="train the press-outcome classifier and use it as the filter scorer") + ap.add_argument("--presser_steps", type=int, default=0, help="train an AWR presser for this many steps and use it as the reacher") + ap.add_argument("--presser_alpha", type=float, default=3.0) + ap.add_argument("--reacher_acc", type=int, default=0, help="run the reacher micro-benchmark with N trials instead of the eval") + a = ap.parse_args() + + import jax + import jax.numpy as jnp + import ogbench + from utils.env_utils import make_env_and_datasets + from train_genq_jax import build_ends + from genq_jax import load_genq_params, genq_q as genq_q_jax + from genq_recursive_jax import fit_midpoint_actor + import target_extractors + + _env, ds, _ = make_env_and_datasets(ENV, frame_stack=None) + obs = np.asarray(ds["observations"], dtype=np.float32) + act = np.clip(np.asarray(ds["actions"], dtype=np.float32), -1, 1) + term = np.asarray(ds["terminals"]) + end_of = build_ends(term) + bit_idx = target_extractors.extract_target( + ENV, np.arange(obs.shape[1], dtype=np.float32)[None])[0].astype(np.int64) + POW = 2 ** np.arange(9) + code_all = (np.round(obs[:, bit_idx]).astype(np.int64) @ POW) + + # ---- macro model: dataset config graph + exemplar states per config ---- + adj = {} + for i in range(len(obs) - 1): + if term[i]: + continue + if code_all[i] != code_all[i + 1]: + adj.setdefault(int(code_all[i]), set()).add(int(code_all[i + 1])) + exemplars = {} + for i, c in enumerate(code_all): + exemplars.setdefault(int(c), []).append(i) + # edge-specific exemplars: for each observed press edge (c -> c'), the exact data + # segments that performed it: (pre-press index, post-press index). Conditioning the + # BC reacher on the post-press state of a segment whose PRE-press state matches the + # current one is in-distribution for BC's hindsight training. + edge_ex = {} + for i in range(len(obs) - 1): + if term[i]: + continue + if code_all[i] != code_all[i + 1]: + j = min(i + 1 + 10, len(obs) - 1) # a few steps past the press + edge_ex.setdefault((int(code_all[i]), int(code_all[i + 1])), []).append((i, j)) + print(f"[ctl] graph: {len(adj)} nodes, edge exemplars: {len(edge_ex)} edges, " + f"mean segs/edge: {np.mean([len(v) for v in edge_ex.values()]):.1f}", flush=True) + + def bfs_next(src, dst): + """first hop of a shortest path src->dst on the data graph (None if src==dst).""" + if src == dst: + return None + seen = {src} + q = deque([(src, None)]) + while q: + u, first = q.popleft() + for v in adj.get(u, ()): + f = first if first is not None else v + if v == dst: + return f + if v not in seen: + seen.add(v) + q.append((v, f)) + return None # unreachable (shouldn't happen) + + # ---- reacher: gc-BC (+ optional one-hop occupancy Q-filter) ---- + bc_fn, bcl = fit_midpoint_actor(obs, act, end_of, goal_of=lambda gi: obs[gi], + steps=a.bc_steps, seed=SEED, log_every=0) + print(f"[ctl] BC fit {bcl:.4f}", flush=True) + P, meta = load_genq_params(CKPT) + sig_vec = np.full(obs.shape[1], 1e6, dtype=np.float32) + sig_vec[bit_idx] = 0.5 + # one-hop Q with per-dim sigma via distance rescale (genq_q uses scalar sigma; do it manually) + from genq_jax import sample as occ_sample + + @jax.jit + def qf_scores(s_rep, cand, g_rep, k): + c = jnp.concatenate([s_rep, cand, g_rep], -1) + x = occ_sample(P, meta, c, a.n_occ, k, steps=10) # [K, n, obs] + d2 = jnp.sum(((x - g_rep[:, None, :]) / jnp.asarray(sig_vec)) ** 2, -1) + return jnp.exp(-0.5 * d2).mean(1) + + rng = np.random.default_rng(SEED) + key = jax.random.PRNGKey(SEED) + + # ---- optional TRAINED PRESSER: AWR on the one-hop occupancy Q at press-scale + # hindsight goals (goal = a few steps past the NEXT bit flip). adv_norm-style + # per-batch standardized advantages -> scale-free temperature. No TD. + press_fn = None + if a.presser_steps > 0: + import flax.linen as fnn + import optax + + # precompute per-index press-scale hindsight goal: first bit-flip ahead + 5 + code_np = code_all + nxt_flip = np.full(len(obs), -1, dtype=np.int64) + last = -1 + for i in range(len(obs) - 2, -1, -1): + if term[i]: + last = -1 + elif code_np[i + 1] != code_np[i]: + last = i + 1 + nxt_flip[i] = last + valid = np.where(nxt_flip > 0)[0] + goal_idx_of = np.minimum(nxt_flip + 5, end_of[np.arange(len(obs))] - 1) + + class _Actor(fnn.Module): + @fnn.compact + def __call__(self, s, g): + h = jnp.concatenate([s, g], -1) + for _ in range(3): + h = fnn.relu(fnn.Dense(512)(h)) + return fnn.tanh(fnn.Dense(act.shape[1])(h)) + + actor = _Actor() + pparams = actor.init(jax.random.PRNGKey(SEED + 7), jnp.zeros((1, obs.shape[1])), + jnp.zeros((1, obs.shape[1]))) + ptx = optax.adam(3e-4) + popt = ptx.init(pparams) + + @jax.jit + def presser_update(pp, oo, s, g, aa, w): + def loss(pp): + pred = actor.apply(pp, s, g) + return jnp.mean(w * jnp.sum((pred - aa) ** 2, -1)) + l, gr = jax.value_and_grad(loss)(pp) + u, oo = ptx.update(gr, oo, pp) + return optax.apply_updates(pp, u), oo, l + + @jax.jit + def one_hop_q(s, aa, g, k): + c = jnp.concatenate([s, aa, g], -1) + x = occ_sample(P, meta, c, 64, k, steps=10) + d2 = jnp.sum(((x - g[:, None, :]) / jnp.asarray(sig_vec)) ** 2, -1) + return jnp.exp(-0.5 * d2).mean(1) + + print(f"[ctl] training AWR presser {a.presser_steps} steps (alpha={a.presser_alpha})", flush=True) + import tqdm as _tqdm + for it in _tqdm.trange(1, a.presser_steps + 1, mininterval=30, dynamic_ncols=True): + b = rng.choice(valid, 256) + gb = obs[goal_idx_of[b]] + key, ks = jax.random.split(key) + q = np.asarray(one_hop_q(jnp.asarray(obs[b]), jnp.asarray(act[b]), jnp.asarray(gb), ks)) + adv = (q - q.mean()) / (q.std() + 1e-6) + w = np.exp(np.clip(a.presser_alpha * adv, -5, 5)).astype(np.float32) + pparams, popt, l = presser_update(pparams, popt, jnp.asarray(obs[b]), + jnp.asarray(gb), jnp.asarray(act[b]), + jnp.asarray(w)) + def press_fn(s, g): + return actor.apply(pparams, s, g) + print(f"[ctl] presser trained (final weighted loss {float(l):.4f})", flush=True) + + # ---- optional PRESS-OUTCOME CLASSIFIER: p(next pressed button | s, a), 9-way CE + # on exact dataset labels (which button's bit block changes at the next flip). + clf_prob = None + if a.clf_steps > 0: + import flax.linen as fnn + import optax as _optax + code_np2 = code_all + nxt_flip2 = np.full(len(obs), -1, dtype=np.int64) + last = -1 + for i in range(len(obs) - 2, -1, -1): + if term[i]: + last = -1 + elif code_np2[i + 1] != code_np2[i]: + last = i + 1 + nxt_flip2[i] = last + lab = np.full(len(obs), -1, dtype=np.int64) + v = np.where(nxt_flip2 > 0)[0] + # pressed button = the one whose own bit toggled (Lights-Out: exactly the + # pressed button's bit + neighbors toggle; the pressed one is identified by + # the flip pattern matching FLIP[b]) + FLIP9 = np.zeros((9, 9), dtype=np.int8) + for i in range(9): + r_, c_ = divmod(i, 3) + for dr, dc in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)]: + rr, cc = r_ + dr, c_ + dc + if 0 <= rr < 3 and 0 <= cc < 3: + FLIP9[i, rr * 3 + cc] = 1 + flip_code = (FLIP9 @ (2 ** np.arange(9))) + for i in v: + x = int(code_np2[i]) ^ int(code_np2[nxt_flip2[i]]) + m = np.where(flip_code == x)[0] + if len(m): + lab[i] = m[0] + vlab = np.where(lab >= 0)[0] + print(f"[ctl] classifier labels: {len(vlab)} of {len(obs)}", flush=True) + + class _Clf(fnn.Module): + @fnn.compact + def __call__(self, s, aa): + h = jnp.concatenate([s, aa], -1) + for _ in range(3): + h = fnn.gelu(fnn.Dense(512)(h)) + return fnn.Dense(9)(h) + + clf = _Clf() + cparams = clf.init(jax.random.PRNGKey(SEED + 11), jnp.zeros((1, obs.shape[1])), + jnp.zeros((1, act.shape[1]))) + ctx = _optax.adam(3e-4) + copt = ctx.init(cparams) + + @jax.jit + def clf_update(pp, oo, s, aa, y): + def loss(pp): + lg = clf.apply(pp, s, aa) + return _optax.softmax_cross_entropy_with_integer_labels(lg, y).mean() + l, gr = jax.value_and_grad(loss)(pp) + u, oo = ctx.update(gr, oo, pp) + return _optax.apply_updates(pp, u), oo, l + + import tqdm as _tqdm2 + print(f"[ctl] training press classifier {a.clf_steps} steps", flush=True) + for it in _tqdm2.trange(1, a.clf_steps + 1, mininterval=30, dynamic_ncols=True): + b = rng.choice(vlab, 512) + cparams, copt, l = clf_update(cparams, copt, jnp.asarray(obs[b]), + jnp.asarray(act[b]), jnp.asarray(lab[b])) + print(f"[ctl] classifier trained (final CE {float(l):.3f})", flush=True) + + @jax.jit + def clf_prob_j(s, aa): + return jax.nn.softmax(clf.apply(cparams, s, aa), -1) + + def clf_prob(s, aa): + return np.asarray(clf_prob_j(jnp.asarray(s), jnp.asarray(aa))) + + _FLIP_CODES = [] + for _i in range(9): + _r, _c = divmod(_i, 3) + _v = 0 + for _dr, _dc in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)]: + _rr, _cc = _r + _dr, _c + _dc + if 0 <= _rr < 3 and 0 <= _cc < 3: + _v |= (1 << (_rr * 3 + _cc)) + _FLIP_CODES.append(_v) + + def intended_button(src_code, dst_code): + """which button press turns src config into dst config (None if not one press).""" + x = int(src_code) ^ int(dst_code) + return _FLIP_CODES.index(x) if x in _FLIP_CODES else None + + def reach_action(ob2, sub): + if press_fn is not None: + return np.asarray(press_fn(ob2[None], sub[None]))[0] + return np.asarray(bc_fn(ob2[None], sub[None]))[0] + + env = ogbench.make_env_and_datasets(ENV, env_only=True) + + def pick_exemplar(cfg, ob, src_cfg=None): + # prefer an edge-specific exemplar: post-press state of the segment whose + # pre-press state is nearest (effector) to the current one. + if src_cfg is not None and (int(src_cfg), int(cfg)) in edge_ex: + segs = edge_ex[(int(src_cfg), int(cfg))] + pres = obs[[p_ for p_, _ in segs]] + d = np.linalg.norm(pres[:, EFF_SLICE] - np.asarray(ob)[EFF_SLICE][None], axis=1) + return obs[segs[int(np.argmin(d))][1]] + idxs = exemplars.get(int(cfg)) + if not idxs: + return None + cand = obs[idxs] if len(idxs) <= 512 else obs[rng.choice(idxs, 512, replace=False)] + d = np.linalg.norm(cand[:, EFF_SLICE] - np.asarray(ob)[EFF_SLICE][None], axis=1) + return cand[int(np.argmin(d))] + + def run_episode(tid, arm): + nonlocal key + ob, info = env.reset(options=dict(task_id=tid)) + gob = np.asarray(info["goal"], dtype=np.float32) + gcode = int(np.round(gob[bit_idx]).astype(np.int64) @ POW) + succ, subgoal, last_code, steps_since = 0.0, None, None, 0 + _nxt_cfg = None + for t in range(500): + ob = np.asarray(ob, dtype=np.float32) + ccode = int(np.round(ob[bit_idx]).astype(np.int64) @ POW) + if arm == "bc": + target = gob + else: + if ccode != last_code or subgoal is None or steps_since >= a.replan: + nxt = bfs_next(ccode, gcode) + _nxt_cfg = nxt + subgoal = gob if nxt is None else pick_exemplar(nxt, ob, src_cfg=ccode) + if subgoal is None: + subgoal = gob + last_code, steps_since = ccode, 0 + target = subgoal + aa = np.asarray(bc_fn(ob[None], target[None]))[0] if arm == "bc" else reach_action(ob, target) + if arm == "plan_qf": + cand = np.clip(np.concatenate([ + aa[None], + aa[None] + rng.normal(0, 0.3, (a.qf_k - 1, aa.shape[0]))]), -1, 1).astype(np.float32) + ib = None if last_code is None else intended_button(ccode, _nxt_cfg) if _nxt_cfg is not None else None + if clf_prob is not None and ib is not None: + pr = clf_prob(np.repeat(ob[None], a.qf_k, 0), cand) + aa = cand[int(np.argmax(pr[:, ib]))] + else: + key, ks = jax.random.split(key) + sc = np.asarray(qf_scores(jnp.asarray(np.repeat(ob[None], a.qf_k, 0)), + jnp.asarray(cand), + jnp.asarray(np.repeat(target[None], a.qf_k, 0)), ks)) + aa = cand[int(np.argmax(sc))] + ob, _, _, _, info = env.step(np.clip(aa, -1, 1)) + steps_since += 1 + succ = max(succ, float(info.get("success", 0.0))) + return succ + + if a.reacher_acc: + # micro-benchmark: from behavior-like sim states, target a random feasible press + # edge; measure P(the intended config is the next one reached) per arm. + accs = {arm: [] for arm in ["bc_reach", "qf_reach"]} + for trial in range(a.reacher_acc): + ob, info = env.reset(options=dict(task_id=int(rng.integers(1, 6)))) + gob0 = np.asarray(info["goal"], dtype=np.float32) + for _ in range(int(rng.integers(0, 250))): + aa = np.asarray(bc_fn(np.asarray(ob, dtype=np.float32)[None], gob0[None]))[0] + ob, *_ = env.unwrapped.step(np.clip(aa + rng.normal(0, 0.1, aa.shape), -1, 1)) + ob = np.asarray(ob, dtype=np.float32) + ccode = int(np.round(ob[bit_idx]).astype(np.int64) @ POW) + nbrs = list(adj.get(ccode, ())) + if not nbrs: + continue + tgt = int(rng.choice(nbrs)) + snap = (env.unwrapped._data.qpos.copy(), env.unwrapped._data.qvel.copy(), + env.unwrapped._cur_button_states.copy()) + for arm in ["bc_reach", "qf_reach"]: + env.unwrapped.set_state(*snap) + ob2 = env.unwrapped.compute_observation().astype(np.float32) + sub = pick_exemplar(tgt, ob2, src_cfg=ccode) + ib = intended_button(ccode, tgt) + got = None + for _ in range(120): + aa = reach_action(ob2, sub) + if arm == "qf_reach": + cand = np.clip(np.concatenate([ + aa[None], + aa[None] + rng.normal(0, 0.3, (a.qf_k - 1, aa.shape[0]))]), -1, 1).astype(np.float32) + if clf_prob is not None and ib is not None: + pr = clf_prob(np.repeat(ob2[None], a.qf_k, 0), cand) + aa = cand[int(np.argmax(pr[:, ib]))] + else: + key, ks = jax.random.split(key) + sc = np.asarray(qf_scores(jnp.asarray(np.repeat(ob2[None], a.qf_k, 0)), + jnp.asarray(cand), + jnp.asarray(np.repeat(sub[None], a.qf_k, 0)), ks)) + aa = cand[int(np.argmax(sc))] + ob2, *_ = env.unwrapped.step(np.clip(aa, -1, 1)) + ob2 = np.asarray(ob2, dtype=np.float32) + c2 = int(np.round(ob2[bit_idx]).astype(np.int64) @ POW) + if c2 != ccode: + got = c2 + break + accs[arm].append(1.0 if got == tgt else 0.0) + for arm, v in accs.items(): + print(f"[ctl] REACHER {arm}: P(intended press)={np.mean(v):.3f} (n={len(v)})", flush=True) + json.dump({k: float(np.mean(v)) for k, v in accs.items()}, + open(os.path.join(PKG, "diagnostics", "reacher_acc.json"), "w")) + return + + res = {} + for arm in a.arms.split(","): + srs = [] + for tid in range(1, 6): + for _ in range(a.episodes): + srs.append(run_episode(tid, arm)) + res[arm] = dict(sr=float(np.mean(srs)), n=len(srs), + per_task=[float(np.mean(srs[i * a.episodes:(i + 1) * a.episodes])) + for i in range(5)]) + print(f"[ctl] ARM {arm:8s}: success={res[arm]['sr']:.3f} per-task={res[arm]['per_task']}", + flush=True) + + out = os.path.join(PKG, "diagnostics", "press_planner_eval.json") + json.dump(res, open(out, "w"), indent=2) + print("wrote", out, flush=True) + + +if __name__ == "__main__": + main() diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_feasibility.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_feasibility.json new file mode 100644 index 0000000000000000000000000000000000000000..ddf198bb80f5ea0990751072e44e84a35f5fca72 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/press_planner_feasibility.json @@ -0,0 +1,11 @@ +{ + "bc_loss": 0.019449947401881218, + "n_anchors": 32, + "hops": 8, + "n_chains": 256, + "mean_score": 0.028768700620552614, + "mean_spread": 0.1143798828125, + "discriminating_frac": 0.625, + "top_press_delta_mean": -0.03125, + "rand_press_delta_mean": -0.1875 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/puzzle_why.md b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/puzzle_why.md new file mode 100644 index 0000000000000000000000000000000000000000..fb0211517a7a7f5174d9fc02f0fcc187536346ab --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/puzzle_why.md @@ -0,0 +1,254 @@ +# Why Gen-Q (incl. recursive) fails on puzzle-3x3 while GCIQL works — closed (#57) + +Two probes on top of the 45-cell elimination campaign (`genq-rec-puzzle3x3-fix`), which had +established that the model, read-out, value functional, target space, extraction, and +composition are individually not the cause (all variants band at 0.10–0.19 vs reference +GCIQL 0.948). + +## Probe 1 — GCIQL expectile ablation (evaluation vs improvement) + +Reference GCIQL (ddpgbc α=1.0, 500k, seed 0) with the upper expectile — TD's implicit +maximization — dialed off: + +| expectile | best | final | +|---|---|---| +| τ=0.5 (pure behavior-policy TD evaluation) | **0.960** | 0.888 | +| τ=0.7 | **0.973** | 0.944 | +| τ=0.9 (reference) | 0.960 | 0.948 | + +**No dose-response.** The Q*-flavored ingredient contributes nothing on puzzle-3x3; an +accurate **behavior-policy Q** suffices to extract a ~0.9 policy. So the campaign's residual +explanation ("TD escapes via Q*-approximation / stitching") was half right: it is the +**stitching in evaluation**, not the improvement operator. + +## Probe 2 — model-free goal coverage (`diag_goal_coverage.py`) + +Fraction of (s,g) pairs whose within-trajectory future EVER reaches the goal (exact from the +raw trajectories, 20k pairs, GCDataset-style goal branches): + +| env | hindsight goals | random goals | near-miss on zero-support pairs | +|---|---|---|---| +| pointmaze-medium | 0.998 | **0.350** | graded (median 1.4 in xy) | +| cube-single | 0.998 | **0.221** | graded (median 0.76) | +| puzzle-3x3 | 0.998 | **0.029** | **median 2 bits — no gradient** | + +All 512 configs are visited *globally* in the play data, but from a given state the +trajectory-bounded future reaches a random goal config only 2.9% of the time, and misses +carry no graded signal in a combinatorial space. + +## The closed WHY + +Gen-Q's occupancy is trained on within-trajectory (s_t → s_{t+k}) pairs — it learns the +**trajectory-bounded (MC-semantics) future**. TD's bootstrap composes one-step pieces +through the function approximator, computing the **Markov-chain Q^β**, whose futures splice +across trajectories. On interpolating target spaces (pointmaze/cube) the two nearly +coincide, so Gen-Q wins there; on puzzle they diverge catastrophically: 2.9% support means +the trajectory-bounded read-out is exactly 0 (or σ-noise) for 97% of random-goal pairs, for +*every* action — zero advantage signal precisely where policy improvement is learned. Every +variant in the 45-cell campaign estimated the trajectory-bounded functional, which is why +they all landed in one band. + +## Implication for the recursive method (and the fix direction) + +The recursive composition re-conditions on the midpoint at every jump — it splices +trajectories exactly like the bootstrap does and computes the **Markov-level** d_γ^π. +Composition IS the Gen-Q-native stitching operator, and by Probe 1 **no improvement operator +is needed** — BC midpoints + one extraction step suffice in principle. The recursive puzzle +cells failed for an implementation reason, not a conceptual one: state==target forced a +**bits-only chain state that marginalizes the arm at every jump** (measured read-out corr +drop 0.38 → 0.22), destroying the conditioning fidelity the stitching needs (at 50 Hz a +button press takes ~50 steps of arm motion the bits chain cannot represent). + +**Decisive fix experiment (composes existing pieces, no new machinery):** recursive +composition over a **full-state occupancy** — state = target = the 55-d obs (or the +dynamics-aux latent), so midpoints carry the arm through the chain — with the read-out's +per-dim σ set bits-sharp / rest-ignored, BC midpoints, β=0.95. Note the campaign's full-55d +cells do not predict failure here: they tested full-55d **direct read-outs** (46 soft dims +crushing the reward exponent); in the recursive chain the full state serves only as chain +state while the reward still reads bits. If the mechanism above is right, this escapes the +0.19 band with no TD anywhere. + +## Post-script: the fix experiments are negative — the WHY, final form + +Full-state chain (state==target==55-d obs, arm carried through; bits-only per-dim σ +read-out) and the horizon sweep at γ=0.998 (episode-length window), seed 0, AWR α=300: + +| cell | best | final | +|---|---|---| +| bits-only β=.95 γ=.99 (canonical) | 0.053 | 0.032 | +| full-state β=.95 γ=.99 (arm fix) | 0.093 | 0.052 | +| full-state β=.998 γ=.998 (direct control, no splicing) | 0.067 | 0.036 | +| full-state β=.99 γ=.998 (~5 splices) | 0.027 | 0.000 | +| full-state β=.98 γ=.998 (~10 splices) | 0.067 | 0.016 | +| full-state β=.95 γ=.998 (~26 splices) | 0.027 | 0.008 | + +Arm-fidelity helps marginally (0.053→0.093); horizon extension does nothing. An initial +reading blamed compounding per-jump error, but the forced-depth diagnostic +(`diag_chain_depth.py`) **refutes that**: chain endpoints stay distributionally calibrated +through 26 jumps (bit-ness, range violations, and manifold distance flat in depth; +flip-rates match data ground truth at every matched horizon). + +**Final diagnosis (corrected by `diag_chain_depth.py`).** The composed chain faithfully +estimates the Markov-level occupancy — and that reveals the true failure: **action- +information washout**. The per-action Q gap at one β=0.95 jump (~20-step horizon) is ++0.0104 ± 0.0032 (real, ~33% of Q); at 26 composed jumps (~episode horizon) it is ++0.00025 ± 0.00017 — statistically zero even at n_occ=1024 (the n_occ sweep 16→1024 +shrinks the standard error 8× and reveals no hidden signal: NOT a variance problem). +The *true* long-horizon behavior-Q on puzzle is action-flat; the chain reports it +honestly. + +This sharpens the TD question: τ=0.5 GCIQL (0.960) nominally estimates the same +action-flat functional — so its action ordering cannot come from the true values +either. Working hypothesis: TD's critic trains mostly on near-horizon goals (where +the action signal is strong, cf. the depth-1 gap) and its function approximator +**generalizes that ordering to far goals** through bootstrap chaining — TD wins by +useful generalization bias where the truth is flat, not by better estimation. +Directly testable: measure the trained τ=0.5 critic's data-vs-random action gap on +the same anchor pairs; a large gap where the truth is ~0.0002 confirms it. + +**Implication.** Since the flatness is a property of the target functional, fixes must +inject ordering where the truth is flat, not estimate better: (i) extraction driven by +the **short-horizon signal** (depth-1 gap is real) composed sequentially — subgoal / +hierarchical decomposition; (ii) *fitted occupancy iteration* (γ-model-style bootstrapped +occupancy training, Janner et al. 2020) — now motivated by the generalization-bias +channel (each MLE projection generalizes near-goal structure across conditioning, as +TD's regression does), not by noise reduction; (iii) or accept the characterized +limitation. The plain read-out / composition axis is exhausted with evidence. + +## Closure: the TD-gap probe (`diag_td_gap.py`) + +The trained τ=0.5 GCIQL critic (the 0.96-scoring, improvement-free configuration), +measured on the SAME anchor tuples as the chain diagnostic: + +| goals | TD gap (data−rand action) | P(data wins) | relative gap | true (chain, n=1024) | +|---|---|---|---|---| +| near (20 steps) | +17.21 ± 1.12 | 0.887 | **76%** | +0.0104 ± 0.0032 (real) | +| far (median ~250 steps) | +3.46 ± 0.69 (5σ) | 0.625 | 3.6% | +0.00025 ± 0.00017 (≈0) | + +**Mechanism, closed.** TD's critic carries a coherent, useful action ordering at far +goals where the true behavior-Q is statistically flat. It does not estimate the far-goal +functional better — it **generalizes the massive near-goal signal outward** through the +bootstrap (recursive targets chain near-goal structure across intermediate (s,g)), with +GCDataset's near-concentrated goal mix supplying that signal densely. This is a useful +*bias* of fitted value iteration that no unbiased sample-based read-out of the true +occupancy can replicate — the read-out faithfully reports a genuinely flat function. + +**Complete causal chain for the puzzle-3x3 gap:** combinatorial target space ⇒ 2.9% +trajectory-bounded random-goal support and zero graded misses ⇒ behavior futures carry +action signal only at short horizons (depth-1 gap real, composed-horizon gap truly ~0) +⇒ any faithful behavior-occupancy critic is action-flat at improvement-relevant goals +⇒ AWR/DDPG extraction degenerates ⇒ 0.03–0.19 band. TD escapes via near-goal signal × +bootstrap generalization, needing no improvement operator (τ=0.5 ≈ τ=0.9 ≈ 0.95). + +**Fix directions ranked by this evidence:** (1) build extraction on the short-horizon +signal explicitly — occupancy-sampled subgoals + short-β reaching (hierarchical), where +Gen-Q's depth-1 gap is as real as TD's near-goal gap; (2) fitted occupancy iteration +(γ-model-style bootstrapped occupancy training) — inherits TD's generalization channel +at the model level; (3) report the characterized limitation. Better read-outs, more +samples, deeper chains, and longer horizons are all evidenced dead ends. + +## Oracle closure (`diag_oracle_q.py`): the true behavior-Q is confirmed useless at task horizons + +Ground-truth MC oracle — simulator snapshot/restore, behavior policy = tight full-state +gc-BC (loss 0.019) + dataset action noise, NO learned estimator in the value loop: + +| goal type | oracle rel gap | Q magnitude | nonzero anchors | +|---|---|---|---| +| near (next bit-flip, ~1 press) | **+37%** | 0.25 | 86% | +| far eval task goal | — | **~0.0000** | **2%** | +| random dataset goal | — | 0.0007 | 6% | + +**Oracle-argmax control** (K=8 candidates, true-sim rollouts, replan every 5): success +**0.000**, identical to the BC baseline — argmax over the TRUE behavior-Q does nothing, +because at ~98% of states every candidate action scores exactly zero at the task goal. + +This independently validates the whole chain of findings (the +37% oracle near-gap +matches the occupancy chain's +33%; the zero far-value matches the 2.9% coverage and +the flat composed gap) and settles the estimator-vs-functional question with the +strongest instrument: **no faithful estimator of the behavior-Q can drive far-goal +improvement on this env.** GCIQL succeeds because its critic is usefully unfaithful — +near-goal signal amplified ~2.5x beyond truth and propagated to far goals by bootstrap +generalization (gap-source suite: near-only goals sufficient, SR 0.900; random-only +goals dead, 0.012; Gen-Q's truth-faithful critic with matching extraction: 0.052). +The constructive residue: the near-horizon truth is real and oracle-verified — any +TD-free fix must be built on it (sequential subgoal decomposition, or an explicit +contrast-amplification scheme at the target level). + +## TAKEAWAYS — the complete, probe-by-probe causal picture (final) + +1. **Coverage** (`diag_goal_coverage`): trajectory-bounded random-goal support is 2.9% + on puzzle (vs 35%/22% pointmaze/cube), with no graded misses (combinatorial space). +2. **The true behavior-Q is useless at task horizons** (`diag_oracle_q`): sim-oracle + Q ≡ 0 at ~98% of states for every action; ORACLE-argmax control = 0.000 = BC. The + apparent one-press signal (+37%) is hindsight-flavored — for random 1-press goals + the behavior first-action gap is ~0 (`diag_midpoint_competence`). +3. **Gen-Q estimates that truth faithfully** — chain calibrated to 26 hops; regressed + critic rank-correlates 0.85 with true values; its far-goal action ranking is even + progress-ALIGNED (+0.37, top-1 usefulness 0.70) (`diag_ordering_content`). +4. **TD wins with a manufactured surface, not a better estimate**: near-reached-goal + training is necessary and sufficient (0.900 vs 0.012); the bootstrap amplifies + action contrast ~2.5-3x beyond truth; its values are uncorrelated with the truth + (rank 0.008) AND its far ordering is progress-uncorrelated (-0.05) — yet extraction + succeeds. Success tracks critic-surface TRAINABILITY (scale x smoothness x + coherence), not per-state ranking correctness. +5. **Eliminated as the delta, each with direct evidence**: occupancy-model quality + (calibrated; exact categorical in-band), sample count (n_occ→1024), read-out shape + (σ/expectile/sparse), value functional (absorbing first-passage), target space, + horizon (γ=0.998), composition depth/β, extraction style (ddpgbc on Gen-Q critic: + 0.052), flat-target poisoning (near-only goals: no change), midpoint-actor + competence alone (values turn on — Q 0→0.5-0.9 — but per-tick gaps stay ≤2%). +6. **The physics of the env**: the 50 Hz arm action is below the task's decision + granularity. True per-tick advantages cap at ~2% under ANY continuation; true + press-level (macro) choices differ by ~60%. TD succeeds by amplifying coherent 2% + micro-signals into a trainable field; a faithful estimator cannot. +7. **No-TD paths consistent with every measurement**: (i) **press-scale decision + making** — optimize the recursive chain's midpoint CHOICE (which one-press future + to steer toward), scored by sampled reach-values under an improved continuation, + iterated so competence bootstraps coverage (policy iteration in occupancy space; + large true gaps live at this level); (ii) **target-level trainability manufacture** + (amplified/sharpened regression targets) — must reproduce TD's scale+coherence, + knowing correctness alone demonstrably doesn't suffice. + +## Offline policy-iteration round 1 (`pi_loop.py`): the composition cannot carry an improved policy + +Strict-offline round 1 (pi_1 = best Gen-Q extraction, SR 0.160): compose Q^{pi_1} by +steering the full-state chain's midpoint actions with pi_1, at beta in {0.5, 0.8, 0.95} +(beta=0.5 => pi_1 nominally controls ~half the ticks). Result: **no lift over the BC- +midpoint control at any beta** (e.g. beta=0.5: Q=0.0012 vs 0.0014), and none even +restricted to task-1 goals where pi_1 is 0.8-competent (0.0002 vs 0.0003). + +**Why (structural):** the beta-occupancy family conditions on actions only through each +hop's FIRST tick, whose influence on hop outcomes is the measured <=2%; and the family +never degenerates to a one-step model (k=0 carries mass 1-beta, so low beta = mostly +self-resampling + accumulated model noise: Q collapses at 297 hops). Hence recursive +composition of behavior-trained d_beta is locked to ~the behavior policy's occupancy +regardless of the midpoint policy — offline PI cannot run through the composition alone. + +**The remaining offline door:** a learned ONE-STEP dynamics model (supervised, offline) +in which the improved policy picks EVERY tick of imagined rollouts; the occupancy is +then re-fit on imagined data (Dyna-style; no TD; Gen-Q read-out unchanged). Compounding +model error over ~100-500 ticks is the known hazard — to be measured with the same +calibration methodology before trusting values. + +## Sampling-alignment matrix (goal-conditioning x functional), puzzle seed 0 + +Found: the occupancy's goal-CONDITIONING distribution (hindsight-far: median 242 steps, +0% own-goal, 0% random) is badly mismatched to the PI driver's query mixture (20% own, +50% geom-near, 30% random), and its functional (occupancy-mass) differs from TD's +(absorbing first-passage) exactly at the own-goal anchor TD pins at max. + +| occupancy | own-goal calibration (truth 1.0) | PI @ orig (a30 s0.5) | PI @ best (a300 s2) | +|---|---|---|---| +| legacy | 0.563 (hindsight-optimism) | 0.053 | 0.187 | +| gmix (matched conditioning) | 0.186 (honest, wrong functional) | 0.027 | 0.187 | +| gmixabs (matched + absorbing) | **0.928** | 0.093 | 0.160 | + +Verdict: the alignment fixes are real (near-perfect anchor calibration; 2-3x at the +original settings) but the band stands — consistent with the oracle diagnosis: the +ceiling is the true functional's action-flatness at eval horizons, not estimation +error. Estimation on puzzle is now fixed AND insufficient, completing the elimination. +The sampler fixes should transfer as pure improvements to envs where Gen-Q works +(pointmaze/cube) — being tested. Offline-PI status: composition structurally locked; +hybrid world-model imagination yields calibrated Q^{pi1} > Q^beta state-value +separation (0.129 vs 0.098, honest press rates) but no per-tick action signal (the +same granularity wall). diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/reacher_acc.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/reacher_acc.json new file mode 100644 index 0000000000000000000000000000000000000000..8f27891910107af342160d42e5f80f8d4afb899f --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/reacher_acc.json @@ -0,0 +1 @@ +{"bc_reach": 0.11666666666666667, "qf_reach": 0.8333333333333334} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/td_gap.json b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/td_gap.json new file mode 100644 index 0000000000000000000000000000000000000000..c6906c8a58390be3561baf82e080b5aa5095aaf1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/diagnostics_tier1/td_gap.json @@ -0,0 +1,19 @@ +{ + "far_hindsight": { + "gap": 3.464782238006592, + "sem": 0.6901950240135193, + "p_data_wins": 0.625, + "q_mean": -97.0274429321289, + "q_std_across_anchors": 42.16262435913086, + "rel_gap": 0.03570832312107086 + }, + "near_20step": { + "gap": 17.20806121826172, + "sem": 1.121052622795105, + "p_data_wins": 0.88671875, + "q_mean": -22.689453125, + "q_std_across_anchors": 4.206350326538086, + "rel_gap": 0.7584167718887329 + }, + "median_far_horizon_steps": 206 +} \ No newline at end of file diff --git a/gen_q_rsm/ogbench_genq/unused/docs/ABLATIONS.md b/gen_q_rsm/ogbench_genq/unused/docs/ABLATIONS.md new file mode 100644 index 0000000000000000000000000000000000000000..f46852a24e18aa7444568fcda1f4728244733a95 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/docs/ABLATIONS.md @@ -0,0 +1,193 @@ +# Gen-Q on puzzle-3x3 — variants, pseudocode, and the ablation matrix + +> **Historical document.** The campaign's fused trainer `genq_joint_fast.py` +> and all variant flags referenced below now live in `unused/`; the surviving +> recipe is `rsm.py` (see `DESIGN_HISTORY.md` for what was dropped and why). +> The measurements and verdicts here remain the evidence base. + +Co-author orientation for issue #57 / PR #59. Every variant in the campaign is +a point in one design space: **carrier × nine recipe dimensions**. This file +gives (1) pseudocode for the shared machinery and both carriers, (2) the +ablation table — every dimension, the options tested, and the verdict with +numbers, (3) the variant catalog mapping run tags to coordinates. Companion +docs: `README.md` (leaderboard + formulations), `BETA_RECURSION.md` (recursion +mechanics in depth), `EXPERIMENTS.md` (live ledger), `VARIANTS.md` +(reproduction commands). + +Evaluation protocol everywhere: **official** = 50 episodes/task (250 total); +*periodic* = 15/task, ±0.05. Reference: GCIQL (tuned TD) 0.928 official @500k. +No variant uses TD anywhere. + +--- + +## 1. Shared machinery (pseudocode) + +### 1.1 Occupancy model — masked discrete diffusion over the 9 goal bits + +``` +# training tuple: (s_t, a_t, g) -> bits(s_{t+k}), k ~ Geom(1-gamma_i), with +# absorbing first-passage + reward-targeted stratification (exact IS weights w) +def occ_update(theta): + (s, a, g, y_bits, w) = sample_occupancy_tuple() # per-row discount gamma_i + t = uniform_timestep() # masking level + mask = bernoulli(masking_rate(t), shape=[9]) + logits = f_theta(visible(y_bits, mask), mask, t, cond=[s, a, g_bits (, enc(gamma_i))]) + loss = w * BCE(logits[mask], y_bits[mask]) # predict masked bits + theta_EMA <- polyak(theta_EMA, theta, tau=0.005) # all read-outs use EMA +``` + +### 1.2 gl — exact goal-likelihood read-out (the Q primitive) + +``` +def gl(s, a, g_bits, discount, n_orders=16): + # absorbing diffusion => any-order autoregressive likelihood, exact per order + total = 0 + for order in random_orders(n_orders): + x, mask, logp = all_masked(), ones(9), 0 + for i in range(9): + logits = f_EMA(x, mask, t_for(i), cond=[s, a, g_bits (, enc(discount))]) + j = order[i] + logp += log_sigmoid(logits[j] if g_bits[j]==1 else -logits[j]) + x[j], mask[j] = signed(g_bits[j]), 0 # TEACHER-FORCE the goal bit + total += exp(logp) + return total / n_orders # = p(goal bits | s, a) at this discount +# Zero hit-variance (nothing sampled), differentiable in a (2-model needs this). +``` + +### 1.3 Completion head — bits -> full state (retrieval-free midpoints) + +``` +# conditional Gaussian diffusion, co-trained on the SAME occupancy tuples: +# target = full future observation, its bits teacher-forced into the condition +def complete(bits, s, a, g_bits): # 25 DDIM steps, eps clip +-6 + return ddim_sample(f_cmpl_EMA, cond=[s, a, g_bits, bits]) +``` + +### 1.4 The β-recursion walk — expectation ("prob") form + +``` +p = (gamma - beta) / (gamma * (1 - beta)) # continue-probability, ~0.842 + +def Q_walk(s, a, g_bits, g_obs): # one unbiased Q sample + for level in range(10): # depth cap (masked scan) + if uniform() >= p: # COIN: stop w.p. 1-p + break + c = ancestral_sample_bits(s, a, g_bits) # 9-step, sampled (not forced) + x_c = complete(c, s, a, g_bits) # full midpoint state + a_c = actor.mode(x_c, g_obs) # LIVE actor re-decides + s, a = x_c, a_c + return gl(s, a, g_bits, discount=beta) # value at the stop node +# E[Q_walk] = (1-p) gl_b(hop1) + p(1-p) E[gl_b(hop2)] + p^2(1-p) E[gl_b(hop3)] + ... +# NO max anywhere. The retired "certificate" form replaced the series with +# max(direct, best midpoint route) — upward-biased under estimator noise. +``` + +### 1.5 Actor-agreement weighting (3-network only, after the ablation) + +``` +w_pi = exp(-alpha/2 * mean_{j in next 25 steps} ||a_dataset_j - actor.mode(s_j, g)||^2) +occupancy tuple weight *= w_pi / batch_mean(w_pi) # occupancy tracks the actor +``` + +--- + +## 2. The two carriers (pseudocode) + +### 2.1 Three-network (`--extraction r3`): occupancy + distilled critic + value + actor + +``` +for step in range(train_steps): + occ_update(); cmpl_update() + batch = sample_policy_batch() # GCIQL reference goal mix + if step > rec_after: # composition gate + q_target = clip(Q_walk(batch.s, batch.a, value_goal_bits), 0, 1) + # (record arm actually uses the certificate depth-1 variant here, + # filtered by clip(min target-critic) — the critic absorbs the max bias) + else: + q_target = gl(batch.s, batch.a, value_goal_bits, gamma) + critic <- MSE-distill towards q_target # THE noise buffer + value <- expectile regression on critic + actor <- DDPG+BC against critic # standard GCIQL updates +``` + +### 2.2 Two-model (`--extraction ddpg2`): occupancy + actor, nothing else + +``` +for step in range(train_steps): + occ_update(); cmpl_update() + (s, a_data, g_bits, g_obs) = sample_policy_batch() + # forward-only prep (no gradients): + c1 = ancestral_sample_bits(s, a_data, g_bits) # midpoint under DATA action + den = gl(s, a_data, c1, beta) # its likelihood under a_data + v1 = clip(Q_walk(complete(c1,...), actor.mode(...), g_bits), 0, 1) + # differentiable actor loss (gradient flows through mu only): + mu = actor.mode(s, g_obs) + q = (1-p) * gl(s, mu, g_bits, beta or gamma) # first-hop term + + p * ( gl(s, mu, c1, beta) / stop_grad(den) ) * v1 # exact IS ratio + L = -log(q) / stop_grad(|log q|) + alpha * BC(mu, a_data) +# bits are not reparameterizable -> the actor reaches the midpoint term through +# the exact likelihood ratio gl(s,mu,c1)/gl(s,a,c1), not through the sample. +``` + +Deployment for both: the trained actor alone, one forward pass per env step. + +--- + +## 3. The ablation matrix — every dimension, options, verdict + +Success rates are puzzle-3x3 officials unless marked (p) = periodic band. + +| # | dimension | options tested | verdict (numbers) | +|---|---|---|---| +| D1 | **carrier** | 3-network / 2-model | both work at scale; 3-network higher ceiling (0.85–1.00 (p), banked 0.947) but noisier eval-to-eval (conversion −0.16); 2-model = simpler + deploy-stable (conversion −0.06), official 0.780 and climbing | +| D2 | **recursion form** | off / certificate (max) / probabilistic (expectation) | carrier-split: 3-network tolerates certificate (critic filters the max bias; record arm) and prob chains added nothing (flat, killed); 2-model REQUIRES expectation (cert collapsed it: 0.404 < 0.524 no-rec; prob powers the 0.780 flagship); plain no-rec control 0.740 → recursion worth ~+0.04 and growing | +| D3 | **recursion depth rule** | fixed depth-1 / β-rule stochastic (β = 0.95, 0.90) | β-rule > fixed (3-network 1M: β=0.95 0.724 vs depth-1 cohort 0.547); shorter hops win (β=0.90 0.584 — deeper chains compound completion noise) | +| D4 | **composition density** | every-2 / every-step | every-step > every-2 (3-network 1M: 0.728 vs 0.547 cohort mean; caveat: seed spread 0.488–0.728) | +| D5 | **midpoint source** | dataset retrieval (ε-grid) / generated (completion head) | retrieval removed by ruling; retrieval-free reaches/exceeds retrieval-era numbers once D7 is large (retrieval control 0.784; current flagship 0.780 @ ⅕ budget) | +| D6 | **midpoint pessimism** | none / min over K=2 completions | NO effect anywhere (3-network 0.560≈cohort; 2-model 0.408≈0.404 collapse; test-time min-of-2 reads 0.224=0.224) — midpoint errors are systematic bias, not noise; only structural fixes (D2 expectation, D7 averaging) work | +| D7 | **batch size** | 1024 / 4096 / (8192, 16384 throughput-only) | THE biggest lever. Samples/s saturates at 4096 (bigger = no throughput gain) but quality keeps improving: 3-network 0.728 → 0.947 banked; 2-model 0.5-shelf → 0.867 banked. 8k/16k: pure wall-clock waste | +| D8 | **actor-agreement weighting** | on / off | carrier-split: 2-model DROP (6 matched checkpoints, unweighted ≥ weighted; twins locked) — chains re-anchor on the live actor anyway; 3-network KEEP (cold-start: essential, flat 0.20 vs 0.51 @200k; warm-started: worth ~0.15 at matched steps, converges late) | +| D9 | **discount conditioning (γ-spectrum)** | none / scalar γ column / two-point one-hot / Fourier log-horizon | scalar = BUG (~0.2 drag both carriers: raw-γ under-resolves horizon geometry; model learns the γ-marginal); two-point = best occupancy FIT (loss 0.24 vs 0.28) but WORST policy (0.467 peak — data split starves the γ-head); Fourier = at parity with no-conditioning (0.733 vs 0.707–0.747 @400k) — OPEN, 2 seeds running; none = current best (flagship) | +| D10 | **speed stack** (quality-neutral, verified) | host vs fused; 16 vs 4 actor-loss orders; 1/2/4-GPU data-parallel; occupancy warm start | fused ≈5× host; 4-order actor loss 1.95× (curves match to ±0.02); data-parallel ~99% weak-scaling (bit-identical replicas); warm start shifts early curve only. Stacked: 2.4 s/100 steps @batch 4096 ≈ 169k samples/s | + +Cross-cutting finding (D2+D6+test-time evals): **max-selection over noisy +generative estimates is the failure mode everywhere** — training certificates, +banked-best snapshots (conversion −0.06 sustained / −0.15 fresh-jump), and +test-time action argmax (0.760→0.224) are the same optimizer's curse; the +fixes that worked are structural (expectation form, density penalties, +batch/critic averaging), never resampling. + +--- + +## 4. Variant catalog — run tags → coordinates + +Only recipe dimensions shown; all 4M arms carry the D10 speed stack. + +| tag | D1 carrier | D2 form | D3 depth | D4 dens. | D7 batch | D8 wgt | D9 γ-cond | status / best | +|---|---|---|---|---|---|---|---|---| +| `joint4M_recE1B4k` | 3-net | cert (M=4) | fixed-1 | every | 4096 | on | none | 🏃 **champion**: banked 0.947, peak 1.000 (p) | +| `joint4M_recE1B4kNWWS` | 3-net | cert (M=4) | fixed-1 | every | 4096 | **off** | none | 🏃 official 0.736 @1.8M — D8 evidence | +| `joint1M_recnrE1 / recb95w1 / recb90w1 / recnrP2` | 3-net | cert (M=1) | 1 / β.95 / β.90 / 1+pess | every / every-2 | 1024 | on | none | closed: 0.728 / 0.724 / 0.584 / 0.560 — D3, D4, D6 evidence | +| `joint1M_gspec / joint1M_prob / joint4M_probB4k` | 3-net | cert / prob | β.95 | every-2 / every | 1024 / 4096 | on | scalar | closed negative: 0.452 / 0.408 / flat-killed — D9 scalar + D2-on-3net evidence | +| `ddpg2_1M_rec` | 2-model | cert | β.95 | every-2 | 1024 | on | none (retrieval midpoints) | closed: **0.784 official** — retrieval-era record (D5 control) | +| `ddpg2_4M_probB4kNS` | 2-model | **prob** | β.95 | every | 4096 | on* | **none** | 🏃 **flagship**: official **0.780** @825k (*weighting proven no-op on this carrier) | +| `ddpg2_4M_plainB4k` | 2-model | **off** | — | — | 4096 | on* | none | 🏃 official 0.740 @500k — the D2 no-recursion control | +| `ddpg2_4M_probB4k / O4 / O4DP4 / O4NW` | 2-model | prob | β.95 | every | 4096 | on/on/on/**off** | **scalar** | 🏃 the D9-scalar cohort: 0.5-shelf then 0.6–0.8 (p) — slower than NS everywhere; O4/DP4/NW are D10/D8 twins | +| `ddpg2_4M_prob2pt` | 2-model | prob | β.95 | every | 4096 | on | two-point | closed negative @375k: peak 0.467 (best fit, worst policy) | +| `ddpg2_4M_probFour` (s0, s1) | 2-model | prob | β.95 | every | 4096 | on | **Fourier** | 🏃 OPEN: 0.733 @400k ≈ flagship — the owner's target stack, 2 seeds | +| `ddpg2_1M_{ema,recnr,recnrP2,recb95w1,recb90w1,gspec,prob}`, `ddpg2_{2M_recnr,4M_fast}` | 2-model | various | various | various | 1024 | on | none/scalar | closed 1M/reference-batch cohort: 0.368–0.632 — D2/D3/D6/D7/D9 evidence rows | +| `awr2_1M` | 2-model | — (AWR actor) | — | — | 1024 | on | none | closed negative (killed @300k, declining): within-support reweighting can't move the mode | + +--- + +## 5. The recipe in one sentence per carrier + +**3-network:** occupancy (masked-bits diffusion, warm-started or agreement- +weighted) → every-step composed targets (certificate midpoints filtered by +min-target-critic) → distilled critic → expectile value → DDPG+BC actor, at +batch 4096. + +**2-model:** occupancy + completion head → coin-terminated β=0.95 expectation +walks → actor loss = first-hop gl + exact-IS midpoint term + BC anchor, at +batch 4096 — no critic, no value net, no weighting, no (or Fourier-encoded) +discount conditioning. diff --git a/gen_q_rsm/ogbench_genq/unused/docs/BETA_RECURSION.md b/gen_q_rsm/ogbench_genq/unused/docs/BETA_RECURSION.md new file mode 100644 index 0000000000000000000000000000000000000000..0bde6a0c96907a40e5c23adc9843f07cc1058a1a --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/docs/BETA_RECURSION.md @@ -0,0 +1,181 @@ +# How the probabilistic β-recursion runs inside training + +This is the operational companion to the formulation in `README.md` (§2-model / +§3-network): what actually executes, in what order, at what cost, when +`--rec_free --rec_target 1 --rec_beta 0.95 --rec_prob` is on. All function +names refer to the fused trainer (written as `genq_joint_fast.py`, now +`unused/genq_joint_fast.py`; the same machinery is what `rsm.py` runs when +recursion is on, with these flags baked in at β=0.98). The host path +`unused/genq_joint.py` implements the same math with numpy midpoint plumbing. + +## 1. What is being estimated + +The geometric splitting identity (PGF proof in README): with +p = (γ−β)/(γ(1−β)), + + Q̄_γ(s,a,g) = (1−p) · gl_β(s,a,g) + + p · E_{x_c ~ d_β(·|s,a,g)} [ Q̄_γ(x_c, μ(x_c,g), g) ] + +`gl_β` = exact goal-likelihood of the occupancy at hop discount β (teacher- +forced any-order unmasking — exact per order because the bits model is a +masked discrete diffusion). The estimator unrolls the recursion with a coin: +tails (1−p) → return `gl_β` here; heads (p) → sample a β-midpoint, complete it +to a full state, act with the live actor, recurse. Expectation form — **no max +anywhere** — which is what removed the one-sided optimism that collapsed the +certificate variant on the 2-model. + +At (γ, β) = (0.99, 0.95): p ≈ 0.842, mean chain length 1/(1−p) ≈ 5.2 hops, +mean hop horizon β/(1−β) ≈ 19 steps. + +## 2. Where it sits in the fused training step (`one_step`) + +Every training step, in order, all on-device inside one `lax.scan` body: + +1. **Occupancy update** (`occ_step`): one masked-diffusion BCE step on + absorbing/rt-stratified tuples; EMA (`occ_tau=0.005`) tracks it. All chain + queries below use the **EMA** occupancy. +2. **Completion-head update** (`cmpl_step`, only when recursion is on): the + conditional Gaussian diffusion that expands 9 midpoint bits into a full + 55-dim observation trains on the *same* tuple (target = the future + observation, its bits teacher-forced into the conditioning). Chains use its + EMA `cm_e`. +3. **Policy batch** (`sample_pi_batch`): states t, value goals `gi_v`, actor + goals `gi_a` with GCIQL's reference goal mix. +4. **Recursion prep** (the `rec_mode == "prob"` branches): build the chain + quantities (§3–4). +5. **Agent update** (`pi_step`): the carrier-specific loss consumes them. +6. The `compose` gate: `(step > rec_after) & (step % rec_every == 0)` — + with the standing `--rec_after 100000 --rec_every 1`, composition is on + every step after 100k. Before the gate, plain `gl_γ` targets are used + (`jnp.where(compose, ...)` selects; both sides are computed because shapes + must be static under jit). + +## 3. One chain, level by level (`chain_prob`) + +`chain_prob(ema, ce, actor_params, s0, a0, gb, gobs, k)` runs a **fixed-depth +masked scan** — `rec_max_depth = 10` levels always execute so jit shapes stay +static; terminated rows simply stop changing: + +For each level, per batch row: + +1. **Coin**: `cont = alive & (uniform < rec_p)` — the Bernoulli(p) of the + identity. A row that draws tails (or was already dead) freezes. +2. **Midpoint bits** (`occ_bits`): 9-step any-order *ancestral* sampling from + the EMA occupancy conditioned on (s_cur, a_cur, g-bits) at the hop discount + — the same masked-diffusion machinery as `gl`, but sampling each bit + (Bernoulli of the logit) instead of teacher-forcing the goal. +3. **Completion** (`cmpl_sample`): 25-step DDIM of the completion head maps + the bits (plus the conditioning) to a full 55-dim state `x_new`; ε clipped + to ±6. +4. **Re-decision**: `a_new = clip(actor.mode(x_new, goal_obs))` — the live + actor chooses the action at the generated midpoint. This is the policy- + improvement coupling; nothing is retrieved from the dataset. +5. **Masked advance**: `s_cur = where(cont, x_new, s_cur)` (same for the + action) — alive rows hop, dead rows carry their stop-state forward. + +After 10 levels: **one** goal-likelihood read `gl(s_f, a_f, gb)` at the hop +discount on every row's final node. That read is the estimator's value: for a +row whose coin stopped it at level k, this is exactly the `gl_β` of the +identity's termination branch at its k-th midpoint. (Rows still alive at the +cap return `gl_β` there — a small truncation bias; P(depth > 10) ≈ 0.18 at +β = 0.95, and the value contribution decays with each hop.) + +Per-level compute per row: 9 denoiser calls (bits) + 25 denoiser calls +(completion) + 1 actor forward; ×10 levels; + one 16-order `gl` at the end. +This is the dominant cost of a recursion step and why the chains run once per +*training step*, not per read-out. + +## 4. Carrier wiring + +### 3-network (`extraction r3`) — chains as critic targets + + q_rec = clip(chain_prob(EMA occ, EMA completion, live actor, + s_t, a_t, value-goal bits, value-goal obs), 0, 1) + q_v = where(compose, q_rec, gl_γ(s_t, a_t, g)) + +`q_v` is distilled into the critic (MSE on log-space targets inside +`GCIQLAblateAgent`); the expectile value and DDPG+BC actor then run off the +critic exactly as in GCIQL. The critic is the noise buffer: chain variance is +absorbed by SGD averaging across steps before the actor ever sees it. (The +0.947-record arm actually runs the *certificate* variant — `cert1`, a max over +M=4 depth-1 midpoints filtered by `clip(min target-critic)` — which this +carrier tolerates because of that same buffer; the prob chains are the 2-model +formulation.) + +### 2-model (`extraction ddpg2`) — chains inside the actor loss + +Prep (once per step, forward-only, all `stop_gradient` to the actor): + + c1 = occ_bits(s_t, a_t, actor-goal bits) # ONE midpoint, dataset action + den = gl_β(s_t, a_t, c1) # likelihood of c1 under a_t + x1 = cmpl_sample(... c1 ...) # completed midpoint state + a1 = actor.mode(x1, goal_obs) + v1 = clip(chain_prob(... from (x1, a1) ...), 0, 1) # value onward from midpoint + rec_aux = (c1, sg(den), v1) + +Loss (differentiated w.r.t. actor parameters; `n_orders_pi=4` orders on these +reads — the batch averages the extra per-state noise): + + glb = gl(s_t, μ, g-bits; dv = where(compose, β, γ)) # one read serves both branches + num = gl_β(s_t, μ, c1) + q = (1−p)·glb + p·(num / max(den, 1e-6))·v1 # importance-weighted midpoint term + L = −log(max(q, 1e-9)) / sg(|log q|) + α·(−log π(a_t | s_t, g)) + +The ratio `num/den` is the exact importance weight moving the midpoint's +probability from the dataset action (under which c1 was sampled) to the +actor's action — computable because `gl` is an exact likelihood; bits are not +reparameterizable, so the actor's gradient reaches the midpoint term through +this ratio rather than through the sample. + +## 5. Knobs, gates, and the discount conditioning + +| flag | role | standing value | +|---|---|---| +| `--rec_free --rec_target 1 --rec_prob` | retrieval-free, width-1, expectation form | on | +| `--rec_beta` | hop discount β → p=(γ−β)/(γ(1−β)) | 0.95 | +| `--rec_max_depth` | scan length (compute cap, small truncation) | 10 | +| `--rec_after` / `--rec_every` | composition onset / density | 100000 / 1 (every step) | +| `--gamma_spectrum_lo` + `--gamma_encoding` | whether/how the occupancy is discount-conditioned; sets `hop_disc` | best arm: **off** (hops query the γ model); `onehot2` / `fourier` re-encodings in flight | +| `--n_orders_pi` | orders on the differentiated actor-loss reads | 4 | +| `--batch_size` / `--occ_batch` | rows per step (chains run per PI row) | 4096 / 2048 | + +When the spectrum is off, `hop_disc = γ`: the chain hops query the γ-occupancy +— a deliberate measure mismatch that is empirically the current best +(`probB4kNS`, 0.764 official @525k). With conditioning on, `hop_disc = β` and +every `gl`/`occ_bits`/completion conditioning carries the encoded discount +column(s). + +## 6. Measured cost + +At batch 4096 on one H100, the full stack (occupancy + completion updates + +one chain per row + actor update) runs at 4.9 s/100 steps with the 4-order +actor loss (9.6 s with 16 orders); 2.4 s/100 on 4 GPUs data-parallel +(~169k samples/s). The chain block (occ_bits + DDIM completion × 10 levels) +is the largest single term; the fixed-depth masked scan wastes ~18% of level +compute on dead rows in exchange for static jit shapes. + +## 7. Reproduce the current best 2-model arm + + python ogbench_genq/experiments/puzzle-3x3-play-v0/train_genq_joint.py \ + --seed 0 --variant_tag ddpg2_probB4kNS --fast --data_parallel \ + --steps_per_dispatch 100 --train_steps 4000000 --actor_ema_tau 0.005 \ + --rec_after 100000 --rec_free --rec_target 1 --rec_every 1 \ + --rec_beta 0.95 --rec_max_depth 10 --rec_prob \ + --batch_size 4096 --occ_batch 2048 --n_orders_pi 4 --pi_alpha 1.0 \ + --extraction ddpg2 --occ_warmup 10000 \ + --occ_warmstart_npz ogbench_genq/checkpoints/m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz \ + --save_agent ckpt/actor.pkl --save_occ ckpt/occ.npz --save_best ckpt/best.pkl + +(Submit through LSF with `bash /abs/path/script.sh`; see `VARIANTS.md` §5 for +the cluster pattern. Note the weighting ablation verdict: `--pi_alpha 0` is +equivalent on this carrier.) + +## 8. Code map + +- `genq_joint_fast.py :: chain_prob` — the coin-terminated masked-scan walk. +- `genq_joint_fast.py :: occ_bits` — any-order ancestral bit sampler. +- `genq_joint_fast.py :: cmpl_sample` / `cmpl_step` — completion head (DDIM / training). +- `genq_joint_fast.py :: gl` — exact goal-likelihood (teacher-forced unmasking; `n_ord` override). +- `genq_joint_fast.py :: one_step` — step ordering, `compose` gate, `rec_aux` prep per carrier. +- `genq_joint_fast.py :: pi_step` — the r3/ddpg2 loss branches consuming the chain quantities. +- `genq_joint.py` — host-path equivalents (`rec_chain_prob`, `ddpg2_update_prob`). diff --git a/gen_q_rsm/ogbench_genq/unused/docs/BRANCHING.md b/gen_q_rsm/ogbench_genq/unused/docs/BRANCHING.md new file mode 100644 index 0000000000000000000000000000000000000000..79358b2be4a0ef7a21cdad7ef524b5f150f56233 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/docs/BRANCHING.md @@ -0,0 +1,145 @@ +# Base your task on RSM (Recursive Successor Model) + +Instructions for collaborators branching off this PR (`genq-rec-puzzle3x3-fix`, +PR #59) to run RSM on a new environment or task. Read the root `README.md` +first (what RSM is, with the math and the animation); this file is the *how*. + +RSM's puzzle results (officials 0.928–0.960, above the TD baseline on every +seed) and the pointmaze record (officials 1.000/0.900 across two 50-episode +reads, mean 0.950 — above the GCIQL band ~0.7–0.8, continuous goals) both +come from ONE trainer and ONE recipe family — you should not need to +re-derive any of it. + +## 0. Branch and environment + +```bash +git checkout genq-rec-puzzle3x3-fix +git checkout -b rsm-- +cp .env.example .env # WANDB_API_KEY, WANDB_ENTITY (lines are `export`ed) +# python env: the repo venv (.ogbench_venv) has jax[cuda], flax, optax, ogbench, wandb +``` + +Datasets cache to `~/.ogbench/data` on first use. GPUs here are LSF-only +(`bsub`); adapt §5 to your scheduler. + +## 1. The TWO task-specific decisions + +### (a) The target extractor — what are your reward-relevant coordinates? + +Implement `ogbench_genq/genq/target_extractors.py :: extract_target(env_id, obs)` +→ an `(N, d)` array of the coordinates whose value at the goal defines +success. Puzzle: 9 button bits (`obs` columns). Mazes: `obs[:, :2]` (already +implemented for all OGBench mazes). Images / high-dim states: a +reward-predictive latent (the root `CLAUDE.md` requirement). + +### (b) The goal space — discrete or continuous? + +`rsm.py` picks the read-out from the goal space (`--goal_space auto` resolves +from the env id; pass `discrete`/`continuous` to override): + +| goal space | read-out (automatic) | notes | +|---|---|---| +| finite alphabet (bits/tokens) | exact any-order likelihood (`gl`) | zero variance; the puzzle records | +| continuous coordinates | diffusion-classifier ELBO at the goal point | the pointmaze result; `--elbo_K/--elbo_c/--elbo_pess` are its knobs | + +The kernel Monte-Carlo read-out lost the race in both goal spaces and was +removed from `rsm.py` (archived in `unused/genq_joint_fast.py`). + +## 2. Run it + +There is one trainer for every env — no per-env driver to write: + +**Discrete goals** (proven to 0.928–0.960 official on puzzle) — the record +recipe (β=0.98 recursion, Fourier γ-spectrum, batch 4096, `pi_alpha 0`) is +the default: + +```bash +python ogbench_genq/rsm.py --env --seed 0 --save_best ckpt/best.pkl +``` + +**Continuous goals** (pointmaze record: officials 1.000/0.900, mean 0.950, +from the banked EMA snapshot of exactly this recipe) — recursion defaults +OFF here (see §6) and the read-out is the ELBO: + +```bash +python ogbench_genq/rsm.py --env --seed 0 --alpha \ + --save_best ckpt/best.pkl +``` + +## 3. The one hyperparameter you must set: `--alpha` + +**The BC weight `--alpha` must be set per env, and the TD reference value is +NOT automatically right.** Look up your env's +GCIQL alpha in `~/ogbench_ref/impls/hyperparameters.sh` as the *lower* +bracket. We measured on pointmaze that the anchor is two-sided for a +generative Q: the TD value (0.003) under-anchors (peaks high, then the actor +drifts off-data and collapses), while 1.0 over-anchors (caps at behavior +level). Start at ~10× the TD reference (pointmaze: 0.03) and consider +`--alpha_ramp 300000` (anneals 1.0 → α) and `--elbo_pess 1.0` +(uncertainty-penalized ELBO) if you see rise-then-oscillate. + +What the puzzle ablations already settled (don't burn GPUs re-testing +without cause): batch 4096 ≫ 1024 (quality, not just speed); Fourier +γ-encoding ≫ scalar (+0.2 end-to-end); β=0.98 ≥ 0.95 ≫ 0.90; every-step +composition; expectation-form recursion (never max); no agreement weighting +(`--pi_alpha 0`); `--n_orders_pi 4` is quality-neutral and ~2× faster. Add +`--data_parallel` on a multi-GPU allocation (verified bit-identical, ~99% +weak scaling). + +## 4. Evaluate properly (the two-number discipline) + +Periodic in-training evals are 15 episodes/task and **overstate**. The +number you report is the 50-episode protocol, now env-agnostic and +vectorized (~2 min): + +```bash +python ogbench_genq/eval_plan.py --env_id \ + --actor_pkl ckpt/best.pkl --plan_k 1 --episodes 50 --vec 25 +``` + +Measured conversions (bank → official): sustained bands −0.005…−0.04, +fresh spikes −0.07…−0.15. Run ≥2 seeds before claiming numbers (measured +spread ±0.02–0.12 depending on budget). Officials go in +`experiments//results//` and get committed. + +## 5. Cluster pattern (LSF here; adapt freely) + +```bash +# one job script per arm, launched with BASH and an ABSOLUTE path — never `sh` +bsub -J -G -q normal \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" -M 200G \ + -o logs/.%J.out bash /abs/path/to/script.sh +# script skeleton: cd repo; source .env; export OGBENCH_IMPLS=...; +# XLA_PYTHON_CLIENT_PREALLOCATE=false; python driver ... > log 2>&1 +``` + +~4.9 s/100 steps at batch 4096 on one H100; 2.4 s/100 on 4 GPUs. + +## 6. Known open edge: recursion on continuous goals + +The β-recursion is the proven ceiling-lifter on discrete goals but currently +**destabilizes continuous-goal training** (collapse ~25k steps after +`rec_after`, at every BC weight tested — the chain re-decides at generated +off-manifold coordinates). Until the guard lands (ratio clipping, +common-random-number draws, composition ramp — tracked in +`EXPERIMENTS.md`), run continuous tasks recursion-free. On pointmaze the +recursion-free recipe now solves all 5 tasks in its best banked snapshot +(officials 1.000/0.900) — but training oscillates, so the EMA actor + +best-checkpoint banking are load-bearing; recursion remains the candidate +fix for making long-horizon performance *sustained* rather than banked, and +for harder continuous envs. + +## 7. What to touch, what to leave + +| you will edit | leave alone | +|---|---| +| `genq/target_extractors.py` (your coordinates) | the read-out / recursion machinery (`rsm.py` internals) | +| `--alpha` (+ `--alpha_ramp` / `--elbo_pess`) per env | the estimator math (`BETA_RECURSION.md` documents it) | +| `--goal_space` if the env-id heuristic guesses wrong | eval protocol (`eval_plan.py`, best-ckpt banking) | +| | `.env` conventions, result-JSON schema, `unused/` (archived, unmaintained) | + +Questions → issue #57 (the campaign log with every decision) or the docs: +root `README.md` (RSM method + math) · `DESIGN_HISTORY.md` (what we tried and +why it was dropped — read before proposing a variant) · `ABLATIONS.md` +(design matrix) · `BETA_RECURSION.md` (estimator mechanics) · +`EXPERIMENTS.md` (live ledger). diff --git a/gen_q_rsm/ogbench_genq/unused/docs/DESIGN_HISTORY.md b/gen_q_rsm/ogbench_genq/unused/docs/DESIGN_HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..16c6110ae664fdc21774ec50ad6719d0892fac79 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/docs/DESIGN_HISTORY.md @@ -0,0 +1,100 @@ +# Design history — what we tried, what survived, why the rest was dropped + +The surviving method is **RSM (Recursive Successor Model)**, implemented as the +single trainer `ogbench_genq/rsm.py` (both goal spaces, one flag). Everything +below is a design that was actually built, run, and measured on the way there — +kept for reference so nobody re-derives (or re-burns GPUs on) a settled +question. Archived code lives in `ogbench_genq/unused/` (see its README; +archived files may have stale imports). The full arm-by-arm evidence is in +`EXPERIMENTS.md` (live ledger), `ABLATIONS.md` (design matrix), and +`VARIANTS.md` (puzzle-era equations + result ladder); campaign log with every +decision: issue #57 / PR #59. + +Reference bars: puzzle-3x3 GCIQL 0.928 @500k (ceiling 0.947–0.948); pointmaze +GCIQL band ~0.7–0.8. RSM officials: puzzle 0.928 / 0.932 (family best 0.960); +pointmaze 0.800. + +## Trainer lineage + +`genq/genq_jax.py` (staged: occupancy first, policy after) → +`genq_joint.py` (joint loop, host-side) → +`genq_joint_fast.py` (fused `lax.scan`, all variants behind flags) → +**`rsm.py`** (the go-to recipe only, goal-space switch, everything else +stripped). The first three are archived in `unused/`. + +## The design matrix — every fork and its verdict + +### Carrier (how many networks) + +| design | result | verdict | +|---|---|---| +| GCIQL + preloaded Gen-Q critic (`unused/gciql_genq.py`) | never beat plain GCIQL; Torch-ckpt dependency violated the JAX-only rule | **dropped** — replaced by joint training | +| 3-network (occupancy + actor + distilled critic, `--extraction r3`) | **0.968** puzzle final (all-time record); last-step actor alone reads 0.960 | **dropped from the pitch** — doubles the network count and the headline claim is "no critic"; the 2-model carrier reaches 0.928–0.960 official on its own. Code path deleted from `rsm.py`, still runnable from `unused/genq_joint_fast.py` | +| **2-model (occupancy + DDPG+BC actor), `ddpg2`** | 0.928 / 0.932 / 0.960 puzzle officials; 0.800 pointmaze | **KEPT — this is RSM** | +| AWR actor (`awr2`) | declining, 0.013 | dropped — advantage-weighted regression can't exploit the differentiable read-out | +| GLIQL-style extraction (`unused/genq_gliql.py`, `gliql`) | below ddpg2 on every cell | dropped | + +### Occupancy architecture + +| design | result | verdict | +|---|---|---| +| Factored per-coordinate occupancy (`unused/genq_factored.py`, `_dp`) | trained, but coordinates of the future state are strongly dependent (walls, object couplings); factored samples were incoherent | dropped — joint masked discrete diffusion / joint continuous diffusion | +| Inpainting formulation (`unused/genq/genq_inpaint_jax.py`, `run_inpaint_eval.py`) | goal-conditioned inpainting of futures; eval-only wins, no PI lift | dropped | +| Mixed-bits hybrid (bits + continuous columns in one model) | worked as a bridge; superseded once the target extractor made each env's reward-relevant coordinates explicit (puzzle: 9 bits; maze: 2-D position) | folded into the target-extractor design, not a separate model | + +### Discount handling (the γ-spectrum) + +| design | result | verdict | +|---|---|---| +| Fixed single γ | one model per horizon; recursion impossible (needs Q at β *and* γ) | dropped | +| Scalar γ column | **0.74 ceiling** — the γ input moves 0.04 while the horizon triples; the MLP can't resolve it and collapses to the γ-marginal | dropped (measured cost ≈ 0.2 end-to-end) | +| One-hot γ bins (`onehot2`) | splits the data — each bin's occupancy sees only its slice | dropped | +| **Fourier features of normalized log-horizon** u(γ̃) ∝ log 1/(1−γ̃), K=4 sin/cos pairs | spectrum is free; every RSM record uses it | **KEPT** | + +### Recursion (long-horizon composition) + +| design | result | verdict | +|---|---|---| +| No recursion (one-shot γ read) | puzzle no-recursion control finals **0.712** vs 0.82–0.96 with recursion | kept only as the *continuous-goal* default until the guards land (see open edge below) | +| Value distillation into a critic (`unused/genq/genq_recursive_jax.py`, task #16 era) | worked, but requires the third network | dropped with the 3-net carrier | +| Certificate / max recursion (`cert1`) | one-sided optimism on the 2-model carrier: officials **0.404–0.504** | dropped — max propagates occupancy over-estimates | +| ε-grid retrieved midpoints | 0.768/0.784 historical records; established the mechanism but assumes dataset lookup + goal-space structure | **owner-ruled out ("no retrieval at all")** — replaced by the generative completion head (`--rec_free`) | +| Scheduled TD handoff (hybrid) | out-of-scope ruling (not pure Gen-Q); code removed from the branch entirely | dropped | +| β=0.90 | too many hops — compound generation noise | dropped; **β=0.98 ≥ 0.95 ≫ 0.90** | +| **Probabilistic β-recursion, expectation form, one sample per hop** (coin p=(γ−β)/(γ(1−β))) | the ceiling-lifter: puzzle 0.82–0.96 | **KEPT — the "R" in RSM** | + +### Q read-out (occupancy → value) + +| design | result | verdict | +|---|---|---| +| Kernel Monte-Carlo over pathwise DDIM samples (`sample`) | discrete: 9-bit product-kernel log-Q noise at K=4 drowns the BC gradient — flat **0.000** (also at sharper kernel / K=16); continuous: lost to ELBO | dropped both spaces (debug fallback only) | +| ELBO on **discrete** goals | **0.12 plateau** — exact likelihood is free on a finite alphabet, the bound just adds slack | dropped on discrete | +| Read-out min-K pessimism | no-op — the read-out error is bias, not noise | dropped (superseded by `--elbo_pess`, which penalizes *spread* where the occupancy extrapolates) | +| **Exact any-order autoregressive likelihood (`gl`)** — masked discrete diffusion | zero variance, differentiable; the puzzle records | **KEPT for discrete** | +| **Diffusion-classifier ELBO at the goal point (`elbo`)** — Q = exp(−c·L̂(g\|s,a)), stratified t | pointmaze 0.800; no likelihood computation anywhere | **KEPT for continuous** | + +### Actor objective details + +| design | result | verdict | +|---|---|---| +| Agreement weighting (`--pi_alpha > 0`) | needed only to cold-start the 3-net carrier; every 2-model RSM record ran **pi_alpha=0** | dropped (owner: "looks so hacky") | +| TD-reference BC weight α on continuous goals | the anchor is **two-sided** for a generative Q: TD value 0.003 under-anchors (0.680 peak → actor drifts off-data → collapse), 1.0 over-anchors (caps 0.24–0.28) | rule: start at ~10× the TD reference (pointmaze 0.03); levers `--alpha_ramp`, `--elbo_pess` | +| Test-time raw-argmax Q-filter planning | optimizer's curse — argmax picks read-out over-estimates | density-penalized variant (0.832) kept as a *tool* in `eval_plan.py`, not the headline | + +### Throughput (settled, don't retest) + +Batch 4096 ≫ 1024 — a **quality** lever, not just speed (generated-sample +noise averages inside every update); >4096 saturated. bf16/TF32: dead +(numerics). Warm-starting the occupancy: early-curve only, same final. +`--n_orders_pi 4`: quality-neutral, ~2× faster. Data-parallel pmap: +bit-identical, ~99% weak scaling. + +## The one open edge + +**β-recursion on continuous goals** destabilizes training (collapse ~25k steps +after `rec_after`, at every BC weight tested — the chain re-decides at +generated off-manifold coordinates). Guards in flight: ratio clipping, +common-random-number draws for the num/den ELBO ratio, composition-probability +ramp. Until one lands, `rsm.py` defaults recursion **off** on continuous goals +(`--recursion auto`); pointmaze reaches 0.800 without it, and the one failed +long-horizon task is exactly what recursion should buy back. diff --git a/gen_q_rsm/ogbench_genq/unused/docs/EXPERIMENTS.md b/gen_q_rsm/ogbench_genq/unused/docs/EXPERIMENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..2a0fb75a798bc2a2040458717e5e66ca2a082232 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/docs/EXPERIMENTS.md @@ -0,0 +1,693 @@ +# Live experiment ledger — puzzle-3x3-play-v0 campaign (issue #57 / PR #59) + +Snapshot date: 2026-07-13. This document describes every experiment currently +running (20 LSF jobs) plus the measurements closed this window: the hypothesis +each one tests, how it is implemented, the exact configuration, interim status, +and the decision rule it feeds. Full method math lives in `README.md` (carrier +formulations, equations, pseudocode) and `VARIANTS.md` (recipes, repro commands); +this file is the *why-is-this-job-running* ledger. + +**Targets.** GCIQL reference on puzzle-3x3-play-v0: 0.792 @300k / **0.928 @500k**. +Best pure Gen-Q (no TD anywhere) to date: **0.784** final / 0.800 peak +(2-model + retrieval-based recursion, historical control — retrieval since +removed by owner ruling). All success rates are 50-episode finals unless marked +"periodic" (15-episode evals, ±0.05 noise). + +--- + +## Vocabulary + +Every run tag decomposes into carrier × mechanism × budget: + +- **3-network / `joint`** — occupancy + distilled critic + expectile value + + actor (GCIQL agent with the TD critic replaced by distillation from + occupancy-derived targets). +- **2-model / `ddpg2`** — occupancy + actor only. Q is read directly from the + occupancy and the actor gradient flows through the read-out's conditioning. + The pitch variant: fewest networks, critic = the generative model itself. +- **gl (goal-likelihood read-out)** — exact likelihood that the occupancy + assigns to the goal bit-configuration, computed by teacher-forced any-order + unmasking (16 random orders averaged). Zero hit-variance, differentiable in + the action. +- **Completion head** — conditional Gaussian diffusion that expands a sampled + 9-bit midpoint configuration into a full 55-dim observation, so recursion + needs no dataset retrieval (owner ruling: no retrieval anywhere). +- **β-rule stochastic depth** — chains continue with probability + p = (γ−β)/(γ(1−β)) (geometric-splitting identity), so β sets expected hop + count: β=0.95 → ~5 hops, β=0.90 → ~11. One midpoint per level (width 1). +- **prob (probabilistic estimator)** — expectation form of the splitting + identity: Q_γ = (1−p)·gl_β + p·E[Q_γ(midpoint)], estimated by a + coin-terminated chain. No max anywhere (kills one-sided optimism + structurally). Certificate form (`cert`) = the older max-over-chain variant. +- **gspec (γ-spectrum)** — occupancy conditioned on the discount: each training + tuple draws its own γ_i (task γ w.p. 0.5, else log-uniform-in-horizon down to + a floor). Policy-improvement reads at task γ; chain hops read at β. +- **E1 (every-step density)** — recursion composes targets on *every* training + step (default was every 2). The proven lever: 2× SGD averaging of + generated-midpoint noise (1M final 0.728 vs 0.547 cohort mean). +- **P2 (pessimism)** — midpoint value = min over 2 independent completion + draws. +- **NW (no weighting)** — actor-agreement weighting off (`--pi_alpha 0`). +- **F / B4k (fused / batch 4096)** — `genq_joint_fast.py` fused on-device + training (lax.scan over 100-step dispatches); B4k = `--batch_size 4096 + --occ_batch 2048`. +- **EMA actor** — Polyak average of actor params evaluated alongside the live + actor; best-checkpoint protocol takes the better of last-step and best + periodic snapshot at the 50-episode final. + +--- + +## A. Success-rate campaign (toward 0.928) + +### A1. 4M budget wave — six host arms + +**Hypothesis.** The retrieval-free recursion arms are *budget*-limited, not +mechanism-limited: their 1M finals (0.72–0.73 shelf) sit below the retrieval +control (0.784) because the actor breaks out late and midpoint-value quality +improves with continued occupancy co-training. 4× budget should convert the +shelf into ≥0.784, ideally toward 0.928. + +**Implementation.** `genq_joint.py` (host path), driver +`experiments/puzzle-3x3-play-v0/train_genq_joint.py`. All arms: +`--train_steps 4000000 --actor_ema_tau 0.005 --rec_free` + occupancy warm-start +from the pretrained mixed-bits checkpoint (`m9_..._v0.genqjax.npz`). + +| job | tag | carrier | mechanism | +|---|---|---|---| +| 139371 | `joint4M_recnrE1` | 3-network | every-step density, depth-1 | +| 139372 | `joint4M_recb95w1E1` | 3-network | β=0.95 stochastic depth × every-step | +| 139366 | `ddpg2_4M_recnrE1` | 2-model | every-step density, depth-1 | +| 139373 | `ddpg2_4M_gspecb95` | 2-model | γ-spectrum [0.90,0.99] + β=0.95, every-2 | +| 142860 | `ddpg2_4M_prob` | 2-model | spectrum [0.95,0.99] + β=0.95 expectation form, every-step (**owner's target stack**) | +| 142861 | `ddpg2_4M_gspecE1` | 2-model | spectrum + certificate form, every-step | + +**Decision rule.** Any arm ≥0.792 final: pure Gen-Q matches GCIQL@300k — +commit, push-notify, promote recipe. The `joint4M_recb95w1E1` arm also decides +whether the two independent 0.72-shelf levers (density, stochastic depth) +compose or saturate the same bottleneck. + +**Status — `joint4M_recb95w1E1` CLOSED (disk-full casualty).** Job 139372 died +at 1.495M/4M when `/proj/inf-scaling` hit 100% (write failure; the same +incident class that killed the first probFourOB4k launch). Verdict through +1.475M is already legible: peak 0.693, band 0.59–0.67 — clearly below both the +champion `joint4M_recE1B4k` (peak 1.000, sustained 0.96) and its own +retrieval-free sibling `recnrE1` (peak 0.813). The two levers do **not** +compose on the host path. Not relaunched — the partial curve (59 evals, +committed) answers the question this arm was asked. Relight with +`bash bsub_outputs/pz_joint4M_recb95w1E1.sh` via bsub if a full 4M final is +ever needed. + +### A2. β-depth ladder (1M, closing) + +**Hypothesis.** Stochastic depth by the β-rule beats fixed depth-1, and +shorter hops (higher β) beat longer ones because each generated hop compounds +completion-head noise. + +**Status.** β=0.95 3-network **FINAL 0.724** (peak 0.747; committed) ≈ density +0.728 — hypothesis half-confirmed (β-rule ≫ depth-1 cohort 0.547). β=0.90 +(job 132284, ~775k) trailing at 0.600 — long-chain half also confirming. +2-model β pair (job 132285) still mid-run. + +### A3. Pessimism (1M, job 137726) and density×pessimism (job 137857) + +**Hypothesis.** The −0.10 periodic→final conversion gap is one-sided value +optimism at generated midpoints; min-over-2 completion draws should close it. + +**Status.** `joint1M_recnrP2` 0.613 @675k — above depth-1 cohort, below the +0.72 shelf: pessimism is the *weakest* of the three optimism counters +(consistent with the planning-ladder dissociation in B6: the exploited errors +are systematic bias, which repeated draws don't fix). `recnrE1P2` +(density×pessimism combo) 0.640 @500k, on the density arm's pace. Job 137857 +also replicates plain `recnrE1` on seed 1. + +### A4. Probabilistic expectation estimator (1M pair, job 140030) + +**Hypothesis (owner's).** Replacing max-certificates with the coin-terminated +expectation estimator removes the optimism *structurally*, so prob arms should +convert periodic→final without the −0.10 gap and lift the 2-model especially. + +**Implementation.** `--rec_prob`: target = chain estimate directly (no max +against the direct read); 2-model actor gradient via the exact importance +ratio gl_β(s,μ,c)/stopgrad(gl_β(s,a,c)) — bits are not reparameterizable, the +ratio is (README §2-model). + +**Status.** ~260k in; past recursion onset, too early to call. + +### A5. Discount-conditioned occupancy (1M pair, job 133713) + +**Hypothesis.** β-hops should query the β-discount occupancy — the measure the +splitting identity actually composes — not the task-γ occupancy. One +γ-conditioned model provides both. + +**Status: REVISED — negative at reference batch for BOTH carriers.** +3-network 1M final 0.452 (vs no-spectrum twin 0.724); 2-model 1M final 0.368 +(vs no-recursion 0.524) — the mid-run "helps the 2-model" cohort read did not +survive to the final. At reference batch, conditioning the occupancy on the +discount costs more capacity than the correct-measure hops return. The live +question is batch 4096, where every running 2-model arm carries the spectrum +and the control still leads all reference-batch finals at a fraction of the +steps. **Update: at scale the spectrum was ~0.2 drag (intervention arms) — +but the owner's encoding critique reframes the verdict.** The scalar γ column +under-resolves the horizon geometry (1/(1−γ) triples across [0.95, 0.99] +while raw γ moves 0.04; MLP spectral bias + the zero-init warm-start row → +the model learns the γ-*marginal* occupancy, which is exactly the measured +dilution). Since only two discounts are ever queried (task-γ reads, β hops), +`--gamma_encoding onehot2` conditions on a discrete which-measure indicator +instead of interpolating a continuum. `ddpg2_4M_prob2pt` = the +spectrum-free winner's recipe + two-point conditioning, so chains hop at the +TRUE β measure without the scalar dilution. **CLOSED NEGATIVE (killed @375k): +peak 0.467 through 275k of chains — below even the scalar-spectrum arms at +matched steps.** Best occupancy fit of any arm (loss 0.24 vs 0.28+) yet worst +policy: the discrete indicator splits training tuples across two heads and +starves the γ-head the policy actually reads. Correct-measure hops are worth +less than full-data γ-hops on this task. **Fourier encoding (`probFour`, +owner's stack) — verdict @600k: best conditioning variant, still net −0.13** +(band 0.60–0.73 vs the spectrum-free leader's 0.73–0.84 over 400–600k; both +seeds continue to 4M finals). Conditioning summary across encodings: scalar = +bug (−0.2 dilution), two-point = data-split failure (best fit, worst policy), +Fourier = clean mechanics, ~0.13 behind at matched steps through 600k. +**Owner's revised criterion (2026-07-14): slower learning is acceptable if +Fourier CONVERGES to the spectrum-free variant's level** — the capability +(arbitrary-γ read-outs) is worth a training-time tax but not an asymptotic +one. Decision moves to the 4M finals: Fourier (2 seeds) vs the spectrum-free +flagship, official 50-ep protocol. Verdict pending; matched-step verdicts +stand only for scalar (bug) and two-point (data split). **Spectrum-specific +hyper arms (owner: 'large batch may be more helpful for the spectrum; tune +the other hyperparameters'):** `probFourOB4k` (job 174168, occ_batch 2048→4096 +— the spectrum halves per-measure data per occupancy update; doubling +restores it) and `probFourP25` (job 174169, mixture 0.5→0.25 — more data on +the task-γ head while still covering the spectrum). Both single-variable vs +`probFour` s0. Held in reserve: wider occupancy trunk (capacity), more +Fourier frequency pairs. **Retest at scale (owner: '3model can also run with +gamma-spectrum beta recursive jump'): CLOSED NEGATIVE.** `joint4M_probB4k` +peaked at 0.453 *pre*-recursion, then 350k steps of spectrum+β-prob chains +produced zero net gain (0.427/0.320 @450k), through and past the record +recipe's breakout window. Killed at 450k. The carriers split on recursion +form: 3-network wants certificates + distillation filtering (0.947 arm), +2-model wants expectation-form chains. + +**2-model stall at ~0.5 (replicated) + interventions.** Both the control and +the stacked flagship shelf at 0.44–0.52 from ~225k through 350k — where the +3-network broke 0.5 → 0.85. Two single-variable interventions on the freed +GPUs (2 each, data-parallel): `ddpg2_4M_probB4kNS` (job 160549) drops the +spectrum (the 1M finals' prime suspect — chains hop at task γ instead), and +`ddpg2_4M_plainB4k` (job 160550) drops recursion entirely (is the stack +riding on batch alone? plain batch-1024 4M final was 0.632). Whichever +unsticks past 0.55–0.6 by ~300k names the stall's cause; if neither, the +reserve lever is per-state chain averaging (`--rec_chains`). + +### A6. Large batch as a *quality* lever (fused twins) + +**Hypothesis (owner's, refined).** Throughput saturates at batch 4096 (see +B1), but simulation-based targets average generated-midpoint noise *inside +each update*, so 4× batch should improve midpoint-value quality per step even +at flat samples/s — attacking the same bottleneck as E1 density, orthogonally. + +**Implementation.** `--batch_size 4096 --occ_batch 2048` on the fused path +(`genq_joint_fast.py`); recursion ported on-device (prob chains as fixed-depth +masked `lax.scan`, completion head, spectrum). + +**Status.** `joint4M_recE1B4k` (143311): **BREAKOUT — 0.853 live / 0.867 EMA +@375k**, past GCIQL@300k (0.792) and every pure record; jumped from the +0.70–0.77 band at ~350k (early curve: 0.120 @125k → 0.427 @150k → 0.507 +@200k). `ddpg2_4M_probB4k` (143310), the 2-model twin, is tracking the same +shape *earlier*: 0.413 @125k vs reference-batch 0.267 (and vs the 3-network +B4k's own 0.120 at that step). Large batch bites for both carriers. + +**Acceleration (owner: "2model large batch — make it work").** +`ddpg2_4M_probB4kDP4` (job 151475): exact twin of the 2-model B4k arm on +4 GPUs via `--data_parallel` — measured 3.6 s/100 steps for this config → +4M in ~40 h instead of ~4.3 days. The 1-GPU arm continues as control (and is +~125k steps ahead). Held in reserve if the 2-model plateaus below the +3-network: per-state chain averaging (`--rec_chains C` — average C +coin-terminated chains per state in the actor target, the 2-model's analogue +of the critic's per-state smoothing; cross-state batch averaging reduces +gradient variance but leaves each state's value estimate 1-chain noisy). + +**Decision rule.** 2-model arm ≥0.792 → pitch variant matches GCIQL@300k, +push-notify; plateau <0.8 while 3-network holds ≥0.85 → deploy `--rec_chains`. + +### A8. Fourier-spectrum wave (owner 2026-07-14, jobs 176393–176403) + +**Directive.** "Aim for making the fourier gamma-spectrum, 2-model and +3-model, beta recursion, no weighting match GCIQL 0.94. Sweep hyperparameters +in parallel." Also: relaunch the disk-cutoff run. + +**Base recipe (every arm).** Fast path, Fourier γ-encoding +(`--gamma_encoding fourier`, spectrum [0.95, 0.99]), probabilistic β=0.95 +expectation-form chains, every-step composition, batch 4096, occ_batch 2048, +4-order actor loss, **no agreement weighting** (`--pi_alpha 0`), 4M steps. +All arms are **cold-start** (`--occ_warmup 50000`) — the warm-start npz was +purged in the owner-ordered checkpoint cleanup. Each arm changes ONE thing: + +| job | tag | carrier | the one change | +|---|---|---|---| +| 176393 | `ddpg2_4M_fourNW` | 2-model | none — the target-stack base | +| 176394 | `ddpg2_4M_fourNW_KF8` | 2-model | 8 Fourier pairs (finer horizon resolution) | +| 176395 | `ddpg2_4M_fourNW_H512` | 2-model | occupancy trunk 256→512 (capacity for the γ-slices) | +| 176396 | `ddpg2_4M_fourNW_LR1e3` | 2-model | occupancy lr 3e-4→1e-3 (faster spectrum fit) | +| 176398 | `ddpg2_4M_fourNW_B98` | 2-model | β=0.98 (shorter hops, p≈0.51 vs 0.84) | +| 176399 | `joint4M_fourNW` | 3-network | none — first 3-net Fourier arm | +| 176400 | `joint4M_fourNW_KF8` | 3-network | 8 Fourier pairs | +| 176401 | `joint4M_fourNW_H512` | 3-network | trunk 512 | +| 176402 | `joint4M_fourW` | 3-network | weighting ON (control: weighting was the *cold-start* accelerator, and this whole wave is cold-start) | +| 176403 | `joint4M_recb95w1E1r` | 3-network | relaunch of the disk casualty (host path, cold-start, re-tagged `r`) | + +New driver knobs for this wave (committed): `--gamma_fourier_k`, +`--occ_hidden`, `--occ_lr`. + +**Decision rule.** Compare at matched steps against the running `probFour` +cohort (weighted, warm-started) and spectrum-free `probB4kNS`. Any arm +sustaining ≥0.85 periodic banks an official; the wave's champion recipe gets +2 more seeds before any 0.94 claim. The `fourW` control decides whether +weighting re-enters the recipe *only* as a cold-start accelerator. + +**Launch incident (diagnosed).** `joint4M_fourNW` (176399) and `joint4M_fourW` +(176402) died ~5 min in with wandb-swallowed tracebacks. NOT a code bug: a +debug twin with `WANDB_MODE=disabled` (job 176479) ran the identical config +clean through 10k steps to FINAL. Root cause: the filesystem was rejecting +writes (quota) in that window; wandb's async writer crashes the whole process +on a failed write ("Uncaught exception in run_soon callback" — same signature +as the `recb95w1E1` and `probFour_s1` deaths). The apparent "both at dispatch +33" was wall-clock alignment of their first flush, not a step-indexed bug. +Both relaunched wandb-disabled (jobs 176625/176626, `--wandb_mode disabled`); +their curves live in the result JSONs and training logs. Until the volume has +headroom, wandb-online runs are exposed to this failure mode. + +### A7b. `probNW` RETIRED at 2.1M (was job 144227) + +Reference-batch unweighted twin: shelved 0.45–0.52 for its last 1M steps, peak +0.587 — the batch-4096 verdict (B1/A6) makes its 4M final redundant. Killed to +free a GPU for the `probB4kNS` 0.920-bank record eval during queue congestion. +Partial curve committed (12b3977). + +### A9. Likelihood-free read-out (owner 2026-07-15, jobs 186841/186842) + +**Directive.** "Remove the assumption that you can read out likelihood from +the occupancy since we won't be able to do it in continuous goal space. +Figure out a solution that works for both discrete and continuous goal +spaces." + +**Design (`--readout sample`).** Three substitutions, everything else +identical: +1. Occupancy becomes a **continuous ε-prediction diffusion over the + reward-relevant coordinates z** (puzzle: the 9 bit columns as continuous + values; a continuous env: its goal coordinates; images: the + reward-predictive latent). Deterministic DDIM sampling is a differentiable + map of the conditioning — **pathwise actor gradients, no likelihood, no + score**. +2. Q read-out = **kernel Monte-Carlo**: Q̂ = (1/K)·Σ K_h(z_k, g) over K DDIM + samples — CLAUDE.md's original E[r] formulation with a smoothed success + predicate. Puzzle kernel: per-bit sigmoid match, product over bits + (`ker_match`); a continuous env swaps in an RBF at its success radius — + ONE function, nothing else changes. +3. The β-recursion keeps its exact structure; the likelihood ratio num/den in + the actor branch becomes the same ratio of **kernel Monte-Carlo estimates** + (kernel-density ratio; consistent as sharpness→∞, K→∞; finite-K noise is + absorbed by batch 4096 exactly as the n_orders_pi=4 finding showed). + +Implementation: `gl` and `occ_bits` get drop-in sample-based twins (`q_ker`, +`z_bits`) with identical signatures, rebound when `readout=="sample"` — every +downstream site (chains, recursion prep, actor loss, critic targets) is +readout-agnostic. Flags: `--readout {gl,sample} --ker_K 16 --ker_sharp 8.0`. +CPU-smoked end-to-end (continuous occ loss, pathwise samples, kernel +recursion, chains, FINAL protocol). + +**Arms.** Twins of the two record recipes, sample-readout, all else equal: +186841 `ddpg2_4M_sampNW` (β=0.95, vs `fourNW` gl-twin: bank 0.880 @500k, +official 0.872) and 186842 `ddpg2_4M_sampNW_B98` (β=0.98, vs `fourNW_B98`: +official 0.928 @525k). + +**Decision rule.** Sample twins tracking their gl twins' curves at matched +steps (within seed spread) ⇒ the likelihood assumption is removed at no cost +and the stack is goal-space-agnostic; then a `pointmaze-medium-navigate-v0` +driver (continuous 2-D goals, RBF kernel at the success radius) is the +continuous-space proof. Sample twins materially behind ⇒ the exact read-out +is load-bearing and continuous spaces need the fallback ladder (kernel +bandwidth sweep → learned reward head R(z,g) → FSQ tokens + gl). + +**Interim verdict, puzzle sample twins (jobs 188066/188067 RETIRED at 75k).** +Six consecutive all-zero evals vs the gl twins' 0.1–0.2 at 25k (BC alone +delivers that) ⇒ actively broken, not merely slow. Diagnosis: the 9-bit +PRODUCT kernel's log-Q at K_pi=4 samples is enormously noisy (the exact +hit-variance failure mode `gl`'s exact likelihood was built to avoid — as +predicted, it bites hardest in DISCRETE spaces), and that gradient noise +drowns the BC term entirely. Supporting contrast: the POINTMAZE sample arms +(2-D RBF kernel) learn normally (0.147@75k and climbing), and the puzzle +ELBO twins (point evaluation, no product) show first life. Fallback-ladder +rung 1 launched: `sampNW_sharp3` (job 189633; ker_sharp 8→3, K_pi 4→16). +If it stays flat too, the discrete-space conclusion is: kernel-MC for +continuous goals, ELBO (or gl where available) for discrete ones. + +**Pointmaze decay ROOT-CAUSED: wrong BC weight, not the read-outs.** All +three pointmaze arms peaked 0.24–0.28 then decayed/collapsed — a SHARED +pattern. The OGBench reference GCIQL (DDPG+BC) alpha for +pointmaze-medium-navigate is **0.003**; the arms ran the puzzle default +**1.0** (puzzle's reference value — verified correct for puzzle from the +same `hyperparameters.sh`). A 330× over-weighted BC term pins the actor to +the exploratory behavior data and lets residual Q-noise degrade it — the +observed peak-then-decay. Triplet relaunched at α=0.003 (jobs 192745–47: +elbo / kernel+recursion / plain). Lesson recorded: per-env BC weight comes +from the reference table, not the puzzle default. + +**REPLICATION GATE PASSED — seed 1 officials 0.900 / 0.800 (mean 0.850), +2026-07-16.** The `rsm.py` replication (seed 1, post-cleanup trainer, pure +defaults) banked 0.853 @325k; two 50-episode officials of the stamped +snapshot (`best_rsm_pm_s1_p853.pkl`): **0.900** (1.0/1.0/0.5/1.0/1.0) and +**0.800** (1.0/1.0/0.0/1.0/1.0) — mean **0.850**, above the GCIQL band and +the earlier 0.800 record on an independent training seed. The long-horizon +task is 1.0 in ALL FOUR official reads across both seeds — solved by the +recipe, not by one lucky snapshot; the residual weakness is task 3 (0.0–0.5 +across reads/seeds). Cross-seed mean spread 0.950 vs 0.850 ≈ ±0.05–0.10, +consistent with prior seed-spread measurements. Seed 2 still training (bank +0.773 @~275k). JSONs: `results/1/official_rsm_pm_s1_325k_read{1,2}.json`. + +**POINTMAZE RECORD — officials 1.000 / 0.900 (mean 0.950), 2026-07-16.** The +`pm2M_elboNW_a03r500` arm (delayed-recursion arbiter, plain phase — recipe +identical to the RSM continuous default: ELBO read-out, α=0.03, no +recursion yet) banked its EMA actor at periodic 0.947 @225k (live read +0.907; the same arm read 0.440 at 200k — the spike is real but the band +oscillates). Two independent 50-episode officials of the stamped snapshot +(`best_pm2M_elboNW_a03r500_s225k_p947.pkl`): **1.000** (per-task +1.0/1.0/1.0/1.0/1.0) and **0.900** (1.0/1.0/0.5/1.0/1.0) — mean 0.950, +decisively above the previous 0.800 record and the GCIQL band (~0.7–0.8), +and **both reads solve the long-horizon task that every earlier snapshot +failed at 0.0** (it was 4/5's missing task). Read-to-read spread of the same +snapshot is ±0.10 — report officials as multi-read means from now on. +Caveats: single training seed, banked (not sustained) performance — +replication across seeds is the next gate; the EMA actor + best-ckpt +protocol are load-bearing. The arm continues toward its 500k recursion +switch, which now tests whether composition can make this SUSTAINED instead +of banked. JSONs: +`results/0/official_pm2M_elboNW_a03r500_s225k_{p1000,read2_p900}.json`. + +**RSM stability program (owner named the method: Recursive Successor Model).** +Beyond α, the stability levers for the ELBO-RSM on continuous goals, ranked +by mechanism fit (drift → extrapolated ELBO optimism → oscillation/collapse): +(1) uncertainty-penalized ELBO — Q = exp(−c·(mean + λ·std over the K draws)), +free conservatism where the occupancy extrapolates (`--elbo_pess`, +implemented); (2) BC-weight ramp 1.0→α over N steps — start in the +never-collapsing anchored regime, relax as the occupancy matures +(`--alpha_ramp`, implemented); (3) common-random-number (t,ε) draws for the +recursion's num/den ratio; (4) ratio clipping at 1 (no generated-midpoint +optimism); (5) composition-probability ramp instead of the rec_after step +function; (6) SNR-weighted bound-exact ELBO; (7) frozen occupancy read +snapshots. Arms: `pm2M_rsmPlain_pess` (λ=1, job 202208) and +`pm2M_rsmPlain_ramp` (ramp 300k, job 202209) race the plain α ladder. + +**Recursion-trigger diagnosis CONFIRMED across three α values.** α=0.1 also +collapsed at 125k (0.560 peak → 0.04) — α ∈ {0.003, 0.03, 0.1} all die +exactly 25k after `rec_after=100000`, independent of BC weight. The +β-recursion composition on continuous goal coordinates destabilizes the +actor. Remaining arbiters: `pm2M_elboPlain_a03` (no recursion — must climb +past 125k to seal it) and `pm2M_elboNW_a03r500` (recursion at 500k on a +maturer occupancy — tests whether better-trained models generate +on-manifold midpoints and survive composition). If plain survives, the +continuous-goal recipe ships WITHOUT recursion first, and the recursion +guard (manifold-clipped midpoints / min-filters) becomes a follow-up. + +**Collapse re-diagnosed: it's `rec_after`, not (only) α.** Both α=0.003 and +α=0.03 collapse at ~125k — 25k AFTER the recursion composition switches on +at `rec_after=100000` — while α=1.0 (BC-dominated gradient) never collapses. +On puzzle, composed β-chains lifted the ceiling; on pointmaze they blow up +the actor: candidate mechanisms are the chain's re-decision at GENERATED +continuous states (off-manifold states a 2-D coordinate model happily +produces inside walls) and the ELBO ratio at generated midpoints. Decisive +pair launched at α=0.03: `pm2M_elboPlain_a03` (no recursion, no spectrum — +job 200955) and `pm2M_elboNW_a03r500` (recursion delayed to 500k — job +200956). If plain climbs past 125k, recursion-on-continuous needs its own +guard (e.g., midpoint clipping to the data manifold, or certificate-style +min filters); α=0.1 (job 196108) doubles as the α-side control approaching +its own 125k test. + +**Owner ruling (2026-07-15): ELBO is a CONTINUOUS-domain effort only — no +discrete ELBO runs.** The last puzzle ELBO arm (c10) retired; discrete goals +use exact `gl`, period. All ELBO work now targets the pointmaze BC-anchor +window: α ladder = {0.003 collapsed from 0.680 peak, **0.03 running** +(0.400 @25k), **0.1 launched** (job 196108), 1.0 capped at 0.28}. + +**Pointmaze α=0.003 also collapses — the BC anchor is two-sided for a +GENERATIVE Q.** `pm2M_elboNW_a003` peaked 0.680 (2.4× the α=1.0 era, banked) +then fell to 0.000 by 125k — same shape, higher peak. Reading: α=1.0 +over-anchors (BC caps the policy at the behavior level), α=0.003 — +reference-correct for a TD critic — under-anchors a generative Q, whose +off-data bias the actor exploits once it escapes the data manifold. +The optimal tether for Gen-Q sits between; `pm2M_elboNW_a03` (α=0.03, +job 195374) probes the middle. The 0.680 bank is preserved for an official +if useful. + +**Temperature rung CLOSED (all four puzzle ELBO arms retired).** The ladder: +c=1 → 0.05, c=30 → 0.09, c=10 → 0.12 (the knee), all plateauing at 150–275k +far below gl's ~0.5 at matched steps. VERDICT: on discrete goal alphabets +the ELBO surrogate's action-ranking signal caps out regardless of +temperature — use exact `gl` there (it exists precisely there). ELBO remains +the general read-out for continuous goals, where its 0.680 pointmaze peak +leads everything likelihood-free; the open item there is the BC-anchor +window (α rung running), not the read-out. + +**Temperature rung SEPARATED: elbo_c matters (superseded — see closure above).** `elboNW_c10` reads 0.120 at +200k vs the c1 twins' 0.027–0.053 at the same step — ~2–4× and climbing +smoothly. `elboNW_c30` launched (job 192750) to find the knee; if the trend +holds, ELBO-with-tuned-temperature is the closing candidate for the gl pace +gap on discrete goals. + +**Discrete-kernel rung CLOSED (sharp3 killed at 75k, still 0.000).** Both +bandwidths (sharp 8 and 3) and both sample counts (K_pi 4 and 16) leave the +puzzle bit-product kernel at zero through 75k+. FINAL VERDICT for the +kernel-MC read-out: continuous-goal fallback only (and even there the plain +pointmaze kernel arm collapsed after an early peak); **ELBO point-evaluation +is the general likelihood-free read-out**, with exact gl the special case +for finite goal alphabets. Remaining question: closing the ELBO twins' pace +gap to gl (temperature rung `elboNW_c10` running; no separation vs c1 at +75k yet). + +**Pointmaze update: the kernel arms COLLAPSE, the ELBO arm leads.** +`pm2M_sampPlain` learned to a 0.280 peak (~150k) then collapsed to 0.000 by +200k; `pm2M_sampNW` flat. Pattern: as the occupancy sharpens, the smoothed +ε-ball kernel's Q saturates/spikes and its gradient destabilizes the actor — +the same noise pathology as the puzzle bit-product kernel, arriving later. +Meanwhile `pm2M_elboNW` climbs steadily (0.213 @75k, best likelihood-free +pointmaze arm). Combined with the puzzle picture, the emerging verdict: +**ELBO point-evaluation is the go-to likelihood-free read-out in BOTH goal +spaces**; kernel-MC is the fallback, not the recommendation. Puzzle ELBO +twins are alive-but-slow (0.04 @75k vs gl 0.2 @50k) — suspected flat-Q from +elbo_c=1 under-amplifying small denoising-loss differences; `elboNW_c10` +(job 190195, elbo_c=10) launched per the pre-registered sweep. + +**Third option — `--readout elbo` (owner: "if you can use elbo of diffusion +model it is fine if it makes goal likelihood accurate enough").** The +diffusion-classifier surrogate: per-condition denoising loss evaluated AT the +goal's z (stratified t over K draws), Q = exp(−elbo_c·loss). Point evaluation +like gl (zero hit-variance — no samples need to land near the goal), any goal +space like sample, and cheaper than both (ONE model apply per draw vs 9-step +teacher-forcing or 8–25-step DDIM). The recursion's num/den ratio cancels the +ELBO's unknown normalizer exactly; the known risk is a condition-dependent +bound gap biasing rankings — that is what the twins test. Arms: 188924 +`ddpg2_4M_elboNW` (β=0.95), 188925 `ddpg2_4M_elboNW_B98` (β=0.98), 188926 +`pm2M_elboNW` (pointmaze). Race vs the sample-readout arms; the better +likelihood-free candidate becomes the continuous-space recipe. + +**Continuous-goal arms (jobs 187996/187997).** The trainer is generalized: +non-puzzle envs run under `--readout sample` with z standardized by dataset +target stats and the kernel a smoothed ε-ball in RAW units at the env's +success radius (`--ker_eps`; OGBench pointmaze `_goal_tol` = 1.0, verified +from source). `pointmaze-medium-navigate-v0`, 2M steps, batch 4096: +`pm2M_sampNW` (full target stack: Fourier spectrum + prob β=0.95 chains) and +`pm2M_sampPlain` (no recursion). Reference points: GCIQL ≈ 0.7-0.8 on this +env per the OGBench paper; the trainer's in-run 50-ep FINAL protocol is the +official. CPU-smoked end-to-end before launch. + +### A7. Controls: `ddpg2_2M_recnr` (job 128201, ~1.75M) + +2M-budget control for the 2-model depth-1 collapse arm (1M final 0.404): +does budget alone rescue the raw-midpoint-value actor? (3-network 2M control +already answered no: 0.632 < no-recursion 0.680.) + +--- + +## B. Scalability / pitch campaign + +Owner goal: pitch the 2-model as the scalable variant — big datasets, big +batches, parallelization, memory-efficient for big models. + +### B1. Batch saturation ladder — CLOSED + +**Hypothesis.** No TD backup to wait on → batch scales averaging directly; +find where a single H100 saturates. + +**Verdict.** Samples/s flat beyond batch 4096 (2-model: 30k @1024 → 43k @4096 +→ 45k @8192; 3-network: 93k @4096 → 100k @16384). Killed the 8k/16k rungs. +Batch beyond 4096 is bought with wall-clock, not throughput — its remaining +value is A6's quality channel. + +### B2. Matmul-precision ladder — CLOSED, dead lever + +Default 3.38 s/100 steps, bfloat16 3.46, TF32 4.02 (compile-corrected steady +windows). At 256–512-wide MLPs the fused step is launch/memory-bound; +precision does nothing (TF32 regresses via worse kernel selection). Re-test at +VLA scale where matmuls dominate. + +### B3. Multi-GPU data parallelism — CLOSED, ~99% weak scaling + +**Hypothesis.** Occupancy MLE + simulation-based targets have no target-network +sync or backup serialization → device scaling like supervised generative +pretraining. + +**Implementation.** `--data_parallel` (fast path): `jax.pmap` over the whole +per-dispatch scan; per-device batch shards from fold_in RNG streams; gradients +`lax.pmean`'d before every optimizer update (replicas verified bit-identical: +max divergence 0.0 over 4 forced CPU devices with prob-recursion engaged); +eval/checkpoints read device 0. Commit a170801. + +**Verdict (4× H100, job 144845).** Weak scaling 3.5 s/it at 4× global batch vs +3.45 on 1 GPU = **~99% efficiency, ~118k samples/s**; strong scaling at fixed +global batch 9.61 → 3.6 s/it (2.7×, shortfall = per-device under-occupancy, +not communication). Headline pitch numbers, measured. + +### B4. Actor-agreement weighting ablation (owner: "looks so hacky") + +**Hypothesis.** The weighting (occupancy tuples reweighted by +exp(−α·mean‖a_data − μ_actor‖²/2) over a 25-step future window — a heuristic +importance weight making the occupancy track the *improving* policy) may be +redundant: β-recursion already re-selects actions at midpoints with the live +actor, a cleaner mechanism for the same policy-improvement coupling. + +**Implementation.** `ddpg2_4M_probNW` (job 144227) = exact twin of +`ddpg2_4M_probF` with `--pi_alpha 0`; commit 2c68928 statically skips the +25-step actor forward at α=0 (both paths). + +**Status.** Compute cost of the weighting: **~2%** (3.38 vs 3.45 s/it). Five +matched checkpoints (100k–400k): twins statistically identical, unweighted +nominally *ahead* at 400k (0.320/0.333-peak vs 0.293/0.307-peak), occupancy +losses equal. Owner directive on the strength of this: rerun the most +promising variants unweighted — `joint4M_recE1B4kNW` (job 156001, exact clone +of the 0.947-record arm + `--pi_alpha 0`, data-parallel ×4, snapshots saved to +disk this time) and `ddpg2_4M_probO4NW` (job 156002, clone of the 2-model +stacked flagship + `--pi_alpha 0`). + +**Decision rule.** Curves twinned at 500k+ → drop the weighting from the +standing recipe (simpler story, one less moving part). NW clearly below → +the weighting is load-bearing and the "hack" earns its keep; document the +mechanism. + +**Verdict at 500k — SPLIT by carrier.** 2-model: unweighted AHEAD at the +pre-registered decision point (0.293/0.307, peak 0.387 vs weighted +0.240/0.267, peak 0.307; six matched checkpoints never favored the +weighting) → **weighting dropped from the 2-model standing recipe**. The +warm-started 2-model flagship NW twin (`ddpg2_4M_probO4NW`) tracks its +weighted counterpart exactly, consistent. 3-network: OPEN — the unweighted +record-recipe twin (`joint4M_recE1B4kNW`, from-scratch occupancy) sat flat at +0.200 through 200k where the weighted original had reached 0.507; either the +weighting shapes the from-scratch occupancy in the critical early window +(warm-start × weighting interaction — the 2-model twins all warm-start), or +this recipe's known early variance (the weighted arm itself dipped to 0.120 +at 125k before jumping 3×). Disambiguation: the twin's 300k+ reads; if still +flat, rerun unweighted WITH warm start. **Update: flat at 0.227–0.253 through +300k — conclusive for the cold-start case; twin killed (2× the original's +breakout budget with zero climb). `joint4M_recE1B4kNWWS` (job 158266) reruns +unweighted WITH the warm start: climbs → the weighting was a cold-start +accelerator and warm-start+unweighted becomes the simplest 3-network recipe; +flat → the 3-network needs the occupancy–policy coupling the 2-model doesn't.** + +### B5. AWR extraction (`awr2`, job 144772) + +**Hypothesis (owner's).** The 2-model's per-sample cost is dominated by the +actor gradient differentiating through the 16-order gl read-out. +Advantage-weighted regression needs gl only *forward* (weights), so it should +run at ~3-network speed while keeping the 2-network memory story — if the +selection pressure suffices. + +**Implementation.** `extraction=awr2` (host path, commit a170801): actor loss += exp(3·A)-weighted behavior cloning, A = log gl(s,a_data,g) − +log gl(s,μ_EMA(s,g),g), batch-std normalized (adv_norm lesson: temperature +scale-free), weight clip 100. gl never differentiated. Saves actor + +co-trained occupancy (`--save_occ`, new) for B6. + +**Status: CLOSED NEGATIVE (killed at 300k).** 0.013 @300k, peak 0.120 early +and *declining* — exp-weighted BC amplifies advantage noise: weighted tuples +drift the actor off-data, the dataset-action log-likelihood drops, and the +EMA baseline chases the drift. Consistent with the pre-gl history (AWR 0.112) +and with the reference recipe's own choice of DDPG+BC over AWR on puzzle: +within-support reweighting is structurally weak where improvement requires +moving the mode. Verdict: the differentiable read-out is load-bearing; the +pitch keeps the ddpg2 gradient and buys throughput with batch + devices +instead. The arm's other deliverable (a saved co-trained occupancy for B6 +phase 2) moved to the 4-GPU 2-model arm, relaunched with `--save_occ` (job +152199; fast-path export added, commit pushed). + +### B6. Test-time planning (`eval_plan.py`, jobs 144700 + 148004) + +**Hypothesis (owner's).** Skip the actor gradient entirely: train occupancy +(supervised) + actor (BC-ish), apply all selection pressure at deployment by +sampling K candidate actions and executing the gl-argmax. + +**Implementation.** Standalone `eval_plan.py`: loads actor pickle + occupancy +npz; candidates = actor mode + σ·N(0,1) trust region (mode always included); +score = log gl, optional `--plan_pess R` (min over R reads) and `--plan_bc λ` +(density penalty λ‖a−mode‖²/2, commit after the collapse finding). Test rig: +0.784-record 2-model actor × *pretrained behavior* occupancy (mismatched — +co-trained occupancies of past arms were never saved; `--save_occ` fixes +forward). + +**Results — mismatched-occupancy phase CLOSED (50 ep/task; anchor = raw actor +0.760; JSONs in `results/0/eval_plan_*.json`).** + +| score | σ=0.1 K=8 / K=32 | σ=0.2 K=8 / K=32 | +|---|---|---| +| raw gl | 0.600 / 0.480 | 0.296 / 0.224 | +| min-over-2 reads | — | 0.272 / 0.224 | +| gl − 1·‖a−μ‖²/2 | — | 0.380 / — | +| gl − 10·‖a−μ‖²/2 | — | **0.752** / **0.724** | + +**Findings.** (1) Raw argmax degrades monotonically in both K and σ — +optimizer's curse: every candidate is a chance to find a systematic occupancy +error. (2) Read-out pessimism is an exact no-op (0.272/0.224 vs 0.296/0.224): +gl is already low-variance; the exploited errors are *bias*, not noise, and +re-querying a biased model cannot fix bias. (3) The density penalty at λ=10 +restores parity at both candidate counts (0.752 @K=8, 0.724 @K=32): the +training objective's BC anchor is the buffer that protects the actor, and +restoring it at test time removes the pathology. This answers "why doesn't the +actor have this issue" — it does, but the BC tether + SGD averaging + +parametric smoothing + co-adaptation buffer it; the raw argmax has none of the +four. + +**Decision rule.** Parity is not value: planning earns a place in the pitch +only if a *matched co-trained* occupancy (from B5's `--save_occ`) pushes +density-penalized planning *above* the raw actor. Otherwise: planning is +harmless-at-best under model bias, and the pitch stays with trained actors. + +**Phase 2 — matched occupancy: CLOSED POSITIVE (job 175611, +`eval_plan_plan_phase2_matched.json`).** Rig: the NWWS record pair — 3-network +actor (`best_..._s1800k_p907.pkl`, 0.812 official) × its *co-trained* occupancy +(`occ_joint4M_recE1B4kNWWS_puzzle.npz`), density-penalized score +(σ=0.2, λ=10), 50 ep/task: + +| K=1 (re-anchor) | K=8 | K=32 | +|---|---|---| +| 0.776 | 0.796 | **0.832** | + +Monotone *up* in K — the exact reverse of the mismatched-occupancy collapse — +and K=32 clears both the in-run anchor (+0.056, ≈2 s.e. at ~0.025/point) and +the 0.812 official record. Per the decision rule, planning is a real +extraction lever *when the occupancy is co-trained with the actor*: phase 1's +curse was mismatch bias, not planning per se. **0.832 is the new pure Gen-Q +official record** (per-task 1.0 / 0.88 / 0.72 / 0.66 / 0.90). Caveat for the +pitch: single rig, single seed; the +0.020 over the 0.812 official anchor is +within eval noise — the load-bearing claim is the monotone ladder over the +in-run K=1, not the record margin. + +--- + +## Memory accounting (pitch reference) + +2-model trains 2 networks (+1 completion head when recursion is on); EMA +copies carry no optimizer state; the critic IS the generative model — no +separate critic tower, no target-critic copy of the big network. GCIQL trains +actor + double critic + value (Adam state on all four) and holds target-critic +copies resident. At scale, TD keeps ~2× critic params in memory and its backup +is sequential; Gen-Q's only large network is the occupancy, trained +i.i.d.-supervised (B3 shows the resulting parallelism empirically). + +Honest counterpoint: per-sample the 2-model currently costs ~2× the 3-network +(actor VJP through the 16-order read-out + chains). B5 (AWR) and a fused +train-time n_orders cut are the identified fixes. diff --git a/gen_q_rsm/ogbench_genq/unused/docs/VARIANTS.md b/gen_q_rsm/ogbench_genq/unused/docs/VARIANTS.md new file mode 100644 index 0000000000000000000000000000000000000000..f910bc0a20fe5322607c0faefb66a4865d875a3b --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/docs/VARIANTS.md @@ -0,0 +1,683 @@ +# Gen-Q Variants on puzzle-3x3-play-v0 — equations, pseudocode, results + +> **Historical document** (puzzle-campaign era). Reproduction commands below +> reference drivers and flags now archived in `unused/`; the surviving +> trainer is `rsm.py` and the per-design drop rationale is in +> `DESIGN_HISTORY.md`. + +Issue [#57](https://github.com/williamd4112/gen_q/issues/57), PR +[#59](https://github.com/williamd4112/gen_q/pull/59), branch `genq-rec-puzzle3x3-fix`. +Everything below is **pure Gen-Q**: no TD backup on environment rewards anywhere in the +value path. The scheduled-hybrid (TD handoff) line was ruled out-of-scope and its code +and results have been removed from the branch. + +Reference bar (TD): GCIQL ddpgbc α=1.0 — **0.792 @ 300k / 0.928 @ 500k** finals. + +**Headline (2026-07-11): recursion-in-loop (§2.5) reaches FINAL 0.784 / periodic peak +0.800 at 1M steps — on the TWO-MODEL carrier (occupancy + actor, no critic network) — +with the 3-model carrier at 0.768/0.800 (banked snapshot 0.813). Pure Gen-Q +statistically at the GCIQL 300k reference** (gap 0.008 / 0.024, inside 50-episode +noise ±0.06). Pure finals ladder: 0.032 → 0.384 → 0.440 → 0.484 → 0.532 → 0.540 → +0.604 → 0.680 → 0.768 → **0.784** (peaks 0.493 → 0.667 → 0.720 → 0.773 → **0.800**). +The 2-model line alone: 0.376 → 0.524 → **0.784**. The 0.928-at-500k bar remains +open. + +**Owner ruling (2026-07-11): NO RETRIEVAL AT ALL.** The 0.768/0.784 records were +measured with ε-grid-retrieved midpoint evaluation points and stand as historical +controls that established the mechanism; the **standing recipe is `--rec_free`** +(§2.5: full-state completion head + live-actor midpoint actions — no ε-grid, no +dataset lookup, no goal-space assumption), optionally with the β-rule stochastic +recursion depth (`--rec_beta`). Retrieval-free finals are in flight; everything +below marked *retrieval* is off the standing path. + +--- + +## 0. Common machinery (all variants build on this) + +### 0.1 Absorbing first-passage occupancy — what the generative model is trained on + +Dataset $\mathcal D$ of trajectories; $t$ a query index, `end_of[t]` = one-past-end of +its trajectory, $L = \text{end\_of}[t]-t$, discount $\gamma = 0.99$, goal extraction +$\varphi(s) \in \{0,1\}^9$ (the nine puzzle bits). + +A training tuple $(s_t, a_t, g, y)$ is built by sampling a goal index $g_i$ and a +future index $j$: + +$$K \sim \mathrm{TruncGeom}(1-\gamma)\ \text{on}\ [0, L-1],\qquad + j = \min(t + K,\ g_i)\quad(\text{absorb at the goal}),\qquad y = \varphi(s_j).$$ + +Under this **absorbing** construction the model's mass on the goal configuration is the +truncated first-passage probability + +$$P_\theta(x = g \mid s,a,g)\ \xrightarrow{\ \text{MLE}\ }\ + \Pr[K \ge d] = \frac{\gamma^{d} - \gamma^{L}}{1 - \gamma^{L}},\qquad d = g_i - t,$$ + +which is exactly the functional GCIQL's mask-at-success TD critic estimates. The +normalized Q read-out is $\bar Q(s,a,g) = P_\theta(x=g\mid s,a,g) \in [0,1]$. + +### 0.2 Mixed-bits occupancy model (`train_genq_jax.py --mixed_bits`) + +One conditional diffusion model, two heads over a shared trunk: + +* continuous dims: standard $\varepsilon$-prediction DDPM, cosine $\bar\alpha$, + deterministic DDIM sampling; +* the 9 bits: **masked absorbing-state discrete diffusion** (MDLM class). During + training each bit is independently MASKed with prob $1-\kappa_t$ ($\kappa_t$ = the + shared signal level); the model predicts logits for masked bits only: + +$$\mathcal L(\theta) = \mathbb E\Big[\, w \cdot \big( \Vert \hat\varepsilon_\theta - + \varepsilon \Vert^2_{\text{cont}} + \lambda\, \mathrm{BCE}\big(\hat b_\theta, + b\big)\big|_{\text{masked bits}} \big) \Big],$$ + +with $w$ the importance weights from §0.4/§1.2 (1 otherwise). At sampling, masked bits +unmask w.p. $(\kappa_{t+1}-\kappa_t)/(1-\kappa_t)$ by a Bernoulli draw from the +predicted logit, then freeze and condition every later step — output bits are exact +$\{0,1\}$, never rounded Gaussians. + +### 0.3 Goal-mix `ref` (`--goal_mix ref`) + +The occupancy is trained on the same value-goal distribution the PI critic queries: +20% current state / 50% within-trajectory geometric / 30% random cross-trajectory +(mirrors `GCDataset.sample_goals`). Fixed the OOD-conditioning failure +($\rho$ @ random goals 0.44 → in-traj 0.92 was the diagnosis; goal-mix moved PI from +0.28 → 0.38 finals). + +### 0.4 Reward-targeted stratified sampling (`--rt_eta`) + +For in-trajectory goals, force the hit event $\{j = g_i\}$ with probability $\eta$ and +correct with exact truncated-geometric importance weights: + +$$p_{hit} = \frac{\gamma^{d} - \gamma^{L}}{1-\gamma^{L}},\qquad + w_{hit} = \frac{p_{hit}}{\eta},\qquad w_{miss} = \frac{1-p_{hit}}{1-\eta},$$ + +miss branch draws $K \mid K < d$ by inverse CDF of the front-truncated geometric. +$\mathbb E[w] = 1$; the learned conditional is unbiased, but the rare hit event (the +only reward-bearing sample) gets a constant fraction of the batch. + +### 0.5 Goal-likelihood read-out `gl` (`--readout gl`) + +Instead of sampling $N$ futures and counting hits, evaluate $P_\theta(x=g\mid s,a,g)$ +**exactly** by teacher-forced any-order unmasking of the bit head. For a random order +$\sigma$ over the 9 bits, with all earlier bits teacher-forced to the goal's values: + +$$\log P^{(\sigma)} = \sum_{i=1}^{9} \log p_\theta\big(b_{\sigma(i)} = g_{\sigma(i)} + \,\big|\, b_{\sigma(20.7$); prob-form recursion composes via `logaddexp`. Calibration + diagnostics (`elbo/q_self` vs `elbo/q_rand`, log-gap) logged each periodic eval. + +### 2.6 Fused training (`--fast`, `genq_joint_fast.py`) + +Same math as §2.2/§2.3 (plain r3/ddpg2 only — recursion not yet ported), +re-engineered for throughput: dataset resident in HBM, all tuple sampling in `jnp` +(goal-mix, absorbing/rt IS weights, actor-agreement), gl in one fused 2048-row call, +occupancy + PI steps fused into one jitted step driven by +`lax.scan` (`--steps_per_dispatch 100`). The workload is **latency-bound** (tiny +MLPs, GPU >95% idle under the host-driven loop), so the win is ~11 it/s → **~225 +steps/s** (r3): 4M steps ≈ 13 h. Equivalence verified against the host path (matched +early curves within periodic noise). `joint4M_fast` FINAL 0.636/0.760 is the +budget-saturation control of §2.2. + +--- + +## 3. Closed negative lines (don't re-open without new evidence) + +* **Read-out recursion** — $Q_{h+1} = Q_h + (1-Q_h)\cdot + \mathrm{agg}_c\, gl(s_c, a_c, g)$ with retrieved midpoints, at inference: + $\rho$ @ random goals **degrades** with hops (0.53 → 0.45; mean and max agg, + dataset-retrieved i.e. in-distribution midpoints) — every hop re-queries the same + OOD-limited model; composition compounds error at read-out. This is precisely what + §1.2 (compose in data) and §2.4 (compose in training targets) fix. + `diagnostics/diag_rec_stitch.py`. +* **gl-IQL** (V + policy on $Q = \log gl$, no ∂Q/∂a): ~0.10. +* **AWR extractions** on any Gen-Q critic (incl. adv-norm, expectile 0.95): ≤ 0.112. +* **R2 one-step Bellman distill** (V bootstraps through Gen-Q-anchored values): + 0.244 < plain distillation. +* **Static 2-model tilt** $\pi^+ \propto \pi_\beta \cdot P(x{=}g)^\kappa$ (K proposals, + softmax/argmax): 0.176. Lattice value iteration: dropped by owner. +* **Scheduled hybrid** (actor reads Gen-Q critic until step K, then TD): 0.920 — ruled + **cheating** (TD in the value path); code and results removed from the branch. + +--- + +## 4. Results board (peaks are 15-ep periodic ±0.05; FINALS are 50-ep, §0.6 protocol) + +Synthesis-free line (the scalable recipe — no stitch, no retrieval in training data): + +| variant | steps | peak | FINAL | status | +|---|---|---|---|---| +| **ddpg2_1M_rec (§2.5, 2-model + recursion)** | 1M | **0.800** | **0.784 — record** | done | +| **joint1M_rec (§2.5, r3 + recursion, cold)** | 1M | **0.800** (EMA snapshot 0.813) | **0.768** | done | +| recjoint_gmrt_1M_recactor (r3 + rec + **--rec_actor**; retrieval midpoints — historical-control class, gmrt ws) | 1M | **0.880** | 0.772 | done (PR #60) | +| recjoint_gmrt_500k_recactor (same, 500k) | 500k | 0.840 | **0.776 @ 500k** (twin without rec_actor: 0.648) | done (PR #60) | +| joint2M_ema (§2.2, cold) | 2M | 0.773 | 0.680 | done | +| joint4M_fast (§2.6, cold, fused) | 4M | 0.760 | 0.636 | done | +| joint1M_ema (§2.2, cold) | 1M | 0.707 | 0.604 | done | +| ddpg2_1M_ema (§2.3) | 1M | 0.560 | 0.524 | done | +| ddpg2_4M_fast (§2.6, fused) | 4M | 0.547 @ 1.5M | — | running | +| recvd_gmrt_2M_m8 (§2.4, frozen occ + recursion) | 2M | 0.587 | 0.476 | done | +| joint1M (§2.2, cold, pre-protocol) | 1M | 0.667 | 0.532 | done | +| recvd 1M (§2.4) | 1M | 0.467 | 0.408 | done | +| jointws (§2.2, gmrt ws) | 500k | 0.547 | 0.484 | done | +| joint500k / pia2 (§2.2, cold) | 500k | 0.493 / 0.440 | 0.440 / 0.424 | done | +| ddpg2 (§2.3) | 500k | 0.453 | 0.376 | done | +| recvd 500k, 30/120-step (§2.4) | 500k | 0.467 / 0.427 | 0.340 / 0.340 | done | +| R3-gm-gl (§2.1, frozen) | 500k | 0.493 | 0.320 | done | +| R3-gm n64/n256/n512 (§2.1) | 300k–1M | 0.427/0.400/0.392 | 0.384/0.352/0.392 | done | +| **GCIQL reference (TD)** | 300k/500k | — | **0.792 / 0.928** | the bar | + +Stitch-accelerated arms (data synthesis — puzzle-class accelerator, off the scalable +path per §1.2): + +| variant | steps | peak | FINAL | +|---|---|---|---| +| joint2Mst (gmst ws) | 2M | 0.773 | 0.640 | +| joint1Mst s0/s1/s2/s2+EMA (gmst ws) | 1M | 0.720/0.720/0.693/0.680 | 0.480/0.656/0.608/0.600 | +| jointstws (gmst ws) | 500k | 0.573 | 0.540 | +| ab_r3gmst (frozen gmst) | 500k | 0.413 | 0.304 | + +Verified lever ladder, in the order they were earned: goal-mix (§0.3) → +reward-targeted sampling (§0.4) → gl read-out (§0.5) → joint re-fitting (§2.2) → +best-ckpt protocol (§0.6) → **recursion-in-loop (§2.5)**. The stitch lever (§1.2) is +real (+0.056 at 500k) but redundant at 1M+ and non-scalable. + +--- + +## 5. Reproducing the headline results — step by step + +**Environment.** Python venv `.ogbench_venv` (JAX + ogbench); the reference GCIQL +implementation is resolved via `OGBENCH_IMPLS` (default `$HOME/ogbench_ref/impls`). +`source .env` for W&B credentials (result JSONs then carry a real `wandb_url`). +GPUs are only reachable through LSF (`bsub`); the login node is CPU-only: + +```bash +bsub -G grp_runtime -q normal -J -M 200G \ + -gpu "num=1/task:mode=shared:j_exclusive=yes" \ + -o bsub_outputs/.%J.out bash /abs/path/to/ +``` + +Invoke job scripts with **`bash` + absolute path**, never `sh`: /bin/sh runs bash in +POSIX mode, where `source .env` searches only `$PATH` (no CWD fallback) and, being a +special builtin, its failure **aborts the shell silently** — the job exits 1 with no +output and no log. + +Per-run env vars (all launch scripts under `bsub_outputs/*.sh` use these): +`XLA_PYTHON_CLIENT_PREALLOCATE=false XLA_PYTHON_CLIENT_MEM_FRACTION=0.85 +XLA_PYTHON_CLIENT_ALLOCATOR=platform OMP_NUM_THREADS=4`. + +### 5.1 The record recipe (retrieval-free standing form) + +Cold start: no occupancy warm start, no stitch, no data synthesis, **no retrieval** +(owner ruling). One H100, ~15–24 h (host path). + +```bash +python ogbench_genq/experiments/puzzle-3x3-play-v0/train_genq_joint.py \ + --seed 0 --variant_tag joint1M_recnr --train_steps 1000000 \ + --actor_ema_tau 0.005 --rec_target 4 --rec_every 2 --rec_after 100000 \ + --rec_free \ + --save_agent ogbench_genq/checkpoints/actor_joint1M_recnr_puzzle.pkl +``` + +Optional β-rule stochastic depth: add `--rec_beta 0.95 --rec_max_depth 6`. + +Historical control (ε-grid retrieval midpoints — drop `--rec_free`, tag +`joint1M_rec`): FINAL **0.768** / peak 0.800 (banked snapshot 0.813). This is the +number the mechanism was established with; retrieval-free finals in flight. + +Defaults that matter (all in the JSON for audit): `--extraction r3`, +`--occ_warmup 50000` (actor-agreement weighting gated until then), `--occ_tau 0.005` +(EMA occupancy for read-out), `--rt_eta 0.5`, `--pi_alpha 1.0` with horizon 25 +(α_π∈[2,3] equivalent), `--rec_eps 0.5` (ε-grid snap; 512 cells on puzzle), +`--n_orders 16`, batch 1024, γ=0.99, expectile 0.9, ddpgbc α=1.0. + +Expected shape: plateau ~0.35–0.5 through the mid band, breakout at ~650–800k, +periodic peaks ≥0.78 in the last 300k, `final_best_ckpt` ≈ 0.75–0.80. Output: +`experiments/puzzle-3x3-play-v0/results/{seed}/genq_joint_joint1M_rec.json` +(curve, dual finals, per-task success, wandb_url). + +### 5.2 The 2-model arm (retrieval-free standing form) + +```bash +python ogbench_genq/experiments/puzzle-3x3-play-v0/train_genq_joint.py \ + --seed 0 --variant_tag ddpg2_1M_recnr --extraction ddpg2 \ + --train_steps 1000000 --occ_warmup 10000 \ + --actor_ema_tau 0.005 --rec_target 4 --rec_every 2 --rec_after 100000 \ + --rec_free \ + --occ_warmstart_npz ogbench_genq/checkpoints/m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz \ + --save_agent ogbench_genq/checkpoints/actor_ddpg2_1M_recnr_puzzle.pkl +``` + +Historical control (retrieval midpoints, drop `--rec_free`, tag `ddpg2_1M_rec`): +FINAL **0.784** / peak 0.800 — the overall record and the number in the PR title. + +2-model arms warm-start the occupancy from gmrt (the actor reads the occupancy +directly from step one, so it needs a sane critic immediately). gmrt is pure MC +MLE — no synthesis. To rebuild it (~2 h): + +```bash +python ogbench_genq/genq/train_genq_jax.py --env puzzle-3x3-play-v0 \ + --mixed_bits --absorb_goal --goal_mix ref --rt_eta 0.5 --train_steps 300000 \ + --out ogbench_genq/checkpoints/m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz +``` + +### 5.3 Controls and baselines + +* **No-recursion twin**: drop the `--rec_*` flags → joint1M_ema 0.604/0.707, + ddpg2_1M_ema 0.524/0.560. This isolates recursion's +0.13–0.16. +* **Budget control (fused)**: `--fast --train_steps 4000000` → joint4M_fast + 0.636/0.760 in ~13 h — proves the record is *not* reachable by budget alone. +* **Frozen-occupancy recursion** (mechanism-only, §2.4): + `experiments/puzzle-3x3-play-v0/train_gciql_ablate.py --readout gl --genq_actor + --genq_value --rec_target 8 --rec_every 2 --genq_npz ` → 0.476/0.587 @ 2M. +* **GCIQL reference (TD)**: the reference recipe via `run_gciql.py` (ddpgbc α=1.0) + → 0.792 @ 300k / 0.928 @ 500k finals. + +### 5.4 Protocol + +Always report `final_best_ckpt` (§0.6). Periodic evals are 15 episodes (±0.05 +noise) every 25k; finals are 50 episodes. Never read a last-step number as the +result of an oscillating joint arm. + +--- + +## 6. Where to branch off + +* **Branch**: `genq-rec-puzzle3x3-fix` (PR #59). Start from `HEAD`. +* **Best recipe today**: §5.1 verbatim (recursion-in-loop, cold, synthesis-free). +* **Key checkpoints** (`ogbench_genq/checkpoints/`): + `actor_joint1M_rec_puzzle.pkl` (the 0.768/0.813 banked policy), + `m9_genq_mixb_gmrt_…npz` (MC occupancy warm start), + `m9_genq_mixb_gmst_…npz` (stitched variant — accelerator experiments only), + `gciql_ref_puzzle_3x3_agent.pkl` (trained TD critic, 0.947 — diagnostics only). +* **Diagnostics**: `diagnostics/diag_q_compare.py` (per-goal-type ρ vs the TD critic — + run first for any new occupancy; go/no-go = ρ @ random goals), + `diagnostics/diag_rec_stitch.py` (read-out recursion probe). +* **Open frontier**: (1) multi-seed the record recipe + rec hyperparameter sweep + (M, rec_every, rec_after) and 2M budgets — in flight; (2) the 0.928-at-500k bar; + (3) retrieval-free midpoints (evaluate $v_m$ at full-state occupancy samples, no + ε-snap) — the scalability unlock; (4) port recursion into the fused fast path + (§2.6) for 4M-scale recursion runs; (5) transfer the stack to cube-single / + pointmaze. diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gcbc.py b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gcbc.py new file mode 100644 index 0000000000000000000000000000000000000000..c3d4ee1cdcb3c94556c0181041a2da5f40838440 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gcbc.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +"""Train the goal-conditioned BC baseline on antmaze-large-navigate-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gcbc + +ENV = "antmaze-large-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql.py b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql.py new file mode 100644 index 0000000000000000000000000000000000000000..d64c8cbe43094d9416edba179b0b9682f97094db --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Train the standard GCIQL baseline (TD critic) on antmaze-large-navigate-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql + +ENV = "antmaze-large-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=500000) + ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=0.3) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql_genq.py b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql_genq.py new file mode 100644 index 0000000000000000000000000000000000000000..70a22898722ae421756b6fc411c242cbdcfc6491 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql_genq.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +"""Train GCIQL with the Gen-Q occupancy critic on antmaze-large-navigate-v0 (JAX-only, diffusion occupancy). + +Best Gen-Q config for this env (M10 score table; legacy tree removed, see git history): +awr alpha=10.0 expectile=0.5 n_occ=16 sigma=5.0. +Requires a trained Gen-Q diffusion occupancy ckpt; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env antmaze-large-navigate-v0 +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq + +ENV = "antmaze-large-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=10.0) + ap.add_argument("--expectile", type=float, default=0.5) + ap.add_argument("--n_occ", type=int, default=16) + ap.add_argument("--sigma", type=float, default=5.0) + ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, sigma=a.sigma, + genq_npz=a.genq_npz, latent_npz=a.latent_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql_genq_recursive.py b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql_genq_recursive.py new file mode 100644 index 0000000000000000000000000000000000000000..26ce66f7f062dc563447dd549c751ade75b57d37 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-large-navigate-v0/train_gciql_genq_recursive.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on antmaze-large-navigate-v0. + +The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric +recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))). +Requires a --state_target short-beta occupancy; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \ + --env antmaze-large-navigate-v0 --gamma --state_target \ + --out ogbench_genq/checkpoints/m9_genq_rec_antmaze_large_navigate_v0_b.genqjax.npz +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq_recursive + +ENV = "antmaze-large-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy") + ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion") + ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump") + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=30.0) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--n_occ", type=int, default=16) + ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps, + recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma, + steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, + genq_npz=a.genq_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gcbc.py b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gcbc.py new file mode 100644 index 0000000000000000000000000000000000000000..bca62e4c6d01c11dbd564658a1e6c0cfeda3bf16 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gcbc.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +"""Train the goal-conditioned BC baseline on antmaze-medium-navigate-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gcbc + +ENV = "antmaze-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql.py b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql.py new file mode 100644 index 0000000000000000000000000000000000000000..33f91b5ccb79f16097b79281bfe067fe4e284678 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Train the standard GCIQL baseline (TD critic) on antmaze-medium-navigate-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql + +ENV = "antmaze-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=500000) + ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=0.3) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql_genq.py b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql_genq.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6603f283ce55076675c549b8c8304d92fa98a9 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql_genq.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +"""Train GCIQL with the Gen-Q occupancy critic on antmaze-medium-navigate-v0 (JAX-only, diffusion occupancy). + +Best Gen-Q config for this env (M10 score table; legacy tree removed, see git history): +awr alpha=10.0 expectile=0.5 n_occ=16 sigma=5.0. +Requires a trained Gen-Q diffusion occupancy ckpt; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env antmaze-medium-navigate-v0 +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq + +ENV = "antmaze-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=10.0) + ap.add_argument("--expectile", type=float, default=0.5) + ap.add_argument("--n_occ", type=int, default=16) + ap.add_argument("--sigma", type=float, default=5.0) + ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, sigma=a.sigma, + genq_npz=a.genq_npz, latent_npz=a.latent_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql_genq_recursive.py b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql_genq_recursive.py new file mode 100644 index 0000000000000000000000000000000000000000..91813276c867f47d5f0376a16168c224b3e500ae --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antmaze-medium-navigate-v0/train_gciql_genq_recursive.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on antmaze-medium-navigate-v0. + +The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric +recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))). +Requires a --state_target short-beta occupancy; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \ + --env antmaze-medium-navigate-v0 --gamma --state_target \ + --out ogbench_genq/checkpoints/m9_genq_rec_antmaze_medium_navigate_v0_b.genqjax.npz +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq_recursive + +ENV = "antmaze-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy") + ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion") + ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump") + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=30.0) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--n_occ", type=int, default=16) + ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps, + recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma, + steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, + genq_npz=a.genq_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gcbc.py b/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gcbc.py new file mode 100644 index 0000000000000000000000000000000000000000..8c7a409410724507289a7fdfbce1c31254bde103 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gcbc.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +"""Train the goal-conditioned BC baseline on antsoccer-medium-navigate-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gcbc + +ENV = "antsoccer-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql.py b/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql.py new file mode 100644 index 0000000000000000000000000000000000000000..6bfebd2b3c8cd9814c242e4e45bf10d160e43425 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Train the standard GCIQL baseline (TD critic) on antsoccer-medium-navigate-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql + +ENV = "antsoccer-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=500000) + ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=0.3) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql_genq.py b/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql_genq.py new file mode 100644 index 0000000000000000000000000000000000000000..48db3e7627b3c0e5e6ffec622edad5b924c5b2bf --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql_genq.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +"""Train GCIQL with the Gen-Q occupancy critic on antsoccer-medium-navigate-v0 (JAX-only, diffusion occupancy). + +Best Gen-Q config for this env (M10 score table; legacy tree removed, see git history): +awr alpha=30.0 expectile=0.9 n_occ=64 sigma=5.0. +Requires a trained Gen-Q diffusion occupancy ckpt; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env antsoccer-medium-navigate-v0 +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq + +ENV = "antsoccer-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=30.0) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--n_occ", type=int, default=64) + ap.add_argument("--sigma", type=float, default=5.0) + ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, sigma=a.sigma, + genq_npz=a.genq_npz, latent_npz=a.latent_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql_genq_recursive.py b/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql_genq_recursive.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0744affb796152d411bb2c34ea456b159ddcd1 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/antsoccer-medium-navigate-v0/train_gciql_genq_recursive.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on antsoccer-medium-navigate-v0. + +The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric +recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))). +Requires a --state_target short-beta occupancy; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \ + --env antsoccer-medium-navigate-v0 --gamma --state_target \ + --out ogbench_genq/checkpoints/m9_genq_rec_antsoccer_medium_navigate_v0_b.genqjax.npz +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq_recursive + +ENV = "antsoccer-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy") + ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion") + ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump") + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=30.0) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--n_occ", type=int, default=16) + ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps, + recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma, + steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, + genq_npz=a.genq_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gcbc.py b/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gcbc.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb87ea3469fa1d968bb2a095f0837af50ebf296 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gcbc.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +"""Train the goal-conditioned BC baseline on cube-double-play-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gcbc + +ENV = "cube-double-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql.py b/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql.py new file mode 100644 index 0000000000000000000000000000000000000000..deffa41cf91fa5d36b91539af59a0cf42b02e6f5 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Train the standard GCIQL baseline (TD critic) on cube-double-play-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql + +ENV = "cube-double-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=500000) + ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=0.3) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql_genq.py b/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql_genq.py new file mode 100644 index 0000000000000000000000000000000000000000..eb99db23388b282e10f59b6551cd7f356ba7a410 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql_genq.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +"""Train GCIQL with the Gen-Q occupancy critic on cube-double-play-v0 (JAX-only, diffusion occupancy). + +Best Gen-Q config for this env (M10 score table; legacy tree removed, see git history): +ddpgbc alpha=0.3 expectile=0.9 n_occ=64 sigma=2.0. +Requires a trained Gen-Q diffusion occupancy ckpt; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env cube-double-play-v0 +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq + +ENV = "cube-double-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=0.3) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--n_occ", type=int, default=64) + ap.add_argument("--sigma", type=float, default=2.0) + ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, sigma=a.sigma, + genq_npz=a.genq_npz, latent_npz=a.latent_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql_genq_recursive.py b/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql_genq_recursive.py new file mode 100644 index 0000000000000000000000000000000000000000..a8343a9c2deec3c24d212fc96c0a11b0a3e7c029 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/cube-double-play-v0/train_gciql_genq_recursive.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on cube-double-play-v0. + +The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric +recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))). +Requires a --state_target short-beta occupancy; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \ + --env cube-double-play-v0 --gamma --state_target \ + --out ogbench_genq/checkpoints/m9_genq_rec_cube_double_play_v0_b.genqjax.npz +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq_recursive + +ENV = "cube-double-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy") + ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion") + ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump") + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=30.0) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--n_occ", type=int, default=16) + ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps, + recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma, + steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, + genq_npz=a.genq_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gcbc.py b/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gcbc.py new file mode 100644 index 0000000000000000000000000000000000000000..707423b58a28147221ca3012cf237dc9c7067cb4 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gcbc.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +"""Train the goal-conditioned BC baseline on cube-single-play-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gcbc + +ENV = "cube-single-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql.py b/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql.py new file mode 100644 index 0000000000000000000000000000000000000000..b4b263a5fdacf05de135424032dbb22ebdaae4f5 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Train the standard GCIQL baseline (TD critic) on cube-single-play-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql + +ENV = "cube-single-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=500000) + ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=0.3) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql_genq.py b/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql_genq.py new file mode 100644 index 0000000000000000000000000000000000000000..8114579d905fbdb659297d129ea38b9c51600033 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql_genq.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +"""Train GCIQL with the Gen-Q occupancy critic on cube-single-play-v0 (JAX-only, diffusion occupancy). + +Best Gen-Q config for this env (results/m10_score_table.md): AWR alpha=30 expectile=0.7. +Requires a trained Gen-Q diffusion occupancy ckpt; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env cube-single-play-v0 +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq + +ENV = "cube-single-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=30.0) + ap.add_argument("--expectile", type=float, default=0.7) + ap.add_argument("--n_occ", type=int, default=64) + ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, genq_npz=a.genq_npz, + latent_npz=a.latent_npz, eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql_genq_recursive.py b/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql_genq_recursive.py new file mode 100644 index 0000000000000000000000000000000000000000..09e62c759b9223a6d7edb2325196a02edd852477 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/cube-single-play-v0/train_gciql_genq_recursive.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python +"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on cube-single-play-v0. + +The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric +recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))). +Requires a --state_target short-beta occupancy; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \ + --env cube-single-play-v0 --gamma --state_target \ + --out ogbench_genq/checkpoints/m9_genq_rec_cube_single_play_v0_b.genqjax.npz +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq_recursive + +ENV = "cube-single-play-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy") + ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion") + ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump") + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=30.0) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--n_occ", type=int, default=16) + ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps, + recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma, + steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, + genq_npz=a.genq_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gcbc.py b/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gcbc.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd8072f23f7985a13cfd1b7699cd9b366b79081 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gcbc.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python +"""Train the goal-conditioned BC baseline on humanoidmaze-medium-navigate-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gcbc + +ENV = "humanoidmaze-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gciql.py b/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gciql.py new file mode 100644 index 0000000000000000000000000000000000000000..aad711c112ebfe64a2d16bacde3e9559861443ce --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gciql.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Train the standard GCIQL baseline (TD critic) on humanoidmaze-medium-navigate-v0 (JAX-only).""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql + +ENV = "humanoidmaze-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=500000) + ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=0.3) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode) diff --git a/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gciql_genq.py b/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gciql_genq.py new file mode 100644 index 0000000000000000000000000000000000000000..0734c1b6dd55dff86adf55124e166d4a31d58648 --- /dev/null +++ b/gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gciql_genq.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +"""Train GCIQL with the Gen-Q occupancy critic on humanoidmaze-medium-navigate-v0 (JAX-only, diffusion occupancy). + +Best Gen-Q config for this env (M10 score table; legacy tree removed, see git history): +awr alpha=30.0 expectile=0.9 n_occ=64 sigma=5.0. +Requires a trained Gen-Q diffusion occupancy ckpt; train it first with: + PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env humanoidmaze-medium-navigate-v0 +""" +import argparse, os, sys +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +from ogbench_genq._runner import run_gciql_genq + +ENV = "humanoidmaze-medium-navigate-v0" + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--seed", type=int, default=0) + ap.add_argument("--train_steps", type=int, default=300000) + ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"]) + ap.add_argument("--alpha", type=float, default=30.0) + ap.add_argument("--expectile", type=float, default=0.9) + ap.add_argument("--n_occ", type=int, default=64) + ap.add_argument("--sigma", type=float, default=5.0) + ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)") + ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)") + ap.add_argument("--eval_episodes", type=int, default=50) + ap.add_argument("--wandb_mode", default="online") + a = ap.parse_args() + run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss, + alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, sigma=a.sigma, + genq_npz=a.genq_npz, latent_npz=a.latent_npz, eval_episodes=a.eval_episodes, + wandb_mode=a.wandb_mode)