rsm_rise code snapshot (HF_PUSH_ALL) (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +6 -0
- gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gciql_genq_recursive.py +37 -0
- gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_gcbc.py +17 -0
- gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_gciql.py +21 -0
- gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_gciql_genq.py +29 -0
- gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_gciql_genq_recursive.py +37 -0
- gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_genq_joint.py +171 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gcbc.py +17 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gciql.py +23 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gciql_ablate.py +66 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gciql_genq.py +51 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gciql_genq_recursive.py +64 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_genq_factored.py +22 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_genq_factored_dp.py +24 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_genq_gliql.py +28 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_genq_joint.py +201 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-4x4-play-v0/train_gcbc.py +17 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-4x4-play-v0/train_gciql.py +21 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-4x4-play-v0/train_gciql_genq.py +32 -0
- gen_q_rsm/ogbench_genq/unused/experiments/puzzle-4x4-play-v0/train_gciql_genq_recursive.py +37 -0
- gen_q_rsm/ogbench_genq/unused/experiments/scene-play-v0/train_gcbc.py +17 -0
- gen_q_rsm/ogbench_genq/unused/experiments/scene-play-v0/train_gciql.py +21 -0
- gen_q_rsm/ogbench_genq/unused/experiments/scene-play-v0/train_gciql_genq.py +32 -0
- gen_q_rsm/ogbench_genq/unused/experiments/scene-play-v0/train_gciql_genq_recursive.py +37 -0
- gen_q_rsm/ogbench_genq/unused/gciql_ablate.py +194 -0
- gen_q_rsm/ogbench_genq/unused/gciql_genq.py +188 -0
- gen_q_rsm/ogbench_genq/unused/genq/genq_discrete_jax.py +230 -0
- gen_q_rsm/ogbench_genq/unused/genq/genq_inpaint_jax.py +76 -0
- gen_q_rsm/ogbench_genq/unused/genq/genq_jax.py +298 -0
- gen_q_rsm/ogbench_genq/unused/genq/genq_recursive_jax.py +243 -0
- gen_q_rsm/ogbench_genq/unused/genq/run_inpaint_eval.py +94 -0
- gen_q_rsm/ogbench_genq/unused/genq_factored.py +175 -0
- gen_q_rsm/ogbench_genq/unused/genq_factored_dp.py +283 -0
- gen_q_rsm/ogbench_genq/unused/genq_gliql.py +174 -0
- gen_q_rsm/ogbench_genq/unused/genq_joint.py +1468 -0
- gen_q_rsm/ogbench_genq/unused/genq_joint_fast.py +1010 -0
- gen_q_rsm/ogbench_genq/unused/goto_variant.gif +3 -0
- gen_q_rsm/ogbench_genq/unused/make_figure.py +74 -0
- gen_q_rsm/ogbench_genq/unused/rsm_graft.py +976 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_a03r500_s225k.sh +10 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_a03r500_s225k_confirm.sh +10 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_antmaze_lg_p427.sh +19 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_antmaze_med_p813.sh +19 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_cube_a3_75k.sh +26 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_cube_officials.sh +26 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_graft_ls_p853.sh +18 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_humanoid_1M_p507.sh +19 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_humanoid_p240.sh +18 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_humanoid_s1_p333.sh +19 -0
- gen_q_rsm/ogbench_genq/unused/scripts/eval_humanoid_s1_p427.sh +19 -0
.gitattributes
CHANGED
|
@@ -66,3 +66,9 @@ gen_q_rsm/ogbench_genq/figures/beta_recursion.gif filter=lfs diff=lfs merge=lfs
|
|
| 66 |
gen_q_rsm/ogbench_genq/figures/fig_actor.png filter=lfs diff=lfs merge=lfs -text
|
| 67 |
gen_q_rsm/ogbench_genq/figures/fig_occupancy.png filter=lfs diff=lfs merge=lfs -text
|
| 68 |
gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.png filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
gen_q_rsm/ogbench_genq/figures/fig_actor.png filter=lfs diff=lfs merge=lfs -text
|
| 67 |
gen_q_rsm/ogbench_genq/figures/fig_occupancy.png filter=lfs diff=lfs merge=lfs -text
|
| 68 |
gen_q_rsm/ogbench_genq/figures/visual_rsm_reader_metric.png filter=lfs diff=lfs merge=lfs -text
|
| 69 |
+
gen_q_rsm/ogbench_genq/unused/goto_variant.gif filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
gen_q_rsm/plans/genq-plan.pdf filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
gen_q_rsm/preliminary_analysis/experiments/antmaze_large_navigate_v0/figures/illustration.gif filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
gen_q_rsm/preliminary_analysis/experiments/antmaze_medium_navigate_v0/figures/illustration.gif filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
gen_q_rsm/preliminary_analysis/experiments/pointmaze_large_navigate_v0/figures/illustration.gif filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
gen_q_rsm/preliminary_analysis/experiments/pointmaze_medium_navigate_v0/figures/illustration.gif filter=lfs diff=lfs merge=lfs -text
|
gen_q_rsm/ogbench_genq/unused/experiments/humanoidmaze-medium-navigate-v0/train_gciql_genq_recursive.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on humanoidmaze-medium-navigate-v0.
|
| 3 |
+
|
| 4 |
+
The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric
|
| 5 |
+
recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))).
|
| 6 |
+
Requires a --state_target short-beta occupancy; train it first with:
|
| 7 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \
|
| 8 |
+
--env humanoidmaze-medium-navigate-v0 --gamma <beta> --state_target \
|
| 9 |
+
--out ogbench_genq/checkpoints/m9_genq_rec_humanoidmaze_medium_navigate_v0_b<tag>.genqjax.npz
|
| 10 |
+
"""
|
| 11 |
+
import argparse, os, sys
|
| 12 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 13 |
+
from ogbench_genq._runner import run_gciql_genq_recursive
|
| 14 |
+
|
| 15 |
+
ENV = "humanoidmaze-medium-navigate-v0"
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 20 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 21 |
+
ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy")
|
| 22 |
+
ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion")
|
| 23 |
+
ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump")
|
| 24 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 25 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 26 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 27 |
+
ap.add_argument("--n_occ", type=int, default=16)
|
| 28 |
+
ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)")
|
| 29 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 30 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 31 |
+
a = ap.parse_args()
|
| 32 |
+
run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps,
|
| 33 |
+
recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma,
|
| 34 |
+
steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss,
|
| 35 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ,
|
| 36 |
+
genq_npz=a.genq_npz, eval_episodes=a.eval_episodes,
|
| 37 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_gcbc.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train the goal-conditioned BC baseline on pointmaze-medium-navigate-v0 (JAX-only)."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq._runner import run_gcbc
|
| 6 |
+
|
| 7 |
+
ENV = "pointmaze-medium-navigate-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 13 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 14 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 15 |
+
a = ap.parse_args()
|
| 16 |
+
run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes,
|
| 17 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_gciql.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train the standard GCIQL baseline (TD critic) on pointmaze-medium-navigate-v0 (JAX-only)."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq._runner import run_gciql
|
| 6 |
+
|
| 7 |
+
ENV = "pointmaze-medium-navigate-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=500000)
|
| 13 |
+
ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"])
|
| 14 |
+
ap.add_argument("--alpha", type=float, default=0.3)
|
| 15 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 16 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 17 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 18 |
+
a = ap.parse_args()
|
| 19 |
+
run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 20 |
+
alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes,
|
| 21 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_gciql_genq.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the Gen-Q occupancy critic on pointmaze-medium-navigate-v0 (JAX-only, diffusion occupancy).
|
| 3 |
+
|
| 4 |
+
Best Gen-Q config for this env (results/m10_score_table.md): AWR alpha=30 expectile=0.9.
|
| 5 |
+
Requires a trained Gen-Q diffusion occupancy ckpt; train it first with:
|
| 6 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env pointmaze-medium-navigate-v0
|
| 7 |
+
"""
|
| 8 |
+
import argparse, os, sys
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 10 |
+
from ogbench_genq._runner import run_gciql_genq
|
| 11 |
+
|
| 12 |
+
ENV = "pointmaze-medium-navigate-v0"
|
| 13 |
+
|
| 14 |
+
if __name__ == "__main__":
|
| 15 |
+
ap = argparse.ArgumentParser()
|
| 16 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 17 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 18 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 19 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 20 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 21 |
+
ap.add_argument("--n_occ", type=int, default=64)
|
| 22 |
+
ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)")
|
| 23 |
+
ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)")
|
| 24 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 25 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 26 |
+
a = ap.parse_args()
|
| 27 |
+
run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 28 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, genq_npz=a.genq_npz,
|
| 29 |
+
latent_npz=a.latent_npz, eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_gciql_genq_recursive.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on pointmaze-medium-navigate-v0.
|
| 3 |
+
|
| 4 |
+
The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric
|
| 5 |
+
recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))).
|
| 6 |
+
Requires a --state_target short-beta occupancy; train it first with:
|
| 7 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \
|
| 8 |
+
--env pointmaze-medium-navigate-v0 --gamma <beta> --state_target \
|
| 9 |
+
--out ogbench_genq/checkpoints/m9_genq_rec_pointmaze_medium_navigate_v0_b<tag>.genqjax.npz
|
| 10 |
+
"""
|
| 11 |
+
import argparse, os, sys
|
| 12 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 13 |
+
from ogbench_genq._runner import run_gciql_genq_recursive
|
| 14 |
+
|
| 15 |
+
ENV = "pointmaze-medium-navigate-v0"
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 20 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 21 |
+
ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy")
|
| 22 |
+
ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion")
|
| 23 |
+
ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump")
|
| 24 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 25 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 26 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 27 |
+
ap.add_argument("--n_occ", type=int, default=16)
|
| 28 |
+
ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)")
|
| 29 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 30 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 31 |
+
a = ap.parse_args()
|
| 32 |
+
run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps,
|
| 33 |
+
recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma,
|
| 34 |
+
steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss,
|
| 35 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ,
|
| 36 |
+
genq_npz=a.genq_npz, eval_episodes=a.eval_episodes,
|
| 37 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/pointmaze-medium-navigate-v0/train_genq_joint.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""JOINT Gen-Q policy iteration on pointmaze-medium-navigate-v0: occupancy + critic + V + actor in one
|
| 3 |
+
loop (no TD, no staging). See ogbench_genq/genq_joint.py."""
|
| 4 |
+
import argparse, os, sys
|
| 5 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 6 |
+
from ogbench_genq.genq_joint import run_genq_joint
|
| 7 |
+
|
| 8 |
+
ENV = "pointmaze-medium-navigate-v0"
|
| 9 |
+
|
| 10 |
+
if __name__ == "__main__":
|
| 11 |
+
ap = argparse.ArgumentParser()
|
| 12 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 13 |
+
ap.add_argument("--train_steps", type=int, default=500000)
|
| 14 |
+
ap.add_argument("--alpha", type=float, default=1.0)
|
| 15 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 16 |
+
ap.add_argument("--rt_eta", type=float, default=0.5)
|
| 17 |
+
ap.add_argument("--pi_alpha", type=float, default=1.0)
|
| 18 |
+
ap.add_argument("--pi_horizon", type=int, default=25)
|
| 19 |
+
ap.add_argument("--occ_warmup", type=int, default=50000)
|
| 20 |
+
ap.add_argument("--occ_tau", type=float, default=0.005)
|
| 21 |
+
ap.add_argument("--n_orders", type=int, default=16)
|
| 22 |
+
ap.add_argument("--extraction", default="r3",
|
| 23 |
+
choices=["r3", "gliql", "ddpg2", "awr2"])
|
| 24 |
+
ap.add_argument("--gliql_alpha", type=float, default=3.0)
|
| 25 |
+
ap.add_argument("--awr_alpha", type=float, default=3.0,
|
| 26 |
+
help="awr2 temperature on the batch-std-normalized log-gl "
|
| 27 |
+
"advantage (forward-only actor loss; host path only)")
|
| 28 |
+
ap.add_argument("--occ_warmstart_npz", default=None)
|
| 29 |
+
ap.add_argument("--eval_interval", type=int, default=25000)
|
| 30 |
+
ap.add_argument("--variant_tag", default=None)
|
| 31 |
+
ap.add_argument("--save_agent", default=None)
|
| 32 |
+
ap.add_argument("--save_occ", default=None,
|
| 33 |
+
help="save the co-trained occupancy EMA as a warm-start-format "
|
| 34 |
+
"npz (input for eval_plan.py test-time planning)")
|
| 35 |
+
ap.add_argument("--save_best", default=None,
|
| 36 |
+
help="fast path: pickle the banked best snapshot to this path "
|
| 37 |
+
"every time it improves, so it can be 50-ep evaluated "
|
| 38 |
+
"offline mid-run")
|
| 39 |
+
ap.add_argument("--rec_target", type=int, default=0,
|
| 40 |
+
help="RECURSIVE PREDICTION: M occupancy-sampled midpoints; r3 composes "
|
| 41 |
+
"critic targets, ddpg2 composes the actor loss through gl jumps")
|
| 42 |
+
ap.add_argument("--rec_every", type=int, default=2)
|
| 43 |
+
ap.add_argument("--rec_eps", type=float, default=0.5)
|
| 44 |
+
ap.add_argument("--rec_after", type=int, default=100000)
|
| 45 |
+
ap.add_argument("--rec_beta", type=float, default=0.0,
|
| 46 |
+
help="beta-recursive rule: stochastic recursion depth, continue "
|
| 47 |
+
"w.p. p=(gamma-beta)/(gamma*(1-beta)); 0 = fixed depth-1")
|
| 48 |
+
ap.add_argument("--rec_max_depth", type=int, default=6)
|
| 49 |
+
ap.add_argument("--rec_prob", action="store_true",
|
| 50 |
+
help="probabilistic beta-jump Q estimator (splitting identity, "
|
| 51 |
+
"expectation instead of max-certificates; needs rec_free+rec_beta)")
|
| 52 |
+
ap.add_argument("--rec_pess", type=int, default=1,
|
| 53 |
+
help="pessimism at generated midpoints: value = min over K "
|
| 54 |
+
"independent completion draws (1 = off)")
|
| 55 |
+
ap.add_argument("--gamma_spectrum_lo", type=float, default=0.0,
|
| 56 |
+
help="train the occupancy CONDITIONED on the discount, sampled "
|
| 57 |
+
"log-uniform-in-horizon in [lo, gamma] (0 = fixed gamma). "
|
| 58 |
+
"PI gl reads at task gamma; recursion hops at rec_beta.")
|
| 59 |
+
ap.add_argument("--gamma_spectrum_p", type=float, default=0.5)
|
| 60 |
+
ap.add_argument("--gamma_encoding", default="scalar",
|
| 61 |
+
choices=["scalar", "onehot2", "fourier"],
|
| 62 |
+
help="how the discount enters the conditioning (fast path). "
|
| 63 |
+
"scalar = raw gamma column (original; under-resolved by "
|
| 64 |
+
"the MLP). onehot2 = discrete which-measure indicator over "
|
| 65 |
+
"{task gamma, beta} — no interpolation burden; needs "
|
| 66 |
+
"--rec_beta")
|
| 67 |
+
ap.add_argument("--readout", default="gl", choices=["gl", "sample", "elbo"],
|
| 68 |
+
help="Q read-out (fast path). gl = exact any-order likelihood "
|
| 69 |
+
"from the masked DISCRETE occupancy (finite goal alphabets "
|
| 70 |
+
"only). sample = kernel Monte-Carlo over pathwise DDIM "
|
| 71 |
+
"samples from a CONTINUOUS occupancy — no likelihood "
|
| 72 |
+
"anywhere. elbo = diffusion-classifier ELBO surrogate: "
|
| 73 |
+
"denoising loss AT the goal point, Q=exp(-elbo_c*loss) — "
|
| 74 |
+
"point evaluation like gl, any goal space like sample "
|
| 75 |
+
"(owner directive 2026-07-15)")
|
| 76 |
+
ap.add_argument("--elbo_c", type=float, default=1.0,
|
| 77 |
+
help="elbo readout: temperature on the denoising loss")
|
| 78 |
+
ap.add_argument("--elbo_pess", type=float, default=0.0,
|
| 79 |
+
help="RSM stability: uncertainty-penalized ELBO — Q = "
|
| 80 |
+
"exp(-c*(mean + pess*std)) over the K draws")
|
| 81 |
+
ap.add_argument("--alpha_ramp", type=int, default=0,
|
| 82 |
+
help="RSM stability: anneal the BC weight 1.0 -> alpha "
|
| 83 |
+
"over this many steps (0 = static alpha)")
|
| 84 |
+
ap.add_argument("--ker_K", type=int, default=16,
|
| 85 |
+
help="sample readout: samples per Q estimate (targets/eval)")
|
| 86 |
+
ap.add_argument("--ker_sharp", type=float, default=8.0,
|
| 87 |
+
help="sample readout: kernel sharpness (puzzle: per-bit "
|
| 88 |
+
"sigmoid match; continuous envs: edge softness of the "
|
| 89 |
+
"smoothed eps-ball)")
|
| 90 |
+
ap.add_argument("--ker_eps", type=float, default=0.5,
|
| 91 |
+
help="sample readout, continuous envs: the env's success "
|
| 92 |
+
"radius (OGBench pointmaze: 1.0; ant/humanoid maze: 0.5)")
|
| 93 |
+
ap.add_argument("--gamma_fourier_k", type=int, default=4,
|
| 94 |
+
help="fourier encoding: number of sin/cos frequency pairs over "
|
| 95 |
+
"normalized log-horizon (fast path; default 4)")
|
| 96 |
+
ap.add_argument("--occ_hidden", type=int, default=256,
|
| 97 |
+
help="occupancy/completion trunk width (fast path)")
|
| 98 |
+
ap.add_argument("--occ_lr", type=float, default=3e-4,
|
| 99 |
+
help="occupancy learning rate (fast path)")
|
| 100 |
+
ap.add_argument("--rec_free", action="store_true",
|
| 101 |
+
help="retrieval-free midpoints: full-state completion head, "
|
| 102 |
+
"live-actor midpoint actions (no eps-grid, no lookup)")
|
| 103 |
+
ap.add_argument("--actor_ema_tau", type=float, default=0.0,
|
| 104 |
+
help="Polyak EMA of the actor, evaluated alongside the live actor each "
|
| 105 |
+
"periodic eval (late-band stabilizer; best-ckpt picks the winner)")
|
| 106 |
+
ap.add_argument("--fast", action="store_true",
|
| 107 |
+
help="fused on-device train step + lax.scan (plain r3/ddpg2 only; "
|
| 108 |
+
"no rec_target/gliql)")
|
| 109 |
+
ap.add_argument("--steps_per_dispatch", type=int, default=100)
|
| 110 |
+
ap.add_argument("--data_parallel", action="store_true",
|
| 111 |
+
help="pmap the fused train step over all local devices (fast path "
|
| 112 |
+
"only): per-device batch = batch/D, grads pmean'd, global "
|
| 113 |
+
"batch semantics preserved")
|
| 114 |
+
ap.add_argument("--batch_size", type=int, default=0,
|
| 115 |
+
help="override PI batch size (fast path; 0 = reference 1024)")
|
| 116 |
+
ap.add_argument("--occ_batch", type=int, default=256)
|
| 117 |
+
ap.add_argument("--n_orders_pi", type=int, default=0,
|
| 118 |
+
help="order count for the differentiated actor-loss gl calls "
|
| 119 |
+
"(fast path; 0 = full n_orders). Large batch absorbs the "
|
| 120 |
+
"extra per-state read-out noise")
|
| 121 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 122 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 123 |
+
a = ap.parse_args()
|
| 124 |
+
assert not (a.data_parallel and not a.fast), "--data_parallel requires --fast"
|
| 125 |
+
if a.fast:
|
| 126 |
+
from ogbench_genq.genq_joint_fast import run_genq_joint_fast
|
| 127 |
+
assert a.extraction in ("r3", "ddpg2")
|
| 128 |
+
assert not (a.rec_target > 0 and not a.rec_free), \
|
| 129 |
+
"fast recursion is retrieval-free only"
|
| 130 |
+
run_genq_joint_fast(ENV, seed=a.seed, train_steps=a.train_steps, alpha=a.alpha,
|
| 131 |
+
expectile=a.expectile, rt_eta=a.rt_eta, pi_alpha=a.pi_alpha,
|
| 132 |
+
pi_horizon=a.pi_horizon, occ_warmup=a.occ_warmup,
|
| 133 |
+
occ_tau=a.occ_tau, n_orders=a.n_orders,
|
| 134 |
+
extraction=a.extraction,
|
| 135 |
+
occ_warmstart_npz=a.occ_warmstart_npz,
|
| 136 |
+
eval_interval=a.eval_interval, variant_tag=a.variant_tag,
|
| 137 |
+
save_agent=a.save_agent, save_occ=a.save_occ,
|
| 138 |
+
save_best=a.save_best, n_orders_pi=a.n_orders_pi,
|
| 139 |
+
actor_ema_tau=a.actor_ema_tau,
|
| 140 |
+
steps_per_dispatch=a.steps_per_dispatch,
|
| 141 |
+
batch_size=a.batch_size, occ_batch=a.occ_batch,
|
| 142 |
+
rec_target=a.rec_target, rec_every=a.rec_every,
|
| 143 |
+
rec_after=a.rec_after, rec_beta=a.rec_beta,
|
| 144 |
+
rec_max_depth=a.rec_max_depth, rec_prob=a.rec_prob,
|
| 145 |
+
gamma_spectrum_lo=a.gamma_spectrum_lo,
|
| 146 |
+
gamma_spectrum_p=a.gamma_spectrum_p,
|
| 147 |
+
gamma_encoding=a.gamma_encoding,
|
| 148 |
+
gamma_fourier_k=a.gamma_fourier_k,
|
| 149 |
+
readout=a.readout, ker_K=a.ker_K, ker_sharp=a.ker_sharp,
|
| 150 |
+
ker_eps=a.ker_eps, elbo_c=a.elbo_c,
|
| 151 |
+
elbo_pess=a.elbo_pess, alpha_ramp=a.alpha_ramp,
|
| 152 |
+
occ_hidden=a.occ_hidden, occ_lr=a.occ_lr,
|
| 153 |
+
data_parallel=a.data_parallel,
|
| 154 |
+
eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
| 155 |
+
raise SystemExit(0)
|
| 156 |
+
run_genq_joint(ENV, seed=a.seed, train_steps=a.train_steps, alpha=a.alpha,
|
| 157 |
+
expectile=a.expectile, rt_eta=a.rt_eta, pi_alpha=a.pi_alpha,
|
| 158 |
+
pi_horizon=a.pi_horizon, occ_warmup=a.occ_warmup, occ_tau=a.occ_tau,
|
| 159 |
+
n_orders=a.n_orders, extraction=a.extraction,
|
| 160 |
+
gliql_alpha=a.gliql_alpha, awr_alpha=a.awr_alpha,
|
| 161 |
+
occ_warmstart_npz=a.occ_warmstart_npz,
|
| 162 |
+
eval_interval=a.eval_interval,
|
| 163 |
+
variant_tag=a.variant_tag, save_agent=a.save_agent,
|
| 164 |
+
save_occ=a.save_occ,
|
| 165 |
+
actor_ema_tau=a.actor_ema_tau,
|
| 166 |
+
rec_target=a.rec_target, rec_every=a.rec_every, rec_eps=a.rec_eps,
|
| 167 |
+
rec_after=a.rec_after, rec_free=a.rec_free,
|
| 168 |
+
rec_beta=a.rec_beta, rec_max_depth=a.rec_max_depth, rec_pess=a.rec_pess,
|
| 169 |
+
rec_prob=a.rec_prob,
|
| 170 |
+
gamma_spectrum_lo=a.gamma_spectrum_lo, gamma_spectrum_p=a.gamma_spectrum_p,
|
| 171 |
+
eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gcbc.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train the goal-conditioned BC baseline on puzzle-3x3-play-v0 (JAX-only)."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq._runner import run_gcbc
|
| 6 |
+
|
| 7 |
+
ENV = "puzzle-3x3-play-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 13 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 14 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 15 |
+
a = ap.parse_args()
|
| 16 |
+
run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes,
|
| 17 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gciql.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train the standard GCIQL baseline (TD critic) on puzzle-3x3-play-v0 (JAX-only)."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq._runner import run_gciql
|
| 6 |
+
|
| 7 |
+
ENV = "puzzle-3x3-play-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=500000)
|
| 13 |
+
ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"])
|
| 14 |
+
ap.add_argument("--alpha", type=float, default=0.3)
|
| 15 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 16 |
+
ap.add_argument("--variant_tag", default=None, help="suffix for the result JSON / wandb name (hparam sweeps)")
|
| 17 |
+
ap.add_argument("--save_agent", default=None, help="pickle the trained network params (Q-comparison diag)")
|
| 18 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 19 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 20 |
+
a = ap.parse_args()
|
| 21 |
+
run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 22 |
+
alpha=a.alpha, expectile=a.expectile, variant_tag=a.variant_tag,
|
| 23 |
+
save_agent=a.save_agent, eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gciql_ablate.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""GCIQL -> GenQ component ablation on puzzle-3x3-play-v0 (issue #57).
|
| 3 |
+
|
| 4 |
+
Rungs (reference puzzle recipe: ddpgbc alpha=1.0, everything else reference defaults):
|
| 5 |
+
R0: -- reference GCIQL (distilled Gen-Q critic trained, unused)
|
| 6 |
+
R1: --genq_actor actor's Q source = distilled Gen-Q critic
|
| 7 |
+
R2: --genq_value expectile-V source = distilled Gen-Q critic
|
| 8 |
+
R3: --genq_actor --genq_value fully TD-free value path
|
| 9 |
+
"""
|
| 10 |
+
import argparse, os, sys
|
| 11 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 12 |
+
from ogbench_genq._runner import run_gciql_ablate
|
| 13 |
+
|
| 14 |
+
ENV = "puzzle-3x3-play-v0"
|
| 15 |
+
|
| 16 |
+
if __name__ == "__main__":
|
| 17 |
+
ap = argparse.ArgumentParser()
|
| 18 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 19 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 20 |
+
ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"])
|
| 21 |
+
ap.add_argument("--alpha", type=float, default=1.0, help="reference puzzle GCIQL: ddpgbc alpha=1.0")
|
| 22 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 23 |
+
ap.add_argument("--genq_actor", action="store_true")
|
| 24 |
+
ap.add_argument("--genq_value", action="store_true")
|
| 25 |
+
ap.add_argument("--adv_norm", action="store_true", help="standardize AWR advantage per batch")
|
| 26 |
+
ap.add_argument("--n_occ", type=int, default=64)
|
| 27 |
+
ap.add_argument("--sigma", type=float, default=None)
|
| 28 |
+
ap.add_argument("--readout_tau", type=float, default=0.0)
|
| 29 |
+
ap.add_argument("--readout", default="sample", choices=["sample", "gl"],
|
| 30 |
+
help="gl = goal-likelihood (reward-target IS): P(x=g) by teacher-forced unmasking")
|
| 31 |
+
ap.add_argument("--genq_npz", default=None)
|
| 32 |
+
ap.add_argument("--rec_target", type=int, default=0,
|
| 33 |
+
help="RECURSION AT TRAINING TIME: M occupancy-sampled midpoints per tuple; "
|
| 34 |
+
"critic target = max(gl, agg_m[gl(s,a,c_m) * min Q_ema(c_m, g)])")
|
| 35 |
+
ap.add_argument("--rec_agg", default="max", choices=["max", "mean"])
|
| 36 |
+
ap.add_argument("--rec_after", type=int, default=10000,
|
| 37 |
+
help="start composing targets after this step (EMA critic needs warmup)")
|
| 38 |
+
ap.add_argument("--rec_steps", type=int, default=None,
|
| 39 |
+
help="denoising steps for midpoint sampling (owner hypothesis: more steps "
|
| 40 |
+
"= less OOD midpoints); None = checkpoint default")
|
| 41 |
+
ap.add_argument("--rec_eps", type=float, default=0.5,
|
| 42 |
+
help="eps-grid junction tolerance for midpoint retrieval (std units)")
|
| 43 |
+
ap.add_argument("--rec_every", type=int, default=2,
|
| 44 |
+
help="compose targets on every k-th step (throughput; EMA critic "
|
| 45 |
+
"averages composed targets in regardless)")
|
| 46 |
+
ap.add_argument("--rec_actor", action="store_true",
|
| 47 |
+
help="also compose actor-goal targets (2x composition cost; actor "
|
| 48 |
+
"goals are mostly in-trajectory where recursion adds least)")
|
| 49 |
+
ap.add_argument("--eval_interval", type=int, default=20000)
|
| 50 |
+
ap.add_argument("--variant_tag", default=None)
|
| 51 |
+
ap.add_argument("--save_agent", default=None)
|
| 52 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 53 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 54 |
+
a = ap.parse_args()
|
| 55 |
+
run_gciql_ablate(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 56 |
+
alpha=a.alpha, expectile=a.expectile, adv_norm=a.adv_norm,
|
| 57 |
+
genq_actor=a.genq_actor,
|
| 58 |
+
genq_value=a.genq_value, n_occ=a.n_occ, sigma=a.sigma,
|
| 59 |
+
readout_tau=a.readout_tau, readout=a.readout,
|
| 60 |
+
genq_npz=a.genq_npz,
|
| 61 |
+
rec_target=a.rec_target, rec_agg=a.rec_agg, rec_after=a.rec_after,
|
| 62 |
+
rec_steps=a.rec_steps, rec_eps=a.rec_eps, rec_every=a.rec_every,
|
| 63 |
+
rec_actor=a.rec_actor,
|
| 64 |
+
eval_interval=a.eval_interval, variant_tag=a.variant_tag,
|
| 65 |
+
save_agent=a.save_agent, eval_episodes=a.eval_episodes,
|
| 66 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gciql_genq.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the Gen-Q occupancy critic on puzzle-3x3-play-v0 (JAX-only, diffusion occupancy).
|
| 3 |
+
|
| 4 |
+
Best Gen-Q config for this env (results/m10_score_table.md): AWR alpha=30 expectile=0.9.
|
| 5 |
+
Requires a trained Gen-Q diffusion occupancy ckpt; train it first with:
|
| 6 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env puzzle-3x3-play-v0
|
| 7 |
+
"""
|
| 8 |
+
import argparse, os, sys
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 10 |
+
from ogbench_genq._runner import run_gciql_genq
|
| 11 |
+
|
| 12 |
+
ENV = "puzzle-3x3-play-v0"
|
| 13 |
+
|
| 14 |
+
if __name__ == "__main__":
|
| 15 |
+
ap = argparse.ArgumentParser()
|
| 16 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 17 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 18 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 19 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 20 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 21 |
+
ap.add_argument("--n_occ", type=int, default=64)
|
| 22 |
+
ap.add_argument("--sigma", type=float, default=None, help="Gen-Q read-out bandwidth (default: SIGMA_BY_ENV)")
|
| 23 |
+
ap.add_argument("--adv_norm", action="store_true", help="standardize the AWR advantage per batch (alpha becomes scale-free)")
|
| 24 |
+
ap.add_argument("--q_filter_k", type=int, default=0, help="if >0, eval with deployment-time Q-filter: argmax Gen-Q Q over K actor proposals")
|
| 25 |
+
ap.add_argument("--actor_geom", action="store_true", help="geometric (near-horizon) actor goals instead of uniform-future")
|
| 26 |
+
ap.add_argument("--readout_tau", type=float, default=0.0,
|
| 27 |
+
help="if >0, optimistic tau-expectile read-out of r under the occupancy instead of the mean "
|
| 28 |
+
"(tau->1 ~ best behavior-consistent future; TD-free improvement operator)")
|
| 29 |
+
ap.add_argument("--genq_discrete_npz", default=None,
|
| 30 |
+
help="exact discrete categorical occupancy ckpt (genq/genq_discrete_jax.py); replaces the diffusion sampler")
|
| 31 |
+
ap.add_argument("--target_variant", default="default",
|
| 32 |
+
help="occupancy target variant (bits_eff | full); needs an occupancy trained with the same variant")
|
| 33 |
+
ap.add_argument("--sigma_aux", type=float, default=2.0,
|
| 34 |
+
help="read-out sigma for non-bit target dims under a target_variant")
|
| 35 |
+
ap.add_argument("--readout_steps", type=int, default=None,
|
| 36 |
+
help="denoising steps at read-out (default: ckpt's sample_steps, 30)")
|
| 37 |
+
ap.add_argument("--eval_interval", type=int, default=20000) # frequent evals (owner ask): peaks land at 100-200k, 50k grid missed them
|
| 38 |
+
ap.add_argument("--variant_tag", default=None, help="suffix for the result JSON / wandb name (hparam sweeps)")
|
| 39 |
+
ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)")
|
| 40 |
+
ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)")
|
| 41 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 42 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 43 |
+
a = ap.parse_args()
|
| 44 |
+
run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 45 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, sigma=a.sigma,
|
| 46 |
+
variant_tag=a.variant_tag, adv_norm=a.adv_norm, q_filter_k=a.q_filter_k,
|
| 47 |
+
actor_geom_sample=a.actor_geom, readout_tau=a.readout_tau,
|
| 48 |
+
genq_discrete_npz=a.genq_discrete_npz, target_variant=a.target_variant,
|
| 49 |
+
sigma_aux=a.sigma_aux, readout_steps=a.readout_steps,
|
| 50 |
+
eval_interval=a.eval_interval, genq_npz=a.genq_npz,
|
| 51 |
+
latent_npz=a.latent_npz, eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_gciql_genq_recursive.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on puzzle-3x3-play-v0.
|
| 3 |
+
|
| 4 |
+
The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric
|
| 5 |
+
recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))).
|
| 6 |
+
Requires a --state_target short-beta occupancy; train it first with:
|
| 7 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \
|
| 8 |
+
--env puzzle-3x3-play-v0 --gamma <beta> --state_target \
|
| 9 |
+
--out ogbench_genq/checkpoints/m9_genq_rec_puzzle_3x3_play_v0_b<tag>.genqjax.npz
|
| 10 |
+
"""
|
| 11 |
+
import argparse, os, sys
|
| 12 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 13 |
+
from ogbench_genq._runner import run_gciql_genq_recursive
|
| 14 |
+
|
| 15 |
+
ENV = "puzzle-3x3-play-v0"
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 20 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 21 |
+
ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy")
|
| 22 |
+
ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion")
|
| 23 |
+
ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump")
|
| 24 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 25 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 26 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 27 |
+
ap.add_argument("--n_occ", type=int, default=16)
|
| 28 |
+
ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)")
|
| 29 |
+
ap.add_argument("--greedy_k", type=int, default=0,
|
| 30 |
+
help="if >0, each midpoint is a GREEDY improvement step: argmax of the short-beta "
|
| 31 |
+
"occupancy Q over K candidate actions (approximate value iteration, no TD)")
|
| 32 |
+
ap.add_argument("--greedy_n_occ", type=int, default=2,
|
| 33 |
+
help="occupancy samples per greedy candidate score (wall-clock knob)")
|
| 34 |
+
ap.add_argument("--midpoint_awr_alpha", type=float, default=0.0,
|
| 35 |
+
help="if >0, weight the midpoint BC by exp(alpha * normalized short-beta advantage) "
|
| 36 |
+
"(improved midpoint policy -> composed occupancy approximates d_gamma of the "
|
| 37 |
+
"improved policy; soft policy iteration, no TD)")
|
| 38 |
+
ap.add_argument("--adv_norm", action="store_true",
|
| 39 |
+
help="standardize the AWR advantage per batch (alpha becomes scale-free)")
|
| 40 |
+
ap.add_argument("--readout_tau", type=float, default=0.0,
|
| 41 |
+
help="if >0, optimistic tau-expectile read-out over the composed endpoints "
|
| 42 |
+
"instead of the mean (with greedy_k: optimism over futures on top of "
|
| 43 |
+
"greedy midpoints — the full TD-free improvement stack)")
|
| 44 |
+
ap.add_argument("--target_variant", default="default",
|
| 45 |
+
help="state==target variant (bits_eff recommended: keeps the effector in the "
|
| 46 |
+
"chain conditioning, softening the arm-marginalization of bits-only)")
|
| 47 |
+
ap.add_argument("--sigma_aux", type=float, default=2.0,
|
| 48 |
+
help="read-out sigma for non-bit target dims under a target_variant")
|
| 49 |
+
ap.add_argument("--eval_interval", type=int, default=20000)
|
| 50 |
+
ap.add_argument("--variant_tag", default=None, help="suffix for the result JSON / wandb name (hparam sweeps)")
|
| 51 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 52 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 53 |
+
a = ap.parse_args()
|
| 54 |
+
run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps,
|
| 55 |
+
recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma,
|
| 56 |
+
steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss,
|
| 57 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ,
|
| 58 |
+
genq_npz=a.genq_npz, midpoint_awr_alpha=a.midpoint_awr_alpha,
|
| 59 |
+
greedy_k=a.greedy_k, greedy_n_occ=a.greedy_n_occ,
|
| 60 |
+
variant_tag=a.variant_tag,
|
| 61 |
+
adv_norm=a.adv_norm, readout_tau=a.readout_tau,
|
| 62 |
+
target_variant=a.target_variant, sigma_aux=a.sigma_aux,
|
| 63 |
+
eval_interval=a.eval_interval,
|
| 64 |
+
eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_genq_factored.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""FACTORED Gen-Q on puzzle-3x3: pi_plus(a|s,g) ~ pi_beta(a|s,g) * P(x=g|s,a,g)^kappa.
|
| 3 |
+
Two models (BC head + frozen occupancy); improvement is a training-free tilted read-out."""
|
| 4 |
+
import argparse, os, sys
|
| 5 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 6 |
+
from ogbench_genq.genq_factored import run_genq_factored
|
| 7 |
+
|
| 8 |
+
ENV = "puzzle-3x3-play-v0"
|
| 9 |
+
|
| 10 |
+
if __name__ == "__main__":
|
| 11 |
+
ap = argparse.ArgumentParser()
|
| 12 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 13 |
+
ap.add_argument("--bc_steps", type=int, default=200000)
|
| 14 |
+
ap.add_argument("--genq_npz", default=None)
|
| 15 |
+
ap.add_argument("--n_orders", type=int, default=16)
|
| 16 |
+
ap.add_argument("--variant_tag", default=None)
|
| 17 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 18 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 19 |
+
a = ap.parse_args()
|
| 20 |
+
run_genq_factored(ENV, seed=a.seed, bc_steps=a.bc_steps, genq_npz=a.genq_npz,
|
| 21 |
+
n_orders=a.n_orders, variant_tag=a.variant_tag,
|
| 22 |
+
eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_genq_factored_dp.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Factored Gen-Q + lattice value iteration (explicit stitching) on puzzle-3x3."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq.genq_factored_dp import run_genq_factored_dp
|
| 6 |
+
|
| 7 |
+
ENV = "puzzle-3x3-play-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--bc_steps", type=int, default=200000)
|
| 13 |
+
ap.add_argument("--genq_npz", default=None)
|
| 14 |
+
ap.add_argument("--n_orders", type=int, default=16)
|
| 15 |
+
ap.add_argument("--edge_samples", type=int, default=6)
|
| 16 |
+
ap.add_argument("--max_hop_frames", type=int, default=120)
|
| 17 |
+
ap.add_argument("--variant_tag", default=None)
|
| 18 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 19 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 20 |
+
a = ap.parse_args()
|
| 21 |
+
run_genq_factored_dp(ENV, seed=a.seed, bc_steps=a.bc_steps, genq_npz=a.genq_npz,
|
| 22 |
+
n_orders=a.n_orders, edge_samples=a.edge_samples,
|
| 23 |
+
max_hop_frames=a.max_hop_frames, variant_tag=a.variant_tag,
|
| 24 |
+
eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_genq_gliql.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""gl-IQL on puzzle-3x3: IQL with Q = log P(x=g|s,a,g) read directly from the occupancy."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq.genq_gliql import run_genq_gliql
|
| 6 |
+
|
| 7 |
+
ENV = "puzzle-3x3-play-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=500000)
|
| 13 |
+
ap.add_argument("--alpha", type=float, default=3.0)
|
| 14 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 15 |
+
ap.add_argument("--no_adv_norm", action="store_true")
|
| 16 |
+
ap.add_argument("--n_orders", type=int, default=16)
|
| 17 |
+
ap.add_argument("--genq_npz", default=None)
|
| 18 |
+
ap.add_argument("--eval_interval", type=int, default=25000)
|
| 19 |
+
ap.add_argument("--variant_tag", default=None)
|
| 20 |
+
ap.add_argument("--save_agent", default=None)
|
| 21 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 22 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 23 |
+
a = ap.parse_args()
|
| 24 |
+
run_genq_gliql(ENV, seed=a.seed, train_steps=a.train_steps, alpha=a.alpha,
|
| 25 |
+
expectile=a.expectile, adv_norm=not a.no_adv_norm, n_orders=a.n_orders,
|
| 26 |
+
genq_npz=a.genq_npz, eval_interval=a.eval_interval,
|
| 27 |
+
variant_tag=a.variant_tag, save_agent=a.save_agent,
|
| 28 |
+
eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-3x3-play-v0/train_genq_joint.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""JOINT Gen-Q policy iteration on puzzle-3x3-play-v0: occupancy + critic + V + actor in one
|
| 3 |
+
loop (no TD, no staging). See ogbench_genq/genq_joint.py."""
|
| 4 |
+
import argparse, os, sys
|
| 5 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 6 |
+
from ogbench_genq.genq_joint import run_genq_joint
|
| 7 |
+
|
| 8 |
+
ENV = "puzzle-3x3-play-v0"
|
| 9 |
+
|
| 10 |
+
if __name__ == "__main__":
|
| 11 |
+
ap = argparse.ArgumentParser()
|
| 12 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 13 |
+
ap.add_argument("--train_steps", type=int, default=500000)
|
| 14 |
+
ap.add_argument("--alpha", type=float, default=1.0)
|
| 15 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 16 |
+
ap.add_argument("--rt_eta", type=float, default=0.5)
|
| 17 |
+
ap.add_argument("--pi_alpha", type=float, default=1.0)
|
| 18 |
+
ap.add_argument("--pi_horizon", type=int, default=25)
|
| 19 |
+
ap.add_argument("--occ_warmup", type=int, default=50000)
|
| 20 |
+
ap.add_argument("--occ_tau", type=float, default=0.005)
|
| 21 |
+
ap.add_argument("--n_orders", type=int, default=16)
|
| 22 |
+
ap.add_argument("--extraction", default="r3",
|
| 23 |
+
choices=["r3", "gliql", "ddpg2", "awr2"])
|
| 24 |
+
ap.add_argument("--gliql_alpha", type=float, default=3.0)
|
| 25 |
+
ap.add_argument("--awr_alpha", type=float, default=3.0,
|
| 26 |
+
help="awr2 temperature on the batch-std-normalized log-gl "
|
| 27 |
+
"advantage (forward-only actor loss; host path only)")
|
| 28 |
+
ap.add_argument("--occ_warmstart_npz", default=None)
|
| 29 |
+
ap.add_argument("--eval_interval", type=int, default=25000)
|
| 30 |
+
ap.add_argument("--variant_tag", default=None)
|
| 31 |
+
ap.add_argument("--save_agent", default=None)
|
| 32 |
+
ap.add_argument("--save_occ", default=None,
|
| 33 |
+
help="save the co-trained occupancy EMA as a warm-start-format "
|
| 34 |
+
"npz (input for eval_plan.py test-time planning)")
|
| 35 |
+
ap.add_argument("--save_best", default=None,
|
| 36 |
+
help="fast path: pickle the banked best snapshot to this path "
|
| 37 |
+
"every time it improves, so it can be 50-ep evaluated "
|
| 38 |
+
"offline mid-run")
|
| 39 |
+
ap.add_argument("--rec_target", type=int, default=0,
|
| 40 |
+
help="RECURSIVE PREDICTION: M occupancy-sampled midpoints; r3 composes "
|
| 41 |
+
"critic targets, ddpg2 composes the actor loss through gl jumps")
|
| 42 |
+
ap.add_argument("--rec_every", type=int, default=2)
|
| 43 |
+
ap.add_argument("--rec_eps", type=float, default=0.5)
|
| 44 |
+
ap.add_argument("--rec_after", type=int, default=100000)
|
| 45 |
+
ap.add_argument("--rec_beta", type=float, default=0.0,
|
| 46 |
+
help="beta-recursive rule: stochastic recursion depth, continue "
|
| 47 |
+
"w.p. p=(gamma-beta)/(gamma*(1-beta)); 0 = fixed depth-1")
|
| 48 |
+
ap.add_argument("--rec_max_depth", type=int, default=6)
|
| 49 |
+
ap.add_argument("--rec_prob", action="store_true",
|
| 50 |
+
help="probabilistic beta-jump Q estimator (splitting identity, "
|
| 51 |
+
"expectation instead of max-certificates; needs rec_free+rec_beta)")
|
| 52 |
+
ap.add_argument("--rec_pess", type=int, default=1,
|
| 53 |
+
help="pessimism at generated midpoints: value = min over K "
|
| 54 |
+
"independent completion draws (1 = off)")
|
| 55 |
+
ap.add_argument("--gamma_spectrum_lo", type=float, default=0.0,
|
| 56 |
+
help="train the occupancy CONDITIONED on the discount, sampled "
|
| 57 |
+
"log-uniform-in-horizon in [lo, gamma] (0 = fixed gamma). "
|
| 58 |
+
"PI gl reads at task gamma; recursion hops at rec_beta.")
|
| 59 |
+
ap.add_argument("--gamma_spectrum_p", type=float, default=0.5)
|
| 60 |
+
ap.add_argument("--gamma_encoding", default="scalar",
|
| 61 |
+
choices=["scalar", "onehot2", "fourier"],
|
| 62 |
+
help="how the discount enters the conditioning (fast path). "
|
| 63 |
+
"scalar = raw gamma column (original; under-resolved by "
|
| 64 |
+
"the MLP). onehot2 = discrete which-measure indicator over "
|
| 65 |
+
"{task gamma, beta} — no interpolation burden; needs "
|
| 66 |
+
"--rec_beta")
|
| 67 |
+
ap.add_argument("--readout", default="gl", choices=["gl", "sample", "elbo"],
|
| 68 |
+
help="Q read-out (fast path). gl = exact any-order likelihood "
|
| 69 |
+
"from the masked DISCRETE occupancy (finite goal alphabets "
|
| 70 |
+
"only). sample = kernel Monte-Carlo over pathwise DDIM "
|
| 71 |
+
"samples from a CONTINUOUS occupancy — no likelihood "
|
| 72 |
+
"anywhere. elbo = diffusion-classifier ELBO surrogate: "
|
| 73 |
+
"denoising loss AT the goal point, Q=exp(-elbo_c*loss) — "
|
| 74 |
+
"point evaluation like gl, any goal space like sample "
|
| 75 |
+
"(owner directive 2026-07-15)")
|
| 76 |
+
ap.add_argument("--elbo_c", type=float, default=1.0,
|
| 77 |
+
help="elbo readout: temperature on the denoising loss")
|
| 78 |
+
ap.add_argument("--elbo_pess", type=float, default=0.0,
|
| 79 |
+
help="RSM stability: uncertainty-penalized ELBO — Q = "
|
| 80 |
+
"exp(-c*(mean + pess*std)) over the K draws")
|
| 81 |
+
ap.add_argument("--alpha_ramp", type=int, default=0,
|
| 82 |
+
help="RSM stability: anneal the BC weight 1.0 -> alpha "
|
| 83 |
+
"over this many steps (0 = static alpha)")
|
| 84 |
+
ap.add_argument("--ker_K", type=int, default=16,
|
| 85 |
+
help="sample readout: samples per Q estimate (targets/eval)")
|
| 86 |
+
ap.add_argument("--ker_sharp", type=float, default=8.0,
|
| 87 |
+
help="sample readout: kernel sharpness (puzzle: per-bit "
|
| 88 |
+
"sigmoid match; continuous envs: edge softness of the "
|
| 89 |
+
"smoothed eps-ball)")
|
| 90 |
+
ap.add_argument("--ker_eps", type=float, default=0.5,
|
| 91 |
+
help="sample readout, continuous envs: the env's success "
|
| 92 |
+
"radius (OGBench pointmaze: 1.0; ant/humanoid maze: 0.5)")
|
| 93 |
+
ap.add_argument("--gamma_fourier_k", type=int, default=4,
|
| 94 |
+
help="fourier encoding: number of sin/cos frequency pairs over "
|
| 95 |
+
"normalized log-horizon (fast path; default 4)")
|
| 96 |
+
ap.add_argument("--occ_hidden", type=int, default=256,
|
| 97 |
+
help="occupancy/completion trunk width (fast path)")
|
| 98 |
+
ap.add_argument("--occ_lr", type=float, default=3e-4,
|
| 99 |
+
help="occupancy learning rate (fast path)")
|
| 100 |
+
ap.add_argument("--rec_free", action="store_true",
|
| 101 |
+
help="retrieval-free midpoints: full-state completion head, "
|
| 102 |
+
"live-actor midpoint actions (no eps-grid, no lookup)")
|
| 103 |
+
ap.add_argument("--readout", default="gl", choices=["gl", "sample", "elbo"],
|
| 104 |
+
help="occupancy Q read-out for targets/hit terms (host path): gl = "
|
| 105 |
+
"exact teacher-forced likelihood; sample = de-hacked MC "
|
| 106 |
+
"hit-count over n_occ_ro ancestral draws; elbo = PUZZLE-AS-"
|
| 107 |
+
"CONTINUOUS (space-agnostic): eps-prediction DDPM over the 9 "
|
| 108 |
+
"bits embedded as +-1, Q = exp(-elbo_c * denoising loss at "
|
| 109 |
+
"the goal) — no masked diffusion, same code path as pointmaze")
|
| 110 |
+
ap.add_argument("--n_occ_ro", type=int, default=64)
|
| 111 |
+
ap.add_argument("--elbo_c", type=float, default=10.0,
|
| 112 |
+
help="ELBO read-out temperature Q = exp(-c * L_den); targets/eval "
|
| 113 |
+
"only — c cancels in the plain actor gradient (log-space). "
|
| 114 |
+
"Collaborator's puzzle rung: c=10 is the knee")
|
| 115 |
+
ap.add_argument("--elbo_K", type=int, default=8,
|
| 116 |
+
help="ELBO (t, eps) draws per read (even; antithetic +-eps pairs)")
|
| 117 |
+
ap.add_argument("--elbo_tlo", type=float, default=0.0)
|
| 118 |
+
ap.add_argument("--elbo_thi", type=float, default=1.0,
|
| 119 |
+
help="stratified-t quantile band for the ELBO read (high-t eps "
|
| 120 |
+
"predictions are nearly condition-independent and dilute "
|
| 121 |
+
"the ranking signal; band-limiting is the design-around)")
|
| 122 |
+
ap.add_argument("--rec_actor", action="store_true",
|
| 123 |
+
help="r3: ALSO compose the actor-goal targets — the ddpgbc actor "
|
| 124 |
+
"differentiates the distilled critic at actor_goals, so "
|
| 125 |
+
"composition reaches the head the policy gradient reads "
|
| 126 |
+
"(retrieval-form cell: +0.13 final over value-goals-only)")
|
| 127 |
+
ap.add_argument("--actor_ema_tau", type=float, default=0.0,
|
| 128 |
+
help="Polyak EMA of the actor, evaluated alongside the live actor each "
|
| 129 |
+
"periodic eval (late-band stabilizer; best-ckpt picks the winner)")
|
| 130 |
+
ap.add_argument("--fast", action="store_true",
|
| 131 |
+
help="fused on-device train step + lax.scan (plain r3/ddpg2 only; "
|
| 132 |
+
"no rec_target/gliql)")
|
| 133 |
+
ap.add_argument("--steps_per_dispatch", type=int, default=100)
|
| 134 |
+
ap.add_argument("--data_parallel", action="store_true",
|
| 135 |
+
help="pmap the fused train step over all local devices (fast path "
|
| 136 |
+
"only): per-device batch = batch/D, grads pmean'd, global "
|
| 137 |
+
"batch semantics preserved")
|
| 138 |
+
ap.add_argument("--batch_size", type=int, default=0,
|
| 139 |
+
help="override PI batch size (fast path; 0 = reference 1024)")
|
| 140 |
+
ap.add_argument("--occ_batch", type=int, default=256)
|
| 141 |
+
ap.add_argument("--n_orders_pi", type=int, default=0,
|
| 142 |
+
help="order count for the differentiated actor-loss gl calls "
|
| 143 |
+
"(fast path; 0 = full n_orders). Large batch absorbs the "
|
| 144 |
+
"extra per-state read-out noise")
|
| 145 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 146 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 147 |
+
a = ap.parse_args()
|
| 148 |
+
assert not (a.data_parallel and not a.fast), "--data_parallel requires --fast"
|
| 149 |
+
assert not (a.fast and a.readout == "elbo"), \
|
| 150 |
+
"--readout elbo is host-path only (this branch's fast carrier has no elbo)"
|
| 151 |
+
if a.fast:
|
| 152 |
+
from ogbench_genq.genq_joint_fast import run_genq_joint_fast
|
| 153 |
+
assert a.extraction in ("r3", "ddpg2")
|
| 154 |
+
assert not (a.rec_target > 0 and not a.rec_free), \
|
| 155 |
+
"fast recursion is retrieval-free only"
|
| 156 |
+
run_genq_joint_fast(ENV, seed=a.seed, train_steps=a.train_steps, alpha=a.alpha,
|
| 157 |
+
expectile=a.expectile, rt_eta=a.rt_eta, pi_alpha=a.pi_alpha,
|
| 158 |
+
pi_horizon=a.pi_horizon, occ_warmup=a.occ_warmup,
|
| 159 |
+
occ_tau=a.occ_tau, n_orders=a.n_orders,
|
| 160 |
+
extraction=a.extraction,
|
| 161 |
+
occ_warmstart_npz=a.occ_warmstart_npz,
|
| 162 |
+
eval_interval=a.eval_interval, variant_tag=a.variant_tag,
|
| 163 |
+
save_agent=a.save_agent, save_occ=a.save_occ,
|
| 164 |
+
save_best=a.save_best, n_orders_pi=a.n_orders_pi,
|
| 165 |
+
actor_ema_tau=a.actor_ema_tau,
|
| 166 |
+
steps_per_dispatch=a.steps_per_dispatch,
|
| 167 |
+
batch_size=a.batch_size, occ_batch=a.occ_batch,
|
| 168 |
+
rec_target=a.rec_target, rec_every=a.rec_every,
|
| 169 |
+
rec_after=a.rec_after, rec_beta=a.rec_beta,
|
| 170 |
+
rec_max_depth=a.rec_max_depth, rec_prob=a.rec_prob,
|
| 171 |
+
rec_actor=a.rec_actor,
|
| 172 |
+
gamma_spectrum_lo=a.gamma_spectrum_lo,
|
| 173 |
+
gamma_spectrum_p=a.gamma_spectrum_p,
|
| 174 |
+
gamma_encoding=a.gamma_encoding,
|
| 175 |
+
gamma_fourier_k=a.gamma_fourier_k,
|
| 176 |
+
readout=a.readout, ker_K=a.ker_K, ker_sharp=a.ker_sharp,
|
| 177 |
+
ker_eps=a.ker_eps, elbo_c=a.elbo_c,
|
| 178 |
+
elbo_pess=a.elbo_pess, alpha_ramp=a.alpha_ramp,
|
| 179 |
+
occ_hidden=a.occ_hidden, occ_lr=a.occ_lr,
|
| 180 |
+
data_parallel=a.data_parallel,
|
| 181 |
+
eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
| 182 |
+
raise SystemExit(0)
|
| 183 |
+
run_genq_joint(ENV, seed=a.seed, train_steps=a.train_steps, alpha=a.alpha,
|
| 184 |
+
expectile=a.expectile, rt_eta=a.rt_eta, pi_alpha=a.pi_alpha,
|
| 185 |
+
pi_horizon=a.pi_horizon, occ_warmup=a.occ_warmup, occ_tau=a.occ_tau,
|
| 186 |
+
n_orders=a.n_orders, extraction=a.extraction,
|
| 187 |
+
gliql_alpha=a.gliql_alpha, awr_alpha=a.awr_alpha,
|
| 188 |
+
occ_warmstart_npz=a.occ_warmstart_npz,
|
| 189 |
+
eval_interval=a.eval_interval,
|
| 190 |
+
variant_tag=a.variant_tag, save_agent=a.save_agent,
|
| 191 |
+
save_occ=a.save_occ,
|
| 192 |
+
actor_ema_tau=a.actor_ema_tau,
|
| 193 |
+
rec_target=a.rec_target, rec_every=a.rec_every, rec_eps=a.rec_eps,
|
| 194 |
+
rec_after=a.rec_after, rec_free=a.rec_free,
|
| 195 |
+
rec_beta=a.rec_beta, rec_max_depth=a.rec_max_depth, rec_pess=a.rec_pess,
|
| 196 |
+
rec_prob=a.rec_prob, rec_actor=a.rec_actor,
|
| 197 |
+
readout=a.readout, n_occ_ro=a.n_occ_ro,
|
| 198 |
+
elbo_c=a.elbo_c, elbo_K=a.elbo_K,
|
| 199 |
+
elbo_tlo=a.elbo_tlo, elbo_thi=a.elbo_thi,
|
| 200 |
+
gamma_spectrum_lo=a.gamma_spectrum_lo, gamma_spectrum_p=a.gamma_spectrum_p,
|
| 201 |
+
eval_episodes=a.eval_episodes, wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-4x4-play-v0/train_gcbc.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train the goal-conditioned BC baseline on puzzle-4x4-play-v0 (JAX-only)."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq._runner import run_gcbc
|
| 6 |
+
|
| 7 |
+
ENV = "puzzle-4x4-play-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 13 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 14 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 15 |
+
a = ap.parse_args()
|
| 16 |
+
run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes,
|
| 17 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-4x4-play-v0/train_gciql.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train the standard GCIQL baseline (TD critic) on puzzle-4x4-play-v0 (JAX-only)."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq._runner import run_gciql
|
| 6 |
+
|
| 7 |
+
ENV = "puzzle-4x4-play-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=500000)
|
| 13 |
+
ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"])
|
| 14 |
+
ap.add_argument("--alpha", type=float, default=0.3)
|
| 15 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 16 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 17 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 18 |
+
a = ap.parse_args()
|
| 19 |
+
run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 20 |
+
alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes,
|
| 21 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-4x4-play-v0/train_gciql_genq.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the Gen-Q occupancy critic on puzzle-4x4-play-v0 (JAX-only, diffusion occupancy).
|
| 3 |
+
|
| 4 |
+
Best Gen-Q config for this env (M10 score table; legacy tree removed, see git history):
|
| 5 |
+
awr alpha=30.0 expectile=0.9 n_occ=64 sigma=0.5.
|
| 6 |
+
Requires a trained Gen-Q diffusion occupancy ckpt; train it first with:
|
| 7 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env puzzle-4x4-play-v0
|
| 8 |
+
"""
|
| 9 |
+
import argparse, os, sys
|
| 10 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 11 |
+
from ogbench_genq._runner import run_gciql_genq
|
| 12 |
+
|
| 13 |
+
ENV = "puzzle-4x4-play-v0"
|
| 14 |
+
|
| 15 |
+
if __name__ == "__main__":
|
| 16 |
+
ap = argparse.ArgumentParser()
|
| 17 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 18 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 19 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 20 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 21 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 22 |
+
ap.add_argument("--n_occ", type=int, default=64)
|
| 23 |
+
ap.add_argument("--sigma", type=float, default=0.5)
|
| 24 |
+
ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)")
|
| 25 |
+
ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)")
|
| 26 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 27 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 28 |
+
a = ap.parse_args()
|
| 29 |
+
run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 30 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, sigma=a.sigma,
|
| 31 |
+
genq_npz=a.genq_npz, latent_npz=a.latent_npz, eval_episodes=a.eval_episodes,
|
| 32 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/puzzle-4x4-play-v0/train_gciql_genq_recursive.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on puzzle-4x4-play-v0.
|
| 3 |
+
|
| 4 |
+
The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric
|
| 5 |
+
recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))).
|
| 6 |
+
Requires a --state_target short-beta occupancy; train it first with:
|
| 7 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \
|
| 8 |
+
--env puzzle-4x4-play-v0 --gamma <beta> --state_target \
|
| 9 |
+
--out ogbench_genq/checkpoints/m9_genq_rec_puzzle_4x4_play_v0_b<tag>.genqjax.npz
|
| 10 |
+
"""
|
| 11 |
+
import argparse, os, sys
|
| 12 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 13 |
+
from ogbench_genq._runner import run_gciql_genq_recursive
|
| 14 |
+
|
| 15 |
+
ENV = "puzzle-4x4-play-v0"
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 20 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 21 |
+
ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy")
|
| 22 |
+
ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion")
|
| 23 |
+
ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump")
|
| 24 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 25 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 26 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 27 |
+
ap.add_argument("--n_occ", type=int, default=16)
|
| 28 |
+
ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)")
|
| 29 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 30 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 31 |
+
a = ap.parse_args()
|
| 32 |
+
run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps,
|
| 33 |
+
recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma,
|
| 34 |
+
steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss,
|
| 35 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ,
|
| 36 |
+
genq_npz=a.genq_npz, eval_episodes=a.eval_episodes,
|
| 37 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/scene-play-v0/train_gcbc.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train the goal-conditioned BC baseline on scene-play-v0 (JAX-only)."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq._runner import run_gcbc
|
| 6 |
+
|
| 7 |
+
ENV = "scene-play-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 13 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 14 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 15 |
+
a = ap.parse_args()
|
| 16 |
+
run_gcbc(ENV, seed=a.seed, train_steps=a.train_steps, eval_episodes=a.eval_episodes,
|
| 17 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/scene-play-v0/train_gciql.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train the standard GCIQL baseline (TD critic) on scene-play-v0 (JAX-only)."""
|
| 3 |
+
import argparse, os, sys
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 5 |
+
from ogbench_genq._runner import run_gciql
|
| 6 |
+
|
| 7 |
+
ENV = "scene-play-v0"
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
ap = argparse.ArgumentParser()
|
| 11 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 12 |
+
ap.add_argument("--train_steps", type=int, default=500000)
|
| 13 |
+
ap.add_argument("--actor_loss", default="ddpgbc", choices=["ddpgbc", "awr"])
|
| 14 |
+
ap.add_argument("--alpha", type=float, default=0.3)
|
| 15 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 16 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 17 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 18 |
+
a = ap.parse_args()
|
| 19 |
+
run_gciql(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 20 |
+
alpha=a.alpha, expectile=a.expectile, eval_episodes=a.eval_episodes,
|
| 21 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/scene-play-v0/train_gciql_genq.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the Gen-Q occupancy critic on scene-play-v0 (JAX-only, diffusion occupancy).
|
| 3 |
+
|
| 4 |
+
Best Gen-Q config for this env (M10 score table; legacy tree removed, see git history):
|
| 5 |
+
awr alpha=30.0 expectile=0.9 n_occ=64 sigma=1.0.
|
| 6 |
+
Requires a trained Gen-Q diffusion occupancy ckpt; train it first with:
|
| 7 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py --env scene-play-v0
|
| 8 |
+
"""
|
| 9 |
+
import argparse, os, sys
|
| 10 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 11 |
+
from ogbench_genq._runner import run_gciql_genq
|
| 12 |
+
|
| 13 |
+
ENV = "scene-play-v0"
|
| 14 |
+
|
| 15 |
+
if __name__ == "__main__":
|
| 16 |
+
ap = argparse.ArgumentParser()
|
| 17 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 18 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 19 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 20 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 21 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 22 |
+
ap.add_argument("--n_occ", type=int, default=64)
|
| 23 |
+
ap.add_argument("--sigma", type=float, default=1.0)
|
| 24 |
+
ap.add_argument("--genq_npz", default=None, help="trained Gen-Q .genqjax.npz (auto-discovered if omitted)")
|
| 25 |
+
ap.add_argument("--latent_npz", default=None, help="frozen reward-predictive latent encoder (image envs)")
|
| 26 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 27 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 28 |
+
a = ap.parse_args()
|
| 29 |
+
run_gciql_genq(ENV, seed=a.seed, train_steps=a.train_steps, actor_loss=a.actor_loss,
|
| 30 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ, sigma=a.sigma,
|
| 31 |
+
genq_npz=a.genq_npz, latent_npz=a.latent_npz, eval_episodes=a.eval_episodes,
|
| 32 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/experiments/scene-play-v0/train_gciql_genq_recursive.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Train GCIQL with the RECURSIVE Gen-Q occupancy critic on scene-play-v0.
|
| 3 |
+
|
| 4 |
+
The critic samples d_gamma endpoints by composing a SHORT-beta occupancy with geometric
|
| 5 |
+
recursive jumps (genq/genq_recursive_jax.py; stop prob p = beta(1-gamma)/(gamma(1-beta))).
|
| 6 |
+
Requires a --state_target short-beta occupancy; train it first with:
|
| 7 |
+
PYTHONPATH=$OGB:ogbench_genq/genq python ogbench_genq/genq/train_genq_jax.py \
|
| 8 |
+
--env scene-play-v0 --gamma <beta> --state_target \
|
| 9 |
+
--out ogbench_genq/checkpoints/m9_genq_rec_scene_play_v0_b<tag>.genqjax.npz
|
| 10 |
+
"""
|
| 11 |
+
import argparse, os, sys
|
| 12 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
| 13 |
+
from ogbench_genq._runner import run_gciql_genq_recursive
|
| 14 |
+
|
| 15 |
+
ENV = "scene-play-v0"
|
| 16 |
+
|
| 17 |
+
if __name__ == "__main__":
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 20 |
+
ap.add_argument("--train_steps", type=int, default=300000)
|
| 21 |
+
ap.add_argument("--recursive_beta", type=float, default=0.95, help="short discount of the occupancy")
|
| 22 |
+
ap.add_argument("--recursive_gamma", type=float, default=0.99, help="target discount recovered by recursion")
|
| 23 |
+
ap.add_argument("--steps_per_jump", type=int, default=10, help="DDIM steps per recursive jump")
|
| 24 |
+
ap.add_argument("--actor_loss", default="awr", choices=["ddpgbc", "awr"])
|
| 25 |
+
ap.add_argument("--alpha", type=float, default=30.0)
|
| 26 |
+
ap.add_argument("--expectile", type=float, default=0.9)
|
| 27 |
+
ap.add_argument("--n_occ", type=int, default=16)
|
| 28 |
+
ap.add_argument("--genq_npz", default=None, help="short-beta --state_target .genqjax.npz (auto-discovered if omitted)")
|
| 29 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 30 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 31 |
+
a = ap.parse_args()
|
| 32 |
+
run_gciql_genq_recursive(ENV, seed=a.seed, train_steps=a.train_steps,
|
| 33 |
+
recursive_beta=a.recursive_beta, recursive_gamma=a.recursive_gamma,
|
| 34 |
+
steps_per_jump=a.steps_per_jump, actor_loss=a.actor_loss,
|
| 35 |
+
alpha=a.alpha, expectile=a.expectile, n_occ=a.n_occ,
|
| 36 |
+
genq_npz=a.genq_npz, eval_episodes=a.eval_episodes,
|
| 37 |
+
wandb_mode=a.wandb_mode)
|
gen_q_rsm/ogbench_genq/unused/gciql_ablate.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GCIQL -> GenQ component-ablation agent (issue #57, owner directive 2026-07-07).
|
| 2 |
+
|
| 3 |
+
"If our learned Q-function is as good as GCIQL's and we use the same policy extraction,
|
| 4 |
+
we should do as well as GCIQL. Ablate away from GCIQL step by step."
|
| 5 |
+
|
| 6 |
+
This is the REFERENCE OGBench GCIQLAgent (agents/gciql.py) plus the SMALLEST possible
|
| 7 |
+
delta: an extra 2-head critic ('genq_critic') distilled on-the-fly from the Gen-Q
|
| 8 |
+
occupancy Q (the driver injects batch['genq_q_value'] / batch['genq_q_actor'] targets at
|
| 9 |
+
the batch's own value/actor goals), and two switches choosing which Q each reference
|
| 10 |
+
component reads:
|
| 11 |
+
|
| 12 |
+
genq_actor: the actor loss reads genq_critic instead of critic. (rung R1)
|
| 13 |
+
genq_value: the expectile V fits target_genq_critic instead of (rung R2)
|
| 14 |
+
target_critic — and therefore the TD critic bootstraps
|
| 15 |
+
through GenQ-anchored values.
|
| 16 |
+
both: fully TD-free value path. (rung R3)
|
| 17 |
+
|
| 18 |
+
Everything else — TD critic loss, expectile V, DDPG+BC/AWR actor, Polyak targets,
|
| 19 |
+
GCDataset goal mix, reward/mask convention, lr, batch, networks — is byte-for-byte the
|
| 20 |
+
reference. Rung R0 (both switches off) IS reference GCIQL, with the distilled critic
|
| 21 |
+
trained but unused (so compute differences don't confound the comparison).
|
| 22 |
+
"""
|
| 23 |
+
import copy
|
| 24 |
+
|
| 25 |
+
import flax
|
| 26 |
+
import jax
|
| 27 |
+
import jax.numpy as jnp
|
| 28 |
+
import ml_collections
|
| 29 |
+
import optax
|
| 30 |
+
|
| 31 |
+
from agents.gciql import GCIQLAgent, get_config as _ref_get_config
|
| 32 |
+
from utils.encoders import GCEncoder, encoder_modules
|
| 33 |
+
from utils.flax_utils import ModuleDict, TrainState
|
| 34 |
+
from utils.networks import GCActor, GCValue
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class GCIQLAblateAgent(GCIQLAgent):
|
| 38 |
+
"""Reference GCIQL + distilled genq_critic + per-component Q-source switches."""
|
| 39 |
+
|
| 40 |
+
def genq_critic_loss(self, batch, grad_params):
|
| 41 |
+
"""Distill the on-the-fly Gen-Q occupancy Q into the genq_critic (both heads).
|
| 42 |
+
|
| 43 |
+
Supervised at value_goals always; at actor_goals too when the driver supplies
|
| 44 |
+
batch['genq_q_actor'] (needed when the actor reads this critic, since DDPG+BC
|
| 45 |
+
queries at actor_goals)."""
|
| 46 |
+
def reg_at(goal_key, target):
|
| 47 |
+
q1, q2 = self.network.select('genq_critic')(
|
| 48 |
+
batch['observations'], batch[goal_key], batch['actions'], params=grad_params)
|
| 49 |
+
return ((q1 - target) ** 2 + (q2 - target) ** 2).mean()
|
| 50 |
+
|
| 51 |
+
loss = reg_at('value_goals', batch['genq_q_value'])
|
| 52 |
+
info = {'genq_critic_loss': loss, 'genq_q_mean': batch['genq_q_value'].mean(),
|
| 53 |
+
'genq_q_max': batch['genq_q_value'].max()}
|
| 54 |
+
if 'genq_q_actor' in batch:
|
| 55 |
+
la = reg_at('actor_goals', batch['genq_q_actor'])
|
| 56 |
+
loss = loss + la
|
| 57 |
+
info['genq_critic_loss_actor'] = la
|
| 58 |
+
return loss, info
|
| 59 |
+
|
| 60 |
+
def value_loss(self, batch, grad_params):
|
| 61 |
+
"""Reference expectile V, with the Q source switched by config['genq_value']."""
|
| 62 |
+
src = 'target_genq_critic' if self.config['genq_value'] else 'target_critic'
|
| 63 |
+
q1, q2 = self.network.select(src)(batch['observations'], batch['value_goals'],
|
| 64 |
+
batch['actions'])
|
| 65 |
+
q = jnp.minimum(q1, q2)
|
| 66 |
+
v = self.network.select('value')(batch['observations'], batch['value_goals'],
|
| 67 |
+
params=grad_params)
|
| 68 |
+
value_loss = self.expectile_loss(q - v, q - v, self.config['expectile']).mean()
|
| 69 |
+
return value_loss, {'value_loss': value_loss, 'v_mean': v.mean(),
|
| 70 |
+
'v_max': v.max(), 'v_min': v.min()}
|
| 71 |
+
|
| 72 |
+
def actor_loss(self, batch, grad_params, rng=None):
|
| 73 |
+
"""Reference AWR / DDPG+BC, with the critic switched by config['genq_actor']."""
|
| 74 |
+
src = 'genq_critic' if self.config['genq_actor'] else 'critic'
|
| 75 |
+
if self.config['actor_loss'] == 'awr':
|
| 76 |
+
v = self.network.select('value')(batch['observations'], batch['actor_goals'])
|
| 77 |
+
q1, q2 = self.network.select(src)(batch['observations'], batch['actor_goals'],
|
| 78 |
+
batch['actions'])
|
| 79 |
+
q = jnp.minimum(q1, q2)
|
| 80 |
+
adv = q - v
|
| 81 |
+
if self.config.get('adv_norm', False):
|
| 82 |
+
# standardize per batch: alpha becomes scale-free (issue #57 lesson —
|
| 83 |
+
# needed when Q lives on the [0,1] Gen-Q scale instead of TD's [-100,0])
|
| 84 |
+
adv = (adv - adv.mean()) / (adv.std() + 1e-6)
|
| 85 |
+
exp_a = jnp.minimum(jnp.exp(adv * self.config['alpha']), 100.0)
|
| 86 |
+
dist = self.network.select('actor')(batch['observations'], batch['actor_goals'],
|
| 87 |
+
params=grad_params)
|
| 88 |
+
log_prob = dist.log_prob(batch['actions'])
|
| 89 |
+
actor_loss = -(exp_a * log_prob).mean()
|
| 90 |
+
return actor_loss, {'actor_loss': actor_loss, 'adv': adv.mean(),
|
| 91 |
+
'bc_log_prob': log_prob.mean(),
|
| 92 |
+
'mse': jnp.mean((dist.mode() - batch['actions']) ** 2)}
|
| 93 |
+
# ddpgbc (reference puzzle recipe: alpha=1.0)
|
| 94 |
+
assert not self.config['discrete']
|
| 95 |
+
dist = self.network.select('actor')(batch['observations'], batch['actor_goals'],
|
| 96 |
+
params=grad_params)
|
| 97 |
+
if self.config['const_std']:
|
| 98 |
+
q_actions = jnp.clip(dist.mode(), -1, 1)
|
| 99 |
+
else:
|
| 100 |
+
q_actions = jnp.clip(dist.sample(seed=rng), -1, 1)
|
| 101 |
+
q1, q2 = self.network.select(src)(batch['observations'], batch['actor_goals'], q_actions)
|
| 102 |
+
q = jnp.minimum(q1, q2)
|
| 103 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6)
|
| 104 |
+
log_prob = dist.log_prob(batch['actions'])
|
| 105 |
+
bc_loss = -(self.config['alpha'] * log_prob).mean()
|
| 106 |
+
actor_loss = q_loss + bc_loss
|
| 107 |
+
return actor_loss, {'actor_loss': actor_loss, 'q_loss': q_loss, 'bc_loss': bc_loss,
|
| 108 |
+
'q_mean': q.mean(), 'q_abs_mean': jnp.abs(q).mean(),
|
| 109 |
+
'bc_log_prob': log_prob.mean(),
|
| 110 |
+
'mse': jnp.mean((dist.mode() - batch['actions']) ** 2),
|
| 111 |
+
'std': jnp.mean(dist.scale_diag)}
|
| 112 |
+
|
| 113 |
+
@jax.jit
|
| 114 |
+
def total_loss(self, batch, grad_params, rng=None):
|
| 115 |
+
info = {}
|
| 116 |
+
rng = rng if rng is not None else self.rng
|
| 117 |
+
value_loss, value_info = self.value_loss(batch, grad_params)
|
| 118 |
+
info.update({f'value/{k}': v for k, v in value_info.items()})
|
| 119 |
+
critic_loss, critic_info = self.critic_loss(batch, grad_params) # reference TD loss
|
| 120 |
+
info.update({f'critic/{k}': v for k, v in critic_info.items()})
|
| 121 |
+
genq_loss, genq_info = self.genq_critic_loss(batch, grad_params)
|
| 122 |
+
info.update({f'genq/{k}': v for k, v in genq_info.items()})
|
| 123 |
+
rng, actor_rng = jax.random.split(rng)
|
| 124 |
+
actor_loss, actor_info = self.actor_loss(batch, grad_params, actor_rng)
|
| 125 |
+
info.update({f'actor/{k}': v for k, v in actor_info.items()})
|
| 126 |
+
return value_loss + critic_loss + genq_loss + actor_loss, info
|
| 127 |
+
|
| 128 |
+
@jax.jit
|
| 129 |
+
def update(self, batch):
|
| 130 |
+
new_rng, rng = jax.random.split(self.rng)
|
| 131 |
+
|
| 132 |
+
def loss_fn(grad_params):
|
| 133 |
+
return self.total_loss(batch, grad_params, rng=rng)
|
| 134 |
+
|
| 135 |
+
new_network, info = self.network.apply_loss_fn(loss_fn=loss_fn)
|
| 136 |
+
self.target_update(new_network, 'critic')
|
| 137 |
+
self.target_update(new_network, 'genq_critic')
|
| 138 |
+
return self.replace(network=new_network, rng=new_rng), info
|
| 139 |
+
|
| 140 |
+
@classmethod
|
| 141 |
+
def create(cls, seed, ex_observations, ex_actions, config):
|
| 142 |
+
rng = jax.random.PRNGKey(seed)
|
| 143 |
+
rng, init_rng = jax.random.split(rng, 2)
|
| 144 |
+
ex_goals = ex_observations
|
| 145 |
+
assert not config['discrete']
|
| 146 |
+
action_dim = ex_actions.shape[-1]
|
| 147 |
+
|
| 148 |
+
encoders = dict()
|
| 149 |
+
if config['encoder'] is not None:
|
| 150 |
+
encoder_module = encoder_modules[config['encoder']]
|
| 151 |
+
for k in ('value', 'critic', 'genq_critic', 'actor'):
|
| 152 |
+
encoders[k] = GCEncoder(concat_encoder=encoder_module())
|
| 153 |
+
|
| 154 |
+
value_def = GCValue(hidden_dims=config['value_hidden_dims'],
|
| 155 |
+
layer_norm=config['layer_norm'], ensemble=False,
|
| 156 |
+
gc_encoder=encoders.get('value'))
|
| 157 |
+
critic_def = GCValue(hidden_dims=config['value_hidden_dims'],
|
| 158 |
+
layer_norm=config['layer_norm'], ensemble=True,
|
| 159 |
+
gc_encoder=encoders.get('critic'))
|
| 160 |
+
genq_critic_def = GCValue(hidden_dims=config['value_hidden_dims'],
|
| 161 |
+
layer_norm=config['layer_norm'], ensemble=True,
|
| 162 |
+
gc_encoder=encoders.get('genq_critic'))
|
| 163 |
+
actor_def = GCActor(hidden_dims=config['actor_hidden_dims'], action_dim=action_dim,
|
| 164 |
+
state_dependent_std=False, const_std=config['const_std'],
|
| 165 |
+
gc_encoder=encoders.get('actor'))
|
| 166 |
+
|
| 167 |
+
network_info = dict(
|
| 168 |
+
value=(value_def, (ex_observations, ex_goals)),
|
| 169 |
+
critic=(critic_def, (ex_observations, ex_goals, ex_actions)),
|
| 170 |
+
target_critic=(copy.deepcopy(critic_def), (ex_observations, ex_goals, ex_actions)),
|
| 171 |
+
genq_critic=(genq_critic_def, (ex_observations, ex_goals, ex_actions)),
|
| 172 |
+
target_genq_critic=(copy.deepcopy(genq_critic_def),
|
| 173 |
+
(ex_observations, ex_goals, ex_actions)),
|
| 174 |
+
actor=(actor_def, (ex_observations, ex_goals)),
|
| 175 |
+
)
|
| 176 |
+
networks = {k: v[0] for k, v in network_info.items()}
|
| 177 |
+
network_args = {k: v[1] for k, v in network_info.items()}
|
| 178 |
+
network_def = ModuleDict(networks)
|
| 179 |
+
network_tx = optax.adam(learning_rate=config['lr'])
|
| 180 |
+
network_params = network_def.init(init_rng, **network_args)['params']
|
| 181 |
+
network = TrainState.create(network_def, network_params, tx=network_tx)
|
| 182 |
+
params = network_params
|
| 183 |
+
params['modules_target_critic'] = params['modules_critic']
|
| 184 |
+
params['modules_target_genq_critic'] = params['modules_genq_critic']
|
| 185 |
+
return cls(rng, network=network, config=flax.core.FrozenDict(**config))
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get_config():
|
| 189 |
+
config = _ref_get_config()
|
| 190 |
+
config['agent_name'] = 'gciql_ablate'
|
| 191 |
+
config['genq_actor'] = False # R1: actor reads the distilled Gen-Q critic
|
| 192 |
+
config['genq_value'] = False # R2: expectile V fits the distilled Gen-Q critic
|
| 193 |
+
config['adv_norm'] = False # standardize AWR advantage per batch (scale-free alpha)
|
| 194 |
+
return config
|
gen_q_rsm/ogbench_genq/unused/gciql_genq.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GCIQL using Gen-Q occupancy-based Q (JAX-only, goal-conditioned).
|
| 2 |
+
|
| 3 |
+
This is the policy-improvement agent for the Gen-Q story: faithful OGBench GCIQL with ONLY the
|
| 4 |
+
critic *source* swapped for the Gen-Q occupancy Q.
|
| 5 |
+
|
| 6 |
+
Standard GCIQL learns the critic by a TD/Bellman backup. Here the critic is instead regressed onto
|
| 7 |
+
the Gen-Q occupancy Q-value
|
| 8 |
+
|
| 9 |
+
Q(s, a, g) = E_{x ~ p_theta(. | s, a, g)} [ exp(-||x - g||^2 / 2 sigma^2) ],
|
| 10 |
+
|
| 11 |
+
where p_theta is the conditional diffusion occupancy model (genq/genq_jax.py, trained by
|
| 12 |
+
genq/train_genq_jax.py). No Bellman bootstrap, no TD target on the critic — the occupancy model
|
| 13 |
+
supplies a behavior Q^pi directly, and GCIQL's expectile-V + (ddpgbc | awr) actor performs one step
|
| 14 |
+
of policy improvement on top of it.
|
| 15 |
+
|
| 16 |
+
Everything else (expectile value head, ddpgbc/awr actor, target-critic Polyak, GCDataset goal
|
| 17 |
+
sampling, batch=1024) is byte-for-byte OGBench GCIQL, so this isolates "Gen-Q critic vs TD critic".
|
| 18 |
+
|
| 19 |
+
Goal-conditioning: every network (value, critic, actor) takes the goal g as a first-class input,
|
| 20 |
+
exactly as in OGBench GCIQL. The Gen-Q critic target is computed on-the-fly at the batch's own
|
| 21 |
+
`value_goals` (and optionally `actor_goals`) so the train and query goal distributions match.
|
| 22 |
+
|
| 23 |
+
Image observations: when `--latent_npz` is supplied to the driver, the occupancy model and its Q
|
| 24 |
+
live in a frozen reward-predictive latent space (genq/train_latent_encoder_jax.py), never raw
|
| 25 |
+
pixels — see the driver `experiments/{env}/train_gciql_genq.py`.
|
| 26 |
+
|
| 27 |
+
The driver injects the on-the-fly Gen-Q targets as `batch['genq_q_value']` (and optionally
|
| 28 |
+
`batch['genq_q_value_actor']`). The critic NETWORK still generalizes across goals as in reference
|
| 29 |
+
GCIQL.
|
| 30 |
+
"""
|
| 31 |
+
import copy
|
| 32 |
+
|
| 33 |
+
import flax
|
| 34 |
+
import jax
|
| 35 |
+
import jax.numpy as jnp
|
| 36 |
+
import optax
|
| 37 |
+
|
| 38 |
+
from agents.gciql import GCIQLAgent, get_config as _gciql_get_config
|
| 39 |
+
from utils.encoders import GCEncoder, encoder_modules
|
| 40 |
+
from utils.flax_utils import ModuleDict, TrainState
|
| 41 |
+
from utils.networks import GCActor, GCValue
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class GCIQLGenQAgent(GCIQLAgent):
|
| 45 |
+
"""GCIQL whose critic regresses onto an externally-supplied Gen-Q occupancy Q at the batch's
|
| 46 |
+
own value/actor goals (no Bellman, no static-buffer mismatch). Ensemble + min by default."""
|
| 47 |
+
|
| 48 |
+
def value_loss(self, batch, grad_params):
|
| 49 |
+
"""Expectile V regressed toward the (min over ensemble) target-critic Q.
|
| 50 |
+
|
| 51 |
+
Fit V at value_goals always; when actor-goal supervision is enabled (genq_q_value_actor
|
| 52 |
+
present), ALSO fit V at actor_goals so the actor's adv = Q - V reads V on a goal
|
| 53 |
+
distribution V was actually fit on."""
|
| 54 |
+
def vloss_at(goal_key):
|
| 55 |
+
q = self.network.select('target_critic')(batch['observations'], batch[goal_key],
|
| 56 |
+
batch['actions'])
|
| 57 |
+
if self.config['genq_ensemble']:
|
| 58 |
+
q = jnp.minimum(q[0], q[1])
|
| 59 |
+
v = self.network.select('value')(batch['observations'], batch[goal_key],
|
| 60 |
+
params=grad_params)
|
| 61 |
+
return self.expectile_loss(q - v, q - v, self.config['expectile']).mean(), v
|
| 62 |
+
|
| 63 |
+
value_loss, v = vloss_at('value_goals')
|
| 64 |
+
info = {'value_loss': value_loss, 'v_mean': v.mean(), 'v_max': v.max(), 'v_min': v.min()}
|
| 65 |
+
if 'genq_q_value_actor' in batch:
|
| 66 |
+
vloss_a, va = vloss_at('actor_goals')
|
| 67 |
+
value_loss = value_loss + vloss_a
|
| 68 |
+
info.update(value_loss_actor=vloss_a, v_actor_mean=va.mean())
|
| 69 |
+
return value_loss, info
|
| 70 |
+
|
| 71 |
+
def critic_loss(self, batch, grad_params):
|
| 72 |
+
"""Regress the critic onto the on-the-fly Gen-Q occupancy Q.
|
| 73 |
+
|
| 74 |
+
Always regress at value_goals (target == query distribution). When genq_q_value_actor is
|
| 75 |
+
supplied, ALSO regress at actor_goals so the actor reads a critic that was supervised on
|
| 76 |
+
the actor's own goal distribution.
|
| 77 |
+
"""
|
| 78 |
+
def creg_at(goal_key, target):
|
| 79 |
+
q = self.network.select('critic')(
|
| 80 |
+
batch['observations'], batch[goal_key], batch['actions'], params=grad_params)
|
| 81 |
+
if self.config['genq_ensemble']:
|
| 82 |
+
return ((q[0] - target) ** 2 + (q[1] - target) ** 2).mean(), jnp.minimum(q[0], q[1])
|
| 83 |
+
return ((q - target) ** 2).mean(), q
|
| 84 |
+
|
| 85 |
+
q_target = batch['genq_q_value'] # Gen-Q Q at (observations, value_goals, actions)
|
| 86 |
+
critic_loss, q_pred = creg_at('value_goals', q_target)
|
| 87 |
+
info = {'critic_loss': critic_loss, 'q_mean': q_target.mean(), 'q_max': q_target.max(),
|
| 88 |
+
'q_min': q_target.min(), 'q_pred_mean': q_pred.mean()}
|
| 89 |
+
if 'genq_q_value_actor' in batch:
|
| 90 |
+
cl_a, _ = creg_at('actor_goals', batch['genq_q_value_actor'])
|
| 91 |
+
critic_loss = critic_loss + cl_a
|
| 92 |
+
info.update(critic_loss_actor=cl_a, q_actor_mean=batch['genq_q_value_actor'].mean())
|
| 93 |
+
return critic_loss, info
|
| 94 |
+
|
| 95 |
+
def actor_loss(self, batch, grad_params, rng=None):
|
| 96 |
+
"""AWR (adv = Q - V) or DDPG+BC, using the ensemble-min critic — reference GCIQL semantics."""
|
| 97 |
+
def crit(obs, goals, acts):
|
| 98 |
+
q = self.network.select('critic')(obs, goals, acts)
|
| 99 |
+
return jnp.minimum(q[0], q[1]) if self.config['genq_ensemble'] else q
|
| 100 |
+
|
| 101 |
+
if self.config['actor_loss'] == 'awr':
|
| 102 |
+
v = self.network.select('value')(batch['observations'], batch['actor_goals'])
|
| 103 |
+
q = crit(batch['observations'], batch['actor_goals'], batch['actions'])
|
| 104 |
+
adv = q - v
|
| 105 |
+
if self.config.get('adv_norm', False):
|
| 106 |
+
# Standardize the advantage per batch so alpha is scale-free. The Gen-Q Q
|
| 107 |
+
# contrast varies ~2.5x across envs (puzzle bits vs cube xyz), which makes a
|
| 108 |
+
# fixed temperature collapse AWR to BC on the low-contrast envs (issue #57).
|
| 109 |
+
adv = (adv - adv.mean()) / (adv.std() + 1e-6)
|
| 110 |
+
exp_a = jnp.minimum(jnp.exp(adv * self.config['alpha']), 100.0)
|
| 111 |
+
dist = self.network.select('actor')(batch['observations'], batch['actor_goals'],
|
| 112 |
+
params=grad_params)
|
| 113 |
+
log_prob = dist.log_prob(batch['actions'])
|
| 114 |
+
actor_loss = -(exp_a * log_prob).mean()
|
| 115 |
+
info = {'actor_loss': actor_loss, 'adv': adv.mean(), 'adv_std': adv.std(),
|
| 116 |
+
'bc_log_prob': log_prob.mean(), 'awr_w_mean': exp_a.mean(),
|
| 117 |
+
'awr_w_max': exp_a.max(), 'awr_clip_frac': (exp_a >= 100.0).mean()}
|
| 118 |
+
if not self.config['discrete']:
|
| 119 |
+
info.update({'mse': jnp.mean((dist.mode() - batch['actions']) ** 2),
|
| 120 |
+
'std': jnp.mean(dist.scale_diag)})
|
| 121 |
+
return actor_loss, info
|
| 122 |
+
|
| 123 |
+
# ddpgbc (reference default)
|
| 124 |
+
dist = self.network.select('actor')(batch['observations'], batch['actor_goals'],
|
| 125 |
+
params=grad_params)
|
| 126 |
+
if self.config['const_std']:
|
| 127 |
+
q_actions = jnp.clip(dist.mode(), -1, 1)
|
| 128 |
+
else:
|
| 129 |
+
q_actions = jnp.clip(dist.sample(seed=rng), -1, 1)
|
| 130 |
+
q = crit(batch['observations'], batch['actor_goals'], q_actions)
|
| 131 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6)
|
| 132 |
+
log_prob = dist.log_prob(batch['actions'])
|
| 133 |
+
bc_loss = -(self.config['alpha'] * log_prob).mean()
|
| 134 |
+
actor_loss = q_loss + bc_loss
|
| 135 |
+
return actor_loss, {'actor_loss': actor_loss, 'q_loss': q_loss, 'bc_loss': bc_loss,
|
| 136 |
+
'q_mean': q.mean(), 'q_abs_mean': jnp.abs(q).mean(),
|
| 137 |
+
'bc_log_prob': log_prob.mean(),
|
| 138 |
+
'mse': jnp.mean((dist.mode() - batch['actions']) ** 2),
|
| 139 |
+
'std': jnp.mean(dist.scale_diag)}
|
| 140 |
+
|
| 141 |
+
@classmethod
|
| 142 |
+
def create(cls, seed, ex_observations, ex_actions, config):
|
| 143 |
+
rng = jax.random.PRNGKey(seed)
|
| 144 |
+
rng, init_rng = jax.random.split(rng, 2)
|
| 145 |
+
ex_goals = ex_observations
|
| 146 |
+
assert not config['discrete'], "GenQ-GCIQL assumes continuous actions"
|
| 147 |
+
action_dim = ex_actions.shape[-1]
|
| 148 |
+
ensemble = config['genq_ensemble']
|
| 149 |
+
|
| 150 |
+
encoders = dict()
|
| 151 |
+
if config['encoder'] is not None:
|
| 152 |
+
encoder_module = encoder_modules[config['encoder']]
|
| 153 |
+
for k in ('value', 'critic', 'actor'):
|
| 154 |
+
encoders[k] = GCEncoder(concat_encoder=encoder_module())
|
| 155 |
+
|
| 156 |
+
value_def = GCValue(hidden_dims=config['value_hidden_dims'], layer_norm=config['layer_norm'],
|
| 157 |
+
ensemble=False, gc_encoder=encoders.get('value'))
|
| 158 |
+
critic_def = GCValue(hidden_dims=config['value_hidden_dims'], layer_norm=config['layer_norm'],
|
| 159 |
+
ensemble=ensemble, gc_encoder=encoders.get('critic'))
|
| 160 |
+
actor_def = GCActor(hidden_dims=config['actor_hidden_dims'], action_dim=action_dim,
|
| 161 |
+
state_dependent_std=False, const_std=config['const_std'],
|
| 162 |
+
gc_encoder=encoders.get('actor'))
|
| 163 |
+
|
| 164 |
+
network_info = dict(
|
| 165 |
+
value=(value_def, (ex_observations, ex_goals)),
|
| 166 |
+
critic=(critic_def, (ex_observations, ex_goals, ex_actions)),
|
| 167 |
+
target_critic=(copy.deepcopy(critic_def), (ex_observations, ex_goals, ex_actions)),
|
| 168 |
+
actor=(actor_def, (ex_observations, ex_goals)),
|
| 169 |
+
)
|
| 170 |
+
networks = {k: v[0] for k, v in network_info.items()}
|
| 171 |
+
network_args = {k: v[1] for k, v in network_info.items()}
|
| 172 |
+
network_def = ModuleDict(networks)
|
| 173 |
+
network_tx = optax.adam(learning_rate=config['lr'])
|
| 174 |
+
network_params = network_def.init(init_rng, **network_args)['params']
|
| 175 |
+
network = TrainState.create(network_def, network_params, tx=network_tx)
|
| 176 |
+
params = network_params
|
| 177 |
+
params['modules_target_critic'] = params['modules_critic']
|
| 178 |
+
return cls(rng, network=network, config=flax.core.FrozenDict(**config))
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def get_config():
|
| 182 |
+
config = _gciql_get_config()
|
| 183 |
+
config['agent_name'] = 'gciql_genq'
|
| 184 |
+
config['actor_loss'] = 'ddpgbc' # reference default; overridden by driver --actor_loss
|
| 185 |
+
config['alpha'] = 0.3 # ddpgbc BC coeff (reference default); awr uses larger
|
| 186 |
+
config['genq_ensemble'] = True # 2-head critic + min (reference behavior)
|
| 187 |
+
config['adv_norm'] = False # standardize AWR advantage per batch (alpha becomes scale-free)
|
| 188 |
+
return config
|
gen_q_rsm/ogbench_genq/unused/genq/genq_discrete_jax.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Discrete Gen-Q occupancy for envs whose target space is a small discrete set
|
| 2 |
+
(puzzle button configs: {0,1}^9 = 512 classes for 3x3, 2^16 for 4x4).
|
| 3 |
+
|
| 4 |
+
Owner directive (issue #57 discussion): the puzzle target space is discrete, so use a
|
| 5 |
+
discrete generative model. For <= a few tens of thousands of configs the EXACT
|
| 6 |
+
maximum-likelihood conditional generative model is a categorical softmax over all
|
| 7 |
+
configs:
|
| 8 |
+
|
| 9 |
+
p_theta(c | s, a, g), c in {0,1}^K encoded as an integer class,
|
| 10 |
+
|
| 11 |
+
trained by cross-entropy on the same (s_t, a_t, g) -> bits(s_{t+k}), k ~ Geom(1-gamma)
|
| 12 |
+
tuples the diffusion occupancy uses. Compared to sampling a continuous diffusion:
|
| 13 |
+
|
| 14 |
+
* Q(s,a,g) = sum_c p(c|s,a,g) r(c;g) is computed EXACTLY (no occupancy-sample MC
|
| 15 |
+
noise — the read-out noise that limits the AWR action signal disappears);
|
| 16 |
+
* any distributional statistic is exact too, in particular the UPPER EXPECTILE
|
| 17 |
+
read-out Q_tau (optimistic value over the behavior policy's future randomness —
|
| 18 |
+
the TD-free improvement operator), via a weighted fixed-point over the 512 atoms.
|
| 19 |
+
|
| 20 |
+
This is an env-specific alternative head for the same Gen-Q formulation: the occupancy
|
| 21 |
+
is still learned by maximum likelihood with reward entering only at read-out time.
|
| 22 |
+
|
| 23 |
+
Train:
|
| 24 |
+
.ogbench_venv/bin/python ogbench_genq/genq/genq_discrete_jax.py \
|
| 25 |
+
--env puzzle-3x3-play-v0 --train_steps 200000
|
| 26 |
+
Load in the PI runner via genq_discrete_npz.
|
| 27 |
+
"""
|
| 28 |
+
import argparse
|
| 29 |
+
import os
|
| 30 |
+
import sys
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
|
| 34 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# ----------------------------- model -----------------------------
|
| 38 |
+
def make_mlp(in_dim, hidden_dim, num_layers, out_dim):
|
| 39 |
+
import flax.linen as fnn
|
| 40 |
+
|
| 41 |
+
class MLP(fnn.Module):
|
| 42 |
+
@fnn.compact
|
| 43 |
+
def __call__(self, x):
|
| 44 |
+
h = x
|
| 45 |
+
for _ in range(num_layers):
|
| 46 |
+
h = fnn.silu(fnn.Dense(hidden_dim)(h))
|
| 47 |
+
return fnn.Dense(out_dim)(h)
|
| 48 |
+
|
| 49 |
+
return MLP()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def bits_to_class(bits):
|
| 53 |
+
"""bits:[N,K] in {0,1} -> integer class [N]."""
|
| 54 |
+
K = bits.shape[-1]
|
| 55 |
+
pow2 = (2 ** np.arange(K)).astype(np.int64)
|
| 56 |
+
return (np.round(bits).astype(np.int64) @ pow2)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def class_bit_matrix(K):
|
| 60 |
+
"""[2^K, K] matrix of all configs' bits (float32)."""
|
| 61 |
+
C = np.arange(2 ** K, dtype=np.int64)
|
| 62 |
+
return ((C[:, None] >> np.arange(K)[None, :]) & 1).astype(np.float32)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ----------------------------- load + exact Q read-out -----------------------------
|
| 66 |
+
def load_discrete_params(ckpt_path):
|
| 67 |
+
d = np.load(ckpt_path)
|
| 68 |
+
import jax.numpy as jnp
|
| 69 |
+
n_layers = int(d["meta_num_layers"])
|
| 70 |
+
P = dict(
|
| 71 |
+
w=[jnp.asarray(d[f"dense_{i}_w"]) for i in range(n_layers + 1)],
|
| 72 |
+
b=[jnp.asarray(d[f"dense_{i}_b"]) for i in range(n_layers + 1)],
|
| 73 |
+
cond_mean=jnp.asarray(d["cond_mean"]), cond_std=jnp.asarray(d["cond_std"]),
|
| 74 |
+
bitmat=jnp.asarray(d["bitmat"]),
|
| 75 |
+
)
|
| 76 |
+
meta = dict(cond_dim=int(d["meta_cond_dim"]), n_class=int(d["meta_n_class"]),
|
| 77 |
+
k_bits=int(d["meta_k_bits"]), n_layers=n_layers)
|
| 78 |
+
return P, meta
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def discrete_logits(P, c_raw):
|
| 82 |
+
import jax.numpy as jnp
|
| 83 |
+
import jax
|
| 84 |
+
h = (c_raw - P["cond_mean"]) / P["cond_std"]
|
| 85 |
+
for i in range(len(P["w"]) - 1):
|
| 86 |
+
h = jax.nn.silu(h @ P["w"][i] + P["b"][i])
|
| 87 |
+
return h @ P["w"][-1] + P["b"][-1]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def genq_q_discrete(P, meta, s, a, g, sigma=0.5, readout_tau=0.0, iters=24):
|
| 91 |
+
"""EXACT Q under the categorical occupancy. s:[B,s], a:[B,a], g:[B,K] bits.
|
| 92 |
+
|
| 93 |
+
r_c(g) = exp(-||bits(c) - g||^2 / (2 sigma^2)) over all 2^K configs;
|
| 94 |
+
mean read-out: Q = sum_c p_c r_c (exact, no sampling);
|
| 95 |
+
readout_tau > 0: exact tau-expectile of r under p (weighted fixed point).
|
| 96 |
+
"""
|
| 97 |
+
import jax
|
| 98 |
+
import jax.numpy as jnp
|
| 99 |
+
logits = discrete_logits(P, jnp.concatenate([s, a, g], axis=-1)) # [B, C]
|
| 100 |
+
p = jax.nn.softmax(logits, axis=-1) # [B, C]
|
| 101 |
+
d2 = jnp.sum((P["bitmat"][None] - g[:, None, :]) ** 2, axis=-1) # [B, C]
|
| 102 |
+
if sigma <= 0:
|
| 103 |
+
# TRUE SPARSE read-out: r = 1[config == goal]. With an --absorb_goal
|
| 104 |
+
# occupancy this is EXACTLY P(first-passage to g within a Geom window) —
|
| 105 |
+
# the functional GCIQL's sparse reward + mask-at-success TD backup learns.
|
| 106 |
+
r = (d2 < 0.5).astype(p.dtype)
|
| 107 |
+
else:
|
| 108 |
+
r = jnp.exp(-d2 / (2.0 * sigma * sigma)) # [B, C]
|
| 109 |
+
if readout_tau and readout_tau > 0.0:
|
| 110 |
+
m = (p * r).sum(-1)
|
| 111 |
+
|
| 112 |
+
def step(m, _):
|
| 113 |
+
w = p * jnp.abs(readout_tau - (r < m[:, None]).astype(r.dtype))
|
| 114 |
+
m = (w * r).sum(-1) / (w.sum(-1) + 1e-12)
|
| 115 |
+
return m, None
|
| 116 |
+
|
| 117 |
+
m, _ = jax.lax.scan(step, m, None, length=iters)
|
| 118 |
+
return m
|
| 119 |
+
return (p * r).sum(-1)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ----------------------------- trainer -----------------------------
|
| 123 |
+
def main():
|
| 124 |
+
ap = argparse.ArgumentParser()
|
| 125 |
+
ap.add_argument("--env", required=True)
|
| 126 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 127 |
+
ap.add_argument("--train_steps", type=int, default=200000)
|
| 128 |
+
ap.add_argument("--batch_size", type=int, default=1024)
|
| 129 |
+
ap.add_argument("--lr", type=float, default=3e-4)
|
| 130 |
+
ap.add_argument("--hidden_dim", type=int, default=512)
|
| 131 |
+
ap.add_argument("--num_layers", type=int, default=3)
|
| 132 |
+
ap.add_argument("--gamma", type=float, default=0.99)
|
| 133 |
+
ap.add_argument("--absorb_goal", action="store_true",
|
| 134 |
+
help="absorbing occupancy: goal index first, future clamped at the goal "
|
| 135 |
+
"(j = min(t+Geom, gi)) — see train_genq_jax.py --absorb_goal.")
|
| 136 |
+
ap.add_argument("--ogbench_impls",
|
| 137 |
+
default=os.environ.get("OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls")))
|
| 138 |
+
ap.add_argument("--out", default=None)
|
| 139 |
+
args = ap.parse_args()
|
| 140 |
+
|
| 141 |
+
sys.path.insert(0, HERE)
|
| 142 |
+
sys.path.insert(0, args.ogbench_impls)
|
| 143 |
+
import jax
|
| 144 |
+
import jax.numpy as jnp
|
| 145 |
+
import optax
|
| 146 |
+
import tqdm
|
| 147 |
+
from utils.env_utils import make_env_and_datasets
|
| 148 |
+
import target_extractors
|
| 149 |
+
from target_extractors import env_safe_name
|
| 150 |
+
from train_genq_jax import build_ends, future_idx, sample_goal_after
|
| 151 |
+
|
| 152 |
+
assert "puzzle" in args.env, "discrete occupancy currently supports the puzzle envs (bit targets)"
|
| 153 |
+
safe = env_safe_name(args.env)
|
| 154 |
+
pkg = os.path.dirname(HERE)
|
| 155 |
+
out = args.out or os.path.join(pkg, "checkpoints", f"m9_genq_disc_{safe}.npz")
|
| 156 |
+
|
| 157 |
+
env, train_dataset, _ = make_env_and_datasets(args.env, frame_stack=None)
|
| 158 |
+
obs = np.asarray(train_dataset["observations"], dtype=np.float32)
|
| 159 |
+
act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1, 1)
|
| 160 |
+
end_of = build_ends(train_dataset["terminals"])
|
| 161 |
+
bits = target_extractors.extract_target(args.env, obs).astype(np.float32)
|
| 162 |
+
cls = bits_to_class(bits) # [N]
|
| 163 |
+
K = bits.shape[1]
|
| 164 |
+
n_class = 2 ** K
|
| 165 |
+
N = len(obs)
|
| 166 |
+
s = obs
|
| 167 |
+
cond_dim = s.shape[1] + act.shape[1] + K
|
| 168 |
+
print(f"[genq-disc] env={args.env} N={N} K={K} n_class={n_class} cond_dim={cond_dim} "
|
| 169 |
+
f"devices={jax.devices()}", flush=True)
|
| 170 |
+
|
| 171 |
+
rng_np = np.random.default_rng(args.seed)
|
| 172 |
+
|
| 173 |
+
def make_batch(bs):
|
| 174 |
+
t = rng_np.integers(0, N, bs)
|
| 175 |
+
if args.absorb_goal:
|
| 176 |
+
gi = sample_goal_after(t, end_of, rng_np)
|
| 177 |
+
j = np.minimum(future_idx(t, end_of, args.gamma, rng_np), gi)
|
| 178 |
+
else:
|
| 179 |
+
j = future_idx(t, end_of, args.gamma, rng_np)
|
| 180 |
+
gi = sample_goal_after(j, end_of, rng_np)
|
| 181 |
+
cond = np.concatenate([s[t], act[t], bits[gi]], axis=1).astype(np.float32)
|
| 182 |
+
return cond, cls[j]
|
| 183 |
+
|
| 184 |
+
cond0, _ = make_batch(20000)
|
| 185 |
+
cond_mean = cond0.mean(0)
|
| 186 |
+
cond_std = cond0.std(0) + 1e-6
|
| 187 |
+
|
| 188 |
+
model = make_mlp(cond_dim, args.hidden_dim, args.num_layers, n_class)
|
| 189 |
+
key = jax.random.PRNGKey(args.seed)
|
| 190 |
+
params = model.init(key, jnp.zeros((1, cond_dim)))
|
| 191 |
+
tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(args.lr))
|
| 192 |
+
opt = tx.init(params)
|
| 193 |
+
cm, cs = jnp.asarray(cond_mean), jnp.asarray(cond_std)
|
| 194 |
+
|
| 195 |
+
def loss_fn(pp, c, y):
|
| 196 |
+
logits = model.apply(pp, (c - cm) / cs)
|
| 197 |
+
return optax.softmax_cross_entropy_with_integer_labels(logits, y).mean()
|
| 198 |
+
|
| 199 |
+
@jax.jit
|
| 200 |
+
def update(pp, oo, c, y):
|
| 201 |
+
l, gr = jax.value_and_grad(loss_fn)(pp, c, y)
|
| 202 |
+
u, oo = tx.update(gr, oo, pp)
|
| 203 |
+
return optax.apply_updates(pp, u), oo, l
|
| 204 |
+
|
| 205 |
+
recent = []
|
| 206 |
+
for step in tqdm.trange(1, args.train_steps + 1, smoothing=0.1, dynamic_ncols=True):
|
| 207 |
+
c_b, y_b = make_batch(args.batch_size)
|
| 208 |
+
params, opt, l = update(params, opt, jnp.asarray(c_b), jnp.asarray(y_b))
|
| 209 |
+
recent.append(float(l))
|
| 210 |
+
if len(recent) > 200:
|
| 211 |
+
recent.pop(0)
|
| 212 |
+
if step % 5000 == 0 or step == 1:
|
| 213 |
+
print(f"[genq-disc:{safe}] step {step} CE(running) {np.mean(recent):.4f}", flush=True)
|
| 214 |
+
|
| 215 |
+
# export: flat dense layers
|
| 216 |
+
p = params["params"]
|
| 217 |
+
arrs = {}
|
| 218 |
+
names = sorted(p.keys(), key=lambda n: int(n.split("_")[-1]))
|
| 219 |
+
for i, n in enumerate(names):
|
| 220 |
+
arrs[f"dense_{i}_w"] = np.asarray(p[n]["kernel"], dtype=np.float32)
|
| 221 |
+
arrs[f"dense_{i}_b"] = np.asarray(p[n]["bias"], dtype=np.float32)
|
| 222 |
+
arrs.update(cond_mean=cond_mean.astype(np.float32), cond_std=cond_std.astype(np.float32),
|
| 223 |
+
bitmat=class_bit_matrix(K))
|
| 224 |
+
np.savez(out, **arrs, meta_cond_dim=np.asarray(cond_dim), meta_n_class=np.asarray(n_class),
|
| 225 |
+
meta_k_bits=np.asarray(K), meta_num_layers=np.asarray(args.num_layers))
|
| 226 |
+
print(f"[genq-disc] saved {out} (final CE {np.mean(recent):.4f})", flush=True)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
if __name__ == "__main__":
|
| 230 |
+
main()
|
gen_q_rsm/ogbench_genq/unused/genq/genq_inpaint_jax.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inpainting policy from a JOINT (first-action, future-target) Gen-Q occupancy.
|
| 2 |
+
|
| 3 |
+
Given a diffusion occupancy trained with train_genq_jax.py --action_in_target
|
| 4 |
+
(y = [a_t, target(x_{t+k})], cond = s_t, k ~ Geom(1-gamma)), the goal-conditioned
|
| 5 |
+
policy is the Bayes inverse of the occupancy:
|
| 6 |
+
|
| 7 |
+
pi(a | s, g) ~ p(a, x = g | s),
|
| 8 |
+
|
| 9 |
+
sampled by DDIM with REPLACEMENT INPAINTING: at every denoising step the target
|
| 10 |
+
block of x_t is overwritten with the goal forward-noised to the current level, so
|
| 11 |
+
the action block is denoised CONDITIONED on the future landing at g. Improvement
|
| 12 |
+
comes from conditioning on success — no AWR temperature, no critic, no TD.
|
| 13 |
+
|
| 14 |
+
Eval driver: run_inpaint_eval.py builds a duck-typed sample_actions policy from
|
| 15 |
+
this and rolls it out with OGBench evaluate.
|
| 16 |
+
"""
|
| 17 |
+
import jax
|
| 18 |
+
import jax.numpy as jnp
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_inpaint_params(ckpt_path):
|
| 23 |
+
"""Load an --action_in_target .genqjax.npz (same schema + meta_a_dim flag)."""
|
| 24 |
+
from genq_jax import load_genq_params
|
| 25 |
+
d = np.load(ckpt_path)
|
| 26 |
+
assert int(d.get("meta_action_in_target", 0)) == 1, (
|
| 27 |
+
f"{ckpt_path} was not trained with --action_in_target")
|
| 28 |
+
P, meta = load_genq_params(ckpt_path)
|
| 29 |
+
meta["a_dim"] = int(d["meta_a_dim"])
|
| 30 |
+
meta["x_dim"] = meta["y_dim"] - meta["a_dim"]
|
| 31 |
+
return P, meta
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def sample_actions_inpaint(P, meta, s, g_target, key, n_samples=1, steps=None):
|
| 35 |
+
"""Sample actions a ~ p(a | s, x=g) by replacement inpainting.
|
| 36 |
+
|
| 37 |
+
s:[B,s_dim] raw obs; g_target:[B,x_dim] goal in target space.
|
| 38 |
+
Returns actions [B, n_samples, a_dim] (clipped to [-1,1]).
|
| 39 |
+
"""
|
| 40 |
+
from genq_jax import eps_pred
|
| 41 |
+
steps = steps or meta["sample_steps"]
|
| 42 |
+
T = meta["T"]
|
| 43 |
+
a_dim, x_dim = meta["a_dim"], meta["x_dim"]
|
| 44 |
+
c = (s - P["cond_mean"]) / P["cond_std"]
|
| 45 |
+
B = c.shape[0]
|
| 46 |
+
cc = jnp.repeat(c, n_samples, axis=0) # [B*n, cond]
|
| 47 |
+
# goal block, normalized with the y-normalizer of the target slice
|
| 48 |
+
gk = (g_target - P["y_mean"][a_dim:]) / P["y_std"][a_dim:]
|
| 49 |
+
gk = jnp.repeat(gk, n_samples, axis=0) # [B*n, x_dim]
|
| 50 |
+
|
| 51 |
+
key, sub = jax.random.split(key)
|
| 52 |
+
x = jax.random.normal(sub, (B * n_samples, meta["y_dim"]), dtype=jnp.float32)
|
| 53 |
+
ts = jnp.clip(jnp.round(jnp.linspace(T, 1, steps)).astype(jnp.int32), 1, T)
|
| 54 |
+
|
| 55 |
+
def step(carry, i):
|
| 56 |
+
x, k = carry
|
| 57 |
+
t = ts[i]
|
| 58 |
+
abar_t = P["abar"][t - 1]
|
| 59 |
+
# replacement inpainting: overwrite the target block with the goal noised to level t
|
| 60 |
+
k, kn = jax.random.split(k)
|
| 61 |
+
noise = jax.random.normal(kn, gk.shape, dtype=jnp.float32)
|
| 62 |
+
x_known = jnp.sqrt(abar_t) * gk + jnp.sqrt(1.0 - abar_t) * noise
|
| 63 |
+
x = x.at[:, a_dim:].set(x_known)
|
| 64 |
+
tf = jnp.full((x.shape[0],), t.astype(jnp.float32) / T)
|
| 65 |
+
eps = eps_pred(P, meta, x, tf, cc)
|
| 66 |
+
x0 = (x - jnp.sqrt(1.0 - abar_t) * eps) / jnp.sqrt(abar_t)
|
| 67 |
+
x0 = jnp.clip(x0, -5.0, 5.0)
|
| 68 |
+
t_next = ts[jnp.minimum(i + 1, steps - 1)]
|
| 69 |
+
abar_n = P["abar"][t_next - 1]
|
| 70 |
+
x_next = jnp.sqrt(abar_n) * x0 + jnp.sqrt(jnp.clip(1.0 - abar_n, 0.0, None)) * eps
|
| 71 |
+
x = jnp.where(i < steps - 1, x_next, x0)
|
| 72 |
+
return (x, k), None
|
| 73 |
+
|
| 74 |
+
(x, _), _ = jax.lax.scan(step, (x, key), jnp.arange(steps))
|
| 75 |
+
a = x[:, :a_dim] * P["y_std"][:a_dim] + P["y_mean"][:a_dim] # unnormalize action block
|
| 76 |
+
return jnp.clip(a, -1.0, 1.0).reshape(B, n_samples, a_dim)
|
gen_q_rsm/ogbench_genq/unused/genq/genq_jax.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Native JAX Gen-Q — the conditional discounted-occupancy model + its Q estimate, pure JAX.
|
| 2 |
+
|
| 3 |
+
This is the occupancy model that produces the Gen-Q Q-values used by `gciql_genq.py`. It is a
|
| 4 |
+
**conditional denoising diffusion model** (DDPM cosine schedule, DDIM eta=0 sampling) over the
|
| 5 |
+
discounted future-state occupancy
|
| 6 |
+
|
| 7 |
+
p_theta(x_{t+k} | s_t, a_t, g), k ~ Geom(1 - gamma),
|
| 8 |
+
|
| 9 |
+
trained by `train_genq_jax.py` and loaded here from its `.genqjax.npz`. It is JAX end-to-end: NO
|
| 10 |
+
PyTorch, no torch checkpoints, no cross-process bridge. `genq_q(...)` is a plain in-graph JAX call
|
| 11 |
+
(jit-able, vmap-able) that runs in the SAME process as GCIQL.
|
| 12 |
+
|
| 13 |
+
Architecture (matches the trainer's flax ScoreNet, train_genq_jax.py:make_model):
|
| 14 |
+
- time_emb : SinusoidalEmbedding(time_dim) -> Linear -> SiLU -> Linear
|
| 15 |
+
- cond_emb : Linear(cond, hidden) -> SiLU
|
| 16 |
+
- x_emb : Linear(y, hidden)
|
| 17 |
+
- trunk : [Linear(.,hidden) -> SiLU] x num_layers (in0 = hidden+hidden+time_dim)
|
| 18 |
+
- out : Linear(hidden, y)
|
| 19 |
+
- cosine abar schedule (buffer), cond/y normalization (buffers)
|
| 20 |
+
- DDIM sampler (eta=0): x0 = (x - sqrt(1-abar_t) eps)/sqrt(abar_t), clamp [-5,5]; abar step.
|
| 21 |
+
|
| 22 |
+
Q estimate (occupancy-sample-and-average, goal-conditioned):
|
| 23 |
+
x_i ~ p_theta(.|s,a,g) (N draws), d_i = ||x_i - g||, Q = mean_i exp(-d_i^2 / (2 sigma^2)).
|
| 24 |
+
"""
|
| 25 |
+
import math
|
| 26 |
+
|
| 27 |
+
import jax
|
| 28 |
+
import jax.numpy as jnp
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _silu(x):
|
| 33 |
+
return x * jax.nn.sigmoid(x)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load_genq_params(ckpt_path):
|
| 37 |
+
"""Load Gen-Q diffusion weights (a `.genqjax.npz` from train_genq_jax.py) into jnp arrays + meta.
|
| 38 |
+
|
| 39 |
+
Pure numpy/JAX — no torch dependency, runs under the GPU-JAX venv.
|
| 40 |
+
"""
|
| 41 |
+
assert ckpt_path.endswith(".npz"), f"genq_jax loads .genqjax.npz only, got {ckpt_path}"
|
| 42 |
+
d = np.load(ckpt_path)
|
| 43 |
+
g = lambda k: jnp.asarray(d[k], dtype=jnp.float32)
|
| 44 |
+
n_layers = int(d["meta_num_layers"])
|
| 45 |
+
ck_get = lambda k: int(d[f"meta_{k}"])
|
| 46 |
+
P = dict(
|
| 47 |
+
time1_w=g("time_emb.1.weight"), time1_b=g("time_emb.1.bias"),
|
| 48 |
+
time3_w=g("time_emb.3.weight"), time3_b=g("time_emb.3.bias"),
|
| 49 |
+
cond_w=g("cond_emb.0.weight"), cond_b=g("cond_emb.0.bias"),
|
| 50 |
+
x_w=g("x_emb.weight"), x_b=g("x_emb.bias"),
|
| 51 |
+
out_w=g("out.weight"), out_b=g("out.bias"),
|
| 52 |
+
abar=g("abar"), abar_prev=g("abar_prev"),
|
| 53 |
+
cond_mean=g("cond_mean"), cond_std=g("cond_std"),
|
| 54 |
+
y_mean=g("y_mean"), y_std=g("y_std"),
|
| 55 |
+
)
|
| 56 |
+
P["trunk_w"] = [g(f"trunk.{2*i}.weight") for i in range(n_layers)]
|
| 57 |
+
P["trunk_b"] = [g(f"trunk.{2*i}.bias") for i in range(n_layers)]
|
| 58 |
+
meta = dict(cond_dim=ck_get("cond_dim"), y_dim=ck_get("y_dim"),
|
| 59 |
+
T=ck_get("diffusion_T"), sample_steps=ck_get("sample_steps"),
|
| 60 |
+
time_dim=int(P["time1_w"].shape[0]), n_layers=n_layers,
|
| 61 |
+
flow=bool(int(d["meta_model_flow"])) if "meta_model_flow" in d.files else False)
|
| 62 |
+
# hybrid continuous/discrete ckpt (train_genq_jax --mixed_bits): bit dims use masked
|
| 63 |
+
# absorbing-state discrete diffusion; the sampler commits them by categorical draws.
|
| 64 |
+
if "meta_mixed_bits" in d.files and int(d["meta_mixed_bits"]):
|
| 65 |
+
bm = np.asarray(d["bit_mask"]) > 0.5
|
| 66 |
+
meta["mixed"] = True
|
| 67 |
+
meta["bit_idx"] = jnp.asarray(np.where(bm)[0])
|
| 68 |
+
meta["n_bits"] = int(bm.sum())
|
| 69 |
+
else:
|
| 70 |
+
meta["mixed"] = False
|
| 71 |
+
return P, meta
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _sinusoid(t, dim):
|
| 75 |
+
"""t:[B] float in [0,1]; matches the trainer SinusoidalEmbedding (ang = t*freqs*1000)."""
|
| 76 |
+
half = dim // 2
|
| 77 |
+
freqs = jnp.exp(-math.log(10000.0) * jnp.arange(half, dtype=jnp.float32) / max(half - 1, 1))
|
| 78 |
+
ang = t[:, None] * freqs[None] * 1000.0
|
| 79 |
+
return jnp.concatenate([jnp.sin(ang), jnp.cos(ang)], axis=-1)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _lin(x, w, b):
|
| 83 |
+
return x @ w.T + b # weights stored [out,in] (torch-style); train_genq_jax stores kernel.T
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def eps_pred(P, meta, x, t_frac, c):
|
| 87 |
+
"""x:[B,y] normalized, t_frac:[B] in (0,1], c:[B,cond] normalized -> eps[B,y]."""
|
| 88 |
+
te = _sinusoid(t_frac, meta["time_dim"])
|
| 89 |
+
te = _lin(_silu(_lin(te, P["time1_w"], P["time1_b"])), P["time3_w"], P["time3_b"])
|
| 90 |
+
ce = _silu(_lin(c, P["cond_w"], P["cond_b"]))
|
| 91 |
+
xe = _lin(x, P["x_w"], P["x_b"])
|
| 92 |
+
h = jnp.concatenate([xe, ce, te], axis=-1)
|
| 93 |
+
for w, b in zip(P["trunk_w"], P["trunk_b"]):
|
| 94 |
+
h = _silu(_lin(h, w, b))
|
| 95 |
+
return _lin(h, P["out_w"], P["out_b"])
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def sample(P, meta, c_raw, n_samples, key, steps=None):
|
| 99 |
+
"""Sample the occupancy: DDIM (eta=0) for diffusion ckpts, Euler ODE for flow ckpts.
|
| 100 |
+
|
| 101 |
+
MIXED-BITS ckpts (meta["mixed"], train_genq_jax --mixed_bits): continuous dims follow
|
| 102 |
+
the Gaussian sampler; bit dims follow masked absorbing-state discrete diffusion — they
|
| 103 |
+
start MASKed (value 0, flag 1) and, as the shared signal level kappa rises (abar_t for
|
| 104 |
+
diffusion, t for flow), each masked bit unmasks w.p. (kappa_next-kappa)/(1-kappa) by a
|
| 105 |
+
Bernoulli draw from the predicted logit, then stays frozen and conditions every later
|
| 106 |
+
denoising step. Bits are returned as exact {0,1} — never a rounded Gaussian.
|
| 107 |
+
|
| 108 |
+
c_raw:[B,cond] raw. Returns x:[B,n_samples,y] raw coords."""
|
| 109 |
+
steps = steps or meta["sample_steps"]
|
| 110 |
+
T = meta["T"]
|
| 111 |
+
c = (c_raw - P["cond_mean"]) / P["cond_std"]
|
| 112 |
+
B = c.shape[0]
|
| 113 |
+
cc = jnp.repeat(c, n_samples, axis=0) # [B*n, cond]
|
| 114 |
+
key, sub = jax.random.split(key)
|
| 115 |
+
x = jax.random.normal(sub, (B * n_samples, meta["y_dim"]), dtype=jnp.float32)
|
| 116 |
+
mixed = meta.get("mixed", False)
|
| 117 |
+
if mixed:
|
| 118 |
+
bit_idx = meta["bit_idx"]
|
| 119 |
+
x = x.at[:, bit_idx].set(0.0) # all bits start MASKed
|
| 120 |
+
m = jnp.ones((B * n_samples, meta["n_bits"]), dtype=jnp.float32)
|
| 121 |
+
|
| 122 |
+
def commit_bits(out, x, m, p_un, key):
|
| 123 |
+
"""Unmask each still-masked bit w.p. p_un by a Bernoulli draw from its logit."""
|
| 124 |
+
key, k1, k2 = jax.random.split(key, 3)
|
| 125 |
+
b = (jax.random.uniform(k2, m.shape) < jax.nn.sigmoid(out[:, bit_idx])).astype(jnp.float32)
|
| 126 |
+
newly = m * (jax.random.uniform(k1, m.shape) < p_un).astype(jnp.float32)
|
| 127 |
+
bits = x[:, bit_idx] * (1.0 - newly) + (2.0 * b - 1.0) * newly # frozen once committed
|
| 128 |
+
return bits, m * (1.0 - newly), key
|
| 129 |
+
|
| 130 |
+
def finish(x):
|
| 131 |
+
x = x * P["y_std"] + P["y_mean"] # unnormalize (bit dims are identity-normalized)
|
| 132 |
+
if mixed:
|
| 133 |
+
x = x.at[:, bit_idx].set((x[:, bit_idx] + 1.0) * 0.5) # signed +-1 -> raw {0,1}
|
| 134 |
+
return x.reshape(B, n_samples, meta["y_dim"])
|
| 135 |
+
|
| 136 |
+
if meta.get("flow"):
|
| 137 |
+
dt = 1.0 / steps
|
| 138 |
+
|
| 139 |
+
def fstep(i, val):
|
| 140 |
+
x, m, key = val
|
| 141 |
+
tf = jnp.full((B * n_samples,), (i + 0.5) * dt) # midpoint of the Euler cell
|
| 142 |
+
v = eps_pred(P, meta, jnp.concatenate([x, m], -1) if mixed else x, tf, cc)
|
| 143 |
+
xn = x + v * dt # network predicts velocity
|
| 144 |
+
if mixed:
|
| 145 |
+
# visible fraction kappa = t: unmask prob over [i*dt, (i+1)*dt]
|
| 146 |
+
p_un = jnp.where(i >= steps - 1, 1.0,
|
| 147 |
+
jnp.clip(dt / (1.0 - i * dt), 0.0, 1.0))
|
| 148 |
+
bits, m, key = commit_bits(v, x, m, p_un, key)
|
| 149 |
+
xn = xn.at[:, bit_idx].set(bits)
|
| 150 |
+
return (xn, m, key)
|
| 151 |
+
|
| 152 |
+
dummy_m = m if mixed else jnp.zeros((0,), jnp.float32)
|
| 153 |
+
x, _, key = jax.lax.fori_loop(0, steps, fstep, (x, dummy_m, key))
|
| 154 |
+
return finish(x)
|
| 155 |
+
# ts = linspace(T,1,steps) cast to int, clamp[1,T] -> 1-based indices; abar index t-1
|
| 156 |
+
ts = jnp.clip(jnp.round(jnp.linspace(T, 1, steps)).astype(jnp.int32), 1, T)
|
| 157 |
+
|
| 158 |
+
def step(i, val):
|
| 159 |
+
x, m, key = val
|
| 160 |
+
t = ts[i]
|
| 161 |
+
abar_t = P["abar"][t - 1]
|
| 162 |
+
tf = jnp.full((B * n_samples,), t.astype(jnp.float32) / T)
|
| 163 |
+
out = eps_pred(P, meta, jnp.concatenate([x, m], -1) if mixed else x, tf, cc)
|
| 164 |
+
# eps target is N(0,1); clipping to +-6 sigma is a no-op on the healthy path but
|
| 165 |
+
# prevents the x ~ eps(x) self-feedback divergence on fine step grids (steps ~ T),
|
| 166 |
+
# where consecutive iterations sit in the tiny-abar region.
|
| 167 |
+
eps = jnp.clip(out, -6.0, 6.0)
|
| 168 |
+
x0 = (x - jnp.sqrt(1.0 - abar_t) * eps) / jnp.sqrt(abar_t)
|
| 169 |
+
x0 = jnp.clip(x0, -5.0, 5.0)
|
| 170 |
+
t_next = ts[jnp.minimum(i + 1, steps - 1)]
|
| 171 |
+
abar_n = P["abar"][t_next - 1]
|
| 172 |
+
x_next = jnp.sqrt(abar_n) * x0 + jnp.sqrt(jnp.clip(1.0 - abar_n, 0.0, None)) * eps
|
| 173 |
+
xn = jnp.where(i < steps - 1, x_next, x0)
|
| 174 |
+
if mixed:
|
| 175 |
+
# visible fraction kappa = abar: unmask prob for the abar_t -> abar_n move
|
| 176 |
+
kappa_n = jnp.where(i < steps - 1, abar_n, 1.0)
|
| 177 |
+
p_un = jnp.clip((kappa_n - abar_t) / (1.0 - abar_t + 1e-8), 0.0, 1.0)
|
| 178 |
+
bits, m, key = commit_bits(out, x, m, p_un, key) # logits from UNclipped out
|
| 179 |
+
xn = xn.at[:, bit_idx].set(bits)
|
| 180 |
+
return (xn, m, key)
|
| 181 |
+
|
| 182 |
+
dummy_m = m if mixed else jnp.zeros((0,), jnp.float32)
|
| 183 |
+
x, _, key = jax.lax.fori_loop(0, steps, step, (x, dummy_m, key))
|
| 184 |
+
return finish(x)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def sample_expectile(r, tau, weights=None, iters=24):
|
| 188 |
+
"""tau-expectile of samples r:[B,N] (optionally weighted), by fixed-point iteration.
|
| 189 |
+
|
| 190 |
+
The tau-expectile m solves sum_i w_i |tau - 1[r_i < m]| (r_i - m) = 0; iterating
|
| 191 |
+
m <- weighted_mean(r, w_i |tau - 1[r_i < m]|) converges monotonically. tau=0.5 is
|
| 192 |
+
the (weighted) mean; tau -> 1 approaches the max over the support. Used as the
|
| 193 |
+
OPTIMISTIC Gen-Q read-out: an upper expectile of the reward under the occupancy
|
| 194 |
+
implicitly maximizes over the behavior policy's future randomness — a TD-free
|
| 195 |
+
improvement operator on top of the same occupancy model.
|
| 196 |
+
"""
|
| 197 |
+
if weights is None:
|
| 198 |
+
weights = jnp.ones_like(r)
|
| 199 |
+
m0 = (weights * r).sum(-1) / weights.sum(-1)
|
| 200 |
+
|
| 201 |
+
def step(m, _):
|
| 202 |
+
w = weights * jnp.abs(tau - (r < m[:, None]).astype(r.dtype))
|
| 203 |
+
m = (w * r).sum(-1) / (w.sum(-1) + 1e-12)
|
| 204 |
+
return m, None
|
| 205 |
+
|
| 206 |
+
m, _ = jax.lax.scan(step, m0, None, length=iters)
|
| 207 |
+
return m
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def genq_q_goal_likelihood(P, meta, s, a, g, key, n_orders=8):
|
| 211 |
+
"""P(x = g | s, a, g) for a PURE-BITS mixed ckpt by teacher-forced any-order unmasking.
|
| 212 |
+
|
| 213 |
+
This is the reward-target importance-sampling read-out (issue #57, owner idea): instead
|
| 214 |
+
of drawing occupancy samples and checking whether they hit g (hit-or-miss, quantized to
|
| 215 |
+
1/n_occ, mostly exactly 0), collapse the proposal onto the reward target itself —
|
| 216 |
+
q = delta_g — so the IS estimate becomes the model's own probability mass at g.
|
| 217 |
+
Concretely: commit the bits to their GOAL values one at a time in a random order,
|
| 218 |
+
reading each bit's Bernoulli probability from the denoiser conditioned on the bits
|
| 219 |
+
already committed (the masked-diffusion any-order AR factorization), and accumulate
|
| 220 |
+
|
| 221 |
+
P(x=g) ~= E_order [ prod_i p_theta(x_{o_i} = g_{o_i} | x_{o_<i} = g_{o_<i}, s,a,g) ].
|
| 222 |
+
|
| 223 |
+
With an --absorb_goal occupancy this is a low-variance, CONTINUOUS estimate of the
|
| 224 |
+
first-passage probability that the sparse sample read-out estimates by indicator
|
| 225 |
+
averaging. ~27x cheaper than n_occ=64 sampling (n_bits x n_orders net calls/row) and
|
| 226 |
+
with zero hit-variance; residual variance is only over unmasking orders. (The parallel
|
| 227 |
+
sampler commits several bits per step independently, so sampled Q approximates this
|
| 228 |
+
one-at-a-time value.)
|
| 229 |
+
|
| 230 |
+
s:[B,s_dim] a:[B,a_dim] g:[B,y_dim] raw (bits in {0,1}). Returns Q:[B].
|
| 231 |
+
"""
|
| 232 |
+
assert meta.get("mixed") and meta["n_bits"] == meta["y_dim"], \
|
| 233 |
+
"goal-likelihood read-out needs a pure-bits --mixed_bits ckpt"
|
| 234 |
+
nb = meta["n_bits"]
|
| 235 |
+
T = meta["T"]
|
| 236 |
+
c = (jnp.concatenate([s, a, g], axis=-1) - P["cond_mean"]) / P["cond_std"]
|
| 237 |
+
B = c.shape[0]
|
| 238 |
+
cc = jnp.repeat(c, n_orders, axis=0) # [BO, cond]
|
| 239 |
+
BO = B * n_orders
|
| 240 |
+
g01 = jnp.round(jnp.clip(jnp.repeat(g, n_orders, axis=0), 0.0, 1.0)) # [BO, nb]
|
| 241 |
+
|
| 242 |
+
# schedule level when i bits are already visible: kappa = i/nb -> network time input.
|
| 243 |
+
# diffusion: t with abar_t closest to kappa; flow: t_frac = kappa (clamped >= 1/T).
|
| 244 |
+
kappas = np.arange(nb, dtype=np.float64) / nb
|
| 245 |
+
if meta.get("flow"):
|
| 246 |
+
ts_frac = np.maximum(kappas, 1.0 / T).astype(np.float32)
|
| 247 |
+
else:
|
| 248 |
+
abar = np.asarray(P["abar"]) # abar[t-1], decreasing-ish in t
|
| 249 |
+
ts_frac = np.array([(1 + int(np.argmin(np.abs(abar - k)))) / T for k in kappas],
|
| 250 |
+
dtype=np.float32)
|
| 251 |
+
ts_frac = jnp.asarray(ts_frac)
|
| 252 |
+
|
| 253 |
+
key, sub = jax.random.split(key)
|
| 254 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BO, nb)), axis=-1) # random orders
|
| 255 |
+
rows = jnp.arange(BO)
|
| 256 |
+
|
| 257 |
+
def step(carry, i):
|
| 258 |
+
x, m, logp = carry
|
| 259 |
+
out = eps_pred(P, meta, jnp.concatenate([x, m], -1),
|
| 260 |
+
jnp.full((BO,), ts_frac[i]), cc) # logits at bit positions
|
| 261 |
+
idx = orders[:, i]
|
| 262 |
+
logit = out[rows, idx]
|
| 263 |
+
gbit = g01[rows, idx]
|
| 264 |
+
logp = logp + gbit * jax.nn.log_sigmoid(logit) + (1.0 - gbit) * jax.nn.log_sigmoid(-logit)
|
| 265 |
+
x = x.at[rows, idx].set(2.0 * gbit - 1.0) # commit to the GOAL value
|
| 266 |
+
m = m.at[rows, idx].set(0.0)
|
| 267 |
+
return (x, m, logp), None
|
| 268 |
+
|
| 269 |
+
init = (jnp.zeros((BO, nb), jnp.float32), jnp.ones((BO, nb), jnp.float32),
|
| 270 |
+
jnp.zeros((BO,), jnp.float32))
|
| 271 |
+
(x, m, logp), _ = jax.lax.scan(step, init, jnp.arange(nb))
|
| 272 |
+
return jnp.exp(logp).reshape(B, n_orders).mean(axis=1) # [B] = P(x = g)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def genq_q(P, meta, s, a, g, key, n_occ=16, sigma=5.0, steps=None, readout_tau=0.0):
|
| 276 |
+
"""Occupancy-sample-and-average Q. s:[B,s_dim] a:[B,a_dim] g:[B,g_dim] (g_dim==y_dim).
|
| 277 |
+
|
| 278 |
+
Q(s,a,g) = (1/N) sum_i exp(-||x_i - g||^2 / (2 sigma^2)), x_i ~ p_theta(.|s,a,g).
|
| 279 |
+
Returns Q:[B]. Pure JAX — jit/vmap-able, runs in-process with GCIQL.
|
| 280 |
+
|
| 281 |
+
readout_tau > 0.5 replaces the mean with the tau-expectile of {r_i}: an optimistic
|
| 282 |
+
read-out approaching max-over-futures as tau -> 1 (see sample_expectile).
|
| 283 |
+
"""
|
| 284 |
+
c = jnp.concatenate([s, a, g], axis=-1) # cond = [s,a,g], cond_dim = s+a+g
|
| 285 |
+
x = sample(P, meta, c, n_occ, key, steps=steps) # [B,N,y]
|
| 286 |
+
# sigma may be a scalar or a per-dim vector [y_dim] (wider targets weight the
|
| 287 |
+
# task bits sharply and the dense action-responsive dims softly). sigma <= 0
|
| 288 |
+
# selects the TRUE SPARSE read-out r = 1[round(x) == g] (with an --absorb_goal
|
| 289 |
+
# occupancy this estimates GCIQL's first-passage functional).
|
| 290 |
+
if np.ndim(sigma) == 0 and float(sigma) <= 0:
|
| 291 |
+
r = (jnp.sum((x - g[:, None, :]) ** 2, axis=-1) < 0.25).astype(jnp.float32)
|
| 292 |
+
else:
|
| 293 |
+
sig = jnp.asarray(sigma, dtype=jnp.float32)
|
| 294 |
+
d2 = jnp.sum(((x - g[:, None, :]) / sig) ** 2, axis=-1) # [B,N]
|
| 295 |
+
r = jnp.exp(-d2 / 2.0)
|
| 296 |
+
if readout_tau and readout_tau > 0.0:
|
| 297 |
+
return sample_expectile(r, readout_tau) # [B] optimistic read-out
|
| 298 |
+
return r.mean(axis=1) # [B]
|
gen_q_rsm/ogbench_genq/unused/genq/genq_recursive_jax.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Recursive Gen-Q: recover the long-horizon d_gamma occupancy from a SHORT-beta
|
| 2 |
+
occupancy diffusion by probabilistic recursive composition. JAX-only, fully jitted.
|
| 3 |
+
|
| 4 |
+
Mechanism
|
| 5 |
+
---------
|
| 6 |
+
Train the occupancy diffusion p_theta on a SHORT discount beta (see
|
| 7 |
+
train_genq_jax.py --gamma <beta> --state_target), then recover the TARGET
|
| 8 |
+
discount gamma at read-out time by chaining geometric jumps:
|
| 9 |
+
|
| 10 |
+
z_0 = s
|
| 11 |
+
repeat: z_{n+1} ~ d_beta(. | z_n, a_n, g); stop w.p. p and return z_{n+1}
|
| 12 |
+
p = beta (1 - gamma) / (gamma (1 - beta)) (valid iff beta <= gamma)
|
| 13 |
+
|
| 14 |
+
The returned endpoint is distributed EXACTLY as d_gamma(. | s, a, g): one d_beta
|
| 15 |
+
jump advances time by K ~ Geom(1-beta) (pgf (1-beta)/(1-beta z)); the number of
|
| 16 |
+
jumps is N ~ Geom(p) on {1,2,...}; the total offset T = sum_{i<=N} K_i then has pgf
|
| 17 |
+
|
| 18 |
+
p G_K / (1 - (1-p) G_K) = (1-gamma)/(1-gamma z) iff p = beta(1-gamma)/(gamma(1-beta)),
|
| 19 |
+
|
| 20 |
+
i.e. T ~ Geom(1-gamma) — the d_gamma jump distribution. No TD, no bootstrap, no
|
| 21 |
+
world model; the Q read-out is unchanged: Q(s,a,g) = E_{y~d_gamma}[r(y; g)].
|
| 22 |
+
|
| 23 |
+
E[jumps] = 1/p = gamma(1-beta)/(beta(1-gamma)); for gamma=0.99: beta=0.9 -> 11.0,
|
| 24 |
+
beta=0.95 -> 5.2. Choose beta near gamma to keep the chain short.
|
| 25 |
+
|
| 26 |
+
State==target requirement
|
| 27 |
+
-------------------------
|
| 28 |
+
The chain feeds each sampled midpoint back in as the next conditioning state, so
|
| 29 |
+
the occupancy's conditioning state must live in the SAME space as its sample
|
| 30 |
+
target. Train the short-beta occupancy with --state_target, which conditions on
|
| 31 |
+
extract_target(obs) instead of the full observation:
|
| 32 |
+
|
| 33 |
+
* mazes: target == xy position — the conditioning pointmaze already uses
|
| 34 |
+
(exact); for loco mazes this is the position-Markov approximation.
|
| 35 |
+
* manipulation (cube/puzzle/scene): target == the low-dim task slice (cube
|
| 36 |
+
xyz / button bits). Conditioning on the task slice alone is a TARGET-MARKOV
|
| 37 |
+
APPROXIMATION — it marginalizes the arm state — and is the documented cost
|
| 38 |
+
of running the recursion in-graph on these envs.
|
| 39 |
+
|
| 40 |
+
Midpoint actions come from a small goal-conditioned BC actor fit on the same
|
| 41 |
+
dataset, (target_state, goal) -> action (`fit_midpoint_actor`), standing in for
|
| 42 |
+
the behavior policy at each jump.
|
| 43 |
+
|
| 44 |
+
Approximations (documented, both small by construction):
|
| 45 |
+
* chains are truncated at max_depth = ceil(3/p) jumps (residual mass
|
| 46 |
+
(1-p)^max_depth ~ e^-3 ~ 5%); unfinished chains return their last midpoint;
|
| 47 |
+
* the gc-BC midpoint actor approximates the data-collection policy.
|
| 48 |
+
|
| 49 |
+
Everything below is jit/vmap-able: the chain is one `jax.lax.scan` of static
|
| 50 |
+
length max_depth over M = B * n_occ independent chains, each scan step doing a
|
| 51 |
+
single batched DDIM call — linear in depth, no N^depth tree, no Python overhead.
|
| 52 |
+
"""
|
| 53 |
+
import math
|
| 54 |
+
|
| 55 |
+
import jax
|
| 56 |
+
import jax.numpy as jnp
|
| 57 |
+
import numpy as np
|
| 58 |
+
|
| 59 |
+
from genq_jax import sample, sample_expectile
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def stop_prob(beta, gamma):
|
| 63 |
+
"""Per-jump stop probability p = beta(1-gamma)/(gamma(1-beta)).
|
| 64 |
+
|
| 65 |
+
Composing Geom(1-beta) jump lengths over Geom(p) jumps gives a total offset
|
| 66 |
+
distributed Geom(1-gamma) exactly (pgf identity in the module docstring).
|
| 67 |
+
Valid (p in (0,1]) iff beta <= gamma.
|
| 68 |
+
"""
|
| 69 |
+
assert beta <= gamma, f"recursion needs beta <= gamma (got beta={beta} > gamma={gamma})"
|
| 70 |
+
return beta * (1.0 - gamma) / (gamma * (1.0 - beta))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def default_max_depth(beta, gamma):
|
| 74 |
+
"""ceil(3/p) jumps: ~3x the expected chain length, truncation mass ~e^-3."""
|
| 75 |
+
return int(math.ceil(3.0 / stop_prob(beta, gamma)))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def recursive_endpoints(P, meta, s, a, g, key, actor_fn, beta, gamma, max_depth,
|
| 79 |
+
steps=None, greedy_k=0, greedy_noise=0.3, greedy_n_occ=2,
|
| 80 |
+
greedy_sigma=0.5):
|
| 81 |
+
"""Sample y ~ d_gamma(.|s,a,g) by recursive short-beta jumps.
|
| 82 |
+
|
| 83 |
+
s:[M,y_dim] (state==target space), a:[M,a_dim], g:[M,y_dim];
|
| 84 |
+
actor_fn(state[M,y_dim], goal[M,y_dim]) -> action[M,a_dim] supplies the
|
| 85 |
+
midpoint (behavior) action. Returns endpoints [M,y_dim]. max_depth is
|
| 86 |
+
static, so the whole chain jits as one lax.scan.
|
| 87 |
+
|
| 88 |
+
greedy_k > 0 turns each midpoint into a GREEDY improvement step (approximate
|
| 89 |
+
value iteration, no TD): propose greedy_k candidate actions (the midpoint
|
| 90 |
+
actor's mode + Gaussian perturbations of scale greedy_noise), score each with
|
| 91 |
+
the short-beta occupancy Q (greedy_n_occ samples, bandwidth greedy_sigma —
|
| 92 |
+
the short horizon is where the Gen-Q action contrast is strongest), and jump
|
| 93 |
+
with the argmax. Greedy selection compounds over the ~1/p jumps, so the
|
| 94 |
+
composed endpoints approximate d_gamma of the greedy policy rather than the
|
| 95 |
+
behavior policy.
|
| 96 |
+
"""
|
| 97 |
+
p = stop_prob(beta, gamma)
|
| 98 |
+
M = s.shape[0]
|
| 99 |
+
y_dim = meta["y_dim"]
|
| 100 |
+
|
| 101 |
+
def pick_action(z, k):
|
| 102 |
+
"""Greedy midpoint: argmax over candidates of the short-beta occupancy Q."""
|
| 103 |
+
a_bc = actor_fn(z, g) # [M, a_dim]
|
| 104 |
+
k_n, k_s = jax.random.split(k)
|
| 105 |
+
eps = greedy_noise * jax.random.normal(k_n, (greedy_k, M, a_bc.shape[-1]))
|
| 106 |
+
eps = eps.at[0].set(0.0) # candidate 0 = BC mode
|
| 107 |
+
cands = jnp.clip(a_bc[None] + eps, -1, 1) # [K, M, a_dim]
|
| 108 |
+
zK = jnp.broadcast_to(z, (greedy_k,) + z.shape).reshape(greedy_k * M, y_dim)
|
| 109 |
+
gK = jnp.broadcast_to(g, (greedy_k,) + g.shape).reshape(greedy_k * M, y_dim)
|
| 110 |
+
cK = jnp.concatenate([zK, cands.reshape(greedy_k * M, -1), gK], axis=-1)
|
| 111 |
+
x = sample(P, meta, cK, greedy_n_occ, k_s, steps=steps) # [K*M, n, y]
|
| 112 |
+
# greedy_sigma may be a scalar or a per-dim vector [y_dim] (target variants:
|
| 113 |
+
# bits sharp, dense action-responsive dims soft) — same convention as genq_q.
|
| 114 |
+
gsig = jnp.asarray(greedy_sigma, dtype=jnp.float32)
|
| 115 |
+
d2 = jnp.sum(((x - gK[:, None, :]) / gsig) ** 2, axis=-1)
|
| 116 |
+
q = jnp.exp(-d2 / 2.0).mean(1).reshape(greedy_k, M)
|
| 117 |
+
return jnp.take_along_axis(cands, jnp.argmax(q, axis=0)[None, :, None], axis=0)[0]
|
| 118 |
+
|
| 119 |
+
def body(carry, _):
|
| 120 |
+
z, a_cur, done, endpoint, k = carry
|
| 121 |
+
k, k_jump, k_stop, k_act = jax.random.split(k, 4)
|
| 122 |
+
c = jnp.concatenate([z, a_cur, g], axis=-1)
|
| 123 |
+
z_next = sample(P, meta, c, 1, k_jump, steps=steps)[:, 0, :] # one d_beta jump [M,y]
|
| 124 |
+
stop = jax.random.bernoulli(k_stop, p, (M,))
|
| 125 |
+
newly = stop & (~done) # freeze at FIRST stop
|
| 126 |
+
endpoint = jnp.where(newly[:, None], z_next, endpoint)
|
| 127 |
+
done = done | stop
|
| 128 |
+
if greedy_k > 0:
|
| 129 |
+
a_next = pick_action(z_next, k_act) # greedy improvement step
|
| 130 |
+
else:
|
| 131 |
+
a_next = actor_fn(z_next, g) # in-graph midpoint action
|
| 132 |
+
return (z_next, a_next, done, endpoint, k), None
|
| 133 |
+
|
| 134 |
+
init = (s, a, jnp.zeros((M,), bool), jnp.zeros((M, y_dim), jnp.float32), key)
|
| 135 |
+
(z_last, _, done, endpoint, _), _ = jax.lax.scan(body, init, None, length=max_depth)
|
| 136 |
+
# truncation fallback: chains that never stopped return their last midpoint.
|
| 137 |
+
return jnp.where(done[:, None], endpoint, z_last)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def genq_q_recursive(P, meta, s, a, g, key, actor_fn, n_occ=16, beta=0.95,
|
| 141 |
+
gamma=0.99, max_depth=None, sigma=5.0, steps=None,
|
| 142 |
+
greedy_k=0, greedy_noise=0.3, greedy_n_occ=2, greedy_sigma=0.5,
|
| 143 |
+
readout_tau=0.0):
|
| 144 |
+
"""Recursive-d_gamma Gen-Q read-out; drop-in for genq_jax.genq_q, but P is a
|
| 145 |
+
SHORT-beta occupancy trained with --state_target (state==target).
|
| 146 |
+
|
| 147 |
+
Q(s,a,g) = (1/n_occ) sum_i exp(-||y_i - g||^2 / (2 sigma^2)),
|
| 148 |
+
y_i ~ d_gamma(.|s,a,g) via recursive composition. Returns Q:[B].
|
| 149 |
+
greedy_k > 0 makes each midpoint a greedy improvement step (see
|
| 150 |
+
recursive_endpoints), so Q approaches a value-iteration fixed point.
|
| 151 |
+
|
| 152 |
+
sigma may be a scalar or a per-dim vector [y_dim] (genq_q convention).
|
| 153 |
+
readout_tau > 0.5 replaces the endpoint mean with the tau-expectile of {r_i}
|
| 154 |
+
(genq_jax.sample_expectile): OPTIMISM over the composed chain's randomness —
|
| 155 |
+
with greedy midpoints this maximizes over both action candidates (in-chain)
|
| 156 |
+
and future randomness (at read-out), the strongest TD-free improvement stack.
|
| 157 |
+
"""
|
| 158 |
+
if max_depth is None:
|
| 159 |
+
max_depth = default_max_depth(beta, gamma)
|
| 160 |
+
B, y_dim = s.shape[0], meta["y_dim"]
|
| 161 |
+
sM = jnp.repeat(s, n_occ, axis=0)
|
| 162 |
+
aM = jnp.repeat(a, n_occ, axis=0)
|
| 163 |
+
gM = jnp.repeat(g, n_occ, axis=0)
|
| 164 |
+
y = recursive_endpoints(P, meta, sM, aM, gM, key, actor_fn, beta, gamma,
|
| 165 |
+
max_depth, steps=steps, greedy_k=greedy_k,
|
| 166 |
+
greedy_noise=greedy_noise, greedy_n_occ=greedy_n_occ,
|
| 167 |
+
greedy_sigma=greedy_sigma) # [B*n_occ, y]
|
| 168 |
+
y = y.reshape(B, n_occ, y_dim)
|
| 169 |
+
sig = jnp.asarray(sigma, dtype=jnp.float32)
|
| 170 |
+
d2 = jnp.sum(((y - g[:, None, :]) / sig) ** 2, axis=-1) # [B, n_occ]
|
| 171 |
+
r = jnp.exp(-d2 / 2.0)
|
| 172 |
+
if readout_tau and readout_tau > 0.0:
|
| 173 |
+
return sample_expectile(r, readout_tau) # [B] optimistic
|
| 174 |
+
return r.mean(axis=1)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def fit_midpoint_actor(state, action, end_of, goal_of, steps=30000, batch_size=256,
|
| 178 |
+
hidden_dim=256, num_layers=3, lr=3e-4, seed=0, log_every=10000,
|
| 179 |
+
weight_fn=None):
|
| 180 |
+
"""Fit the gc-BC midpoint actor (target_state, goal) -> action (tanh mode).
|
| 181 |
+
|
| 182 |
+
state:[N,y_dim] the occupancy's target-space state per dataset step;
|
| 183 |
+
action:[N,a_dim]; end_of:[N] one-past-the-last index of each step's
|
| 184 |
+
trajectory; goal_of(idx)->[len(idx),y_dim] maps dataset indices to
|
| 185 |
+
target-space goals (hindsight goals are drawn downstream in-trajectory).
|
| 186 |
+
Returns (actor_fn, final_loss) with actor_fn(z, g) -> action, pure-JAX and
|
| 187 |
+
usable inside jit (params are closed over as constants).
|
| 188 |
+
|
| 189 |
+
weight_fn: optional (s[B,y], g[B,y], a[B,a_dim], key) -> w[B] per-sample BC
|
| 190 |
+
weights (e.g. exp of a short-beta Gen-Q advantage). Turns the plain gc-BC
|
| 191 |
+
midpoint into an ADVANTAGE-WEIGHTED midpoint policy, so the recursive chain
|
| 192 |
+
composes an improved policy's occupancy (soft policy iteration, no TD).
|
| 193 |
+
"""
|
| 194 |
+
import flax.linen as fnn
|
| 195 |
+
import optax
|
| 196 |
+
|
| 197 |
+
N, a_dim = len(state), action.shape[1]
|
| 198 |
+
y_dim = state.shape[1]
|
| 199 |
+
|
| 200 |
+
class _BC(fnn.Module):
|
| 201 |
+
@fnn.compact
|
| 202 |
+
def __call__(self, s, g):
|
| 203 |
+
h = jnp.concatenate([s, g], -1)
|
| 204 |
+
for _ in range(num_layers):
|
| 205 |
+
h = fnn.relu(fnn.Dense(hidden_dim)(h))
|
| 206 |
+
return jnp.tanh(fnn.Dense(a_dim)(h))
|
| 207 |
+
|
| 208 |
+
bc = _BC()
|
| 209 |
+
params = bc.init(jax.random.PRNGKey(seed), jnp.zeros((1, y_dim)), jnp.zeros((1, y_dim)))
|
| 210 |
+
tx = optax.adam(lr)
|
| 211 |
+
opt = tx.init(params)
|
| 212 |
+
|
| 213 |
+
def loss_fn(pp, s, g, a, w):
|
| 214 |
+
return jnp.mean(w[:, None] * (bc.apply(pp, s, g) - a) ** 2)
|
| 215 |
+
|
| 216 |
+
@jax.jit
|
| 217 |
+
def update(pp, oo, s, g, a, w):
|
| 218 |
+
l, gr = jax.value_and_grad(loss_fn)(pp, s, g, a, w)
|
| 219 |
+
u, oo = tx.update(gr, oo, pp)
|
| 220 |
+
return optax.apply_updates(pp, u), oo, l
|
| 221 |
+
|
| 222 |
+
rng = np.random.default_rng(seed)
|
| 223 |
+
wkey = jax.random.PRNGKey(seed + 4242)
|
| 224 |
+
act_clip = np.clip(np.asarray(action, dtype=np.float32), -1, 1)
|
| 225 |
+
l = float("nan")
|
| 226 |
+
for step in range(1, steps + 1):
|
| 227 |
+
t = rng.integers(0, N, batch_size)
|
| 228 |
+
span = np.maximum(end_of[t] - 1 - t, 1) # hindsight goal downstream
|
| 229 |
+
gi = np.clip(t + (rng.random(batch_size) * span).astype(np.int64), 0, N - 1)
|
| 230 |
+
s_b, g_b, a_b = jnp.asarray(state[t]), jnp.asarray(goal_of(gi)), jnp.asarray(act_clip[t])
|
| 231 |
+
if weight_fn is not None:
|
| 232 |
+
wkey, sub = jax.random.split(wkey)
|
| 233 |
+
w_b = weight_fn(s_b, g_b, a_b, sub)
|
| 234 |
+
else:
|
| 235 |
+
w_b = jnp.ones((batch_size,), jnp.float32)
|
| 236 |
+
params, opt, l = update(params, opt, s_b, g_b, a_b, w_b)
|
| 237 |
+
if log_every and step % log_every == 0:
|
| 238 |
+
print(f"[midpoint-bc] step {step} loss {float(l):.4f}", flush=True)
|
| 239 |
+
|
| 240 |
+
def actor_fn(z, g):
|
| 241 |
+
return bc.apply(params, z, g)
|
| 242 |
+
|
| 243 |
+
return actor_fn, float(l)
|
gen_q_rsm/ogbench_genq/unused/genq/run_inpaint_eval.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluate the Gen-Q INPAINTING policy pi(a|s,g) ~ p(a, x=g | s) on an OGBench env.
|
| 2 |
+
|
| 3 |
+
No actor training at all: the policy is read directly off the joint
|
| 4 |
+
(first-action, future-target) occupancy by goal-inpainting (genq_inpaint_jax.py).
|
| 5 |
+
Rolls out with OGBench `evaluate` over all tasks and writes
|
| 6 |
+
experiments/{env}/results/{seed}/genq_inpaint[_tag].json.
|
| 7 |
+
|
| 8 |
+
Run:
|
| 9 |
+
.ogbench_venv/bin/python ogbench_genq/genq/run_inpaint_eval.py \
|
| 10 |
+
--env puzzle-3x3-play-v0 --genq_npz <action_in_target ckpt> [--n_prop 4]
|
| 11 |
+
|
| 12 |
+
n_prop > 1 draws several inpainted actions per step and executes their MEAN
|
| 13 |
+
(inpainting samples are unimodal per goal in action space more often than not;
|
| 14 |
+
the mean suppresses DDIM noise).
|
| 15 |
+
"""
|
| 16 |
+
import argparse
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 25 |
+
PKG = os.path.dirname(HERE)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
ap = argparse.ArgumentParser()
|
| 30 |
+
ap.add_argument("--env", required=True)
|
| 31 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 32 |
+
ap.add_argument("--genq_npz", required=True)
|
| 33 |
+
ap.add_argument("--n_prop", type=int, default=4)
|
| 34 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 35 |
+
ap.add_argument("--tag", default=None)
|
| 36 |
+
ap.add_argument("--ogbench_impls",
|
| 37 |
+
default=os.environ.get("OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls")))
|
| 38 |
+
args = ap.parse_args()
|
| 39 |
+
|
| 40 |
+
sys.path.insert(0, HERE)
|
| 41 |
+
sys.path.insert(0, args.ogbench_impls)
|
| 42 |
+
import jax
|
| 43 |
+
import jax.numpy as jnp
|
| 44 |
+
from utils.env_utils import make_env_and_datasets
|
| 45 |
+
from utils.evaluation import evaluate
|
| 46 |
+
import target_extractors
|
| 47 |
+
from genq_inpaint_jax import load_inpaint_params, sample_actions_inpaint
|
| 48 |
+
|
| 49 |
+
t0 = time.time()
|
| 50 |
+
env, _, _ = make_env_and_datasets(args.env, frame_stack=None)
|
| 51 |
+
P, meta = load_inpaint_params(args.genq_npz)
|
| 52 |
+
print(f"[inpaint] {os.path.basename(args.genq_npz)} a_dim={meta['a_dim']} "
|
| 53 |
+
f"x_dim={meta['x_dim']} n_prop={args.n_prop}", flush=True)
|
| 54 |
+
|
| 55 |
+
fn = jax.jit(lambda s, g, k: sample_actions_inpaint(P, meta, s, g, k,
|
| 56 |
+
n_samples=args.n_prop))
|
| 57 |
+
|
| 58 |
+
class InpaintPolicy:
|
| 59 |
+
def __init__(self, seed):
|
| 60 |
+
self.key = jax.random.PRNGKey(seed)
|
| 61 |
+
|
| 62 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 63 |
+
s = np.asarray(observations, dtype=np.float32)[None]
|
| 64 |
+
g = target_extractors.extract_target(args.env, np.asarray(goals)[None]).astype(np.float32)
|
| 65 |
+
self.key, sub = jax.random.split(self.key)
|
| 66 |
+
a = np.asarray(fn(jnp.asarray(s), jnp.asarray(g), sub))[0] # [n_prop, a_dim]
|
| 67 |
+
return a.mean(axis=0)
|
| 68 |
+
|
| 69 |
+
pol = InpaintPolicy(args.seed)
|
| 70 |
+
task_infos = env.unwrapped.task_infos if hasattr(env.unwrapped, "task_infos") else env.task_infos
|
| 71 |
+
per = []
|
| 72 |
+
for tid in range(1, len(task_infos) + 1):
|
| 73 |
+
ei, _, _ = evaluate(agent=pol, env=env, task_id=tid, config={},
|
| 74 |
+
num_eval_episodes=args.eval_episodes, num_video_episodes=0,
|
| 75 |
+
video_frame_skip=3, eval_temperature=0.0, eval_gaussian=None)
|
| 76 |
+
per.append(float(ei.get("success", 0.0)))
|
| 77 |
+
print(f"[inpaint] task {tid}: success={per[-1]:.3f}", flush=True)
|
| 78 |
+
sr = float(np.mean(per))
|
| 79 |
+
|
| 80 |
+
tag = f"_{args.tag}" if args.tag else ""
|
| 81 |
+
outdir = os.path.join(PKG, "experiments", args.env, "results", str(args.seed))
|
| 82 |
+
os.makedirs(outdir, exist_ok=True)
|
| 83 |
+
out = os.path.join(outdir, f"genq_inpaint{tag}.json")
|
| 84 |
+
json.dump({"method": "genq_inpaint", "env": args.env, "seed": args.seed,
|
| 85 |
+
"genq_npz": os.path.basename(args.genq_npz), "n_prop": args.n_prop,
|
| 86 |
+
"success_rate": sr, "best_sr": sr, "per_task": per,
|
| 87 |
+
"curve": [[0, sr]], "train_steps": 0,
|
| 88 |
+
"wall_clock_sec": round(time.time() - t0, 1), "wandb_url": ""},
|
| 89 |
+
open(out, "w"), indent=2)
|
| 90 |
+
print(f"[inpaint] {args.env} FINAL sr={sr:.3f} -> {out}", flush=True)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
main()
|
gen_q_rsm/ogbench_genq/unused/genq_factored.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FACTORED Gen-Q policy improvement (issue #57, owner directive): two models only.
|
| 2 |
+
|
| 3 |
+
p(a, x | s, g) = pi_beta(a | s, g) * d^beta(x | s, a, g)
|
| 4 |
+
pi_plus(a | s, g) proportional to pi_beta(a | s, g) * P(x = g | s, a, g)^kappa
|
| 5 |
+
|
| 6 |
+
Policy improvement = conditioning the joint on SUCCESS (the future reaching the goal):
|
| 7 |
+
the action posterior under the absorbing occupancy. Both factors already exist in their
|
| 8 |
+
best validated forms — P(x=g|s,a,g) is the goal-likelihood read-out on the mixed-bits
|
| 9 |
+
occupancy (exact, continuous, cheap), and pi_beta is a plain goal-conditioned BC head.
|
| 10 |
+
No distilled critic, no expectile V, no TD network, no DDPG: improvement happens AT THE
|
| 11 |
+
READ-OUT by tilting K behavior proposals with weights softmax(kappa * log P). kappa is
|
| 12 |
+
the greediness knob (kappa -> inf = argmax filter; kappa = 1 = exact posterior = the
|
| 13 |
+
KL-regularized optimal policy for reward log P). Because the tilt lives in LOG space it
|
| 14 |
+
spreads the small-probability regime a regression-distilled critic compresses.
|
| 15 |
+
|
| 16 |
+
The (kappa, K) improvement grid is TRAINING-FREE — one BC fit, then each grid point is
|
| 17 |
+
just an evaluation pass with a different tilted sampler.
|
| 18 |
+
"""
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import time
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from ogbench_genq._runner import (OGBENCH_IMPLS, PKG_DIR, _make_eval_fn, _result_dir,
|
| 26 |
+
_setup_paths)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class TiltedPolicy:
|
| 30 |
+
"""pi_plus: K proposals from the BC head, tilted by exp(kappa * log P(x=g|s,a,g)).
|
| 31 |
+
|
| 32 |
+
kappa <= 0 selects argmax (the Q-filter limit). Duck-types `sample_actions` for
|
| 33 |
+
OGBench's evaluate()."""
|
| 34 |
+
|
| 35 |
+
def __init__(self, bc_agent, gl_batch, k, kappa, rng):
|
| 36 |
+
self.bc = bc_agent
|
| 37 |
+
self.gl_batch = gl_batch
|
| 38 |
+
self.k = k
|
| 39 |
+
self.kappa = kappa
|
| 40 |
+
self.rng = rng
|
| 41 |
+
|
| 42 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 43 |
+
obs_k = np.repeat(np.asarray(observations)[None], self.k, axis=0)
|
| 44 |
+
goal_k = np.repeat(np.asarray(goals)[None], self.k, axis=0)
|
| 45 |
+
acts = self.bc.sample_actions(observations=obs_k, goals=goal_k, seed=seed,
|
| 46 |
+
temperature=1.0)
|
| 47 |
+
acts = np.clip(np.asarray(acts), -1, 1)
|
| 48 |
+
logp = np.log(np.maximum(self.gl_batch(obs_k, goal_k, acts), 1e-12))
|
| 49 |
+
if self.kappa <= 0:
|
| 50 |
+
return acts[int(np.argmax(logp))]
|
| 51 |
+
z = self.kappa * logp
|
| 52 |
+
z -= z.max()
|
| 53 |
+
p = np.exp(z)
|
| 54 |
+
p /= p.sum()
|
| 55 |
+
return acts[int(self.rng.choice(self.k, p=p))]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def run_genq_factored(env_id, seed=0, bc_steps=200000, eval_episodes=50,
|
| 59 |
+
eval_episodes_grid=25, kappas=(0.0, 5.0, 2.0), ks=(32, 16),
|
| 60 |
+
genq_npz=None, n_orders=16, variant_tag=None, wandb_mode="online",
|
| 61 |
+
ogbench_impls=OGBENCH_IMPLS):
|
| 62 |
+
_setup_paths(ogbench_impls)
|
| 63 |
+
import jax
|
| 64 |
+
import jax.numpy as jnp
|
| 65 |
+
import tqdm
|
| 66 |
+
import wandb
|
| 67 |
+
from utils.datasets import Dataset, GCDataset
|
| 68 |
+
from utils.env_utils import make_env_and_datasets
|
| 69 |
+
from utils.evaluation import evaluate
|
| 70 |
+
from target_extractors import env_safe_name
|
| 71 |
+
import target_extractors
|
| 72 |
+
from genq_jax import load_genq_params, genq_q_goal_likelihood
|
| 73 |
+
import bc as bc_mod
|
| 74 |
+
|
| 75 |
+
t0 = time.time()
|
| 76 |
+
safe = env_safe_name(env_id)
|
| 77 |
+
ckpt_dir = os.path.join(PKG_DIR, "checkpoints")
|
| 78 |
+
if genq_npz is None:
|
| 79 |
+
genq_npz = os.path.join(ckpt_dir, f"m9_genq_mixb_gmrt_{safe}.genqjax.npz")
|
| 80 |
+
assert os.path.exists(genq_npz), genq_npz
|
| 81 |
+
P, meta = load_genq_params(genq_npz)
|
| 82 |
+
|
| 83 |
+
config = bc_mod.get_config()
|
| 84 |
+
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
|
| 85 |
+
train_ds = GCDataset(Dataset.create(**train_dataset), config)
|
| 86 |
+
tgt = lambda o: target_extractors.extract_target(env_id, np.asarray(o)).astype(np.float32)
|
| 87 |
+
|
| 88 |
+
gl_fn = jax.jit(lambda s, a, g, k: genq_q_goal_likelihood(P, meta, s, a, g, k,
|
| 89 |
+
n_orders=n_orders))
|
| 90 |
+
gkey = [jax.random.PRNGKey(seed + 999)]
|
| 91 |
+
|
| 92 |
+
def gl_batch(obs_b, goal_obs, acts):
|
| 93 |
+
s = jnp.asarray(np.asarray(obs_b, dtype=np.float32))
|
| 94 |
+
g = jnp.asarray(tgt(goal_obs))
|
| 95 |
+
a = jnp.asarray(np.clip(np.asarray(acts, dtype=np.float32), -1, 1))
|
| 96 |
+
gkey[0], sub = jax.random.split(gkey[0])
|
| 97 |
+
return np.asarray(gl_fn(s, a, g, sub))
|
| 98 |
+
|
| 99 |
+
vtag = f"_{variant_tag}" if variant_tag else ""
|
| 100 |
+
run = wandb.init(project="gen-q-policy-improvement",
|
| 101 |
+
name=f"genq_factored{vtag}-{env_id}-s{seed}",
|
| 102 |
+
mode=wandb_mode, tags=["genq_factored", env_id],
|
| 103 |
+
config=dict(method="genq_factored", env=env_id, seed=seed,
|
| 104 |
+
bc_steps=bc_steps, kappas=list(kappas), ks=list(ks),
|
| 105 |
+
n_orders=n_orders, genq_npz=os.path.basename(genq_npz)),
|
| 106 |
+
settings=wandb.Settings(start_method="thread"))
|
| 107 |
+
print(f"[factored] WANDB_URL {run.get_url()}", flush=True)
|
| 108 |
+
|
| 109 |
+
# ---- factor 1: plain gc-BC proposal (the ONLY trained network) ----
|
| 110 |
+
ex = train_ds.sample(2)
|
| 111 |
+
bc_agent = bc_mod.GCBCAgent.create(seed, ex["observations"], ex["actions"], config)
|
| 112 |
+
for i in tqdm.trange(1, bc_steps + 1, smoothing=0.1, dynamic_ncols=True):
|
| 113 |
+
bc_agent, info = bc_agent.update(train_ds.sample(config["batch_size"]))
|
| 114 |
+
if i % 5000 == 0:
|
| 115 |
+
wandb.log({f"bc/{k}": float(v) for k, v in info.items()
|
| 116 |
+
if np.ndim(np.asarray(v)) == 0}, step=i)
|
| 117 |
+
print(f"[factored] BC head trained ({bc_steps} steps)", flush=True)
|
| 118 |
+
|
| 119 |
+
# ---- factor 2 is the FROZEN occupancy; improvement = tilted read-out (no training) ----
|
| 120 |
+
# _make_eval_fn device_puts the agent, so tilting is applied via its wrap hook
|
| 121 |
+
# (same pattern as the Q-filter policy): the holder selects the grid point per eval.
|
| 122 |
+
rng = np.random.default_rng(seed)
|
| 123 |
+
holder = {"on": False, "k": 16, "kappa": 0.0}
|
| 124 |
+
|
| 125 |
+
def _wrap(a):
|
| 126 |
+
if not holder["on"]:
|
| 127 |
+
return a
|
| 128 |
+
return TiltedPolicy(a, gl_batch, holder["k"], holder["kappa"], rng)
|
| 129 |
+
|
| 130 |
+
eval_success = _make_eval_fn(env, config, evaluate, jax, wrap=_wrap)
|
| 131 |
+
out = os.path.join(_result_dir(env_id, seed), f"genq_factored{vtag}.json")
|
| 132 |
+
results = {}
|
| 133 |
+
|
| 134 |
+
holder["on"] = False
|
| 135 |
+
sr_bc, per_bc = eval_success(bc_agent, eval_episodes_grid)
|
| 136 |
+
results["bc_only"] = {"sr": sr_bc, "per_task": per_bc}
|
| 137 |
+
print(f"[factored] BC-only sr={sr_bc:.3f}", flush=True)
|
| 138 |
+
wandb.log({"eval/bc_only": sr_bc})
|
| 139 |
+
|
| 140 |
+
best = ("bc_only", sr_bc)
|
| 141 |
+
for kap in kappas:
|
| 142 |
+
for K in ks:
|
| 143 |
+
tag = f"kappa{kap:g}_K{K}"
|
| 144 |
+
holder.update(on=True, k=K, kappa=kap)
|
| 145 |
+
sr, per = eval_success(bc_agent, eval_episodes_grid)
|
| 146 |
+
results[tag] = {"sr": sr, "per_task": per}
|
| 147 |
+
print(f"[factored] {tag}: sr={sr:.3f}", flush=True)
|
| 148 |
+
wandb.log({f"eval/{tag}": sr})
|
| 149 |
+
if sr > best[1]:
|
| 150 |
+
best = (tag, sr)
|
| 151 |
+
json.dump({"method": "genq_factored", "env": env_id, "seed": seed,
|
| 152 |
+
"bc_steps": bc_steps, "n_orders": n_orders,
|
| 153 |
+
"genq_npz": os.path.basename(genq_npz), "grid": results,
|
| 154 |
+
"best": {"config": best[0], "sr": best[1]},
|
| 155 |
+
"wall_clock_sec": round(time.time() - t0, 1),
|
| 156 |
+
"wandb_url": run.get_url()}, open(out, "w"), indent=2)
|
| 157 |
+
|
| 158 |
+
# final 50-episode confirmation of the grid winner
|
| 159 |
+
if best[0] != "bc_only":
|
| 160 |
+
kap = float(best[0].split("_")[0].replace("kappa", ""))
|
| 161 |
+
K = int(best[0].split("_K")[1])
|
| 162 |
+
holder.update(on=True, k=K, kappa=kap)
|
| 163 |
+
sr_f, per_f = eval_success(bc_agent, eval_episodes)
|
| 164 |
+
results["best_final"] = {"config": best[0], "sr": sr_f, "per_task": per_f}
|
| 165 |
+
print(f"[factored] BEST {best[0]} FINAL({eval_episodes} ep) sr={sr_f:.3f}", flush=True)
|
| 166 |
+
wandb.log({"eval/best_final": sr_f})
|
| 167 |
+
json.dump({"method": "genq_factored", "env": env_id, "seed": seed,
|
| 168 |
+
"bc_steps": bc_steps, "n_orders": n_orders,
|
| 169 |
+
"genq_npz": os.path.basename(genq_npz), "grid": results,
|
| 170 |
+
"best": {"config": best[0], "sr_grid": best[1], "sr_final": sr_f},
|
| 171 |
+
"wall_clock_sec": round(time.time() - t0, 1),
|
| 172 |
+
"wandb_url": run.get_url()}, open(out, "w"), indent=2)
|
| 173 |
+
print(f"[factored] {env_id} grid done -> {out}", flush=True)
|
| 174 |
+
wandb.finish()
|
| 175 |
+
return out
|
gen_q_rsm/ogbench_genq/unused/genq_factored_dp.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FACTORED Gen-Q with LATTICE VALUE ITERATION — explicit trajectory stitching, 2 models.
|
| 2 |
+
|
| 3 |
+
The puzzle target space is a finite lattice of 512 bit-configurations, and the
|
| 4 |
+
goal-likelihood read-out gl(s, a, c') scores first-passage to ANY config c', not just the
|
| 5 |
+
task goal. So stitching can be made EXPLICIT instead of hoping the behavior occupancy
|
| 6 |
+
generalizes across trajectories:
|
| 7 |
+
|
| 8 |
+
1. EDGES (one-time, from the 2 models + dataset): for each config c observed in the
|
| 9 |
+
data and each config move c -> c' observed anywhere in the data (the environment's
|
| 10 |
+
press-effect set, data-grounded), estimate
|
| 11 |
+
w(c -> c') = mean_{s_c ~ D[c]} gl(s_c, mu_beta(s_c, g_obs(c')), target(c'))
|
| 12 |
+
— the probability that the behavior policy, started from a REAL dataset state with
|
| 13 |
+
config c and aiming at c', absorbs at c' within the geometric window.
|
| 14 |
+
2. DP: D(c, g) = shortest path distance in -log w over the lattice (Dijkstra from each
|
| 15 |
+
eval goal). This is exactly the multi-hop value TD propagates implicitly — computed
|
| 16 |
+
here in closed form over the discrete lattice.
|
| 17 |
+
3. STITCHED TILT: pi_plus(a|s,g) via K BC proposals scored by
|
| 18 |
+
Q_stitch(s, a, g) = max_{c' in N(c_s) + {g}} gl(s, a, c') * exp(-D(c', g))
|
| 19 |
+
— "which reachable next-config best leads to the goal THROUGH the lattice".
|
| 20 |
+
|
| 21 |
+
Deployment remains 2 models (occupancy + BC head) plus a 512-table cache.
|
| 22 |
+
"""
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import time
|
| 26 |
+
from collections import defaultdict
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
from ogbench_genq._runner import (OGBENCH_IMPLS, PKG_DIR, _make_eval_fn, _result_dir,
|
| 31 |
+
_setup_paths)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _dijkstra(n, adj, src):
|
| 35 |
+
"""adj: dict u -> list[(v, cost)]; returns dist[n] from src (cost = -log w >= 0)."""
|
| 36 |
+
import heapq
|
| 37 |
+
dist = np.full(n, np.inf)
|
| 38 |
+
dist[src] = 0.0
|
| 39 |
+
h = [(0.0, src)]
|
| 40 |
+
while h:
|
| 41 |
+
d, u = heapq.heappop(h)
|
| 42 |
+
if d > dist[u] + 1e-12:
|
| 43 |
+
continue
|
| 44 |
+
for v, c in adj.get(u, ()):
|
| 45 |
+
nd = d + c
|
| 46 |
+
if nd < dist[v] - 1e-12:
|
| 47 |
+
dist[v] = nd
|
| 48 |
+
heapq.heappush(h, (nd, v))
|
| 49 |
+
return dist
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class StitchedTiltedPolicy:
|
| 53 |
+
"""K BC proposals scored by the lattice-stitched value; argmax or softmax(kappa)."""
|
| 54 |
+
|
| 55 |
+
def __init__(self, bc_agent, gl_multi, k, kappa, rng, neighbor_targets, d_to_goal,
|
| 56 |
+
bits_of):
|
| 57 |
+
self.bc = bc_agent
|
| 58 |
+
self.gl_multi = gl_multi # (obs[K], goals_t[K, C, 9]) -> P[K, C]
|
| 59 |
+
self.k = k
|
| 60 |
+
self.kappa = kappa
|
| 61 |
+
self.rng = rng
|
| 62 |
+
self.neighbor_targets = neighbor_targets # (cfg) -> (targets[C,9], D[C]) to goal
|
| 63 |
+
self.d_to_goal = d_to_goal
|
| 64 |
+
self.bits_of = bits_of
|
| 65 |
+
|
| 66 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 67 |
+
obs = np.asarray(observations)
|
| 68 |
+
cfg = self.bits_of(obs[None])[0]
|
| 69 |
+
cand_t, cand_d = self.neighbor_targets(cfg) # [C,9], [C]
|
| 70 |
+
obs_k = np.repeat(obs[None], self.k, axis=0)
|
| 71 |
+
goal_k = np.repeat(np.asarray(goals)[None], self.k, axis=0)
|
| 72 |
+
acts = np.clip(np.asarray(self.bc.sample_actions(
|
| 73 |
+
observations=obs_k, goals=goal_k, seed=seed, temperature=1.0)), -1, 1)
|
| 74 |
+
P = self.gl_multi(obs_k, acts, cand_t) # [K, C]
|
| 75 |
+
with np.errstate(divide="ignore"):
|
| 76 |
+
score = np.log(np.maximum(P, 1e-12)) - cand_d[None, :] # log(gl) - D(c',g)
|
| 77 |
+
q = score.max(-1) # stitched log-value per action
|
| 78 |
+
if self.kappa <= 0:
|
| 79 |
+
return acts[int(np.argmax(q))]
|
| 80 |
+
z = self.kappa * (q - q.max())
|
| 81 |
+
p = np.exp(z)
|
| 82 |
+
p /= p.sum()
|
| 83 |
+
return acts[int(self.rng.choice(self.k, p=p))]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def run_genq_factored_dp(env_id, seed=0, bc_steps=200000, eval_episodes=50,
|
| 87 |
+
eval_episodes_grid=25, kappas=(0.0, 5.0), ks=(32, 16),
|
| 88 |
+
genq_npz=None, n_orders=16, edge_samples=6, max_hop_frames=120,
|
| 89 |
+
variant_tag=None, wandb_mode="online",
|
| 90 |
+
ogbench_impls=OGBENCH_IMPLS):
|
| 91 |
+
_setup_paths(ogbench_impls)
|
| 92 |
+
import jax
|
| 93 |
+
import jax.numpy as jnp
|
| 94 |
+
import tqdm
|
| 95 |
+
import wandb
|
| 96 |
+
from utils.datasets import Dataset, GCDataset
|
| 97 |
+
from utils.env_utils import make_env_and_datasets
|
| 98 |
+
from utils.evaluation import evaluate
|
| 99 |
+
from target_extractors import env_safe_name
|
| 100 |
+
import target_extractors
|
| 101 |
+
from genq_jax import load_genq_params, genq_q_goal_likelihood
|
| 102 |
+
from train_genq_jax import build_ends
|
| 103 |
+
import bc as bc_mod
|
| 104 |
+
|
| 105 |
+
t0 = time.time()
|
| 106 |
+
safe = env_safe_name(env_id)
|
| 107 |
+
ckpt_dir = os.path.join(PKG_DIR, "checkpoints")
|
| 108 |
+
if genq_npz is None:
|
| 109 |
+
genq_npz = os.path.join(ckpt_dir, f"m9_genq_mixb_gmrt_{safe}.genqjax.npz")
|
| 110 |
+
P, meta = load_genq_params(genq_npz)
|
| 111 |
+
n_bits = meta["n_bits"]
|
| 112 |
+
|
| 113 |
+
config = bc_mod.get_config()
|
| 114 |
+
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
|
| 115 |
+
obs = np.asarray(train_dataset["observations"], dtype=np.float32)
|
| 116 |
+
end_of = build_ends(train_dataset["terminals"])
|
| 117 |
+
N = len(obs)
|
| 118 |
+
train_ds = GCDataset(Dataset.create(**train_dataset), config)
|
| 119 |
+
tgt = lambda o: target_extractors.extract_target(env_id, np.asarray(o)).astype(np.float32)
|
| 120 |
+
|
| 121 |
+
bits_all = np.round(np.clip(tgt(obs), 0, 1)).astype(np.int64)
|
| 122 |
+
pow2 = (1 << np.arange(n_bits)).astype(np.int64)
|
| 123 |
+
cfg_all = bits_all @ pow2
|
| 124 |
+
bits_of = lambda o: (np.round(np.clip(tgt(o), 0, 1)).astype(np.int64) @ pow2)
|
| 125 |
+
|
| 126 |
+
# ---- config buckets + data-grounded move set ----
|
| 127 |
+
buckets = defaultdict(list)
|
| 128 |
+
for i in range(N):
|
| 129 |
+
buckets[int(cfg_all[i])].append(i)
|
| 130 |
+
moves = defaultdict(set) # c -> {c'} observed within max_hop_frames
|
| 131 |
+
step = 5
|
| 132 |
+
for i in range(0, N - step, step):
|
| 133 |
+
j = min(i + max_hop_frames, end_of[i] - 1)
|
| 134 |
+
c0 = int(cfg_all[i])
|
| 135 |
+
seen = np.unique(cfg_all[i:j + 1])
|
| 136 |
+
for c1 in seen:
|
| 137 |
+
if int(c1) != c0:
|
| 138 |
+
moves[c0].add(int(c1))
|
| 139 |
+
n_cfg = len(buckets)
|
| 140 |
+
n_edges = sum(len(v) for v in moves.values())
|
| 141 |
+
print(f"[dp] configs in data: {n_cfg}; observed move edges: {n_edges}", flush=True)
|
| 142 |
+
|
| 143 |
+
gl_fn = jax.jit(lambda s, a, g, k: genq_q_goal_likelihood(P, meta, s, a, g, k,
|
| 144 |
+
n_orders=n_orders))
|
| 145 |
+
gkey = [jax.random.PRNGKey(seed + 999)]
|
| 146 |
+
|
| 147 |
+
def gl_np(s, a, g):
|
| 148 |
+
gkey[0], sub = jax.random.split(gkey[0])
|
| 149 |
+
return np.asarray(gl_fn(jnp.asarray(s), jnp.asarray(a), jnp.asarray(g), sub))
|
| 150 |
+
|
| 151 |
+
vtag = f"_{variant_tag}" if variant_tag else ""
|
| 152 |
+
run = wandb.init(project="gen-q-policy-improvement",
|
| 153 |
+
name=f"genq_factored_dp{vtag}-{env_id}-s{seed}",
|
| 154 |
+
mode=wandb_mode, tags=["genq_factored_dp", env_id],
|
| 155 |
+
config=dict(method="genq_factored_dp", env=env_id, seed=seed,
|
| 156 |
+
bc_steps=bc_steps, n_orders=n_orders,
|
| 157 |
+
edge_samples=edge_samples, max_hop_frames=max_hop_frames,
|
| 158 |
+
n_cfg=n_cfg, n_edges=n_edges,
|
| 159 |
+
genq_npz=os.path.basename(genq_npz)),
|
| 160 |
+
settings=wandb.Settings(start_method="thread"))
|
| 161 |
+
print(f"[dp] WANDB_URL {run.get_url()}", flush=True)
|
| 162 |
+
|
| 163 |
+
# ---- factor 1: BC head ----
|
| 164 |
+
ex = train_ds.sample(2)
|
| 165 |
+
bc_agent = bc_mod.GCBCAgent.create(seed, ex["observations"], ex["actions"], config)
|
| 166 |
+
for i in tqdm.trange(1, bc_steps + 1, smoothing=0.1, dynamic_ncols=True):
|
| 167 |
+
bc_agent, info = bc_agent.update(train_ds.sample(config["batch_size"]))
|
| 168 |
+
print(f"[dp] BC head trained ({bc_steps} steps)", flush=True)
|
| 169 |
+
|
| 170 |
+
rng = np.random.default_rng(seed)
|
| 171 |
+
bits_vec = lambda c: ((int(c) >> np.arange(n_bits)) & 1).astype(np.float32)
|
| 172 |
+
|
| 173 |
+
# ---- edge table: w(c -> c') = mean gl(s_c, mu_bc(s_c, g_obs(c')), bits(c')) ----
|
| 174 |
+
print(f"[dp] building edge table ({n_edges} edges x {edge_samples} samples)", flush=True)
|
| 175 |
+
edge_list = [(c, c2) for c, dsts in moves.items() for c2 in dsts]
|
| 176 |
+
adj = defaultdict(list)
|
| 177 |
+
B = 512
|
| 178 |
+
for lo in tqdm.trange(0, len(edge_list), B, dynamic_ncols=True):
|
| 179 |
+
chunk = edge_list[lo:lo + B]
|
| 180 |
+
S, A, G = [], [], []
|
| 181 |
+
for (c, c2) in chunk:
|
| 182 |
+
src = rng.choice(buckets[c], size=min(edge_samples, len(buckets[c])),
|
| 183 |
+
replace=False)
|
| 184 |
+
dst_obs = obs[rng.choice(buckets[c2])]
|
| 185 |
+
g_t = bits_vec(c2)
|
| 186 |
+
for si in src:
|
| 187 |
+
S.append(obs[si]); G.append((dst_obs, g_t))
|
| 188 |
+
S = np.asarray(S, np.float32)
|
| 189 |
+
Gobs = np.asarray([g[0] for g in G], np.float32)
|
| 190 |
+
Gt = np.asarray([g[1] for g in G], np.float32)
|
| 191 |
+
acts = np.clip(np.asarray(bc_agent.sample_actions(
|
| 192 |
+
observations=S, goals=Gobs, seed=jax.random.PRNGKey(lo), temperature=0.0)), -1, 1)
|
| 193 |
+
pr = gl_np(S, acts, Gt)
|
| 194 |
+
k0 = 0
|
| 195 |
+
for (c, c2) in chunk:
|
| 196 |
+
ns = min(edge_samples, len(buckets[c]))
|
| 197 |
+
w = float(pr[k0:k0 + ns].mean()); k0 += ns
|
| 198 |
+
if w > 1e-6:
|
| 199 |
+
adj[c2].append((c, -np.log(w))) # REVERSED edges (for Dijkstra from goal)
|
| 200 |
+
print(f"[dp] edge table done ({time.time()-t0:.0f}s)", flush=True)
|
| 201 |
+
|
| 202 |
+
# ---- eval-time machinery ----
|
| 203 |
+
d_cache = {}
|
| 204 |
+
|
| 205 |
+
def d_to_goal(gcfg):
|
| 206 |
+
if gcfg not in d_cache:
|
| 207 |
+
idx = {c: i for i, c in enumerate(buckets.keys())}
|
| 208 |
+
radj = {idx[u]: [(idx[v], c) for v, c in adj[u] if v in idx]
|
| 209 |
+
for u in adj if u in idx}
|
| 210 |
+
if gcfg not in idx:
|
| 211 |
+
d_cache[gcfg] = None
|
| 212 |
+
else:
|
| 213 |
+
dist = _dijkstra(len(idx), radj, idx[gcfg])
|
| 214 |
+
d_cache[gcfg] = {c: float(dist[i]) for c, i in idx.items()}
|
| 215 |
+
return d_cache[gcfg]
|
| 216 |
+
|
| 217 |
+
goal_holder = {"cfg": None}
|
| 218 |
+
|
| 219 |
+
def neighbor_targets(cfg):
|
| 220 |
+
gd = d_to_goal(goal_holder["cfg"]) or {}
|
| 221 |
+
cands = list(moves.get(int(cfg), []))[:24] + [goal_holder["cfg"]]
|
| 222 |
+
ts, ds = [], []
|
| 223 |
+
for c2 in cands:
|
| 224 |
+
ts.append(bits_vec(c2))
|
| 225 |
+
ds.append(gd.get(c2, np.inf) if c2 != goal_holder["cfg"] else 0.0)
|
| 226 |
+
return np.asarray(ts, np.float32), np.asarray(ds, np.float64)
|
| 227 |
+
|
| 228 |
+
def gl_multi(obs_k, acts, cand_t):
|
| 229 |
+
K, C = len(obs_k), len(cand_t)
|
| 230 |
+
S = np.repeat(obs_k, C, axis=0)
|
| 231 |
+
A = np.repeat(acts, C, axis=0)
|
| 232 |
+
Gt = np.tile(cand_t, (K, 1))
|
| 233 |
+
return gl_np(S, A, Gt).reshape(K, C)
|
| 234 |
+
|
| 235 |
+
class _Wrap:
|
| 236 |
+
def __init__(self, inner):
|
| 237 |
+
self.inner = inner
|
| 238 |
+
|
| 239 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 240 |
+
goal_holder["cfg"] = int(bits_of(np.asarray(goals)[None])[0])
|
| 241 |
+
return self.inner.sample_actions(observations, goals=goals, seed=seed,
|
| 242 |
+
temperature=temperature)
|
| 243 |
+
|
| 244 |
+
holder = {"on": False, "k": 16, "kappa": 0.0}
|
| 245 |
+
|
| 246 |
+
def _wrap(a):
|
| 247 |
+
if not holder["on"]:
|
| 248 |
+
return a
|
| 249 |
+
return _Wrap(StitchedTiltedPolicy(a, gl_multi, holder["k"], holder["kappa"], rng,
|
| 250 |
+
neighbor_targets, d_to_goal, bits_of))
|
| 251 |
+
|
| 252 |
+
eval_success = _make_eval_fn(env, config, evaluate, jax, wrap=_wrap)
|
| 253 |
+
out = os.path.join(_result_dir(env_id, seed), f"genq_factored_dp{vtag}.json")
|
| 254 |
+
results = {}
|
| 255 |
+
best = (None, -1.0)
|
| 256 |
+
for kap in kappas:
|
| 257 |
+
for K in ks:
|
| 258 |
+
tag = f"kappa{kap:g}_K{K}"
|
| 259 |
+
holder.update(on=True, k=K, kappa=kap)
|
| 260 |
+
sr, per = eval_success(bc_agent, eval_episodes_grid)
|
| 261 |
+
results[tag] = {"sr": sr, "per_task": per}
|
| 262 |
+
print(f"[dp] {tag}: sr={sr:.3f}", flush=True)
|
| 263 |
+
wandb.log({f"eval/{tag}": sr})
|
| 264 |
+
if sr > best[1]:
|
| 265 |
+
best = (tag, sr)
|
| 266 |
+
json.dump({"method": "genq_factored_dp", "env": env_id, "seed": seed,
|
| 267 |
+
"n_cfg": n_cfg, "n_edges": n_edges, "grid": results,
|
| 268 |
+
"best": {"config": best[0], "sr": best[1]},
|
| 269 |
+
"wall_clock_sec": round(time.time() - t0, 1),
|
| 270 |
+
"wandb_url": run.get_url()}, open(out, "w"), indent=2)
|
| 271 |
+
kap = float(best[0].split("_")[0].replace("kappa", ""))
|
| 272 |
+
K = int(best[0].split("_K")[1])
|
| 273 |
+
holder.update(on=True, k=K, kappa=kap)
|
| 274 |
+
sr_f, per_f = eval_success(bc_agent, eval_episodes)
|
| 275 |
+
results["best_final"] = {"config": best[0], "sr": sr_f, "per_task": per_f}
|
| 276 |
+
json.dump({"method": "genq_factored_dp", "env": env_id, "seed": seed,
|
| 277 |
+
"n_cfg": n_cfg, "n_edges": n_edges, "grid": results,
|
| 278 |
+
"best": {"config": best[0], "sr_grid": best[1], "sr_final": sr_f},
|
| 279 |
+
"wall_clock_sec": round(time.time() - t0, 1),
|
| 280 |
+
"wandb_url": run.get_url()}, open(out, "w"), indent=2)
|
| 281 |
+
print(f"[dp] BEST {best[0]} FINAL sr={sr_f:.3f} -> {out}", flush=True)
|
| 282 |
+
wandb.finish()
|
| 283 |
+
return out
|
gen_q_rsm/ogbench_genq/unused/genq_gliql.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""gl-IQL (issue #57, owner directive): run IQL on the policy model with the Gen-Q critic
|
| 2 |
+
read DIRECTLY — no critic network, no distillation, no TD.
|
| 3 |
+
|
| 4 |
+
Q(s, a, g) := log P(x = g | s, a, g) (exact goal-likelihood read-out)
|
| 5 |
+
V: expectile_tau regression toward Q at dataset actions (IQL implicit max)
|
| 6 |
+
pi: AWR, w = exp(alpha * norm(Q - V)), L = -w log pi(a|s,g)
|
| 7 |
+
|
| 8 |
+
Why log space: the earlier AWR arm used a distilled critic regressing raw P in [0,1],
|
| 9 |
+
which compresses exactly the small-probability differences the advantage must resolve;
|
| 10 |
+
log P spreads them. Why expectile: IQL's tau-expectile V is an in-sample max over
|
| 11 |
+
actions — the optimism operator that won the composition sweep — applied here without
|
| 12 |
+
any TD backup. Trained networks: V + policy head (the occupancy is frozen)."""
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from ogbench_genq._runner import (OGBENCH_IMPLS, PKG_DIR, SIGMA_BY_ENV, _make_eval_fn,
|
| 20 |
+
_result_dir, _setup_paths)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def run_genq_gliql(env_id, seed=0, train_steps=500000, eval_episodes=50, eval_interval=25000,
|
| 24 |
+
eval_episodes_periodic=15, alpha=3.0, expectile=0.9, adv_norm=True,
|
| 25 |
+
n_orders=16, genq_npz=None, variant_tag=None, save_agent=None,
|
| 26 |
+
wandb_mode="online", ogbench_impls=OGBENCH_IMPLS):
|
| 27 |
+
_setup_paths(ogbench_impls)
|
| 28 |
+
import flax
|
| 29 |
+
import jax
|
| 30 |
+
import jax.numpy as jnp
|
| 31 |
+
import optax
|
| 32 |
+
import tqdm
|
| 33 |
+
import wandb
|
| 34 |
+
from utils.datasets import Dataset, GCDataset
|
| 35 |
+
from utils.env_utils import make_env_and_datasets
|
| 36 |
+
from utils.evaluation import evaluate
|
| 37 |
+
from utils.flax_utils import ModuleDict, TrainState
|
| 38 |
+
from utils.networks import GCActor, GCValue
|
| 39 |
+
from target_extractors import env_safe_name
|
| 40 |
+
import target_extractors
|
| 41 |
+
from genq_jax import load_genq_params, genq_q_goal_likelihood
|
| 42 |
+
from agents.gciql import get_config as ref_config
|
| 43 |
+
|
| 44 |
+
t0 = time.time()
|
| 45 |
+
safe = env_safe_name(env_id)
|
| 46 |
+
ckpt_dir = os.path.join(PKG_DIR, "checkpoints")
|
| 47 |
+
if genq_npz is None:
|
| 48 |
+
genq_npz = os.path.join(ckpt_dir, f"m9_genq_mixb_gmrt_{safe}.genqjax.npz")
|
| 49 |
+
P, meta = load_genq_params(genq_npz)
|
| 50 |
+
|
| 51 |
+
config = ref_config() # reference GCDataset goal mix / networks / lr / batch
|
| 52 |
+
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
|
| 53 |
+
train_ds = GCDataset(Dataset.create(**train_dataset), config)
|
| 54 |
+
tgt = lambda o: target_extractors.extract_target(env_id, np.asarray(o)).astype(np.float32)
|
| 55 |
+
|
| 56 |
+
gl_fn = jax.jit(lambda s, a, g, k: genq_q_goal_likelihood(P, meta, s, a, g, k,
|
| 57 |
+
n_orders=n_orders))
|
| 58 |
+
gkey = [jax.random.PRNGKey(seed + 999)]
|
| 59 |
+
|
| 60 |
+
def q_log_batch(obs_b, goal_obs, acts, _chunk=256):
|
| 61 |
+
s = np.asarray(obs_b, dtype=np.float32)
|
| 62 |
+
g = tgt(goal_obs)
|
| 63 |
+
a = np.clip(np.asarray(acts, dtype=np.float32), -1, 1)
|
| 64 |
+
outs = []
|
| 65 |
+
for i in range(0, len(s), _chunk):
|
| 66 |
+
gkey[0], sub = jax.random.split(gkey[0])
|
| 67 |
+
outs.append(np.asarray(gl_fn(jnp.asarray(s[i:i + _chunk]),
|
| 68 |
+
jnp.asarray(a[i:i + _chunk]),
|
| 69 |
+
jnp.asarray(g[i:i + _chunk]), sub)))
|
| 70 |
+
return np.log(np.maximum(np.concatenate(outs), 1e-9)).astype(np.float32)
|
| 71 |
+
|
| 72 |
+
# ---- networks: V + actor only ----
|
| 73 |
+
ex = train_ds.sample(2)
|
| 74 |
+
a_dim = ex["actions"].shape[-1]
|
| 75 |
+
value_def = GCValue(hidden_dims=tuple(config["value_hidden_dims"]),
|
| 76 |
+
layer_norm=config["layer_norm"], ensemble=False)
|
| 77 |
+
actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]), action_dim=a_dim,
|
| 78 |
+
state_dependent_std=False, const_std=config["const_std"])
|
| 79 |
+
net_def = ModuleDict(dict(value=value_def, actor=actor_def))
|
| 80 |
+
key = jax.random.PRNGKey(seed)
|
| 81 |
+
params = net_def.init(key, value=(ex["observations"], ex["observations"]),
|
| 82 |
+
actor=(ex["observations"], ex["observations"]))["params"]
|
| 83 |
+
net = TrainState.create(net_def, params, tx=optax.adam(learning_rate=config["lr"]))
|
| 84 |
+
|
| 85 |
+
tau = expectile
|
| 86 |
+
|
| 87 |
+
@jax.jit
|
| 88 |
+
def update(net, obs, vgoals, agoals, acts, q_v, q_a):
|
| 89 |
+
def loss_fn(p):
|
| 90 |
+
v = net.select("value")(obs, vgoals, params=p)
|
| 91 |
+
diff = q_v - v
|
| 92 |
+
value_loss = (jnp.abs(tau - (diff < 0).astype(jnp.float32)) * diff ** 2).mean()
|
| 93 |
+
va = net.select("value")(obs, agoals)
|
| 94 |
+
adv = q_a - va
|
| 95 |
+
if adv_norm:
|
| 96 |
+
adv = (adv - adv.mean()) / (adv.std() + 1e-6)
|
| 97 |
+
w = jnp.minimum(jnp.exp(alpha * adv), 100.0)
|
| 98 |
+
dist = net.select("actor")(obs, agoals, params=p)
|
| 99 |
+
log_prob = dist.log_prob(acts)
|
| 100 |
+
actor_loss = -(w * log_prob).mean()
|
| 101 |
+
info = {"value_loss": value_loss, "actor_loss": actor_loss, "v_mean": v.mean(),
|
| 102 |
+
"adv_std": (q_a - va).std(), "w_max": w.max(),
|
| 103 |
+
"bc_log_prob": log_prob.mean()}
|
| 104 |
+
return value_loss + actor_loss, info
|
| 105 |
+
|
| 106 |
+
new_net, info = net.apply_loss_fn(loss_fn=loss_fn)
|
| 107 |
+
return new_net, info
|
| 108 |
+
|
| 109 |
+
class _Agent:
|
| 110 |
+
"""sample_actions shim for the shared eval harness."""
|
| 111 |
+
|
| 112 |
+
def __init__(self, net):
|
| 113 |
+
self.net = net
|
| 114 |
+
|
| 115 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 116 |
+
dist = self.net.select("actor")(observations, goals, temperature=temperature)
|
| 117 |
+
acts = dist.sample(seed=seed)
|
| 118 |
+
return jnp.clip(acts, -1, 1)
|
| 119 |
+
|
| 120 |
+
vtag = f"_{variant_tag}" if variant_tag else ""
|
| 121 |
+
run = wandb.init(project="gen-q-policy-improvement",
|
| 122 |
+
name=f"genq_gliql{vtag}-{env_id}-a{alpha}-tau{tau}-s{seed}",
|
| 123 |
+
mode=wandb_mode, tags=["genq_gliql", env_id],
|
| 124 |
+
config=dict(method="genq_gliql", env=env_id, seed=seed, alpha=alpha,
|
| 125 |
+
expectile=tau, adv_norm=adv_norm, n_orders=n_orders,
|
| 126 |
+
genq_npz=os.path.basename(genq_npz),
|
| 127 |
+
train_steps=train_steps),
|
| 128 |
+
settings=wandb.Settings(start_method="thread"))
|
| 129 |
+
print(f"[gliql] WANDB_URL {run.get_url()}", flush=True)
|
| 130 |
+
|
| 131 |
+
# eval harness device_puts the agent: pass the TrainState (a pytree), wrap into the shim
|
| 132 |
+
eval_success = _make_eval_fn(env, config, evaluate, jax, wrap=lambda ts: _Agent(ts))
|
| 133 |
+
out = os.path.join(_result_dir(env_id, seed), f"genq_gliql{vtag}.json")
|
| 134 |
+
curve = []
|
| 135 |
+
|
| 136 |
+
def dump(sr, per):
|
| 137 |
+
json.dump({"method": "genq_gliql", "env": env_id, "seed": seed, "alpha": alpha,
|
| 138 |
+
"expectile": tau, "adv_norm": adv_norm, "n_orders": n_orders,
|
| 139 |
+
"genq_npz": os.path.basename(genq_npz), "success_rate": sr,
|
| 140 |
+
"best_sr": (max(v for _, v in curve) if curve else sr), "per_task": per,
|
| 141 |
+
"curve": curve, "train_steps": train_steps,
|
| 142 |
+
"wall_clock_sec": round(time.time() - t0, 1),
|
| 143 |
+
"wandb_url": run.get_url()}, open(out, "w"), indent=2)
|
| 144 |
+
|
| 145 |
+
for i in tqdm.trange(1, train_steps + 1, smoothing=0.1, dynamic_ncols=True):
|
| 146 |
+
batch = train_ds.sample(config["batch_size"])
|
| 147 |
+
q_v = q_log_batch(batch["observations"], batch["value_goals"], batch["actions"])
|
| 148 |
+
q_a = q_log_batch(batch["observations"], batch["actor_goals"], batch["actions"])
|
| 149 |
+
net, info = update(net, jnp.asarray(batch["observations"]),
|
| 150 |
+
jnp.asarray(batch["value_goals"]),
|
| 151 |
+
jnp.asarray(batch["actor_goals"]),
|
| 152 |
+
jnp.asarray(np.clip(batch["actions"], -1, 1)),
|
| 153 |
+
jnp.asarray(q_v), jnp.asarray(q_a))
|
| 154 |
+
if i % 1000 == 0:
|
| 155 |
+
wandb.log({f"train/{k}": float(v) for k, v in info.items()}, step=i)
|
| 156 |
+
if eval_interval > 0 and i % eval_interval == 0:
|
| 157 |
+
sr, per = eval_success(net, eval_episodes_periodic)
|
| 158 |
+
curve.append((i, sr))
|
| 159 |
+
wandb.log({"eval/success_rate": sr, "eval/peak": max(v for _, v in curve)}, step=i)
|
| 160 |
+
print(f"[gliql] step {i} sr={sr:.3f} (peak {max(v for _, v in curve):.3f})",
|
| 161 |
+
flush=True)
|
| 162 |
+
dump(sr, per)
|
| 163 |
+
|
| 164 |
+
sr, per = eval_success(net, eval_episodes)
|
| 165 |
+
curve.append((train_steps, sr))
|
| 166 |
+
dump(sr, per)
|
| 167 |
+
if save_agent:
|
| 168 |
+
import pickle
|
| 169 |
+
with open(save_agent, "wb") as f:
|
| 170 |
+
pickle.dump({"params": jax.device_get(net.params), "config": dict(config)}, f)
|
| 171 |
+
print(f"[gliql] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}",
|
| 172 |
+
flush=True)
|
| 173 |
+
wandb.finish()
|
| 174 |
+
return out
|
gen_q_rsm/ogbench_genq/unused/genq_joint.py
ADDED
|
@@ -0,0 +1,1468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""JOINT Gen-Q policy iteration (issue #57, owner directive): fit the occupancy IN THE SAME
|
| 2 |
+
LOOP as the critic/value/actor instead of staging frozen-occupancy rounds.
|
| 3 |
+
|
| 4 |
+
Why: the ablation isolated the residual GenQ<->GCIQL gap to critic-policy co-adaptation —
|
| 5 |
+
TD's critic re-evaluates continuously as the policy improves, while a frozen behavior
|
| 6 |
+
occupancy cannot. The staged v2 (PI -> re-fit -> PI) approximates that with a few coarse
|
| 7 |
+
rounds; here the loop is closed at EVERY step, purely TD-free:
|
| 8 |
+
|
| 9 |
+
per step i:
|
| 10 |
+
1. occupancy tuple batch (ref goal mix + rt stratification, exact Geom IS weights),
|
| 11 |
+
futures ADDITIONALLY weighted by agreement with the LIVE actor
|
| 12 |
+
(w_pi = exp(-pi_alpha * mean||a - mu_actor(s, g)||^2 / 2), self-normalized;
|
| 13 |
+
enabled after a behavior-only warmup) -> one denoising update on the
|
| 14 |
+
mixed-bits occupancy.
|
| 15 |
+
2. EMA (Polyak) copy of the occupancy provides the goal-likelihood read-out
|
| 16 |
+
Q = P(x = g | s, a, g) -> distillation targets for the genq_critic
|
| 17 |
+
(target-network trick: decouples the agent from per-step occupancy noise).
|
| 18 |
+
3. reference-recipe agent update (GCIQLAblateAgent, R3: actor + expectile-V both
|
| 19 |
+
read the distilled Gen-Q critic; ddpgbc alpha=1.0). No TD anywhere.
|
| 20 |
+
|
| 21 |
+
Everything reuses the validated pieces: mixed-bits masked diffusion, absorbing
|
| 22 |
+
first-passage, GCDataset ref goal mix, rt stratified hits, gl read-out, reference
|
| 23 |
+
extraction. The occupancy tracks d^{pi_t} online — pure Gen-Q policy iteration.
|
| 24 |
+
|
| 25 |
+
TARGET MODES (auto-selected by env prefix; the tuple samplers — absorbing
|
| 26 |
+
first-passage, goal-mix ref, rt_eta IS weights, actor-agreement — are
|
| 27 |
+
target-representation-agnostic and shared):
|
| 28 |
+
|
| 29 |
+
* bits (puzzle*): masked discrete diffusion over the config bits; read-out = exact
|
| 30 |
+
teacher-forced goal-likelihood gl (or --readout sample). Unchanged from the record
|
| 31 |
+
recipe. --readout elbo instead routes puzzle through CONT mode (puzzle-as-
|
| 32 |
+
continuous): eps-prediction DDPM over the bits embedded as +-1, denoising-loss
|
| 33 |
+
likelihood surrogate — the generality demonstration (same code path as pointmaze).
|
| 34 |
+
* cont (pointmaze*/antmaze*): standard eps-prediction DDPM over the continuous
|
| 35 |
+
extract_target dims (xy for mazes; y normalized by dataset mean/std), cosine abar.
|
| 36 |
+
Read-out = N DDIM draws + the Gaussian tolerance kernel of genq_jax.genq_q
|
| 37 |
+
(Q = mean_i exp(-||x_i - g||^2 / (2 sigma^2)), sigma from _runner.SIGMA_BY_ENV);
|
| 38 |
+
recursion midpoints are raw continuous occupancy samples (no snapping/retrieval;
|
| 39 |
+
--rec_free required). --readout elbo swaps the kernel read for the denoising-loss
|
| 40 |
+
likelihood surrogate Q = exp(-elbo_c * L_den(g)) — space-agnostic, point-evaluated,
|
| 41 |
+
differentiable in the action — and additionally unlocks the 2-model ddpg2
|
| 42 |
+
extraction (actor differentiates L_den directly; prob-form recursion composes in
|
| 43 |
+
log space). Other extractions (awr2/gliql) still wire through the bits-only gl
|
| 44 |
+
machinery. Occupancy conditioning stays the FULL observation, as in
|
| 45 |
+
bits mode: for pointmaze the full obs IS the xy target (identical to _runner's
|
| 46 |
+
to_genq_state), and for antmaze train_genq_jax also conditions on the full obs
|
| 47 |
+
(LOCO_FULL) — so full-obs conditioning is the smaller diff AND matches precedent.
|
| 48 |
+
"""
|
| 49 |
+
import json
|
| 50 |
+
import math
|
| 51 |
+
import os
|
| 52 |
+
import time
|
| 53 |
+
|
| 54 |
+
import numpy as np
|
| 55 |
+
|
| 56 |
+
from ogbench_genq._runner import (OGBENCH_IMPLS, PKG_DIR, SIGMA_BY_ENV, _make_eval_fn,
|
| 57 |
+
_result_dir, _setup_paths)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def run_genq_joint(env_id, seed=0, train_steps=500000, eval_episodes=50, eval_interval=25000,
|
| 61 |
+
eval_episodes_periodic=15, alpha=1.0, expectile=0.9, gamma=0.99,
|
| 62 |
+
occ_lr=3e-4, occ_batch=256, occ_hidden=256, occ_layers=3, occ_time_dim=64,
|
| 63 |
+
occ_T=100, occ_tau=0.005, occ_warmup=50000, rt_eta=0.5,
|
| 64 |
+
pi_alpha=1.0, pi_horizon=25, n_orders=16, occ_updates_per_step=1,
|
| 65 |
+
readout="gl", n_occ_ro=64,
|
| 66 |
+
elbo_c=10.0, elbo_K=8, elbo_tlo=0.0, elbo_thi=1.0,
|
| 67 |
+
extraction="r3", gliql_alpha=3.0, awr_alpha=3.0, occ_warmstart_npz=None,
|
| 68 |
+
variant_tag=None, save_agent=None, save_occ=None, actor_ema_tau=0.0,
|
| 69 |
+
rec_target=0, rec_every=2, rec_eps=0.5, rec_after=100000,
|
| 70 |
+
rec_free=False, rec_beta=0.0, rec_max_depth=6, rec_pess=1, rec_prob=False,
|
| 71 |
+
rec_actor=False,
|
| 72 |
+
gamma_spectrum_lo=0.0, gamma_spectrum_p=0.5,
|
| 73 |
+
wandb_mode="online", ogbench_impls=OGBENCH_IMPLS):
|
| 74 |
+
_setup_paths(ogbench_impls)
|
| 75 |
+
import jax
|
| 76 |
+
import jax.numpy as jnp
|
| 77 |
+
import optax
|
| 78 |
+
import tqdm
|
| 79 |
+
import wandb
|
| 80 |
+
from utils.datasets import Dataset, GCDataset
|
| 81 |
+
from utils.env_utils import make_env_and_datasets
|
| 82 |
+
from utils.evaluation import evaluate
|
| 83 |
+
from utils.networks import GCActor, GCValue
|
| 84 |
+
from utils.flax_utils import ModuleDict, TrainState
|
| 85 |
+
from target_extractors import env_safe_name
|
| 86 |
+
import target_extractors
|
| 87 |
+
from train_genq_jax import build_ends, cosine_abar, future_idx, make_model
|
| 88 |
+
from gciql_ablate import GCIQLAblateAgent, get_config
|
| 89 |
+
|
| 90 |
+
if env_id.startswith("puzzle"):
|
| 91 |
+
# --readout elbo = PUZZLE-AS-CONTINUOUS: the space-agnostic path. The
|
| 92 |
+
# occupancy is the standard eps-prediction DDPM over the 9 config bits
|
| 93 |
+
# embedded as a +-1 continuous vector (y stats forced to 0.5/0.5 below),
|
| 94 |
+
# read out by the denoising-loss likelihood surrogate — no masked
|
| 95 |
+
# diffusion, no bit machinery; the same code that runs on pointmaze.
|
| 96 |
+
target_mode = "cont" if readout == "elbo" else "bits"
|
| 97 |
+
elif env_id.startswith(("pointmaze", "antmaze")):
|
| 98 |
+
target_mode = "cont" # eps-prediction DDPM over the continuous xy target
|
| 99 |
+
else:
|
| 100 |
+
raise NotImplementedError(
|
| 101 |
+
f"genq_joint: no target mode for {env_id} (puzzle* -> bits, "
|
| 102 |
+
"pointmaze*/antmaze* -> cont)")
|
| 103 |
+
bits = target_mode == "bits"
|
| 104 |
+
print(f"[joint] TARGET_MODE={target_mode} env={env_id}", flush=True)
|
| 105 |
+
if not bits:
|
| 106 |
+
assert extraction == "r3" or (extraction == "ddpg2" and readout == "elbo"), (
|
| 107 |
+
"cont target mode supports --extraction r3, or ddpg2 with --readout elbo "
|
| 108 |
+
"(the denoising-loss read-out is the differentiable-in-action coupling; "
|
| 109 |
+
"awr2/gliql are wired through the bits-only gl_q_orders machinery)")
|
| 110 |
+
assert rec_target == 0 or rec_free, (
|
| 111 |
+
"cont target mode recursion is retrieval-free only: pass --rec_free "
|
| 112 |
+
"(midpoints are raw continuous occupancy samples, no eps-grid snapping)")
|
| 113 |
+
assert not (extraction == "ddpg2" and rec_target > 0 and not rec_prob), (
|
| 114 |
+
"cont ddpg2 recursion is wired for the prob (splitting-identity) form "
|
| 115 |
+
"only: pass --rec_prob (the max-certificate actor loss is bits-only)")
|
| 116 |
+
ro_sigma = float(SIGMA_BY_ENV.get(env_id, 5.0))
|
| 117 |
+
t0 = time.time()
|
| 118 |
+
safe = env_safe_name(env_id)
|
| 119 |
+
config = get_config()
|
| 120 |
+
config["actor_loss"] = "ddpgbc"
|
| 121 |
+
config["alpha"] = alpha
|
| 122 |
+
config["expectile"] = expectile
|
| 123 |
+
config["genq_actor"] = True
|
| 124 |
+
config["genq_value"] = True
|
| 125 |
+
|
| 126 |
+
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
|
| 127 |
+
obs = np.asarray(train_dataset["observations"], dtype=np.float32)
|
| 128 |
+
act = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1.0, 1.0)
|
| 129 |
+
end_of = build_ends(train_dataset["terminals"])
|
| 130 |
+
N = len(obs)
|
| 131 |
+
a_dim = act.shape[1]
|
| 132 |
+
tgt = lambda o: target_extractors.extract_target(env_id, o).astype(np.float32)
|
| 133 |
+
target_full = tgt(obs)
|
| 134 |
+
y_dim = target_full.shape[1] # 9 bits
|
| 135 |
+
n_bits = y_dim
|
| 136 |
+
# DISCOUNT-CONDITIONED occupancy (owner directive, the gamma-spectrum axis of
|
| 137 |
+
# #55 brought into the PI loop): one model p(x | s,a,g, gamma_i) trained across
|
| 138 |
+
# a spectrum of discounts. gl at the TASK discount serves the PI read-out and
|
| 139 |
+
# the direct term; recursion chains hop with the BETA-discount occupancy, which
|
| 140 |
+
# is what the geometric-splitting identity actually composes.
|
| 141 |
+
spec_on = gamma_spectrum_lo > 0.0
|
| 142 |
+
if spec_on:
|
| 143 |
+
assert gamma_spectrum_lo < gamma
|
| 144 |
+
|
| 145 |
+
def sample_gammas(n):
|
| 146 |
+
# task discount w.p. 1-p; else log-uniform in horizon 1/(1-gamma)
|
| 147 |
+
h = np.exp(rng_np.uniform(np.log(1.0 / (1.0 - gamma_spectrum_lo)),
|
| 148 |
+
np.log(1.0 / (1.0 - gamma)), n))
|
| 149 |
+
gam = 1.0 - 1.0 / h
|
| 150 |
+
keep_task = rng_np.random(n) >= gamma_spectrum_p
|
| 151 |
+
return np.where(keep_task, gamma, gam).astype(np.float64)
|
| 152 |
+
|
| 153 |
+
cond_dim = obs.shape[1] + a_dim + y_dim + (1 if spec_on else 0)
|
| 154 |
+
|
| 155 |
+
# ---- occupancy model (mixed-bits masked diffusion; bits-only target) ----
|
| 156 |
+
occ_model = make_model(cond_dim, y_dim, occ_hidden, occ_layers, occ_time_dim)
|
| 157 |
+
key = jax.random.PRNGKey(seed)
|
| 158 |
+
key, ik = jax.random.split(key)
|
| 159 |
+
# bits: x input = [signed bit values ; mask flags]; cont: x input = noisy y only
|
| 160 |
+
occ_x_dim = y_dim + n_bits if bits else y_dim
|
| 161 |
+
occ_params = occ_model.init(ik, jnp.zeros((1, occ_x_dim)), jnp.zeros((1,)),
|
| 162 |
+
jnp.zeros((1, cond_dim)))
|
| 163 |
+
if occ_warmstart_npz:
|
| 164 |
+
# warm-start from a pretrained mixed-bits ckpt (torch-key npz -> flax tree):
|
| 165 |
+
# removes the ~100k from-scratch handicap so co-adaptation starts immediately.
|
| 166 |
+
d = np.load(occ_warmstart_npz)
|
| 167 |
+
pt = occ_params["params"]
|
| 168 |
+
|
| 169 |
+
def _ld(name, key):
|
| 170 |
+
kern = d[f"{key}.weight"].T
|
| 171 |
+
want = pt[name]["kernel"].shape
|
| 172 |
+
if kern.shape != want and name == "cond_emb_0":
|
| 173 |
+
# discount-conditioned model warm-started from a fixed-gamma ckpt:
|
| 174 |
+
# zero-pad the input row for the gamma feature (identical function
|
| 175 |
+
# at init; the gamma-dependence is learned in-loop)
|
| 176 |
+
pad = np.zeros((want[0] - kern.shape[0], kern.shape[1]), kern.dtype)
|
| 177 |
+
kern = np.concatenate([kern, pad], 0)
|
| 178 |
+
pt[name]["kernel"] = jnp.asarray(kern)
|
| 179 |
+
pt[name]["bias"] = jnp.asarray(d[f"{key}.bias"])
|
| 180 |
+
|
| 181 |
+
_ld("time_emb_1", "time_emb.1"); _ld("time_emb_3", "time_emb.3")
|
| 182 |
+
_ld("cond_emb_0", "cond_emb.0"); _ld("x_emb", "x_emb"); _ld("out", "out")
|
| 183 |
+
for li in range(occ_layers):
|
| 184 |
+
_ld(f"trunk_{li}", f"trunk.{2 * li}")
|
| 185 |
+
occ_params = {"params": pt}
|
| 186 |
+
print(f"[joint] occupancy warm-started from {os.path.basename(occ_warmstart_npz)}",
|
| 187 |
+
flush=True)
|
| 188 |
+
occ_ema = jax.tree_util.tree_map(lambda x: x, occ_params)
|
| 189 |
+
occ_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(occ_lr))
|
| 190 |
+
occ_opt = occ_tx.init(occ_params)
|
| 191 |
+
abar = cosine_abar(occ_T)
|
| 192 |
+
abar_j = jnp.asarray(abar)
|
| 193 |
+
|
| 194 |
+
# fixed conditioning normalization from behavior stats (goals via the ref mix)
|
| 195 |
+
rng_np = np.random.default_rng(seed)
|
| 196 |
+
t_p = rng_np.integers(0, N, 20000)
|
| 197 |
+
gi_p = np.minimum(t_p + rng_np.geometric(1 - gamma, 20000), end_of[t_p] - 1)
|
| 198 |
+
cond_parts_p = [obs[t_p], act[t_p], target_full[gi_p]]
|
| 199 |
+
if spec_on:
|
| 200 |
+
cond_parts_p.append(sample_gammas(20000)[:, None].astype(np.float32))
|
| 201 |
+
cond_p = np.concatenate(cond_parts_p, axis=1)
|
| 202 |
+
if occ_warmstart_npz:
|
| 203 |
+
d0 = np.load(occ_warmstart_npz)
|
| 204 |
+
cm, cs = np.asarray(d0["cond_mean"]), np.asarray(d0["cond_std"])
|
| 205 |
+
if spec_on and len(cm) < cond_dim:
|
| 206 |
+
cm = np.concatenate([cm, cond_p[:, -1:].mean(0)])
|
| 207 |
+
cs = np.concatenate([cs, cond_p[:, -1:].std(0) + 1e-6])
|
| 208 |
+
cond_mean = jnp.asarray(cm)
|
| 209 |
+
cond_std = jnp.asarray(cs)
|
| 210 |
+
else:
|
| 211 |
+
cond_mean = jnp.asarray(cond_p.mean(0))
|
| 212 |
+
cond_std = jnp.asarray(cond_p.std(0) + 1e-6)
|
| 213 |
+
|
| 214 |
+
if not bits:
|
| 215 |
+
# continuous target normalization (whole-dataset stats; the tuple-sampled
|
| 216 |
+
# stats train_genq_jax uses agree to ~1% for maze xy). A warm-start ckpt's
|
| 217 |
+
# y stats override — the loaded weights were trained against them.
|
| 218 |
+
# Puzzle-as-continuous: force mean=0.5/std=0.5 so the 0/1 config bits
|
| 219 |
+
# embed EXACTLY as +-1 (the natural scale, independent of bit balance).
|
| 220 |
+
if env_id.startswith("puzzle"):
|
| 221 |
+
y_mean_j = jnp.full((y_dim,), 0.5)
|
| 222 |
+
y_std_j = jnp.full((y_dim,), 0.5)
|
| 223 |
+
elif occ_warmstart_npz and "y_mean" in np.load(occ_warmstart_npz).files:
|
| 224 |
+
d0y = np.load(occ_warmstart_npz)
|
| 225 |
+
y_mean_j = jnp.asarray(d0y["y_mean"])
|
| 226 |
+
y_std_j = jnp.asarray(d0y["y_std"])
|
| 227 |
+
else:
|
| 228 |
+
y_mean_j = jnp.asarray(target_full.mean(0))
|
| 229 |
+
y_std_j = jnp.asarray(target_full.std(0) + 1e-6)
|
| 230 |
+
|
| 231 |
+
if bits:
|
| 232 |
+
def occ_loss_fn(params, c_raw, b01, t_int, m, w):
|
| 233 |
+
c = (c_raw - cond_mean) / cond_std
|
| 234 |
+
tf = t_int.astype(jnp.float32) / occ_T
|
| 235 |
+
xt = (2.0 * b01 - 1.0) * (1.0 - m) # visible signed bits, 0 = MASK
|
| 236 |
+
pred = occ_model.apply(params, jnp.concatenate([xt, m], -1), tf, c)
|
| 237 |
+
bce = optax.sigmoid_binary_cross_entropy(pred, b01)
|
| 238 |
+
return (w[:, None] * bce * m).sum() / jnp.maximum(m.sum(), 1.0)
|
| 239 |
+
else:
|
| 240 |
+
# standard weighted eps-prediction DDPM (train_genq_jax loss_fn, diffusion path);
|
| 241 |
+
# the 4th data arg carries the Gaussian noise instead of the bit mask
|
| 242 |
+
def occ_loss_fn(params, c_raw, y_raw, t_int, eps, w):
|
| 243 |
+
c = (c_raw - cond_mean) / cond_std
|
| 244 |
+
x0 = (y_raw - y_mean_j) / y_std_j
|
| 245 |
+
tf = t_int.astype(jnp.float32) / occ_T
|
| 246 |
+
ab = abar_j[t_int - 1][:, None]
|
| 247 |
+
xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1.0 - ab) * eps
|
| 248 |
+
pred = occ_model.apply(params, xt, tf, c)
|
| 249 |
+
return (w[:, None] * (pred - eps) ** 2).mean()
|
| 250 |
+
|
| 251 |
+
@jax.jit
|
| 252 |
+
def occ_update(params, opt_state, ema, c_raw, b01, t_int, m, w):
|
| 253 |
+
loss, grads = jax.value_and_grad(occ_loss_fn)(params, c_raw, b01, t_int, m, w)
|
| 254 |
+
updates, opt_state = occ_tx.update(grads, opt_state, params)
|
| 255 |
+
params = optax.apply_updates(params, updates)
|
| 256 |
+
ema = jax.tree_util.tree_map(lambda e, p: e * (1 - occ_tau) + p * occ_tau, ema, params)
|
| 257 |
+
return params, opt_state, ema, loss
|
| 258 |
+
|
| 259 |
+
if not bits:
|
| 260 |
+
# ---- continuous read-out: N DDIM occupancy draws + the Gaussian tolerance
|
| 261 |
+
# kernel of genq_jax.genq_q — Q = mean_i exp(-||x_i - g||^2 / (2 sigma^2)),
|
| 262 |
+
# sigma from _runner.SIGMA_BY_ENV. The sampler replicates genq_jax.sample's
|
| 263 |
+
# diffusion path exactly: ts = linspace(T,1,steps) (1-based, abar index t-1),
|
| 264 |
+
# eps clip +-6, x0 clip +-5 (normalized space), last step returns x0. ----
|
| 265 |
+
_ro_steps = 30 # genq_jax meta sample_steps default
|
| 266 |
+
ts_ro = jnp.asarray(np.clip(np.round(np.linspace(occ_T, 1, _ro_steps))
|
| 267 |
+
.astype(np.int32), 1, occ_T))
|
| 268 |
+
|
| 269 |
+
def ddim_draws(ema, cc, key):
|
| 270 |
+
"""cc:[BM,cond] normalized -> x:[BM,y_dim] raw target coords."""
|
| 271 |
+
BM = cc.shape[0]
|
| 272 |
+
key, sub = jax.random.split(key)
|
| 273 |
+
x = jax.random.normal(sub, (BM, y_dim))
|
| 274 |
+
|
| 275 |
+
def step(x, i):
|
| 276 |
+
t = ts_ro[i]
|
| 277 |
+
abar_t = abar_j[t - 1]
|
| 278 |
+
tf = jnp.full((BM,), t.astype(jnp.float32) / occ_T)
|
| 279 |
+
eps = jnp.clip(occ_model.apply(ema, x, tf, cc), -6.0, 6.0)
|
| 280 |
+
x0 = jnp.clip((x - jnp.sqrt(1.0 - abar_t) * eps) / jnp.sqrt(abar_t),
|
| 281 |
+
-5.0, 5.0)
|
| 282 |
+
t_next = ts_ro[jnp.minimum(i + 1, _ro_steps - 1)]
|
| 283 |
+
abar_n = abar_j[t_next - 1]
|
| 284 |
+
x_next = (jnp.sqrt(abar_n) * x0 +
|
| 285 |
+
jnp.sqrt(jnp.clip(1.0 - abar_n, 0.0, None)) * eps)
|
| 286 |
+
return jnp.where(i < _ro_steps - 1, x_next, x0), None
|
| 287 |
+
|
| 288 |
+
x, _ = jax.lax.scan(step, x, jnp.arange(_ro_steps))
|
| 289 |
+
return x * y_std_j + y_mean_j
|
| 290 |
+
|
| 291 |
+
@jax.jit
|
| 292 |
+
def samp_kernel_q(ema, s, a, g, k, dv=None):
|
| 293 |
+
parts = [s, a, g] + ([dv[:, None]] if spec_on else [])
|
| 294 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 295 |
+
B = c.shape[0]
|
| 296 |
+
cc = jnp.repeat(c, n_occ_ro, axis=0)
|
| 297 |
+
x = ddim_draws(ema, cc, k).reshape(B, n_occ_ro, y_dim)
|
| 298 |
+
d2 = jnp.sum(((x - g[:, None, :]) / ro_sigma) ** 2, axis=-1)
|
| 299 |
+
return jnp.exp(-d2 / 2.0).mean(-1)
|
| 300 |
+
|
| 301 |
+
# ---- ELBO read-out (--readout elbo): the GENERAL, space-agnostic
|
| 302 |
+
# likelihood surrogate. Evaluate the eps-prediction denoising loss AT
|
| 303 |
+
# the goal's continuous embedding z_g = (g - y_mean)/y_std (+-1 bits on
|
| 304 |
+
# puzzle, standardized xy on mazes):
|
| 305 |
+
# L_den(g; cond) = mean_{i=1..K} ||eps_theta(sqrt(abar_ti) z_g +
|
| 306 |
+
# sqrt(1-abar_ti) eps_i, ti | cond) - eps_i||^2,
|
| 307 |
+
# a monotone surrogate of -log p(g | cond) up to a condition-independent
|
| 308 |
+
# constant; Q = exp(-elbo_c * L_den). Point evaluation like gl (zero
|
| 309 |
+
# hit-variance — no samples need to land on the goal), one model apply
|
| 310 |
+
# per draw, differentiable in the action through the conditioning.
|
| 311 |
+
# t stratified over [elbo_tlo, elbo_thi] quantile bands; antithetic
|
| 312 |
+
# (+eps, -eps at the same t) pairs halve estimator variance for free.
|
| 313 |
+
assert elbo_K % 2 == 0, "--elbo_K must be even (antithetic pairs)"
|
| 314 |
+
|
| 315 |
+
def _elbo_cond(s, a, g, dv):
|
| 316 |
+
parts = [s, a, g] + ([dv[:, None]] if spec_on else [])
|
| 317 |
+
return (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 318 |
+
|
| 319 |
+
def elbo_loss(ema, c, g, k, K):
|
| 320 |
+
"""c: [B,cond] normalized conditioning; g: [B,y_dim] raw target.
|
| 321 |
+
The (t, eps) draws depend only on `k` — never on the conditioning —
|
| 322 |
+
so a fixed per-batch key gives the actor a smooth estimator to
|
| 323 |
+
differentiate through c."""
|
| 324 |
+
B = c.shape[0]
|
| 325 |
+
Kh = K // 2
|
| 326 |
+
zg = (g - y_mean_j) / y_std_j
|
| 327 |
+
k1, k2 = jax.random.split(k)
|
| 328 |
+
# stratified t: draw i covers quantile band i/Kh of [tlo, thi]
|
| 329 |
+
u = jax.random.uniform(k1, (B, Kh))
|
| 330 |
+
frac = elbo_tlo + (jnp.arange(Kh)[None, :] + u) / Kh * (elbo_thi - elbo_tlo)
|
| 331 |
+
t_int = jnp.clip((frac * occ_T).astype(jnp.int32) + 1, 1, occ_T)
|
| 332 |
+
t_int = jnp.tile(t_int, (1, 2)).reshape(-1) # antithetic twin shares t
|
| 333 |
+
e = jax.random.normal(k2, (B, Kh, y_dim))
|
| 334 |
+
eps = jnp.concatenate([e, -e], 1).reshape(B * K, y_dim)
|
| 335 |
+
cc = jnp.repeat(c, K, axis=0)
|
| 336 |
+
zg_r = jnp.repeat(zg, K, axis=0)
|
| 337 |
+
ab = abar_j[t_int - 1][:, None]
|
| 338 |
+
zt = jnp.sqrt(ab) * zg_r + jnp.sqrt(1.0 - ab) * eps
|
| 339 |
+
pred = occ_model.apply(ema, zt, t_int.astype(jnp.float32) / occ_T, cc)
|
| 340 |
+
return ((pred - eps) ** 2).mean(-1).reshape(B, K).mean(-1)
|
| 341 |
+
|
| 342 |
+
@jax.jit
|
| 343 |
+
def elbo_q(ema, s, a, g, k, dv=None):
|
| 344 |
+
return jnp.exp(-elbo_c * elbo_loss(ema, _elbo_cond(s, a, g, dv), g, k,
|
| 345 |
+
elbo_K))
|
| 346 |
+
|
| 347 |
+
if readout == "elbo":
|
| 348 |
+
ro_q = elbo_q
|
| 349 |
+
print(f"[joint] READOUT=elbo c={elbo_c} K={elbo_K} "
|
| 350 |
+
f"t_band=[{elbo_tlo},{elbo_thi}] (denoising-loss likelihood "
|
| 351 |
+
f"surrogate, antithetic; cont mode)", flush=True)
|
| 352 |
+
else:
|
| 353 |
+
ro_q = samp_kernel_q
|
| 354 |
+
print(f"[joint] READOUT=kernel-sample n_occ={n_occ_ro} sigma={ro_sigma} "
|
| 355 |
+
f"ddim_steps={_ro_steps} (cont mode)", flush=True)
|
| 356 |
+
|
| 357 |
+
# in-graph goal-obs -> raw target (the differentiated ddpg2 path reads
|
| 358 |
+
# goals from full goal observations inside jit)
|
| 359 |
+
if env_id.startswith("puzzle"):
|
| 360 |
+
from target_extractors import (_PUZZLE_PRESSED_IDX,
|
| 361 |
+
_PUZZLE4X4_PRESSED_IDX)
|
| 362 |
+
_tgt_idx_c = jnp.asarray(_PUZZLE4X4_PRESSED_IDX if "4x4" in env_id
|
| 363 |
+
else _PUZZLE_PRESSED_IDX)
|
| 364 |
+
tgt_j = lambda gobs: gobs[:, _tgt_idx_c]
|
| 365 |
+
else:
|
| 366 |
+
tgt_j = lambda gobs: gobs[:, :y_dim] # maze xy = leading obs dims
|
| 367 |
+
if bits:
|
| 368 |
+
# ---- goal-likelihood read-out on the EMA occupancy (teacher-forced unmasking) ----
|
| 369 |
+
kappas = np.arange(n_bits, dtype=np.float64) / n_bits
|
| 370 |
+
ts_frac = jnp.asarray(np.array(
|
| 371 |
+
[(1 + int(np.argmin(np.abs(abar - k)))) / occ_T for k in kappas],
|
| 372 |
+
dtype=np.float32))
|
| 373 |
+
|
| 374 |
+
# goal-obs -> 9 target bits, in-graph (indices from target_extractors)
|
| 375 |
+
from target_extractors import _PUZZLE_PRESSED_IDX, _PUZZLE4X4_PRESSED_IDX
|
| 376 |
+
tgt_idx = jnp.asarray(_PUZZLE4X4_PRESSED_IDX if "4x4" in env_id
|
| 377 |
+
else _PUZZLE_PRESSED_IDX)
|
| 378 |
+
tgt_j = lambda gobs: gobs[:, tgt_idx]
|
| 379 |
+
|
| 380 |
+
def gl_q_orders(ema, s, a, g, k, n_ord, dv=None):
|
| 381 |
+
parts = [s, a, g] + ([dv[:, None]] if spec_on else [])
|
| 382 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 383 |
+
B = c.shape[0]
|
| 384 |
+
cc = jnp.repeat(c, n_ord, axis=0)
|
| 385 |
+
BO = B * n_ord
|
| 386 |
+
g01 = jnp.round(jnp.clip(jnp.repeat(g, n_ord, axis=0), 0.0, 1.0))
|
| 387 |
+
k, sub = jax.random.split(k)
|
| 388 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BO, n_bits)), axis=-1)
|
| 389 |
+
rows = jnp.arange(BO)
|
| 390 |
+
|
| 391 |
+
def _step(carry, i):
|
| 392 |
+
x, m, logp = carry
|
| 393 |
+
out = occ_model.apply(ema, jnp.concatenate([x, m], -1),
|
| 394 |
+
jnp.full((BO,), ts_frac[i]), cc)
|
| 395 |
+
idx = orders[:, i]
|
| 396 |
+
logit = out[rows, idx]
|
| 397 |
+
gbit = g01[rows, idx]
|
| 398 |
+
logp = logp + gbit * jax.nn.log_sigmoid(logit) + (1 - gbit) * jax.nn.log_sigmoid(-logit)
|
| 399 |
+
x = x.at[rows, idx].set(2.0 * gbit - 1.0)
|
| 400 |
+
m = m.at[rows, idx].set(0.0)
|
| 401 |
+
return (x, m, logp), None
|
| 402 |
+
|
| 403 |
+
init = (jnp.zeros((BO, n_bits)), jnp.ones((BO, n_bits)), jnp.zeros((BO,)))
|
| 404 |
+
(_, _, logp), _ = jax.lax.scan(_step, init, jnp.arange(n_bits))
|
| 405 |
+
return jnp.exp(logp).reshape(B, n_ord).mean(-1)
|
| 406 |
+
|
| 407 |
+
@jax.jit
|
| 408 |
+
def gl_q(ema, s, a, g, k, dv=None):
|
| 409 |
+
parts = [s, a, g] + ([dv[:, None]] if spec_on else [])
|
| 410 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 411 |
+
B = c.shape[0]
|
| 412 |
+
cc = jnp.repeat(c, n_orders, axis=0)
|
| 413 |
+
BO = B * n_orders
|
| 414 |
+
g01 = jnp.round(jnp.clip(jnp.repeat(g, n_orders, axis=0), 0.0, 1.0))
|
| 415 |
+
k, sub = jax.random.split(k)
|
| 416 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BO, n_bits)), axis=-1)
|
| 417 |
+
rows = jnp.arange(BO)
|
| 418 |
+
|
| 419 |
+
def step(carry, i):
|
| 420 |
+
x, m, logp = carry
|
| 421 |
+
out = occ_model.apply(ema, jnp.concatenate([x, m], -1),
|
| 422 |
+
jnp.full((BO,), ts_frac[i]), cc)
|
| 423 |
+
idx = orders[:, i]
|
| 424 |
+
logit = out[rows, idx]
|
| 425 |
+
gbit = g01[rows, idx]
|
| 426 |
+
logp = logp + gbit * jax.nn.log_sigmoid(logit) + (1 - gbit) * jax.nn.log_sigmoid(-logit)
|
| 427 |
+
x = x.at[rows, idx].set(2.0 * gbit - 1.0)
|
| 428 |
+
m = m.at[rows, idx].set(0.0)
|
| 429 |
+
return (x, m, logp), None
|
| 430 |
+
|
| 431 |
+
init = (jnp.zeros((BO, n_bits)), jnp.ones((BO, n_bits)), jnp.zeros((BO,)))
|
| 432 |
+
(_, _, logp), _ = jax.lax.scan(step, init, jnp.arange(n_bits))
|
| 433 |
+
return jnp.exp(logp).reshape(B, n_orders).mean(-1)
|
| 434 |
+
|
| 435 |
+
# ---- sampling-count read-out (--readout sample): the DE-HACKED control for gl.
|
| 436 |
+
# Same quantity P(x=g|s,a,g), estimated the generic way — N ancestral draws from
|
| 437 |
+
# the occupancy, exact bit-match rate. No closed-form likelihood, no ordering
|
| 438 |
+
# ensemble, no discreteness exploited beyond what any sampler needs. Higher
|
| 439 |
+
# variance (binomial), ~n_occ_ro/(n_orders) x the cost; targets only — the actor
|
| 440 |
+
# still differentiates the distilled critic, so nothing else changes. ----
|
| 441 |
+
@jax.jit
|
| 442 |
+
def samp_prob_q(ema, s, a, g, k, dv=None):
|
| 443 |
+
parts = [s, a, g] + ([dv[:, None]] if spec_on else [])
|
| 444 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 445 |
+
B = c.shape[0]
|
| 446 |
+
cc = jnp.repeat(c, n_occ_ro, axis=0)
|
| 447 |
+
BM = B * n_occ_ro
|
| 448 |
+
k, sub = jax.random.split(k)
|
| 449 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BM, n_bits)), axis=-1)
|
| 450 |
+
rows = jnp.arange(BM)
|
| 451 |
+
|
| 452 |
+
def step(carry, i):
|
| 453 |
+
x, m, kk = carry
|
| 454 |
+
out = occ_model.apply(ema, jnp.concatenate([x, m], -1),
|
| 455 |
+
jnp.full((BM,), ts_frac[i]), cc)
|
| 456 |
+
idx = orders[:, i]
|
| 457 |
+
kk, sub2 = jax.random.split(kk)
|
| 458 |
+
b = jax.random.bernoulli(sub2, jax.nn.sigmoid(out[rows, idx])).astype(jnp.float32)
|
| 459 |
+
x = x.at[rows, idx].set(2.0 * b - 1.0)
|
| 460 |
+
m = m.at[rows, idx].set(0.0)
|
| 461 |
+
return (x, m, kk), None
|
| 462 |
+
|
| 463 |
+
init = (jnp.zeros((BM, n_bits)), jnp.ones((BM, n_bits)), k)
|
| 464 |
+
(x, _, _), _ = jax.lax.scan(step, init, jnp.arange(n_bits))
|
| 465 |
+
bits = (x + 1.0) / 2.0
|
| 466 |
+
g01 = jnp.round(jnp.clip(jnp.repeat(g, n_occ_ro, axis=0), 0.0, 1.0))
|
| 467 |
+
hit = jnp.all(jnp.abs(bits - g01) < 0.5, axis=-1).astype(jnp.float32)
|
| 468 |
+
return hit.reshape(B, n_occ_ro).mean(-1)
|
| 469 |
+
|
| 470 |
+
if bits:
|
| 471 |
+
ro_q = samp_prob_q if readout == "sample" else gl_q
|
| 472 |
+
if readout == "sample":
|
| 473 |
+
print(f"[joint] READOUT=sample n_occ={n_occ_ro} (de-hacked MC hit-count "
|
| 474 |
+
f"targets; gl exact-likelihood disabled)", flush=True)
|
| 475 |
+
|
| 476 |
+
# ---- RECURSIVE PREDICTION on the live occupancy (owner directive: try recursion
|
| 477 |
+
# on the 2-model and 3-model joint carriers). Midpoints are sampled from the EMA
|
| 478 |
+
# occupancy by ANY-ORDER ANCESTRAL SAMPLING (9 bits -> 9 unmasking steps, exact for
|
| 479 |
+
# the masked-diffusion factorization), snapped to dataset rows via the eps-grid. ----
|
| 480 |
+
rec_cells = None
|
| 481 |
+
if rec_target > 0:
|
| 482 |
+
if not bits:
|
| 483 |
+
@jax.jit
|
| 484 |
+
def occ_sample_bits(ema, s, a, g, k, dv=None):
|
| 485 |
+
"""cont: M raw continuous occupancy draws per row — the midpoints
|
| 486 |
+
c_m. No snapping, no retrieval (rec_free asserted at entry); same
|
| 487 |
+
name and [B, M, y_dim] contract as the bits sampler so downstream
|
| 488 |
+
composition code is shared."""
|
| 489 |
+
parts = [s, a, g] + ([dv[:, None]] if spec_on else [])
|
| 490 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 491 |
+
B = c.shape[0]
|
| 492 |
+
cc = jnp.repeat(c, rec_target, axis=0)
|
| 493 |
+
return ddim_draws(ema, cc, k).reshape(B, rec_target, y_dim)
|
| 494 |
+
else:
|
| 495 |
+
@jax.jit
|
| 496 |
+
def occ_sample_bits(ema, s, a, g, k, dv=None):
|
| 497 |
+
parts = [s, a, g] + ([dv[:, None]] if spec_on else [])
|
| 498 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 499 |
+
B = c.shape[0]
|
| 500 |
+
cc = jnp.repeat(c, rec_target, axis=0)
|
| 501 |
+
BM = B * rec_target
|
| 502 |
+
k, sub = jax.random.split(k)
|
| 503 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BM, n_bits)), axis=-1)
|
| 504 |
+
rows = jnp.arange(BM)
|
| 505 |
+
|
| 506 |
+
def step(carry, i):
|
| 507 |
+
x, m, kk = carry
|
| 508 |
+
out = occ_model.apply(ema, jnp.concatenate([x, m], -1),
|
| 509 |
+
jnp.full((BM,), ts_frac[i]), cc)
|
| 510 |
+
idx = orders[:, i]
|
| 511 |
+
kk, sub2 = jax.random.split(kk)
|
| 512 |
+
b = jax.random.bernoulli(
|
| 513 |
+
sub2, jax.nn.sigmoid(out[rows, idx])).astype(jnp.float32)
|
| 514 |
+
x = x.at[rows, idx].set(2.0 * b - 1.0)
|
| 515 |
+
m = m.at[rows, idx].set(0.0)
|
| 516 |
+
return (x, m, kk), None
|
| 517 |
+
|
| 518 |
+
init = (jnp.zeros((BM, n_bits)), jnp.ones((BM, n_bits)), k)
|
| 519 |
+
(x, _, _), _ = jax.lax.scan(step, init, jnp.arange(n_bits))
|
| 520 |
+
return ((x + 1.0) / 2.0).reshape(B, rec_target, n_bits)
|
| 521 |
+
|
| 522 |
+
if not rec_free:
|
| 523 |
+
_w_rec = (rec_eps * (target_full.std(0) + 1e-6)).astype(np.float32)
|
| 524 |
+
_cells_r = np.floor(target_full / _w_rec).astype(np.int64)
|
| 525 |
+
_uniq_r, _inv_r = np.unique(_cells_r, axis=0, return_inverse=True)
|
| 526 |
+
_order_r = np.argsort(_inv_r, kind="stable")
|
| 527 |
+
_bounds_r = np.searchsorted(_inv_r[_order_r], np.arange(len(_uniq_r) + 1))
|
| 528 |
+
rec_cells = {tuple(u): (int(_bounds_r[j2]), int(_bounds_r[j2 + 1]))
|
| 529 |
+
for j2, u in enumerate(_uniq_r)}
|
| 530 |
+
rng_rec = np.random.default_rng(seed + 4242)
|
| 531 |
+
print(f"[joint] REC M={rec_target} every={rec_every} after={rec_after} "
|
| 532 |
+
f"eps={rec_eps}: {len(_uniq_r)} junction cells", flush=True)
|
| 533 |
+
|
| 534 |
+
def rec_retrieve(bits):
|
| 535 |
+
"""[B,M,n_bits] sampled endpoints -> dataset rows + validity (unseen cell -> 0)."""
|
| 536 |
+
keys_ = np.floor(np.asarray(bits).reshape(-1, n_bits) / _w_rec).astype(np.int64)
|
| 537 |
+
rows_ = np.zeros(len(keys_), np.int64)
|
| 538 |
+
valid = np.zeros(len(keys_), np.float32)
|
| 539 |
+
for i2 in range(len(keys_)):
|
| 540 |
+
cell = rec_cells.get(tuple(keys_[i2]))
|
| 541 |
+
if cell is not None:
|
| 542 |
+
lo, hi = cell
|
| 543 |
+
rows_[i2] = _order_r[lo + int(rng_rec.integers(hi - lo))]
|
| 544 |
+
valid[i2] = 1.0
|
| 545 |
+
return rows_, valid
|
| 546 |
+
else:
|
| 547 |
+
# RETRIEVAL-FREE midpoints (owner directive): the occupancy stack predicts
|
| 548 |
+
# the FULL STATE, so no dataset lookup exists anywhere. Factorization
|
| 549 |
+
# p(x_full | s,a,g) = p(bits | s,a,g) * p(x_full | s,a,g,bits):
|
| 550 |
+
# the exact masked-bits model (gl read-out) is untouched; a co-trained
|
| 551 |
+
# conditional Gaussian diffusion COMPLETES the sampled config into a full
|
| 552 |
+
# observation, trained on the same absorbing/rt/actor-weighted tuples
|
| 553 |
+
# (target obs[j], bits teacher-forced). The midpoint ACTION comes from the
|
| 554 |
+
# live actor at the generated state (a behavior action at a generated
|
| 555 |
+
# state would require retrieval by definition).
|
| 556 |
+
obs_mu_j = jnp.asarray(obs.mean(0))
|
| 557 |
+
obs_sd_j = jnp.asarray(obs.std(0) + 1e-6)
|
| 558 |
+
# midpoint slot of the completion conditioning: bits are 0/1 (0.5/0.5
|
| 559 |
+
# normalization); continuous midpoints use the target y stats
|
| 560 |
+
c2_mean = jnp.concatenate(
|
| 561 |
+
[cond_mean, jnp.full((n_bits,), 0.5) if bits else y_mean_j])
|
| 562 |
+
c2_std = jnp.concatenate(
|
| 563 |
+
[cond_std, jnp.full((n_bits,), 0.5) if bits else y_std_j])
|
| 564 |
+
cmpl_model = make_model(cond_dim + n_bits, obs.shape[1], occ_hidden,
|
| 565 |
+
occ_layers, occ_time_dim)
|
| 566 |
+
cmpl_params = cmpl_model.init(jax.random.PRNGKey(seed + 7),
|
| 567 |
+
jnp.zeros((1, obs.shape[1])), jnp.zeros((1,)),
|
| 568 |
+
jnp.zeros((1, cond_dim + n_bits)))
|
| 569 |
+
cmpl_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(occ_lr))
|
| 570 |
+
cmpl_opt = cmpl_tx.init(cmpl_params)
|
| 571 |
+
cmpl_ema = jax.tree_util.tree_map(lambda x: x, cmpl_params)
|
| 572 |
+
|
| 573 |
+
@jax.jit
|
| 574 |
+
def cmpl_update(cp, co, ce, cond2_raw, x0_raw, t_int, eps, w):
|
| 575 |
+
c2 = (cond2_raw - c2_mean) / c2_std
|
| 576 |
+
x0 = (x0_raw - obs_mu_j) / obs_sd_j
|
| 577 |
+
ab = abar_j[t_int - 1][:, None]
|
| 578 |
+
xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1.0 - ab) * eps
|
| 579 |
+
|
| 580 |
+
def lf(p):
|
| 581 |
+
pred = cmpl_model.apply(p, xt, t_int.astype(jnp.float32) / occ_T, c2)
|
| 582 |
+
return (w[:, None] * (pred - eps) ** 2).mean()
|
| 583 |
+
|
| 584 |
+
cl, gr = jax.value_and_grad(lf)(cp)
|
| 585 |
+
upd, co = cmpl_tx.update(gr, co, cp)
|
| 586 |
+
cp = optax.apply_updates(cp, upd)
|
| 587 |
+
ce = jax.tree_util.tree_map(
|
| 588 |
+
lambda e, q: e * (1 - occ_tau) + q * occ_tau, ce, cp)
|
| 589 |
+
return cp, co, ce, cl
|
| 590 |
+
|
| 591 |
+
_ts_c = np.unique(np.linspace(occ_T, 1, 25).round().astype(np.int32))[::-1].copy()
|
| 592 |
+
ts_c_now = jnp.asarray(_ts_c)
|
| 593 |
+
ts_c_nxt = jnp.asarray(np.concatenate([_ts_c[1:], [0]]).astype(np.int32))
|
| 594 |
+
|
| 595 |
+
@jax.jit
|
| 596 |
+
def cmpl_sample(ce, cond2_raw, key):
|
| 597 |
+
c2 = (cond2_raw - c2_mean) / c2_std
|
| 598 |
+
B2 = c2.shape[0]
|
| 599 |
+
x = jax.random.normal(key, (B2, obs.shape[1]))
|
| 600 |
+
|
| 601 |
+
def step(x, i2):
|
| 602 |
+
tn = ts_c_now[i2]
|
| 603 |
+
tx = ts_c_nxt[i2]
|
| 604 |
+
ab_n = abar_j[tn - 1]
|
| 605 |
+
ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0)
|
| 606 |
+
eps = jnp.clip(cmpl_model.apply(
|
| 607 |
+
ce, x, jnp.full((B2,), tn.astype(jnp.float32) / occ_T), c2),
|
| 608 |
+
-6.0, 6.0)
|
| 609 |
+
x0h = (x - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8))
|
| 610 |
+
return jnp.sqrt(ab_x) * x0h + jnp.sqrt(1.0 - ab_x) * eps, None
|
| 611 |
+
|
| 612 |
+
x, _ = jax.lax.scan(step, x, jnp.arange(len(_ts_c)))
|
| 613 |
+
return x * obs_sd_j + obs_mu_j
|
| 614 |
+
|
| 615 |
+
print(f"[joint] REC M={rec_target} every={rec_every} after={rec_after} "
|
| 616 |
+
f"RETRIEVAL-FREE (full-state completion head, {len(_ts_c)}-step DDIM)",
|
| 617 |
+
flush=True)
|
| 618 |
+
|
| 619 |
+
def gl_np(s_, a_, g_, _chunk=256, disc=None):
|
| 620 |
+
dd = gamma if disc is None else disc
|
| 621 |
+
outs = []
|
| 622 |
+
for i0 in range(0, len(s_), _chunk):
|
| 623 |
+
gkey[0], sub2 = jax.random.split(gkey[0])
|
| 624 |
+
nn_ = len(s_[i0:i0 + _chunk])
|
| 625 |
+
outs.append(np.asarray(ro_q(occ_ema, jnp.asarray(s_[i0:i0 + _chunk]),
|
| 626 |
+
jnp.asarray(a_[i0:i0 + _chunk]),
|
| 627 |
+
jnp.asarray(g_[i0:i0 + _chunk]), sub2,
|
| 628 |
+
jnp.full((nn_,), dd, jnp.float32))))
|
| 629 |
+
return np.concatenate(outs)
|
| 630 |
+
|
| 631 |
+
# ---- live-actor future weighting ----
|
| 632 |
+
actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]), action_dim=a_dim,
|
| 633 |
+
state_dependent_std=False, const_std=config["const_std"])
|
| 634 |
+
|
| 635 |
+
@jax.jit
|
| 636 |
+
def actor_mse(actor_params, obs_b, goal_b, act_b):
|
| 637 |
+
mu = jnp.clip(actor_def.apply({"params": actor_params}, obs_b, goal_b).mode(), -1, 1)
|
| 638 |
+
return ((act_b - mu) ** 2).sum(-1)
|
| 639 |
+
|
| 640 |
+
@jax.jit
|
| 641 |
+
def actor_mode(actor_params, obs_b, goal_b):
|
| 642 |
+
return jnp.clip(actor_def.apply({"params": actor_params}, obs_b, goal_b).mode(),
|
| 643 |
+
-1, 1)
|
| 644 |
+
|
| 645 |
+
def occ_tuple_batch(agent, use_pi):
|
| 646 |
+
"""(c_raw, b01, t_int, m, w): ref goal mix + rt stratified hits + live-actor weights."""
|
| 647 |
+
B = occ_batch
|
| 648 |
+
t = rng_np.integers(0, N, B)
|
| 649 |
+
gam = sample_gammas(B) if spec_on else np.full(B, gamma)
|
| 650 |
+
offsets = rng_np.geometric(1.0 - gam, size=B)
|
| 651 |
+
gi_traj = np.minimum(t + offsets, end_of[t] - 1)
|
| 652 |
+
gi_rand = rng_np.integers(0, N, B)
|
| 653 |
+
gi = np.where(rng_np.random(B) < 0.5 / 0.8, gi_traj, gi_rand)
|
| 654 |
+
gi = np.where(rng_np.random(B) < 0.2, t, gi)
|
| 655 |
+
in_traj = (gi >= t) & (gi < end_of[t])
|
| 656 |
+
L = (end_of[t] - t).astype(np.float64)
|
| 657 |
+
d = np.clip(gi - t, 0, None).astype(np.float64)
|
| 658 |
+
lgam = np.log(gam)
|
| 659 |
+
gL = np.power(gam, L)
|
| 660 |
+
p_hit = np.where(in_traj, (np.power(gam, d) - gL) / (1.0 - gL), 0.0)
|
| 661 |
+
take_hit = in_traj & ((rng_np.random(B) < rt_eta) | (gi == t))
|
| 662 |
+
u = rng_np.random(B)
|
| 663 |
+
pd = 1.0 - np.power(gam, np.maximum(d, 1.0))
|
| 664 |
+
k_miss = np.ceil(np.log1p(-u * pd) / lgam).astype(np.int64) - 1
|
| 665 |
+
k_miss = np.clip(k_miss, 0, np.maximum(gi - t - 1, 0))
|
| 666 |
+
u2 = rng_np.random(B)
|
| 667 |
+
k_pl = np.ceil(np.log1p(-u2 * (1.0 - gL)) / lgam).astype(np.int64) - 1
|
| 668 |
+
j_plain = t + np.clip(k_pl, 0, (end_of[t] - t - 1))
|
| 669 |
+
j = np.where(take_hit, gi, np.where(in_traj, t + k_miss, j_plain))
|
| 670 |
+
w = np.ones(B)
|
| 671 |
+
w = np.where(take_hit & (gi != t), p_hit / rt_eta, w)
|
| 672 |
+
w = np.where(in_traj & ~take_hit, (1.0 - p_hit) / (1.0 - rt_eta), w)
|
| 673 |
+
if use_pi and pi_alpha > 0:
|
| 674 |
+
offs = np.arange(1, pi_horizon + 1)
|
| 675 |
+
idx = np.minimum(t[:, None] + offs[None, :], j[:, None])
|
| 676 |
+
valid = (t[:, None] + offs[None, :]) <= j[:, None]
|
| 677 |
+
flat = idx.reshape(-1)
|
| 678 |
+
g_obs = np.repeat(obs[gi], pi_horizon, axis=0)
|
| 679 |
+
ap = agent_actor_params()
|
| 680 |
+
mse = np.asarray(actor_mse(ap, jnp.asarray(obs[flat]), jnp.asarray(g_obs),
|
| 681 |
+
jnp.asarray(act[flat]))).reshape(B, pi_horizon)
|
| 682 |
+
denom = np.maximum(valid.sum(-1), 1)
|
| 683 |
+
m_mse = np.where(valid.any(-1), (mse * valid).sum(-1) / denom, 0.0)
|
| 684 |
+
w_pi = np.exp(-pi_alpha * m_mse / 2.0)
|
| 685 |
+
w = w * (w_pi / max(w_pi.mean(), 1e-8))
|
| 686 |
+
c_parts = [obs[t], act[t], target_full[gi]]
|
| 687 |
+
if spec_on:
|
| 688 |
+
c_parts.append(gam[:, None].astype(np.float32))
|
| 689 |
+
c_raw = np.concatenate(c_parts, axis=1)
|
| 690 |
+
b01 = target_full[j]
|
| 691 |
+
t_int = rng_np.integers(1, occ_T + 1, B).astype(np.int32)
|
| 692 |
+
if bits:
|
| 693 |
+
keep = abar[t_int - 1]
|
| 694 |
+
m = (rng_np.random((B, n_bits)) >= keep[:, None]).astype(np.float32)
|
| 695 |
+
else:
|
| 696 |
+
# cont: the 4th slot carries the Gaussian eps for the DDPM loss
|
| 697 |
+
m = rng_np.standard_normal((B, y_dim)).astype(np.float32)
|
| 698 |
+
return (jnp.asarray(c_raw), jnp.asarray(b01), jnp.asarray(t_int),
|
| 699 |
+
jnp.asarray(m), jnp.asarray(w.astype(np.float32)), j)
|
| 700 |
+
|
| 701 |
+
# ---- agent + data ----
|
| 702 |
+
train_ds = GCDataset(Dataset.create(**train_dataset), config)
|
| 703 |
+
ex = train_ds.sample(2)
|
| 704 |
+
if extraction in ("ddpg2", "awr2"):
|
| 705 |
+
assert not (extraction == "awr2" and rec_target > 0), \
|
| 706 |
+
"awr2 v1: plain-gl advantage only (no recursion wiring yet)"
|
| 707 |
+
# TRUE 2-MODEL improvement (owner directive): the goal-likelihood is
|
| 708 |
+
# differentiable in the action (a enters only through the conditioning of a
|
| 709 |
+
# smooth net), so DDPG+BC runs THROUGH THE OCCUPANCY -- no critic network:
|
| 710 |
+
# L = -log gl(s, mu(s,g), g)/|log gl| + alpha * (-log pi(a_data|s,g)).
|
| 711 |
+
# Networks: occupancy + policy head. That's all.
|
| 712 |
+
# awr2 = same two networks but the actor loss is advantage-weighted BC with
|
| 713 |
+
# FORWARD-ONLY gl (no gradient through the occupancy at all; owner: 'if actor
|
| 714 |
+
# gradient is slow consider using awr').
|
| 715 |
+
ddpg2_actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]),
|
| 716 |
+
action_dim=a_dim, state_dependent_std=False,
|
| 717 |
+
const_std=config["const_std"])
|
| 718 |
+
d2holder = {}
|
| 719 |
+
d2holder["params"] = ddpg2_actor_def.init(
|
| 720 |
+
jax.random.PRNGKey(seed + 1), ex["observations"], ex["observations"])["params"]
|
| 721 |
+
d2tx = optax.adam(learning_rate=config["lr"])
|
| 722 |
+
d2holder["opt"] = d2tx.init(d2holder["params"])
|
| 723 |
+
n_orders_grad = 8
|
| 724 |
+
|
| 725 |
+
@jax.jit
|
| 726 |
+
def ddpg2_update(params, opt_state, ema, obs_b, ag, acts, key):
|
| 727 |
+
def loss_fn(pp):
|
| 728 |
+
dist = ddpg2_actor_def.apply({"params": pp}, obs_b, ag)
|
| 729 |
+
mu = jnp.clip(dist.mode(), -1, 1)
|
| 730 |
+
dv_t = jnp.full((obs_b.shape[0],), gamma, jnp.float32)
|
| 731 |
+
q = jnp.log(jnp.maximum(
|
| 732 |
+
gl_q_orders(ema, obs_b, mu, tgt_j(ag), key, n_orders_grad, dv_t),
|
| 733 |
+
1e-9))
|
| 734 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6)
|
| 735 |
+
bc = -dist.log_prob(acts).mean()
|
| 736 |
+
return q_loss + config["alpha"] * bc, {"q_loss": q_loss, "bc_loss": bc,
|
| 737 |
+
"q_mean": q.mean()}
|
| 738 |
+
(_, info), grads = jax.value_and_grad(loss_fn, has_aux=True)(params)
|
| 739 |
+
updates, opt_state = d2tx.update(grads, opt_state, params)
|
| 740 |
+
return optax.apply_updates(params, updates), opt_state, info
|
| 741 |
+
|
| 742 |
+
@jax.jit
|
| 743 |
+
def awr2_adv(ema, base_params, obs_b, ag, acts, key):
|
| 744 |
+
# forward-only log-space advantage: A = log gl(s, a_data, g) -
|
| 745 |
+
# log gl(s, mu_base(s,g), g); the baseline action comes from the EMA
|
| 746 |
+
# actor (or the live one when no EMA). Batch-std normalization makes
|
| 747 |
+
# awr_alpha scale-free (campaign lesson: adv_norm, alpha in [2,3]).
|
| 748 |
+
ks = jax.random.split(key, 2)
|
| 749 |
+
mu = jnp.clip(ddpg2_actor_def.apply({"params": base_params}, obs_b,
|
| 750 |
+
ag).mode(), -1, 1)
|
| 751 |
+
dv_t = jnp.full((obs_b.shape[0],), gamma, jnp.float32)
|
| 752 |
+
qa = jnp.log(jnp.maximum(
|
| 753 |
+
gl_q_orders(ema, obs_b, acts, tgt_j(ag), ks[0], n_orders_grad, dv_t),
|
| 754 |
+
1e-9))
|
| 755 |
+
qb = jnp.log(jnp.maximum(
|
| 756 |
+
gl_q_orders(ema, obs_b, mu, tgt_j(ag), ks[1], n_orders_grad, dv_t),
|
| 757 |
+
1e-9))
|
| 758 |
+
adv = qa - qb
|
| 759 |
+
return adv / (jnp.std(adv) + 1e-6)
|
| 760 |
+
|
| 761 |
+
@jax.jit
|
| 762 |
+
def awr2_update(params, opt_state, obs_b, ag, acts, adv):
|
| 763 |
+
w = jnp.minimum(jnp.exp(awr_alpha * adv), 100.0)
|
| 764 |
+
|
| 765 |
+
def loss_fn(pp):
|
| 766 |
+
dist = ddpg2_actor_def.apply({"params": pp}, obs_b, ag)
|
| 767 |
+
bc = -dist.log_prob(acts)
|
| 768 |
+
return (w * bc).mean(), {"bc_loss": bc.mean(), "w_mean": w.mean(),
|
| 769 |
+
"adv_mean": adv.mean()}
|
| 770 |
+
|
| 771 |
+
(_, info), grads = jax.value_and_grad(loss_fn, has_aux=True)(params)
|
| 772 |
+
updates, opt_state = d2tx.update(grads, opt_state, params)
|
| 773 |
+
return optax.apply_updates(params, updates), opt_state, info
|
| 774 |
+
|
| 775 |
+
if rec_target > 0 and rec_prob:
|
| 776 |
+
# PROBABILISTIC beta-jump actor loss (splitting identity, no max):
|
| 777 |
+
# Q = (1-p)*gl_b(s,mu,g) + p * [gl_b(s,mu,c)/sg(gl_b(s,a_samp,c))] * v_c
|
| 778 |
+
# The exact any-order likelihood makes the first hop differentiable in mu
|
| 779 |
+
# via an exact importance ratio instead of max-picking; v_c is the
|
| 780 |
+
# coin-terminated chain estimate from the generated midpoint (host const).
|
| 781 |
+
@jax.jit
|
| 782 |
+
def ddpg2_update_prob(params, opt_state, ema, obs_b, ag, acts, key,
|
| 783 |
+
mid_g, mid_v, mid_den):
|
| 784 |
+
def loss_fn(pp):
|
| 785 |
+
dist = ddpg2_actor_def.apply({"params": pp}, obs_b, ag)
|
| 786 |
+
mu = jnp.clip(dist.mode(), -1, 1)
|
| 787 |
+
ks = jax.random.split(key, 2)
|
| 788 |
+
dv_h = jnp.full((obs_b.shape[0],), hop_disc, jnp.float32)
|
| 789 |
+
glb = gl_q_orders(ema, obs_b, mu, tgt_j(ag), ks[0], n_orders_grad,
|
| 790 |
+
dv_h)
|
| 791 |
+
num = gl_q_orders(ema, obs_b, mu, mid_g, ks[1], n_orders_grad,
|
| 792 |
+
dv_h)
|
| 793 |
+
ratio = num / jnp.maximum(mid_den, 1e-6)
|
| 794 |
+
qv = (1.0 - rec_p) * glb + rec_p * ratio * mid_v
|
| 795 |
+
q = jnp.log(jnp.maximum(qv, 1e-9))
|
| 796 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6)
|
| 797 |
+
bc = -dist.log_prob(acts).mean()
|
| 798 |
+
return q_loss + config["alpha"] * bc, {"q_loss": q_loss,
|
| 799 |
+
"bc_loss": bc,
|
| 800 |
+
"q_mean": q.mean()}
|
| 801 |
+
(_, info), grads = jax.value_and_grad(loss_fn, has_aux=True)(params)
|
| 802 |
+
updates, opt_state = d2tx.update(grads, opt_state, params)
|
| 803 |
+
return optax.apply_updates(params, updates), opt_state, info
|
| 804 |
+
|
| 805 |
+
if rec_target > 0:
|
| 806 |
+
# RECURSIVE 2-model actor loss: Q = log max( gl(s,mu,g),
|
| 807 |
+
# max_m gl(s,mu,c_m) * v_m ) with v_m = gl(c_m_row, a_row, g) a host-side
|
| 808 |
+
# constant. The actor gets gradient toward REACHING useful midpoints even
|
| 809 |
+
# where gl(s,mu,g) ~ 0 — the sparse-far-goal regime.
|
| 810 |
+
@jax.jit
|
| 811 |
+
def ddpg2_update_rec(params, opt_state, ema, obs_b, ag, acts, key, mid_g, mid_v):
|
| 812 |
+
def loss_fn(pp):
|
| 813 |
+
dist = ddpg2_actor_def.apply({"params": pp}, obs_b, ag)
|
| 814 |
+
mu = jnp.clip(dist.mode(), -1, 1)
|
| 815 |
+
ks = jax.random.split(key, rec_target + 1)
|
| 816 |
+
dv_t = jnp.full((obs_b.shape[0],), gamma, jnp.float32)
|
| 817 |
+
dv_h = jnp.full((obs_b.shape[0],), hop_disc, jnp.float32)
|
| 818 |
+
best = gl_q_orders(ema, obs_b, mu, tgt_j(ag), ks[0], n_orders_grad,
|
| 819 |
+
dv_t)
|
| 820 |
+
for m2 in range(rec_target):
|
| 821 |
+
ph = gl_q_orders(ema, obs_b, mu, mid_g[:, m2], ks[m2 + 1],
|
| 822 |
+
n_orders_grad, dv_h)
|
| 823 |
+
best = jnp.maximum(best, ph * mid_v[:, m2])
|
| 824 |
+
q = jnp.log(jnp.maximum(best, 1e-9))
|
| 825 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6)
|
| 826 |
+
bc = -dist.log_prob(acts).mean()
|
| 827 |
+
return q_loss + config["alpha"] * bc, {"q_loss": q_loss, "bc_loss": bc,
|
| 828 |
+
"q_mean": q.mean()}
|
| 829 |
+
(_, info), grads = jax.value_and_grad(loss_fn, has_aux=True)(params)
|
| 830 |
+
updates, opt_state = d2tx.update(grads, opt_state, params)
|
| 831 |
+
return optax.apply_updates(params, updates), opt_state, info
|
| 832 |
+
|
| 833 |
+
if not bits:
|
| 834 |
+
# ---- cont-mode 2-model coupling (readout=elbo; asserted at entry).
|
| 835 |
+
# The actor differentiates the denoising loss AT the goal directly:
|
| 836 |
+
# L_den is monotone in the -log p(g|s,mu,g) bound, so no exp (and no
|
| 837 |
+
# temperature — elbo_c cancels exactly in the self-normalized form)
|
| 838 |
+
# sits in the plain gradient path. The (t, eps) draws come from the
|
| 839 |
+
# step key, independent of the action, so the estimator is smooth
|
| 840 |
+
# in mu. Same signatures as the bits versions — the loop is
|
| 841 |
+
# readout-agnostic. ----
|
| 842 |
+
@jax.jit
|
| 843 |
+
def ddpg2_update(params, opt_state, ema, obs_b, ag, acts, key):
|
| 844 |
+
def loss_fn(pp):
|
| 845 |
+
dist = ddpg2_actor_def.apply({"params": pp}, obs_b, ag)
|
| 846 |
+
mu = jnp.clip(dist.mode(), -1, 1)
|
| 847 |
+
gt = tgt_j(ag)
|
| 848 |
+
dv_t = jnp.full((obs_b.shape[0],), gamma, jnp.float32)
|
| 849 |
+
q = -elbo_c * elbo_loss(ema, _elbo_cond(obs_b, mu, gt, dv_t),
|
| 850 |
+
gt, key, elbo_K)
|
| 851 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6)
|
| 852 |
+
bc = -dist.log_prob(acts).mean()
|
| 853 |
+
return q_loss + config["alpha"] * bc, {"q_loss": q_loss,
|
| 854 |
+
"bc_loss": bc,
|
| 855 |
+
"q_mean": q.mean()}
|
| 856 |
+
(_, info), grads = jax.value_and_grad(loss_fn, has_aux=True)(params)
|
| 857 |
+
updates, opt_state = d2tx.update(grads, opt_state, params)
|
| 858 |
+
return optax.apply_updates(params, updates), opt_state, info
|
| 859 |
+
|
| 860 |
+
if rec_target > 0 and rec_prob:
|
| 861 |
+
# prob-form composed actor loss, ENTIRELY in log space:
|
| 862 |
+
# q = log[(1-p) e^{-c L_g} + p e^{-c L_c} / den * v_c]
|
| 863 |
+
# via logaddexp — no float32 exp underflow (exp(-c*L) dies below
|
| 864 |
+
# ~1e-38 for c*L > 87; the log-space form ranks correctly at any
|
| 865 |
+
# temperature). den and v_c are host-side constants in Q form.
|
| 866 |
+
@jax.jit
|
| 867 |
+
def ddpg2_update_prob(params, opt_state, ema, obs_b, ag, acts, key,
|
| 868 |
+
mid_g, mid_v, mid_den):
|
| 869 |
+
def loss_fn(pp):
|
| 870 |
+
dist = ddpg2_actor_def.apply({"params": pp}, obs_b, ag)
|
| 871 |
+
mu = jnp.clip(dist.mode(), -1, 1)
|
| 872 |
+
ks = jax.random.split(key, 2)
|
| 873 |
+
dv_h = jnp.full((obs_b.shape[0],), hop_disc, jnp.float32)
|
| 874 |
+
gt = tgt_j(ag)
|
| 875 |
+
lq_g = -elbo_c * elbo_loss(
|
| 876 |
+
ema, _elbo_cond(obs_b, mu, gt, dv_h), gt, ks[0], elbo_K)
|
| 877 |
+
lq_c = -elbo_c * elbo_loss(
|
| 878 |
+
ema, _elbo_cond(obs_b, mu, mid_g, dv_h), mid_g, ks[1],
|
| 879 |
+
elbo_K)
|
| 880 |
+
log_comp = (jnp.log(rec_p) + lq_c
|
| 881 |
+
- jnp.log(jnp.maximum(mid_den, 1e-9))
|
| 882 |
+
+ jnp.log(jnp.maximum(mid_v, 1e-9)))
|
| 883 |
+
q = jnp.logaddexp(jnp.log(1.0 - rec_p) + lq_g, log_comp)
|
| 884 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(
|
| 885 |
+
jnp.abs(q).mean() + 1e-6)
|
| 886 |
+
bc = -dist.log_prob(acts).mean()
|
| 887 |
+
return q_loss + config["alpha"] * bc, {"q_loss": q_loss,
|
| 888 |
+
"bc_loss": bc,
|
| 889 |
+
"q_mean": q.mean()}
|
| 890 |
+
(_, info), grads = jax.value_and_grad(loss_fn, has_aux=True)(params)
|
| 891 |
+
updates, opt_state = d2tx.update(grads, opt_state, params)
|
| 892 |
+
return optax.apply_updates(params, updates), opt_state, info
|
| 893 |
+
|
| 894 |
+
class _D2:
|
| 895 |
+
def __init__(self, params):
|
| 896 |
+
self.params = params
|
| 897 |
+
|
| 898 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 899 |
+
dist = ddpg2_actor_def.apply({"params": self.params}, observations, goals,
|
| 900 |
+
temperature=temperature)
|
| 901 |
+
return jnp.clip(dist.sample(seed=seed), -1, 1)
|
| 902 |
+
|
| 903 |
+
agent = d2holder["params"]
|
| 904 |
+
agent_actor_params = lambda: d2holder["params"]
|
| 905 |
+
eval_wrap = lambda pp: _D2(pp)
|
| 906 |
+
elif extraction == "gliql":
|
| 907 |
+
# gl-IQL extraction inside the joint loop (owner directive): V + policy only,
|
| 908 |
+
# Q = log gl from the EMA occupancy consumed directly — no distilled critic,
|
| 909 |
+
# no TD passenger. Joint stack = 3 networks (occupancy, V, actor).
|
| 910 |
+
value_def = GCValue(hidden_dims=tuple(config["value_hidden_dims"]),
|
| 911 |
+
layer_norm=config["layer_norm"], ensemble=False)
|
| 912 |
+
gliql_actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]),
|
| 913 |
+
action_dim=a_dim, state_dependent_std=False,
|
| 914 |
+
const_std=config["const_std"])
|
| 915 |
+
net_def = ModuleDict(dict(value=value_def, actor=gliql_actor_def))
|
| 916 |
+
gparams = net_def.init(jax.random.PRNGKey(seed + 1),
|
| 917 |
+
value=(ex["observations"], ex["observations"]),
|
| 918 |
+
actor=(ex["observations"], ex["observations"]))["params"]
|
| 919 |
+
gnet = TrainState.create(net_def, gparams, tx=optax.adam(learning_rate=config["lr"]))
|
| 920 |
+
gtau = expectile
|
| 921 |
+
|
| 922 |
+
@jax.jit
|
| 923 |
+
def gliql_update(net, obs_b, vg, ag, acts, q_v, q_a):
|
| 924 |
+
def loss_fn(p):
|
| 925 |
+
v = net.select("value")(obs_b, vg, params=p)
|
| 926 |
+
diff = q_v - v
|
| 927 |
+
vl = (jnp.abs(gtau - (diff < 0).astype(jnp.float32)) * diff ** 2).mean()
|
| 928 |
+
va = net.select("value")(obs_b, ag)
|
| 929 |
+
adv = q_a - va
|
| 930 |
+
adv = (adv - adv.mean()) / (adv.std() + 1e-6)
|
| 931 |
+
w = jnp.minimum(jnp.exp(gliql_alpha * adv), 100.0)
|
| 932 |
+
dist = net.select("actor")(obs_b, ag, params=p)
|
| 933 |
+
lp = dist.log_prob(acts)
|
| 934 |
+
al = -(w * lp).mean()
|
| 935 |
+
return vl + al, {"value_loss": vl, "actor_loss": al,
|
| 936 |
+
"bc_log_prob": lp.mean()}
|
| 937 |
+
return net.apply_loss_fn(loss_fn=loss_fn)
|
| 938 |
+
|
| 939 |
+
class _GA:
|
| 940 |
+
def __init__(self, net):
|
| 941 |
+
self.net = net
|
| 942 |
+
|
| 943 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 944 |
+
dist = self.net.select("actor")(observations, goals, temperature=temperature)
|
| 945 |
+
return jnp.clip(dist.sample(seed=seed), -1, 1)
|
| 946 |
+
|
| 947 |
+
agent = gnet
|
| 948 |
+
agent_actor_params = lambda: gnet.params["modules_actor"]
|
| 949 |
+
eval_wrap = lambda ts: _GA(ts)
|
| 950 |
+
else:
|
| 951 |
+
agent = GCIQLAblateAgent.create(seed, ex["observations"], ex["actions"], config)
|
| 952 |
+
agent_actor_params = lambda: agent.network.params["modules_actor"]
|
| 953 |
+
eval_wrap = None
|
| 954 |
+
if rec_target > 0:
|
| 955 |
+
_mdef_rec = agent.network.model_def
|
| 956 |
+
tgtq_fn = jax.jit(lambda prms, o_, g_, a_: jnp.minimum(
|
| 957 |
+
*_mdef_rec.apply({"params": prms}, o_, g_, a_, name="target_genq_critic")))
|
| 958 |
+
# Late-band stabilizer (2M-ladder lesson: the co-adapting critic keeps perturbing the
|
| 959 |
+
# actor, so late evals oscillate 0.4-0.77 and finals under-report peaks). Polyak EMA
|
| 960 |
+
# of the ACTOR params, evaluated alongside the live actor each periodic eval; the
|
| 961 |
+
# best-checkpoint protocol picks whichever wins. r3 extraction only.
|
| 962 |
+
ema_actor = None
|
| 963 |
+
if actor_ema_tau > 0:
|
| 964 |
+
assert extraction in ("r3", "ddpg2", "awr2"), \
|
| 965 |
+
"--actor_ema_tau supports r3, ddpg2, awr2"
|
| 966 |
+
if extraction in ("ddpg2", "awr2"):
|
| 967 |
+
# ddpg2's eval agent IS the actor params pytree (wrapped at eval time)
|
| 968 |
+
ema_actor = jax.tree_util.tree_map(lambda x: x, d2holder["params"])
|
| 969 |
+
with_actor = lambda ag, actor_params: actor_params
|
| 970 |
+
else:
|
| 971 |
+
ema_actor = jax.tree_util.tree_map(lambda x: x,
|
| 972 |
+
agent.network.params["modules_actor"])
|
| 973 |
+
|
| 974 |
+
def with_actor(ag, actor_params):
|
| 975 |
+
prms = dict(ag.network.params)
|
| 976 |
+
prms["modules_actor"] = actor_params
|
| 977 |
+
return ag.replace(network=ag.network.replace(params=prms))
|
| 978 |
+
gkey = [jax.random.PRNGKey(seed + 999)]
|
| 979 |
+
|
| 980 |
+
def genq_q_batch(obs_b, goal_obs, acts, _chunk=256):
|
| 981 |
+
s = np.asarray(obs_b, dtype=np.float32)
|
| 982 |
+
g = tgt(np.asarray(goal_obs))
|
| 983 |
+
a = np.clip(np.asarray(acts, dtype=np.float32), -1, 1)
|
| 984 |
+
outs = []
|
| 985 |
+
for i in range(0, len(s), _chunk):
|
| 986 |
+
gkey[0], sub = jax.random.split(gkey[0])
|
| 987 |
+
nn_ = len(s[i:i + _chunk])
|
| 988 |
+
outs.append(np.asarray(ro_q(occ_ema, jnp.asarray(s[i:i + _chunk]),
|
| 989 |
+
jnp.asarray(a[i:i + _chunk]),
|
| 990 |
+
jnp.asarray(g[i:i + _chunk]), sub,
|
| 991 |
+
jnp.full((nn_,), gamma, jnp.float32))))
|
| 992 |
+
return np.concatenate(outs)
|
| 993 |
+
|
| 994 |
+
# ---- beta-recursive rule (owner directive: don't FIX the recursion count).
|
| 995 |
+
# Depth is STOCHASTIC: at each level the chain continues w.p. p and terminates
|
| 996 |
+
# w.p. 1-p, with p set by beta through the geometric-splitting identity
|
| 997 |
+
# p = (gamma - beta) / (gamma * (1 - beta)),
|
| 998 |
+
# i.e. chaining geometric jumps with continuation p reproduces the
|
| 999 |
+
# gamma-geometric total (E[depth] = 1/(1-p)). Chains extend over GENERATED
|
| 1000 |
+
# states (completion head) with live-actor actions; each level contributes a
|
| 1001 |
+
# certificate acc * hit * value and the best certificate wins. acc < 1 decays
|
| 1002 |
+
# multiplicatively (gl < 1 pays the discount per hop), so deep chains die
|
| 1003 |
+
# economically; rec_max_depth is only a compute cap. ----
|
| 1004 |
+
rec_p = 0.0
|
| 1005 |
+
# chain hops query the beta-discount occupancy when the spectrum is on
|
| 1006 |
+
hop_disc = rec_beta if (spec_on and rec_beta > 0.0) else gamma
|
| 1007 |
+
if rec_target > 0 and rec_beta > 0.0:
|
| 1008 |
+
assert rec_free, "--rec_beta needs --rec_free (chains extend over generated states)"
|
| 1009 |
+
assert 0.0 < rec_beta < gamma, "need 0 < beta < gamma"
|
| 1010 |
+
rec_p = (gamma - rec_beta) / (gamma * (1.0 - rec_beta))
|
| 1011 |
+
print(f"[joint] REC beta-rule: beta={rec_beta} -> continue p={rec_p:.3f} "
|
| 1012 |
+
f"E[depth]={1.0 / (1.0 - rec_p):.1f} cap={rec_max_depth}", flush=True)
|
| 1013 |
+
|
| 1014 |
+
def _pad2(arr, n):
|
| 1015 |
+
# pad rows to the next power of two: the alive set shrinks every level,
|
| 1016 |
+
# and without bucketing every distinct size would retrace each jitted fn
|
| 1017 |
+
# (unbounded compile cache). <= log2(B) shapes per fn this way.
|
| 1018 |
+
P = 1
|
| 1019 |
+
while P < n:
|
| 1020 |
+
P *= 2
|
| 1021 |
+
if P == n:
|
| 1022 |
+
return arr, n
|
| 1023 |
+
pad = np.zeros((P - n,) + arr.shape[1:], arr.dtype)
|
| 1024 |
+
return np.concatenate([arr, pad], 0), n
|
| 1025 |
+
|
| 1026 |
+
def rec_chain_prob(s0, a0, g_bits, g_obs, actor_p):
|
| 1027 |
+
"""Splitting-identity estimator: simulate the beta-jump chain with
|
| 1028 |
+
continuation prob rec_p; return gl_beta(stop node -> g) under the live
|
| 1029 |
+
actor. An EXPECTATION over stochastic depth (two-sided noise, SGD
|
| 1030 |
+
averages) — the probabilistic alternative to max-certificates."""
|
| 1031 |
+
n0 = len(s0)
|
| 1032 |
+
s_cur, a_cur = np.array(s0, np.float32), np.array(a0, np.float32)
|
| 1033 |
+
alive = np.ones(n0, bool)
|
| 1034 |
+
for _lvl in range(rec_max_depth):
|
| 1035 |
+
cont = alive & (rng_np.random(n0) < rec_p)
|
| 1036 |
+
idx = np.nonzero(cont)[0]
|
| 1037 |
+
if len(idx) == 0:
|
| 1038 |
+
break
|
| 1039 |
+
n = len(idx)
|
| 1040 |
+
s_p, _ = _pad2(s_cur[idx], n)
|
| 1041 |
+
a_p, _ = _pad2(a_cur[idx], n)
|
| 1042 |
+
gb_p, _ = _pad2(g_bits[idx], n)
|
| 1043 |
+
go_p, _ = _pad2(g_obs[idx], n)
|
| 1044 |
+
gkey[0], subk = jax.random.split(gkey[0])
|
| 1045 |
+
dv_p = jnp.full((len(s_p),), hop_disc, jnp.float32)
|
| 1046 |
+
mids = np.asarray(occ_sample_bits(
|
| 1047 |
+
occ_ema, jnp.asarray(s_p), jnp.asarray(a_p),
|
| 1048 |
+
jnp.asarray(gb_p), subk, dv_p),
|
| 1049 |
+
np.float32)[:, 0, :] # width 1 per level
|
| 1050 |
+
c2_parts = [s_p, a_p, gb_p]
|
| 1051 |
+
if spec_on:
|
| 1052 |
+
c2_parts.append(np.full((len(s_p), 1), hop_disc, np.float32))
|
| 1053 |
+
cond2 = np.concatenate(c2_parts + [mids], 1)
|
| 1054 |
+
gkey[0], subk2 = jax.random.split(gkey[0])
|
| 1055 |
+
x_k = np.asarray(cmpl_sample(cmpl_ema, jnp.asarray(cond2), subk2),
|
| 1056 |
+
np.float32)
|
| 1057 |
+
a_k = np.asarray(actor_mode(actor_p, jnp.asarray(x_k),
|
| 1058 |
+
jnp.asarray(go_p)), np.float32)
|
| 1059 |
+
s_cur[idx] = x_k[:n]
|
| 1060 |
+
a_cur[idx] = a_k[:n]
|
| 1061 |
+
alive = cont
|
| 1062 |
+
# terminal: direct beta-gl from wherever the coin stopped the chain
|
| 1063 |
+
return gl_np(s_cur, a_cur, g_bits, _chunk=2048, disc=hop_disc)
|
| 1064 |
+
|
| 1065 |
+
def rec_chain(s0, a0, g_bits, g_obs, val_fn, actor_p, first_gated):
|
| 1066 |
+
"""Best stochastic-depth composed certificate from (s0,a0) toward g.
|
| 1067 |
+
|
| 1068 |
+
val_fn(x, a, g_obs, g_bits) -> [n] terminal value estimate at a node.
|
| 1069 |
+
first_gated=False makes level 1 unconditional (r3: level-1 composition
|
| 1070 |
+
is the depth-1 baseline); deeper levels always flip the beta coin.
|
| 1071 |
+
"""
|
| 1072 |
+
n0 = len(s0)
|
| 1073 |
+
best = np.zeros(n0, np.float32)
|
| 1074 |
+
acc = np.ones(n0, np.float32)
|
| 1075 |
+
s_cur, a_cur = np.array(s0, np.float32), np.array(a0, np.float32)
|
| 1076 |
+
alive = np.ones(n0, bool)
|
| 1077 |
+
M = rec_target
|
| 1078 |
+
for lvl in range(rec_max_depth):
|
| 1079 |
+
if lvl > 0 or first_gated:
|
| 1080 |
+
alive = alive & (rng_np.random(n0) < rec_p)
|
| 1081 |
+
alive = alive & (acc > 1e-3)
|
| 1082 |
+
idx = np.nonzero(alive)[0]
|
| 1083 |
+
n = len(idx)
|
| 1084 |
+
if n == 0:
|
| 1085 |
+
break
|
| 1086 |
+
s_p, _ = _pad2(s_cur[idx], n)
|
| 1087 |
+
a_p, _ = _pad2(a_cur[idx], n)
|
| 1088 |
+
gb_p, _ = _pad2(g_bits[idx], n)
|
| 1089 |
+
go_p, _ = _pad2(g_obs[idx], n)
|
| 1090 |
+
gkey[0], subk = jax.random.split(gkey[0])
|
| 1091 |
+
dv_p = jnp.full((len(s_p),), hop_disc, jnp.float32)
|
| 1092 |
+
mids = np.asarray(occ_sample_bits(
|
| 1093 |
+
occ_ema, jnp.asarray(s_p), jnp.asarray(a_p),
|
| 1094 |
+
jnp.asarray(gb_p), subk, dv_p), np.float32).reshape(-1, n_bits)
|
| 1095 |
+
sr_ = np.repeat(s_p, M, 0)
|
| 1096 |
+
ar_ = np.repeat(a_p, M, 0)
|
| 1097 |
+
gb_rep = np.repeat(gb_p, M, 0)
|
| 1098 |
+
go_rep = np.repeat(go_p, M, 0)
|
| 1099 |
+
hit = gl_np(sr_, ar_, mids, _chunk=2048, disc=hop_disc)
|
| 1100 |
+
c2_parts = [sr_, ar_, gb_rep]
|
| 1101 |
+
if spec_on:
|
| 1102 |
+
c2_parts.append(np.full((len(sr_), 1), hop_disc, np.float32))
|
| 1103 |
+
cond2 = np.concatenate(c2_parts + [mids], 1)
|
| 1104 |
+
v_m = None
|
| 1105 |
+
x_m = a_m = None
|
| 1106 |
+
for _k in range(rec_pess):
|
| 1107 |
+
gkey[0], subk2 = jax.random.split(gkey[0])
|
| 1108 |
+
x_k = np.asarray(cmpl_sample(cmpl_ema, jnp.asarray(cond2), subk2),
|
| 1109 |
+
np.float32)
|
| 1110 |
+
a_k = np.asarray(actor_mode(actor_p, jnp.asarray(x_k),
|
| 1111 |
+
jnp.asarray(go_rep)), np.float32)
|
| 1112 |
+
v_k = np.clip(val_fn(x_k, a_k, go_rep, gb_rep), 0.0, 1.0)
|
| 1113 |
+
if v_m is None:
|
| 1114 |
+
v_m, x_m, a_m = v_k, x_k, a_k # chain continues from draw 0
|
| 1115 |
+
else:
|
| 1116 |
+
v_m = np.minimum(v_m, v_k)
|
| 1117 |
+
nm = n * M
|
| 1118 |
+
cand = (hit[:nm] * v_m[:nm]).reshape(n, M)
|
| 1119 |
+
rows = np.arange(n)
|
| 1120 |
+
mstar = cand.argmax(1)
|
| 1121 |
+
best[idx] = np.maximum(best[idx], acc[idx] * cand[rows, mstar])
|
| 1122 |
+
sel = rows * M + mstar
|
| 1123 |
+
acc[idx] = acc[idx] * hit[sel]
|
| 1124 |
+
s_cur[idx] = x_m[sel]
|
| 1125 |
+
a_cur[idx] = a_m[sel]
|
| 1126 |
+
return best
|
| 1127 |
+
|
| 1128 |
+
vtag = f"_{variant_tag}" if variant_tag else ""
|
| 1129 |
+
run = wandb.init(project="gen-q-policy-improvement",
|
| 1130 |
+
name=f"genq_joint{vtag}-{env_id}-a{alpha}-s{seed}",
|
| 1131 |
+
mode=wandb_mode, tags=["genq_joint", env_id],
|
| 1132 |
+
config=dict(method="genq_joint", env=env_id, seed=seed, alpha=alpha,
|
| 1133 |
+
expectile=expectile, rt_eta=rt_eta, pi_alpha=pi_alpha,
|
| 1134 |
+
pi_horizon=pi_horizon, occ_warmup=occ_warmup,
|
| 1135 |
+
occ_tau=occ_tau, n_orders=n_orders,
|
| 1136 |
+
extraction=extraction, gliql_alpha=gliql_alpha,
|
| 1137 |
+
train_steps=train_steps),
|
| 1138 |
+
settings=wandb.Settings(start_method="thread"))
|
| 1139 |
+
print(f"[joint] WANDB_URL {run.get_url()}", flush=True)
|
| 1140 |
+
|
| 1141 |
+
eval_success = _make_eval_fn(env, config, evaluate, jax, wrap=eval_wrap)
|
| 1142 |
+
out = os.path.join(_result_dir(env_id, seed), f"genq_joint{vtag}.json")
|
| 1143 |
+
curve = []
|
| 1144 |
+
# Best-checkpoint protocol (joint1Mst lesson: the co-adaptation arms oscillate hard
|
| 1145 |
+
# late — 0.43-0.72 band — so a last-step 50-ep final under-reports the arm). JAX
|
| 1146 |
+
# pytrees are immutable, so snapshotting = keeping the reference at eval time.
|
| 1147 |
+
best = {"sr": -1.0, "agent": None}
|
| 1148 |
+
final_info = {}
|
| 1149 |
+
|
| 1150 |
+
def dump(sr, per):
|
| 1151 |
+
json.dump({"method": "genq_joint", "extraction": extraction,
|
| 1152 |
+
"env": env_id, "seed": seed, "alpha": alpha,
|
| 1153 |
+
"expectile": expectile, "rt_eta": rt_eta, "pi_alpha": pi_alpha,
|
| 1154 |
+
"pi_horizon": pi_horizon, "occ_warmup": occ_warmup,
|
| 1155 |
+
"rec_target": rec_target, "rec_every": rec_every, "rec_after": rec_after,
|
| 1156 |
+
"rec_free": rec_free, "rec_beta": rec_beta,
|
| 1157 |
+
"rec_max_depth": rec_max_depth, "rec_pess": rec_pess, "rec_prob": rec_prob,
|
| 1158 |
+
"rec_actor": rec_actor, "readout": readout, "n_occ_ro": n_occ_ro,
|
| 1159 |
+
**({"elbo_c": elbo_c, "elbo_K": elbo_K, "elbo_tlo": elbo_tlo,
|
| 1160 |
+
"elbo_thi": elbo_thi} if readout == "elbo" else {}),
|
| 1161 |
+
**({"target_mode": target_mode, "sigma": ro_sigma} if not bits else {}),
|
| 1162 |
+
"gamma_spectrum_lo": gamma_spectrum_lo,
|
| 1163 |
+
"gamma_spectrum_p": gamma_spectrum_p,
|
| 1164 |
+
"success_rate": sr, "best_sr": (max(v for _, v in curve) if curve else sr),
|
| 1165 |
+
**final_info,
|
| 1166 |
+
"per_task": per, "curve": curve, "train_steps": train_steps,
|
| 1167 |
+
"wall_clock_sec": round(time.time() - t0, 1),
|
| 1168 |
+
"wandb_url": run.get_url()}, open(out, "w"), indent=2)
|
| 1169 |
+
|
| 1170 |
+
for i in tqdm.trange(1, train_steps + 1, smoothing=0.1, dynamic_ncols=True):
|
| 1171 |
+
use_pi = i > occ_warmup
|
| 1172 |
+
for _ in range(occ_updates_per_step):
|
| 1173 |
+
c_raw, b01, t_int, m, w, j_idx = occ_tuple_batch(agent, use_pi)
|
| 1174 |
+
occ_params, occ_opt, occ_ema, occ_l = occ_update(occ_params, occ_opt, occ_ema,
|
| 1175 |
+
c_raw, b01, t_int, m, w)
|
| 1176 |
+
if rec_target > 0 and rec_free:
|
| 1177 |
+
# completion head trained on the SAME tuple: x0 = obs[j], bits at j
|
| 1178 |
+
# teacher-forced into the conditioning
|
| 1179 |
+
gkey[0], sub_c = jax.random.split(gkey[0])
|
| 1180 |
+
t2 = jnp.asarray(rng_np.integers(1, occ_T + 1, len(j_idx)).astype(np.int32))
|
| 1181 |
+
eps2 = jax.random.normal(sub_c, (len(j_idx), obs.shape[1]))
|
| 1182 |
+
cmpl_params, cmpl_opt, cmpl_ema, cmpl_l = cmpl_update(
|
| 1183 |
+
cmpl_params, cmpl_opt, cmpl_ema,
|
| 1184 |
+
jnp.concatenate([c_raw, b01], -1), jnp.asarray(obs[j_idx]),
|
| 1185 |
+
t2, eps2, w)
|
| 1186 |
+
batch = train_ds.sample(config["batch_size"])
|
| 1187 |
+
rec_now = rec_target > 0 and i > rec_after and i % rec_every == 0
|
| 1188 |
+
if extraction not in ("ddpg2", "awr2"):
|
| 1189 |
+
q_v = genq_q_batch(batch["observations"], batch["value_goals"], batch["actions"])
|
| 1190 |
+
q_a = genq_q_batch(batch["observations"], batch["actor_goals"], batch["actions"])
|
| 1191 |
+
|
| 1192 |
+
def compose_r3(goal_obs, q_base):
|
| 1193 |
+
# compose targets through live-occupancy jumps + EMA critic, at the
|
| 1194 |
+
# given goal stream. Value goals always; actor goals under
|
| 1195 |
+
# --rec_actor — the ddpgbc actor differentiates the distilled critic
|
| 1196 |
+
# at ACTOR goals, so composition must reach the head the policy
|
| 1197 |
+
# gradient reads (retrieval-form controlled cell: +0.13 final at
|
| 1198 |
+
# 500k over the value-goals-only twin).
|
| 1199 |
+
s_b = np.asarray(batch["observations"], np.float32)
|
| 1200 |
+
a_b = np.clip(np.asarray(batch["actions"], np.float32), -1, 1)
|
| 1201 |
+
go_np = np.asarray(goal_obs, np.float32)
|
| 1202 |
+
g_b = tgt(go_np)
|
| 1203 |
+
gkey[0], sub = jax.random.split(gkey[0])
|
| 1204 |
+
mids = occ_sample_bits(occ_ema, jnp.asarray(s_b), jnp.asarray(a_b),
|
| 1205 |
+
jnp.asarray(g_b), sub,
|
| 1206 |
+
jnp.full((len(s_b),), hop_disc, jnp.float32))
|
| 1207 |
+
Bm, M = len(s_b), rec_target
|
| 1208 |
+
if rec_free and rec_prob:
|
| 1209 |
+
# probabilistic beta-jump target (splitting identity): the chain
|
| 1210 |
+
# estimator IS the gamma-value estimate — expectation, no max
|
| 1211 |
+
comp = np.clip(rec_chain_prob(
|
| 1212 |
+
s_b, a_b, g_b, go_np, agent_actor_params()), 0.0, 1.0)
|
| 1213 |
+
elif rec_free and rec_beta > 0.0:
|
| 1214 |
+
# beta-rule: stochastic-depth chain (level 1 unconditional = the
|
| 1215 |
+
# depth-1 baseline; deeper levels flip the beta coin)
|
| 1216 |
+
def _val_r3(x_, a_, go_, gb_):
|
| 1217 |
+
return np.asarray(tgtq_fn(agent.network.params, jnp.asarray(x_),
|
| 1218 |
+
jnp.asarray(go_), jnp.asarray(a_)))
|
| 1219 |
+
comp = rec_chain(s_b, a_b, g_b, go_np,
|
| 1220 |
+
_val_r3, agent_actor_params(), first_gated=False)
|
| 1221 |
+
elif rec_free:
|
| 1222 |
+
# generate the midpoint state, act with the live actor there
|
| 1223 |
+
mids_f = np.asarray(mids, np.float32).reshape(-1, n_bits)
|
| 1224 |
+
hit = gl_np(np.repeat(s_b, M, 0), np.repeat(a_b, M, 0), mids_f,
|
| 1225 |
+
disc=hop_disc)
|
| 1226 |
+
c2_parts = [np.repeat(np.concatenate([s_b, a_b, g_b], 1), M, 0)]
|
| 1227 |
+
if spec_on:
|
| 1228 |
+
c2_parts.append(np.full((Bm * M, 1), hop_disc, np.float32))
|
| 1229 |
+
cond2 = np.concatenate(c2_parts + [mids_f], 1)
|
| 1230 |
+
gv_rep = jnp.asarray(np.repeat(go_np, M, 0))
|
| 1231 |
+
vq = None
|
| 1232 |
+
for _k in range(rec_pess):
|
| 1233 |
+
# PESSIMISM over completion draws: value hallucination at a
|
| 1234 |
+
# generated midpoint is one-sided (optimistic targets get
|
| 1235 |
+
# exploited by the actor); min over K independent
|
| 1236 |
+
# completions bounds it
|
| 1237 |
+
gkey[0], sub2 = jax.random.split(gkey[0])
|
| 1238 |
+
x_m = cmpl_sample(cmpl_ema, jnp.asarray(cond2), sub2)
|
| 1239 |
+
a_m = actor_mode(agent_actor_params(), x_m, gv_rep)
|
| 1240 |
+
v_k = np.asarray(tgtq_fn(agent.network.params, x_m, gv_rep,
|
| 1241 |
+
a_m))
|
| 1242 |
+
vq = v_k if vq is None else np.minimum(vq, v_k)
|
| 1243 |
+
comp = (hit * np.clip(vq, 0.0, 1.0)).reshape(Bm, M).max(1)
|
| 1244 |
+
else:
|
| 1245 |
+
rows_, valid = rec_retrieve(mids)
|
| 1246 |
+
hit = gl_np(np.repeat(s_b, M, 0), np.repeat(a_b, M, 0),
|
| 1247 |
+
target_full[rows_])
|
| 1248 |
+
vq = np.asarray(tgtq_fn(agent.network.params, jnp.asarray(obs[rows_]),
|
| 1249 |
+
jnp.asarray(np.repeat(go_np, M, 0)),
|
| 1250 |
+
jnp.asarray(act[rows_])))
|
| 1251 |
+
comp = (hit * np.clip(vq, 0.0, 1.0) * valid).reshape(Bm, M).max(1)
|
| 1252 |
+
if rec_free and rec_prob:
|
| 1253 |
+
return comp # pure expectation, no max
|
| 1254 |
+
return np.maximum(q_base, comp)
|
| 1255 |
+
|
| 1256 |
+
if rec_now and extraction == "r3":
|
| 1257 |
+
q_v = compose_r3(batch["value_goals"], q_v)
|
| 1258 |
+
if rec_actor:
|
| 1259 |
+
q_a = compose_r3(batch["actor_goals"], q_a)
|
| 1260 |
+
if extraction == "ddpg2":
|
| 1261 |
+
gkey[0], sub = jax.random.split(gkey[0])
|
| 1262 |
+
if rec_now:
|
| 1263 |
+
# midpoints for the composed actor loss (host: sample + value)
|
| 1264 |
+
s_b = np.asarray(batch["observations"], np.float32)
|
| 1265 |
+
a_b = np.clip(np.asarray(batch["actions"], np.float32), -1, 1)
|
| 1266 |
+
ag_b = np.asarray(batch["actor_goals"], np.float32)
|
| 1267 |
+
g_b = tgt(ag_b)
|
| 1268 |
+
gkey[0], sub2 = jax.random.split(gkey[0])
|
| 1269 |
+
mids = occ_sample_bits(occ_ema, jnp.asarray(s_b), jnp.asarray(a_b),
|
| 1270 |
+
jnp.asarray(g_b), sub2,
|
| 1271 |
+
jnp.full((len(s_b),), hop_disc, jnp.float32))
|
| 1272 |
+
Bm, M = len(s_b), rec_target
|
| 1273 |
+
if rec_free and rec_prob:
|
| 1274 |
+
# one midpoint per row; IS denominator = its likelihood under the
|
| 1275 |
+
# sampling conditioning; v = coin-terminated chain from x_c
|
| 1276 |
+
c1 = np.asarray(mids, np.float32)[:, 0, :]
|
| 1277 |
+
den = gl_np(s_b, a_b, c1, _chunk=2048, disc=hop_disc)
|
| 1278 |
+
c2_parts = [s_b, a_b, g_b]
|
| 1279 |
+
if spec_on:
|
| 1280 |
+
c2_parts.append(np.full((Bm, 1), hop_disc, np.float32))
|
| 1281 |
+
cond2 = np.concatenate(c2_parts + [c1], 1)
|
| 1282 |
+
gkey[0], sub4 = jax.random.split(gkey[0])
|
| 1283 |
+
x1 = np.asarray(cmpl_sample(cmpl_ema, jnp.asarray(cond2), sub4),
|
| 1284 |
+
np.float32)
|
| 1285 |
+
a1 = np.asarray(actor_mode(d2holder["params"], jnp.asarray(x1),
|
| 1286 |
+
jnp.asarray(ag_b)), np.float32)
|
| 1287 |
+
v1 = np.clip(rec_chain_prob(x1, a1, g_b, ag_b,
|
| 1288 |
+
d2holder["params"]), 0.0, 1.0)
|
| 1289 |
+
d2holder["params"], d2holder["opt"], info = ddpg2_update_prob(
|
| 1290 |
+
d2holder["params"], d2holder["opt"], occ_ema,
|
| 1291 |
+
jnp.asarray(s_b), jnp.asarray(ag_b), jnp.asarray(a_b), sub,
|
| 1292 |
+
jnp.asarray(c1), jnp.asarray(v1.astype(np.float32)),
|
| 1293 |
+
jnp.asarray(den.astype(np.float32)))
|
| 1294 |
+
elif rec_free:
|
| 1295 |
+
# generate the midpoint state; its value toward g under the LIVE actor
|
| 1296 |
+
mids_f = np.asarray(mids, np.float32).reshape(-1, n_bits)
|
| 1297 |
+
c2_parts = [np.repeat(np.concatenate([s_b, a_b, g_b], 1), M, 0)]
|
| 1298 |
+
if spec_on:
|
| 1299 |
+
c2_parts.append(np.full((Bm * M, 1), hop_disc, np.float32))
|
| 1300 |
+
cond2 = np.concatenate(c2_parts + [mids_f], 1)
|
| 1301 |
+
g_rep = np.repeat(g_b, M, 0)
|
| 1302 |
+
v1 = None
|
| 1303 |
+
x_m = a_m = None
|
| 1304 |
+
for _k in range(rec_pess):
|
| 1305 |
+
gkey[0], sub3 = jax.random.split(gkey[0])
|
| 1306 |
+
x_m = np.asarray(cmpl_sample(cmpl_ema, jnp.asarray(cond2),
|
| 1307 |
+
sub3), np.float32)
|
| 1308 |
+
a_m = np.asarray(actor_mode(d2holder["params"],
|
| 1309 |
+
jnp.asarray(x_m),
|
| 1310 |
+
jnp.asarray(np.repeat(ag_b, M, 0))),
|
| 1311 |
+
np.float32)
|
| 1312 |
+
v_k = gl_np(x_m, a_m, g_rep, _chunk=2048, disc=hop_disc)
|
| 1313 |
+
v1 = v_k if v1 is None else np.minimum(v1, v_k)
|
| 1314 |
+
if rec_beta > 0.0:
|
| 1315 |
+
# beta-rule: extend the value-from-midpoint by a stochastic-
|
| 1316 |
+
# depth chain (all levels coin-gated; v1 is the depth-1 base)
|
| 1317 |
+
def _val_d2(x_, a_, go_, gb_):
|
| 1318 |
+
return gl_np(x_, a_, gb_, _chunk=2048, disc=hop_disc)
|
| 1319 |
+
vchain = rec_chain(x_m, a_m, g_rep, np.repeat(ag_b, M, 0),
|
| 1320 |
+
_val_d2, d2holder["params"], first_gated=True)
|
| 1321 |
+
v1 = np.maximum(v1, vchain)
|
| 1322 |
+
mid_v = v1.reshape(Bm, M).astype(np.float32)
|
| 1323 |
+
mid_g = mids_f.reshape(Bm, M, n_bits)
|
| 1324 |
+
else:
|
| 1325 |
+
rows_, valid = rec_retrieve(mids)
|
| 1326 |
+
mid_v = (gl_np(obs[rows_], act[rows_], np.repeat(g_b, M, 0))
|
| 1327 |
+
* valid).reshape(Bm, M).astype(np.float32)
|
| 1328 |
+
mid_g = target_full[rows_].reshape(Bm, M, n_bits).astype(np.float32)
|
| 1329 |
+
if not (rec_free and rec_prob):
|
| 1330 |
+
# prob mode already ran its own update above
|
| 1331 |
+
d2holder["params"], d2holder["opt"], info = ddpg2_update_rec(
|
| 1332 |
+
d2holder["params"], d2holder["opt"], occ_ema,
|
| 1333 |
+
jnp.asarray(s_b), jnp.asarray(ag_b), jnp.asarray(a_b), sub,
|
| 1334 |
+
jnp.asarray(mid_g), jnp.asarray(mid_v))
|
| 1335 |
+
else:
|
| 1336 |
+
d2holder["params"], d2holder["opt"], info = ddpg2_update(
|
| 1337 |
+
d2holder["params"], d2holder["opt"], occ_ema,
|
| 1338 |
+
jnp.asarray(batch["observations"]), jnp.asarray(batch["actor_goals"]),
|
| 1339 |
+
jnp.asarray(np.clip(batch["actions"], -1, 1)), sub)
|
| 1340 |
+
agent = d2holder["params"]
|
| 1341 |
+
if ema_actor is not None:
|
| 1342 |
+
ema_actor = jax.tree_util.tree_map(
|
| 1343 |
+
lambda e, p: e * (1 - actor_ema_tau) + p * actor_ema_tau,
|
| 1344 |
+
ema_actor, d2holder["params"])
|
| 1345 |
+
elif extraction == "awr2":
|
| 1346 |
+
gkey[0], sub = jax.random.split(gkey[0])
|
| 1347 |
+
s_b = jnp.asarray(batch["observations"])
|
| 1348 |
+
ag_b = jnp.asarray(batch["actor_goals"])
|
| 1349 |
+
a_b = jnp.asarray(np.clip(batch["actions"], -1, 1))
|
| 1350 |
+
base = ema_actor if ema_actor is not None else d2holder["params"]
|
| 1351 |
+
adv = awr2_adv(occ_ema, base, s_b, ag_b, a_b, sub)
|
| 1352 |
+
d2holder["params"], d2holder["opt"], info = awr2_update(
|
| 1353 |
+
d2holder["params"], d2holder["opt"], s_b, ag_b, a_b, adv)
|
| 1354 |
+
agent = d2holder["params"]
|
| 1355 |
+
if ema_actor is not None:
|
| 1356 |
+
ema_actor = jax.tree_util.tree_map(
|
| 1357 |
+
lambda e, p: e * (1 - actor_ema_tau) + p * actor_ema_tau,
|
| 1358 |
+
ema_actor, d2holder["params"])
|
| 1359 |
+
elif extraction == "gliql":
|
| 1360 |
+
acts_c = jnp.asarray(np.clip(batch["actions"], -1, 1))
|
| 1361 |
+
gnet, info = gliql_update(gnet, jnp.asarray(batch["observations"]),
|
| 1362 |
+
jnp.asarray(batch["value_goals"]),
|
| 1363 |
+
jnp.asarray(batch["actor_goals"]), acts_c,
|
| 1364 |
+
jnp.asarray(np.log(np.maximum(q_v, 1e-9))),
|
| 1365 |
+
jnp.asarray(np.log(np.maximum(q_a, 1e-9))))
|
| 1366 |
+
agent = gnet
|
| 1367 |
+
else:
|
| 1368 |
+
batch["genq_q_value"] = q_v
|
| 1369 |
+
batch["genq_q_actor"] = q_a
|
| 1370 |
+
agent, info = agent.update(batch)
|
| 1371 |
+
if ema_actor is not None:
|
| 1372 |
+
ema_actor = jax.tree_util.tree_map(
|
| 1373 |
+
lambda e, p: e * (1 - actor_ema_tau) + p * actor_ema_tau,
|
| 1374 |
+
ema_actor, agent.network.params["modules_actor"])
|
| 1375 |
+
if i % 1000 == 0:
|
| 1376 |
+
wandb.log({**{f"train/{k}": float(v) for k, v in info.items()
|
| 1377 |
+
if np.ndim(np.asarray(v)) == 0},
|
| 1378 |
+
"occ/loss": float(occ_l), "occ/pi_on": float(use_pi)}, step=i)
|
| 1379 |
+
if eval_interval > 0 and i % eval_interval == 0:
|
| 1380 |
+
sr, per = eval_success(agent, eval_episodes_periodic)
|
| 1381 |
+
curve.append((i, sr))
|
| 1382 |
+
if sr >= best["sr"]:
|
| 1383 |
+
best["sr"], best["agent"] = sr, agent
|
| 1384 |
+
ema_msg = ""
|
| 1385 |
+
if ema_actor is not None:
|
| 1386 |
+
ema_agent = with_actor(agent, ema_actor)
|
| 1387 |
+
sr_e, per_e = eval_success(ema_agent, eval_episodes_periodic)
|
| 1388 |
+
if sr_e >= best["sr"]:
|
| 1389 |
+
best["sr"], best["agent"] = sr_e, ema_agent
|
| 1390 |
+
wandb.log({"eval/success_rate_ema": sr_e}, step=i)
|
| 1391 |
+
ema_msg = f" ema={sr_e:.3f}"
|
| 1392 |
+
wandb.log({"eval/success_rate": sr, "eval/peak": max(v for _, v in curve)}, step=i)
|
| 1393 |
+
print(f"[joint] step {i} sr={sr:.3f}{ema_msg} (peak {max(v for _, v in curve):.3f}) "
|
| 1394 |
+
f"occ_loss={float(occ_l):.4f} pi_on={use_pi}", flush=True)
|
| 1395 |
+
if not bits and extraction not in ("ddpg2", "awr2"):
|
| 1396 |
+
# cont-mode read-out calibration at the value-goal stream
|
| 1397 |
+
print(f"[joint] readout calib @ value_goals: mean={q_v.mean():.4f} "
|
| 1398 |
+
f"std={q_v.std():.4f} min={q_v.min():.4f} max={q_v.max():.4f}",
|
| 1399 |
+
flush=True)
|
| 1400 |
+
if not bits and readout == "elbo":
|
| 1401 |
+
# ELBO dynamic-range diagnostic (the discrete-ELBO plateau watch):
|
| 1402 |
+
# read-out at data-adjacent goals (g = own target, d=0 — absorbing
|
| 1403 |
+
# first-passage calibration says ~1) vs permuted random goals. A
|
| 1404 |
+
# collapsing self/rand gap = the flat-Q pathology; log it every eval.
|
| 1405 |
+
nD = 256
|
| 1406 |
+
iD = rng_np.integers(0, N, nD)
|
| 1407 |
+
sD, aD = jnp.asarray(obs[iD]), jnp.asarray(act[iD])
|
| 1408 |
+
gD_self = jnp.asarray(target_full[iD])
|
| 1409 |
+
gD_rand = jnp.asarray(target_full[rng_np.permutation(iD)])
|
| 1410 |
+
dvD = jnp.full((nD,), gamma, jnp.float32)
|
| 1411 |
+
gkey[0], skD = jax.random.split(gkey[0])
|
| 1412 |
+
q_self = np.asarray(ro_q(occ_ema, sD, aD, gD_self, skD, dvD))
|
| 1413 |
+
gkey[0], skD = jax.random.split(gkey[0])
|
| 1414 |
+
q_rand = np.asarray(ro_q(occ_ema, sD, aD, gD_rand, skD, dvD))
|
| 1415 |
+
wandb.log({"elbo/q_self": float(q_self.mean()),
|
| 1416 |
+
"elbo/q_rand": float(q_rand.mean()),
|
| 1417 |
+
"elbo/log_gap": float(np.log(np.maximum(q_self, 1e-12)).mean()
|
| 1418 |
+
- np.log(np.maximum(q_rand, 1e-12)).mean())},
|
| 1419 |
+
step=i)
|
| 1420 |
+
print(f"[joint] elbo calib: q_self={q_self.mean():.4f} "
|
| 1421 |
+
f"q_rand={q_rand.mean():.4f} (log-gap "
|
| 1422 |
+
f"{np.log(np.maximum(q_self, 1e-12)).mean() - np.log(np.maximum(q_rand, 1e-12)).mean():.3f})",
|
| 1423 |
+
flush=True)
|
| 1424 |
+
dump(sr, per)
|
| 1425 |
+
|
| 1426 |
+
sr_last, per = eval_success(agent, eval_episodes)
|
| 1427 |
+
curve.append((train_steps, sr_last))
|
| 1428 |
+
sr, best_agent = sr_last, agent
|
| 1429 |
+
final_info["final_last_step"] = sr_last
|
| 1430 |
+
if best["agent"] is not None:
|
| 1431 |
+
sr_b, per_b = eval_success(best["agent"], eval_episodes)
|
| 1432 |
+
final_info["final_best_ckpt"] = sr_b
|
| 1433 |
+
final_info["best_ckpt_periodic_sr"] = best["sr"]
|
| 1434 |
+
print(f"[joint] best-ckpt (periodic {best['sr']:.3f}) 50-ep FINAL sr={sr_b:.3f} "
|
| 1435 |
+
f"vs last-step {sr_last:.3f}", flush=True)
|
| 1436 |
+
if sr_b > sr:
|
| 1437 |
+
sr, per, best_agent = sr_b, per_b, best["agent"]
|
| 1438 |
+
dump(sr, per)
|
| 1439 |
+
if save_agent:
|
| 1440 |
+
import pickle
|
| 1441 |
+
if extraction in ("ddpg2", "awr2"):
|
| 1442 |
+
pms = {"modules_actor": best_agent}
|
| 1443 |
+
else:
|
| 1444 |
+
pms = best_agent.params if extraction == "gliql" else best_agent.network.params
|
| 1445 |
+
with open(save_agent, "wb") as f:
|
| 1446 |
+
pickle.dump({"params": jax.device_get(pms), "config": dict(config)}, f)
|
| 1447 |
+
if save_occ:
|
| 1448 |
+
# co-trained occupancy EMA in the same torch-key npz layout as the warm
|
| 1449 |
+
# start, so eval_plan.py / warm-start loaders read it unchanged
|
| 1450 |
+
pe = jax.device_get(occ_ema)["params"]
|
| 1451 |
+
pairs = ([("time_emb_1", "time_emb.1"), ("time_emb_3", "time_emb.3"),
|
| 1452 |
+
("cond_emb_0", "cond_emb.0"), ("x_emb", "x_emb"), ("out", "out")] +
|
| 1453 |
+
[(f"trunk_{li}", f"trunk.{2 * li}") for li in range(occ_layers)])
|
| 1454 |
+
occ_out = {}
|
| 1455 |
+
for name, k2 in pairs:
|
| 1456 |
+
occ_out[f"{k2}.weight"] = np.asarray(pe[name]["kernel"]).T
|
| 1457 |
+
occ_out[f"{k2}.bias"] = np.asarray(pe[name]["bias"])
|
| 1458 |
+
occ_out["cond_mean"] = np.asarray(cond_mean)
|
| 1459 |
+
occ_out["cond_std"] = np.asarray(cond_std)
|
| 1460 |
+
if not bits:
|
| 1461 |
+
occ_out["y_mean"] = np.asarray(y_mean_j)
|
| 1462 |
+
occ_out["y_std"] = np.asarray(y_std_j)
|
| 1463 |
+
np.savez(save_occ, **occ_out)
|
| 1464 |
+
print(f"[joint] occupancy EMA saved -> {save_occ}", flush=True)
|
| 1465 |
+
print(f"[joint] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}",
|
| 1466 |
+
flush=True)
|
| 1467 |
+
wandb.finish()
|
| 1468 |
+
return out
|
gen_q_rsm/ogbench_genq/unused/genq_joint_fast.py
ADDED
|
@@ -0,0 +1,1010 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FUSED joint Gen-Q (issue #57, owner: 'why so slow? scale it up'): same math as
|
| 2 |
+
genq_joint.py for the PLAIN r3 / ddpg2 recipes, but the entire training step lives on
|
| 3 |
+
device and lax.scan amortizes dispatch.
|
| 4 |
+
|
| 5 |
+
Why the original is slow: the nets are tiny (~0.3-2M params; the H100 is >95% idle) —
|
| 6 |
+
wall clock is host-side numpy tuple assembly, 8 chunked gl calls with device->host
|
| 7 |
+
syncs, and 3 separate jit dispatches per step. This is latency-bound, and steps are
|
| 8 |
+
sequential (step t+1 needs step t's params), so multi-GPU data parallelism cannot help
|
| 9 |
+
the UNFUSED loop. The fix is fusion first, then more GPUs:
|
| 10 |
+
|
| 11 |
+
* dataset arrays live in HBM (~300 MB); all index sampling (GCDataset ref goal mix,
|
| 12 |
+
absorbing first-passage, rt-stratified hits with exact truncated-Geom IS weights,
|
| 13 |
+
live-actor agreement weights) is jnp on device;
|
| 14 |
+
* one fused step = occ update + gl targets (2048 rows, ONE call) + agent update;
|
| 15 |
+
* lax.scan over steps_per_dispatch steps -> one dispatch per window.
|
| 16 |
+
|
| 17 |
+
Once fused, each gradient step IS embarrassingly data-parallel (occupancy MLE +
|
| 18 |
+
simulation-based chain targets; no TD bootstrap, no replay sequencing) — the method
|
| 19 |
+
scales like supervised generative-model training. `data_parallel=True` pmaps the whole
|
| 20 |
+
per-dispatch scan over jax.local_device_count() devices (axis_name="dp"): every device
|
| 21 |
+
holds a full replica of params/opt-states/EMA, draws its OWN batch shard (occ_batch/D
|
| 22 |
+
and batch/D rows from a fold_in-per-device RNG stream, so global batch semantics are
|
| 23 |
+
preserved), and gradients are lax.pmean'd across devices BEFORE each optimizer update,
|
| 24 |
+
keeping params bit-identical on all devices. Eval/checkpoints read device 0. With the
|
| 25 |
+
flag off (or one device) the code path is unchanged.
|
| 26 |
+
|
| 27 |
+
Not supported here (use genq_joint.py): rec_target (host eps-grid retrieval), gliql.
|
| 28 |
+
"""
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
import time
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
|
| 35 |
+
from ogbench_genq._runner import (OGBENCH_IMPLS, PKG_DIR, _make_eval_fn, _result_dir,
|
| 36 |
+
_setup_paths)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run_genq_joint_fast(env_id, seed=0, train_steps=1000000, eval_episodes=50,
|
| 40 |
+
eval_interval=25000, eval_episodes_periodic=15, alpha=1.0,
|
| 41 |
+
expectile=0.9, gamma=0.99, occ_lr=3e-4, occ_batch=256,
|
| 42 |
+
occ_hidden=256, occ_layers=3, occ_time_dim=64, occ_T=100,
|
| 43 |
+
occ_tau=0.005, occ_warmup=50000, rt_eta=0.5, pi_alpha=1.0,
|
| 44 |
+
pi_horizon=25, n_orders=16, extraction="r3",
|
| 45 |
+
occ_warmstart_npz=None, variant_tag=None, save_agent=None,
|
| 46 |
+
save_occ=None, save_best=None, n_orders_pi=0,
|
| 47 |
+
actor_ema_tau=0.0, steps_per_dispatch=100,
|
| 48 |
+
rec_target=0, rec_every=1, rec_after=100000, rec_beta=0.0,
|
| 49 |
+
rec_max_depth=10, rec_prob=False,
|
| 50 |
+
gamma_spectrum_lo=0.0, gamma_spectrum_p=0.5,
|
| 51 |
+
gamma_encoding="scalar", gamma_fourier_k=4,
|
| 52 |
+
readout="gl", ker_K=16, ker_sharp=8.0, ker_eps=0.5,
|
| 53 |
+
elbo_c=1.0, elbo_pess=0.0, alpha_ramp=0, batch_size=0,
|
| 54 |
+
data_parallel=False, wandb_mode="online",
|
| 55 |
+
ogbench_impls=OGBENCH_IMPLS):
|
| 56 |
+
_setup_paths(ogbench_impls)
|
| 57 |
+
import jax
|
| 58 |
+
import jax.numpy as jnp
|
| 59 |
+
import optax
|
| 60 |
+
import tqdm
|
| 61 |
+
import wandb
|
| 62 |
+
from utils.env_utils import make_env_and_datasets
|
| 63 |
+
from utils.evaluation import evaluate
|
| 64 |
+
from utils.networks import GCActor
|
| 65 |
+
from target_extractors import env_safe_name, _PUZZLE_PRESSED_IDX
|
| 66 |
+
import target_extractors
|
| 67 |
+
from train_genq_jax import build_ends, cosine_abar, make_model
|
| 68 |
+
from gciql_ablate import GCIQLAblateAgent, get_config
|
| 69 |
+
|
| 70 |
+
# gl (exact likelihood) needs a finite goal alphabet — puzzle bits only.
|
| 71 |
+
# The sample readout is goal-space-agnostic: any env with an extractor.
|
| 72 |
+
is_bits = env_id.startswith("puzzle")
|
| 73 |
+
assert is_bits or readout != "gl", \
|
| 74 |
+
"non-puzzle envs need --readout sample or elbo (no exact likelihood " \
|
| 75 |
+
"in continuous goal spaces)"
|
| 76 |
+
assert extraction in ("r3", "ddpg2")
|
| 77 |
+
assert eval_interval % steps_per_dispatch == 0
|
| 78 |
+
t0 = time.time()
|
| 79 |
+
safe = env_safe_name(env_id)
|
| 80 |
+
config = get_config()
|
| 81 |
+
config["actor_loss"] = "ddpgbc"
|
| 82 |
+
config["alpha"] = alpha
|
| 83 |
+
config["expectile"] = expectile
|
| 84 |
+
config["genq_actor"] = True
|
| 85 |
+
config["genq_value"] = True
|
| 86 |
+
if batch_size:
|
| 87 |
+
# large-batch mode: targets here are simulation-based (occupancy MLE +
|
| 88 |
+
# chain estimates), not TD backups — batch scales averaging directly,
|
| 89 |
+
# with no value-propagation bottleneck to wait on
|
| 90 |
+
config["batch_size"] = int(batch_size)
|
| 91 |
+
|
| 92 |
+
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
|
| 93 |
+
obs_np = np.asarray(train_dataset["observations"], dtype=np.float32)
|
| 94 |
+
act_np = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1.0, 1.0)
|
| 95 |
+
end_np = build_ends(train_dataset["terminals"])
|
| 96 |
+
N = len(obs_np)
|
| 97 |
+
# next observation with within-trajectory clamp (OGBench datasets don't ship it)
|
| 98 |
+
nobs_np = obs_np[np.minimum(np.arange(N) + 1, end_np - 1)]
|
| 99 |
+
a_dim = act_np.shape[1]
|
| 100 |
+
tgt = lambda o: target_extractors.extract_target(env_id, o).astype(np.float32)
|
| 101 |
+
tgt_np = tgt(obs_np)
|
| 102 |
+
n_bits = tgt_np.shape[1]
|
| 103 |
+
# target-space stats: the continuous (rbf) sample readout standardizes z
|
| 104 |
+
# for diffusion and evaluates the kernel back in RAW target units, where
|
| 105 |
+
# ker_eps is the env's success radius. Puzzle bits keep the ±1 scale.
|
| 106 |
+
tgt_mu_np = tgt_np.mean(0)
|
| 107 |
+
tgt_sd_np = tgt_np.std(0) + 1e-6
|
| 108 |
+
# FUSED RECURSION PORT: 'prob' = probabilistic beta-jump estimator (splitting
|
| 109 |
+
# identity, expectation form); 'cert1' = depth-1 M-midpoint certificate (max).
|
| 110 |
+
# Multi-level certificate chains stay on the host path.
|
| 111 |
+
spec_on = gamma_spectrum_lo > 0.0
|
| 112 |
+
if rec_target > 0 and rec_beta > 0.0:
|
| 113 |
+
assert rec_prob, "fast path supports beta chains in prob form only"
|
| 114 |
+
rec_mode = "prob"
|
| 115 |
+
elif rec_target > 0:
|
| 116 |
+
rec_mode = "cert1"
|
| 117 |
+
else:
|
| 118 |
+
rec_mode = "off"
|
| 119 |
+
rec_p = ((gamma - rec_beta) / (gamma * (1.0 - rec_beta))
|
| 120 |
+
if rec_beta > 0.0 else 0.0)
|
| 121 |
+
hop_disc = rec_beta if (spec_on and rec_beta > 0.0) else gamma
|
| 122 |
+
# fourier gamma-encoding uses KF sin/cos pairs of normalized log-horizon;
|
| 123 |
+
# scalar and onehot2 use one column
|
| 124 |
+
KF = int(gamma_fourier_k)
|
| 125 |
+
g_cols = (2 * KF if gamma_encoding == "fourier" else 1) if spec_on else 0
|
| 126 |
+
cond_dim = obs_np.shape[1] + a_dim + n_bits + g_cols
|
| 127 |
+
B_pi = int(config["batch_size"])
|
| 128 |
+
|
| 129 |
+
# ---- multi-GPU data parallelism (pmap over the whole per-dispatch scan) ----
|
| 130 |
+
# Each device runs the SAME fused step on its own batch shard (occ_batch/D and
|
| 131 |
+
# B_pi/D rows, distinct RNG streams) and gradients are pmean'd across devices
|
| 132 |
+
# BEFORE every optimizer update, so params/EMA/targets stay bit-identical across
|
| 133 |
+
# devices and global-batch semantics match the single-device run. All samplers
|
| 134 |
+
# below close over the (now per-device) occ_batch / B_pi, so shapes shard for free.
|
| 135 |
+
n_dev = jax.local_device_count()
|
| 136 |
+
dp = bool(data_parallel) and n_dev > 1
|
| 137 |
+
if dp:
|
| 138 |
+
assert occ_batch % n_dev == 0 and B_pi % n_dev == 0, (
|
| 139 |
+
f"occ_batch={occ_batch} and batch_size={B_pi} must be divisible by the "
|
| 140 |
+
f"device count {n_dev}")
|
| 141 |
+
occ_batch //= n_dev
|
| 142 |
+
B_pi //= n_dev
|
| 143 |
+
psync = lambda tree: jax.lax.pmean(tree, axis_name="dp")
|
| 144 |
+
print(f"[fast] DATA-PARALLEL over {n_dev} devices: per-device occ_batch="
|
| 145 |
+
f"{occ_batch} pi_batch={B_pi} (global batch preserved, grads pmean'd)",
|
| 146 |
+
flush=True)
|
| 147 |
+
else:
|
| 148 |
+
psync = lambda tree: tree
|
| 149 |
+
|
| 150 |
+
# device-resident dataset (~300 MB on an 80 GB H100)
|
| 151 |
+
obs_d = jnp.asarray(obs_np)
|
| 152 |
+
nobs_d = jnp.asarray(nobs_np)
|
| 153 |
+
act_d = jnp.asarray(act_np)
|
| 154 |
+
tgt_d = jnp.asarray(tgt_np)
|
| 155 |
+
end_d = jnp.asarray(end_np.astype(np.int32))
|
| 156 |
+
|
| 157 |
+
# ---- occupancy model + warm start (identical to genq_joint) ----
|
| 158 |
+
# readout="gl": masked DISCRETE diffusion over bits, Q = exact any-order
|
| 159 |
+
# autoregressive likelihood (puzzle-only: needs a finite goal alphabet).
|
| 160 |
+
# readout="sample": CONTINUOUS eps-prediction diffusion over the same
|
| 161 |
+
# reward-relevant coordinates z, Q = kernel Monte-Carlo over K DDIM
|
| 162 |
+
# samples. DDIM is deterministic given noise, so samples are
|
| 163 |
+
# REPARAMETERIZABLE and actor gradients flow pathwise — no likelihood
|
| 164 |
+
# anywhere. This is the goal-space-agnostic form: discrete envs use a
|
| 165 |
+
# per-bit sigmoid-match kernel, continuous envs an RBF at the success
|
| 166 |
+
# radius, image envs the reward-predictive latent (CLAUDE.md).
|
| 167 |
+
# readout="elbo": evaluate the continuous occupancy's denoising loss AT
|
| 168 |
+
# the goal point (stratified t, K eps draws) and read Q as
|
| 169 |
+
# exp(-elbo_c * loss) — the diffusion-classifier ELBO surrogate for
|
| 170 |
+
# log-likelihood. Point evaluation like gl (zero hit-variance), works
|
| 171 |
+
# in any goal space like sample, and cheaper than both (one apply per
|
| 172 |
+
# draw). Recursion ratios cancel the unknown normalizer exactly.
|
| 173 |
+
assert readout in ("gl", "sample", "elbo")
|
| 174 |
+
if readout != "gl":
|
| 175 |
+
assert not occ_warmstart_npz, \
|
| 176 |
+
"sample/elbo readouts use a continuous occupancy (different " \
|
| 177 |
+
"x_emb width); no gl-era warm starts"
|
| 178 |
+
occ_x_dim = 2 * n_bits if readout == "gl" else n_bits
|
| 179 |
+
occ_model = make_model(cond_dim, n_bits, occ_hidden, occ_layers, occ_time_dim)
|
| 180 |
+
key = jax.random.PRNGKey(seed)
|
| 181 |
+
key, ik = jax.random.split(key)
|
| 182 |
+
occ_params = occ_model.init(ik, jnp.zeros((1, occ_x_dim)), jnp.zeros((1,)),
|
| 183 |
+
jnp.zeros((1, cond_dim)))
|
| 184 |
+
if occ_warmstart_npz:
|
| 185 |
+
d = np.load(occ_warmstart_npz)
|
| 186 |
+
pt = occ_params["params"]
|
| 187 |
+
|
| 188 |
+
def _ld(name, k2):
|
| 189 |
+
kern = d[f"{k2}.weight"].T
|
| 190 |
+
want = pt[name]["kernel"].shape
|
| 191 |
+
if kern.shape != want and name == "cond_emb_0":
|
| 192 |
+
kern = np.concatenate(
|
| 193 |
+
[kern, np.zeros((want[0] - kern.shape[0], kern.shape[1]),
|
| 194 |
+
kern.dtype)], 0)
|
| 195 |
+
pt[name]["kernel"] = jnp.asarray(kern)
|
| 196 |
+
pt[name]["bias"] = jnp.asarray(d[f"{k2}.bias"])
|
| 197 |
+
|
| 198 |
+
_ld("time_emb_1", "time_emb.1"); _ld("time_emb_3", "time_emb.3")
|
| 199 |
+
_ld("cond_emb_0", "cond_emb.0"); _ld("x_emb", "x_emb"); _ld("out", "out")
|
| 200 |
+
for li in range(occ_layers):
|
| 201 |
+
_ld(f"trunk_{li}", f"trunk.{2 * li}")
|
| 202 |
+
occ_params = {"params": pt}
|
| 203 |
+
print(f"[fast] occupancy warm-started from {os.path.basename(occ_warmstart_npz)}",
|
| 204 |
+
flush=True)
|
| 205 |
+
occ_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(occ_lr))
|
| 206 |
+
occ_opt = occ_tx.init(occ_params)
|
| 207 |
+
occ_ema = jax.tree_util.tree_map(lambda x: x, occ_params)
|
| 208 |
+
abar = cosine_abar(occ_T)
|
| 209 |
+
abar_j = jnp.asarray(abar)
|
| 210 |
+
kappas = np.arange(n_bits, dtype=np.float64) / n_bits
|
| 211 |
+
ts_frac = jnp.asarray(np.array(
|
| 212 |
+
[(1 + int(np.argmin(np.abs(abar - k)))) / occ_T for k in kappas], dtype=np.float32))
|
| 213 |
+
logg = float(np.log(gamma))
|
| 214 |
+
|
| 215 |
+
rng_np = np.random.default_rng(seed)
|
| 216 |
+
t_p = rng_np.integers(0, N, 20000)
|
| 217 |
+
gi_p = np.minimum(t_p + rng_np.geometric(1 - gamma, 20000), end_np[t_p] - 1)
|
| 218 |
+
# ---- discount conditioning encoding ----
|
| 219 |
+
# "scalar": raw gamma value, one z-scored column (original). Weakness: the
|
| 220 |
+
# occupancy's gamma-dependence runs through the horizon 1/(1-gamma), which
|
| 221 |
+
# triples across [0.95, 0.99] while raw gamma moves 0.04 — one linear feature
|
| 222 |
+
# + MLP spectral bias under-resolves it and the model drifts to the gamma-
|
| 223 |
+
# MARGINAL occupancy (the measured dilution).
|
| 224 |
+
# "onehot2": we only ever query TWO discounts (task gamma for reads, beta for
|
| 225 |
+
# hops), so condition on a discrete which-measure indicator instead of asking
|
| 226 |
+
# the net to interpolate a continuum: tuples train at beta w.p.
|
| 227 |
+
# gamma_spectrum_p else task gamma; column = 1 iff the beta measure.
|
| 228 |
+
# "fourier": KF sin/cos pairs of the NORMALIZED LOG-HORIZON u(gamma) =
|
| 229 |
+
# (log 1/(1-gamma) - lo_h)/(hi_h - lo_h) in [0,1] — the geometry-correct
|
| 230 |
+
# coordinate (horizon triples across [0.95,0.99] while raw gamma moves 0.04)
|
| 231 |
+
# with the same high-frequency sensitivity trick the diffusion timestep gets.
|
| 232 |
+
_lo_h = float(np.log(1.0 / (1.0 - gamma_spectrum_lo))) if spec_on else 0.0
|
| 233 |
+
_hi_h = float(np.log(1.0 / (1.0 - gamma)))
|
| 234 |
+
_fr_np = (np.pi * (2.0 ** np.arange(KF))).astype(np.float32)
|
| 235 |
+
if gamma_encoding == "onehot2":
|
| 236 |
+
assert rec_beta > 0.0, "onehot2 conditions on {beta, gamma}; needs --rec_beta"
|
| 237 |
+
g_enc = lambda dv: (dv < gamma - 1e-6).astype(jnp.float32)[:, None]
|
| 238 |
+
g_enc_np = lambda dv: (dv < gamma - 1e-6).astype(np.float32)[:, None]
|
| 239 |
+
elif gamma_encoding == "fourier":
|
| 240 |
+
_fr_j = jnp.asarray(_fr_np)
|
| 241 |
+
|
| 242 |
+
def g_enc(dv):
|
| 243 |
+
u = (jnp.log(1.0 / (1.0 - dv)) - _lo_h) / max(_hi_h - _lo_h, 1e-8)
|
| 244 |
+
ang = u[:, None] * _fr_j[None, :]
|
| 245 |
+
return jnp.concatenate([jnp.sin(ang), jnp.cos(ang)], -1)
|
| 246 |
+
|
| 247 |
+
def g_enc_np(dv):
|
| 248 |
+
u = (np.log(1.0 / (1.0 - dv)) - _lo_h) / max(_hi_h - _lo_h, 1e-8)
|
| 249 |
+
ang = u[:, None] * _fr_np[None, :]
|
| 250 |
+
return np.concatenate([np.sin(ang), np.cos(ang)], -1).astype(np.float32)
|
| 251 |
+
else:
|
| 252 |
+
g_enc = lambda dv: dv[:, None].astype(jnp.float32)
|
| 253 |
+
g_enc_np = lambda dv: dv[:, None].astype(np.float32)
|
| 254 |
+
|
| 255 |
+
def _np_gammas(n):
|
| 256 |
+
if gamma_encoding == "onehot2":
|
| 257 |
+
return np.where(rng_np.random(n) >= gamma_spectrum_p, gamma, rec_beta)
|
| 258 |
+
h = np.exp(rng_np.uniform(np.log(1.0 / (1.0 - gamma_spectrum_lo)),
|
| 259 |
+
np.log(1.0 / (1.0 - gamma)), n))
|
| 260 |
+
gam = 1.0 - 1.0 / h
|
| 261 |
+
return np.where(rng_np.random(n) >= gamma_spectrum_p, gamma, gam)
|
| 262 |
+
|
| 263 |
+
gpart = ([g_enc_np(_np_gammas(20000))] if spec_on else [])
|
| 264 |
+
cond_p = np.concatenate([obs_np[t_p], act_np[t_p], tgt_np[gi_p]] + gpart, axis=1)
|
| 265 |
+
if occ_warmstart_npz:
|
| 266 |
+
d0 = np.load(occ_warmstart_npz)
|
| 267 |
+
cm, cs = np.asarray(d0["cond_mean"]), np.asarray(d0["cond_std"])
|
| 268 |
+
if spec_on and len(cm) < cond_dim:
|
| 269 |
+
# append stats for however many gamma-encoding columns were added
|
| 270 |
+
cm = np.concatenate([cm, cond_p[:, len(cm):].mean(0)])
|
| 271 |
+
cs = np.concatenate([cs, cond_p[:, len(cs):].std(0) + 1e-6])
|
| 272 |
+
cond_mean, cond_std = jnp.asarray(cm), jnp.asarray(cs)
|
| 273 |
+
else:
|
| 274 |
+
cond_mean = jnp.asarray(cond_p.mean(0))
|
| 275 |
+
cond_std = jnp.asarray(cond_p.std(0) + 1e-6)
|
| 276 |
+
|
| 277 |
+
tgt_idx = jnp.asarray(_PUZZLE_PRESSED_IDX) if is_bits else None
|
| 278 |
+
tgt_mu_j = jnp.asarray(tgt_mu_np)
|
| 279 |
+
tgt_sd_j = jnp.asarray(tgt_sd_np)
|
| 280 |
+
actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]), action_dim=a_dim,
|
| 281 |
+
state_dependent_std=False, const_std=config["const_std"])
|
| 282 |
+
|
| 283 |
+
# ---- pure-jnp samplers (GCDataset ref semantics + absorbing/rt occupancy tuple) ----
|
| 284 |
+
def _geom(k, shape):
|
| 285 |
+
u = jax.random.uniform(k, shape, minval=1e-6, maxval=1.0 - 1e-6)
|
| 286 |
+
return (jnp.floor(jnp.log1p(-u) / logg)).astype(jnp.int32) + 1
|
| 287 |
+
|
| 288 |
+
lo_h = float(np.log(1.0 / (1.0 - gamma_spectrum_lo))) if spec_on else 0.0
|
| 289 |
+
hi_h = float(np.log(1.0 / (1.0 - gamma)))
|
| 290 |
+
|
| 291 |
+
def _gammas(k, shape):
|
| 292 |
+
if not spec_on:
|
| 293 |
+
return jnp.full(shape, gamma)
|
| 294 |
+
k1, k2 = jax.random.split(k)
|
| 295 |
+
if gamma_encoding == "onehot2":
|
| 296 |
+
return jnp.where(jax.random.uniform(k2, shape) >= gamma_spectrum_p,
|
| 297 |
+
gamma, rec_beta)
|
| 298 |
+
h = jnp.exp(jax.random.uniform(k1, shape, minval=lo_h, maxval=hi_h))
|
| 299 |
+
return jnp.where(jax.random.uniform(k2, shape) >= gamma_spectrum_p,
|
| 300 |
+
gamma, 1.0 - 1.0 / h)
|
| 301 |
+
|
| 302 |
+
def _ref_goals(k, t):
|
| 303 |
+
e1 = end_d[t] - 1
|
| 304 |
+
k1, k2, k3, k4 = jax.random.split(k, 4)
|
| 305 |
+
gi_traj = jnp.minimum(t + _geom(k1, t.shape), e1)
|
| 306 |
+
gi_rand = jax.random.randint(k2, t.shape, 0, N)
|
| 307 |
+
gi = jnp.where(jax.random.uniform(k3, t.shape) < 0.5 / 0.8, gi_traj, gi_rand)
|
| 308 |
+
return jnp.where(jax.random.uniform(k4, t.shape) < 0.2, t, gi)
|
| 309 |
+
|
| 310 |
+
def sample_pi_batch(k):
|
| 311 |
+
k0, kv, ka, kd = jax.random.split(k, 4)
|
| 312 |
+
t = jax.random.randint(k0, (B_pi,), 0, N)
|
| 313 |
+
gi_v = _ref_goals(kv, t)
|
| 314 |
+
e1 = (end_d[t] - 1).astype(jnp.float32)
|
| 315 |
+
lo = jnp.minimum(t + 1, end_d[t] - 1).astype(jnp.float32)
|
| 316 |
+
dfrac = jax.random.uniform(ka, (B_pi,))
|
| 317 |
+
gi_a = jnp.round(lo * dfrac + e1 * (1.0 - dfrac)).astype(jnp.int32)
|
| 318 |
+
success = (gi_v == t).astype(jnp.float32)
|
| 319 |
+
return t, gi_v, gi_a, success
|
| 320 |
+
|
| 321 |
+
def sample_occ_tuple(k, actor_params, pi_on):
|
| 322 |
+
ks = jax.random.split(k, 7)
|
| 323 |
+
t = jax.random.randint(ks[0], (occ_batch,), 0, N)
|
| 324 |
+
gi = _ref_goals(ks[1], t)
|
| 325 |
+
gam = _gammas(ks[6], t.shape)
|
| 326 |
+
lgam = jnp.log(gam)
|
| 327 |
+
in_traj = (gi >= t) & (gi < end_d[t])
|
| 328 |
+
L = (end_d[t] - t).astype(jnp.float32)
|
| 329 |
+
dd = jnp.clip((gi - t).astype(jnp.float32), 0.0, None)
|
| 330 |
+
gL = jnp.exp(L * lgam)
|
| 331 |
+
p_hit = jnp.where(in_traj, (jnp.exp(dd * lgam) - gL) / (1.0 - gL), 0.0)
|
| 332 |
+
take_hit = in_traj & ((jax.random.uniform(ks[2], t.shape) < rt_eta) | (gi == t))
|
| 333 |
+
u = jax.random.uniform(ks[3], t.shape, minval=1e-6, maxval=1.0 - 1e-6)
|
| 334 |
+
pd = 1.0 - jnp.exp(jnp.maximum(dd, 1.0) * lgam)
|
| 335 |
+
k_miss = jnp.ceil(jnp.log1p(-u * pd) / lgam).astype(jnp.int32) - 1
|
| 336 |
+
k_miss = jnp.clip(k_miss, 0, jnp.maximum(gi - t - 1, 0))
|
| 337 |
+
u2 = jax.random.uniform(ks[4], t.shape, minval=1e-6, maxval=1.0 - 1e-6)
|
| 338 |
+
Fmax = jnp.maximum(1.0 - gL, 1e-12)
|
| 339 |
+
k_pl = jnp.clip(jnp.ceil(jnp.log1p(-u2 * Fmax) / lgam).astype(jnp.int32) - 1,
|
| 340 |
+
0, (end_d[t] - t) - 1)
|
| 341 |
+
j = jnp.where(take_hit, gi, jnp.where(in_traj, t + k_miss, t + k_pl))
|
| 342 |
+
w = jnp.ones((occ_batch,))
|
| 343 |
+
w = jnp.where(take_hit & (gi != t), p_hit / rt_eta, w)
|
| 344 |
+
w = jnp.where(in_traj & ~take_hit, (1.0 - p_hit) / (1.0 - rt_eta), w)
|
| 345 |
+
# live-actor agreement over the future window (gated by pi_on);
|
| 346 |
+
# pi_alpha == 0 makes w_pi identically 1, so skip the actor forward entirely
|
| 347 |
+
if pi_alpha > 0:
|
| 348 |
+
offs = jnp.arange(1, pi_horizon + 1)
|
| 349 |
+
widx = jnp.minimum(t[:, None] + offs[None, :], j[:, None])
|
| 350 |
+
valid = ((t[:, None] + offs[None, :]) <= j[:, None]).astype(jnp.float32)
|
| 351 |
+
flat = widx.reshape(-1)
|
| 352 |
+
gobs = jnp.repeat(obs_d[gi], pi_horizon, axis=0)
|
| 353 |
+
mu = jnp.clip(actor_def.apply({"params": actor_params}, obs_d[flat], gobs).mode(),
|
| 354 |
+
-1, 1)
|
| 355 |
+
mse = ((act_d[flat] - mu) ** 2).sum(-1).reshape(occ_batch, pi_horizon)
|
| 356 |
+
m_mse = (mse * valid).sum(-1) / jnp.maximum(valid.sum(-1), 1.0)
|
| 357 |
+
w_pi = jnp.exp(-pi_alpha * m_mse / 2.0)
|
| 358 |
+
w_pi = w_pi / jnp.maximum(w_pi.mean(), 1e-8)
|
| 359 |
+
w = w * jnp.where(pi_on, w_pi, 1.0)
|
| 360 |
+
parts = [obs_d[t], act_d[t], tgt_d[gi]] + \
|
| 361 |
+
([g_enc(gam)] if spec_on else [])
|
| 362 |
+
c_raw = jnp.concatenate(parts, axis=1)
|
| 363 |
+
return c_raw, tgt_d[j], w, j
|
| 364 |
+
|
| 365 |
+
def occ_step(params, opt_state, ema, k, actor_params, pi_on):
|
| 366 |
+
k1, k2, k3 = jax.random.split(k, 3)
|
| 367 |
+
c_raw, b01, w, _j = sample_occ_tuple(k1, actor_params, pi_on)
|
| 368 |
+
t_int = jax.random.randint(k2, (occ_batch,), 1, occ_T + 1)
|
| 369 |
+
keep = abar_j[t_int - 1]
|
| 370 |
+
m = (jax.random.uniform(k3, (occ_batch, n_bits)) >= keep[:, None]).astype(jnp.float32)
|
| 371 |
+
|
| 372 |
+
if readout == "gl":
|
| 373 |
+
def loss_fn(p):
|
| 374 |
+
c = (c_raw - cond_mean) / cond_std
|
| 375 |
+
tf = t_int.astype(jnp.float32) / occ_T
|
| 376 |
+
xt = (2.0 * b01 - 1.0) * (1.0 - m)
|
| 377 |
+
pred = occ_model.apply(p, jnp.concatenate([xt, m], -1), tf, c)
|
| 378 |
+
bce = optax.sigmoid_binary_cross_entropy(pred, b01)
|
| 379 |
+
return (w[:, None] * bce * m).sum() / jnp.maximum(m.sum(), 1.0)
|
| 380 |
+
else:
|
| 381 |
+
# continuous eps-prediction over z (same tuples/weights). Bits envs
|
| 382 |
+
# keep the natural ±1 scale; continuous targets are standardized.
|
| 383 |
+
eps_n = jax.random.normal(k3, (occ_batch, n_bits))
|
| 384 |
+
|
| 385 |
+
def loss_fn(p):
|
| 386 |
+
c = (c_raw - cond_mean) / cond_std
|
| 387 |
+
tf = t_int.astype(jnp.float32) / occ_T
|
| 388 |
+
z0 = 2.0 * b01 - 1.0 if is_bits else (b01 - tgt_mu_j) / tgt_sd_j
|
| 389 |
+
ab = abar_j[t_int - 1][:, None]
|
| 390 |
+
zt = jnp.sqrt(ab) * z0 + jnp.sqrt(1.0 - ab) * eps_n
|
| 391 |
+
pred = occ_model.apply(p, zt, tf, c)
|
| 392 |
+
return (w[:, None] * (pred - eps_n) ** 2).mean()
|
| 393 |
+
|
| 394 |
+
loss, grads = jax.value_and_grad(loss_fn)(params)
|
| 395 |
+
grads = psync(grads)
|
| 396 |
+
updates, opt_state = occ_tx.update(grads, opt_state, params)
|
| 397 |
+
params = optax.apply_updates(params, updates)
|
| 398 |
+
ema = jax.tree_util.tree_map(lambda e, p: e * (1 - occ_tau) + p * occ_tau,
|
| 399 |
+
ema, params)
|
| 400 |
+
return params, opt_state, ema, loss
|
| 401 |
+
|
| 402 |
+
def gl(ema, s, a, g, k, dv=None, n_ord=None):
|
| 403 |
+
# n_ord: static override of the order count (the order average is Monte-
|
| 404 |
+
# Carlo; the actor LOSS can run fewer orders because the batch averages
|
| 405 |
+
# the gradient — targets/eval keep the full n_orders)
|
| 406 |
+
n_o = n_orders if n_ord is None else n_ord
|
| 407 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 408 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 409 |
+
B = c.shape[0]
|
| 410 |
+
cc = jnp.repeat(c, n_o, axis=0)
|
| 411 |
+
BO = B * n_o
|
| 412 |
+
g01 = jnp.round(jnp.clip(jnp.repeat(g, n_o, axis=0), 0.0, 1.0))
|
| 413 |
+
k, sub = jax.random.split(k)
|
| 414 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BO, n_bits)), axis=-1)
|
| 415 |
+
rows = jnp.arange(BO)
|
| 416 |
+
|
| 417 |
+
def step(carry, i):
|
| 418 |
+
x, m, logp = carry
|
| 419 |
+
out = occ_model.apply(ema, jnp.concatenate([x, m], -1),
|
| 420 |
+
jnp.full((BO,), ts_frac[i]), cc)
|
| 421 |
+
idx = orders[:, i]
|
| 422 |
+
logit = out[rows, idx]
|
| 423 |
+
gbit = g01[rows, idx]
|
| 424 |
+
logp = logp + gbit * jax.nn.log_sigmoid(logit) + \
|
| 425 |
+
(1 - gbit) * jax.nn.log_sigmoid(-logit)
|
| 426 |
+
x = x.at[rows, idx].set(2.0 * gbit - 1.0)
|
| 427 |
+
m = m.at[rows, idx].set(0.0)
|
| 428 |
+
return (x, m, logp), None
|
| 429 |
+
|
| 430 |
+
init = (jnp.zeros((BO, n_bits)), jnp.ones((BO, n_bits)), jnp.zeros((BO,)))
|
| 431 |
+
(_, _, logp), _ = jax.lax.scan(step, init, jnp.arange(n_bits))
|
| 432 |
+
return jnp.exp(logp).reshape(B, n_o).mean(-1)
|
| 433 |
+
|
| 434 |
+
# ---- likelihood-free readout (readout="sample"): pathwise DDIM samples +
|
| 435 |
+
# kernel Monte-Carlo. Drop-in twins of gl/occ_bits with identical
|
| 436 |
+
# signatures, so every downstream site (chains, recursion prep, actor loss,
|
| 437 |
+
# critic targets) is readout-agnostic. ----
|
| 438 |
+
_ts_z = np.unique(np.linspace(occ_T, 1, 25).round().astype(np.int32))[::-1].copy()
|
| 439 |
+
# short schedule for the DIFFERENTIATED actor-loss path only (targets keep
|
| 440 |
+
# 25 steps): backprop through 8 DDIM steps instead of 25 — the same
|
| 441 |
+
# noise-the-batch-absorbs trade as n_orders_pi=4, ~2x actor-step speedup
|
| 442 |
+
_ts_z8 = np.unique(np.linspace(occ_T, 1, 8).round().astype(np.int32))[::-1].copy()
|
| 443 |
+
_zs = {False: (jnp.asarray(_ts_z),
|
| 444 |
+
jnp.asarray(np.concatenate([_ts_z[1:], [0]]).astype(np.int32)),
|
| 445 |
+
len(_ts_z)),
|
| 446 |
+
True: (jnp.asarray(_ts_z8),
|
| 447 |
+
jnp.asarray(np.concatenate([_ts_z8[1:], [0]]).astype(np.int32)),
|
| 448 |
+
len(_ts_z8))}
|
| 449 |
+
|
| 450 |
+
def z_sample(ema, cond_norm, k, short=False):
|
| 451 |
+
# deterministic DDIM on the z-columns given Gaussian init noise:
|
| 452 |
+
# z = f(noise; cond) is differentiable in cond (pathwise gradients).
|
| 453 |
+
ts_now, ts_nxt, n_steps = _zs[short]
|
| 454 |
+
B2 = cond_norm.shape[0]
|
| 455 |
+
z = jax.random.normal(k, (B2, n_bits))
|
| 456 |
+
|
| 457 |
+
def stepf(z, i2):
|
| 458 |
+
tn = ts_now[i2]
|
| 459 |
+
tx = ts_nxt[i2]
|
| 460 |
+
ab_n = abar_j[tn - 1]
|
| 461 |
+
ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0)
|
| 462 |
+
eps = jnp.clip(occ_model.apply(
|
| 463 |
+
ema, z, jnp.full((B2,), tn.astype(jnp.float32) / occ_T),
|
| 464 |
+
cond_norm), -6.0, 6.0)
|
| 465 |
+
z0h = (z - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8))
|
| 466 |
+
return jnp.sqrt(ab_x) * z0h + jnp.sqrt(1.0 - ab_x) * eps, None
|
| 467 |
+
|
| 468 |
+
z, _ = jax.lax.scan(stepf, z, jnp.arange(n_steps))
|
| 469 |
+
return z
|
| 470 |
+
|
| 471 |
+
def ker_match(z, g01):
|
| 472 |
+
# smoothed success predicate — the ONE env-specific piece of the
|
| 473 |
+
# sample readout. Discrete (puzzle): per-bit sigmoid match of z ~ ±1
|
| 474 |
+
# against goal bits, product over bits. Continuous: smoothed eps-ball
|
| 475 |
+
# in RAW target units, sigmoid(sharp*(ker_eps - ||z_raw - g||)) — the
|
| 476 |
+
# env's success predicate with soft edges.
|
| 477 |
+
if is_bits:
|
| 478 |
+
sgn = 2.0 * g01 - 1.0
|
| 479 |
+
return jnp.exp(jax.nn.log_sigmoid(ker_sharp * z * sgn).sum(-1))
|
| 480 |
+
z_raw = z * tgt_sd_j + tgt_mu_j
|
| 481 |
+
dist = jnp.sqrt(((z_raw - g01) ** 2).sum(-1) + 1e-12)
|
| 482 |
+
return jax.nn.sigmoid(ker_sharp * (ker_eps - dist))
|
| 483 |
+
|
| 484 |
+
def q_ker(ema, s, a, g, k, dv=None, n_ord=None):
|
| 485 |
+
# kernel Monte-Carlo Q: mean over K pathwise samples of the smoothed
|
| 486 |
+
# reward at the goal. Same signature as gl; n_ord overrides K (the
|
| 487 |
+
# actor loss runs fewer samples — the batch absorbs the extra noise,
|
| 488 |
+
# same finding as n_orders_pi for gl).
|
| 489 |
+
K = ker_K if n_ord is None else n_ord
|
| 490 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 491 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 492 |
+
B = c.shape[0]
|
| 493 |
+
cc = jnp.repeat(c, K, axis=0)
|
| 494 |
+
# n_ord present == differentiated actor-loss context: short DDIM path
|
| 495 |
+
z = z_sample(ema, cc, k, short=n_ord is not None)
|
| 496 |
+
return ker_match(z, jnp.repeat(g, K, axis=0)).reshape(B, K).mean(-1)
|
| 497 |
+
|
| 498 |
+
def z_bits(ema, s, a, g, k, dv, m_wide):
|
| 499 |
+
# sample-mode twin of occ_bits: M pathwise z draws in the RAW target
|
| 500 |
+
# scale of the env (puzzle: [0,1] bits; continuous: coordinates) — the
|
| 501 |
+
# scale downstream completion conditioning and kernel reads expect.
|
| 502 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 503 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 504 |
+
B2 = c.shape[0]
|
| 505 |
+
cc = jnp.repeat(c, m_wide, axis=0)
|
| 506 |
+
z = z_sample(ema, cc, k)
|
| 507 |
+
if is_bits:
|
| 508 |
+
z = jnp.clip((z + 1.0) / 2.0, 0.0, 1.0)
|
| 509 |
+
else:
|
| 510 |
+
z = z * tgt_sd_j + tgt_mu_j
|
| 511 |
+
return z.reshape(B2, m_wide, n_bits)
|
| 512 |
+
|
| 513 |
+
def q_elbo(ema, s, a, g, k, dv=None, n_ord=None):
|
| 514 |
+
# ELBO point read-out (owner: "if you can use elbo of diffusion model
|
| 515 |
+
# it is fine if it makes goal likelihood accurate enough"): the
|
| 516 |
+
# per-condition denoising loss at the goal's z is a monotone surrogate
|
| 517 |
+
# of -log p(g | s,a); Q = exp(-elbo_c * loss). Stratified t over K
|
| 518 |
+
# draws for variance; differentiable in `a` through the conditioning
|
| 519 |
+
# with ONE model apply per draw.
|
| 520 |
+
K = ker_K if n_ord is None else n_ord
|
| 521 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 522 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 523 |
+
B = c.shape[0]
|
| 524 |
+
cc = jnp.repeat(c, K, axis=0)
|
| 525 |
+
BO = B * K
|
| 526 |
+
zg = 2.0 * g - 1.0 if is_bits else (g - tgt_mu_j) / tgt_sd_j
|
| 527 |
+
zg = jnp.repeat(zg, K, axis=0)
|
| 528 |
+
k1, k2 = jax.random.split(k)
|
| 529 |
+
# stratified timesteps: draw i covers quantile band i/K..(i+1)/K
|
| 530 |
+
u = jax.random.uniform(k1, (B, K))
|
| 531 |
+
strat = (jnp.arange(K)[None, :] + u) / K
|
| 532 |
+
t_int = jnp.clip((strat.reshape(-1) * occ_T).astype(jnp.int32) + 1, 1, occ_T)
|
| 533 |
+
eps = jax.random.normal(k2, (BO, n_bits))
|
| 534 |
+
ab = abar_j[t_int - 1][:, None]
|
| 535 |
+
zt = jnp.sqrt(ab) * zg + jnp.sqrt(1.0 - ab) * eps
|
| 536 |
+
pred = occ_model.apply(ema, zt, t_int.astype(jnp.float32) / occ_T, cc)
|
| 537 |
+
per = ((pred - eps) ** 2).mean(-1).reshape(B, K)
|
| 538 |
+
loss = per.mean(-1)
|
| 539 |
+
if elbo_pess > 0:
|
| 540 |
+
# uncertainty-penalized ELBO (RSM stability): off-data conditions
|
| 541 |
+
# produce higher spread across the K (t,eps) draws — penalizing it
|
| 542 |
+
# is conservatism exactly where the occupancy extrapolates
|
| 543 |
+
loss = loss + elbo_pess * per.std(-1)
|
| 544 |
+
return jnp.exp(-elbo_c * loss)
|
| 545 |
+
|
| 546 |
+
if readout == "sample":
|
| 547 |
+
gl = q_ker
|
| 548 |
+
elif readout == "elbo":
|
| 549 |
+
gl = q_elbo
|
| 550 |
+
|
| 551 |
+
# ---- recursion machinery (fused): completion head + width-1 sampler + chain ----
|
| 552 |
+
obs_dim = obs_np.shape[1]
|
| 553 |
+
obs_mu_j = jnp.asarray(obs_np.mean(0))
|
| 554 |
+
obs_sd_j = jnp.asarray(obs_np.std(0) + 1e-6)
|
| 555 |
+
# mids-slot stats: bits live on [0,1] (mean/std 0.5); continuous targets
|
| 556 |
+
# use their dataset stats
|
| 557 |
+
_m_mu = jnp.full((n_bits,), 0.5) if is_bits else tgt_mu_j
|
| 558 |
+
_m_sd = jnp.full((n_bits,), 0.5) if is_bits else tgt_sd_j
|
| 559 |
+
c2_mean = jnp.concatenate([cond_mean, _m_mu])
|
| 560 |
+
c2_std = jnp.concatenate([cond_std, _m_sd])
|
| 561 |
+
cmpl_model = make_model(cond_dim + n_bits, obs_dim, occ_hidden, occ_layers,
|
| 562 |
+
occ_time_dim)
|
| 563 |
+
key, ik3 = jax.random.split(key)
|
| 564 |
+
cmpl_params = cmpl_model.init(ik3, jnp.zeros((1, obs_dim)), jnp.zeros((1,)),
|
| 565 |
+
jnp.zeros((1, cond_dim + n_bits)))
|
| 566 |
+
cmpl_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(occ_lr))
|
| 567 |
+
cmpl_opt = cmpl_tx.init(cmpl_params)
|
| 568 |
+
cmpl_ema = jax.tree_util.tree_map(lambda x: x, cmpl_params)
|
| 569 |
+
_ts_c = np.unique(np.linspace(occ_T, 1, 25).round().astype(np.int32))[::-1].copy()
|
| 570 |
+
ts_c_now = jnp.asarray(_ts_c)
|
| 571 |
+
ts_c_nxt = jnp.asarray(np.concatenate([_ts_c[1:], [0]]).astype(np.int32))
|
| 572 |
+
|
| 573 |
+
def cmpl_step(cp, co, ce, k, c_raw, j, w):
|
| 574 |
+
k1, k2 = jax.random.split(k)
|
| 575 |
+
t_int = jax.random.randint(k1, (occ_batch,), 1, occ_T + 1)
|
| 576 |
+
eps = jax.random.normal(k2, (occ_batch, obs_dim))
|
| 577 |
+
c2 = (jnp.concatenate([c_raw, tgt_d[j]], -1) - c2_mean) / c2_std
|
| 578 |
+
x0 = (obs_d[j] - obs_mu_j) / obs_sd_j
|
| 579 |
+
ab = abar_j[t_int - 1][:, None]
|
| 580 |
+
xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1.0 - ab) * eps
|
| 581 |
+
|
| 582 |
+
def lf(pp):
|
| 583 |
+
pred = cmpl_model.apply(pp, xt, t_int.astype(jnp.float32) / occ_T, c2)
|
| 584 |
+
return (w[:, None] * (pred - eps) ** 2).mean()
|
| 585 |
+
|
| 586 |
+
cl, gr = jax.value_and_grad(lf)(cp)
|
| 587 |
+
gr = psync(gr)
|
| 588 |
+
upd, co = cmpl_tx.update(gr, co, cp)
|
| 589 |
+
cp = optax.apply_updates(cp, upd)
|
| 590 |
+
ce = jax.tree_util.tree_map(lambda e, q: e * (1 - occ_tau) + q * occ_tau, ce, cp)
|
| 591 |
+
return cp, co, ce, cl
|
| 592 |
+
|
| 593 |
+
def cmpl_sample(ce, cond2_raw, k):
|
| 594 |
+
c2 = (cond2_raw - c2_mean) / c2_std
|
| 595 |
+
B2 = c2.shape[0]
|
| 596 |
+
x = jax.random.normal(k, (B2, obs_dim))
|
| 597 |
+
|
| 598 |
+
def stepf(x, i2):
|
| 599 |
+
tn = ts_c_now[i2]
|
| 600 |
+
tx = ts_c_nxt[i2]
|
| 601 |
+
ab_n = abar_j[tn - 1]
|
| 602 |
+
ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0)
|
| 603 |
+
eps = jnp.clip(cmpl_model.apply(
|
| 604 |
+
ce, x, jnp.full((B2,), tn.astype(jnp.float32) / occ_T), c2), -6.0, 6.0)
|
| 605 |
+
x0h = (x - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8))
|
| 606 |
+
return jnp.sqrt(ab_x) * x0h + jnp.sqrt(1.0 - ab_x) * eps, None
|
| 607 |
+
|
| 608 |
+
x, _ = jax.lax.scan(stepf, x, jnp.arange(len(_ts_c)))
|
| 609 |
+
return x * obs_sd_j + obs_mu_j
|
| 610 |
+
|
| 611 |
+
def occ_bits(ema, s, a, g, k, dv, m_wide):
|
| 612 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 613 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 614 |
+
B2 = c.shape[0]
|
| 615 |
+
cc = jnp.repeat(c, m_wide, axis=0)
|
| 616 |
+
BM = B2 * m_wide
|
| 617 |
+
k, sub = jax.random.split(k)
|
| 618 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BM, n_bits)), axis=-1)
|
| 619 |
+
rows = jnp.arange(BM)
|
| 620 |
+
|
| 621 |
+
def stepf(carry, i):
|
| 622 |
+
x, m, kk = carry
|
| 623 |
+
out = occ_model.apply(ema, jnp.concatenate([x, m], -1),
|
| 624 |
+
jnp.full((BM,), ts_frac[i]), cc)
|
| 625 |
+
idx = orders[:, i]
|
| 626 |
+
kk, sub2 = jax.random.split(kk)
|
| 627 |
+
b = jax.random.bernoulli(sub2, jax.nn.sigmoid(out[rows, idx])).astype(
|
| 628 |
+
jnp.float32)
|
| 629 |
+
x = x.at[rows, idx].set(2.0 * b - 1.0)
|
| 630 |
+
m = m.at[rows, idx].set(0.0)
|
| 631 |
+
return (x, m, kk), None
|
| 632 |
+
|
| 633 |
+
init = (jnp.zeros((BM, n_bits)), jnp.ones((BM, n_bits)), k)
|
| 634 |
+
(x, _, _), _ = jax.lax.scan(stepf, init, jnp.arange(n_bits))
|
| 635 |
+
return ((x + 1.0) / 2.0).reshape(B2, m_wide, n_bits)
|
| 636 |
+
|
| 637 |
+
if readout != "gl":
|
| 638 |
+
occ_bits = z_bits
|
| 639 |
+
|
| 640 |
+
def mk_cond2(s, a, gb, mids):
|
| 641 |
+
parts = [s, a, gb] + \
|
| 642 |
+
([g_enc(jnp.full((s.shape[0],), hop_disc))] if spec_on else []) + [mids]
|
| 643 |
+
return jnp.concatenate(parts, -1)
|
| 644 |
+
|
| 645 |
+
def chain_prob(ema, ce, actor_params, s0, a0, gb, gobs, k):
|
| 646 |
+
# splitting-identity estimator: coin-terminated beta-jump walk over
|
| 647 |
+
# generated states; every level coin-gated; dead rows freeze (masked)
|
| 648 |
+
B2 = s0.shape[0]
|
| 649 |
+
dvh = jnp.full((B2,), hop_disc)
|
| 650 |
+
|
| 651 |
+
def level(carry, _):
|
| 652 |
+
s_cur, a_cur, alive, kk = carry
|
| 653 |
+
kk, kc, ks_, kx = jax.random.split(kk, 4)
|
| 654 |
+
cont = alive & (jax.random.uniform(kc, (B2,)) < rec_p)
|
| 655 |
+
mids = occ_bits(ema, s_cur, a_cur, gb, ks_, dvh, 1)[:, 0, :]
|
| 656 |
+
x_new = cmpl_sample(ce, mk_cond2(s_cur, a_cur, gb, mids), kx)
|
| 657 |
+
a_new = jnp.clip(actor_def.apply({"params": actor_params},
|
| 658 |
+
x_new, gobs).mode(), -1, 1)
|
| 659 |
+
s_cur = jnp.where(cont[:, None], x_new, s_cur)
|
| 660 |
+
a_cur = jnp.where(cont[:, None], a_new, a_cur)
|
| 661 |
+
return (s_cur, a_cur, cont, kk), None
|
| 662 |
+
|
| 663 |
+
(s_f, a_f, _, k), _ = jax.lax.scan(
|
| 664 |
+
level, (s0, a0, jnp.ones((B2,), bool), k), None, length=rec_max_depth)
|
| 665 |
+
k, kg = jax.random.split(k)
|
| 666 |
+
return gl(ema, s_f, a_f, gb, kg, dvh)
|
| 667 |
+
|
| 668 |
+
# ---- agents ----
|
| 669 |
+
class _D2:
|
| 670 |
+
def __init__(self, params):
|
| 671 |
+
self.params = params
|
| 672 |
+
|
| 673 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 674 |
+
dist = actor_def.apply({"params": self.params}, observations, goals,
|
| 675 |
+
temperature=temperature)
|
| 676 |
+
return jnp.clip(dist.sample(seed=seed), -1, 1)
|
| 677 |
+
|
| 678 |
+
ex = {"observations": obs_np[:2], "actions": act_np[:2]}
|
| 679 |
+
if extraction == "r3":
|
| 680 |
+
agent = GCIQLAblateAgent.create(seed, ex["observations"], ex["actions"], config)
|
| 681 |
+
actor_of = lambda ag: ag.network.params["modules_actor"]
|
| 682 |
+
eval_wrap = None
|
| 683 |
+
d2tx = None
|
| 684 |
+
else:
|
| 685 |
+
key, ik2 = jax.random.split(key)
|
| 686 |
+
d2params = actor_def.init(ik2, obs_np[:2], obs_np[:2])["params"]
|
| 687 |
+
d2tx = optax.adam(learning_rate=config["lr"])
|
| 688 |
+
agent = (d2params, d2tx.init(d2params))
|
| 689 |
+
actor_of = lambda ag: ag[0]
|
| 690 |
+
eval_wrap = lambda ag: _D2(ag[0] if isinstance(ag, tuple) else ag)
|
| 691 |
+
# order count for the DIFFERENTIATED actor-loss gl calls (0 = full n_orders).
|
| 692 |
+
# The order average is MC of the same expectation; at batch >=1024 the
|
| 693 |
+
# gradient averages per-state read-out noise, so 4 orders trades noise the
|
| 694 |
+
# batch absorbs for ~4x less loss-side compute.
|
| 695 |
+
n_orders_pi = int(n_orders_pi) if n_orders_pi else n_orders
|
| 696 |
+
|
| 697 |
+
def pi_step(ag, k, q_v, q_a, t, gi_v, gi_a, success, ema, rec_aux, compose,
|
| 698 |
+
bc_w):
|
| 699 |
+
if extraction == "r3":
|
| 700 |
+
batch = {"observations": obs_d[t], "next_observations": nobs_d[t],
|
| 701 |
+
"actions": act_d[t], "value_goals": obs_d[gi_v],
|
| 702 |
+
"actor_goals": obs_d[gi_a], "rewards": success - 1.0,
|
| 703 |
+
"masks": 1.0 - success, "genq_q_value": q_v, "genq_q_actor": q_a}
|
| 704 |
+
if not dp:
|
| 705 |
+
new_ag, info = ag.update(batch)
|
| 706 |
+
return new_ag, info["actor/actor_loss"]
|
| 707 |
+
# data-parallel r3: mirror GCIQLAblateAgent.update / TrainState.apply_loss_fn
|
| 708 |
+
# exactly, with the cross-device grad pmean inserted before Adam (the
|
| 709 |
+
# reference update applies grads inside apply_loss_fn, where we cannot hook;
|
| 710 |
+
# its extra grad-stat info entries are unused here)
|
| 711 |
+
new_rng, rng2 = jax.random.split(ag.rng)
|
| 712 |
+
grads, info = jax.grad(lambda gp: ag.total_loss(batch, gp, rng=rng2),
|
| 713 |
+
has_aux=True)(ag.network.params)
|
| 714 |
+
new_network = ag.network.apply_gradients(grads=psync(grads))
|
| 715 |
+
ag.target_update(new_network, "critic")
|
| 716 |
+
ag.target_update(new_network, "genq_critic")
|
| 717 |
+
return ag.replace(network=new_network, rng=new_rng), \
|
| 718 |
+
info["actor/actor_loss"]
|
| 719 |
+
params, opt_state = ag
|
| 720 |
+
dv_t = jnp.full((B_pi,), gamma)
|
| 721 |
+
dv_h = jnp.full((B_pi,), hop_disc)
|
| 722 |
+
|
| 723 |
+
def loss_fn(pp):
|
| 724 |
+
dist = actor_def.apply({"params": pp}, obs_d[t], obs_d[gi_a])
|
| 725 |
+
mu = jnp.clip(dist.mode(), -1, 1)
|
| 726 |
+
k1, k2, k3 = jax.random.split(k, 3)
|
| 727 |
+
if rec_mode == "prob":
|
| 728 |
+
c1, den, v1 = rec_aux
|
| 729 |
+
# ONE goal-read serves both branches: at the hop discount when
|
| 730 |
+
# composing (the beta-term of q_rec), at the task discount when
|
| 731 |
+
# not (the plain read) — identical values to the two-call form,
|
| 732 |
+
# one fewer differentiated 9-step gl scan per actor step
|
| 733 |
+
dv_sel = jnp.where(compose, dv_h, dv_t)
|
| 734 |
+
glb = gl(ema, obs_d[t], mu, tgt_d[gi_a], k1, dv_sel,
|
| 735 |
+
n_ord=n_orders_pi)
|
| 736 |
+
num = gl(ema, obs_d[t], mu, c1, k2, dv_h, n_ord=n_orders_pi)
|
| 737 |
+
q_rec = (1.0 - rec_p) * glb + \
|
| 738 |
+
rec_p * (num / jnp.maximum(den, 1e-6)) * v1
|
| 739 |
+
qv = jnp.where(compose, q_rec, glb)
|
| 740 |
+
elif rec_mode == "cert1":
|
| 741 |
+
mid_g, mid_v = rec_aux
|
| 742 |
+
best = gl(ema, obs_d[t], mu, tgt_d[gi_a], k1, dv_t,
|
| 743 |
+
n_ord=n_orders_pi)
|
| 744 |
+
ks = jax.random.split(k2, rec_target)
|
| 745 |
+
for m2 in range(rec_target):
|
| 746 |
+
ph = gl(ema, obs_d[t], mu, mid_g[:, m2], ks[m2], dv_h,
|
| 747 |
+
n_ord=n_orders_pi)
|
| 748 |
+
cand = jnp.where(compose, ph * mid_v[:, m2], 0.0)
|
| 749 |
+
best = jnp.maximum(best, cand)
|
| 750 |
+
qv = best
|
| 751 |
+
else:
|
| 752 |
+
qv = gl(ema, obs_d[t], mu, tgt_d[gi_a], k1, dv_t,
|
| 753 |
+
n_ord=n_orders_pi)
|
| 754 |
+
q = jnp.log(jnp.maximum(qv, 1e-9))
|
| 755 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6)
|
| 756 |
+
bc = -dist.log_prob(act_d[t]).mean()
|
| 757 |
+
return q_loss + bc_w * bc
|
| 758 |
+
|
| 759 |
+
loss, grads = jax.value_and_grad(loss_fn)(params)
|
| 760 |
+
grads = psync(grads)
|
| 761 |
+
updates, opt_state = d2tx.update(grads, opt_state, params)
|
| 762 |
+
return (optax.apply_updates(params, updates), opt_state), loss
|
| 763 |
+
|
| 764 |
+
def one_step(carry, _):
|
| 765 |
+
occ_p, occ_o, ema, cm_p, cm_o, cm_e, ag, ema_actor, k, step = carry
|
| 766 |
+
k, k1, k2, k3, k4, k5, k6, k7, k8 = jax.random.split(k, 9)
|
| 767 |
+
pi_on = step > occ_warmup
|
| 768 |
+
compose = (step > rec_after) & ((step % rec_every) == 0)
|
| 769 |
+
occ_p, occ_o, ema, occ_l = occ_step(occ_p, occ_o, ema, k1, actor_of(ag), pi_on)
|
| 770 |
+
if rec_mode != "off":
|
| 771 |
+
c_raw2, _b, w2, j2 = sample_occ_tuple(k5, actor_of(ag), pi_on)
|
| 772 |
+
cm_p, cm_o, cm_e, _cl = cmpl_step(cm_p, cm_o, cm_e, k6, c_raw2, j2, w2)
|
| 773 |
+
t, gi_v, gi_a, success = sample_pi_batch(k2)
|
| 774 |
+
dv_t = jnp.full((B_pi,), gamma)
|
| 775 |
+
dv_h = jnp.full((B_pi,), hop_disc)
|
| 776 |
+
rec_aux = ()
|
| 777 |
+
if extraction == "r3":
|
| 778 |
+
both = gl(ema, jnp.concatenate([obs_d[t], obs_d[t]]),
|
| 779 |
+
jnp.concatenate([act_d[t], act_d[t]]),
|
| 780 |
+
jnp.concatenate([tgt_d[gi_v], tgt_d[gi_a]]), k3,
|
| 781 |
+
jnp.concatenate([dv_t, dv_t]))
|
| 782 |
+
q_v, q_a = both[:B_pi], both[B_pi:]
|
| 783 |
+
if rec_mode == "prob":
|
| 784 |
+
q_rec = jnp.clip(chain_prob(ema, cm_e, actor_of(ag), obs_d[t],
|
| 785 |
+
act_d[t], tgt_d[gi_v], obs_d[gi_v], k7),
|
| 786 |
+
0.0, 1.0)
|
| 787 |
+
q_v = jnp.where(compose, q_rec, q_v)
|
| 788 |
+
elif rec_mode == "cert1":
|
| 789 |
+
mids = occ_bits(ema, obs_d[t], act_d[t], tgt_d[gi_v], k7, dv_h,
|
| 790 |
+
rec_target)
|
| 791 |
+
sr_ = jnp.repeat(obs_d[t], rec_target, 0)
|
| 792 |
+
ar_ = jnp.repeat(act_d[t], rec_target, 0)
|
| 793 |
+
gb_ = jnp.repeat(tgt_d[gi_v], rec_target, 0)
|
| 794 |
+
go_ = jnp.repeat(obs_d[gi_v], rec_target, 0)
|
| 795 |
+
mf = mids.reshape(-1, n_bits)
|
| 796 |
+
k7a, k7b = jax.random.split(k8)
|
| 797 |
+
hit = gl(ema, sr_, ar_, mf, k7a,
|
| 798 |
+
jnp.full((B_pi * rec_target,), hop_disc))
|
| 799 |
+
x_m = cmpl_sample(cm_e, mk_cond2(sr_, ar_, gb_, mf), k7b)
|
| 800 |
+
a_m = jnp.clip(actor_def.apply(
|
| 801 |
+
{"params": ag.network.params["modules_actor"]}, x_m, go_).mode(),
|
| 802 |
+
-1, 1)
|
| 803 |
+
vq = jnp.minimum(*ag.network.model_def.apply(
|
| 804 |
+
{"params": ag.network.params}, x_m, go_, a_m,
|
| 805 |
+
name="target_genq_critic"))
|
| 806 |
+
comp = (hit * jnp.clip(vq, 0.0, 1.0)).reshape(B_pi, rec_target).max(1)
|
| 807 |
+
q_v = jnp.where(compose, jnp.maximum(q_v, comp), q_v)
|
| 808 |
+
else:
|
| 809 |
+
q_v = q_a = jnp.zeros((B_pi,))
|
| 810 |
+
if rec_mode == "prob":
|
| 811 |
+
c1 = occ_bits(ema, obs_d[t], act_d[t], tgt_d[gi_a], k7, dv_h,
|
| 812 |
+
1)[:, 0, :]
|
| 813 |
+
k8a, k8b, k8c = jax.random.split(k8, 3)
|
| 814 |
+
den = gl(ema, obs_d[t], act_d[t], c1, k8a, dv_h)
|
| 815 |
+
x1 = cmpl_sample(cm_e, mk_cond2(obs_d[t], act_d[t], tgt_d[gi_a], c1),
|
| 816 |
+
k8b)
|
| 817 |
+
a1 = jnp.clip(actor_def.apply({"params": actor_of(ag)},
|
| 818 |
+
x1, obs_d[gi_a]).mode(), -1, 1)
|
| 819 |
+
v1 = jnp.clip(chain_prob(ema, cm_e, actor_of(ag), x1, a1,
|
| 820 |
+
tgt_d[gi_a], obs_d[gi_a], k8c), 0.0, 1.0)
|
| 821 |
+
rec_aux = (c1, jax.lax.stop_gradient(den), v1)
|
| 822 |
+
elif rec_mode == "cert1":
|
| 823 |
+
mids = occ_bits(ema, obs_d[t], act_d[t], tgt_d[gi_a], k7, dv_h,
|
| 824 |
+
rec_target)
|
| 825 |
+
sr_ = jnp.repeat(obs_d[t], rec_target, 0)
|
| 826 |
+
ar_ = jnp.repeat(act_d[t], rec_target, 0)
|
| 827 |
+
gb_ = jnp.repeat(tgt_d[gi_a], rec_target, 0)
|
| 828 |
+
go_ = jnp.repeat(obs_d[gi_a], rec_target, 0)
|
| 829 |
+
mf = mids.reshape(-1, n_bits)
|
| 830 |
+
k8a, k8b = jax.random.split(k8)
|
| 831 |
+
x_m = cmpl_sample(cm_e, mk_cond2(sr_, ar_, gb_, mf), k8a)
|
| 832 |
+
a_m = jnp.clip(actor_def.apply({"params": actor_of(ag)},
|
| 833 |
+
x_m, go_).mode(), -1, 1)
|
| 834 |
+
v_m = gl(ema, x_m, a_m, gb_, k8b,
|
| 835 |
+
jnp.full((B_pi * rec_target,), hop_disc))
|
| 836 |
+
rec_aux = (mf.reshape(B_pi, rec_target, n_bits),
|
| 837 |
+
v_m.reshape(B_pi, rec_target))
|
| 838 |
+
if alpha_ramp > 0:
|
| 839 |
+
frac = jnp.clip(step.astype(jnp.float32) / alpha_ramp, 0.0, 1.0)
|
| 840 |
+
bc_w = 1.0 + (config["alpha"] - 1.0) * frac
|
| 841 |
+
else:
|
| 842 |
+
bc_w = config["alpha"]
|
| 843 |
+
ag, pi_l = pi_step(ag, k4, q_v, q_a, t, gi_v, gi_a, success, ema, rec_aux,
|
| 844 |
+
compose, bc_w)
|
| 845 |
+
if actor_ema_tau > 0:
|
| 846 |
+
ema_actor = jax.tree_util.tree_map(
|
| 847 |
+
lambda e, p: e * (1 - actor_ema_tau) + p * actor_ema_tau,
|
| 848 |
+
ema_actor, actor_of(ag))
|
| 849 |
+
return (occ_p, occ_o, ema, cm_p, cm_o, cm_e, ag, ema_actor, k, step + 1), \
|
| 850 |
+
(occ_l, pi_l)
|
| 851 |
+
|
| 852 |
+
def _window(carry):
|
| 853 |
+
return jax.lax.scan(one_step, carry, None, length=steps_per_dispatch)
|
| 854 |
+
|
| 855 |
+
# dp: one pmap over the whole per-dispatch scan; the closed-over dataset arrays
|
| 856 |
+
# (~300 MB) are broadcast to every device as compile-time constants (fine on
|
| 857 |
+
# 80 GB HBM; on the CPU smoke all "devices" share host RAM)
|
| 858 |
+
dispatch = jax.pmap(_window, axis_name="dp") if dp else jax.jit(_window)
|
| 859 |
+
|
| 860 |
+
ema_actor = jax.tree_util.tree_map(lambda x: x, actor_of(agent))
|
| 861 |
+
vtag = f"_{variant_tag}" if variant_tag else ""
|
| 862 |
+
run = wandb.init(project="gen-q-policy-improvement",
|
| 863 |
+
name=f"genq_joint_fast{vtag}-{env_id}-s{seed}", mode=wandb_mode,
|
| 864 |
+
tags=["genq_joint_fast", env_id],
|
| 865 |
+
config=dict(method="genq_joint_fast", env=env_id, seed=seed,
|
| 866 |
+
extraction=extraction, alpha=alpha, occ_warmup=occ_warmup,
|
| 867 |
+
rt_eta=rt_eta, pi_alpha=pi_alpha, n_orders=n_orders,
|
| 868 |
+
actor_ema_tau=actor_ema_tau, train_steps=train_steps,
|
| 869 |
+
steps_per_dispatch=steps_per_dispatch,
|
| 870 |
+
data_parallel=dp, n_devices=(n_dev if dp else 1)),
|
| 871 |
+
settings=wandb.Settings(start_method="thread"))
|
| 872 |
+
print(f"[fast] WANDB_URL {run.get_url()}", flush=True)
|
| 873 |
+
eval_success = _make_eval_fn(env, config, evaluate, jax,
|
| 874 |
+
wrap=(eval_wrap if extraction == "ddpg2" else None))
|
| 875 |
+
out = os.path.join(_result_dir(env_id, seed), f"genq_joint_fast{vtag}.json")
|
| 876 |
+
curve = []
|
| 877 |
+
best = {"sr": -1.0, "agent": None}
|
| 878 |
+
best_saved = [-1.0]
|
| 879 |
+
final_info = {}
|
| 880 |
+
|
| 881 |
+
def dump(sr, per):
|
| 882 |
+
json.dump({"method": "genq_joint_fast", "extraction": extraction, "env": env_id,
|
| 883 |
+
"seed": seed, "alpha": alpha, "rt_eta": rt_eta, "pi_alpha": pi_alpha,
|
| 884 |
+
"occ_warmup": occ_warmup, "actor_ema_tau": actor_ema_tau,
|
| 885 |
+
"rec_target": rec_target, "rec_every": rec_every,
|
| 886 |
+
"rec_after": rec_after, "rec_beta": rec_beta,
|
| 887 |
+
"rec_prob": rec_prob, "rec_mode": rec_mode,
|
| 888 |
+
"gamma_spectrum_lo": gamma_spectrum_lo,
|
| 889 |
+
"gamma_spectrum_p": gamma_spectrum_p,
|
| 890 |
+
"data_parallel": bool(dp), "n_devices": int(n_dev if dp else 1),
|
| 891 |
+
"success_rate": sr,
|
| 892 |
+
"best_sr": (max(v for _, v in curve) if curve else sr), **final_info,
|
| 893 |
+
"per_task": per, "curve": curve, "train_steps": train_steps,
|
| 894 |
+
"wall_clock_sec": round(time.time() - t0, 1),
|
| 895 |
+
"wandb_url": run.get_url()}, open(out, "w"), indent=2)
|
| 896 |
+
|
| 897 |
+
carry = (occ_params, occ_opt, occ_ema, cmpl_params, cmpl_opt, cmpl_ema,
|
| 898 |
+
agent, ema_actor, key, jnp.asarray(0))
|
| 899 |
+
if dp:
|
| 900 |
+
# replicate every leaf across devices (leading axis = n_dev; pmap shards it on
|
| 901 |
+
# the first call and the carry stays device-resident thereafter — jax 0.10 has
|
| 902 |
+
# no device_put_replicated). Only the rng differs per device: fold_in(device
|
| 903 |
+
# index) gives each replica its own batch stream; step/gates stay identical.
|
| 904 |
+
carry = jax.tree_util.tree_map(
|
| 905 |
+
lambda x: jnp.broadcast_to(jnp.asarray(x)[None],
|
| 906 |
+
(n_dev,) + jnp.shape(x)), carry)
|
| 907 |
+
dev_keys = jnp.stack([jax.random.fold_in(key, d) for d in range(n_dev)])
|
| 908 |
+
carry = carry[:8] + (dev_keys, carry[9])
|
| 909 |
+
# eval/checkpoints read the (bit-identical) replica on device 0
|
| 910 |
+
unrep = lambda tree: jax.tree_util.tree_map(lambda x: x[0], tree)
|
| 911 |
+
else:
|
| 912 |
+
unrep = lambda tree: tree
|
| 913 |
+
n_disp = train_steps // steps_per_dispatch
|
| 914 |
+
tw = time.time()
|
| 915 |
+
for di in tqdm.trange(1, n_disp + 1, smoothing=0.05, dynamic_ncols=True):
|
| 916 |
+
carry, (occ_ls, pi_ls) = dispatch(carry)
|
| 917 |
+
i = di * steps_per_dispatch
|
| 918 |
+
if di == 3:
|
| 919 |
+
jax.block_until_ready(carry[0])
|
| 920 |
+
rate = 3 * steps_per_dispatch / (time.time() - tw)
|
| 921 |
+
print(f"[fast] throughput ~{rate:.1f} steps/s "
|
| 922 |
+
f"({train_steps / rate / 3600:.1f} h for {train_steps} steps)", flush=True)
|
| 923 |
+
if i % 1000 == 0:
|
| 924 |
+
wandb.log({"occ/loss": float(occ_ls.mean()), "train/pi_loss": float(pi_ls.mean())},
|
| 925 |
+
step=i)
|
| 926 |
+
if i % eval_interval == 0:
|
| 927 |
+
ag = unrep(carry[6])
|
| 928 |
+
sr, per = eval_success(ag, eval_episodes_periodic)
|
| 929 |
+
if sr >= best["sr"]:
|
| 930 |
+
best["sr"], best["agent"] = sr, ag
|
| 931 |
+
ema_msg = ""
|
| 932 |
+
if actor_ema_tau > 0:
|
| 933 |
+
if extraction == "r3":
|
| 934 |
+
prms = dict(ag.network.params)
|
| 935 |
+
prms["modules_actor"] = unrep(carry[7])
|
| 936 |
+
ema_ag = ag.replace(network=ag.network.replace(params=prms))
|
| 937 |
+
else:
|
| 938 |
+
ema_ag = (unrep(carry[7]), ag[1])
|
| 939 |
+
sr_e, per_e = eval_success(ema_ag, eval_episodes_periodic)
|
| 940 |
+
if sr_e >= best["sr"]:
|
| 941 |
+
best["sr"], best["agent"] = sr_e, ema_ag
|
| 942 |
+
ema_msg = f" ema={sr_e:.3f}"
|
| 943 |
+
wandb.log({"eval/success_rate_ema": sr_e}, step=i)
|
| 944 |
+
curve.append((i, sr))
|
| 945 |
+
wandb.log({"eval/success_rate": sr,
|
| 946 |
+
"eval/peak": max(v for _, v in curve)}, step=i)
|
| 947 |
+
print(f"[fast] step {i} sr={sr:.3f}{ema_msg} "
|
| 948 |
+
f"(peak {max(v for _, v in curve):.3f}) occ_loss={float(occ_ls.mean()):.4f}",
|
| 949 |
+
flush=True)
|
| 950 |
+
dump(sr, per)
|
| 951 |
+
if save_best and best["agent"] is not None and best["sr"] > best_saved[0]:
|
| 952 |
+
# persist the banked snapshot so it can be 50-ep evaluated offline
|
| 953 |
+
# at any time (the in-process best is otherwise unreachable mid-run)
|
| 954 |
+
import pickle
|
| 955 |
+
if extraction == "ddpg2":
|
| 956 |
+
bp = {"modules_actor": (best["agent"][0]
|
| 957 |
+
if isinstance(best["agent"], tuple)
|
| 958 |
+
else best["agent"])}
|
| 959 |
+
else:
|
| 960 |
+
bp = best["agent"].network.params
|
| 961 |
+
with open(save_best, "wb") as fbest:
|
| 962 |
+
pickle.dump({"params": jax.device_get(bp),
|
| 963 |
+
"config": dict(config), "step": i,
|
| 964 |
+
"periodic_sr": best["sr"]}, fbest)
|
| 965 |
+
best_saved[0] = best["sr"]
|
| 966 |
+
print(f"[fast] best snapshot (periodic {best['sr']:.3f}) saved -> "
|
| 967 |
+
f"{save_best}", flush=True)
|
| 968 |
+
|
| 969 |
+
ag = unrep(carry[6])
|
| 970 |
+
sr_last, per = eval_success(ag, eval_episodes)
|
| 971 |
+
curve.append((train_steps, sr_last))
|
| 972 |
+
sr, best_agent = sr_last, ag
|
| 973 |
+
final_info["final_last_step"] = sr_last
|
| 974 |
+
if best["agent"] is not None:
|
| 975 |
+
sr_b, per_b = eval_success(best["agent"], eval_episodes)
|
| 976 |
+
final_info["final_best_ckpt"] = sr_b
|
| 977 |
+
final_info["best_ckpt_periodic_sr"] = best["sr"]
|
| 978 |
+
print(f"[fast] best-ckpt (periodic {best['sr']:.3f}) 50-ep FINAL sr={sr_b:.3f} "
|
| 979 |
+
f"vs last-step {sr_last:.3f}", flush=True)
|
| 980 |
+
if sr_b > sr:
|
| 981 |
+
sr, per, best_agent = sr_b, per_b, best["agent"]
|
| 982 |
+
dump(sr, per)
|
| 983 |
+
if save_agent:
|
| 984 |
+
import pickle
|
| 985 |
+
if extraction == "ddpg2":
|
| 986 |
+
pms = {"modules_actor": (best_agent[0] if isinstance(best_agent, tuple)
|
| 987 |
+
else best_agent)}
|
| 988 |
+
else:
|
| 989 |
+
pms = best_agent.network.params
|
| 990 |
+
with open(save_agent, "wb") as f:
|
| 991 |
+
pickle.dump({"params": jax.device_get(pms), "config": dict(config)}, f)
|
| 992 |
+
if save_occ:
|
| 993 |
+
# co-trained occupancy EMA in the warm-start npz layout (torch keys), so
|
| 994 |
+
# eval_plan.py / warm starts read it unchanged — same export as the host path
|
| 995 |
+
pe = jax.device_get(unrep(carry[2]))["params"]
|
| 996 |
+
pairs = ([("time_emb_1", "time_emb.1"), ("time_emb_3", "time_emb.3"),
|
| 997 |
+
("cond_emb_0", "cond_emb.0"), ("x_emb", "x_emb"), ("out", "out")] +
|
| 998 |
+
[(f"trunk_{li}", f"trunk.{2 * li}") for li in range(occ_layers)])
|
| 999 |
+
occ_out = {}
|
| 1000 |
+
for name, k2 in pairs:
|
| 1001 |
+
occ_out[f"{k2}.weight"] = np.asarray(pe[name]["kernel"]).T
|
| 1002 |
+
occ_out[f"{k2}.bias"] = np.asarray(pe[name]["bias"])
|
| 1003 |
+
occ_out["cond_mean"] = np.asarray(cond_mean)
|
| 1004 |
+
occ_out["cond_std"] = np.asarray(cond_std)
|
| 1005 |
+
np.savez(save_occ, **occ_out)
|
| 1006 |
+
print(f"[fast] occupancy EMA saved -> {save_occ}", flush=True)
|
| 1007 |
+
print(f"[fast] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}",
|
| 1008 |
+
flush=True)
|
| 1009 |
+
wandb.finish()
|
| 1010 |
+
return out
|
gen_q_rsm/ogbench_genq/unused/goto_variant.gif
ADDED
|
Git LFS Details
|
gen_q_rsm/ogbench_genq/unused/make_figure.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Build experiments/{env}/figures/suc.png — fresh-rollout success rate per method, mean +- std
|
| 3 |
+
over seeds, with best-checkpoint values annotated.
|
| 4 |
+
|
| 5 |
+
Reads experiments/{env}/results/{seed}/{gcbc,gciql,gciql_genq,gciql_genq_rec_b*}.json.
|
| 6 |
+
"""
|
| 7 |
+
import argparse
|
| 8 |
+
import glob
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
import matplotlib
|
| 13 |
+
matplotlib.use("Agg")
|
| 14 |
+
import matplotlib.pyplot as plt
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
PKG_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 18 |
+
METHODS = [("gcbc", "GCBC", "#888888"), ("gciql", "GCIQL", "#1f77b4"),
|
| 19 |
+
("gciql_genq", "Gen-Q-GCIQL", "#d62728"),
|
| 20 |
+
("gciql_genq_rec_b09", "Gen-Q-Rec-GCIQL β=0.9", "#ff9f4a"),
|
| 21 |
+
("gciql_genq_rec_b095", "Gen-Q-Rec-GCIQL β=0.95", "#e377c2")]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def collect(env):
|
| 25 |
+
rdir = os.path.join(PKG_DIR, "experiments", env, "results")
|
| 26 |
+
out = {}
|
| 27 |
+
for method, _, _ in METHODS:
|
| 28 |
+
best, final = [], []
|
| 29 |
+
for f in sorted(glob.glob(os.path.join(rdir, "*", f"{method}.json"))):
|
| 30 |
+
d = json.load(open(f))
|
| 31 |
+
best.append(float(d.get("best_sr", d.get("success_rate", 0.0))))
|
| 32 |
+
final.append(float(d.get("success_rate", 0.0)))
|
| 33 |
+
out[method] = dict(best=best, final=final)
|
| 34 |
+
return out
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def make(env):
|
| 38 |
+
data = collect(env)
|
| 39 |
+
fig, ax = plt.subplots(figsize=(7.5, 4))
|
| 40 |
+
xs, labels = [], []
|
| 41 |
+
for i, (method, label, color) in enumerate(METHODS):
|
| 42 |
+
best = data[method]["best"]
|
| 43 |
+
if not best:
|
| 44 |
+
continue
|
| 45 |
+
m, s = float(np.mean(best)), float(np.std(best))
|
| 46 |
+
ax.bar(i, m * 100, yerr=s * 100, color=color, capsize=4, width=0.6,
|
| 47 |
+
label=f"{label} (n={len(best)})")
|
| 48 |
+
ax.text(i, m * 100 + 1.5, f"{m*100:.1f}", ha="center", va="bottom", fontsize=9)
|
| 49 |
+
xs.append(i)
|
| 50 |
+
labels.append(label)
|
| 51 |
+
ax.set_xticks(xs)
|
| 52 |
+
ax.set_xticklabels(labels, rotation=12, ha="right", fontsize=8)
|
| 53 |
+
ax.set_ylabel("Fresh-rollout success rate (%)")
|
| 54 |
+
ax.set_title(f"Policy improvement — {env}\n(best-checkpoint, mean ± std over seeds)")
|
| 55 |
+
ax.set_ylim(0, 105)
|
| 56 |
+
ax.grid(axis="y", alpha=0.3)
|
| 57 |
+
ax.legend(fontsize=8)
|
| 58 |
+
fig.tight_layout()
|
| 59 |
+
fdir = os.path.join(PKG_DIR, "experiments", env, "figures")
|
| 60 |
+
os.makedirs(fdir, exist_ok=True)
|
| 61 |
+
out = os.path.join(fdir, "suc.png")
|
| 62 |
+
fig.savefig(out, dpi=130)
|
| 63 |
+
plt.close(fig)
|
| 64 |
+
print(f"[fig] {env} -> {out} "
|
| 65 |
+
+ " ".join(f"{m}={np.mean(data[m]['best'])*100:.1f}%(n={len(data[m]['best'])})"
|
| 66 |
+
if data[m]["best"] else f"{m}=absent" for m, _, _ in METHODS))
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
ap = argparse.ArgumentParser()
|
| 72 |
+
ap.add_argument("--env", required=True)
|
| 73 |
+
a = ap.parse_args()
|
| 74 |
+
make(a.env)
|
gen_q_rsm/ogbench_genq/unused/rsm_graft.py
ADDED
|
@@ -0,0 +1,976 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RSM — Recursive Successor Model.
|
| 2 |
+
|
| 3 |
+
Policy iteration with TWO networks and no TD:
|
| 4 |
+
|
| 5 |
+
* an OCCUPANCY model: a conditional diffusion model p(z | s, a, gamma~)
|
| 6 |
+
of the reward-relevant coordinates z of the state the policy reaches
|
| 7 |
+
after a geometrically-distributed number of steps (the discounted
|
| 8 |
+
successor measure). Trained by plain maximum likelihood on offline
|
| 9 |
+
data — no reward, no bootstrap.
|
| 10 |
+
* an ACTOR trained by gradient ascent on a Q read directly off the
|
| 11 |
+
occupancy — "how much probability does the model put on the goal?" —
|
| 12 |
+
anchored by behavior cloning. No critic network, no target copies,
|
| 13 |
+
no max anywhere.
|
| 14 |
+
|
| 15 |
+
The training loop, in plain words (one fused step):
|
| 16 |
+
|
| 17 |
+
1. occupancy update : one diffusion MLE step on (s,a) -> z_{t+k} pairs,
|
| 18 |
+
k ~ Geom(1-gamma~), gamma~ drawn from a spectrum
|
| 19 |
+
2. completion update : (recursion only) train the small head that turns
|
| 20 |
+
sampled goal-coordinates into a full state
|
| 21 |
+
3. actor update : Q(s, mu(s), g) = occupancy read-out at the goal;
|
| 22 |
+
loss = -log Q (normalized) + alpha * BC
|
| 23 |
+
with recursion on, Q is estimated by the
|
| 24 |
+
coin-gated beta-hop chain instead of one read
|
| 25 |
+
4. EMA + banking : Polyak copies of occupancy and actor; periodic
|
| 26 |
+
evals bank the best snapshot for offline evals
|
| 27 |
+
|
| 28 |
+
ONE recipe for both goal spaces — beta-recursion is on everywhere. The
|
| 29 |
+
goal space picks only what it must:
|
| 30 |
+
discrete alphabet (puzzle bits) -> exact likelihood read-out ("gl"),
|
| 31 |
+
fully differentiated chain
|
| 32 |
+
continuous coordinates (mazes) -> diffusion-ELBO read-out, chain with
|
| 33 |
+
the "tails" guard (stop-grad heads;
|
| 34 |
+
the differentiated form collapses)
|
| 35 |
+
|
| 36 |
+
Run:
|
| 37 |
+
python ogbench_genq/rsm.py --env puzzle-3x3-play-v0 --save_best ckpt/best.pkl
|
| 38 |
+
python ogbench_genq/rsm.py --env pointmaze-medium-navigate-v0 ...
|
| 39 |
+
|
| 40 |
+
Everything here IS the record recipe; settled hyperparameters live in the
|
| 41 |
+
RECIPE CONSTANTS block below and are not command-line arguments (the
|
| 42 |
+
evidence for each is in ABLATION.md — change them only with new evidence).
|
| 43 |
+
Dropped designs and the levers that lost their races are archived in
|
| 44 |
+
unused/genq_joint_fast.py. Method + math: root README.md. Internals +
|
| 45 |
+
dropped designs: DESIGN.md. Numbers + protocol: RESULTS.md.
|
| 46 |
+
"""
|
| 47 |
+
import json
|
| 48 |
+
import os
|
| 49 |
+
import time
|
| 50 |
+
|
| 51 |
+
import numpy as np
|
| 52 |
+
|
| 53 |
+
if __package__ in (None, ""): # allow direct `python ogbench_genq/rsm.py`
|
| 54 |
+
import sys as _sys
|
| 55 |
+
_sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 56 |
+
|
| 57 |
+
from ogbench_genq._runner import (OGBENCH_IMPLS, PKG_DIR, _make_eval_fn, _result_dir,
|
| 58 |
+
_setup_paths)
|
| 59 |
+
|
| 60 |
+
# ======================= RECIPE CONSTANTS (settled) =======================
|
| 61 |
+
# Every value below was fixed by ablation — see ABLATION.md for the verdicts.
|
| 62 |
+
GAMMA = 0.99 # task discount (OGBench standard)
|
| 63 |
+
OCC_LR = 3e-4 # occupancy / completion AdamW learning rate
|
| 64 |
+
OCC_HIDDEN = 256 # occupancy MLP width (512 tried: no gain)
|
| 65 |
+
OCC_LAYERS = 3
|
| 66 |
+
OCC_TIME_DIM = 64
|
| 67 |
+
OCC_T = 100 # diffusion timesteps
|
| 68 |
+
OCC_TAU = 0.005 # occupancy Polyak rate (all read-outs use the EMA)
|
| 69 |
+
RT_ETA = 0.5 # reward-targeted stratification rate (exact IS weights)
|
| 70 |
+
N_ORDERS = 16 # gl order-average for targets and evals
|
| 71 |
+
N_ORDERS_PI = 4 # fewer orders inside the actor loss — the large
|
| 72 |
+
# batch absorbs the extra Monte-Carlo noise (~2x faster)
|
| 73 |
+
GAMMA_SPECTRUM_P = 0.5 # P(spectrum draw) vs task gamma, per occupancy tuple
|
| 74 |
+
FOURIER_K = 4 # sin/cos pairs of the log-horizon gamma encoding
|
| 75 |
+
REC_EVERY = 1 # compose every step (every-2 measured worse)
|
| 76 |
+
REC_MAX_DEPTH = 10 # chain cap; P(depth > 10) ~ 1e-3 at beta = 0.98
|
| 77 |
+
ACTOR_EMA_TAU = 0.005 # EMA actor for banking (load-bearing: the records
|
| 78 |
+
# are EMA-actor banks)
|
| 79 |
+
EVAL_EPISODES_PERIODIC = 15 # in-training eval size (overstates; see RESULTS.md)
|
| 80 |
+
STEPS_PER_DISPATCH = 100 # fused lax.scan window per host dispatch
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def run_rsm(env_id, seed=0, train_steps=2000000, alpha=1.0,
|
| 84 |
+
recursion="auto", rec_beta=0.98, rec_after=100000, rec_guard="off",
|
| 85 |
+
gamma_spectrum_lo=0.0, elbo_K=16,
|
| 86 |
+
elbo_logspace=False, elbo_antithetic=False,
|
| 87 |
+
batch_size=4096, occ_batch=2048,
|
| 88 |
+
eval_interval=25000, eval_episodes=50,
|
| 89 |
+
variant_tag=None, save_best=None, wandb_mode="online",
|
| 90 |
+
ogbench_impls=OGBENCH_IMPLS):
|
| 91 |
+
"""Train RSM on one OGBench environment. Returns the result-JSON path."""
|
| 92 |
+
_setup_paths(ogbench_impls)
|
| 93 |
+
import jax
|
| 94 |
+
import jax.numpy as jnp
|
| 95 |
+
import optax
|
| 96 |
+
import tqdm
|
| 97 |
+
import wandb
|
| 98 |
+
from utils.env_utils import make_env_and_datasets
|
| 99 |
+
from utils.evaluation import evaluate
|
| 100 |
+
from utils.networks import GCActor
|
| 101 |
+
import target_extractors
|
| 102 |
+
from train_genq_jax import build_ends, cosine_abar, make_model
|
| 103 |
+
from agents.gciql import get_config
|
| 104 |
+
|
| 105 |
+
# ===================================================================
|
| 106 |
+
# 0. Resolve the recipe from the goal space
|
| 107 |
+
# ===================================================================
|
| 108 |
+
# Discrete goal alphabets get the exact likelihood read-out; continuous
|
| 109 |
+
# coordinates get the ELBO read-out. Recursion is part of the recipe in
|
| 110 |
+
# BOTH spaces; the guard level differs (DESIGN.md section 3).
|
| 111 |
+
is_bits = env_id.startswith("puzzle")
|
| 112 |
+
readout = "gl" if is_bits else "elbo"
|
| 113 |
+
rec_guard = "off" if rec_guard == "none" else rec_guard # alias
|
| 114 |
+
assert not (is_bits and (elbo_logspace or elbo_antithetic)), \
|
| 115 |
+
"--elbo_logspace / --elbo_antithetic apply to the continuous ELBO read-out only"
|
| 116 |
+
rec_on = recursion == "on" or (recursion == "auto" and is_bits)
|
| 117 |
+
rec_p = (GAMMA - rec_beta) / (GAMMA * (1.0 - rec_beta)) if rec_on else 0.0
|
| 118 |
+
if rec_on:
|
| 119 |
+
# which parameters serve the policy evaluations INSIDE the chain
|
| 120 |
+
# (midpoint re-decisions + the actions continuation values are read at)
|
| 121 |
+
chain_pi_src = "EMA actor (lagged ~1/tau updates)" if rec_guard == "ema" \
|
| 122 |
+
else "live actor"
|
| 123 |
+
print(f"[rsm] rec_guard={rec_guard}: chain-internal re-decisions use the "
|
| 124 |
+
f"{chain_pi_src}", flush=True)
|
| 125 |
+
# the discount spectrum is only needed when chains hop at beta
|
| 126 |
+
spec_on = rec_on and gamma_spectrum_lo > 0.0
|
| 127 |
+
hop_disc = rec_beta if spec_on else GAMMA
|
| 128 |
+
|
| 129 |
+
assert eval_interval % STEPS_PER_DISPATCH == 0
|
| 130 |
+
t0 = time.time()
|
| 131 |
+
config = get_config() # reference GCActor sizes / lr / goal mix
|
| 132 |
+
config["actor_loss"] = "ddpgbc"
|
| 133 |
+
config["alpha"] = alpha
|
| 134 |
+
# batch is a QUALITY lever here: targets are simulation-based (occupancy
|
| 135 |
+
# samples + chain estimates), so a bigger batch directly averages
|
| 136 |
+
# generation noise — there is no TD backup to wait on.
|
| 137 |
+
config["batch_size"] = int(batch_size)
|
| 138 |
+
B_pi = int(config["batch_size"])
|
| 139 |
+
|
| 140 |
+
# ===================================================================
|
| 141 |
+
# 1. Dataset -> device arrays
|
| 142 |
+
# ===================================================================
|
| 143 |
+
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
|
| 144 |
+
obs_np = np.asarray(train_dataset["observations"], dtype=np.float32)
|
| 145 |
+
act_np = np.clip(np.asarray(train_dataset["actions"], dtype=np.float32), -1.0, 1.0)
|
| 146 |
+
end_np = build_ends(train_dataset["terminals"]) # end_np[i] = end of i's trajectory
|
| 147 |
+
N = len(obs_np)
|
| 148 |
+
a_dim = act_np.shape[1]
|
| 149 |
+
|
| 150 |
+
# z = the reward-relevant coordinates (puzzle: 9 button bits; mazes: x,y).
|
| 151 |
+
# This is the ONLY thing the occupancy models — see target_extractors.py.
|
| 152 |
+
tgt_np = target_extractors.extract_target(env_id, obs_np).astype(np.float32)
|
| 153 |
+
n_bits = tgt_np.shape[1]
|
| 154 |
+
tgt_mu_np, tgt_sd_np = tgt_np.mean(0), tgt_np.std(0) + 1e-6 # standardization
|
| 155 |
+
# (continuous z only)
|
| 156 |
+
|
| 157 |
+
obs_d = jnp.asarray(obs_np) # ~300 MB device-resident dataset
|
| 158 |
+
act_d = jnp.asarray(act_np)
|
| 159 |
+
tgt_d = jnp.asarray(tgt_np)
|
| 160 |
+
end_d = jnp.asarray(end_np.astype(np.int32))
|
| 161 |
+
tgt_mu_j, tgt_sd_j = jnp.asarray(tgt_mu_np), jnp.asarray(tgt_sd_np)
|
| 162 |
+
|
| 163 |
+
# ===================================================================
|
| 164 |
+
# 2. The occupancy model p(z | s, a, gamma~)
|
| 165 |
+
# ===================================================================
|
| 166 |
+
# One conditional diffusion MLP. Discrete goals: a masked DISCRETE
|
| 167 |
+
# diffusion over the bits (input = [current bits, mask]); continuous
|
| 168 |
+
# goals: a standard eps-prediction Gaussian diffusion over z.
|
| 169 |
+
# The condition is [s, a, goal-z, enc(gamma~)].
|
| 170 |
+
g_cols = 2 * FOURIER_K if spec_on else 0
|
| 171 |
+
cond_dim = obs_np.shape[1] + a_dim + n_bits + g_cols
|
| 172 |
+
occ_x_dim = 2 * n_bits if is_bits else n_bits
|
| 173 |
+
|
| 174 |
+
occ_model = make_model(cond_dim, n_bits, OCC_HIDDEN, OCC_LAYERS, OCC_TIME_DIM)
|
| 175 |
+
key = jax.random.PRNGKey(seed)
|
| 176 |
+
key, ik = jax.random.split(key)
|
| 177 |
+
occ_params = occ_model.init(ik, jnp.zeros((1, occ_x_dim)), jnp.zeros((1,)),
|
| 178 |
+
jnp.zeros((1, cond_dim)))
|
| 179 |
+
occ_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(OCC_LR))
|
| 180 |
+
occ_opt = occ_tx.init(occ_params)
|
| 181 |
+
occ_ema = jax.tree_util.tree_map(lambda x: x, occ_params) # read-outs use the EMA
|
| 182 |
+
|
| 183 |
+
abar = cosine_abar(OCC_T) # cosine noise schedule
|
| 184 |
+
abar_j = jnp.asarray(abar)
|
| 185 |
+
# per-bit unmasking timestep for the any-order discrete diffusion
|
| 186 |
+
kappas = np.arange(n_bits, dtype=np.float64) / n_bits
|
| 187 |
+
ts_frac = jnp.asarray(np.array(
|
| 188 |
+
[(1 + int(np.argmin(np.abs(abar - k)))) / OCC_T for k in kappas], dtype=np.float32))
|
| 189 |
+
logg = float(np.log(GAMMA))
|
| 190 |
+
|
| 191 |
+
# ---- discount spectrum: sample gamma~, encode it with Fourier features ----
|
| 192 |
+
# The chain needs Q at beta AND gamma from ONE model, so the occupancy is
|
| 193 |
+
# conditioned on gamma~ sampled log-uniformly IN HORIZON SPACE over
|
| 194 |
+
# [gamma_spectrum_lo, GAMMA]. The encoding is Fourier features of the
|
| 195 |
+
# normalized log-horizon u(gamma~): a raw gamma column cannot resolve a
|
| 196 |
+
# horizon that triples while gamma moves 0.04 (scalar/one-hot encodings
|
| 197 |
+
# were measured worse and are archived — DESIGN.md).
|
| 198 |
+
lo_h = float(np.log(1.0 / (1.0 - gamma_spectrum_lo))) if spec_on else 0.0
|
| 199 |
+
hi_h = float(np.log(1.0 / (1.0 - GAMMA)))
|
| 200 |
+
_fr_np = (np.pi * (2.0 ** np.arange(FOURIER_K))).astype(np.float32)
|
| 201 |
+
_fr_j = jnp.asarray(_fr_np)
|
| 202 |
+
|
| 203 |
+
def g_enc(dv):
|
| 204 |
+
u = (jnp.log(1.0 / (1.0 - dv)) - lo_h) / max(hi_h - lo_h, 1e-8)
|
| 205 |
+
ang = u[:, None] * _fr_j[None, :]
|
| 206 |
+
return jnp.concatenate([jnp.sin(ang), jnp.cos(ang)], -1)
|
| 207 |
+
|
| 208 |
+
def g_enc_np(dv):
|
| 209 |
+
u = (np.log(1.0 / (1.0 - dv)) - lo_h) / max(hi_h - lo_h, 1e-8)
|
| 210 |
+
ang = u[:, None] * _fr_np[None, :]
|
| 211 |
+
return np.concatenate([np.sin(ang), np.cos(ang)], -1).astype(np.float32)
|
| 212 |
+
|
| 213 |
+
# condition-normalization stats from a 20k-pair probe of the sampler
|
| 214 |
+
rng_np = np.random.default_rng(seed)
|
| 215 |
+
t_p = rng_np.integers(0, N, 20000)
|
| 216 |
+
gi_p = np.minimum(t_p + rng_np.geometric(1 - GAMMA, 20000), end_np[t_p] - 1)
|
| 217 |
+
|
| 218 |
+
def _np_gammas(n):
|
| 219 |
+
h = np.exp(rng_np.uniform(np.log(1.0 / (1.0 - gamma_spectrum_lo)),
|
| 220 |
+
np.log(1.0 / (1.0 - GAMMA)), n))
|
| 221 |
+
gam = 1.0 - 1.0 / h
|
| 222 |
+
return np.where(rng_np.random(n) >= GAMMA_SPECTRUM_P, GAMMA, gam)
|
| 223 |
+
|
| 224 |
+
gpart = [g_enc_np(_np_gammas(20000))] if spec_on else []
|
| 225 |
+
cond_p = np.concatenate([obs_np[t_p], act_np[t_p], tgt_np[gi_p]] + gpart, axis=1)
|
| 226 |
+
cond_mean = jnp.asarray(cond_p.mean(0))
|
| 227 |
+
cond_std = jnp.asarray(cond_p.std(0) + 1e-6)
|
| 228 |
+
|
| 229 |
+
actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]),
|
| 230 |
+
action_dim=a_dim, state_dependent_std=False,
|
| 231 |
+
const_std=config["const_std"])
|
| 232 |
+
|
| 233 |
+
# ===================================================================
|
| 234 |
+
# 3. Batch samplers (pure jnp; reference GCIQL goal-mix semantics)
|
| 235 |
+
# ===================================================================
|
| 236 |
+
def _geom(k, shape):
|
| 237 |
+
"""k ~ Geom(1-GAMMA), the discounted-occupancy horizon."""
|
| 238 |
+
u = jax.random.uniform(k, shape, minval=1e-6, maxval=1.0 - 1e-6)
|
| 239 |
+
return (jnp.floor(jnp.log1p(-u) / logg)).astype(jnp.int32) + 1
|
| 240 |
+
|
| 241 |
+
def _gammas(k, shape):
|
| 242 |
+
"""gamma~ per tuple: the task gamma w.p. 1-p, else a spectrum draw."""
|
| 243 |
+
if not spec_on:
|
| 244 |
+
return jnp.full(shape, GAMMA)
|
| 245 |
+
k1, k2 = jax.random.split(k)
|
| 246 |
+
h = jnp.exp(jax.random.uniform(k1, shape, minval=lo_h, maxval=hi_h))
|
| 247 |
+
return jnp.where(jax.random.uniform(k2, shape) >= GAMMA_SPECTRUM_P,
|
| 248 |
+
GAMMA, 1.0 - 1.0 / h)
|
| 249 |
+
|
| 250 |
+
def _ref_goals(k, t):
|
| 251 |
+
"""GCIQL's reference value-goal mix: 20% current / 50% future / 30% random."""
|
| 252 |
+
e1 = end_d[t] - 1
|
| 253 |
+
k1, k2, k3, k4 = jax.random.split(k, 4)
|
| 254 |
+
gi_traj = jnp.minimum(t + _geom(k1, t.shape), e1)
|
| 255 |
+
gi_rand = jax.random.randint(k2, t.shape, 0, N)
|
| 256 |
+
gi = jnp.where(jax.random.uniform(k3, t.shape) < 0.5 / 0.8, gi_traj, gi_rand)
|
| 257 |
+
return jnp.where(jax.random.uniform(k4, t.shape) < 0.2, t, gi)
|
| 258 |
+
|
| 259 |
+
def sample_pi_batch(k):
|
| 260 |
+
"""States + actor goals for the actor update."""
|
| 261 |
+
k0, kv, ka, kd = jax.random.split(k, 4)
|
| 262 |
+
t = jax.random.randint(k0, (B_pi,), 0, N)
|
| 263 |
+
_gi_v = _ref_goals(kv, t) # drawn to keep the RNG stream stable
|
| 264 |
+
e1 = (end_d[t] - 1).astype(jnp.float32)
|
| 265 |
+
lo = jnp.minimum(t + 1, end_d[t] - 1).astype(jnp.float32)
|
| 266 |
+
dfrac = jax.random.uniform(ka, (B_pi,))
|
| 267 |
+
gi_a = jnp.round(lo * dfrac + e1 * (1.0 - dfrac)).astype(jnp.int32)
|
| 268 |
+
return t, gi_a
|
| 269 |
+
|
| 270 |
+
def sample_occ_tuple(k):
|
| 271 |
+
"""One occupancy training tuple per row: condition, target z, weight.
|
| 272 |
+
|
| 273 |
+
The future index j is drawn from the truncated geometric at gamma~
|
| 274 |
+
with absorbing first-passage handling and reward-targeted
|
| 275 |
+
stratification: with prob RT_ETA take the goal index itself (a "hit"),
|
| 276 |
+
else a miss step — each branch importance-weighted exactly, so the
|
| 277 |
+
fit stays an unbiased MLE of the occupancy.
|
| 278 |
+
"""
|
| 279 |
+
ks = jax.random.split(k, 7)
|
| 280 |
+
t = jax.random.randint(ks[0], (occ_batch,), 0, N)
|
| 281 |
+
gi = _ref_goals(ks[1], t)
|
| 282 |
+
gam = _gammas(ks[6], t.shape)
|
| 283 |
+
lgam = jnp.log(gam)
|
| 284 |
+
in_traj = (gi >= t) & (gi < end_d[t])
|
| 285 |
+
L = (end_d[t] - t).astype(jnp.float32)
|
| 286 |
+
dd = jnp.clip((gi - t).astype(jnp.float32), 0.0, None)
|
| 287 |
+
gL = jnp.exp(L * lgam)
|
| 288 |
+
p_hit = jnp.where(in_traj, (jnp.exp(dd * lgam) - gL) / (1.0 - gL), 0.0)
|
| 289 |
+
take_hit = in_traj & ((jax.random.uniform(ks[2], t.shape) < RT_ETA) | (gi == t))
|
| 290 |
+
u = jax.random.uniform(ks[3], t.shape, minval=1e-6, maxval=1.0 - 1e-6)
|
| 291 |
+
pd = 1.0 - jnp.exp(jnp.maximum(dd, 1.0) * lgam)
|
| 292 |
+
k_miss = jnp.ceil(jnp.log1p(-u * pd) / lgam).astype(jnp.int32) - 1
|
| 293 |
+
k_miss = jnp.clip(k_miss, 0, jnp.maximum(gi - t - 1, 0))
|
| 294 |
+
u2 = jax.random.uniform(ks[4], t.shape, minval=1e-6, maxval=1.0 - 1e-6)
|
| 295 |
+
Fmax = jnp.maximum(1.0 - gL, 1e-12)
|
| 296 |
+
k_pl = jnp.clip(jnp.ceil(jnp.log1p(-u2 * Fmax) / lgam).astype(jnp.int32) - 1,
|
| 297 |
+
0, (end_d[t] - t) - 1)
|
| 298 |
+
j = jnp.where(take_hit, gi, jnp.where(in_traj, t + k_miss, t + k_pl))
|
| 299 |
+
w = jnp.ones((occ_batch,))
|
| 300 |
+
w = jnp.where(take_hit & (gi != t), p_hit / RT_ETA, w)
|
| 301 |
+
w = jnp.where(in_traj & ~take_hit, (1.0 - p_hit) / (1.0 - RT_ETA), w)
|
| 302 |
+
parts = [obs_d[t], act_d[t], tgt_d[gi]] + ([g_enc(gam)] if spec_on else [])
|
| 303 |
+
cond_raw = jnp.concatenate(parts, axis=1)
|
| 304 |
+
return cond_raw, tgt_d[j], w, j
|
| 305 |
+
|
| 306 |
+
# ===================================================================
|
| 307 |
+
# 4. Occupancy training step (diffusion MLE)
|
| 308 |
+
# ===================================================================
|
| 309 |
+
def occ_step(params, opt_state, ema, k):
|
| 310 |
+
k1, k2, k3 = jax.random.split(k, 3)
|
| 311 |
+
cond_raw, z_data, w, _j = sample_occ_tuple(k1)
|
| 312 |
+
t_int = jax.random.randint(k2, (occ_batch,), 1, OCC_T + 1)
|
| 313 |
+
|
| 314 |
+
if is_bits:
|
| 315 |
+
# masked discrete diffusion: BCE on the masked bits
|
| 316 |
+
keep = abar_j[t_int - 1]
|
| 317 |
+
m = (jax.random.uniform(k3, (occ_batch, n_bits)) >= keep[:, None]
|
| 318 |
+
).astype(jnp.float32)
|
| 319 |
+
|
| 320 |
+
def loss_fn(p):
|
| 321 |
+
c = (cond_raw - cond_mean) / cond_std
|
| 322 |
+
tf = t_int.astype(jnp.float32) / OCC_T
|
| 323 |
+
xt = (2.0 * z_data - 1.0) * (1.0 - m)
|
| 324 |
+
pred = occ_model.apply(p, jnp.concatenate([xt, m], -1), tf, c)
|
| 325 |
+
bce = optax.sigmoid_binary_cross_entropy(pred, z_data)
|
| 326 |
+
return (w[:, None] * bce * m).sum() / jnp.maximum(m.sum(), 1.0)
|
| 327 |
+
else:
|
| 328 |
+
# Gaussian eps-prediction diffusion on standardized z
|
| 329 |
+
eps_n = jax.random.normal(k3, (occ_batch, n_bits))
|
| 330 |
+
|
| 331 |
+
def loss_fn(p):
|
| 332 |
+
c = (cond_raw - cond_mean) / cond_std
|
| 333 |
+
tf = t_int.astype(jnp.float32) / OCC_T
|
| 334 |
+
z0 = (z_data - tgt_mu_j) / tgt_sd_j
|
| 335 |
+
ab = abar_j[t_int - 1][:, None]
|
| 336 |
+
zt = jnp.sqrt(ab) * z0 + jnp.sqrt(1.0 - ab) * eps_n
|
| 337 |
+
pred = occ_model.apply(p, zt, tf, c)
|
| 338 |
+
return (w[:, None] * (pred - eps_n) ** 2).mean()
|
| 339 |
+
|
| 340 |
+
loss, grads = jax.value_and_grad(loss_fn)(params)
|
| 341 |
+
updates, opt_state = occ_tx.update(grads, opt_state, params)
|
| 342 |
+
params = optax.apply_updates(params, updates)
|
| 343 |
+
ema = jax.tree_util.tree_map(lambda e, p: e * (1 - OCC_TAU) + p * OCC_TAU,
|
| 344 |
+
ema, params)
|
| 345 |
+
return params, opt_state, ema, loss
|
| 346 |
+
|
| 347 |
+
# ===================================================================
|
| 348 |
+
# 5. Q read-outs: occupancy -> value at the goal
|
| 349 |
+
# ===================================================================
|
| 350 |
+
def gl(ema, s, a, g, k, dv=None, n_ord=None):
|
| 351 |
+
"""Exact goal likelihood (discrete goals): teacher-forced any-order
|
| 352 |
+
autoregressive unmasking of the goal's bits. Exact per order, averaged
|
| 353 |
+
over n_ord random orders; zero hit-variance; differentiable in `a`."""
|
| 354 |
+
n_o = N_ORDERS if n_ord is None else n_ord
|
| 355 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 356 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 357 |
+
B = c.shape[0]
|
| 358 |
+
cc = jnp.repeat(c, n_o, axis=0)
|
| 359 |
+
BO = B * n_o
|
| 360 |
+
g01 = jnp.round(jnp.clip(jnp.repeat(g, n_o, axis=0), 0.0, 1.0))
|
| 361 |
+
k, sub = jax.random.split(k)
|
| 362 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BO, n_bits)), axis=-1)
|
| 363 |
+
rows = jnp.arange(BO)
|
| 364 |
+
|
| 365 |
+
def step(carry, i):
|
| 366 |
+
x, m, logp = carry
|
| 367 |
+
out = occ_model.apply(ema, jnp.concatenate([x, m], -1),
|
| 368 |
+
jnp.full((BO,), ts_frac[i]), cc)
|
| 369 |
+
idx = orders[:, i]
|
| 370 |
+
logit = out[rows, idx]
|
| 371 |
+
gbit = g01[rows, idx]
|
| 372 |
+
logp = logp + gbit * jax.nn.log_sigmoid(logit) + \
|
| 373 |
+
(1 - gbit) * jax.nn.log_sigmoid(-logit)
|
| 374 |
+
x = x.at[rows, idx].set(2.0 * gbit - 1.0)
|
| 375 |
+
m = m.at[rows, idx].set(0.0)
|
| 376 |
+
return (x, m, logp), None
|
| 377 |
+
|
| 378 |
+
init = (jnp.zeros((BO, n_bits)), jnp.ones((BO, n_bits)), jnp.zeros((BO,)))
|
| 379 |
+
(_, _, logp), _ = jax.lax.scan(step, init, jnp.arange(n_bits))
|
| 380 |
+
return jnp.exp(logp).reshape(B, n_o).mean(-1)
|
| 381 |
+
|
| 382 |
+
def q_elbo(ema, s, a, g, k, dv=None, n_ord=None, log_out=False):
|
| 383 |
+
"""ELBO read-out (continuous goals): the denoising loss evaluated AT
|
| 384 |
+
the goal's z is a monotone surrogate of -log p(g | s,a); Q =
|
| 385 |
+
exp(-loss). Point evaluation like `gl` (nothing sampled), works in
|
| 386 |
+
any goal space, one network apply per draw; K stratified timesteps
|
| 387 |
+
for variance. Recursion ratios cancel the unknown normalizer.
|
| 388 |
+
|
| 389 |
+
log_out=True returns -loss (log Q) directly — the --elbo_logspace
|
| 390 |
+
actor path uses it so no exp / floor-clip sits on the gradient.
|
| 391 |
+
--elbo_antithetic pairs the noise draws (+eps, -eps) sharing one
|
| 392 |
+
stratified t per pair (K draws = K/2 pairs, same total applies)."""
|
| 393 |
+
K = elbo_K if n_ord is None else n_ord
|
| 394 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 395 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 396 |
+
B = c.shape[0]
|
| 397 |
+
k1, k2 = jax.random.split(k)
|
| 398 |
+
if elbo_antithetic:
|
| 399 |
+
Kp = max(K // 2, 1) # antithetic: K = Kp pairs x 2
|
| 400 |
+
u = jax.random.uniform(k1, (B, Kp))
|
| 401 |
+
strat = (jnp.arange(Kp)[None, :] + u) / Kp
|
| 402 |
+
t_half = jnp.clip((strat * OCC_T).astype(jnp.int32) + 1, 1, OCC_T)
|
| 403 |
+
t_int = jnp.concatenate([t_half, t_half], -1).reshape(-1) # pair shares t
|
| 404 |
+
e_half = jax.random.normal(k2, (B, Kp, n_bits))
|
| 405 |
+
eps = jnp.concatenate([e_half, -e_half], 1).reshape(B * 2 * Kp, n_bits)
|
| 406 |
+
K = 2 * Kp
|
| 407 |
+
else:
|
| 408 |
+
u = jax.random.uniform(k1, (B, K)) # stratified t: draw i covers
|
| 409 |
+
strat = (jnp.arange(K)[None, :] + u) / K # quantile band i/K..(i+1)/K
|
| 410 |
+
t_int = jnp.clip((strat.reshape(-1) * OCC_T).astype(jnp.int32) + 1, 1, OCC_T)
|
| 411 |
+
eps = jax.random.normal(k2, (B * K, n_bits))
|
| 412 |
+
cc = jnp.repeat(c, K, axis=0)
|
| 413 |
+
zg = 2.0 * g - 1.0 if is_bits else (g - tgt_mu_j) / tgt_sd_j
|
| 414 |
+
zg = jnp.repeat(zg, K, axis=0)
|
| 415 |
+
ab = abar_j[t_int - 1][:, None]
|
| 416 |
+
zt = jnp.sqrt(ab) * zg + jnp.sqrt(1.0 - ab) * eps
|
| 417 |
+
pred = occ_model.apply(ema, zt, t_int.astype(jnp.float32) / OCC_T, cc)
|
| 418 |
+
loss = ((pred - eps) ** 2).mean(-1).reshape(B, K).mean(-1)
|
| 419 |
+
return -loss if log_out else jnp.exp(-loss)
|
| 420 |
+
|
| 421 |
+
if not is_bits:
|
| 422 |
+
gl = q_elbo # every downstream call site is read-out-agnostic
|
| 423 |
+
|
| 424 |
+
# ===================================================================
|
| 425 |
+
# 6. Occupancy SAMPLING (midpoints for the recursion chain)
|
| 426 |
+
# ===================================================================
|
| 427 |
+
def occ_bits(ema, s, a, g, k, dv, m_wide):
|
| 428 |
+
"""Discrete goals: ancestral any-order sampling of the bits — the
|
| 429 |
+
sampling twin of `gl` (Bernoulli per bit instead of teacher-forced)."""
|
| 430 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 431 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 432 |
+
B2 = c.shape[0]
|
| 433 |
+
cc = jnp.repeat(c, m_wide, axis=0)
|
| 434 |
+
BM = B2 * m_wide
|
| 435 |
+
k, sub = jax.random.split(k)
|
| 436 |
+
orders = jnp.argsort(jax.random.uniform(sub, (BM, n_bits)), axis=-1)
|
| 437 |
+
rows = jnp.arange(BM)
|
| 438 |
+
|
| 439 |
+
def stepf(carry, i):
|
| 440 |
+
x, m, kk = carry
|
| 441 |
+
out = occ_model.apply(ema, jnp.concatenate([x, m], -1),
|
| 442 |
+
jnp.full((BM,), ts_frac[i]), cc)
|
| 443 |
+
idx = orders[:, i]
|
| 444 |
+
kk, sub2 = jax.random.split(kk)
|
| 445 |
+
b = jax.random.bernoulli(sub2, jax.nn.sigmoid(out[rows, idx])).astype(
|
| 446 |
+
jnp.float32)
|
| 447 |
+
x = x.at[rows, idx].set(2.0 * b - 1.0)
|
| 448 |
+
m = m.at[rows, idx].set(0.0)
|
| 449 |
+
return (x, m, kk), None
|
| 450 |
+
|
| 451 |
+
init = (jnp.zeros((BM, n_bits)), jnp.ones((BM, n_bits)), k)
|
| 452 |
+
(x, _, _), _ = jax.lax.scan(stepf, init, jnp.arange(n_bits))
|
| 453 |
+
return ((x + 1.0) / 2.0).reshape(B2, m_wide, n_bits)
|
| 454 |
+
|
| 455 |
+
# 25-step deterministic DDIM schedule (continuous sampling + completion)
|
| 456 |
+
_ts_z = np.unique(np.linspace(OCC_T, 1, 25).round().astype(np.int32))[::-1].copy()
|
| 457 |
+
ts_z_now = jnp.asarray(_ts_z)
|
| 458 |
+
ts_z_nxt = jnp.asarray(np.concatenate([_ts_z[1:], [0]]).astype(np.int32))
|
| 459 |
+
|
| 460 |
+
def z_sample(ema, cond_norm, k):
|
| 461 |
+
"""Continuous goals: deterministic DDIM sample of z given the condition."""
|
| 462 |
+
B2 = cond_norm.shape[0]
|
| 463 |
+
z = jax.random.normal(k, (B2, n_bits))
|
| 464 |
+
|
| 465 |
+
def stepf(z, i2):
|
| 466 |
+
tn, tx = ts_z_now[i2], ts_z_nxt[i2]
|
| 467 |
+
ab_n = abar_j[tn - 1]
|
| 468 |
+
ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0)
|
| 469 |
+
eps = jnp.clip(occ_model.apply(
|
| 470 |
+
ema, z, jnp.full((B2,), tn.astype(jnp.float32) / OCC_T),
|
| 471 |
+
cond_norm), -6.0, 6.0)
|
| 472 |
+
z0h = (z - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8))
|
| 473 |
+
return jnp.sqrt(ab_x) * z0h + jnp.sqrt(1.0 - ab_x) * eps, None
|
| 474 |
+
|
| 475 |
+
z, _ = jax.lax.scan(stepf, z, jnp.arange(len(_ts_z)))
|
| 476 |
+
return z
|
| 477 |
+
|
| 478 |
+
def z_bits(ema, s, a, g, k, dv, m_wide):
|
| 479 |
+
"""Continuous twin of occ_bits: DDIM draws, back in the raw z scale."""
|
| 480 |
+
parts = [s, a, g] + ([g_enc(dv)] if spec_on else [])
|
| 481 |
+
c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std
|
| 482 |
+
B2 = c.shape[0]
|
| 483 |
+
cc = jnp.repeat(c, m_wide, axis=0)
|
| 484 |
+
z = z_sample(ema, cc, k)
|
| 485 |
+
z = jnp.clip((z + 1.0) / 2.0, 0.0, 1.0) if is_bits else z * tgt_sd_j + tgt_mu_j
|
| 486 |
+
return z.reshape(B2, m_wide, n_bits)
|
| 487 |
+
|
| 488 |
+
if not is_bits:
|
| 489 |
+
occ_bits = z_bits
|
| 490 |
+
|
| 491 |
+
# ===================================================================
|
| 492 |
+
# 7. Completion head + the beta-recursion chain
|
| 493 |
+
# ===================================================================
|
| 494 |
+
# The chain hops through GENERATED states: the occupancy proposes the
|
| 495 |
+
# next reward-relevant coordinates, the completion head (a small
|
| 496 |
+
# conditional Gaussian diffusion, co-trained on the same tuples with the
|
| 497 |
+
# coordinates teacher-forced) expands them to a full observation, and the
|
| 498 |
+
# live actor re-decides there. No dataset retrieval anywhere.
|
| 499 |
+
obs_dim = obs_np.shape[1]
|
| 500 |
+
obs_mu_j = jnp.asarray(obs_np.mean(0))
|
| 501 |
+
obs_sd_j = jnp.asarray(obs_np.std(0) + 1e-6)
|
| 502 |
+
_m_mu = jnp.full((n_bits,), 0.5) if is_bits else tgt_mu_j
|
| 503 |
+
_m_sd = jnp.full((n_bits,), 0.5) if is_bits else tgt_sd_j
|
| 504 |
+
c2_mean = jnp.concatenate([cond_mean, _m_mu])
|
| 505 |
+
c2_std = jnp.concatenate([cond_std, _m_sd])
|
| 506 |
+
cmpl_model = make_model(cond_dim + n_bits, obs_dim, OCC_HIDDEN, OCC_LAYERS,
|
| 507 |
+
OCC_TIME_DIM)
|
| 508 |
+
key, ik3 = jax.random.split(key)
|
| 509 |
+
cmpl_params = cmpl_model.init(ik3, jnp.zeros((1, obs_dim)), jnp.zeros((1,)),
|
| 510 |
+
jnp.zeros((1, cond_dim + n_bits)))
|
| 511 |
+
cmpl_tx = optax.chain(optax.clip_by_global_norm(10.0), optax.adamw(OCC_LR))
|
| 512 |
+
cmpl_opt = cmpl_tx.init(cmpl_params)
|
| 513 |
+
cmpl_ema = jax.tree_util.tree_map(lambda x: x, cmpl_params)
|
| 514 |
+
|
| 515 |
+
def cmpl_step(cp, co, ce, k, cond_raw, j, w):
|
| 516 |
+
"""One diffusion MLE step of the completion head."""
|
| 517 |
+
k1, k2 = jax.random.split(k)
|
| 518 |
+
t_int = jax.random.randint(k1, (occ_batch,), 1, OCC_T + 1)
|
| 519 |
+
eps = jax.random.normal(k2, (occ_batch, obs_dim))
|
| 520 |
+
c2 = (jnp.concatenate([cond_raw, tgt_d[j]], -1) - c2_mean) / c2_std
|
| 521 |
+
x0 = (obs_d[j] - obs_mu_j) / obs_sd_j
|
| 522 |
+
ab = abar_j[t_int - 1][:, None]
|
| 523 |
+
xt = jnp.sqrt(ab) * x0 + jnp.sqrt(1.0 - ab) * eps
|
| 524 |
+
|
| 525 |
+
def lf(pp):
|
| 526 |
+
pred = cmpl_model.apply(pp, xt, t_int.astype(jnp.float32) / OCC_T, c2)
|
| 527 |
+
return (w[:, None] * (pred - eps) ** 2).mean()
|
| 528 |
+
|
| 529 |
+
cl, gr = jax.value_and_grad(lf)(cp)
|
| 530 |
+
upd, co = cmpl_tx.update(gr, co, cp)
|
| 531 |
+
cp = optax.apply_updates(cp, upd)
|
| 532 |
+
ce = jax.tree_util.tree_map(lambda e, q: e * (1 - OCC_TAU) + q * OCC_TAU, ce, cp)
|
| 533 |
+
return cp, co, ce, cl
|
| 534 |
+
|
| 535 |
+
def cmpl_sample(ce, cond2_raw, k):
|
| 536 |
+
"""25-step DDIM sample of a full observation from the completion head."""
|
| 537 |
+
c2 = (cond2_raw - c2_mean) / c2_std
|
| 538 |
+
B2 = c2.shape[0]
|
| 539 |
+
x = jax.random.normal(k, (B2, obs_dim))
|
| 540 |
+
|
| 541 |
+
def stepf(x, i2):
|
| 542 |
+
tn, tx = ts_z_now[i2], ts_z_nxt[i2]
|
| 543 |
+
ab_n = abar_j[tn - 1]
|
| 544 |
+
ab_x = jnp.where(tx > 0, abar_j[jnp.maximum(tx - 1, 0)], 1.0)
|
| 545 |
+
eps = jnp.clip(cmpl_model.apply(
|
| 546 |
+
ce, x, jnp.full((B2,), tn.astype(jnp.float32) / OCC_T), c2), -6.0, 6.0)
|
| 547 |
+
x0h = (x - jnp.sqrt(1.0 - ab_n) * eps) / jnp.sqrt(jnp.maximum(ab_n, 1e-8))
|
| 548 |
+
return jnp.sqrt(ab_x) * x0h + jnp.sqrt(1.0 - ab_x) * eps, None
|
| 549 |
+
|
| 550 |
+
x, _ = jax.lax.scan(stepf, x, jnp.arange(len(_ts_z)))
|
| 551 |
+
return x * obs_sd_j + obs_mu_j
|
| 552 |
+
|
| 553 |
+
def mk_cond2(s, a, gb, mids):
|
| 554 |
+
parts = [s, a, gb] + \
|
| 555 |
+
([g_enc(jnp.full((s.shape[0],), hop_disc))] if spec_on else []) + [mids]
|
| 556 |
+
return jnp.concatenate(parts, -1)
|
| 557 |
+
|
| 558 |
+
def chain_prob(ema, ce, actor_params, s0, a0, gb, gobs, k):
|
| 559 |
+
"""The splitting-identity estimator (root README 2.4):
|
| 560 |
+
|
| 561 |
+
Q_gamma = (1-p) * gl_beta + p * E[ Q_gamma(next hop) ]
|
| 562 |
+
|
| 563 |
+
run as a coin-terminated walk: each level, alive rows flip the coin
|
| 564 |
+
(p = continuation), sample ONE beta-horizon midpoint, complete it to
|
| 565 |
+
a full state, and let the live actor re-decide there; dead rows
|
| 566 |
+
freeze. Fixed depth keeps jit shapes static; ONE gl read at every
|
| 567 |
+
row's final node is the estimate. Expectation form — no max."""
|
| 568 |
+
B2 = s0.shape[0]
|
| 569 |
+
dvh = jnp.full((B2,), hop_disc)
|
| 570 |
+
|
| 571 |
+
def level(carry, _):
|
| 572 |
+
s_cur, a_cur, alive, kk = carry
|
| 573 |
+
kk, kc, ks_, kx = jax.random.split(kk, 4)
|
| 574 |
+
cont = alive & (jax.random.uniform(kc, (B2,)) < rec_p)
|
| 575 |
+
mids = occ_bits(ema, s_cur, a_cur, gb, ks_, dvh, 1)[:, 0, :]
|
| 576 |
+
x_new = cmpl_sample(ce, mk_cond2(s_cur, a_cur, gb, mids), kx)
|
| 577 |
+
a_new = jnp.clip(actor_def.apply({"params": actor_params},
|
| 578 |
+
x_new, gobs).mode(), -1, 1)
|
| 579 |
+
s_cur = jnp.where(cont[:, None], x_new, s_cur)
|
| 580 |
+
a_cur = jnp.where(cont[:, None], a_new, a_cur)
|
| 581 |
+
return (s_cur, a_cur, cont, kk), None
|
| 582 |
+
|
| 583 |
+
(s_f, a_f, _, k), _ = jax.lax.scan(
|
| 584 |
+
level, (s0, a0, jnp.ones((B2,), bool), k), None, length=REC_MAX_DEPTH)
|
| 585 |
+
k, kg = jax.random.split(k)
|
| 586 |
+
return gl(ema, s_f, a_f, gb, kg, dvh)
|
| 587 |
+
|
| 588 |
+
# ===================================================================
|
| 589 |
+
# 8. Actor: anchored gradient ascent through the read-out
|
| 590 |
+
# ===================================================================
|
| 591 |
+
class _EvalAgent:
|
| 592 |
+
"""Minimal wrapper so the OGBench evaluate() loop can act."""
|
| 593 |
+
|
| 594 |
+
def __init__(self, params):
|
| 595 |
+
self.params = params
|
| 596 |
+
|
| 597 |
+
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0):
|
| 598 |
+
dist = actor_def.apply({"params": self.params}, observations, goals,
|
| 599 |
+
temperature=temperature)
|
| 600 |
+
return jnp.clip(dist.sample(seed=seed), -1, 1)
|
| 601 |
+
|
| 602 |
+
key, ik2 = jax.random.split(key)
|
| 603 |
+
actor_params = actor_def.init(ik2, obs_np[:2], obs_np[:2])["params"]
|
| 604 |
+
actor_tx = optax.adam(learning_rate=config["lr"])
|
| 605 |
+
agent = (actor_params, actor_tx.init(actor_params))
|
| 606 |
+
actor_of = lambda ag: ag[0]
|
| 607 |
+
eval_wrap = lambda ag: _EvalAgent(ag[0] if isinstance(ag, tuple) else ag)
|
| 608 |
+
|
| 609 |
+
def pi_step(ag, k, t, gi_a, ema, rec_aux, compose):
|
| 610 |
+
"""L(mu) = -log Q(s, mu(s), g) / |log Q| + alpha * BC.
|
| 611 |
+
|
| 612 |
+
With recursion on, Q is the chain estimate: the coin's tails branch is
|
| 613 |
+
a differentiated first-hop read; the heads branch multiplies the
|
| 614 |
+
(stop-gradient) tail value v1 by the likelihood ratio
|
| 615 |
+
num/den = gl(s,mu,c1)/gl(s,a,c1) — the actor's influence on reaching
|
| 616 |
+
the midpoint c1 (z is not reparameterizable, so gradients go through
|
| 617 |
+
the ratio, not the sample)."""
|
| 618 |
+
params, opt_state = ag
|
| 619 |
+
dv_t = jnp.full((B_pi,), GAMMA)
|
| 620 |
+
dv_h = jnp.full((B_pi,), hop_disc)
|
| 621 |
+
|
| 622 |
+
def loss_fn(pp):
|
| 623 |
+
dist = actor_def.apply({"params": pp}, obs_d[t], obs_d[gi_a])
|
| 624 |
+
mu = jnp.clip(dist.mode(), -1, 1)
|
| 625 |
+
k1, k2, k3 = jax.random.split(k, 3)
|
| 626 |
+
lg = {"log_out": True} if elbo_logspace else {}
|
| 627 |
+
if rec_on:
|
| 628 |
+
c1, den, v1 = rec_aux
|
| 629 |
+
# one goal-read serves both branches: hop discount while
|
| 630 |
+
# composing, task discount before rec_after kicks in
|
| 631 |
+
dv_sel = jnp.where(compose, dv_h, dv_t)
|
| 632 |
+
glb = gl(ema, obs_d[t], mu, tgt_d[gi_a], k1, dv_sel,
|
| 633 |
+
n_ord=N_ORDERS_PI, **lg)
|
| 634 |
+
num = gl(ema, obs_d[t], mu, c1, k2, dv_h, n_ord=N_ORDERS_PI, **lg)
|
| 635 |
+
# continuous-goal stability guards (unguarded chains collapse
|
| 636 |
+
# ~25k steps after composition, regardless of occupancy
|
| 637 |
+
# maturity — DESIGN.md section 3). Levels:
|
| 638 |
+
# "ratio": (a) common random numbers — the denominator
|
| 639 |
+
# re-reads with the SAME key as the numerator so the
|
| 640 |
+
# (t, eps) draws cancel in the ratio instead of being
|
| 641 |
+
# exploitable; (b) clip the ratio at 1 — the actor can
|
| 642 |
+
# never look better than the DATA action at reaching a
|
| 643 |
+
# generated midpoint. MEASURED INSUFFICIENT (collapsed
|
| 644 |
+
# at 125k like unguarded) — kept for the record.
|
| 645 |
+
# "tails": ratio guards + stop-gradient on the whole heads
|
| 646 |
+
# term, so the actor's gradient flows ONLY through the
|
| 647 |
+
# beta tails read at the true goal. MEASURED: first
|
| 648 |
+
# composing arm to SURVIVE on continuous goals (band
|
| 649 |
+
# intact 50k+ past the switch where all others died) —
|
| 650 |
+
# the heads gradient was the collapse mechanism (the
|
| 651 |
+
# clip bounds the ratio's value, not its gradient below
|
| 652 |
+
# 1). The stop-gradded heads value still shapes credit:
|
| 653 |
+
# it sits inside log(qv), damping the tails gradient on
|
| 654 |
+
# rows the chain already reaches.
|
| 655 |
+
# "ema": NO stop-grad anywhere — the composed objective is
|
| 656 |
+
# fully differentiated like the puzzle-record form. The
|
| 657 |
+
# collapse loop is instead broken TEMPORALLY: every
|
| 658 |
+
# policy evaluation inside the chain (the midpoint
|
| 659 |
+
# re-decisions a1 and chain_prob's per-level actions,
|
| 660 |
+
# computed in one_step) uses the banking EMA actor, so
|
| 661 |
+
# the chain's internal values lag the live actor by
|
| 662 |
+
# ~1/ACTOR_EMA_TAU updates and cannot co-adapt with it
|
| 663 |
+
# within an update.
|
| 664 |
+
if rec_guard in ("ratio", "tails"):
|
| 665 |
+
den = jax.lax.stop_gradient(
|
| 666 |
+
gl(ema, obs_d[t], act_d[t], c1, k2, dv_h,
|
| 667 |
+
n_ord=N_ORDERS_PI, **lg))
|
| 668 |
+
if elbo_logspace: # log-ratio, clipped at log 1 = 0
|
| 669 |
+
lratio = jnp.minimum(num - den, 0.0)
|
| 670 |
+
else:
|
| 671 |
+
ratio = jnp.minimum(num / jnp.maximum(den, 1e-6), 1.0)
|
| 672 |
+
else:
|
| 673 |
+
if elbo_logspace: # den precomputed in prob space (const)
|
| 674 |
+
lratio = num - jnp.log(jnp.maximum(den, 1e-6))
|
| 675 |
+
else:
|
| 676 |
+
ratio = num / jnp.maximum(den, 1e-6)
|
| 677 |
+
if elbo_logspace:
|
| 678 |
+
# log-space splitting identity: no exp / floor-clip on
|
| 679 |
+
# the differentiated path (v1 is a constant here)
|
| 680 |
+
heads_l = jnp.log(rec_p) + lratio + \
|
| 681 |
+
jnp.log(jnp.maximum(v1, 1e-30))
|
| 682 |
+
if rec_guard == "tails":
|
| 683 |
+
heads_l = jax.lax.stop_gradient(heads_l)
|
| 684 |
+
q_rec_l = jnp.logaddexp(jnp.log(1.0 - rec_p) + glb, heads_l)
|
| 685 |
+
q = jnp.where(compose, q_rec_l, glb)
|
| 686 |
+
else:
|
| 687 |
+
heads = rec_p * ratio * v1
|
| 688 |
+
if rec_guard == "tails":
|
| 689 |
+
heads = jax.lax.stop_gradient(heads)
|
| 690 |
+
q_rec = (1.0 - rec_p) * glb + heads
|
| 691 |
+
qv = jnp.where(compose, q_rec, glb)
|
| 692 |
+
else:
|
| 693 |
+
qv = gl(ema, obs_d[t], mu, tgt_d[gi_a], k1, dv_t,
|
| 694 |
+
n_ord=N_ORDERS_PI, **lg)
|
| 695 |
+
if elbo_logspace:
|
| 696 |
+
q = qv
|
| 697 |
+
if not elbo_logspace:
|
| 698 |
+
q = jnp.log(jnp.maximum(qv, 1e-9))
|
| 699 |
+
q_loss = -q.mean() / jax.lax.stop_gradient(jnp.abs(q).mean() + 1e-6)
|
| 700 |
+
bc = -dist.log_prob(act_d[t]).mean()
|
| 701 |
+
return q_loss + alpha * bc
|
| 702 |
+
|
| 703 |
+
loss, grads = jax.value_and_grad(loss_fn)(params)
|
| 704 |
+
updates, opt_state = actor_tx.update(grads, opt_state, params)
|
| 705 |
+
return (optax.apply_updates(params, updates), opt_state), loss
|
| 706 |
+
|
| 707 |
+
# ===================================================================
|
| 708 |
+
# 9. One fused training step (occupancy -> completion -> actor -> EMAs)
|
| 709 |
+
# ===================================================================
|
| 710 |
+
def one_step(carry, _):
|
| 711 |
+
occ_p, occ_o, ema, cm_p, cm_o, cm_e, ag, ema_actor, k, step = carry
|
| 712 |
+
# 9-way split kept from the multi-variant era so RNG streams (and
|
| 713 |
+
# therefore trained parameters) stay reproducible across versions
|
| 714 |
+
k, k1, k2, k3, k4, k5, k6, k7, k8 = jax.random.split(k, 9)
|
| 715 |
+
compose = (step > rec_after) & ((step % REC_EVERY) == 0)
|
| 716 |
+
|
| 717 |
+
occ_p, occ_o, ema, occ_l = occ_step(occ_p, occ_o, ema, k1)
|
| 718 |
+
if rec_on:
|
| 719 |
+
cond2, _z, w2, j2 = sample_occ_tuple(k5)
|
| 720 |
+
cm_p, cm_o, cm_e, _cl = cmpl_step(cm_p, cm_o, cm_e, k6, cond2, j2, w2)
|
| 721 |
+
|
| 722 |
+
t, gi_a = sample_pi_batch(k2)
|
| 723 |
+
rec_aux = ()
|
| 724 |
+
if rec_on:
|
| 725 |
+
# pre-compute the (non-differentiated) chain quantities: first
|
| 726 |
+
# midpoint c1, its density under the DATA action (the IS
|
| 727 |
+
# denominator), and the chain value from the first hop onward
|
| 728 |
+
dv_h = jnp.full((B_pi,), hop_disc)
|
| 729 |
+
c1 = occ_bits(ema, obs_d[t], act_d[t], tgt_d[gi_a], k7, dv_h, 1)[:, 0, :]
|
| 730 |
+
k8a, k8b, k8c = jax.random.split(k8, 3)
|
| 731 |
+
den = gl(ema, obs_d[t], act_d[t], c1, k8a, dv_h)
|
| 732 |
+
x1 = cmpl_sample(cm_e, mk_cond2(obs_d[t], act_d[t], tgt_d[gi_a], c1), k8b)
|
| 733 |
+
# rec_guard="ema": ALL chain-internal policy evaluations (the
|
| 734 |
+
# first-hop re-decision a1 and every level inside chain_prob)
|
| 735 |
+
# come from the lagged EMA actor, not the live one — see the
|
| 736 |
+
# guard notes in pi_step
|
| 737 |
+
chain_pi = ema_actor if rec_guard == "ema" else actor_of(ag)
|
| 738 |
+
a1 = jnp.clip(actor_def.apply({"params": chain_pi},
|
| 739 |
+
x1, obs_d[gi_a]).mode(), -1, 1)
|
| 740 |
+
v1 = jnp.clip(chain_prob(ema, cm_e, chain_pi, x1, a1,
|
| 741 |
+
tgt_d[gi_a], obs_d[gi_a], k8c), 0.0, 1.0)
|
| 742 |
+
rec_aux = (c1, jax.lax.stop_gradient(den), v1)
|
| 743 |
+
|
| 744 |
+
ag, pi_l = pi_step(ag, k4, t, gi_a, ema, rec_aux, compose)
|
| 745 |
+
ema_actor = jax.tree_util.tree_map(
|
| 746 |
+
lambda e, p: e * (1 - ACTOR_EMA_TAU) + p * ACTOR_EMA_TAU,
|
| 747 |
+
ema_actor, actor_of(ag))
|
| 748 |
+
return (occ_p, occ_o, ema, cm_p, cm_o, cm_e, ag, ema_actor, k, step + 1), \
|
| 749 |
+
(occ_l, pi_l)
|
| 750 |
+
|
| 751 |
+
dispatch = jax.jit(
|
| 752 |
+
lambda carry: jax.lax.scan(one_step, carry, None, length=STEPS_PER_DISPATCH))
|
| 753 |
+
|
| 754 |
+
# ===================================================================
|
| 755 |
+
# 10. Train / evaluate / bank
|
| 756 |
+
# ===================================================================
|
| 757 |
+
ema_actor = jax.tree_util.tree_map(lambda x: x, actor_of(agent))
|
| 758 |
+
vtag = f"_{variant_tag}" if variant_tag else ""
|
| 759 |
+
run = wandb.init(project="gen-q-policy-improvement",
|
| 760 |
+
name=f"rsm{vtag}-{env_id}-s{seed}", mode=wandb_mode,
|
| 761 |
+
tags=["rsm", env_id],
|
| 762 |
+
config=dict(method="rsm", env=env_id, seed=seed,
|
| 763 |
+
readout=readout, alpha=alpha,
|
| 764 |
+
recursion=("prob" if rec_on else "off"),
|
| 765 |
+
rec_beta=rec_beta, rec_after=rec_after,
|
| 766 |
+
rec_guard=str(rec_guard),
|
| 767 |
+
elbo_logspace=elbo_logspace,
|
| 768 |
+
elbo_antithetic=elbo_antithetic,
|
| 769 |
+
gamma_spectrum_lo=gamma_spectrum_lo,
|
| 770 |
+
batch_size=B_pi, occ_batch=occ_batch,
|
| 771 |
+
train_steps=train_steps),
|
| 772 |
+
settings=wandb.Settings(start_method="thread"))
|
| 773 |
+
print(f"[fast] WANDB_URL {run.get_url()}", flush=True)
|
| 774 |
+
eval_success = _make_eval_fn(env, config, evaluate, jax, wrap=eval_wrap)
|
| 775 |
+
# ---- always-on read-out calibration probe (mirrors genq_joint.py's
|
| 776 |
+
# elbo/q_self-vs-q_rand diagnostic): Q at the row's OWN target (d=0 —
|
| 777 |
+
# absorbing first-passage calibration says ~1) vs a permuted random
|
| 778 |
+
# target, data actions, task gamma. A collapsing self/rand log-gap is
|
| 779 |
+
# the flat-Q pathology; logged every eval, costs one 256-row read.
|
| 780 |
+
_calib_read = jax.jit(lambda em, s, a, g, kk: gl(
|
| 781 |
+
em, s, a, g, kk, jnp.full((s.shape[0],), GAMMA)))
|
| 782 |
+
calib_key = jax.random.PRNGKey(seed + 777) # separate stream: training
|
| 783 |
+
# RNG chain stays untouched
|
| 784 |
+
out = os.path.join(_result_dir(env_id, seed), f"rsm{vtag}.json")
|
| 785 |
+
curve = []
|
| 786 |
+
best = {"sr": -1.0, "agent": None}
|
| 787 |
+
best_saved = [-1.0]
|
| 788 |
+
final_info = {}
|
| 789 |
+
|
| 790 |
+
def dump(sr, per):
|
| 791 |
+
json.dump({"method": "rsm", "readout": readout, "env": env_id,
|
| 792 |
+
"seed": seed, "alpha": alpha,
|
| 793 |
+
"recursion": ("prob" if rec_on else "off"),
|
| 794 |
+
"rec_after": rec_after, "rec_beta": rec_beta,
|
| 795 |
+
"rec_guard": str(rec_guard),
|
| 796 |
+
"elbo_logspace": elbo_logspace,
|
| 797 |
+
"elbo_antithetic": elbo_antithetic,
|
| 798 |
+
"gamma_spectrum_lo": gamma_spectrum_lo,
|
| 799 |
+
"success_rate": sr,
|
| 800 |
+
"best_sr": (max(v for _, v in curve) if curve else sr), **final_info,
|
| 801 |
+
"per_task": per, "curve": curve, "train_steps": train_steps,
|
| 802 |
+
"wall_clock_sec": round(time.time() - t0, 1),
|
| 803 |
+
"wandb_url": run.get_url()}, open(out, "w"), indent=2)
|
| 804 |
+
|
| 805 |
+
carry = (occ_params, occ_opt, occ_ema, cmpl_params, cmpl_opt, cmpl_ema,
|
| 806 |
+
agent, ema_actor, key, jnp.asarray(0))
|
| 807 |
+
n_disp = train_steps // STEPS_PER_DISPATCH
|
| 808 |
+
tw = time.time()
|
| 809 |
+
for di in tqdm.trange(1, n_disp + 1, smoothing=0.05, dynamic_ncols=True):
|
| 810 |
+
carry, (occ_ls, pi_ls) = dispatch(carry)
|
| 811 |
+
i = di * STEPS_PER_DISPATCH
|
| 812 |
+
if di == 3:
|
| 813 |
+
jax.block_until_ready(carry[0])
|
| 814 |
+
rate = 3 * STEPS_PER_DISPATCH / (time.time() - tw)
|
| 815 |
+
print(f"[fast] throughput ~{rate:.1f} steps/s "
|
| 816 |
+
f"({train_steps / rate / 3600:.1f} h for {train_steps} steps)",
|
| 817 |
+
flush=True)
|
| 818 |
+
if i % 1000 == 0:
|
| 819 |
+
wandb.log({"occ/loss": float(occ_ls.mean()),
|
| 820 |
+
"train/pi_loss": float(pi_ls.mean())}, step=i)
|
| 821 |
+
if i % eval_interval != 0:
|
| 822 |
+
continue
|
| 823 |
+
# ---- periodic eval: live actor AND the EMA actor; bank the winner ----
|
| 824 |
+
ag = carry[6]
|
| 825 |
+
sr, per = eval_success(ag, EVAL_EPISODES_PERIODIC)
|
| 826 |
+
if sr >= best["sr"]:
|
| 827 |
+
best["sr"], best["agent"] = sr, ag
|
| 828 |
+
ema_ag = (carry[7], ag[1])
|
| 829 |
+
sr_e, per_e = eval_success(ema_ag, EVAL_EPISODES_PERIODIC)
|
| 830 |
+
if sr_e >= best["sr"]:
|
| 831 |
+
best["sr"], best["agent"] = sr_e, ema_ag
|
| 832 |
+
wandb.log({"eval/success_rate_ema": sr_e}, step=i)
|
| 833 |
+
curve.append((i, sr))
|
| 834 |
+
wandb.log({"eval/success_rate": sr,
|
| 835 |
+
"eval/peak": max(v for _, v in curve)}, step=i)
|
| 836 |
+
# ---- calibration probe (always on) ----
|
| 837 |
+
nD = 256
|
| 838 |
+
iD = rng_np.integers(0, N, nD)
|
| 839 |
+
calib_key, ck1, ck2 = jax.random.split(calib_key, 3)
|
| 840 |
+
q_self = np.asarray(_calib_read(carry[2], obs_d[iD], act_d[iD],
|
| 841 |
+
tgt_d[iD], ck1))
|
| 842 |
+
q_rand = np.asarray(_calib_read(carry[2], obs_d[iD], act_d[iD],
|
| 843 |
+
tgt_d[rng_np.permutation(iD)], ck2))
|
| 844 |
+
log_gap = float(np.log(np.maximum(q_self, 1e-12)).mean()
|
| 845 |
+
- np.log(np.maximum(q_rand, 1e-12)).mean())
|
| 846 |
+
wandb.log({"calib/q_self": float(q_self.mean()),
|
| 847 |
+
"calib/q_rand": float(q_rand.mean()),
|
| 848 |
+
"calib/log_gap": log_gap}, step=i)
|
| 849 |
+
print(f"[fast] step {i} sr={sr:.3f} ema={sr_e:.3f} "
|
| 850 |
+
f"(peak {max(v for _, v in curve):.3f}) occ_loss={float(occ_ls.mean()):.4f} "
|
| 851 |
+
f"calib q_self={q_self.mean():.4f} q_rand={q_rand.mean():.4f} "
|
| 852 |
+
f"log_gap={log_gap:.3f}",
|
| 853 |
+
flush=True)
|
| 854 |
+
dump(sr, per)
|
| 855 |
+
if save_best and best["agent"] is not None and best["sr"] > best_saved[0]:
|
| 856 |
+
# bank the best snapshot so it can be 50-ep evaluated offline
|
| 857 |
+
import pickle
|
| 858 |
+
bp = {"modules_actor": (best["agent"][0]
|
| 859 |
+
if isinstance(best["agent"], tuple)
|
| 860 |
+
else best["agent"])}
|
| 861 |
+
with open(save_best, "wb") as fbest:
|
| 862 |
+
pickle.dump({"params": jax.device_get(bp),
|
| 863 |
+
"config": dict(config), "step": i,
|
| 864 |
+
"periodic_sr": best["sr"]}, fbest)
|
| 865 |
+
best_saved[0] = best["sr"]
|
| 866 |
+
print(f"[fast] best snapshot (periodic {best['sr']:.3f}) saved -> "
|
| 867 |
+
f"{save_best}", flush=True)
|
| 868 |
+
|
| 869 |
+
# ---- final: 50-episode officials of the last-step AND banked agents ----
|
| 870 |
+
ag = carry[6]
|
| 871 |
+
sr_last, per = eval_success(ag, eval_episodes)
|
| 872 |
+
curve.append((train_steps, sr_last))
|
| 873 |
+
sr = sr_last
|
| 874 |
+
final_info["final_last_step"] = sr_last
|
| 875 |
+
if best["agent"] is not None:
|
| 876 |
+
sr_b, per_b = eval_success(best["agent"], eval_episodes)
|
| 877 |
+
final_info["final_best_ckpt"] = sr_b
|
| 878 |
+
final_info["best_ckpt_periodic_sr"] = best["sr"]
|
| 879 |
+
print(f"[fast] best-ckpt (periodic {best['sr']:.3f}) 50-ep FINAL sr={sr_b:.3f} "
|
| 880 |
+
f"vs last-step {sr_last:.3f}", flush=True)
|
| 881 |
+
if sr_b > sr:
|
| 882 |
+
sr, per = sr_b, per_b
|
| 883 |
+
dump(sr, per)
|
| 884 |
+
print(f"[fast] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}",
|
| 885 |
+
flush=True)
|
| 886 |
+
wandb.finish()
|
| 887 |
+
return out
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def main():
|
| 891 |
+
import argparse
|
| 892 |
+
ap = argparse.ArgumentParser(
|
| 893 |
+
description="RSM (Recursive Successor Model): occupancy + actor, no "
|
| 894 |
+
"critic/TD. Read-out auto-selected by goal space: exact "
|
| 895 |
+
"likelihood (discrete) / diffusion-ELBO (continuous). "
|
| 896 |
+
"Settled recipe values are constants in rsm.py, not flags.")
|
| 897 |
+
ap.add_argument("--env", required=True, help="OGBench env id")
|
| 898 |
+
ap.add_argument("--goal_space", default="auto",
|
| 899 |
+
choices=["auto", "discrete", "continuous"],
|
| 900 |
+
help="auto: puzzle-* -> discrete (gl read-out), otherwise "
|
| 901 |
+
"continuous (ELBO read-out)")
|
| 902 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 903 |
+
ap.add_argument("--train_steps", type=int, default=2000000)
|
| 904 |
+
ap.add_argument("--alpha", type=float, default=None,
|
| 905 |
+
help="BC weight. Default: 1.0 discrete / 0.03 continuous. "
|
| 906 |
+
"Per-env: take the GCIQL reference value as the LOWER "
|
| 907 |
+
"bracket and start ~10x it (see README.md)")
|
| 908 |
+
ap.add_argument("--recursion", default="auto", choices=["auto", "on", "off"],
|
| 909 |
+
help="beta-recursion. auto: ON for both goal spaces "
|
| 910 |
+
"(the unified recipe; continuous goals get the "
|
| 911 |
+
"tails guard — see --rec_guard)")
|
| 912 |
+
ap.add_argument("--rec_beta", type=float, default=0.98)
|
| 913 |
+
ap.add_argument("--rec_after", type=int, default=100000)
|
| 914 |
+
ap.add_argument("--rec_guard", default="auto",
|
| 915 |
+
choices=["auto", "off", "none", "ratio", "tails", "ema"],
|
| 916 |
+
help="recursion guard level. auto: off on discrete "
|
| 917 |
+
"(fully differentiated heads — the puzzle records) "
|
| 918 |
+
"/ tails on continuous (stop-grad heads — the only "
|
| 919 |
+
"form that survives there; ratio-only was measured "
|
| 920 |
+
"insufficient). ema: fully differentiated heads, "
|
| 921 |
+
"but all chain-internal policy evaluations use the "
|
| 922 |
+
"lagged banking-EMA actor (temporal break of the "
|
| 923 |
+
"self-amplifying loop instead of a gradient stop). "
|
| 924 |
+
"none = off.")
|
| 925 |
+
ap.add_argument("--gamma_spectrum_lo", type=float, default=None,
|
| 926 |
+
help="discount-spectrum lower edge (default 0.95 when "
|
| 927 |
+
"recursion is on, 0 otherwise)")
|
| 928 |
+
ap.add_argument("--elbo_K", type=int, default=16,
|
| 929 |
+
help="ELBO read-out draws (continuous goals)")
|
| 930 |
+
ap.add_argument("--elbo_logspace", action="store_true",
|
| 931 |
+
help="actor objective uses -L (log Q) from the ELBO read "
|
| 932 |
+
"directly — no exp, no 1e-9 floor-clip on the "
|
| 933 |
+
"gradient path; value/target-side exp(-L) unchanged "
|
| 934 |
+
"(continuous goals only)")
|
| 935 |
+
ap.add_argument("--elbo_antithetic", action="store_true",
|
| 936 |
+
help="ELBO reads use antithetic +/-eps pairs sharing a "
|
| 937 |
+
"stratified t per pair (K draws = K/2 pairs; "
|
| 938 |
+
"continuous goals only)")
|
| 939 |
+
ap.add_argument("--batch_size", type=int, default=4096)
|
| 940 |
+
ap.add_argument("--occ_batch", type=int, default=2048)
|
| 941 |
+
ap.add_argument("--eval_interval", type=int, default=25000)
|
| 942 |
+
ap.add_argument("--eval_episodes", type=int, default=50)
|
| 943 |
+
ap.add_argument("--variant_tag", default=None)
|
| 944 |
+
ap.add_argument("--save_best", default=None,
|
| 945 |
+
help="bank the best (live-or-EMA) actor snapshot here")
|
| 946 |
+
ap.add_argument("--wandb_mode", default="online")
|
| 947 |
+
a = ap.parse_args()
|
| 948 |
+
|
| 949 |
+
is_discrete = (a.env.startswith("puzzle") if a.goal_space == "auto"
|
| 950 |
+
else a.goal_space == "discrete")
|
| 951 |
+
assert not (is_discrete and not a.env.startswith("puzzle")), \
|
| 952 |
+
"discrete goal space currently implies a puzzle-* extractor"
|
| 953 |
+
alpha = a.alpha if a.alpha is not None else (1.0 if is_discrete else 0.03)
|
| 954 |
+
# ONE recipe for both spaces (owner 2026-07-16): recursion is on
|
| 955 |
+
# everywhere; the goal space picks only what it must — the read-out
|
| 956 |
+
# (exact gl vs ELBO), the BC weight, and the guard level (continuous
|
| 957 |
+
# heads gradients collapse training, so continuous composes with the
|
| 958 |
+
# tails guard: stop-grad heads, gradient through the beta tails read).
|
| 959 |
+
recursion = a.recursion if a.recursion != "auto" else "on"
|
| 960 |
+
rec_guard = a.rec_guard if a.rec_guard != "auto" else \
|
| 961 |
+
("off" if is_discrete else "tails")
|
| 962 |
+
spec_lo = a.gamma_spectrum_lo if a.gamma_spectrum_lo is not None else \
|
| 963 |
+
(0.95 if recursion == "on" else 0.0)
|
| 964 |
+
|
| 965 |
+
run_rsm(a.env, seed=a.seed, train_steps=a.train_steps, alpha=alpha,
|
| 966 |
+
recursion=recursion, rec_beta=a.rec_beta, rec_after=a.rec_after,
|
| 967 |
+
rec_guard=rec_guard, gamma_spectrum_lo=spec_lo, elbo_K=a.elbo_K,
|
| 968 |
+
elbo_logspace=a.elbo_logspace, elbo_antithetic=a.elbo_antithetic,
|
| 969 |
+
batch_size=a.batch_size, occ_batch=a.occ_batch,
|
| 970 |
+
eval_interval=a.eval_interval, eval_episodes=a.eval_episodes,
|
| 971 |
+
variant_tag=a.variant_tag, save_best=a.save_best,
|
| 972 |
+
wandb_mode=a.wandb_mode)
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
if __name__ == "__main__":
|
| 976 |
+
main()
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_a03r500_s225k.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
cd /proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/genq-rec-puzzle3x3-fix
|
| 3 |
+
source .env 2>/dev/null || true
|
| 4 |
+
export OGBENCH_IMPLS=$HOME/ogbench_ref/impls
|
| 5 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 6 |
+
export WANDB_MODE=disabled
|
| 7 |
+
.ogbench_venv/bin/python ogbench_genq/eval_plan.py --env_id pointmaze-medium-navigate-v0 \
|
| 8 |
+
--actor_pkl ogbench_genq/checkpoints/best_pm2M_elboNW_a03r500_s225k_p947.pkl \
|
| 9 |
+
--plan_k 1 --episodes 50 --vec 25 \
|
| 10 |
+
> ogbench_genq/scripts/logs/eval_a03r500_s225k.log 2>&1
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_a03r500_s225k_confirm.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
cd /proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/genq-rec-puzzle3x3-fix
|
| 3 |
+
source .env 2>/dev/null || true
|
| 4 |
+
export OGBENCH_IMPLS=$HOME/ogbench_ref/impls
|
| 5 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 6 |
+
export WANDB_MODE=disabled
|
| 7 |
+
.ogbench_venv/bin/python ogbench_genq/eval_plan.py --env_id pointmaze-medium-navigate-v0 \
|
| 8 |
+
--actor_pkl ogbench_genq/checkpoints/best_pm2M_elboNW_a03r500_s225k_p947.pkl \
|
| 9 |
+
--plan_k 1 --episodes 50 --vec 25 --seed 1 \
|
| 10 |
+
> ogbench_genq/scripts/logs/eval_a03r500_s225k_confirm.log 2>&1
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_antmaze_lg_p427.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Two-read official: antmaze-large-navigate a3, bank 0.427 @200k vs official bar 0.34 (#61).
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
cd "$(dirname "$0")/../../.."
|
| 5 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 6 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 7 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 8 |
+
PY=.ogbench_venv/bin/python
|
| 9 |
+
E=antmaze-large-navigate-v0
|
| 10 |
+
R=ogbench_genq/experiments/$E/results
|
| 11 |
+
mkdir -p $R/0 $R/1
|
| 12 |
+
for rd in 1 2; do
|
| 13 |
+
seed=$((rd - 1))
|
| 14 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 15 |
+
--actor_pkl ckpt/best_rsm_antmaze_lg_a3_s200k_p427.pkl \
|
| 16 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 17 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_antmaze_lg_a3_s200k_p427_read${rd}.json
|
| 18 |
+
echo "[official] antmaze_lg read$rd done"
|
| 19 |
+
done
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_antmaze_med_p813.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Two-read official: antmaze-medium S1 default arm, bank 0.813 @1M vs official bar 0.71 (#61).
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
cd "$(dirname "$0")/../../.."
|
| 5 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 6 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 7 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 8 |
+
PY=.ogbench_venv/bin/python
|
| 9 |
+
E=antmaze-medium-navigate-v0
|
| 10 |
+
R=ogbench_genq/experiments/$E/results
|
| 11 |
+
mkdir -p $R/0 $R/1
|
| 12 |
+
for rd in 1 2; do
|
| 13 |
+
seed=$((rd - 1))
|
| 14 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 15 |
+
--actor_pkl ckpt/best_rsm_antmaze_med_s1_1M_p813.pkl \
|
| 16 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 17 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_antmaze_med_s1_1M_p813_read${rd}.json
|
| 18 |
+
echo "[official] antmaze_med read$rd done"
|
| 19 |
+
done
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_cube_a3_75k.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Two-read officials for BOTH cube-single S2 banks, sequential (eval_plan
|
| 3 |
+
# writes results/<eval-seed>/eval_plan_plan.json — concurrent runs clobber):
|
| 4 |
+
# alpha=3 bank @25k (periodic 0.907) -> official_rsm_cube_a3_s25k_read{1,2}
|
| 5 |
+
# alpha=10 bank @50k (periodic 0.960) -> official_rsm_cube_a10_s50k_read{1,2}
|
| 6 |
+
# Bar: GCIQL 0.595 (5-seed best, closed PR #42).
|
| 7 |
+
set -euo pipefail
|
| 8 |
+
cd "$(dirname "$0")/../../.." # repo root (worktree)
|
| 9 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 10 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 11 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 12 |
+
PY=${PYTHON:-}; [ -z "$PY" ] && [ -x .ogbench_venv/bin/python ] && PY=.ogbench_venv/bin/python; PY=${PY:-python}
|
| 13 |
+
E=cube-single-play-v0
|
| 14 |
+
R=ogbench_genq/experiments/$E/results
|
| 15 |
+
|
| 16 |
+
for arm in a3_s75k_p947; do
|
| 17 |
+
short=${arm%_p*} # a3_s25k / a10_s50k
|
| 18 |
+
for rd in 1 2; do
|
| 19 |
+
seed=$((rd - 1))
|
| 20 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 21 |
+
--actor_pkl ckpt/best_rsm_cube_${arm}.pkl \
|
| 22 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 23 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_cube_${short}_read${rd}.json
|
| 24 |
+
echo "[official] cube $short read$rd done"
|
| 25 |
+
done
|
| 26 |
+
done
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_cube_officials.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Two-read officials for BOTH cube-single S2 banks, sequential (eval_plan
|
| 3 |
+
# writes results/<eval-seed>/eval_plan_plan.json — concurrent runs clobber):
|
| 4 |
+
# alpha=3 bank @25k (periodic 0.907) -> official_rsm_cube_a3_s25k_read{1,2}
|
| 5 |
+
# alpha=10 bank @50k (periodic 0.960) -> official_rsm_cube_a10_s50k_read{1,2}
|
| 6 |
+
# Bar: GCIQL 0.595 (5-seed best, closed PR #42).
|
| 7 |
+
set -euo pipefail
|
| 8 |
+
cd "$(dirname "$0")/../../.." # repo root (worktree)
|
| 9 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 10 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 11 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 12 |
+
PY=${PYTHON:-}; [ -z "$PY" ] && [ -x .ogbench_venv/bin/python ] && PY=.ogbench_venv/bin/python; PY=${PY:-python}
|
| 13 |
+
E=cube-single-play-v0
|
| 14 |
+
R=ogbench_genq/experiments/$E/results
|
| 15 |
+
|
| 16 |
+
for arm in a3_s25k_p907 a10_s50k_p960; do
|
| 17 |
+
short=${arm%_p*} # a3_s25k / a10_s50k
|
| 18 |
+
for rd in 1 2; do
|
| 19 |
+
seed=$((rd - 1))
|
| 20 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 21 |
+
--actor_pkl ckpt/best_rsm_cube_${arm}.pkl \
|
| 22 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 23 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_cube_${short}_read${rd}.json
|
| 24 |
+
echo "[official] cube $short read$rd done"
|
| 25 |
+
done
|
| 26 |
+
done
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_graft_ls_p853.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Two-read official: pointmaze logspace-graft arm, logspace graft EMA bank 0.853 vs plain family 0.925 (#61).
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
cd "$(dirname "$0")/../../.."
|
| 5 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 6 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 7 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 8 |
+
PY=.ogbench_venv/bin/python
|
| 9 |
+
E=pointmaze-medium-navigate-v0
|
| 10 |
+
R=ogbench_genq/experiments/$E/results
|
| 11 |
+
for rd in 1 2; do
|
| 12 |
+
seed=$((rd - 1))
|
| 13 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 14 |
+
--actor_pkl ckpt/best_rsm_pm_graft_ls_s325k_p853.pkl \
|
| 15 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 16 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_pm_graft_ls_s325k_p853_read${rd}.json
|
| 17 |
+
echo "[official] graft_ls read$rd done"
|
| 18 |
+
done
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_humanoid_1M_p507.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Re-official at 1M final: humanoidmaze-medium S1 default, bank 0.507 vs bar 0.27 (#61).
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
cd "$(dirname "$0")/../../.."
|
| 5 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 6 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 7 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 8 |
+
PY=.ogbench_venv/bin/python
|
| 9 |
+
E=humanoidmaze-medium-navigate-v0
|
| 10 |
+
R=ogbench_genq/experiments/$E/results
|
| 11 |
+
mkdir -p $R/0 $R/1
|
| 12 |
+
for rd in 1 2; do
|
| 13 |
+
seed=$((rd - 1))
|
| 14 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 15 |
+
--actor_pkl ckpt/best_rsm_humanoid_s1_1M_p507.pkl \
|
| 16 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 17 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_humanoid_s1_1M_p507_read${rd}.json
|
| 18 |
+
echo "[official] humanoid 1M read$rd done"
|
| 19 |
+
done
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_humanoid_p240.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Two-read official: humanoidmaze S2b arm, alpha=1 EMA bank 0.240 vs GCIQL bar 0.131 (#61).
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
cd "$(dirname "$0")/../../.."
|
| 5 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 6 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 7 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 8 |
+
PY=.ogbench_venv/bin/python
|
| 9 |
+
E=humanoidmaze-medium-navigate-v0
|
| 10 |
+
R=ogbench_genq/experiments/$E/results
|
| 11 |
+
for rd in 1 2; do
|
| 12 |
+
seed=$((rd - 1))
|
| 13 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 14 |
+
--actor_pkl ckpt/best_rsm_humanoid_a1_s75k_p240.pkl \
|
| 15 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 16 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_humanoid_a1_s75k_p240_read${rd}.json
|
| 17 |
+
echo "[official] humanoid read$rd done"
|
| 18 |
+
done
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_humanoid_s1_p333.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Two-read official: humanoidmaze-medium S1 default arm, bank 0.333 @400k vs official bar 0.27 (#61).
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
cd "$(dirname "$0")/../../.."
|
| 5 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 6 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 7 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 8 |
+
PY=.ogbench_venv/bin/python
|
| 9 |
+
E=humanoidmaze-medium-navigate-v0
|
| 10 |
+
R=ogbench_genq/experiments/$E/results
|
| 11 |
+
mkdir -p $R/0 $R/1
|
| 12 |
+
for rd in 1 2; do
|
| 13 |
+
seed=$((rd - 1))
|
| 14 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 15 |
+
--actor_pkl ckpt/best_rsm_humanoid_s1_s400k_p333.pkl \
|
| 16 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 17 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_humanoid_s1_s400k_p333_read${rd}.json
|
| 18 |
+
echo "[official] humanoid s1 read$rd done"
|
| 19 |
+
done
|
gen_q_rsm/ogbench_genq/unused/scripts/eval_humanoid_s1_p427.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Re-official at higher bank: humanoidmaze-medium S1 default arm, bank 0.427 @550k vs bar 0.27 (#61).
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
cd "$(dirname "$0")/../../.."
|
| 5 |
+
[ -f .env ] && set -a && source .env && set +a
|
| 6 |
+
export OGBENCH_IMPLS=${OGBENCH_IMPLS:-$HOME/ogbench_ref/impls}
|
| 7 |
+
export XLA_PYTHON_CLIENT_PREALLOCATE=false
|
| 8 |
+
PY=.ogbench_venv/bin/python
|
| 9 |
+
E=humanoidmaze-medium-navigate-v0
|
| 10 |
+
R=ogbench_genq/experiments/$E/results
|
| 11 |
+
mkdir -p $R/0 $R/1
|
| 12 |
+
for rd in 1 2; do
|
| 13 |
+
seed=$((rd - 1))
|
| 14 |
+
"$PY" ogbench_genq/eval_plan.py --env_id $E \
|
| 15 |
+
--actor_pkl ckpt/best_rsm_humanoid_s1_s550k_p427.pkl \
|
| 16 |
+
--plan_k 1 --episodes 50 --vec 25 --seed $seed
|
| 17 |
+
cp $R/$seed/eval_plan_plan.json $R/0/official_rsm_humanoid_s1_s550k_p427_read${rd}.json
|
| 18 |
+
echo "[official] humanoid2 read$rd done"
|
| 19 |
+
done
|