rsm_rise code snapshot (HF_PUSH_ALL) (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- gen_q_rsm/misc/lewm/train_dinowm.pyAdded+331
- gen_q_rsm/misc/results/tdflow_comparison_report.mdAdded+222
- gen_q_rsm/misc/results/tdflow_fair_antmaze_dense_hindsight.jsonAdded+219
- gen_q_rsm/misc/results/tdflow_fair_antmaze_sparse_hindsight.jsonAdded+219
- gen_q_rsm/misc/results/tdflow_fair_pm_fresh_truth_dense_hindsight.jsonAdded
- gen_q_rsm/misc/results/tdflow_fair_pm_fresh_truth_sparse_hindsight.jsonAdded
- gen_q_rsm/misc/results/tdflow_fair_pointmaze_dense_hindsight.jsonAdded+219
- gen_q_rsm/misc/results/tdflow_fair_pointmaze_sparse_hindsight.jsonAdded+219
- gen_q_rsm/misc/results/tdflow_gpu_antmaze_dense_hindsight.jsonAdded+189
- gen_q_rsm/misc/results/tdflow_gpu_antmaze_sparse_hindsight.jsonAdded+189
- gen_q_rsm/misc/results/tdflow_gpu_pointmaze_dense_hindsight.jsonAdded+189
- gen_q_rsm/misc/results/tdflow_gpu_pointmaze_sparse_hindsight.jsonAdded+189
- gen_q_rsm/ogbench_genq/ABLATION.mdAdded+33
- gen_q_rsm/ogbench_genq/DESIGN.mdAdded+185
- gen_q_rsm/ogbench_genq/README.mdAdded+307
- gen_q_rsm/ogbench_genq/RECIPE.mdAdded+89
- gen_q_rsm/ogbench_genq/RESULTS.mdAdded+320
- gen_q_rsm/ogbench_genq/VISUAL_COORDFREE_RESULTS.mdAdded+340
- gen_q_rsm/ogbench_genq/VISUAL_OCCUPANCY_RECURSION.mdAdded+215
- gen_q_rsm/ogbench_genq/VISUAL_RECURSION.mdAdded+166
- gen_q_rsm/ogbench_genq/__init__.pyAdded
- gen_q_rsm/ogbench_genq/_runner.pyAdded+884
- gen_q_rsm/ogbench_genq/bc.pyAdded+17
- gen_q_rsm/ogbench_genq/checkpoints/m9_genq_mixb_gmst_puzzle_3x3_play_v0.genqjax.npzAdded+3
- gen_q_rsm/ogbench_genq/comp_fixed_eval.shAdded+18
- gen_q_rsm/ogbench_genq/comp_horizon_sweep.shAdded+34
- gen_q_rsm/ogbench_genq/comp_plan.pyAdded+329
- gen_q_rsm/ogbench_genq/comp_plan_combined.pyAdded+299
- gen_q_rsm/ogbench_genq/comp_plan_combined_eval.pyAdded+184
- gen_q_rsm/ogbench_genq/comp_plan_eval.pyAdded+204
- gen_q_rsm/ogbench_genq/comp_plan_tdfree.pyAdded+224
- gen_q_rsm/ogbench_genq/eval_plan.pyAdded+304
- gen_q_rsm/ogbench_genq/experiments/antmaze-giant-navigate-v0/results/0/rsm_g995_a3.jsonAdded+144
- gen_q_rsm/ogbench_genq/experiments/antmaze-giant-navigate-v0/results/0/rsm_g99_a3.jsonAdded+148
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/figures/suc.pngAdded
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gcbc.jsonAdded+47
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql.jsonAdded+66
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq.jsonAdded+55
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq_rec_b09.jsonAdded+59
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq_rec_b09.json.doneAdded
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq_rec_b095.jsonAdded+59
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq_rec_b095.json.doneAdded
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/official_rsm_antmaze_lg_a3_s200k_p427_read1.jsonAdded+29
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/official_rsm_antmaze_lg_a3_s200k_p427_read2.jsonAdded+29
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/rsm_a3.jsonAdded+194
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gcbc.jsonAdded+47
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gciql.jsonAdded+66
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gciql_genq.jsonAdded+55
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gciql_genq_rec_b09.jsonAdded+59
- gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gciql_genq_rec_b09.json.doneAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331"""Train DINO-WM (stable-worldmodel `prejepa.PreJEPA`) on the OGBench releasedcube-single play dataset -- the steel-man world-model baseline for issue #65.
This is a faithful port of stable-worldmodel's canonical DINO-WM training recipe(stable-worldmodel/scripts/train/prejepa.py), so the checkpoints it writes arebyte-compatible with `swm.wm.utils.load_pretrained` and our OGBench eval adapter(eval_lewm_ogbench_suite.py). The ONLY substantive changes vs the canonicalscript are: * config_path points at le-wm/config/train_dinowm (dataset matched to LeWM's). * SaveCkptCallback epoch_interval is read from cfg.save_epoch_interval. * no DDP strategy override (single-GPU normal-queue run) -- otherwise identical.
The DINO-WM objective (Zhou et al. 2024): predict next-step FROZEN DINOv2 patchfeatures from action-conditioned history via a causal transformer; MSE in latentspace, no pixel reconstruction. Planning at eval is MPC/CEM (same World+CEMSolveras LeWM), so this is a like-for-like world-model comparison against LeWM/RSM."""
import osfrom functools import partialfrom pathlib import Path
import hydraimport lightning as plimport stable_pretraining as sptimport stable_worldmodel as swmimport torchfrom lightning.pytorch.callbacks import Callbackfrom lightning.pytorch.loggers import WandbLoggerfrom loguru import logger as loggingfrom omegaconf import OmegaConf, open_dictfrom stable_worldmodel.data import column_normalizer as get_column_normalizerfrom stable_worldmodel.wm.utils import save_pretrainedfrom torch.nn import functional as Ffrom torch.utils.data import DataLoaderfrom transformers import AutoVideoProcessor
# ---------------------------------------------------------------------------# Data helpers (verbatim from scripts/train/prejepa.py)# ---------------------------------------------------------------------------
def get_img_preprocessor(source, target, img_size=224): stats = spt.data.dataset_stats.ImageNet return spt.data.transforms.Compose( spt.data.transforms.ToImage(**stats, source=source, target=target), spt.data.transforms.Resize(img_size, source=source, target=target), )
class VideoPipeline(spt.data.transforms.Transform): def __init__(self, processor, source="image", target="image"): super().__init__() self.processor, self.source, self.target = processor, source, target
def __call__(self, x): frames = self.nested_get(x, self.source) self.nested_set( x, self.processor(frames, return_tensors="pt")["pixel_values_videos"].squeeze(0), self.target, ) return x
# ---------------------------------------------------------------------------# Callbacks# ---------------------------------------------------------------------------
class SaveCkptCallback(Callback): """Save a `save_pretrained` checkpoint by epoch AND (for sub-epoch step budgets) every `step_interval` global steps. Step checkpoints are named `weights_step_{N}.pt` so eval can pick the highest-step (best-trained) one."""
def __init__(self, run_name, cfg, epoch_interval=1, step_interval=None): super().__init__() self.run_name = run_name self.cfg = cfg self.epoch_interval = epoch_interval self.step_interval = step_interval self._last_step_saved = -1
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx): if not trainer.is_global_zero or not self.step_interval: return step = trainer.global_step if step > 0 and step % self.step_interval == 0 and step != self._last_step_saved: self._last_step_saved = step self._save(pl_module.model, f"step_{step}")
def on_train_epoch_end(self, trainer, pl_module): if not trainer.is_global_zero: return epoch = trainer.current_epoch + 1 if epoch % self.epoch_interval == 0: self._save(pl_module.model, f"epoch_{epoch}") if epoch == trainer.max_epochs: self._save(pl_module.model, f"epoch_{epoch}")
def on_train_end(self, trainer, pl_module): # Guarantee a final checkpoint at the step budget even if it doesn't # land exactly on a step_interval boundary. if trainer.is_global_zero: self._save(pl_module.model, f"step_{trainer.global_step}")
def _save(self, model, tag): save_pretrained( model, run_name=self.run_name, config=self.cfg, filename=f"weights_{tag}.pt", )
# ---------------------------------------------------------------------------# Forward (verbatim DINO-WM objective from scripts/train/prejepa.py)# ---------------------------------------------------------------------------
def _strip_action_dims(tensor, action_range): return torch.cat( [tensor[..., : action_range[0]], tensor[..., action_range[1] :]], dim=-1 )
def dinowm_forward(self, batch, stage, cfg): """Encode observations, predict next latent state, compute latent MSE loss.""" for key in self.model.extra_encoders: batch[key] = torch.nan_to_num(batch[key], 0.0).squeeze()
batch = self.model.encode( batch, target="emb", is_video=cfg.backbone.get("is_video_encoder", False), )
embedding = batch["emb"][:, : cfg.wm.history_size, ...] pred_embedding = self.model.predict(embedding) target_embedding = batch["emb"][:, cfg.wm.num_preds :, ...].detach()
pixels_dim = batch["pixels_emb"].size(-1) batch["pixels_loss"] = F.mse_loss( pred_embedding[..., :pixels_dim], target_embedding[..., :pixels_dim] )
start, action_range = pixels_dim, [0, 0] for key in self.model.extra_encoders: dim = batch[f"{key}_emb"].size(-1) lo, hi = start, start + dim if key == "action": action_range = [lo, hi] else: batch[f"{key}_loss"] = F.mse_loss( pred_embedding[..., lo:hi], target_embedding[..., lo:hi].detach() ) start = hi
batch["actionless_emb"] = _strip_action_dims(batch["emb"], action_range) batch["actionless_prev_emb"] = _strip_action_dims(embedding, action_range) batch["actionless_pred_emb"] = _strip_action_dims(pred_embedding, action_range) batch["actionless_target_emb"] = _strip_action_dims(target_embedding, action_range)
batch["loss"] = F.mse_loss( batch["actionless_pred_emb"], batch["actionless_target_emb"].detach() )
if batch["loss"].isnan(): raise ValueError("NaN loss encountered!")
self.log_dict( {f"{stage}/{k}": v.detach() for k, v in batch.items() if "_loss" in k}, on_step=True, sync_dist=True, ) return batch
# ---------------------------------------------------------------------------# Main# ---------------------------------------------------------------------------
@hydra.main(version_base=None, config_path="./config/train_dinowm", config_name="dinowm")def run(cfg): # --- Dataset --- encoding_keys = list(cfg.wm.get("encoding", {}).keys()) keys_to_load = ["pixels"] + encoding_keys
cache_dir = os.environ.get("LOCAL_DATASET_DIR", None) print( f'Loading dataset "{cfg.dataset_name}" from ' f'{"local cache: " + cache_dir if cache_dir else "default location"}' ) dataset = swm.data.load_dataset( cfg.dataset_name, num_steps=cfg.n_steps, frameskip=cfg.frameskip, transform=None, cache_dir=cache_dir, keys_to_load=keys_to_load, keys_to_cache=encoding_keys, )
normalizers = [ get_column_normalizer(dataset, col, col) for col in cfg.wm.get("encoding", {}) ]
if cfg.backbone.get("is_video_encoder", False): processor = AutoVideoProcessor.from_pretrained(cfg.backbone.name) transform = spt.data.transforms.Compose( VideoPipeline(processor, source="pixels", target="pixels"), spt.data.transforms.Resize(cfg.image_size, source="pixels", target="pixels"), *normalizers, ) else: transform = spt.data.transforms.Compose( get_img_preprocessor("pixels", "pixels", cfg.image_size), *normalizers, ) dataset.transform = transform
with open_dict(cfg) as cfg: cfg.extra_dims = {} for key in cfg.wm.get("encoding", {}): if key not in dataset.column_names: raise ValueError(f"Encoding key '{key}' not found in dataset columns.") dim = dataset.get_dim(key) cfg.extra_dims[key] = dim if key != "action" else dim * cfg.frameskip
rnd_gen = torch.Generator().manual_seed(cfg.seed) train_set, val_set = spt.data.random_split( dataset, [cfg.train_split, 1 - cfg.train_split], generator=rnd_gen )
train_loader = DataLoader( train_set, batch_size=cfg.batch_size, num_workers=cfg.num_workers, drop_last=True, persistent_workers=True, pin_memory=True, shuffle=True, generator=rnd_gen, ) val_loader = DataLoader( val_set, batch_size=cfg.batch_size, num_workers=cfg.num_workers, pin_memory=True, )
# --- Model (frozen DINOv2 encoder + trained CausalPredictor) --- encoder = hydra.utils.instantiate(cfg.model.encoder) encoder.eval() encoder.requires_grad_(False)
is_cnn = hasattr(encoder.config, "hidden_sizes") embed_dim = encoder.config.hidden_sizes[-1] if is_cnn else encoder.config.hidden_size num_patches = 1 if is_cnn else (cfg.image_size // cfg.patch_size) ** 2 embed_dim += sum(cfg.wm.get("encoding", {}).values())
if cfg.backbone.get("is_video_encoder", False): num_patches += num_patches * (cfg.n_steps // 4)
with open_dict(cfg): cfg.model.predictor.dim = embed_dim cfg.model.predictor.num_patches = num_patches cfg.model.extra_encoders = { "_target_": "torch.nn.ModuleDict", "modules": { key: { "_target_": "stable_worldmodel.wm.prejepa.module.Embedder", "in_chans": cfg.extra_dims[key], "emb_dim": int(cfg.wm.encoding[key]), } for key in cfg.wm.get("encoding", {}) }, }
world_model = hydra.utils.instantiate(cfg.model, encoder=encoder)
world_model = spt.Module( model=world_model, forward=partial(dinowm_forward, cfg=cfg), optim={"model_opt": {"modules": "model", "optimizer": dict(cfg.optimizer)}}, )
# --- Training --- run_id = cfg.get("subdir") or "" run_dir = Path(swm.data.utils.get_cache_dir(sub_folder="checkpoints"), run_id) run_dir.mkdir(parents=True, exist_ok=True) logging.info(f"Run ID: {run_id}")
with open(run_dir / "config.yaml", "w") as f: OmegaConf.save(cfg, f)
logger = None if cfg.wandb.enabled: logger = WandbLogger(**cfg.wandb.config) logger.log_hyperparams(OmegaConf.to_container(cfg))
trainer = pl.Trainer( **cfg.trainer, callbacks=[ SaveCkptCallback( run_name=cfg.output_model_name, cfg=cfg.model, epoch_interval=cfg.get("save_epoch_interval", 5), step_interval=cfg.get("ckpt_step_interval", None), ), pl.pytorch.callbacks.LearningRateMonitor(logging_interval="step"), ], num_sanity_val_steps=1, logger=logger, enable_checkpointing=True, )
ckpt_path = run_dir / f"{cfg.output_model_name}_weights.ckpt" manager = spt.Manager( trainer=trainer, module=world_model, data=spt.data.DataModule(train=train_loader, val=val_loader), ckpt_path=ckpt_path if ckpt_path.exists() else None, ) manager()
if __name__ == "__main__": run()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222# Gen-Q vs TD-Flow vs InFOM: Offline Goal-Conditioned Q Comparison
**Date**: 2026-06-24 (fair re-run — supersedes the 2026-06-22 numbers)**Driver**: `src/compare_tdflow.py` (training + eval), `src/gc_rollout_truth.py` (PointMaze truth)**Compute**: 1× GPU per (env, reward) cell, packed via `scripts/run_tdflow_fair.sh` on one node**Truth**:- **PointMaze** — *fresh-rollout* ground truth: M=8 fresh on-policy rollouts of the scripted behavior policy from each anchor, scored toward the anchor's hindsight goal (issue #3).- **AntMaze** — single-trajectory MC return (`MC_rollout`). Fresh-rollout truth needs the OGBench SAC expert checkpoint, which is **not available in this environment**, so the AntMaze cells keep the single-trajectory estimator and label it honestly. **Caveat:** on AntMaze the trained-MC baseline regresses the same estimator the truth uses, so MC's AntMaze numbers retain a small circular advantage; read the AntMaze MC column with that in mind.**InFOM**: **free-bits steel-man** (`infom_free_bits=0.5`, `kl = max(kl_raw, 0.5)`) per the CLAUDE.mdmandate, so the intention latent z does **not** posterior-collapse (issue #1). Observed train KLplateaus at ≈0.5 (not ≈0).**Setting**: γ = 0.99, 2000 anchors/cell, 30–40k train steps/method, hindsight goal sampling.
> **What changed vs the 2026-06-22 report.** (a) InFOM is now the free-bits steel-man, not the> collapsed `kl=0.01` strawman. (b) A new **InFOM-g** variant goal-conditions the InFOM flow to> isolate the training rule from the conditioning (issue #2). (c) PointMaze truth is fresh-rollout,> not single-trajectory, and the trained-MC baseline no longer shares the PointMaze estimator> (issue #3). The headline shifts from "3–6× in every cell" to a more nuanced — and more> defensible — claim (see §7).
---
## 1. Methods
| Method | Backbone | Training | Conditioning | Reference ||-------------------|------------|------------------|------------------------|---------------------------------|| **Gen-Q** (ours) | Diffusion | direct MLE | (s, a, g) | this codebase || CFM-Direct | Flow | direct MLE | (s, a, g) | backbone ablation || TD-Flow | Flow | Bellman mixture | (s, a, g) | [arXiv:2503.09817](https://arxiv.org/abs/2503.09817) || TD-Diff | Diffusion | Bellman mixture | (s, a, g) | cross-ablation || InFOM | Flow | SARSA² TD + z (free-bits) | (s, a, z=q_e(s', a')) | [arXiv:2506.08902](https://arxiv.org/abs/2506.08902) || **InFOM-g** | Flow | SARSA² TD + z (free-bits) | (s, a, **g**, z) | issue #2 (this codebase) || MC | scalar NN | regression | (s, a, g) → R̄ | baseline || WM | dyn + π | imagined rollouts | (s, a, g) | baseline |
The clean, confound-free **MLE-vs-TD** ablations (issue #2) are the matched pairs:**Gen-Q vs TD-Diff** (diffusion, both goal-cond) and **CFM-Direct vs TD-Flow** (flow, bothgoal-cond). Vanilla InFOM differs from Gen-Q in *two* axes at once (training rule **and** the flow'sconditioning), so **InFOM-g** is included to isolate the training rule: it gives the InFOM flow thegoal too, leaving only SARSA²-TD-vs-MLE as the difference.
## 2. Environments
| Env | State | Action | Anchors | Truth ||-----|------:|-------:|--------:|-------|| PointMaze (`pointmaze-medium-navigate-v0`) | 2D | 2D | 2000 | fresh-rollout (M=8) || AntMaze (`antmaze-medium-navigate-v0`) | 29D | 8D | 2000 | single-traj `MC_rollout` |
Goal `g` = `s[:2]` of a downstream state on the same trajectory (hindsight). On PointMaze, thefresh-rollout truth correlates with the old single-trajectory return at ρ = 0.73 (dense) / 0.64(sparse) — related but materially different, which is exactly why the single realization was thewrong yardstick.
## 3. Rewards
- **Dense**: `r(s) = exp(-‖s − g‖² / 2σ²)`, σ = 5- **Sparse**: `r(s) = 1[‖s − g‖ < ε]`, ε = 0.5
---
## 4. Results — Q MSE (lower is better)
### N=256 across all 4 settings (headline)
| Method | PM dense | AM dense | PM sparse | AM sparse ||---------------|-----------:|-----------:|-----------:|-----------:|| **Gen-Q** | 0.0266 | 0.0219 | 0.0187 | 0.0129 || **CFM-Direct**| 0.0314 | **0.0192** | 0.0241 | **0.0123** || TD-Flow | 0.0614 | 0.1365 | 0.0098 | 0.0832 || TD-Diff | 0.1022 | 0.2447 | **0.0006** | 0.0816 || InFOM (fb) | 0.0517 | 0.1013 | 0.0076 | 0.0808 || InFOM-g (fb) | 0.0564 | 0.1702 | 0.0074 | 0.0924 || MC | 0.0299 | 0.0364 | 0.0278 | 0.0180 || WM | 0.0594 | 0.0343 | 0.0050 | 0.0496 |
### N=256 — Spearman rank correlation (higher better)
| Method | PM dense | AM dense | PM sparse | AM sparse ||---------------|-----------:|-----------:|-----------:|-----------:|| Gen-Q | 0.863 | 0.857 | 0.374 | 0.486 || **CFM-Direct**| **0.903** | **0.888** | **0.511** | **0.525** || TD-Flow | 0.842 | 0.685 | 0.281 | 0.260 || TD-Diff | -0.025 | 0.166 | 0.006 | -0.030 || InFOM (fb) | 0.830 | 0.613 | 0.249 | 0.125 || InFOM-g (fb) | 0.839 | 0.483 | 0.244 | 0.066 || MC | 0.867 | 0.808 | 0.203 | 0.413 || WM | 0.729 | 0.834 | 0.279 | 0.461 |
### MSE vs sample count (the mechanism)
The direct-MLE methods fall monotonically with N (Monte-Carlo variance reduction); the TD / InFOMmethods are **flat** in N (a bias floor):
| Method (PM dense) | N=1 | N=16 | N=256 ||---|---:|---:|---:|| Gen-Q | 0.118 | 0.033 | 0.027 || CFM-Direct | 0.116 | 0.036 | 0.031 || InFOM (fb) | 0.053 | 0.052 | 0.052 || TD-Flow | 0.064 | 0.062 | 0.061 || MC (N-indep.) | 0.030 | 0.030 | 0.030 |
Same shape in every cell: Gen-Q/CFM start high (1-sample variance) and converge; TD/InFOM never move.
---
## 5. Findings
### 5.1 Direct MLE still beats TD bootstrapping — on dense reward and in high dim
On the three cells where the truth is a genuine expectation with spread (PM dense, AM dense, AMsparse), Gen-Q and CFM-Direct converge with N to the lowest MSE and the highest Spearman, whileTD-Flow / TD-Diff / InFOM plateau at a bias floor. The matched ablations make this confound-free:**Gen-Q < TD-Diff** (0.027 vs 0.102 PM-dense; 0.022 vs 0.245 AM-dense) and**CFM-Direct < TD-Flow** (0.031 vs 0.061 PM-dense; 0.019 vs 0.137 AM-dense). The bias the bootstraptarget injects persists at every N from 1 to 256.
### 5.2 The "3–6× in every cell" headline was too strong — free-bits narrows it
With the **steel-manned** (free-bits) InFOM, the Gen-Q advantage is cell-dependent, **not** a flat3–6×:
| Cell | Gen-Q / InFOM(fb) MSE ratio ||------|---:|| PM dense | **1.9×** || AM dense | **4.6×** || AM sparse | **6.3×** || PM sparse | **0.4× (InFOM wins, see 5.4)** |
The old report's 3–6×-everywhere came from comparing against a *collapsed* InFOM. The honest claimis: Gen-Q beats free-bits InFOM by ~2× on low-dim dense, by ~5–6× in high-dim, and **loses to it onPointMaze-sparse MSE**.
### 5.3 InFOM-g shows the gap is the *training rule*, not the conditioning (issue #2)
Giving the InFOM flow the goal (InFOM-g) does **not** close the gap — it is essentially tied withvanilla InFOM and sometimes *worse* (AM-dense 0.170 vs 0.101). So the Gen-Q win over InFOM is **not**an artifact of "explicit goal conditioning beats intention-latent"; it survives when both aregoal-conditioned. The differentiator is **direct MLE vs SARSA²-TD**, exactly the paper's hypothesis.(This was the central fairness worry in issue #2; the InFOM-g control answers it.)
### 5.4 PointMaze-sparse MSE inverts — but ranking does not (issue #3 nuance)
Under *fresh-rollout* truth, PM-sparse Qbar is tiny for most anchors (a fresh rollout toward anarbitrary hindsight goal rarely enters the ε-ball), so the truth vector is near-zero. Estimatorsthat output a near-constant small value (TD-Diff 0.0006, InFOM 0.008, TD-Flow 0.010) trivially winon **MSE**, while Gen-Q/CFM/MC carry more spread and pay for it. But on **ranking** — what actuallymatters for control — CFM-Direct (0.51) and Gen-Q (0.37) still beat InFOM (0.25), TD-Flow (0.28),and MC (0.20). The lesson: on near-degenerate sparse truth, MSE rewards predicting the prior mean;use Spearman. (AntMaze-sparse, with more reward-reachable anchors, keeps Gen-Q/CFM ahead on *both*.)
### 5.5 Removing MC's circular advantage (issue #3): Gen-Q now beats MC on PointMaze
Previously the trained-MC baseline regressed the *same* single-trajectory estimator used as truth,and posted the best/near-best MSE on PointMaze. With fresh-rollout truth (independent of MC'straining target), **Gen-Q now beats MC on PM dense** (0.027 vs 0.030) and PM sparse (Spearman 0.37vs 0.20). MC is no longer scored against its own objective. (On AntMaze the circular advantageremains — see the §Truth caveat — so the AM MC column is still favorable to MC.)
### 5.6 Occupancy modeling beats MC in high dim (unchanged)
| Env | Reward | Best occupancy | MC | Winner ||--------|--------|---------------:|-------:|--------------------|| PM 2D | dense | 0.0266 (Gen-Q) | 0.0299 | Gen-Q (1.1×) || AM 29D | dense | 0.0192 (CFM) | 0.0364 | **occupancy 1.9×** || AM 29D | sparse | 0.0123 (CFM) | 0.0180 | **occupancy 1.5×** |
The strongest standalone evidence for the Gen-Q design — structured occupancy generalizes betterthan a scalar Q in 29D — is unaffected by the fairness fixes.
### 5.7 CFM-Direct is often the best of our own variants
CFM-Direct (Flow + MLE) has the highest Spearman in all four cells and the lowest MSE on bothAntMaze cells. The named headline method (Gen-Q, Diffusion + MLE) is competitive but not uniformlybest among the authors' own variants — worth stating plainly.
---
## 6. Implementation notes
- **Free-bits (issue #1)**: `train_tdflow.train_infom` reads `infom_free_bits` from the config; `gc_pointmaze.yaml` / `m6_antmaze.yaml` now set it to 0.5, and `compare_tdflow.py` asserts it is enabled so the headline can never silently revert to the collapsed baseline.- **InFOM-g (issue #2)**: `train_infom(..., goal_cond=True)` concatenates the hindsight goal into the flow conditioning; `infom_q_goal(..., goal_cond=True)` mirrors it at eval. The intention encoder `q_e(z | s', a')` is unchanged.- **Fresh-rollout truth (issue #3)**: `src/gc_rollout_truth.py::gc_fresh_truth_pointmaze` rolls the scripted oracle-subgoal controller (the exact PointMaze data-collection policy), inferring the latent navigation goal from the anchor action and scoring toward the external hindsight goal.- AntMaze fresh-rollout truth is a documented gap (no SAC expert checkpoint here).
---
## 7. Verdict
**Direct-MLE occupancy modeling beats TD-based occupancy modeling for offline goal-conditioned Qestimation on dense rewards and in high dimension, on both MSE and ranking — and the advantage isthe training rule, not the goal conditioning.** Against the steel-manned (free-bits) InFOM themargin is ~2× (low-dim dense) to ~5–6× (29-D AntMaze), and the InFOM-g control rules out theconditioning confound. Two honest caveats now on the record: (1) on **PointMaze-sparse** thefresh-rollout truth is near-degenerate and the bias-floor TD/InFOM methods win on **MSE** (thoughnot on ranking); (2) **AntMaze** truth is still single-trajectory (no SAC expert available), givingits MC column a residual circular edge. The earlier "3–6× in every cell against InFOM" claim doesnot survive the steel-man and is retracted in favor of the above.
---
## 8. Artifacts
| File | Contents ||---------------------------------------------------------------|-----------------------------------------|| `results/tdflow_fair_{env}_{reward}_hindsight.json` | per-cell raw MSE / Spearman vs N (fair re-run) || `results/tdflow_fair_pm_fresh_truth_{reward}_hindsight.json` | PointMaze fresh-rollout truth vector + anchors + goals (issue #3 provenance; `src/emit_pm_fresh_truth.py`) || `results/tdflow_gpu_{env}_{reward}_hindsight.json` | **old** (2026-06-22) numbers, retained for diff || `figures/tdflow_comparison_fair_{env}_{reward}_hindsight.png` | per-cell figures (fair re-run) || `results/fair_rerun_summary.md` | auto-generated headline tables (`src/aggregate_fair_results.py`) || `src/compare_tdflow.py` / `src/train_tdflow.py` | driver + TD-Flow/InFOM/InFOM-g training || `src/gc_rollout_truth.py` | PointMaze fresh-rollout GC truth |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219{ "env": "antmaze", "reward": "dense", "goal_mode": "hindsight", "sample_counts": [ 1, 2, 4, 8, 16, 32, 64, 128, 256 ], "methods": { "Gen_Q": { "mse": [ 0.09991595063075047, 0.05972130771093792, 0.04037073161323812, 0.03244439388609538, 0.026272044963170513, 0.024531142478154026, 0.022839635841408138, 0.022438995356735377, 0.02190367777566301 ], "spearman": [ 0.6545005771251442, 0.7203578421297289, 0.7721394955348739, 0.7985766496441623, 0.832037307571341, 0.8435648873912218, 0.852145020036255, 0.8544052026013007, 0.857230134128995 ] }, "CFM_Direct": { "mse": [ 0.09223347736450724, 0.052210997878156036, 0.03729774976790083, 0.027161264087996715, 0.023610786069201584, 0.021100200938958917, 0.019768486737633678, 0.019673095401802027, 0.019160089806232267 ], "spearman": [ 0.6942862040819084, 0.7616142494035624, 0.801914831029426, 0.8377895124473781, 0.8594385288596322, 0.8716489114122278, 0.8824816992013556, 0.8841304445326111, 0.8877643697740042 ] }, "TD_Flow": { "mse": [ 0.1400500228958969, 0.13730378017756592, 0.1372066533399597, 0.13676980215124232, 0.13696011199385058, 0.1364254540854149, 0.1367536726725562, 0.13666433586034368, 0.1365341433710201 ], "spearman": [ 0.670963847740962, 0.6777607619401904, 0.6782579995688466, 0.6834053483576141, 0.6811363612840903, 0.683898635974659, 0.6841331010332753, 0.6843704490926122, 0.685299708324927 ] }, "TD_Diff": { "mse": [ 0.26123123661106196, 0.25402133779882885, 0.2493629757306254, 0.24649216639239202, 0.24531962781665415, 0.24472475639855482, 0.24459517134406672, 0.24486571108187558, 0.24471651014495507 ], "spearman": [ 0.0519561459890365, 0.08102897625724406, 0.08286824971706243, 0.12256542214135555, 0.1255685548921387, 0.1432611013152753, 0.1496479844119961, 0.15777429344357338, 0.16594198748549685 ] }, "InFOM": { "mse": [ 0.10394982194076545, 0.1032939421313844, 0.10229927096758765, 0.1018062588999148, 0.10133066839029456, 0.10121054927416148, 0.10149814655832552, 0.10125419557244941, 0.10134188742649824 ], "spearman": [ 0.5987822501955625, 0.6017182234295558, 0.6063026595756649, 0.6095184173796043, 0.6133247180611763, 0.6125548051387012, 0.6126986746746687, 0.6134904933726233, 0.6127974886993721 ] }, "InFOM_g": { "mse": [ 0.1757690545197499, 0.17276444035637095, 0.1711384636902673, 0.1703462577295688, 0.17035454916198098, 0.17048472981541324, 0.17012240436472884, 0.17014000708809202, 0.17024983159916018 ], "spearman": [ 0.4566042781510695, 0.4669043262260816, 0.47292613173153286, 0.48126931981732995, 0.47847899811974953, 0.47991340647835157, 0.4831811297264754, 0.48341790985447747, 0.4824912351228088 ] }, "MC": { "mse": [ 0.03638216444616623, 0.03638216444616623, 0.03638216444616623, 0.03638216444616623, 0.03638216444616623, 0.03638216444616623, 0.03638216444616623, 0.03638216444616623, 0.03638216444616623 ], "spearman": [ 0.8076640344160086, 0.8076640344160086, 0.8076640344160086, 0.8076640344160086, 0.8076640344160086, 0.8076640344160086, 0.8076640344160086, 0.8076640344160086, 0.8076640344160086 ] }, "WM": { "mse": [ 0.07630250972704096, 0.054405615723018844, 0.045972534032270855, 0.0391026193511653, 0.036792574051486386, 0.035839010348506437, 0.0346794580831158, 0.034466453444648965, 0.03433230127689151 ], "spearman": [ 0.6881578915394728, 0.747641168410292, 0.7813303818325954, 0.8135332223833055, 0.8177454214363552, 0.8255134148783537, 0.8308404547101136, 0.8336450834112709, 0.8341767795441948 ] } }, "truth_kind": "single_traj_MC_rollout", "truth_std": 0.31527707126650545, "truth_mean": 0.4283738412667841, "truth_single_std": 0.31527707126650545, "truth_single_mean": 0.4283738412667841, "corr_fresh_vs_single": null, "infom_free_bits": 0.5, "n_anchors": 2000, "timing_s": 1553.722976922989}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219{ "env": "antmaze", "reward": "sparse", "goal_mode": "hindsight", "sample_counts": [ 1, 2, 4, 8, 16, 32, 64, 128, 256 ], "methods": { "Gen_Q": { "mse": [ 0.055180425267837944, 0.03620247286955783, 0.02369307046167507, 0.019075991458749993, 0.015846279412885796, 0.014220683721212178, 0.013309556780580377, 0.013311126026292898, 0.012908830689078185 ], "spearman": [ 0.4400436704283849, 0.45405864569976134, 0.462781582780738, 0.4700726366561771, 0.4608784941910928, 0.4671875030673925, 0.4813091053648641, 0.48135018405324703, 0.48567254628147716 ] }, "CFM_Direct": { "mse": [ 0.056098234636184685, 0.031843109853224374, 0.022629107959856, 0.01633353805018934, 0.015393053374542968, 0.0129765390721208, 0.012874393974115017, 0.012470351675624077, 0.012287226325425723 ], "spearman": [ 0.44324655569513927, 0.4906667174068689, 0.49940138150657315, 0.491890260357652, 0.4872963082035231, 0.48569663087995907, 0.49550957322339506, 0.5044430860031999, 0.5245140310118815 ] }, "TD_Flow": { "mse": [ 0.09009620218801238, 0.08593630048681539, 0.08419812918456819, 0.0844694359757234, 0.08367019629938202, 0.08273525162398883, 0.0834928702791377, 0.08341583997695685, 0.08317810959737244 ], "spearman": [ 0.10605162903756903, 0.13665842925400537, 0.12609697697708688, 0.16451602138070082, 0.16324366482623334, 0.1821150989984673, 0.21477872066585466, 0.20567516558710144, 0.25968999162652173 ] }, "TD_Diff": { "mse": [ 0.08166774186487734, 0.08169660173178535, 0.0816981719873903, 0.08162482307665421, 0.0816665166839623, 0.08162175090184166, 0.08159273173567189, 0.08161843089026485, 0.0816240624029763 ], "spearman": [ NaN, 0.011316974082530476, -0.013230532391231734, 0.03521140846501613, 0.013748699392177072, -0.013160036008698096, 0.046197718277958245, -5.0135260324747565e-05, -0.029495632776931832 ] }, "InFOM": { "mse": [ 0.08175330019185302, 0.0812733885769284, 0.08113221184713414, 0.08152683826529736, 0.08130498804185567, 0.08078610796312137, 0.08101783913900393, 0.08080946608536906, 0.08081616081690235 ], "spearman": [ 0.019850295189614505, 0.01772138902272969, 0.01576058777353393, 0.04558308652368827, 0.03243909071542348, 0.09587236608801368, 0.11682678431115207, 0.11637534420255555, 0.12492176638982738 ] }, "InFOM_g": { "mse": [ 0.09923391194539681, 0.09771184113347417, 0.09476364452281821, 0.09216867734350487, 0.0932171750684144, 0.09189603720603513, 0.09235344220669395, 0.09192202584428456, 0.09243971016525737 ], "spearman": [ 0.010916080880591088, 0.01870173063302528, 0.03955048274750622, 0.028556498483093083, 0.023145246177003233, 0.06899759557860444, 0.05141101141769581, 0.07545169862576587, 0.06638970247902426 ] }, "MC": { "mse": [ 0.017962991399811196, 0.017962991399811196, 0.017962991399811196, 0.017962991399811196, 0.017962991399811196, 0.017962991399811196, 0.017962991399811196, 0.017962991399811196, 0.017962991399811196 ], "spearman": [ 0.4133635519102373, 0.4133635519102373, 0.4133635519102373, 0.4133635519102373, 0.4133635519102373, 0.4133635519102373, 0.4133635519102373, 0.4133635519102373, 0.4133635519102373 ] }, "WM": { "mse": [ 0.06761577334222452, 0.059468325273278055, 0.05276794047850626, 0.05027821093798424, 0.051739548189609, 0.05073534935690307, 0.049660311642048156, 0.049942303339230165, 0.04963768463645629 ], "spearman": [ 0.2083406919768801, 0.2877980852302451, 0.3724190556278559, 0.4199626105929094, 0.4467834099734699, 0.4576240536065592, 0.4836346182036708, 0.46893596985323355, 0.4610869309108934 ] } }, "truth_kind": "single_traj_MC_rollout", "truth_std": 0.2578413642406279, "truth_mean": 0.12322975594964546, "truth_single_std": 0.2578413642406279, "truth_single_mean": 0.12322975594964546, "corr_fresh_vs_single": null, "infom_free_bits": 0.5, "n_anchors": 2000, "timing_s": 1568.5431423187256}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219{ "env": "pointmaze", "reward": "dense", "goal_mode": "hindsight", "sample_counts": [ 1, 2, 4, 8, 16, 32, 64, 128, 256 ], "methods": { "Gen_Q": { "mse": [ 0.11775300691790601, 0.07215233006700751, 0.04947633555354753, 0.038290010523678204, 0.032974569360617496, 0.028798022023125112, 0.027802801394839524, 0.026765691249570036, 0.02663121360356441 ], "spearman": [ 0.5036772059193015, 0.5525959276489819, 0.6628862362215591, 0.747062864265716, 0.7992637818159454, 0.8336426774106692, 0.8493359768339941, 0.8574067828516957, 0.8629504752376187 ] }, "CFM_Direct": { "mse": [ 0.11587307680095628, 0.06985001160720472, 0.05397902521352317, 0.04316750807694748, 0.03638310367810415, 0.033663823837461665, 0.032304478624526484, 0.031722280926765906, 0.031445518701148714 ], "spearman": [ 0.5584493217811674, 0.6727814626953657, 0.7184917196229299, 0.8025911456477864, 0.8508839178591423, 0.8816072594018147, 0.8920388035097008, 0.8996851502586695, 0.9027059436764858 ] }, "TD_Flow": { "mse": [ 0.06365770696057019, 0.06219196578228547, 0.061882874559644495, 0.06164642905972531, 0.06186092398886337, 0.061503203383941135, 0.061428063771322663, 0.06149294047783137, 0.061430535759845396 ], "spearman": [ 0.833564992391248, 0.8378046894511723, 0.8412237678059419, 0.8401543215385803, 0.8399975654993913, 0.8416993549248386, 0.8419037779759444, 0.8419508734877184, 0.8421530926040807 ] }, "TD_Diff": { "mse": [ 0.11679006546012792, 0.1106486865058846, 0.10521670244506813, 0.10409829288633585, 0.10355379190863795, 0.10293617087359234, 0.10255110894182516, 0.10242091472346815, 0.10220360025482256 ], "spearman": [ 0.09634383158595788, 0.04606749701687425, 0.00975898443974611, -0.027727556431889108, -0.027826463456615866, -0.037715898428974604, -0.03582121645530412, -0.026761445190361294, -0.02464842316210579 ] }, "InFOM": { "mse": [ 0.05301142938953025, 0.05264804876709866, 0.05220394416745997, 0.052075600858600885, 0.051579599620617526, 0.051666997262312345, 0.05184124057165884, 0.05169295008146883, 0.05173414945521822 ], "spearman": [ 0.8188037302009326, 0.8248954717238679, 0.8289816887454221, 0.8278941614735402, 0.8300775860193965, 0.8298379504594875, 0.8299164304791076, 0.8301394808461726, 0.829881948781693 ] }, "InFOM_g": { "mse": [ 0.05849781600122822, 0.05765370614854641, 0.05690717698539817, 0.056412777547571374, 0.05660968793745807, 0.05643651464321235, 0.05652691944651218, 0.05657092823087636, 0.056416409712633696 ], "spearman": [ 0.8282671800667951, 0.835649712412428, 0.8370242842560711, 0.8383888615972153, 0.8380324645081161, 0.8383955890988972, 0.8385831251457814, 0.8387942621985656, 0.8389726872431716 ] }, "MC": { "mse": [ 0.029853207463821464, 0.029853207463821464, 0.029853207463821464, 0.029853207463821464, 0.029853207463821464, 0.029853207463821464, 0.029853207463821464, 0.029853207463821464, 0.029853207463821464 ], "spearman": [ 0.8668374412093602, 0.8668374412093602, 0.8668374412093602, 0.8668374412093602, 0.8668374412093602, 0.8668374412093602, 0.8668374412093602, 0.8668374412093602, 0.8668374412093602 ] }, "WM": { "mse": [ 0.0737684009612585, 0.06596541190133895, 0.06267735515110429, 0.06095491469443823, 0.060753692200724956, 0.0599714802852946, 0.0595856349330605, 0.0594087169533591, 0.05942766416646566 ], "spearman": [ 0.6995245068934484, 0.7162481225620306, 0.7268595212148803, 0.7278244354561089, 0.7267120501780125, 0.7284370971092742, 0.729517208379302, 0.7297388259347064, 0.7288890367222591 ] } }, "truth_kind": "fresh_rollout", "truth_std": 0.17330187551935103, "truth_mean": 0.30351426360028116, "truth_single_std": 0.2294491968554867, "truth_single_mean": 0.3550800132933621, "corr_fresh_vs_single": 0.7299259598335769, "infom_free_bits": 0.5, "n_anchors": 2000, "timing_s": 1125.265121936798}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219{ "env": "pointmaze", "reward": "sparse", "goal_mode": "hindsight", "sample_counts": [ 1, 2, 4, 8, 16, 32, 64, 128, 256 ], "methods": { "Gen_Q": { "mse": [ 0.046248916534078845, 0.03323746991725375, 0.026105636238806577, 0.02150012590987568, 0.021269045237158415, 0.019152608305017162, 0.01906095243855978, 0.018729202203451024, 0.018714472112895272 ], "spearman": [ 0.20906426785567384, 0.20578062391182478, 0.23116419416635878, 0.2436652747090022, 0.26077603088236845, 0.27351701931232497, 0.31201250886449333, 0.34826686970543325, 0.3742680053308477 ] }, "CFM_Direct": { "mse": [ 0.04687317432226104, 0.036537000118626, 0.03112371381935344, 0.02764266713503497, 0.025883518235307015, 0.025000954715976773, 0.024305078358526886, 0.024362569894725156, 0.024141970208388434 ], "spearman": [ 0.2695318597224391, 0.2730810141752468, 0.23711581363407988, 0.29456232116722336, 0.33324087499917054, 0.3932504102308558, 0.3999435479397857, 0.44255993047770886, 0.5112405664243904 ] }, "TD_Flow": { "mse": [ 0.01184851344835584, 0.010786527094556018, 0.009617611223573895, 0.009788855768788858, 0.01007689897987051, 0.009982739735523202, 0.009869059301918571, 0.009899547485386385, 0.009841317803856126 ], "spearman": [ 0.07524632499561912, 0.10303778702361933, 0.09430992950086267, 0.10601777450587961, 0.11888245807159216, 0.17335622948550555, 0.1837782847618214, 0.230759526158279, 0.2809612011278045 ] }, "TD_Diff": { "mse": [ 0.0015975407917896086, 0.000746174413445629, 0.0006860945744313031, 0.0006399347520819659, 0.0006386618184640088, 0.000629829204749595, 0.0006258122240883157, 0.0006237646935719493, 0.0006227595256305873 ], "spearman": [ 0.006456285131277341, 0.021888454746255406, 0.006373864470026992, 0.01022016199504328, -2.0636173855807636e-05, -0.04564384280833171, 0.004251800952902602, 0.011348794480102039, 0.005812044168172316 ] }, "InFOM": { "mse": [ 0.007496027183252874, 0.009234343424406571, 0.008420520571427515, 0.007481884923759336, 0.007369778704615256, 0.007175795587960255, 0.007641203243504899, 0.008583889444194956, 0.007613611726948539 ], "spearman": [ 0.057518779773270266, 0.09117122257878248, 0.09015696867776436, 0.0996223365497919, 0.1113815797635261, 0.12538427717116196, 0.16395858040882402, 0.19531885254042228, 0.24854698481904275 ] }, "InFOM_g": { "mse": [ 0.0065082259129675205, 0.0074146440387734954, 0.007080035859318371, 0.0061900904409794375, 0.007138831433798376, 0.007612788075227783, 0.006918347870923911, 0.007408811417345433, 0.007385370813099547 ], "spearman": [ 0.061033546369833096, 0.07147035809939264, 0.08371397142571049, 0.09232291954938857, 0.06193246182682264, 0.10756612214362962, 0.14447871383234503, 0.20646102579437314, 0.24363664997797935 ] }, "MC": { "mse": [ 0.027815806106538245, 0.027815806106538245, 0.027815806106538245, 0.027815806106538245, 0.027815806106538245, 0.027815806106538245, 0.027815806106538245, 0.027815806106538245, 0.027815806106538245 ], "spearman": [ 0.202755752049879, 0.202755752049879, 0.202755752049879, 0.202755752049879, 0.202755752049879, 0.202755752049879, 0.202755752049879, 0.202755752049879, 0.202755752049879 ] }, "WM": { "mse": [ 0.01739171578815001, 0.013893204795795313, 0.008847534585149745, 0.006499210381027634, 0.006604851406388169, 0.00547932808573963, 0.005314166354901808, 0.005038753656812123, 0.004974256248472475 ], "spearman": [ 0.13907472001828505, 0.16654624730685808, 0.21579115833781196, 0.24680907524237508, 0.2524252769303147, 0.25433974821263394, 0.2737714713331663, 0.28633813109354533, 0.27870452671221696 ] } }, "truth_kind": "fresh_rollout", "truth_std": 0.02334982712174252, "truth_mean": 0.008961193337898013, "truth_single_std": 0.17435385274445053, "truth_single_mean": 0.049474461929701646, "corr_fresh_vs_single": 0.6376999768547283, "infom_free_bits": 0.5, "n_anchors": 2000, "timing_s": 1158.8914308547974}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189{ "env": "antmaze", "reward": "dense", "goal_mode": "hindsight", "sample_counts": [ 1, 2, 4, 8, 16, 32, 64, 128, 256 ], "methods": { "Gen_Q": { "mse": [ 0.09832680783858422, 0.060340211373284734, 0.041215138982056115, 0.0330517144742729, 0.02662042341592559, 0.024270922724286464, 0.022656015513547276, 0.022460478089905925, 0.02203114452874121 ], "spearman": [ 0.6580762972626315, 0.715140371321448, 0.765306423826606, 0.7920763935190984, 0.8262295701172288, 0.8433790358447589, 0.8522388930597232, 0.8536967839241959, 0.856609076652269 ] }, "CFM_Direct": { "mse": [ 0.08724431859867525, 0.05279723865975442, 0.03577178825508232, 0.026846003856895655, 0.023050487152974267, 0.020808116974897886, 0.01980876969353124, 0.019376196223055288, 0.01919401280717881 ], "spearman": [ 0.7024532551133137, 0.7591448179249216, 0.8044292299089684, 0.8430350827587706, 0.8647518676879669, 0.8768676440457365, 0.8828850497212625, 0.8865581861395465, 0.8859380049845011 ] }, "TD_Flow": { "mse": [ 0.13896130004511656, 0.13840645849123234, 0.13697502485484075, 0.13698014831025665, 0.1366122869411925, 0.1365192482390342, 0.136519982959805, 0.13657040650051513, 0.13655550920466522 ], "spearman": [ 0.6767997026999257, 0.6737220364305091, 0.6809491492372873, 0.6809513887378471, 0.6823368370842092, 0.685388088347022, 0.684792239704857, 0.6849442037360509, 0.6853005363251341 ] }, "TD_Diff": { "mse": [ 0.2609142950165604, 0.2533125425308159, 0.24889352418797822, 0.24689624682090663, 0.2443826801416365, 0.2448684200808877, 0.2448892370538474, 0.24477686965087106, 0.24483782088446504 ], "spearman": [ 0.09814778003694502, 0.0732174468043617, 0.09844018111004527, 0.10574693493673373, 0.12405021551255388, 0.12343776385944095, 0.1495695928923982, 0.16247253611813403, 0.15897293474323368 ] }, "InFOM": { "mse": [ 0.07642496690852821, 0.07511339171979227, 0.07448498370677262, 0.07403949933778832, 0.07435572407258147, 0.07431669390009159, 0.07436973719901586, 0.0741467615634472, 0.0742813198302641 ], "spearman": [ 0.7151938172984543, 0.7189133367283341, 0.7200533205133302, 0.7213879548469887, 0.7199203015000455, 0.7209612482403119, 0.7204913536228383, 0.7211430182857546, 0.7206578101644525 ] }, "MC": { "mse": [ 0.03522793997309101, 0.03522793997309101, 0.03522793997309101, 0.03522793997309101, 0.03522793997309101, 0.03522793997309101, 0.03522793997309101, 0.03522793997309101, 0.03522793997309101 ], "spearman": [ 0.800676536169134, 0.800676536169134, 0.800676536169134, 0.800676536169134, 0.800676536169134, 0.800676536169134, 0.800676536169134, 0.800676536169134, 0.800676536169134 ] }, "WM": { "mse": [ 0.09138134528361064, 0.06330578411840163, 0.05210805369818717, 0.045298198813499044, 0.042874524950862955, 0.040039053755682716, 0.039389587221964464, 0.03892915947646542, 0.03858335433209311 ], "spearman": [ 0.6268260331467473, 0.717544064386016, 0.765502064375516, 0.7917411284352822, 0.8009912512478128, 0.8148880602220151, 0.8195293283823322, 0.8242874375718593, 0.824310164077541 ] } }, "truth_std": 0.31527707126650545, "n_anchors": 2000, "timing_s": 1530.3105659484863}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189{ "env": "antmaze", "reward": "sparse", "goal_mode": "hindsight", "sample_counts": [ 1, 2, 4, 8, 16, 32, 64, 128, 256 ], "methods": { "Gen_Q": { "mse": [ 0.055585630872788734, 0.03209536467478736, 0.023003091460784643, 0.018042038720398806, 0.015684606572851974, 0.01422109663400764, 0.01344589798524744, 0.0129312413622943, 0.013189369520213863 ], "spearman": [ 0.4152561510529438, 0.4469347655973817, 0.4812905654880857, 0.4494875385304803, 0.4465977879229545, 0.46604941289757695, 0.46993439792261504, 0.4805144635953005, 0.4909677274429421 ] }, "CFM_Direct": { "mse": [ 0.05719090914627583, 0.029077136005359064, 0.02145314316451038, 0.017488830335567127, 0.01448793313072575, 0.013342245312467934, 0.012487317731272018, 0.012481111659454048, 0.012108308184018377 ], "spearman": [ 0.4501335929879421, 0.47304542782790815, 0.5017453331264341, 0.47441798028530474, 0.4778392928189935, 0.47767384224013143, 0.5183280357443193, 0.5132076932498179, 0.5258666129435713 ] }, "TD_Flow": { "mse": [ 0.09293201460927017, 0.08808659018504053, 0.08434806353048867, 0.08365535325412328, 0.08356136001114457, 0.08306249634943325, 0.08360230785007491, 0.08322043003060804, 0.08312975151658605 ], "spearman": [ 0.07767138855020662, 0.10839389940023406, 0.13975239133133902, 0.1475654216267524, 0.1408556303810672, 0.1607928167511241, 0.19924532941450385, 0.2059521256465402, 0.22716954106975618 ] }, "TD_Diff": { "mse": [ 0.08213785824709888, 0.08166774186487734, 0.08178813599754832, 0.08167749062997802, 0.08166612146327444, 0.08161235435632795, 0.08154760013300259, 0.08159491485729584, 0.08162361587298464 ], "spearman": [ 0.01272688108497694, NaN, -0.024348509710485657, -0.004509396257843656, -0.00658721444566136, 0.025463359558515666, 0.059618895989121005, 0.016447192860791025, -0.019892715714704766 ] }, "InFOM": { "mse": [ 0.08328968247194281, 0.07891418307536292, 0.0798122859783059, 0.07942225329812161, 0.07884979974737584, 0.07895362762917531, 0.07873399096006403, 0.07886544116165939, 0.07854015894406502 ], "spearman": [ 0.07794037777901026, 0.08342894329057118, 0.10225059565198165, 0.10714331487997845, 0.13776083983981308, 0.11330239135086026, 0.12878075047250362, 0.13246811417701584, 0.19565664231698682 ] }, "MC": { "mse": [ 0.018930145773193494, 0.018930145773193494, 0.018930145773193494, 0.018930145773193494, 0.018930145773193494, 0.018930145773193494, 0.018930145773193494, 0.018930145773193494, 0.018930145773193494 ], "spearman": [ 0.4180086300762524, 0.4180086300762524, 0.4180086300762524, 0.4180086300762524, 0.4180086300762524, 0.4180086300762524, 0.4180086300762524, 0.4180086300762524, 0.4180086300762524 ] }, "WM": { "mse": [ 0.07055993771026252, 0.06326281722580201, 0.05735817216165244, 0.05730059061838415, 0.05649657769355252, 0.055895166092147716, 0.05569865217291078, 0.05563564350588654, 0.055336064876993704 ], "spearman": [ 0.1969030459847711, 0.2590416096015826, 0.33409909141678096, 0.40301228650778376, 0.4379121640343478, 0.462926215154373, 0.47630417567911165, 0.47608359724742694, 0.4658213685820684 ] } }, "truth_std": 0.2578413642406279, "n_anchors": 2000, "timing_s": 1214.1306302547455}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189{ "env": "pointmaze", "reward": "dense", "goal_mode": "hindsight", "sample_counts": [ 1, 2, 4, 8, 16, 32, 64, 128, 256 ], "methods": { "Gen_Q": { "mse": [ 0.12778372166653873, 0.0698594411920873, 0.05008865410214841, 0.037088144294540784, 0.030318811155822807, 0.02748401785374604, 0.026075085222513558, 0.02534396307421322, 0.02490245905992911 ], "spearman": [ 0.42331239082809774, 0.5274003450478614, 0.5805442691360672, 0.6579795954948989, 0.7117018959254738, 0.7411896337974084, 0.7539151044787762, 0.7649078597638055, 0.7673468228744608 ] }, "CFM_Direct": { "mse": [ 0.11151697526316774, 0.0660163135957811, 0.04484104282979001, 0.03563214823645547, 0.03065341655129359, 0.02808025411914018, 0.027513977794631227, 0.026696414148982783, 0.026269267417195003 ], "spearman": [ 0.5086944911736229, 0.591680468420117, 0.6796584604146151, 0.7329531377382844, 0.7700604260151065, 0.7862325135581283, 0.793473223868306, 0.8047081471770368, 0.8074903103725776 ] }, "TD_Flow": { "mse": [ 0.07974784645143249, 0.07931513944399748, 0.07854905309427794, 0.07850440738910294, 0.07820086420325074, 0.0781099860163211, 0.07823036426007743, 0.07816021175562148, 0.07805842869827549 ], "spearman": [ 0.6490632632658158, 0.6503463880743567, 0.6522761980690496, 0.6526209911552477, 0.6538140434535109, 0.6540568380142094, 0.6537502349375587, 0.6537539369384843, 0.6542755530688882 ] }, "TD_Diff": { "mse": [ 0.17087405572717615, 0.161649791169361, 0.15948016560137757, 0.1562590893527227, 0.15555193211212048, 0.15543839742363974, 0.15500677783426445, 0.15505181947626062, 0.1550808636987761 ], "spearman": [ 0.03657365564341391, 0.029842975460743864, -0.024771883692970925, -0.010482329620582403, -0.029386493846623462, -0.012639909164717258, -0.011645710411427602, -0.017167465291866323, -0.010359479589869897 ] }, "InFOM": { "mse": [ 0.07559991256029597, 0.07500807422938326, 0.07441242820195469, 0.07442316179733904, 0.0740241526167039, 0.07416641089423713, 0.07389522539798822, 0.07395968824696779, 0.0739955647002355 ], "spearman": [ 0.6370173032543257, 0.6387663741915935, 0.6410725437681359, 0.6402374890593723, 0.6408379917094978, 0.6410929617732404, 0.6416973974243493, 0.6420746655186663, 0.6415729693932424 ] }, "MC": { "mse": [ 0.023889286258653778, 0.023889286258653778, 0.023889286258653778, 0.023889286258653778, 0.023889286258653778, 0.023889286258653778, 0.023889286258653778, 0.023889286258653778, 0.023889286258653778 ], "spearman": [ 0.7915968328992081, 0.7915968328992081, 0.7915968328992081, 0.7915968328992081, 0.7915968328992081, 0.7915968328992081, 0.7915968328992081, 0.7915968328992081, 0.7915968328992081 ] }, "WM": { "mse": [ 0.06941241314374823, 0.0644301342637793, 0.06125399096255823, 0.05921637110622332, 0.05816723762636917, 0.057690365379882036, 0.05753941685436158, 0.057751014690720345, 0.05762761204936133 ], "spearman": [ 0.6262137981517512, 0.635016736254184, 0.6407963786990947, 0.6491499092874773, 0.6517025229256307, 0.6524782826195706, 0.653377847844462, 0.6508678807169702, 0.6509279332319833 ] } }, "truth_std": 0.2294491968554867, "n_anchors": 2000, "timing_s": 1258.4001116752625}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189{ "env": "pointmaze", "reward": "sparse", "goal_mode": "hindsight", "sample_counts": [ 1, 2, 4, 8, 16, 32, 64, 128, 256 ], "methods": { "Gen_Q": { "mse": [ 0.04808570043134326, 0.021966885426629966, 0.014795708637322698, 0.011046481685835975, 0.010476943571515608, 0.008747652508559117, 0.008480607362471422, 0.008142594805266277, 0.007968927186799075 ], "spearman": [ 0.18303071782421834, 0.22344687008545253, 0.18281810544331822, 0.22073092270165098, 0.21561631588889504, 0.23071539529849233, 0.19943554039701147, 0.2514033278559922, 0.25697265675396436 ] }, "CFM_Direct": { "mse": [ 0.03498065979813342, 0.02079295105780941, 0.014327707063795738, 0.011171258588752654, 0.01081052753775002, 0.00885727310881407, 0.008918571428368032, 0.008801009355483204, 0.008670353852834569 ], "spearman": [ 0.2586319054363104, 0.21932167906068845, 0.2366477367626352, 0.2600880816765356, 0.24678213299589274, 0.2253748833339077, 0.25578529174281084, 0.27726322302262263, 0.2708359160437985 ] }, "TD_Flow": { "mse": [ 0.04337951589552462, 0.0430248312662895, 0.04138731778981148, 0.0420075676853675, 0.04162768838683979, 0.04162505805019898, 0.04159268189167733, 0.041613145093350394, 0.04166656317160184 ], "spearman": [ 0.04352224393628135, 0.03571261801747968, 0.06158621343853613, 0.05001454624621038, 0.047658938287739865, 0.0883835521536757, 0.10759295040473724, 0.1751435039631348, 0.21453562073560814 ] }, "TD_Diff": { "mse": [ 0.03284698835006704, 0.03297180179029915, 0.0329580905373562, 0.032856997701225535, 0.03285664070113941, 0.03284487499107561, 0.03284789162851942, 0.03284412882440819, 0.03283367848486806 ], "spearman": [ NaN, -0.027834578968559343, -0.008257785848803158, 0.010713424137143004, -0.028867737500819085, -0.02727007305534989, -0.0007363857253201758, -0.055464582882258, -0.033014944197153125 ] }, "InFOM": { "mse": [ 0.03909114893198496, 0.039959894677207834, 0.03965070809175717, 0.03885974022830703, 0.0389603909227548, 0.03920793198266543, 0.03913591861300517, 0.03879879841051512, 0.03905248915878158 ], "spearman": [ 0.03301501933993944, 0.038035748267269374, 0.02909102118104774, 0.03512273226151782, 0.048326147476086455, 0.06783464027500916, 0.0957432433668396, 0.14193655613626033, 0.18220415035227308 ] }, "MC": { "mse": [ 0.006189354935677517, 0.006189354935677517, 0.006189354935677517, 0.006189354935677517, 0.006189354935677517, 0.006189354935677517, 0.006189354935677517, 0.006189354935677517, 0.006189354935677517 ], "spearman": [ 0.33240338177993956, 0.33240338177993956, 0.33240338177993956, 0.33240338177993956, 0.33240338177993956, 0.33240338177993956, 0.33240338177993956, 0.33240338177993956, 0.33240338177993956 ] }, "WM": { "mse": [ 0.026011480840824858, 0.02410242341074931, 0.021236370736227552, 0.020891487952971802, 0.020971754853957178, 0.019755599094424044, 0.019918689747898767, 0.01984870858119337, 0.019964754213000587 ], "spearman": [ 0.17274687114896045, 0.18122668928319796, 0.22387365132145035, 0.2164245672527173, 0.24261346944093085, 0.21906809716531517, 0.22642132105690743, 0.21875605967896797, 0.21479586972038536 ] } }, "truth_std": 0.17435385274445053, "n_anchors": 2000, "timing_s": 3662.839212179184}123456789101112131415161718192021222324252627282930313233# The RSM ablation matrix
Every recipe dimension, the options tested, and the verdict with numbers.Success rates are puzzle-3x3 **officials** (50 ep/task) unless marked (p) =periodic band. Mechanism explanations: [`DESIGN.md`](DESIGN.md). Protocol:[`RESULTS.md`](RESULTS.md). Don't re-run settled rows without cause.
| # | dimension | options tested | verdict ||---|---|---|---|| D1 | **carrier** | 3-network / **2-model** | both clear the TD bar at scale; 3-network peaks higher (0.968 final) but adds a distilled critic + value net; 2-model reaches 0.928–0.960 official with two networks — **the RSM carrier** || D2 | **recursion form** | off / certificate (max) / **probabilistic (expectation)** | carrier-split, decisively: the 2-model **requires** the expectation form (certificate collapsed it: 0.404 vs 0.524 no-recursion; expectation powers every record); no-recursion control ceilings at 0.712 vs 0.82–0.96 with chains — recursion lifts the *ceiling* || D3 | **hop discount β** | fixed depth-1 / β=0.90 / 0.95 / **0.98** | β-rule stochastic depth > fixed (0.724 vs 0.547 cohort at 1M); shorter hops win: 0.98 ≥ 0.95 ≫ 0.90 (0.584) — deeper chains compound generation noise || D4 | **composition density** | every-2 / **every step** | every-step > every-2 (0.728 vs 0.547 cohort mean) — more SGD averaging of generated-midpoint noise || D5 | **midpoint source** | dataset retrieval (ε-grid) / **generated (completion head)** | retrieval ruled out (doesn't scale past discrete goal spaces); retrieval-free matches then exceeds the retrieval-era 0.784 || D6 | **midpoint / read-out pessimism** | none / min over K | **exact no-op everywhere** (training 0.560≈cohort; test-time 0.224=0.224) — the errors are systematic bias, not noise; only structural fixes work (D2, D7) || D7 | **batch size** | 1024 / **4096** / 8192+ | the biggest single lever: throughput saturates at 4096 but *quality* keeps improving (0.5-shelf → 0.867+ banked on the 2-model); >4096 is wall-clock waste || D8 | **actor-agreement weighting** | on / **off** | 2-model: drop — six matched checkpoints never favored it (chains already re-anchor on the live actor); it was a 3-network cold-start device only || D9 | **γ-conditioning encoding** | none / scalar column / one-hot bins / **Fourier log-horizon** | scalar is a trap (~0.2 drag: the model learns the γ-marginal); one-hot fits best but policies worst (data split); Fourier gives the spectrum for free — required for recursion (needs Q at β *and* γ from one model) || D10 | **speed stack** | host vs fused; 16 vs 4 actor-loss orders; data-parallel; warm starts | all quality-neutral, verified: fused ≈5× host, 4-order ≈2×, pmap bit-identical ~99% weak scaling; warm starts shift the early curve only || D11 | **read-out** (per goal space) | exact `gl` / ELBO / kernel-MC | discrete: exact `gl` (kernel-MC flat 0.000, ELBO plateaus 0.12); continuous: ELBO at the goal point (kernel-MC lost) — auto-selected in `rsm.py` || D12 | **BC weight α** (continuous goals) | TD-reference / 10× / 1.0, ± ramp/pess | two-sided anchor: TD-reference under-anchors (peak-then-collapse), 1.0 over-anchors (~0.25 cap); ~10× the TD reference is the stable window (pointmaze 0.03) |
**The cross-cutting finding.** Max-selection over noisy generative estimatesis the failure mode in every disguise — training certificates (D2), spike-banked snapshots (conversion −0.07…−0.15), test-time action argmax (0.760 →0.224). Every fix that worked is structural: expectation-form estimators,density penalties, batch/critic averaging. Resampling and pessimism-by-minnever helped (D6), because the errors are bias, not variance.
**The recipe in one sentence.** Discount-conditioned (Fourier) occupancydiffusion + completion head → coin-terminated β=0.98 expectation walks →actor = first-hop read-out ascent + exact-IS midpoint term + BC anchor, atbatch 4096 — no critic, no value net, no weighting, no max.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185# RSM design — how it works, and what we tried before it
The formulation with figures is in the [root README](../README.md); thenumbers are in [`RESULTS.md`](RESULTS.md); the per-dimension verdicts are in[`ABLATION.md`](ABLATION.md). This file has two halves: **how the shippedtrainer works internally** (§1), and **every design we tried and why it wasdropped** (§2) — read §2 before proposing a variant, it has probably been run.
---
## 1. The shipped design (`rsm.py`)
Two networks and one auxiliary head:
| module | what | notes ||---|---|---|| occupancy $p_\theta(z\mid s,a,\tilde\gamma)$ | conditional diffusion over reward-relevant coordinates $z$ | masked **discrete** diffusion over bits (discrete goals) or ε-prediction **Gaussian** diffusion (continuous); Polyak-EMA copy used for all read-outs || actor $\mu(s,g)$ | deterministic GCActor, DDPG+BC through the read-out | live + EMA copy; banking dual-evals both || completion head (recursion only) | conditional Gaussian diffusion: midpoint coordinates → full state | co-trained on the same tuples, bits teacher-forced; lets the chain hand a *full state* to the actor with no dataset retrieval |
### 1.1 Occupancy training
Tuples $(s_t, a_t) \to z_{t+k}$ with $k\sim\mathrm{Geom}(1-\tilde\gamma)$ fromoffline trajectories, with absorbing first-passage handling andreward-targeted stratification (exact importance weights, so the fit staysunbiased). The discount $\tilde\gamma$ is sampled per-tuple: the task γ withprobability 1−p, else log-uniform **in horizon space** over $[\beta,\gamma]$,and encoded with Fourier features of the normalized log-horizon (K=4 sin/cospairs). Maximum likelihood only — no reward, no bootstrap, no TD.
### 1.2 Q read-outs
- **Discrete (`gl`)**: exact any-order autoregressive likelihood of the goal's bits under the masked diffusion — teacher-forced unmasking, exact per order, averaged over orders (16 for values, 4 inside the actor loss — quality-neutral, ~2× faster). Zero variance and differentiable in $a$.- **Continuous (`elbo`)**: diffusion-classifier surrogate $\hat Q=\exp(-c \hat L(g\mid s,a))$ where $\hat L$ is the ε-denoising loss evaluated **at the goal point** with stratified timesteps (K=16 draws, one network apply each). No likelihood, no sampling, no normalizer — recursion ratios cancel it. (An uncertainty-penalized variant that adds the std over draws was raced and lost to the plain mean; archived.)
### 1.3 The probabilistic β-recursion (discrete goals)
The splitting identity with continuation probability$p=\frac{\gamma-\beta}{\gamma(1-\beta)}$:
Q̄_γ(s,a,g) = (1−p) · gl_β(s,a,g) + p · E_{x∼d_β(·|s,a)}[ Q̄_γ(x, μ(x,g), g) ]
Runtime shape (all on-device, inside the fused `lax.scan` step):
1. **Coin per row**: tails → freeze; heads → hop.2. **Hop** = sample midpoint coordinates from the EMA occupancy at the *hop* discount β (ancestral, one sample), complete to a full state with the completion head (25-step DDIM), let the **live actor** re-decide there — the policy-improvement coupling; nothing is retrieved from a dataset.3. Fixed-depth masked scan (10 levels, shapes static under jit); terminated rows carry their stop-state. One `gl_β` read at every row's final node is the estimate. Truncation at the cap is a small, decaying bias.4. **Expectation form everywhere — no max.** The actor's gradient reaches the midpoint term through the exact likelihood ratio `gl(s,μ,c)/stopgrad(gl(s,a,c))` (bits are not reparameterizable).5. Composition gates on after `--rec_after` (default 100k) so chains run on a competent occupancy.
At (γ,β)=(0.99, 0.98): p≈0.51, mean chain ≈2 hops of ~49-step horizon each.β=0.98 beat 0.95 beat 0.90 — shorter, fewer hops compound less generationnoise.
### 1.4 Actor objective and banking
L(μ) = −log Q̂(s, μ(s), g) / mean(|log Q̂|) + α‖μ(s) − a_data‖²
The normalizer keeps the gradient scale stable across read-outs. α isper-environment and **two-sided** for a generative Q (§2, "BC anchor").Training keeps live + EMA actors, dual-evals both periodically, and banks thewinner on each new peak — the oscillation-vs-bank discipline in[`RESULTS.md`](RESULTS.md) exists because of this.
### 1.5 Throughput (settled)
Fused `lax.scan` dispatch (~5× the host loop), batch 4096 (a *quality* lever;throughput saturates there), 4-order actor read. Multi-GPU pmap data-parallelism was verified bit-identical with ~99% weak scaling (archived in`unused/genq_joint_fast.py`). ~4.9 s/100 steps on one H100 at batch 4096;~2.4 s/100 on four.
---
## 2. Tried and dropped — the design history
Reference bars: puzzle GCIQL 0.928 @500k (ceiling 0.947–0.948); pointmazeGCIQL band ~0.7–0.8. Trainer lineage: staged (`genq_jax`) → joint host loop(`genq_joint`) → fused multi-variant (`genq_joint_fast`) → **`rsm.py`** (thesurviving recipe only). All archived code: [`unused/`](unused/README.md).
### Carrier (how many networks)
| design | result | why dropped ||---|---|---|| Frozen occupancy + GCIQL critic distillation | never beat plain GCIQL | frozen behavior critic can't follow the improving policy; replaced by joint training || 3-network (occupancy + distilled critic + actor) | **0.968** puzzle final — the all-time record | doubles the network count; the 2-model reaches 0.928–0.960 official on its own, and "no critic" is the claim || AWR actor | declining, 0.013 | within-support reweighting can't exploit the differentiable read-out || GLIQL-style extraction | below DDPG+BC on every cell | || **2-model DDPG+BC through the read-out** | puzzle 0.928–0.960, pointmaze 0.950/0.850 | **KEPT — this is RSM** |
### Occupancy architecture
| design | result | why dropped ||---|---|---|| Factored per-coordinate occupancy | incoherent joint samples | future coordinates are strongly dependent (walls, object couplings) || Inpainting formulation | eval-side wins only | no policy-improvement lift || Gaussian mixture density head | — | ruled out a priori: occupancy is multimodal (root `CLAUDE.md` hard requirement) |
### Discount handling
| design | result | why dropped ||---|---|---|| Fixed single γ | recursion impossible | needs Q at both β and γ || Scalar γ column | 0.74 ceiling | γ moves 0.04 while the horizon triples — the MLP resolves nothing and learns the γ-marginal (≈0.2 cost) || Two-point / one-hot bins | best occupancy *fit*, worst *policy* | splits the data per bin || **Fourier log-horizon features** | spectrum for free | **KEPT** |
### Long-horizon composition
| design | result | why dropped ||---|---|---|| No recursion | 0.712 final at record batch | kept only as the continuous-goal default until the guards land || Value distillation into a critic | worked | needs the third network || Certificate / max recursion | 0.404–0.504 on the 2-model | max propagates occupancy over-estimates; the critic-buffered 3-network tolerated it, the 2-model cannot || ε-grid retrieved midpoints | 0.784 historical record | assumes dataset lookup + goal-space structure — ruled out ("no retrieval"); completion head replaced it at no cost || Scheduled TD handoff | 0.920 | ruled out of scope: not TD-free (kept only as a machinery sanity check) || β=0.90 chains | 0.584 | too many hops — compound generation noise || **Probabilistic β=0.98 chains, expectation form, one sample/hop** | 0.82–0.96 | **KEPT — the "R" in RSM** |
### Read-out
| design | result | why dropped ||---|---|---|| Kernel Monte-Carlo over DDIM samples | 0.000 discrete / lost continuous | product-kernel log-Q noise at small K drowns the BC gradient || ELBO on discrete | 0.12 plateau | exact likelihood is free on bits || min-K read-out pessimism | exact no-op | the error is bias, not noise || uncertainty-penalized ELBO (mean + λ·std) | 0.213 vs plain's 0.85+ banks on pointmaze | penalizing draw-spread punished the wrong thing; dropped || BC-weight ramp (anneal 1.0 → α) | 0.640 vs plain's 0.85+ banks | steadier early, strictly slower; dropped || **`gl` exact (discrete) / ELBO at the goal point (continuous)** | the records | **KEPT, auto-selected by goal space** |
### Actor details
| design | result | why dropped ||---|---|---|| Actor-agreement weighting | needed only to cold-start the 3-network | every RSM record ran without it (`pi_alpha 0`) || TD-reference α on continuous goals | 0.680 peak → collapse | the anchor is two-sided for a generative Q; rule: ~10× the TD reference || Test-time raw-argmax Q-filter | 0.760 → 0.224 with more candidates | optimizer's curse; density-penalized variant kept as a tool in `eval_plan.py` |
### Throughput dead ends
bf16/TF32 (no win at this scale), batch >4096 (saturated), occupancy warmstarts (early-curve only), fixed midpoint counts (the β coin subsumesdepth+width in one knob).
---
## 3. Recursion on continuous goals: solved for survival, open for lift
The differentiated chain that sets the puzzle records **destabilizescontinuous-goal training**: collapse ~25k steps after composition switcheson — at every BC weight, regardless of occupancy maturity (a 500k-delayedarm entered composition at 0.907 and read 0.013 one eval later), and withthe ratio guard alone (CRN draws + IS-clip at 1 — clipping bounds theratio's *value*, not its gradient below 1, so the actor was still pushedtoward generated midpoints).
**The tails guard survives** (first composing arm alive on continuous goals,band intact 100k+ past the switch): stop-gradient on the entire heads term,so the actor's gradient flows only through the β tails read at the truegoal. The heads *value* still shapes credit — inside log Q it damps thetails gradient on rows the chain already reaches and amplifies unreachablerows. This is now the **default continuous recipe** (`--rec_guard auto` →`tails`), making the recipe identical across goal spaces except where thegoal space forces a difference (read-out, α, guard level).
Open measurement: whether tails-composition *lifts* the continuous bandabove the recursion-free officials (0.925 mean over eight reads) or turnsbanked peaks into sustained bands — the multi-seed race is running.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307# ogbench_genq — RSM policy improvement (JAX)
This package answers Milestone 2 of the project: **can a Q-function read off agenerative occupancy model drive policy improvement?** The answer is the**Recursive Successor Model (RSM)** — a 2-network policy-iteration agent(occupancy diffusion + actor; no critic, no TD, no max) that matches or beatsthe reference-tuned TD baseline across OGBench (all numbers +protocol: [`RESULTS.md`](RESULTS.md)).
The method, math, and figures are in the [root README](../README.md).This file is the developer guide: how to run it, how to extend it, and whereeverything lives.
## Documentation
| doc | contents ||---|---|| [`../README.md`](../README.md) | the method, paper-style: formulation, figures, headline results || [`RESULTS.md`](RESULTS.md) | all measured results + the evaluation protocol (how to read/report numbers) || [`DESIGN.md`](DESIGN.md) | how RSM works internally + every alternative we tried and why it was dropped || [`ABLATION.md`](ABLATION.md) | the 10-dimension ablation matrix with verdicts || [`VISUAL_COORDFREE_RESULTS.md`](VISUAL_COORDFREE_RESULTS.md) | strict pixels-only visual RSM result, fairness audit, and immutable artifacts |
Raw campaign material (arm-by-arm ledgers, era-specific docs, launch scripts,superseded trainers) is archived under [`unused/`](unused/README.md) — historyonly, not maintained.
## Setup
```bashcp .env.example .env # WANDB_API_KEY, WANDB_ENTITY# python env needs: jax[cuda], flax, optax, ogbench, wandb# plus the OGBench reference impls on $OGBENCH_IMPLS (utils/, agents/)```
Datasets cache to `~/.ogbench/data` on first use.
## Running RSM and the baselines
One script per method, all in [`experiments/`](experiments/); each takes`<env_id> [seed]` and writes its result JSON to`experiments/<env>/results/<seed>/`:
| script | method | what it is ||---|---|---|| `experiments/run_rsm.sh <env> [seed] [flags…]` | **RSM** | the method: occupancy diffusion + actor, no critic/TD/max; banks the best snapshot to `ckpt/` || `experiments/run_gciql.sh <env> [seed] [alpha]` | GCIQL | the reference-tuned TD baseline — the bar RSM is measured against; pass the env's published reference `alpha` (puzzle-3x3: 1.0, pointmaze: 0.003 — `$OGBENCH_IMPLS/hyperparameters.sh`) || `experiments/run_gcbc.sh <env> [seed]` | GCBC | goal-conditioned behavior cloning — the floor || `experiments/eval_official.sh <env> <ckpt.pkl> [eval_seed]` | — | the **official** 50-episode protocol on a banked snapshot; run ≥2 eval seeds and report the mean ([`RESULTS.md`](RESULTS.md)) || `experiments/run_sweep.sh <plan.txt>` | — | pack several RSM arms onto ONE GPU allocation (never one bsub per cell); plan files live in [`experiments/sweeps/`](experiments/sweeps/) || `experiments/prefetch_datasets.sh <env…>` | — | download datasets on the **login** node before submitting — compute nodes have no internet |
```bash# the method, on both goal spaces (everything defaults to the record recipe)bash ogbench_genq/experiments/run_rsm.sh puzzle-3x3-play-v0 0bash ogbench_genq/experiments/run_rsm.sh pointmaze-medium-navigate-v0 0
# the TD bar and the BC floorbash ogbench_genq/experiments/run_gciql.sh puzzle-3x3-play-v0 0 1.0bash ogbench_genq/experiments/run_gcbc.sh puzzle-3x3-play-v0 0
# the number you report (two reads, mean them)bash ogbench_genq/experiments/eval_official.sh puzzle-3x3-play-v0 ckpt/best_rsm_puzzle-3x3-play-v0_s0.pkl 0bash ogbench_genq/experiments/eval_official.sh puzzle-3x3-play-v0 ckpt/best_rsm_puzzle-3x3-play-v0_s0.pkl 1```
`rsm.py` resolves everything from the goal space (`--goal_space{auto,discrete,continuous}`, auto = from the env id): the read-out (exact `gl`on discrete, ELBO on continuous), the recursion **guard level** (fullydifferentiated chain on discrete / tails-guarded on continuous — recursionitself is on in both spaces), and the BC weight α (1.0 / 0.03). The record recipe — β=0.98probabilistic recursion, Fourier γ-encoding, batch 4096, no agreementweighting — is the default; extra flags after the seed pass straight through(`--train_steps`, `--alpha`, …; `python ogbench_genq/rsm.py -h` lists them).
**Report numbers by the protocol in [`RESULTS.md`](RESULTS.md)** — in-trainingperiodic evals overstate; officials are multi-read 50-episode evals of bankedsnapshots.
## Fair visual RSM implementation
The strict visual path is a pixels-only Recursive Successor Model (RSM), withno temporal-difference (TD) target, bootstrap, proprioception, simulatorcoordinate, reward array, or forward/world model. Its final actor uses the samerendered state and goal images as visual Goal-Conditioned Implicit Q-Learning(GCIQL). The implementation is in [`rsm.py`](rsm.py); this section explains thewinning goal-relative conditional-flow arm.
<p align="center"> <img src="figures/visual_rsm_reader_metric.svg" alt="Visual RSM: state and goal are query inputs, the sampled future is an offline training target, direct occupancy queries generate latent futures, and the official test uses only the actor" width="100%"></p>
### Goal and sampled future are different objects
For an offline row at time \(t\), the **query** is
$$(x_t,\ a_t,\ g,\ \tilde\gamma),$$
where \(x_t\) is the current image, \(a_t\) is the recorded first action, \(g\)is a goal image, and \(\tilde\gamma\) selects the occupancy horizon. The**supervised outcome** is a separate current-or-later trajectory image \(x_j\),with
$$j=t+k,\qquad k\sim\operatorname{Geom}(1-\tilde\gamma)$$
truncated at the trajectory boundary.
- The **goal** is a conditioning input and reward reference: it says which outcome should count as success. At test time it is the task-provided goal image.- The **sampled future** is the random variable being modeled: it records where the recorded trajectory lies at the sampled discounted horizon. It can be the current state, reach the goal, approach it, miss it, or precede it.- A goal and sampled future may occasionally be the same frame, but they are not interchangeable. The implementation oversamples goal-hit futures for efficiency and applies exact importance weights, preserving the truncated geometric occupancy distribution.
Half of each winning-run occupancy batch uses actor-aligned, uniformly sampledsame-trajectory future goals. The other half uses the GCIQL value-goalcurriculum (20% current, 50% same-trajectory geometric, 30% random). Futuretargets are then sampled by the discount-conditioned geometric sampler. In[`rsm.py`](rsm.py), `_occupancy_goals` chooses \(g\), while`sample_occ_tuple` separately chooses the future index \(j\).
### Why model the future-minus-goal delta?
The frozen pixel encoder exposes two representations:
- rich 256-D features \(h(x)\) for conditioning on the current scene and goal;- a compact 8-D reward-predictive latent \(z(x)\) for the modeled future and reward read-out.
A frozen diagonal index reader supplies a positive scale matrix
$$D=\operatorname{diag}\!\left(\frac{\sqrt{w_i}}{s_i}\right).$$
Instead of asking the flow to predict an absolute future latent \(z(x_j)\), itstraining target is
$$u^* = D\big(z(x_j)-z(g)\big).$$
This delta has four useful properties:
1. **The goal becomes the origin.** \(u^*=0\) means that the sampled future matches the goal in the reader's reward geometry. The direction and magnitude of \(u^*\) describe how it misses.2. **Equivalent tasks share coordinates.** Moving toward different absolute goals becomes the same problem—move the future displacement toward zero. The flow does not have to relearn a separate absolute latent offset for every goal.3. **The loss follows reward-relevant geometry.** \(D\) expands reader-sensitive directions and contracts visually large but reward-weak directions, so nuisance arm/background variation does not dominate flow matching.4. **No information is discarded.** The transform is invertible: $$ z(\hat x_j)=z(g)+D^{-1}\hat u. $$ The model remains a generative, potentially multimodal occupancy—not a scalar value regressor or a hand-coded distance critic.
The conditional flow therefore fits
$$p_\theta\!\left(u\mid h(x_t),a_t,h(g),\tilde\gamma\right)$$
using ordinary flow-matching supervision on offline geometric futures. Thewinning model is a one-hop width-256, four-layer flow. Each 2,048-row occupancybatch assigns 50% to task \(\gamma=0.99\), 25% to \(\beta=0.98\), and 25% tohorizons 8/16/32/64 with square-root-horizon priority. Beta is a supervisedendpoint here; recursion is disabled.
### Training query, direct test query, and official deployment
There are three different meanings of “sample a future”:
| phase | future source | why it is used ||---|---|---|| occupancy training | observed current-or-later frame from the offline trajectory | maximum-likelihood target \(u^*\) || direct occupancy-Q query | latent future generated by the conditional flow | Monte-Carlo reward expectation for a candidate action || official rollout | none | the deterministic distilled actor emits the action directly |
For a **direct occupancy query**, provide only current pixels, goal pixels, acandidate action, and the desired discount:
```texth_s, h_g, z_g = frozen_encoder(state_rgb, goal_rgb)u_hat[m] = conditional_flow(noise[m] | h_s, action, h_g, gamma)z_hat[m] = z_g + inverse(D) * u_hat[m]Q_occ = mean_m sigmoid(index_reader(z_hat[m], z_g))```
The winning configuration uses 25 flow steps and 64 generated latent futuresper \(Q_{\mathrm{occ}}\) target. It never receives an observed future image atquery time.
During training, these occupancy reads label the detached actor mode and nearbycounterfactual actions. The recorded behavior action is separately anchored bya direct non-TD absorbing index-return target. The flow, supervised scorer, andraw-pixel DDPG+BC actor update in the same fused step.
For the **official 0.412 rollout**, no occupancy query occurs online:
```textaction = ema_pixel_actor(state_rgb, goal_rgb)```
The saved result records `policy_action_source=deterministic_actor_mode` and37,132 audited pixels-only policy calls. No observed future, generated future,flow integration, or simulator state is needed at deployment.
### Implementation map
| implementation | responsibility ||---|---|| `reward_metric_endpoint_batch_plan` in [`rsm.py`](rsm.py) | exact task/beta/auxiliary discount allocation || `reader_metric_coordinate_diagonal` | validates and constructs \(D\) || `encode_reader_metric_future` / `decode_reader_metric_future` | invertible \(z_{\text{future}}\leftrightarrow u\) transform || `sample_occ_tuple` | samples importance-corrected geometric future targets after `_occupancy_goals` chooses \(g\) || `z_bits` / `q_reward_dec` | generates latent futures, inverts the delta, and averages reader rewards || [`genq/reward_reader.py`](genq/reward_reader.py) | frozen pixels-only index reader and metric metadata || [`genq/eval_visual_rsm_pixel_actor.py`](genq/eval_visual_rsm_pixel_actor.py) | fail-closed actor-only official evaluation || [`genq/gate_visual_occupancy.py`](genq/gate_visual_occupancy.py) | distribution, value, rank, support, and fairness gates || [`experiments/train_visual_rsm_pixel_actor.sh`](experiments/train_visual_rsm_pixel_actor.sh) | pinned frozen-reader metric-flow launcher |
The immutable checkpoint, result hashes, frozen/joint controls, and diagnosticinterpretation are recorded in[`VISUAL_COORDFREE_RESULTS.md`](VISUAL_COORDFREE_RESULTS.md).
## Running RSM on a new environment
Three decisions:
1. **Target extractor** — what are your reward-relevant coordinates? `genq/target_extractors.py` already resolves **every state-based OGBench family by env-id prefix** (mazes: agent xy; antsoccer: *ball* xy; cube: per-cube xyz; puzzle: button bits; scene: 7 task signals), so all sizes and dataset variants work out of the box. A genuinely new family needs one entry in `_spec_for` — the coordinates whose value at the goal defines success, with the layout verified against source + dataset (the file documents how). Images: use the strict path described above—train the reward-predictive encoder (`genq/train_pixel_encoder_jax.py`), precompute frozen rich/compact features (`genq/precompute_pixel_latents.py`), pass `--latent_npz`, `--pixel_encoder`, `--reward_decoder`, `--goal_hidden`, `--drop_proprio`, `--actor_input pixels`, `--occupancy_model flow`, and `--occ_target_space goal_relative_reader_metric`. The occupancy conditions on rich pixel features, models compact goal-relative futures, and the final actor consumes raw pixels. The historical `concat(proprio19, z)` latent wrapper is not strictly pixels-only and is not eligible for the fair visual result. Other high-dimensional states use `genq/train_latent_encoder_jax.py` (root `CLAUDE.md` hard requirement).2. **Goal space** — discrete alphabets get the exact read-out and the fully differentiated chain; continuous coordinates get the ELBO read-out and the tails-guarded chain. `--goal_space` overrides the env-id heuristic if it guesses wrong.3. **The BC weight `--alpha`** is the one hyperparameter to set per continuous env, and the TD-reference value is NOT automatically right: the anchor is two-sided for a generative Q (the TD value under-anchors → drift and collapse; 1.0 over-anchors → capped at behavior level). Start at ~10× the env's TD-reference alpha. (BC annealing and uncertainty-penalized ELBO were raced as stability levers and lost to the plain recipe; they are archived in `unused/genq_joint_fast.py`.) Evidence: [`ABLATION.md`](ABLATION.md), and don't re-test settled dimensions without cause.
Cluster note: pack multiple small arms onto one GPU (each arm is a small MLPdiffusion; batch-4096 arms fit 1–2 per 80 GB H100 with`XLA_PYTHON_CLIENT_MEM_FRACTION` bounded). Multi-GPU data-parallelism wasverified bit-identical with ~99% weak scaling; the pmap implementation isarchived in `unused/genq_joint_fast.py` (single-GPU covers every current env).
## Layout
```ogbench_genq/ rsm.py # THE trainer — both goal spaces (start reading here) bc.py gciql.py # baseline agents (GCBC floor, GCIQL TD bar) eval_plan.py # official evals + test-time Q-filter planning tools _runner.py # shared plumbing (paths, eval harness, baseline runners) genq/ target_extractors.py # per-env reward-relevant coordinates (edit for new envs) train_genq_jax.py # standalone occupancy trainer (warm starts, analysis) train_latent_encoder_jax.py # reward-predictive latent encoder (image envs) reward_reader.py # pixels-only frozen index reader + reader metric gate_visual_occupancy.py # strict visual occupancy/fairness diagnostics eval_visual_rsm_pixel_actor.py # actor-only official visual evaluation experiments/ run_rsm.sh run_gciql.sh run_gcbc.sh eval_official.sh # one script per method train_visual_rsm_pixel_actor.sh # fair visual launcher {env}/results/{seed}/*.json # committed officials + finals figures/ # README figures + their generators (viz_*.py at package root) RESULTS.md DESIGN.md ABLATION.md unused/ # archived: superseded trainers, campaign ledgers, launch scripts```
Checkpoints are never committed (`checkpoints/` is local-only and gitignored);result JSONs are. Campaign history with every decision: issue #57 / PR #59.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# RSM — the single recipe
One occupancy model, one DDPG+BC actor, no critic / no TD / no max. Entry point:[`rsm_recipe.py`](rsm_recipe.py) — one command, the read-out auto-resolves fromthe environment. It delegates to the validated engine (`run_rsm` in `rsm.py`) sothe numerics are exactly the settled ones; it just fixes the recipe and hidesthe experimental flags.
```bashpython -m ogbench_genq.rsm_recipe --env puzzle-3x3-play-v0 --seed 0python -m ogbench_genq.rsm_recipe --env pointmaze-medium-navigate-v0 --seed 0python -m ogbench_genq.rsm_recipe --env visual-cube-single-play-v0 --seed 0 \ --latent_npz <vallat.npz> --pixel_encoder <valenc.npz> \ --reward_decoder <valrdec_diag.npz>```
## Shared core (identical everywhere)
- **Occupancy** = conditional generative model of the discounted future-state occupancy, ML-fit on geometric-horizon `(s,a) → s_{t+k}` pairs. No reward, no bootstrap in the fit.- **Q = read-out**: an expectation under the occupancy at the goal; reward enters only at read-out time.- **Actor** = anchored gradient ascent through the read-out (DDPG+BC). No critic network, no target copies, no `max`.- **Settled constants**: γ 0.99, EMA τ 0.005, Fourier γ-spectrum, β 0.98.
## The one non-unified piece: the read-out (auto-resolved)
| env class | read-out | recursion | α | occupancy ||---|---|---|---|---|| state, discrete (puzzle-*) | exact `gl` likelihood | on (differentiated) | 1.0 | diffusion || state, continuous (mazes) | diffusion `elbo` | off | 0.03 | diffusion || visual (pixels) | goal-relative **reader-metric** flow in a frozen reward-predictive latent | off (one-hop) | 1.0 | flow |
`resolve_recipe(env_id)` in `rsm_recipe.py` picks the block; everything else isshared. Collapsing these three read-outs into one is the open unification work(tracked separately) — this recipe keeps the per-class read-out because each isthe *validated* winner for its domain.
## Acceptance / merge bar
The single recipe must beat the **GCIQL** baseline on all three, official50-episode eval (single seed):
| env | GCIQL | RSM target | read-out ||---|---|---|---|| puzzle-3x3-play-v0 | 0.928 | ≥ 0.928 | gl || pointmaze-medium-navigate-v0 | ~0.7–0.8 | ≥ 0.85 | elbo || visual-cube-single-play-v0 (fair, pixels-only) | 0.364 | > 0.364 | reader-metric |
## Verified results (single-seed, official 250-ep)
| env | RSM (clean recipe) | GCIQL | verdict ||---|---|---|---|| **visual-cube-single-noisy** (fair, pixels-only) | **0.908** @60k, **0.896** @100k | **0.404** @300k | ✅ RSM +0.49–0.50 (>2×) || **pointmaze-medium-navigate** | **0.944** (banked best, 1M) | ~0.7–0.8 | ✅ RSM clears the band || **puzzle-3x3-play** | **0.996** @425k (50-ep, per-task [1,1,1,.98,1]) | 0.928 | ✅ RSM clears the bar |
**All three envs clear GCIQL with one recipe (single-seed, official).** Note: thepuzzle in-training 15-ep periodic (0.933 @300k) *overstated* — its official 50-ep readat that snapshot was 0.888; the 0.996 is a genuine official read of the 425k snapshot(periodic ema had risen to 0.96). Always trust the official 50-ep eval, not the periodic.
Visual is the strict-fair win: both RSM snapshots (`rsm_step{60000,100000}`) render pixelsonly, `drop_proprio`, no coordinates/sim-state/reward-arrays/TD — verified in each resultJSON. GCIQL-noisy per-task [0.28, 0.80, 0.16, 0.34, 0.44]; RSM@100k per-task[1.0, 0.94, 0.64, 0.96, 0.94]. (EGL rendering core-dumps on some nodes — pin eval to aknown-good render node with `bsub -m`.)
## Verification status
- **State (puzzle, pointmaze):** validated path on `main`; datasets cached at `~/.ogbench/data`. Low risk — this is the same engine that produced the headline state numbers.- **Visual:** verified on **`visual-cube-single-noisy-v0`**, not `-play`. The `play` rendered-pixel dataset lives on the `/proj/inf-scaling/` home, which is a different unix group and not readable here; `noisy` is a fully-accessible, fair, pixels-only OGBench-visual env (1,001,000 rendered 64×64×3 frames + a matching stage-1 encoder/latent/reader). Compared against GCIQL on the *same* env. The recipe auto-resolves per-env stage-1 artifacts and the rendered-pixel dataset (+ their SHA-256) from `RSM_VISUAL_CKPT_DIR` / `RSM_OGBENCH_DATA`. The full reader-metric contract is enforced by the engine and encapsulated in `resolve_recipe`: goal-relative reader-metric flow, `reward_metric_endpoints` sampler (50% task-γ / 25% β / 25% aux, √-h over horizons 8/16/32/64), spectrum to 0.875, frozen index reader, strict raw-pixel `ddpgbc_distill` actor with the absorbing empirical index anchor, `goal_hidden`. Train is `--train_only`; eval renders pixels, so it runs as a separate `--eval_only` job on a render-capable node.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320# RSM results
**This file is the single source of truth for every RSM number.** The [rootREADME](../README.md) carries the method and the headline; it links here ratherthan repeating numbers. Internals and dropped alternatives:[`DESIGN.md`](DESIGN.md); full ablation matrix: [`ABLATION.md`](ABLATION.md).
- [1. Results at a glance](#1-results-at-a-glance)- [2. How to read these numbers (protocol)](#2-how-to-read-these-numbers-protocol)- [3. The GCIQL bar — reproduction + fair comparison](#3-the-gciql-bar--reproduction--fair-comparison)- [4. Per-cell notes](#4-per-cell-notes)- [5. Special studies (goal-free · visual vs world models · scene · supervision-fair)](#5-special-studies)- [6. Negative / closed results worth knowing](#6-negative--closed-results-worth-knowing)
Numbers current as of 2026-07-22; the state sweep runs on 8 packed GPUs, allcells `--ckpt`-resumable. **official** = 50-ep banked read (§2); **peak** = bestperiodic bank, job still training.
---
## 1. Results at a glance
### A. State — RSM best vs GCIQL-best (like-for-like, §3)
| cell | RSM (official) | GCIQL-best | verdict ||---|---|---|---|| pointmaze-medium-navigate | **0.925** (8 reads) | 0.585 | ✅ RSM ≫ || cube-single-play | **0.924** | 0.772 | ✅ RSM ≫ || puzzle-4x4-play | **0.644** | 0.303 | ✅ RSM ≫ || humanoidmaze-medium-navigate | **0.392** (peak 0.51) | 0.315 | ✅ RSM > || puzzle-3x3-play | 0.960 | 0.973 | ≈ tie || antmaze-medium-navigate | 0.762 | 0.791 | ≈ tie || antmaze-large-navigate | 0.360 | 0.34 (published final) | ≈ at bar || pointmaze-large-navigate | 0.400 peak | — | in progress || scene-play | 0.44 → *improving* | 0.579 | ⏳ below (rec-ON 0.45↑ + mixed read-out) |
**Best-vs-best: RSM clearly wins 4, ties 2 (puzzle-3×3, antmaze-medium), below on scene.**
### B. State — new-coverage breadth (seed 0; no standard GCIQL bar for most)
| cell | family | RSM (seed 0) | status ||---|---|---|---|| antsoccer-arena-navigate (α=0.3) | locomotion+ball | **0.452** official | done — α=0.3 ≫ α=1.0 (0.32); seed-1 peak 0.52 || pointmaze-teleport-navigate (α=0.03) | maze+teleport | **0.380** official | done; seed-1 peak 0.52 → revising up || pointmaze-giant-navigate (α=0.03, γ=.995) | long-horizon maze | **0.512** official | done || antmaze-teleport-navigate (α=3) | maze+teleport | **0.328** official | done (peak 0.493) || cube-triple-play (α=3) | 3-cube manip | **0.136** official | done (peak 0.173) || puzzle-4x5-play (α=3) | wide bit-vector | 0.187 peak | training || puzzle-4x6-play (α=3) | widest bit-vector | 0.080 peak | training (hardest puzzle) || cube-quadruple-play (α=3) | 4-cube manip | 0.000 | floor — hardest manip (honest, not a bug) || humanoidmaze-large / giant (α=0.03, γ=.995) | giant loco | in progress | slow (largest obs) |
The sweep deliberately reaches for cells where RSM is *not* expected to be easy(4-cube manipulation, giant humanoid mazes, 4×6 puzzles) — reported as-is, floorcells included. Teleport/giant mazes (0.33–0.51) show the occupancy recipetransfers to discontinuous and very-long-horizon dynamics. **Multi-seed bands**land as seeds 1,2 reach 1M; early signal has antsoccer/pointmaze-teleport seed-1*above* seed-0, so those single-seed numbers likely revise **up**.
### C. Visual — image-latent occupancy vs image world models (matched 64² pixels, §5)
| method | obs | replay protocol | OGBench (real tasks) ||---|---|---|---|| **RSM image-latent, recursion-on** | image-latent | — | **0.684** official ||  recursion-off (= jumpy-WM limit) | image-latent | — | **0.592** official || RSM, state (cross-modality upper bound) | state | 1.00 | 0.924 || LeWM (world model) | image | 0.68 (inflated) | **0.000** || DINO-WM (world model) | image | 0.54 | **0.000** || RSM, supervision-fair (pixels only, no coordinate) | image-latent | — | **≈0.000** (reward coord is load-bearing, §5) |
At matched modality the external world models score **0.000** on the benchmark;RSM's own world-model limit (recursion-off) scores **0.592** and compositionlifts it to **0.684**. LeWM's replay 0.68 is on an inflated protocol (32% ofepisodes start at the goal — [`misc/lewm/LEWM_EVAL_ANALYSIS.md`](../misc/lewm/LEWM_EVAL_ANALYSIS.md)).**Caveat (matched modality ≠ matched supervision):** RSM's encoder uses the cubexyz reward coordinate the WMs don't; strip it (recon-only, LeWM's exact diet) andRSM also reads **≈0.000** (§5). So RSM's visual win is at matched *modality*, on*more* supervision — not at matched supervision.
---
## 2. How to read these numbers (protocol)
- **Official** = 50 episodes/task (250 total) via `eval_plan.py --plan_k 1 --episodes 50 --vec 25` on a **banked snapshot**. This is the only number to report. In the JSONs it is `final_best_ckpt` (= `success_rate`); `best_sr` is the periodic peak.- **Periodic** = the 15-ep/task evals printed during training. They systematically overstate: measured official conversion is −0.005…−0.04 for snapshots in a sustained band, −0.07…−0.15 for snapshots at a fresh spike.- **Banking**: training keeps a live actor and a Polyak-EMA actor, dual-evals both, and snapshots whichever wins on a new periodic peak (`--save_best`). Training oscillates (±0.3 swings around the band are normal); bank + EMA are load-bearing, not cosmetic.- **Multi-read means**: same-snapshot officials vary ±0.10 read-to-read (episode init). Records are the mean of ≥2 independent 50-episode reads.- **Seeds**: ≥2 training seeds before a recipe-level claim; measured cross-seed spread is ±0.05–0.12.
---
## 3. The GCIQL bar — reproduction + fair comparison
Reference bars are the **official published OGBench GCIQL** numbers (Park etal., Table 2: 8 seeds, 1M steps, binary success). We **reproduced all sevenfrom the official `main.py` unmodified at 1M steps, every one matching publishedwithin std** (`misc/gciql_repro/gciql_official_1M.json`):
| env | official-code 1M (final / best) | published | published bar | **best bar** ||---|---|---|---|---|| pointmaze-medium | 52.7 / 58.5 | 53±8 | 0.53 | **0.585** || humanoidmaze-medium | 24.8 / 31.5 | 27±2 | 0.27 | **0.315** || cube-single | 70.0 / 77.2 | 68±6 | 0.68 | **0.772** || antmaze-medium | 72.8 / 79.1 | 71±4 | 0.71 | **0.791** || scene-play | 52.9 / 57.9 | 51±4 | 0.51 | **0.579** || puzzle-3x3 | 94.4 / 97.3 | 95±1 | 0.95 | **0.973** || puzzle-4x4 | 28.9 / 30.3 | 26±3 | 0.26 | **0.303** |
> **⚠️ Fair-comparison note (checkpoint selection).** RSM officials are its> *best banked snapshot*, so the like-for-like GCIQL bar is **GCIQL-best**> (repro), not the weaker *final*-step published number (repro confirms:> pointmaze published 53 = final 52.7 vs best 58.5). On the best bar RSM clearly> wins 4 cells, **ties puzzle-3×3 (0.960 vs 0.973) and antmaze-medium (0.762 vs> 0.791)** — *not* "above", as reading against the final bar suggested — and is> below on scene (Table A). The world-model comparison (§5) is unaffected: WMs> score 0.000 and RSM beats that even at last-step.
An earlier local GCIQL sweep used a uniform `alpha=0.3` at 500K steps, whichundertrained cells whose official alpha differs (pointmaze 0.003, humanoidmaze0.1 + discount 0.995); antmaze reproduced only because 0.3 is its officialvalue. That is fixed — the reproduced numbers above are the bars.
---
## 4. Per-cell notes
Numbers are in Table A/B; this section is the *why*, not a second copy of thetable.
**puzzle-3x3-play — discrete goals, exact `gl` read-out — SOLVED.** Officials0.928 (seed 0 @525k) / 0.932 (seed 1 @575k), family best **0.960** @825k —ties/above the official GCIQL 0.95±0.01. How the recipe got there (full matrixin [`ABLATION.md`](ABLATION.md)):- **Recursion lifts the ceiling, not just the pace** — the no-recursion control finals 0.712 where recursion arms official 0.82–0.96.- **Batch 4096 is a quality lever** — simulation-based targets average generated-sample noise inside each update; larger batches saturate.- **Fourier γ-encoding is worth ~+0.2** end-to-end over a scalar γ input.- **β=0.98 ≥ 0.95 ≫ 0.90** — shorter hops beat deeper chains.- A 3-network cousin (archived) reads 0.968 at 4M with +1 distilled critic — dropped from the pitch ([`DESIGN.md`](DESIGN.md)).
**pointmaze-medium-navigate — continuous goals, ELBO read-out — grand mean0.925.** Four independent training runs of the continuous default recipe (ELBOread-out, α=0.03, no recursion) official above the TD band:
| run | official (50-ep reads) | mean | note ||---|---|---|---|| A (EMA bank @225k) | 1.000 / 0.900 | **0.950** | per-task 1/1/1/**1**/1 and 1/1/.5/**1**/1 || B (replication seed 1, @325k) | 0.900 / 0.800 | **0.850** | `rsm.py` pure defaults || C (control arm, EMA @950k) | 1.000 / 0.900 | **0.950** | third independent run, ties A || D (replication seed 2, @825k) | 0.900 / 1.000 / 0.912 | **0.937** | pure defaults; 3rd read = 2M-final of same snapshot || unified (tails-composition, seed 0, @250k) | 1.000 / 0.800 | **0.900** | first official from a *composing* continuous arm |
Grand mean **0.925 over eight 250-episode reads**, vs official GCIQL 0.53. Thelong-horizon task (0.0 on every early snapshot) is **1.0 in all eight reads**;the residual per-read misses rotate across the other tasks — eval-episode noise,not a structural hole. Banked, not sustained (a seed can read 0.44 then 0.91 twoevals later); stabilizing continuous β-recursion is the open lever([`DESIGN.md`](DESIGN.md)).
**cube-single-play — manipulation, ELBO read-out — SOLVED.** Official **0.924**(family best @75k, weakest task 0.82); banked at 25k (≈1/40th of the GCIQLbudget) already reads 0.896. The α rule is the whole story: the pointmaze-tunedα=0.03 never exceeded 0.16 here (anchor mis-calibration, not recipe failure); atα=3 both {3,10} arms banked ~0.9 on their *first* eval. This is the environmentfor the world-model comparison (§5).
**humanoidmaze-medium — official 0.392 (peak 0.51), bar 0.315.** Wasstep-starved, not recipe-limited: 0.184 undertrained → 0.392 official at 1M,above the best bar. RSM's occupancy read-out is far less horizon-sensitive thanGCIQL's TD bootstrap — which is *why* the official GCIQL needs discount 0.995here and RSM does not (`--gamma` γ=0.995 gives only a small lift at matched α;α=1 over-anchors this continuous cell to ~0.21–0.24).
**antmaze-medium — official 0.762 (mean of 0.72/0.804, seed 1 @1M), bar 0.791.**A tie on the best bar. A shorter-hop probe (α=3, rec_beta 0.95) plateaus at thesame ~0.587 periodic ceiling as rec_beta 0.98 — shorter hops don't lift theband; the default-hop official 0.762 stands.
**scene-play — the one below-bar cell (in progress).** See §5.
---
## 5. Special studies
Goal-free RSM · visual vs world models · scene improvement · supervision-fair image arm.
### Goal-free (unconditional) RSM — LeWM's exact training diet
The occupancy needs no goals. Trained goal-free (`rsm_goalfree.py`: occupancy`p(z'|s,a)` + a goal-free BC prior, no goals or rewards at training), the goalenters *only* at deployment: extract its coordinates `z_g` and read the value asthe density the goal-free occupancy assigns there,`Q̂(s,a,g) = p_θ(z_g | s,a) ≈ exp(−ELBO at z_g)` — a point evaluation, nothingsampled, `z_g` never in the conditioning set. This is the direct analogue of howa world model's goal enters only as the planner's cost. cube-single, onegoal-free checkpoint:
| deployment mode | success (50 ep/task ×5) | s/episode ||---|---|---|| BC prior alone | 0.060 | 0.52 || Q-filter over K=32 candidates | 0.112 | 0.80 || **+ gradient steering** through the read-out | **0.256** | 0.78 |
The read-out is **differentiable in the action**, so a few steps up`∇_a log Q̂` from the BC mode more than double the filter (nudges ~0.01 in actionspace, finer than any sampled candidate). Every *widening* of the search hurt(larger step, more CEM rounds, CEM-then-grad) — the density penalty isload-bearing (§6). The 0.256 → 0.924 gap is the **measured value ofgoal-conditioned training** — signal an offline goal-reaching dataset licensesand a JEPA-style diet leaves unused. Same object, both diets.
### Head-to-head vs world models (LeWM + DINO-WM), cube-single
Two JEPA-style world models on `stable-worldmodel`, in **both** eval regimes,using the authors' unmodified code/planner/checkpoint. Numbers in Table C; fullfaithfulness argument and compute analysis: [root README §6](../README.md#6-what-is-the-right-object-to-extract-rsm-vs-world-models).
- **Matched modality, both WMs collapse.** LeWM and DINO-WM (a *different* backbone + codebase) each reproduce their own replay number (0.68 / 0.54, the faithfulness gate) yet both score **0.000 on OGBench** — isolating the failure to the *rollout-and-plan paradigm*, not one backbone. RSM's own world-model limit (recursion-off image-latent) scores 0.592, and composition adds a **+0.09 ceiling** to 0.684 (≈2.5× sample-efficiency too: ON reaches band by 150k, OFF crosses 0.60 only by 375k).- **Compute**: WMs pay the horizon per action via CEM (~23 s/ep LeWM, ~393 s/ep DINO-WM); RSM amortized it into training, so acting is a forward pass (~0.2 s/ep) — a ~100–2000× deployment gap.- **Faithfulness**: LeWM's 0.68 was reproduced through their own `eval.py` *before* its 0.000 was reported (rules out an adapter false-negative); training data is sha256-identical. LeWM's replay 0.68 is on an inflated protocol (32% of starts already satisfy success at reset — [`LEWM_EVAL_ANALYSIS.md`](../misc/lewm/LEWM_EVAL_ANALYSIS.md)).
Second occupancy baseline (CompPlan / Jumpy World Models): same object,TD-trained + test-time planner + requires a pretrained policy repertoire. Ouraudited `CompPlan-lite` reimplementation is faithful (estimator numericallyunbiased; planner improves a competent base 0.033 → 1.000 in a control), but **noCompPlan method verdict is claimed** — our cube-single run (0.092 → 0.016) is anartifact of an undertrained GHM + a weak OOD-fragile base, not a cleanmeasurement. Positive controls pending (`misc/compplan_lite/AUDIT.md`);[README §6.3](../README.md#63-the-other-occupancy-baseline-jumpy-world-models).
### scene-play improvement (in progress)
Two tracks against GCIQL-best 0.579: (1) **recursion-ON** (untried — scenedefaulted rec-OFF) at peak **0.453 @225k and climbing**, already at the oldrec-OFF ceiling (0.44) this early; (2) a **mixed-alphabet read-out** modelingscene's 2 binary button dims as **Bernoulli** and its 5 continuous dims asGaussian (the old ELBO modeled the bits as Gaussian — the diagnosed bottleneck),implemented + smoke-verified, launching into a freed GPU slot. The α bracket isexhausted (α=3 peaks 0.44 then collapses to 0.22; α=30 decays 0.17→0.03), so themixed read-out — not α — is the lever most likely to clear the bar.
### Supervision-fair image arm (recon-only) — RESULT: ≈0.000, the reward coordinate is load-bearing
To answer "does RSM beat the image WMs on LeWM's *exact* diet — pixels only, noprivileged reward coordinate," the recon-only latent (encoder trained on**reconstruction alone**, σ_z re-fit coordinate-free from the latent's ownpairwise stats to σ_z≈0.05) was trained to a full **1M steps**. Verdict:
| arm (visual-cube-single, 64² pixels) | encoder supervision | official ||---|---|---|| RSM combined (reward-metric + reconstruction) | cube xyz coordinate + pixels | **0.592** / **0.684** || **RSM recon-only (coordinate-free, LeWM's diet)** | pixels only | **≈0.000** (best 0.013, final 0.000) || LeWM / DINO-WM | pixels only (JEPA / DINO) | **0.000** |
The occupancy *fit fine* on the recon-only latent (occ_loss converged to ~0.168),but success stayed at the floor: without the reward-predictive coordinate thelatent isn't organized so that "occupancy mass at the goal latent" discriminatesgood actions from bad, so the read-out is uninformative and the actor can'timprove. **Honest conclusion: RSM's visual advantage over the WMs (0.592/0.684)relies on the reward-coordinate supervision in its encoder; at *matched*supervision (pixels only), RSM ≈ WM ≈ 0.000.** This tempers the visual headline —RSM wins at matched *modality*, not at matched *supervision*.
Caveat (what's still open): this tests **one** coordinate-free latent — purereconstruction. LeWM/DINO-WM use learned self-supervised representations(JEPA / DINO), which are stronger than raw reconstruction; whether areward-free *self-supervised* latent (temporal/contrastive) recovers RSM's edgeis untested. The clean claim is only that a **pure-reconstruction** coordinate-freeRSM is at the floor. (Earlier σ_z=1.0 runs that also read 0.000 were a separateflat-kernel calibration artifact — this 1M result uses the coordinate-freeσ_z≈0.05 and is the real measurement.)
---
## 6. Negative / closed results worth knowing
| finding | evidence ||---|---|| Max/certificate recursion collapses the 2-model carrier | officials 0.404–0.504 vs 0.524 no-recursion — one-sided optimism, structural || Kernel Monte-Carlo read-out loses in both goal spaces | flat 0.000 on discrete (product-kernel log-Q noise drowns the BC gradient); lost to ELBO on continuous || ELBO on discrete goals | 0.12 plateau — exact likelihood is free on a finite alphabet, use it || Read-out/midpoint pessimism (min over K) | exact no-op everywhere — the read-out error is systematic bias, not noise || Test-time raw-argmax action selection | optimizer's curse (0.760 → 0.224 as candidates grow); density-penalized variant recovers parity, kept in `eval_plan.py` || β-recursion on continuous goals (differentiated heads term) | collapses ~25k steps after composition switches on, at every BC weight and even with a ratio-clip guard (clip bounds the ratio's value, not its gradient). **`--rec_guard tails` (stop-grad the whole heads term) is the first composing arm to SURVIVE** — band intact 50k+ past the switch; whether it lifts the band above the plain recipe is the open measurement || TD-reference BC weight α on continuous goals | under-anchors: 0.680 peak then collapse; α=1.0 over-anchors at ~0.24–0.28 — the stable window is ~10× the TD reference |
The cross-cutting lesson: **max-selection over noisy generative estimates is thefailure mode everywhere** (training certificates, spike-banked snapshots,test-time argmax are the same optimizer's curse); every fix that worked isstructural — expectation-form estimators, density penalties, batch averaging —never resampling.
---
Raw per-arm ledgers with full curves:[`unused/docs/EXPERIMENTS.md`](unused/docs/EXPERIMENTS.md) (historical).Result JSONs: `experiments/{env}/results/{seed}/*.json`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340# Fair, pixels-only image RSM on visual-cube-single — results & findings
**Goal of this branch.** Make a **fair, strictly-pixels-only** image RecursiveSuccessor Model (RSM; occupancy model + read-out, no temporal-difference learning andno planner) **beat Goal-Conditioned Implicit Q-Learning (GCIQL)** on`visual-cube-single-play-v0`. "Fair" means the model sees only 64×64×3 rendered pixels,actions, and trajectory order, with **no privileged cube coordinate and noproprioception** anywhere in training. The cube coordinate is used only by the sharedenvironment success metric.
## Official result: fair RSM beats the exact visual GCIQL control
Both rows use the same five fixed visual-cube tasks and 50 episodes per task:
| method | per-task success | successes | overall ||---|---|---|---|| exact visual GCIQL control, step 300k | 0.58 / 0.62 / 0.28 / 0.16 / 0.18 | 91 / 250 | **0.364** || RSM reader-metric flow, `sqrt_h`, step 20k | 0.38 / 0.40 / 0.28 / 0.52 / 0.48 | 103 / 250 | **0.412** |
The exact improvement is **+0.048** overall, or 12 additional successful episodes.This is a single-seed, single-checkpoint comparison; it establishes the requestedofficial-protocol win, not a multi-seed uncertainty estimate.
### Key design that made it work
The decisive change was to stop requiring one isotropic latent space to serve asscene representation, occupancy target, and reward geometry:
<p align="center"> <img src="figures/visual_rsm_reader_metric.svg" alt="Three-stage reader-aligned visual RSM architecture" width="100%"></p>
*Figure 1: State and goal images are query inputs at both train and test; thedashed future image is an offline training target only. A direct RSM querygenerates latent futures from noise, while the official rollout calls only thedistilled pixel actor and performs no future sampling. Subtracting the goalmakes it the shared origin: zero displacement is a hit, while thereader-weighted delta preserves the direction and magnitude of a miss.*
1. **Rich context, compact future.** The flow conditions on the frozen encoder's 256-dimensional hidden state and goal features, which retain action- and scene-specific visual information. It predicts only the compact 8-dimensional reward-predictive future used by the goal reader.2. **An invertible, goal-relative reader-metric target.** A frozen diagonal index reader, trained from pixels with trajectory-order relabeling, supplies scales `s_i` and positive weights `w_i`. Instead of modeling an absolute latent future, the conditional flow models `u_i = sqrt(w_i) / s_i * (z_future_i - z_goal_i)`. This centers every requested goal at zero and makes flow error reflect the reward reader's geometry. The transform is invertible, so it does not discard state or turn the occupancy into a scalar value model.3. **Discount-conditioned supervision at useful horizons.** Every occupancy batch protects the task discount (`gamma=0.99`) and beta endpoint (`0.98`) while allocating the remaining mass across horizons 8/16/32/64 with square-root priority. This preserves long-horizon coverage without losing the shorter horizons where actions are identifiable.4. **Anchored but genuinely counterfactual policy extraction.** The scorer's recorded behavior action is anchored by a direct, non-TD absorbing index-return target. The actor mode and nearby counterfactual actions are still labeled only by the discount-conditioned occupancy. Occupancy, scorer, and the GCIQL-matched raw-pixel DDPG+BC actor train in the same fused step.
The resulting model is a plain one-hop 256×4 conditional flow. Larger absolutefuture models and recursive composition were not needed for the official win.
### Immutable audit references
- RSM result: `/proj/inf-scaling/zwhong/visual_rsm_metric_flow_rollouts/official_step20000/sqrth.json`; SHA-256 `a761e6ebf1cb095cca9e516737b29954312903e4bae9c2371fd1be659d96c09f`.- RSM checkpoint: `/proj/inf-scaling/zwhong/visual_rsm_metric_flow_sqrth_s0/rsm_fair_visual_rsm_metricu_sqrth_flowh256l4_warm10k_jointtrain50k_9e6eb9c_s0_step20000.pkl`; SHA-256 `07d4e9abb798e4d158f44ef4acd9e953f9808794d3c672515188c67ce14a14cb`.- Exact GCIQL control: `/proj/inf-scaling/zwhong/projs/gen_q/.claude/worktrees/rsm-visual-coordfree/ogbench_genq/experiments/visual-cube-single-play-v0/results/0/gciql_control_300000.json`; SHA-256 `837ffcb7d892400db3a03068abcc3b8c38f8ec7ac53a8e786edca0075cc13a02`.
Heavy artifacts remain external and are not copied into Git.
### Fairness and training contract
- The saved schema-13 checkpoint and rollout record `pixels_only=true`, `drop_proprio=true`, 64×64×3 pixel state/goal inputs, `coordinate_used=false`, `simulator_state_used=false`, and `reward_array_used=false`.- Occupancy is a conditional flow over an invertible, goal-relative coordinate in a frozen reward-reader metric. It is fitted from Monte-Carlo geometrically sampled trajectory futures and is explicitly discount-conditioned (`gamma=0.99`, spectrum lower bound 0.875, Fourier log-horizon feature). Endpoint sampling assigns 50% to task gamma, 25% to beta 0.98, and 25% across horizons 8/16/32/64 with square-root-horizon priority.- There is no temporal-difference target or bootstrap, no completion or forward/world model, and recursion is off. The occupancy fit uses neither reward arrays nor simulator coordinates.- The final actor consumes raw rendered pixels through an IMPALA-small early-fusion network, initialized from the pinned non-TD goal-conditioned behavior-cloning actor. Occupancy, supervised scorer, and actor are updated in the same fused step, with detached cross-component queries. Policy extraction matches the GCIQL control's DDPG+BC settings (`alpha=1`, expectile 0.9, batch 256, crop probability 0.5).- Evaluation uses the deterministic EMA actor for the exact five-task × 50-episode protocol. The evaluator checked 37,132 pixel-only policy calls and records no validation-only or hidden-state execution path.
### Gamma/beta spectrum and recursion decision
Horizon allocation was selected before the official evaluation. On matched50-episode screens, uniform spectrum allocation reached 0.32, whilesquare-root-horizon priority reached 0.38 at both exact steps 20k and 30k. Atask-heavy allocation (65% task gamma, 25% beta, 10% auxiliary horizons) did notimprove its gate. The winning run therefore retains task `gamma=0.99`, `beta=0.98`,and square-root priority over auxiliary horizons. Recursion remains disabled: theone-hop model already wins the official comparison, and adding recursive gamma/betacomposition would confound occupancy quality with planning depth. Gamma, beta, anddepth are preserved as a downstream ablation rather than used to rescue a weakone-hop model.
The integrated implementation combines the tested reader-metric flow and raw-pixelscorer contracts from `c2ab9a96db668257abb0db84db6c704d5ec5c14e` with thefail-closed launcher from `d52fb0698e05e93b1245fb1007b174d67f0b74f4`, whileretaining the compact/exact-20k diagnostic gates. It also includes the strictraw-pixel scorer-fidelity diagnostic from`120793416256502c3506dd11c898b61ad229e77e`.The complete `test_visual*.py` CPU suite passes 128/128 on this integrated tree.
### Policy-extraction tiers (controls, not the occupancy headline)
Two behavior-only raw-pixel scorer controls scored higher under the same 250-episodeprotocol:
| control | per-task success | overall | result SHA-256 | checkpoint SHA-256 ||---|---|---|---|---|| frozen latent, step 40k | 0.52 / 0.58 / 0.50 / 0.38 / 0.66 | **0.528** | `fc138bb13622142b37006c312989da1b2aa03c0f6a18970ab00e567b8303a8c5` | `e3e26a90c2a085589e51a90cd23426e5e2b16ab9a5c53ebaa971341bb261859c` || jointly trained rich adapter, step 40k | 0.58 / 0.82 / 0.60 / 0.56 / 0.72 | **0.656** | `cfbfe8a8554acffa8eb992bc92524d7a7d99bb0cdb67a3a90a42ec1df139931a` | `ced86348c6ae0f858bc7fd2ae08c7d291304d7a36e2fee91e306dccb7ddf9553` |
Their result files are respectively`/proj/inf-scaling/zwhong/visual_rsm_pxscore_rollouts/behavior_frozen_step40000_official/result.json`and`/proj/inf-scaling/zwhong/visual_rsm_pxscore_rollouts/behavior_joint_step40000_official/result.json`.Both remain fair, non-TD, discount-conditioned, and jointly update actor andoccupancy. However, their scalar targets for recorded actions come directly fromobserved same-trajectory, absorbing first-passage geometric index returns; thebehavior-only scorer does not use occupancy to label those actions. They are thereforestrong policy-extraction controls, **not proof that occupancy correctly ranks unseencounterfactual actions**.
The absolute-future occupancy-support frozen and joint arms both scored 0/50 at step20k. Their result files are`/proj/inf-scaling/zwhong/visual_rsm_pxscore_rollouts/support_frozen_step20000_diag10/result.json`and`/proj/inf-scaling/zwhong/visual_rsm_pxscore_rollouts/support_joint_step20000_diag10/result.json`;their diagnostic result SHA-256 values are`2c16e011eb935af323ee356cce016b2087d5c278e4520bd9c58c4e8319558206`and`f4ea202b3840d89f6d2fe41e48479b18763a7ce12eb273711fa20ff9faf470a4`.The strict EMA-scorer diagnostics make the failure more specific. The support-jointscorer matches its own discount-conditioned occupancy Q substantially better than thesuccessful behavior-joint scorer: all-action Spearman **0.704 vs 0.397** andactor-local Spearman **0.818 vs 0.430**. Nevertheless, their rollout results are 0/50and 0.656 (164/250), respectively. Thus scorer fidelity is not the bottleneck in thefailed absolute-future support arm; its occupancy-derived counterfactual Q ranking isoperationally wrong for policy extraction. The diagnostic files are`/proj/inf-scaling/zwhong/visual_rsm_pxscore_diagnostics/support_joint_s0_step20000_ema.json`(SHA-256`dd1426e8aa25ec5a9bf1aa52b17420507a4f8faba3d707b27acebd2b2a6aa9f1`)and`/proj/inf-scaling/zwhong/visual_rsm_pxscore_diagnostics/behavior_joint_s0_step40000_ema.json`(SHA-256`4680293c70354eaf84110ba8e9c75ed1c7071d5f7989ffbe774e6b67b5e13bd4`).The combined verified-reader-metric occupancy-support arm was also audited at exactstep 20k. Its strict 10-episode-per-task screen scored **15/50 = 0.300**, with per-tasksuccess `0.60 / 0.40 / 0.10 / 0.10 / 0.30`. Its distribution, support, and split-halfranking checks pass (rank correlation 0.836 at horizon 100 and 0.842 at horizon 50),but its value-fidelity gate fails: reward-Q Spearman is 0.579/0.637 and normalized MAEis 0.453/0.350 at horizons 100/50. The scorer is therefore non-collapsed and staysin-support, but its occupancy counterfactual targets still do not identify usefulteacher actions. The result is`/proj/inf-scaling/zwhong/visual_rsm_metric_pixel_support_rollouts/step20000_diag10/result.json`(SHA-256`d2e9dc211ee026bf6a6e6c6a8e598eae7c329ae7afed9b7da5cff1ceac97df96`);the checkpoint is`/proj/inf-scaling/zwhong/visual_rsm_metric_pixel_support_sqrtinit20_s0/rsm_fair_visual_rsm_metric_pixel_support_sqrtinit20_jointtrain50k_c2ab9a9_s0_step20000.pkl`(SHA-256`9bd02973023a62a0070f876b6a4352b2227cc64afe20ac383a09bcb3ccb07d4a`),and the gate result has SHA-256`1f2c5251dfa56df84727f536aa9a051acbc771dab8c5c9e3abed440f187c96d3`.Consequently, **0.412 remains the clean occupancy headline**; the 0.528/0.656 rowsisolate the benefit of matched pixel policy extraction.
---
## Historical diagnostics before the winning recipe
Every **coordinate-free encoder** tested with the default mass-at-goal *density*read-out yielded RSM **0.000**. These runs still used proprioception downstream,so they diagnose the encoder/read-out but are not strictly pixels-only:
| coordinate-free encoder | proxy spearman(z-dist, cube-dist) | RSM SR (density read-out) ||---|---|---|| recon-only | 0.47 | 0.000 || recon-only, σ_z-calibrated | 0.47 | 0.000 || tempcon (temporal InfoNCE) | 0.19–0.45 | — (proxy-gated out) || value_reward (γ^steps kernel) | 0.375 | — (proxy-gated out) || **slow-feature** (latent-velocity penalty) | **0.62–0.69** | 0.000 || combined (**cube coordinate**, reference) | 0.56 | 0.592 |
**The spearman proxy does not predict RSM success** (slow-feature beats combined'sproxy yet reads 0.000). Two distinct root causes, found by direct measurement:
### 1. Metric geometry (encoder). *Solved by slow-feature.*- `arm → cube` position is linearly recoverable at **R² = 0.90**, and recon's cube is decodable at R² = 0.70 — the cube info **is** in the latent.- But recon spends its variance reconstructing the high-variance **19-D arm**, so latent *distance* tracks the arm, not the **3-D cube** → spearman 0.47.- **Slow-feature** (`--w_smooth`: penalize `‖E(x_{t+1}) − E(x_t)‖²`) suppresses the fast arm, exposes the slow cube → proxy 0.67 (> combined's 0.56). Metric fixed, still 0.000.
### 2. The read-out is flat (density). *This is the actual wall.*The pixel read-out `q_elbo = exp(−denoise_loss(z_g | s,a))` averages denoising error over**all** latent dims, so the irrelevant arm dims swamp the cube:
| read-out | q_self (true goal) | q_rand (random goal) | log_gap ||---|---|---|---|| density (`q_elbo`) | 0.99 | 0.94 | 0.057 |
`q_self ≈ q_rand` → the actor gets no signal. Neither σ_z calibration nor`--elbo_logspace` changes this.
**Why GCIQL sidesteps all of this:** TD bootstrapping on the coordinate-free indexreward pushes the reward gradient **end-to-end into the encoder**, sharpening the smallcube, and only needs a *scalar regression* value — never a predictive occupancy. RSMgives up exactly those two things (reward never shapes the representation; the read-outneeds a modeled future distribution).
---
## Classifier read-out and Q-filter diagnostics
Replace the density with the CLAUDE.md image-spec read-out — sample futures and scoreeach with a learned **goal classifier**:
$$Q(s,a,g) = \mathbb{E}_{z' \sim p_\theta(\cdot|s,a,g)}\big[\,\sigma(R_\psi(z', z_g))\,\big]$$
`R_ψ` (`genq/train_reward_decoder.py`) is trained coordinate-free. The supersededreachability target used a downstream goal as positive. The current `index` targetuses a near-in-time frame as the at-goal positive and a random frame as negative.Read-out is wired in `rsm.py --reward_decoder`.
**On the coordinate-free slow-feature latent it opens the gap 4×:**
| read-out (slow-feature latent; proprio downstream) | q_self | q_rand | log_gap | SR ||---|---|---|---|---|| density | 0.99 | 0.94 | 0.057 | 0.000 || **classifier `R_ψ`** (step 25k → 50k) | 0.64 → 0.73 | 0.51 → 0.53 | **0.234 → 0.321** | 0.000 |
The classifier separates the true goal from a random one where density could not, butthe saved classifier-training runs in the table have `drop_proprio=false`; they arediagnostics, not fair pixels-only results.
The sharper `index` decoder reached validation accuracy **0.974**. A Q-filter diagnosticon the saved recon occupancy produced 0.000 for density K=1/8/32 and classifierK=1/8; classifier K=32 was terminated before completion. This diagnostic is also**ineligible**: every result JSON records `drop_proprio=false`, and the saved actor'sfirst layer confirms a 35-wide input (`proprio19 + z + goal-z`) rather than thepixels-only 16-wide input (`z + goal-z`). It cannot be reported against GCIQL.
The next authorized test therefore retrains the entire path from scratch:reconstruction-only pixels → frozen latent → index decoder → diffusion occupancy on`z` alone (`drop_proprio=true`) → advantage-weighted regression (AWR) actor. AWR usesstop-gradient occupancy Q on dataset actions plus an expectile V baseline, avoidingboth the failed proposal-dependent Q-filter and gradients through the diffusionsampler. Recursion is off because the strict visual gate forbids its full-statecompletion/forward-model machinery.
The exact-path AWR smoke (job 378203) completed all 100 training steps and saved acheckpoint whose metadata verifies `drop_proprio=true`, a 16-wide `z + goal-z` actorinput, `actor_loss=awr`, `recursion=off`, and an index reward decoder. Its first visualrollout then hit a process-level EGL abort on `p1-r20-n4`; this is a renderer-hostfailure, not a training failure. Training and evaluation are now decoupled:`--train_only` never constructs the renderer, while a separate `--eval_only` job loadsthe checkpoint on a recently verified rendering host.
The separated evaluation (job 378857) then completed normally on `p5-r05-n3`: oneepisode on each of five tasks, all five rollouts executed, with smoke success`0.000`. That score is not a scientific result after only 100 update steps; itvalidates the complete checkpoint-to-pixel-rollout contract without weakening thefairness gate.
The full reconstruction-only control (job 378858) completed one million occupancy/AWRupdates. Its official separated evaluation (job 385240) ran 50 episodes per task on`p5-r06-n4` and scored **0.000 on all five tasks**. This result is fair and eligible:the saved/result metadata verifies `drop_proprio=true`, `recursion=off`,`readout_kind=classifier`, and `reward_decoder_target=index`. Reconstruction alone istherefore not sufficient even with the corrected pixels-only policy-extraction path.
The next screen replaces the failed long-horizon InfoNCE formulation with animage-pair goal-proximity objective. A positive goal image is within eight trajectoryframes; negatives are a mixture of far same-episode and cross-episode images. Labelsuse trajectory order only. The head uses symmetric pair features and is discardedafter encoder training; no action-conditioned transition model or rollout model isintroduced. A single preemptable job isolates goal-loss weight, latent width, andencoder width before another full RSM fit.
---
## What's built (code inventory)
- `genq/train_latent_variants_jax.py` — fair encoder heads: `--w_smooth` (slow-feature), `--w_goalcls` (goal-reaching InfoNCE), `--w_goalcls_bin` (binary MLP goal classifier), plus existing recon / tempcon / value_reward / stepsto.- `genq/train_reward_decoder.py` — trains `R_ψ`, the coordinate-free goal classifier, for the read-out.- `rsm.py` — invertible reader-metric flow target, schema-13 raw-pixel scorer, `--reward_decoder` classifier read-out, strictly-pixels-only actor, and fused occupancy/scorer/actor training.- `genq/gate_visual_occupancy.py` and `genq/diagnose_visual_pixel_scorer.py` — fail-closed checkpoint/fairness gate plus scorer calibration, ranking, twin-disagreement, support-drift, and crop-stability diagnostics.- `pixel_eval.py` — `drop_proprio` threaded into the eval wrapper.- `genq/readout_diag.py` — read-out ranking diagnostic (fixed vs learned).- `experiments/train_visual_rsm_pixel_scorer.sh` — pinned frozen/joint and behavior/occupancy-support launcher.- `experiments/pack_*` — packed encoder→precompute→RSM pipelines; `submit_valrew_rsm.sh` targets known-good EGL render nodes (`-m`, avoids the node-lottery core-dump).
## Honest status
The requested fair, pixels-only win is achieved: reader-metric flow RSM scores**0.412**, above the exact visual GCIQL control's **0.364**, under 250 matched officialrollouts. The behavior-only scorer controls reach 0.528 and 0.656 but must remainseparate from the occupancy claim because their recorded-action supervision isempirical. The exact-20k combined metric-support screen reaches 0.300 and passesdistribution/ranking/support checks but fails value fidelity, so it does not replacethe winning reader-metric actor. The remaining scientific question is how to makeoccupancy-derived counterfactual action values causally useful for the matchedraw-pixel extraction path.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215# Fair visual occupancy-only recursion
This is the strictly pixels-only recursion path selected by`rsm.py --recursion occupancy`. It does not use the legacy completion head.
## Distributional construction
Let a beta occupancy draw advance an unshifted geometric number of environmentsteps,
\[K_i\sim\mathrm{Geom}(1-\beta),\qquad K_i\in\{0,1,\ldots\}.\]
Continue after each beta jump with probability
\[c=\frac{\gamma-\beta}{\gamma(1-\beta)},\qquad 0<\beta<\gamma<1.\]
If the number of jumps is geometric on `{1, 2, ...}` with stop probability`1-c`, then the probability-generating function of their summed horizon isexactly `(1-gamma)/(1-gamma*z)`. Thus gamma and beta are independentlytunable: gamma chooses the desired policy horizon; beta chooses the difficultyof each occupancy query. `test_occupancy_recursion.py` checks this identity.
The occupancy is still fit only by flow matching on realized offline`(state_t, action_t, goal, discount) -> future_{t+k}` tuples. The querieddiscount is encoded with Fourier log-horizon features. During occupancy-onlyrecursion, the default training mixture places mass 0.50 on exact gamma, 0.25on exact beta, and 0.25 on the remaining auxiliary horizon curriculum. Noreward, next-state value, Bellman equation, or bootstrap enters this fit. Thebeta mass is an overlay inside the non-task part of the shared`gamma_sampler`/task-fraction interface. With `stratified_bins`, every batchhas exact task and beta counts, then balances the remaining rows across theconfigured horizon bins; recursion does not introduce a competing sampler.
## Optional actor-query anti-exploitation ranking
`--occ_action_negative actor_local` changes only the existing reward-freeaction-contrast auxiliary. For each offline occupancy tuple, let `ell_b` bethe flow-matching error under its recorded behavior action. The live actor isqueried at that tuple's exact current state and actor-goal feature, before theactor update in the same fused step. Its detached mode and `K` detachedsigma-local actions give errors `ell_i` using the *same* future, discount,flow time, bridge state, and base noise. The additional loss is
\[\lambda\,\mathbb E\left[ \operatorname{softplus}(m+\ell_b-\ell_i)\right].\]
The expectation retains the occupancy tuple's importance weights. Support isactive from step zero, including during the behavior-cloning warmup. Allnegative actions are stop-gradient, so neither the actor nor a jointly trainedlatent adapter receives a gradient through this auxiliary. Occupancy and actorstill update in the same fused step: occupancy uses the live pre-update actor,then the actor takes its separate policy-extraction update. Reward, simulatorcoordinates, next-state values, Bellman equations, and bootstrap targets areabsent. Every condition still includes the sampled discount.
This is conservative anti-exploitation ranking, not counterfactual groundtruth. An offline tuple identifies the future distribution under its recordedaction; it cannot identify the true future under an unseen actor action.Consequently this auxiliary can discourage the occupancy from assigning therecorded future unusually high likelihood at current off-data queries, but itcannot certify where their generated mass should go or that their rewardread-out is correct. It must be screened as an ablation against the existingbehavior-local contrast, not presented as an identified off-policy occupancy.
The launchers expose `OCC_ACTION_NEGATIVE=actor_local`,`OCC_ACTION_NEGATIVE_K` (default 2), and`OCC_ACTION_NEGATIVE_SIGMA` (default 0.3). Actor-local tags include both `K`and sigma. Checkpoint metadata records the live-preupdate actor source,step-zero support, common-random-number construction, stop-gradient contract,candidate count, and the non-counterfactual interpretation; resume requiresan exact match.
## Rich hidden-future path
The primary visual carrier is
\[p_\theta(h_{t+k}\mid h_t,a_t,h_g,\widetilde\gamma),\]
where `h` is the frozen pixels-only encoder's 256-dimensional `fc_0` ReLUfeature. A generated hidden future is already the next actor input and the nextoccupancy conditioning state, so recursion needs no hidden-to-observationcompletion model. The actor and occupancy goal also use `h_g`.
The actual cached artifact has 147 exactly constant hidden units. The modelkeeps the full h256 actor and condition interface, but masks those exactconstants in flow noise, loss, and integration and pins them to their datasetmean. Active outputs are standardized by per-dimension dataset mean/std.Generated hidden samples are projected to the known nonnegative ReLU support.
Reward is read only after the terminal beta occupancy. The frozen encoder'ssaved `fc_1` maps generated h256 to the compact 8-dimensional z, and the frozenlocal index-reward reader scores `(z_future, z_goal)`. An artifact audit requires`max_abs(cached_z - fc1(cached_h)) < 2e-4`; the selected cache measures about`1.18e-4` on CPU. The residual is consistent with the cache having been madeunder accelerator default/TF32 matmul precision; this is provenance inference,not a changed representation. Cached z is preserved rather than recomputed.
`--recursion_state compact` is a control that closes the same chain directlyin z8. It is expected to be weaker because z8 is reward-predictive but lesscontrol-sufficient.
## Policy extraction
The primary extractor is `ddpgbc_distill`:
1. Draw a composed beta-occupancy chain using the current or exponential moving average actor for intermediate re-decisions.2. Integrate its terminal samples with the frozen local index-reward reader.3. Stop-gradient that Monte Carlo expectation and regress the same twin scalar scorer architecture used by the matched visual DDPG+BC extractor.4. Train DDPG+BC against that supervised scorer.
This target is not `reward + gamma * V(next_state)` and contains no temporal-difference or learned bootstrap term. Direct differentiation through themulti-hop flow is retained only as the `ddpgbc` control.
## Fairness gates and limitations
The implementation hard-requires and records:
- `drop_proprio=true`;- no simulator coordinate or reward label in occupancy supervision;- explicit discount conditioning and an exact-beta training mixture;- local index-reward read-out (discounted-return readers are rejected);- no completion or forward model (`None` completion state in checkpoints);- no temporal-difference or bootstrap target.
There are three explicit approximation sources:
1. Frozen h256 must be sufficiently Markov for occupancy composition. It is richer than compact z8 but is not guaranteed to contain all physical state.2. For a scorer target at an off-policy dataset action, an unshifted beta draw can have `K=0`; the next macro-step then uses the recursive actor rather than repeating that dataset action. Direct actor-action composition does not have this boundary mismatch.3. Learned flow error compounds with hop count, and fixed-depth recursion has residual mass `c**depth`. Every run records that cap mass.
## Staged hidden-future gamma/beta screen
The prepared sweep is fixed in`experiments/visual_rsm_recursion_sweep_manifest.tsv`. It has two phases sothe model that gets composed is the model that was actually audited.
The first phase trains the final hidden-future representation`p(h_future | h_state, action, h_goal, discount)` for exactly 50k steps. Everyarm is configured with occupancy recursion so it has the correct h256 output,support projection, and exact-beta discount mixture, but composition isinactive until `step > rec_after`. All composing arms use `rec_after=50000`;the no-composition control uses the fixed unreachable value `1000000000`.Therefore no recursive target is used in the calibration phase.
At 50k, every checkpoint is independently audited at its own task gamma andbeta. Continuation is eligible only for a checkpoint whose JSON has stricttop-level boolean `"pass": true`, whose checkpoint path, step, gamma, beta,representation, and SHA-256 match the exact checkpoint being resumed. Thecalibration checkpoint remains the immutable evidence. A compact z8 one-hopgate cannot authorize an h256 recursive model.
| arm | gamma | beta | continuation `c` | depth | cap mass `c**depth` | beta batch mass | composition ||---|---:|---:|---:|---:|---:|---:|---|| short-hop | 0.99 | 0.985 | 0.336700 | 8 | 0.000165 | 0.25 | on || central | 0.99 | 0.980 | 0.505051 | 12 | 0.000275 | 0.25 | on || easy-hop/deeper | 0.99 | 0.970 | 0.673401 | 20 | 0.000368 | 0.25 | on || shorter-task control | 0.98 | 0.960 | 0.510204 | 12 | 0.000311 | 0.25 | on || matched no-composition | 0.99 | 0.980 | 0.505051 | 12 | unused | 0.25 | off || beta-support ablation | 0.99 | 0.980 | 0.505051 | 12 | 0.000275 | 0.40 | on |
Gamma fixes the desired policy-evaluation horizon. Beta trades the difficultyof one learned occupancy query against the number of composed queries: beta0.985 asks the flow to model about 67 environment steps per hop but usuallystops after one or two hops, while beta 0.97 models about 33 steps per hop andneeds about three hops on average. The three deeper settings use the smallestinteger depth that puts truncation mass below the pre-fixed `5e-4` budget.The short-hop setting uses depth 8 because depth 7 lands at `4.91e-4`, only1.9% below the cap; one extra cheap level gives useful safety margin.
The beta-mass 0.40 cell is a single targeted ablation, not a second fullmatrix. Recursive evaluation repeatedly queries the exact beta condition, soit tests whether beta-query support is limiting. Gamma retains mass 0.50 andthe remaining auxiliary horizons retain mass 0.10. All primary cells use betamass 0.25, leaving mass 0.25 for the auxiliary spectrum. The 0.99 arms useauxiliary horizons `{2,4,8,16,32,64}`. The 0.98 arm uses`{2,4,8,16,32}` because the 64-step auxiliary discount would exceed its taskdiscount.
Every cell freezes the pixels-only h256 latent, uses a width-512/layer-4conditional flow with 25 integration steps, and pins the index-d4 diagonalreader to SHA-256`9ab338b3940e4c0797b4fc419659d5907f96e745b95a8c57457c85099fdb85a7`.The actor-query contrast and scalar scorer both cover the detached actor modeplus two sigma-0.3 local actions. The actor's occupancy-Q term starts at stepzero; occupancy, scorer, and actor update in the same fused step, with nocross-loss gradient. Composition starts after the gated 50k checkpoint, so thefirst phase is a matched direct one-hop calibration period. Theno-composition control sets `rec_after=1000000000`, leaving the hiddenoccupancy, exact-beta data,discount mixture, actor update, and reader otherwise identical.
The dry-run entry points are`experiments/pack_visual_rsm_recursion_sweep.sh --dry-run` and`experiments/submit_visual_rsm_recursion_sweep.sh`. The latter prints exactlyone preemptable one-GPU allocation by default; only its explicit `--submit`path can mutate scheduler state. That submission is calibration-only and ishard-limited to 50k. Recursive continuation remains fail-closed until theper-checkpoint hidden-future gates pass.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166# Visual RSM with recursion (builds on #68, stacks on rsm-ogbench-matrix)
This document records the graft of Dan's visual/image-observation RSM pipeline(PR #68, branch `origin/visual-antmaze`, which itself was **recursion-OFF**) ontoour **current recursive** `rsm.py` (β-recursion, γ-spectrum, gl/ELBO read-out,tails guard), and the recursion-ON visual results.
It does NOT edit any headline RESULTS/README numbers — it is the standalonefindings log for the visual-recursion work.
## What was grafted from PR #68
Our HEAD (off `rsm-ogbench-matrix`) already had the pixel→RSM hook(`--latent_npz`/`--pixel_encoder`) and the cube pixel files, because Danoriginally cherry-picked that path *from* `rsm-ogbench-matrix`. So the graft wasthe **reverse direction** the task named: our recursive `rsm.py` is the base, andDan's genuinely-new deltas were layered on:
- **`lax.cond` recursion-warmup gate** (the key affordability lever): the expensive depth-N β-chain (`chain_prob`, a `rec_max_depth` scan of DDIM completions) is `pi_step`-discarded whenever `compose` is False, so it is now gated behind `jax.lax.cond(compose, _chain, _skip)`. During the pre-composition warmup (`step <= rec_after`) the cheap zero placeholder runs instead. Bit-identical to before (the chain value was already unused pre-warmup; RNG keys `k7`/`k8` are split unconditionally at the top of `one_step`, so the next step's RNG stream is unchanged). This is what makes recursion-ON affordable on high-dim/visual latents.- **Resumable full-state checkpointing** (`--ckpt`/`--ckpt_every`): atomic pickle of the entire fused-loop carry + host progress; on relaunch with the same `--ckpt` it `device_put`s back and skips completed dispatches. Required for the preemptable queue.- **`--rec_max_depth`** exposed (default 10) — replaces the hardcoded chain depth.- **Jitted eval actor** (`_eval_act`) — ~6x faster CPU eval; eval is temperature 0 (mode()), so no RNG.- **Pixel proprio-key generalization** — `proprio` (generic) or `proprio19` (legacy cube), so maze proprio (27-D) works.- **EGL-teardown `os._exit(0)`** on the visual path only (renderer `__del__` crashes at GC after all results are dumped).- The 4 pixel-pipeline files taken wholesale from #68 (strict additive supersets: env-family branching for maze on top of the cube path): `genq/train_pixel_encoder_jax.py`, `genq/precompute_pixel_latents.py`, `pixel_eval.py`, `genq/train_latent_variants_jax.py`.
Our recursive machinery (`--gamma` flag + γ-spectrum-per-gamma, β-recursion,tails guard, gl/ELBO read-out) is **unchanged** — Dan's branch (off `main`)lacked `--gamma`, and that removal was NOT carried over.
## Equivalence gate (state path bit-identity)
`ogbench_genq/test_visual_recursion_equivalence.py` compares the grafted `rsm.py`(all new features off) against the pre-graft HEAD (`88d05ce`) on occ_loss atsteps 100/200 for puzzle-3x3-play-v0 (discrete/gl) and pointmaze-medium-navigate-v0(continuous/elbo), CPU-only.
**Result: PASS** (2026-07-20, CPU). occ_loss matched to all 6 printed digits atboth probe steps on both read-out paths:
| env | step | current occ_loss | baseline (88d05ce) occ_loss | ||---|---|---|---|---|| puzzle-3x3-play-v0 (discrete/gl) | 100 | 0.553375 | 0.553375 | MATCH || puzzle-3x3-play-v0 | 200 | 0.499918 | 0.499918 | MATCH || pointmaze-medium-navigate-v0 (continuous/elbo) | 100 | 0.422900 | 0.422900 | MATCH || pointmaze-medium-navigate-v0 | 200 | 0.336675 | 0.336675 | MATCH |
The `lax.cond` gate is bit-identical because the chain value is `pi_step`-discardedwhenever `compose` is False (which is always true here — `rec_after=100000` >> 200steps), and the RNG keys `k7`/`k8` are split unconditionally at the top of`one_step`, so the next step's RNG stream is unchanged whether `_chain` or `_skip`runs. `--ckpt` off, `--latent_npz` off → the state training path is untouched.
## The WM comparison — visual-cube-single (PRIORITY)
visual-cube-single is the env where the world-model baselines have numbers(head-to-head #65): **LeWM 0.68 replay / 0.000 OGBench**, **DINO-WM 0.54 replay /0.000 OGBench** — both image observations, both 0.000 on OGBench success. Acurrent-design **RSM-image-latent** number here (combined latent, recursion ON*and* OFF) is the modality-fair comparison that closes the fairness gap flagged inRESULTS.md (WM=image vs RSM=state).
_Numbers: (filled in as jobs bank — no fabricated numbers.)_
**Preliminary trajectory (job 257833, 15-ep periodic evals — NOT final officials;periodic overstates by ~0.05-0.15 per the harness). Both arms share one GPU.**
Recursion-ON (`recon`, `"recursion":"prob"`, rec_after=100k, tails guard):
| step | sr (live) | ema | note ||---|---|---|---|| 50k | 0.000 | 0.000 | pre-composition || 75k | 0.053 | 0.040 | pre-composition || 100k | 0.000 | 0.027 | composition switches ON (transient) || 125k | **0.640** | **0.707** | post-composition — large jump || 150k | **0.747** | 0.560 | sustained + rose (not a one-eval fluke) |
Recursion-OFF (`recoff`, the WM-fair baseline):
| step | sr (live) | ema | peak ||---|---|---|---|| 100k | 0.000 | 0.000 | 0.000 || 150k | 0.000 | 0.000 | 0.000 || 175k | 0.013 | 0.000 | 0.013 || 200k | 0.067 | 0.000 | 0.067 || 225k | 0.053 | 0.053 | 0.067 || 250k | 0.413 | 0.373 | 0.413 || 300k | 0.493 | 0.427 | 0.493 || 325k | 0.520 | 0.467 | 0.520 || 350k | 0.547 | 0.627 | 0.547 || 375k | 0.600 | 0.440 | 0.600 |
**Reading (preliminary, ON @~15% / OFF @~38% of 1M steps).** Two firm findings and oneopen question:
1. **RSM-image-latent on visual-cube-single strongly beats the image world-model baselines' hard 0.000 OGBench floor** (LeWM, DINO-WM, #65) with BOTH recursion settings — closing the modality-fairness gap decisively in RSM's favor.2. **Recursion is markedly more sample-efficient to high SR.** At matched steps the ON arm is far ahead — 125k: ON 0.640 vs OFF 0.000; 150k: ON 0.747 vs OFF 0.000. The ON arm reaches ~0.75 by 150k; the OFF arm reaches comparable territory (~0.55-0.60) only by 350-375k — roughly **2.3x the steps**. The ON lift is now sustained across two post-composition evals (0.640 -> 0.747), not the single-eval transient the earlier note cautioned about.
OPEN: the **final converged ON-vs-OFF margin**. The OFF arm is still climbing (0.60 @375k) and the ON arm is the slower ~27h arm (last at 150k), so whether ON's asymptoteexceeds OFF's needs both matured to 1M + 50-ep officials. No collapse (tails guardholding; occ_loss still declining, ON 0.1180 / OFF 0.1189).
| variant | recursion | visual-cube-single SR | notes ||---|---|---|---|| combined latent | OFF | 0.000 @125k -> 0.60 @375k (periodic, climbing) | WM-fair baseline; final pending || combined latent | ON (β=0.98, tails guard) | 0.640 @125k -> 0.747 @150k (periodic) | ~2.3x more sample-efficient; final pending || LeWM (image WM, #65) | — | 0.000 OGBench | modality-matched baseline || DINO-WM (image WM, #65) | — | 0.000 OGBench | modality-matched baseline |
## visual-antmaze-medium (secondary — Dan's env, WMs never tested here)
Dan's recursion-OFF combined-latent number: **0.52**. Question: does recursionlift it above 0.52? Run only if cube is done and budget remains.
| variant | recursion | visual-antmaze-medium SR | notes ||---|---|---|---|| combined latent | OFF (Dan) | 0.52 | Dan's PR #68 baseline || combined latent | ON | _pending / optional_ | |
## Job ledger
- **job 257833** (preemptable, 1 shared GPU) — `pack_visual_cube_recursion.sh full`: combined latent encoder -> precompute -> RSM recursion-OFF + recursion-ON, all `--ckpt` resumable. Launched 2026-07-20 05:21. - stage 1 (combined encoder, 100k steps) **done**: FINAL proxy **spearman=0.5604, xy_R2=0.8316** (cube geometry; the xy-decodability probe is the maze-oriented proxy, so R2 0.83 on cube is a reasonable reward-aligned latent — the reward target here is scaled cube xyz, not maze xy, so the exact values are not comparable to Dan's antmaze combined ~0.9998). Downstream RSM success rate is the real test. - stage 2 (precompute latents from the cube h5) **done**: z=(1001000, 8), 205 MB; sanity probe spearman(z-dist, reward-coord dist) = **0.6041** (clearly positive — latent is reward-aligned). - stage 3 (RSM recursion off / on, 1M steps each, both --ckpt) **running** (shared GPU, so they contend): recursion-OFF ~39.6 steps/s (~7h), recursion-ON ~10.1 steps/s (~27h — completion head trains throughout; the `lax.cond` gate skips only the expensive chain until step 100k). Preemptable + resumable, so wall time can span multiple SSUSP cycles. - step 25k (pre-composition, 2.5%): OFF sr=0.000, ON sr=0.000, occ_loss ~0.143 for both (identical pre-composition, as expected). Too early to read; recursion engages at rec_after=100k. Watching the post-100k trajectory.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884"""Shared JAX training + fresh-rollout-eval harness for the three policy-improvement methods.
One place owns the GCDataset setup, the OGBench rollout evaluation, W&B logging, and the resultJSON schema, so the per-env `experiments/{env}/train_*.py` scripts are one-line wrappers. Everythinghere is JAX-only (no torch).
Headline metric: fresh-environment rollout success rate, evaluated by rolling out the trainedpolicy in the env over all tasks (OGBench `utils.evaluation.evaluate`) — NOT any in-dataset proxy.
Result JSON (results/{seed}/{gcbc,gciql,gciql_genq}.json) carries: method, env, seed, success_rate (final), best_sr (peak over training), per_task, curve (list of [step, sr]), train_steps, wall_clock_sec, wandb_url, and method-specific config."""import jsonimport osimport sysimport time
import numpy as np
OGBENCH_IMPLS = os.environ.get("OGBENCH_IMPLS", os.path.expanduser("~/ogbench_ref/impls"))PKG_DIR = os.path.dirname(os.path.abspath(__file__))REPO_ROOT = os.path.dirname(PKG_DIR)
# Per-env Gen-Q dense-reward bandwidth (maze xy scale ~0-40 -> 5.0; manip O(1) -> 0.5).SIGMA_BY_ENV = { "pointmaze-medium-navigate-v0": 5.0, "pointmaze-large-navigate-v0": 5.0, "pointmaze-medium-stitch-v0": 5.0, "antmaze-medium-navigate-v0": 5.0, "antmaze-large-navigate-v0": 5.0, "humanoidmaze-medium-navigate-v0": 5.0, "humanoidmaze-large-navigate-v0": 5.0, "antsoccer-medium-navigate-v0": 5.0, "cube-single-play-v0": 0.5, "cube-double-play-v0": 0.5, "puzzle-3x3-play-v0": 0.5, "puzzle-4x4-play-v0": 0.5, "scene-play-v0": 0.5,}LOCO_FULL = ("antmaze", "humanoidmaze", "antsoccer")
def _setup_paths(ogbench_impls): sys.path.insert(0, os.path.join(PKG_DIR, "genq")) sys.path.insert(0, PKG_DIR) sys.path.insert(0, ogbench_impls)
def _result_dir(env, seed): d = os.path.join(PKG_DIR, "experiments", env, "results", str(seed)) os.makedirs(d, exist_ok=True) return d
def _make_eval_fn(env, config, evaluate, jax, wrap=None): task_infos = env.unwrapped.task_infos if hasattr(env.unwrapped, "task_infos") else env.task_infos
def eval_success(agent, n_ep): eag = jax.device_put(agent, device=jax.devices("cpu")[0]) if wrap is not None: eag = wrap(eag) per = [] for tid in range(1, len(task_infos) + 1): ei, _, _ = evaluate(agent=eag, env=env, task_id=tid, config=config, num_eval_episodes=n_ep, num_video_episodes=0, video_frame_skip=3, eval_temperature=0.0, eval_gaussian=None) per.append(float(ei.get("success", 0.0))) return float(np.mean(per)), per
return eval_success
class _QFilterPolicy: """Deployment-time Q-filter: sample K candidate actions from the actor and execute argmax of the Gen-Q occupancy Q (the third policy-improvement recipe in CLAUDE.md).
Duck-types the `sample_actions` interface OGBench's `evaluate` expects. The candidate set is the actor's own stochastic proposals at temperature 1; the executed action is the Gen-Q argmax, so the selection pressure is applied at deployment with K samples instead of through the AWR exponent during training. """
def __init__(self, agent, genq_q_batch, k): self.agent = agent self.genq_q_batch = genq_q_batch self.k = k
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0): obs_k = np.repeat(np.asarray(observations)[None], self.k, axis=0) goal_k = np.repeat(np.asarray(goals)[None], self.k, axis=0) acts = self.agent.sample_actions(observations=obs_k, goals=goal_k, seed=seed, temperature=1.0) acts = np.clip(np.asarray(acts), -1, 1) q = self.genq_q_batch(obs_k, goal_k, acts) return acts[int(np.argmax(q))]
# --------------------------------------------------------------------------------------------------# GCBC baseline# --------------------------------------------------------------------------------------------------def run_gcbc(env_id, seed=0, train_steps=300000, eval_episodes=50, eval_interval=50000, eval_episodes_periodic=15, wandb_mode="online", ogbench_impls=OGBENCH_IMPLS): _setup_paths(ogbench_impls) import jax import tqdm import wandb from utils.datasets import Dataset, GCDataset from utils.env_utils import make_env_and_datasets from utils.evaluation import evaluate from target_extractors import env_safe_name import bc as bc_mod
t0 = time.time() safe = env_safe_name(env_id) config = bc_mod.get_config() env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"]) train_ds = GCDataset(Dataset.create(**train_dataset), config)
run = wandb.init(project="gen-q-policy-improvement", name=f"gcbc-{env_id}-s{seed}", mode=wandb_mode, tags=["gcbc", env_id], config=dict(method="gcbc", env=env_id, seed=seed, train_steps=train_steps), settings=wandb.Settings(start_method="thread")) print(f"[gcbc] WANDB_URL {run.get_url()}", flush=True)
ex = train_ds.sample(2) agent = bc_mod.GCBCAgent.create(seed, ex["observations"], ex["actions"], config) eval_success = _make_eval_fn(env, config, evaluate, jax) out = os.path.join(_result_dir(env_id, seed), "gcbc.json") curve = []
def dump(sr, per): json.dump({"method": "gcbc", "env": env_id, "seed": seed, "success_rate": sr, "best_sr": (max(v for _, v in curve) if curve else sr), "per_task": per, "curve": curve, "train_steps": train_steps, "wall_clock_sec": round(time.time() - t0, 1), "wandb_url": run.get_url()}, open(out, "w"), indent=2)
for i in tqdm.trange(1, train_steps + 1, smoothing=0.1, dynamic_ncols=True): agent, info = agent.update(train_ds.sample(config["batch_size"])) if i % 1000 == 0: wandb.log({f"train/{k}": float(v) for k, v in info.items() if np.ndim(np.asarray(v)) == 0}, step=i) if eval_interval > 0 and i % eval_interval == 0: sr, per = eval_success(agent, eval_episodes_periodic) curve.append((i, sr)) wandb.log({"eval/success_rate": sr}, step=i) print(f"[gcbc] step {i} sr={sr:.3f}", flush=True) dump(sr, per)
sr, per = eval_success(agent, eval_episodes) curve.append((train_steps, sr)) dump(sr, per) print(f"[gcbc] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}", flush=True) wandb.finish() return out
# --------------------------------------------------------------------------------------------------# Standard GCIQL baseline (TD critic)# --------------------------------------------------------------------------------------------------def run_gciql(env_id, seed=0, train_steps=500000, eval_episodes=50, eval_interval=50000, eval_episodes_periodic=15, actor_loss="ddpgbc", alpha=0.3, expectile=0.9, variant_tag=None, save_agent=None, wandb_mode="online", ogbench_impls=OGBENCH_IMPLS): _setup_paths(ogbench_impls) import jax import tqdm import wandb from utils.datasets import Dataset, GCDataset from utils.env_utils import make_env_and_datasets from utils.evaluation import evaluate from target_extractors import env_safe_name import gciql as gciql_mod
t0 = time.time() safe = env_safe_name(env_id) config = gciql_mod.get_config() config["actor_loss"] = actor_loss config["alpha"] = alpha config["expectile"] = expectile env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"]) train_ds = GCDataset(Dataset.create(**train_dataset), config)
vtag = f"_{variant_tag}" if variant_tag else "" run = wandb.init(project="gen-q-policy-improvement", name=f"gciql{vtag}-{env_id}-{actor_loss}-a{alpha}-tau{expectile}-s{seed}", mode=wandb_mode, tags=["gciql", env_id], config=dict(method="gciql", env=env_id, seed=seed, actor_loss=actor_loss, alpha=alpha, expectile=expectile, variant=variant_tag, train_steps=train_steps), settings=wandb.Settings(start_method="thread")) print(f"[gciql] WANDB_URL {run.get_url()}", flush=True)
ex = train_ds.sample(2) agent = gciql_mod.GCIQLAgent.create(seed, ex["observations"], ex["actions"], config) eval_success = _make_eval_fn(env, config, evaluate, jax) out = os.path.join(_result_dir(env_id, seed), f"gciql{vtag}.json") curve = []
def dump(sr, per): json.dump({"method": "gciql", "env": env_id, "seed": seed, "actor_loss": actor_loss, "alpha": alpha, "expectile": expectile, "success_rate": sr, "best_sr": (max(v for _, v in curve) if curve else sr), "per_task": per, "curve": curve, "train_steps": train_steps, "wall_clock_sec": round(time.time() - t0, 1), "wandb_url": run.get_url()}, open(out, "w"), indent=2)
for i in tqdm.trange(1, train_steps + 1, smoothing=0.1, dynamic_ncols=True): agent, info = agent.update(train_ds.sample(config["batch_size"])) if i % 1000 == 0: wandb.log({f"train/{k}": float(v) for k, v in info.items() if np.ndim(np.asarray(v)) == 0}, step=i) if eval_interval > 0 and i % eval_interval == 0: sr, per = eval_success(agent, eval_episodes_periodic) curve.append((i, sr)) wandb.log({"eval/success_rate": sr}, step=i) print(f"[gciql] step {i} sr={sr:.3f}", flush=True) dump(sr, per)
sr, per = eval_success(agent, eval_episodes) curve.append((train_steps, sr)) dump(sr, per) if save_agent: import pickle with open(save_agent, "wb") as f: pickle.dump({"params": jax.device_get(agent.network.params), "config": dict(config)}, f) print(f"[gciql] saved agent params -> {save_agent}", flush=True) print(f"[gciql] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}", flush=True) wandb.finish() return out
def run_gciql_ablate(env_id, seed=0, train_steps=300000, eval_episodes=50, eval_interval=20000, eval_episodes_periodic=15, actor_loss="ddpgbc", alpha=1.0, expectile=0.9, genq_actor=False, genq_value=False, adv_norm=False, n_occ=64, sigma=None, readout_tau=0.0, readout="sample", genq_npz=None, variant_tag=None, save_agent=None, wandb_mode="online", rec_target=0, rec_agg="max", rec_after=10000, rec_steps=None, rec_eps=0.5, rec_every=2, rec_actor=False, ogbench_impls=OGBENCH_IMPLS): """GCIQL -> GenQ component ablation (issue #57 owner directive: 'ablate away from GCIQL step by step... minimize the change from the original GCIQL script').
Rungs: R0 = neither switch (reference GCIQL; the distilled genq_critic trains but is unused). R1 = genq_actor (actor's Q source only). R2 = genq_value (expectile-V source only; the TD critic then bootstraps through GenQ-anchored values). R3 = both (fully TD-free value path). Everything else is the reference recipe (ddpgbc alpha=1.0 for puzzle, GCDataset goal mix, gc_negative reward untouched for the TD side). """ _setup_paths(ogbench_impls) import jax import jax.numpy as jnp import tqdm import wandb from utils.datasets import Dataset, GCDataset from utils.env_utils import make_env_and_datasets from utils.evaluation import evaluate from target_extractors import env_safe_name import target_extractors from genq_jax import (load_genq_params, genq_q as genq_q_jax, genq_q_goal_likelihood, sample as genq_sample) from gciql_ablate import GCIQLAblateAgent, get_config
t0 = time.time() safe = env_safe_name(env_id) ckpt_dir = os.path.join(PKG_DIR, "checkpoints") config = get_config() config["actor_loss"] = actor_loss config["alpha"] = alpha config["expectile"] = expectile config["genq_actor"] = genq_actor config["genq_value"] = genq_value config["adv_norm"] = adv_norm
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
if genq_npz is None: genq_npz = os.path.join(ckpt_dir, f"m9_genq_{safe}.genqjax.npz") assert os.path.exists(genq_npz), f"Gen-Q occupancy ckpt not found: {genq_npz}" P, meta = load_genq_params(genq_npz) sig = float(sigma if sigma is not None else SIGMA_BY_ENV.get(env_id, 5.0)) is_maze = (not env_id.startswith(LOCO_FULL)) and ("maze" in env_id) rung = ("R3" if (genq_actor and genq_value) else "R1" if genq_actor else "R2" if genq_value else "R0") if rec_target > 0: rung += f"+rec{rec_target}{rec_agg}" print(f"[ablate] rung={rung} genq_npz={os.path.basename(genq_npz)} sigma={sig} " f"n_occ={n_occ} readout={readout} readout_tau={readout_tau} " f"actor_loss={actor_loss} alpha={alpha}", flush=True)
def to_genq_state(obs): return obs[:, :2] if is_maze else obs
def to_target_goal(gobs): return target_extractors.extract_target(env_id, gobs).astype(np.float32)
if readout == "gl": # goal-likelihood read-out (reward-target IS, owner idea): P(x=g) by teacher-forced # any-order unmasking; n_occ is reused as the number of orders (8-16 is plenty). genq_q_fn = jax.jit(lambda s, a, g, k: genq_q_goal_likelihood( P, meta, s, a, g, k, n_orders=min(n_occ, 16))) else: genq_q_fn = jax.jit(lambda s, a, g, k: genq_q_jax( P, meta, s, a, g, k, n_occ=n_occ, sigma=sig, readout_tau=readout_tau)) gkey = [jax.random.PRNGKey(seed + 999)]
# Chunked evaluation (rec-sweep lesson): the 4096-row startup probe and 1024-row # critic batches at n_occ 64-256 OOM shared GPUs in one XLA graph. Same math, # one retrace, ~16x smaller live buffers. def genq_q_batch(obs, goal_obs, acts, _chunk=256): s = np.asarray(to_genq_state(obs), dtype=np.float32) g = np.asarray(to_target_goal(goal_obs), dtype=np.float32) a = np.clip(np.asarray(acts, dtype=np.float32), -1, 1) assert len(s) % _chunk == 0, f"batch {len(s)} not divisible by chunk {_chunk}" outs = [] for i in range(0, len(s), _chunk): gkey[0], sub = jax.random.split(gkey[0]) outs.append(np.asarray(genq_q_fn(jnp.asarray(s[i:i + _chunk]), jnp.asarray(a[i:i + _chunk]), jnp.asarray(g[i:i + _chunk]), sub))) return np.concatenate(outs)
train_ds = GCDataset(Dataset.create(**train_dataset), config) _pb = train_ds.sample(4096) _q = genq_q_batch(_pb["observations"], _pb["value_goals"], _pb["actions"]) print(f"[ablate] Gen-Q Q @ value_goals: mean={_q.mean():.4f} std={_q.std():.4f}", flush=True)
vtag = f"_{variant_tag}" if variant_tag else "" run = wandb.init(project="gen-q-policy-improvement", name=f"gciql_ablate_{rung}{vtag}-{env_id}-{actor_loss}-a{alpha}-s{seed}", mode=wandb_mode, tags=["gciql_ablate", env_id], config=dict(method="gciql_ablate", rung=rung, env=env_id, seed=seed, actor_loss=actor_loss, alpha=alpha, expectile=expectile, genq_actor=genq_actor, genq_value=genq_value, n_occ=n_occ, sigma=sig, readout=readout, readout_tau=readout_tau, rec_target=rec_target, rec_agg=rec_agg, rec_after=rec_after, rec_steps=rec_steps, rec_eps=rec_eps, rec_every=rec_every, rec_actor=rec_actor, genq_npz=os.path.basename(genq_npz), train_steps=train_steps), settings=wandb.Settings(start_method="thread")) print(f"[ablate] WANDB_URL {run.get_url()}", flush=True)
ex = train_ds.sample(2) agent = GCIQLAblateAgent.create(seed, ex["observations"], ex["actions"], config) eval_success = _make_eval_fn(env, config, evaluate, jax) out = os.path.join(_result_dir(env_id, seed), f"gciql_ablate{vtag}.json") curve = []
rec_compose = None if rec_target > 0: # RECURSION AT TRAINING TIME (issue #57, owner idea): the distilled critic's # target is the one-hop composed value # y = max( gl(s,a,g), agg_m[ gl(s,a,c_m) * min Q_ema(s_m, a_m, g) ] ) # with midpoints c_m sampled from the occupancy at (s,a,g) (rec_steps denoising # steps) and snapped to dataset rows by the eps-grid junction index (no # discreteness assumption; unseen cells contribute 0). Composition noise is # AVERAGED into the critic by SGD instead of compounding per read-out query, # and iterating through the EMA critic propagates value hop by hop — value # iteration whose backup operator is a Geom-window occupancy jump. No reward # bootstrap anywhere: the only learned value source is the MC occupancy. obs_all = np.asarray(train_dataset["observations"], np.float32) act_all = np.clip(np.asarray(train_dataset["actions"], np.float32), -1, 1) _tgt_all = to_target_goal(obs_all) _w_rec = (rec_eps * (_tgt_all.std(0) + 1e-6)).astype(np.float32) _cells = np.floor(_tgt_all / _w_rec).astype(np.int64) _uniq, _inv = np.unique(_cells, axis=0, return_inverse=True) _order = np.argsort(_inv, kind="stable") _bounds = np.searchsorted(_inv[_order], np.arange(len(_uniq) + 1)) rec_cells = {tuple(u): (int(_bounds[k]), int(_bounds[k + 1])) for k, u in enumerate(_uniq)} rng_rec = np.random.default_rng(seed + 4242) samp_fn = jax.jit(lambda c, k: genq_sample(P, meta, c, rec_target, k, steps=rec_steps)) _mdef = agent.network.model_def tgtq_fn = jax.jit(lambda prms, o, g, a: jnp.minimum( *_mdef.apply({"params": prms}, o, g, a, name="target_genq_critic"))) print(f"[ablate] REC-TARGET M={rec_target} agg={rec_agg} after={rec_after} " f"steps={rec_steps or meta['sample_steps']} eps={rec_eps}: " f"{len(_uniq)} junction cells", flush=True)
def rec_midpoints(s, a, g, _chunk=256): c = np.concatenate([s, a, g], axis=1).astype(np.float32) outs = [] for i0 in range(0, len(c), _chunk): gkey[0], sub = jax.random.split(gkey[0]) outs.append(np.asarray(samp_fn(jnp.asarray(c[i0:i0 + _chunk]), sub))) return np.concatenate(outs)
def rec_compose(obs_b, goal_obs_b, acts_b, base): B, M = len(obs_b), rec_target s = np.asarray(to_genq_state(obs_b), np.float32) g = np.asarray(to_target_goal(goal_obs_b), np.float32) a = np.clip(np.asarray(acts_b, np.float32), -1, 1) xs = rec_midpoints(s, a, g).reshape(B * M, -1) keys = np.floor(xs / _w_rec).astype(np.int64) mid = np.zeros(B * M, np.int64) valid = np.zeros(B * M, np.float32) for k2 in range(B * M): cell = rec_cells.get(tuple(keys[k2])) if cell is not None: lo, hi = cell mid[k2] = _order[lo + int(rng_rec.integers(hi - lo))] valid[k2] = 1.0 obs_m = obs_all[mid] hit = genq_q_batch(np.repeat(obs_b, M, axis=0), obs_m, np.repeat(acts_b, M, axis=0)) qm = np.asarray(tgtq_fn(agent.network.params, jnp.asarray(obs_m), jnp.asarray(np.repeat(goal_obs_b, M, axis=0)), jnp.asarray(act_all[mid]))) comp = hit * np.clip(qm, 0.0, 1.0) * valid comp = comp.reshape(B, M) comp = comp.max(1) if rec_agg == "max" else comp.mean(1) return np.maximum(base, comp), float((comp > base).mean())
def dump(sr, per): json.dump({"method": "gciql_ablate", "rung": rung, "env": env_id, "seed": seed, "actor_loss": actor_loss, "alpha": alpha, "expectile": expectile, "genq_actor": genq_actor, "genq_value": genq_value, "n_occ": n_occ, "rec_target": rec_target, "rec_agg": rec_agg, "rec_after": rec_after, "rec_steps": rec_steps, "rec_eps": rec_eps, "rec_every": rec_every, "rec_actor": rec_actor, "sigma": sig, "readout": readout, "readout_tau": readout_tau, "genq_npz": os.path.basename(genq_npz), "success_rate": sr, "best_sr": (max(v for _, v in curve) if curve else sr), "per_task": per, "curve": curve, "train_steps": train_steps, "wall_clock_sec": round(time.time() - t0, 1), "wandb_url": run.get_url()}, open(out, "w"), indent=2)
need_actor_q = genq_actor # ddpgbc/awr read the distilled critic at actor_goals for i in tqdm.trange(1, train_steps + 1, smoothing=0.1, dynamic_ncols=True): batch = train_ds.sample(config["batch_size"]) batch["genq_q_value"] = genq_q_batch(batch["observations"], batch["value_goals"], batch["actions"]) rec_lift = -1.0 # Compose every rec_every-th step only (throughput: full composition is ~6-8x the # base gl volume; the EMA critic still averages the composed targets in). Actor # goals are mostly in-trajectory, where recursion adds least — compose them only # under rec_actor. rec_now = rec_compose is not None and i > rec_after and i % rec_every == 0 if rec_now: batch["genq_q_value"], rec_lift = rec_compose( batch["observations"], batch["value_goals"], batch["actions"], batch["genq_q_value"]) if need_actor_q: batch["genq_q_actor"] = genq_q_batch(batch["observations"], batch["actor_goals"], batch["actions"]) if rec_now and rec_actor: batch["genq_q_actor"], _ = rec_compose( batch["observations"], batch["actor_goals"], batch["actions"], batch["genq_q_actor"]) agent, info = agent.update(batch) if i % 1000 == 0: if rec_lift >= 0: info = dict(info, rec_lift_frac=rec_lift) wandb.log({f"train/{k}": float(v) for k, v in info.items() if np.ndim(np.asarray(v)) == 0}, step=i) if eval_interval > 0 and i % eval_interval == 0: sr, per = eval_success(agent, eval_episodes_periodic) curve.append((i, sr)) wandb.log({"eval/success_rate": sr, "eval/peak": max(v for _, v in curve)}, step=i) print(f"[ablate:{rung}] step {i} sr={sr:.3f} (peak {max(v for _, v in curve):.3f})", flush=True) dump(sr, per)
sr, per = eval_success(agent, eval_episodes) curve.append((train_steps, sr)) dump(sr, per) if save_agent: import pickle with open(save_agent, "wb") as f: pickle.dump({"params": jax.device_get(agent.network.params), "config": dict(config)}, f) print(f"[ablate] saved agent params -> {save_agent}", flush=True) print(f"[ablate:{rung}] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}", flush=True) wandb.finish() return out
# --------------------------------------------------------------------------------------------------# GCIQL with the Gen-Q occupancy critic# --------------------------------------------------------------------------------------------------def run_gciql_genq(env_id, seed=0, train_steps=300000, eval_episodes=50, eval_interval=50000, eval_episodes_periodic=15, actor_loss="awr", alpha=30.0, expectile=0.9, n_occ=64, batch_size=1024, value_hidden_dims="512,512,512", no_ensemble=False, actor_goal_critic=False, sigma=None, genq_npz=None, latent_npz=None, variant_tag=None, adv_norm=False, q_filter_k=0, actor_geom_sample=False, readout_tau=0.0, genq_discrete_npz=None, target_variant="default", sigma_aux=2.0, readout_steps=None, wandb_mode="online", ogbench_impls=OGBENCH_IMPLS): """Policy improvement with the Gen-Q occupancy critic.
Requires a trained Gen-Q diffusion occupancy ckpt (`genq_npz`, a .genqjax.npz from genq/train_genq_jax.py). For image envs, pass `latent_npz` so the occupancy Q is read off a frozen reward-predictive latent rather than raw pixels. """ _setup_paths(ogbench_impls) import jax import jax.numpy as jnp import tqdm import wandb from utils.datasets import Dataset, GCDataset from utils.env_utils import make_env_and_datasets from utils.evaluation import evaluate from target_extractors import env_safe_name import target_extractors from genq_jax import load_genq_params, genq_q as genq_q_jax from gciql_genq import GCIQLGenQAgent, get_config
t0 = time.time() safe = env_safe_name(env_id) # Gen-Q occupancy ckpts live in this package's checkpoints/ (where genq/train_genq_jax.py # writes them, since occ_dir = dirname(dirname(train_genq_jax.py)) = ogbench_genq/). ckpt_dir = os.path.join(PKG_DIR, "checkpoints")
config = get_config() config["actor_loss"] = actor_loss config["alpha"] = alpha config["expectile"] = expectile config["genq_ensemble"] = not no_ensemble config["batch_size"] = batch_size config["adv_norm"] = adv_norm if actor_geom_sample: # Geometric (near-horizon) actor goals: on envs where the behavior-Q action contrast # decays fast with horizon (puzzle), concentrate AWR supervision where the Gen-Q # signal lives instead of uniformly over the future trajectory. config["actor_geom_sample"] = True vhd = tuple(int(x) for x in value_hidden_dims.split(",")) config["value_hidden_dims"] = vhd config["actor_hidden_dims"] = vhd
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
# ---- Gen-Q occupancy: diffusion (sampled) or exact discrete categorical ---- if genq_discrete_npz is None and genq_npz is None: for cand in (os.path.join(ckpt_dir, f"m9_genq_{safe}.genqjax.npz"), os.path.join(ckpt_dir, f"m9_genq_jax_{safe}.genqjax.npz")): if os.path.exists(cand): genq_npz = cand break if genq_discrete_npz: from genq_discrete_jax import load_discrete_params, genq_q_discrete P, meta = load_discrete_params(genq_discrete_npz) genq_npz = genq_discrete_npz # for logging fields below else: assert genq_npz and os.path.exists(genq_npz), ( f"Gen-Q occupancy ckpt not found for {env_id}; train one with " f"genq/train_genq_jax.py --env {env_id} (expected a .genqjax.npz).") P, meta = load_genq_params(genq_npz) sig_scalar = float(sigma if sigma is not None else SIGMA_BY_ENV.get(env_id, 5.0)) sig = sig_scalar is_maze = (not env_id.startswith(LOCO_FULL)) and ("maze" in env_id) if target_variant != "default": # Wider occupancy target (e.g. puzzle bits_eff / full): per-dim read-out sigma — # task bits sharp (sig), dense action-responsive dims soft (sigma_aux). assert not genq_discrete_npz, "target_variant applies to the diffusion occupancy" bitmask = target_extractors.variant_bit_mask(env_id, target_variant) sig = np.where(bitmask, sig_scalar, float(sigma_aux)).astype(np.float32) assert meta["y_dim"] == len(bitmask), ( f"{os.path.basename(genq_npz)} y_dim={meta['y_dim']} does not match variant " f"'{target_variant}' dim {len(bitmask)} — train the occupancy with " f"--target_variant {target_variant}.") print(f"[genq] genq_npz={os.path.basename(genq_npz)} sigma={sig} is_maze={is_maze} " f"discrete={bool(genq_discrete_npz)} readout_tau={readout_tau} " f"target_variant={target_variant}", flush=True)
def to_genq_state(obs): return obs[:, :2] if is_maze else obs
if latent_npz: from train_latent_encoder_jax import load_encoder, encode_np _encP, _encM = load_encoder(latent_npz) sig = float(_encM["sigma_z"])
def to_target_goal(gobs): raw = np.asarray(gobs, dtype=np.float32) if _encM["full_obs"] else \ target_extractors.extract_target(env_id, gobs).astype(np.float32) return encode_np(_encP, _encM, raw) print(f"[genq] LATENT z_dim={_encM['z_dim']} sigma_z={sig} " f"full_obs={_encM['full_obs']}", flush=True) elif target_variant != "default": def to_target_goal(gobs): return target_extractors.extract_target_variant(env_id, gobs, target_variant).astype(np.float32) else: def to_target_goal(gobs): return target_extractors.extract_target(env_id, gobs).astype(np.float32)
if genq_discrete_npz: genq_q_fn = jax.jit(lambda s, a, g, k: genq_q_discrete( P, meta, s, a, g, sigma=sig, readout_tau=readout_tau)) else: genq_q_fn = jax.jit(lambda s, a, g, k: genq_q_jax( P, meta, s, a, g, k, n_occ=n_occ, sigma=sig, readout_tau=readout_tau, steps=readout_steps)) gkey = [jax.random.PRNGKey(seed + 999)]
def genq_q_batch(obs, goal_obs, acts): s = np.asarray(to_genq_state(obs), dtype=np.float32) g = np.asarray(to_target_goal(goal_obs), dtype=np.float32) a = np.clip(np.asarray(acts, dtype=np.float32), -1, 1) gkey[0], sub = jax.random.split(gkey[0]) return np.asarray(genq_q_fn(jnp.asarray(s), jnp.asarray(a), jnp.asarray(g), sub))
train_ds = GCDataset(Dataset.create(**train_dataset), config) _pb = train_ds.sample(4096) _q = genq_q_batch(_pb["observations"], _pb["value_goals"], _pb["actions"]) print(f"[genq] Gen-Q Q @ value_goals: mean={_q.mean():.4f} std={_q.std():.4f}", flush=True)
vtag = f"_{variant_tag}" if variant_tag else "" run = wandb.init(project="gen-q-policy-improvement", name=f"gciql_genq{vtag}-{env_id}-{actor_loss}-a{alpha}-tau{expectile}-n{n_occ}-s{seed}", mode=wandb_mode, tags=["gciql_genq", env_id], config=dict(method="gciql_genq", env=env_id, seed=seed, actor_loss=actor_loss, alpha=alpha, expectile=expectile, n_occ=n_occ, sigma=sig_scalar, latent=bool(latent_npz), genq_npz=os.path.basename(genq_npz), variant=variant_tag, adv_norm=adv_norm, q_filter_k=q_filter_k, actor_geom_sample=actor_geom_sample, readout_tau=readout_tau, discrete=bool(genq_discrete_npz), target_variant=target_variant, sigma_aux=sigma_aux, train_steps=train_steps), settings=wandb.Settings(start_method="thread")) print(f"[genq] WANDB_URL {run.get_url()}", flush=True) wandb.log({"genq/q_mean": float(_q.mean()), "genq/q_std": float(_q.std())}, step=0)
ex = train_ds.sample(2) agent = GCIQLGenQAgent.create(seed, ex["observations"], ex["actions"], config) wrap = (lambda a: _QFilterPolicy(a, genq_q_batch, q_filter_k)) if q_filter_k > 0 else None eval_success = _make_eval_fn(env, config, evaluate, jax, wrap=wrap) out = os.path.join(_result_dir(env_id, seed), f"gciql_genq{vtag}.json") curve = []
def dump(sr, per): json.dump({"method": "gciql_genq", "env": env_id, "seed": seed, "actor_loss": actor_loss, "alpha": alpha, "expectile": expectile, "n_occ": n_occ, "sigma": sig_scalar, "ensemble": config["genq_ensemble"], "latent": bool(latent_npz), "genq_npz": os.path.basename(genq_npz), "variant": variant_tag, "adv_norm": adv_norm, "q_filter_k": q_filter_k, "readout_tau": readout_tau, "discrete": bool(genq_discrete_npz), "target_variant": target_variant, "sigma_aux": sigma_aux, "success_rate": sr, "best_sr": (max(v for _, v in curve) if curve else sr), "per_task": per, "curve": curve, "train_steps": train_steps, "wall_clock_sec": round(time.time() - t0, 1), "wandb_url": run.get_url()}, open(out, "w"), indent=2)
for i in tqdm.trange(1, train_steps + 1, smoothing=0.1, dynamic_ncols=True): batch = train_ds.sample(config["batch_size"]) batch["genq_q_value"] = genq_q_batch(batch["observations"], batch["value_goals"], batch["actions"]) if actor_goal_critic: batch["genq_q_value_actor"] = genq_q_batch(batch["observations"], batch["actor_goals"], batch["actions"]) agent, info = agent.update(batch) if i % 1000 == 0: wandb.log({f"train/{k}": float(v) for k, v in info.items() if np.ndim(np.asarray(v)) == 0}, step=i) if eval_interval > 0 and i % eval_interval == 0: sr, per = eval_success(agent, eval_episodes_periodic) curve.append((i, sr)) wandb.log({"eval/success_rate": sr, "eval/peak": max(v for _, v in curve)}, step=i) print(f"[genq] step {i} sr={sr:.3f} (peak {max(v for _, v in curve):.3f})", flush=True) dump(sr, per)
sr, per = eval_success(agent, eval_episodes) curve.append((train_steps, sr)) dump(sr, per) print(f"[genq] {env_id} FINAL sr={sr:.3f} best={max(v for _, v in curve):.3f} -> {out}", flush=True) wandb.finish() return out
# --------------------------------------------------------------------------------------------------# GCIQL with the RECURSIVE Gen-Q occupancy critic (short-beta occupancy composed to d_gamma)# --------------------------------------------------------------------------------------------------def run_gciql_genq_recursive(env_id, seed=0, train_steps=300000, eval_episodes=50, eval_interval=50000, eval_episodes_periodic=15, actor_loss="awr", alpha=30.0, expectile=0.9, n_occ=16, batch_size=1024, value_hidden_dims="512,512,512", no_ensemble=False, sigma=None, recursive_beta=0.95, recursive_gamma=0.99, steps_per_jump=10, midpoint_bc_steps=30000, midpoint_awr_alpha=0.0, greedy_k=0, greedy_noise=0.3, greedy_n_occ=2, genq_npz=None, variant_tag=None, adv_norm=False, readout_tau=0.0, target_variant="default", sigma_aux=2.0, wandb_mode="online", ogbench_impls=OGBENCH_IMPLS): """Policy improvement with the recursive-d_gamma Gen-Q critic (genq/genq_recursive_jax.py).
`genq_npz` must be a SHORT-beta occupancy trained with genq/train_genq_jax.py --gamma <recursive_beta> --state_target (state==target, so each sampled midpoint feeds back in-graph). The d_gamma endpoint distribution is recovered exactly by geometric recursive jumps with stop probability p = beta(1-gamma)/(gamma(1-beta)); midpoint actions come from an inline gc-BC actor. Everything else is identical to run_gciql_genq (same agent, same on-the-fly critic target). """ _setup_paths(ogbench_impls) import jax import jax.numpy as jnp import tqdm import wandb from utils.datasets import Dataset, GCDataset from utils.env_utils import make_env_and_datasets from utils.evaluation import evaluate from target_extractors import env_safe_name import target_extractors from genq_jax import load_genq_params, genq_q as genq_q_direct from genq_recursive_jax import (genq_q_recursive, stop_prob, default_max_depth, fit_midpoint_actor) from train_genq_jax import build_ends from gciql_genq import GCIQLGenQAgent, get_config
t0 = time.time() safe = env_safe_name(env_id) ckpt_dir = os.path.join(PKG_DIR, "checkpoints") beta_tag = "b" + str(recursive_beta).replace(".", "") # 0.9 -> b09, 0.95 -> b095
config = get_config() config["actor_loss"] = actor_loss config["alpha"] = alpha config["expectile"] = expectile config["genq_ensemble"] = not no_ensemble config["batch_size"] = batch_size config["adv_norm"] = adv_norm vhd = tuple(int(x) for x in value_hidden_dims.split(",")) config["value_hidden_dims"] = vhd config["actor_hidden_dims"] = vhd
env, train_dataset, _ = make_env_and_datasets(env_id, frame_stack=config["frame_stack"])
# ---- short-beta occupancy (state==target) ---- if genq_npz is None: genq_npz = os.path.join(ckpt_dir, f"m9_genq_rec_{safe}_{beta_tag}.genqjax.npz") assert os.path.exists(genq_npz), ( f"recursive Gen-Q occupancy ckpt not found: {genq_npz}; train it with " f"genq/train_genq_jax.py --env {env_id} --gamma {recursive_beta} --state_target " f"--out {genq_npz}") P, meta = load_genq_params(genq_npz) sig_scalar = float(sigma if sigma is not None else SIGMA_BY_ENV.get(env_id, 5.0)) sig = sig_scalar if target_variant != "default": # Wider state==target space (e.g. puzzle bits_eff): per-dim read-out sigma — # task bits sharp (sig), dense action-responsive dims soft (sigma_aux). Used for # the endpoint read-out AND the in-chain greedy candidate scoring. bitmask = target_extractors.variant_bit_mask(env_id, target_variant) sig = np.where(bitmask, sig_scalar, float(sigma_aux)).astype(np.float32) assert meta["y_dim"] == len(bitmask), ( f"{os.path.basename(genq_npz)} y_dim={meta['y_dim']} does not match variant " f"'{target_variant}' dim {len(bitmask)} — train the occupancy with " f"--target_variant {target_variant} --state_target.") obs_all = np.asarray(train_dataset["observations"], dtype=np.float32) act_all = np.asarray(train_dataset["actions"], dtype=np.float32) a_dim = act_all.shape[1] assert meta["cond_dim"] == 2 * meta["y_dim"] + a_dim, ( f"{os.path.basename(genq_npz)} is not a --state_target occupancy " f"(cond_dim={meta['cond_dim']}, expected 2*{meta['y_dim']}+{a_dim}); the recursion " f"requires state==target conditioning.") p_stop = stop_prob(recursive_beta, recursive_gamma) max_depth = default_max_depth(recursive_beta, recursive_gamma) print(f"[genq-rec] genq_npz={os.path.basename(genq_npz)} beta={recursive_beta} " f"gamma={recursive_gamma} p={p_stop:.4f} E[jumps]={1/p_stop:.1f} max_depth={max_depth} " f"steps/jump={steps_per_jump} sigma={sig} mixed={meta.get('mixed', False)} " f"target_variant={target_variant} readout_tau={readout_tau} adv_norm={adv_norm}", flush=True)
def to_genq_state(obs): return target_extractors.extract_target_variant(env_id, obs, target_variant).astype(np.float32)
to_target_goal = to_genq_state # state == target == goal space
# ---- inline midpoint actor: (target_state, goal) -> action ---- # Plain gc-BC reproduces the BEHAVIOR policy at each jump (midpoint_awr_alpha=0). # With midpoint_awr_alpha>0 the BC is weighted by exp(alpha * normalized short-beta # advantage): the short-beta occupancy has the strongest action contrast (its horizon # ~1/(1-beta) steps is where actions still matter), so the chain composes an IMPROVED # policy's occupancy and the critic estimates Q^{pi_1}, not Q^{behavior} — one extra # policy-improvement step with no TD (issue #57 puzzle fix, stage 2). weight_fn = None if midpoint_awr_alpha > 0: @jax.jit def weight_fn(s_b, g_b, a_b, key): k1, k2, k3 = jax.random.split(key, 3) q_data = genq_q_direct(P, meta, s_b, a_b, g_b, k1, n_occ=8, sigma=sig) a_r1 = jnp.roll(a_b, 1, axis=0) # in-batch action permutations as baseline a_r2 = jnp.roll(a_b, 7, axis=0) q_b1 = genq_q_direct(P, meta, s_b, a_r1, g_b, k2, n_occ=8, sigma=sig) q_b2 = genq_q_direct(P, meta, s_b, a_r2, g_b, k3, n_occ=8, sigma=sig) adv = q_data - 0.5 * (q_b1 + q_b2) adv = (adv - adv.mean()) / (adv.std() + 1e-6) # scale-free (issue #57 lesson) return jnp.minimum(jnp.exp(midpoint_awr_alpha * adv), 100.0)
tgt_all = to_genq_state(obs_all) end_of = build_ends(train_dataset["terminals"]) actor_fn, bc_loss = fit_midpoint_actor(tgt_all, act_all, end_of, goal_of=lambda gi: tgt_all[gi], steps=midpoint_bc_steps, seed=seed, weight_fn=weight_fn) kind = f"AWR-weighted (alpha={midpoint_awr_alpha})" if midpoint_awr_alpha > 0 else "gc-BC" print(f"[genq-rec] midpoint {kind} actor fit (final loss {bc_loss:.4f})", flush=True)
genq_q_fn = jax.jit(lambda s, a, g, k: genq_q_recursive( P, meta, s, a, g, k, actor_fn, n_occ=n_occ, beta=recursive_beta, gamma=recursive_gamma, max_depth=max_depth, sigma=sig, steps=steps_per_jump, greedy_k=greedy_k, greedy_noise=greedy_noise, greedy_n_occ=greedy_n_occ, greedy_sigma=sig, readout_tau=readout_tau)) gkey = [jax.random.PRNGKey(seed + 999)]
# The recursive+greedy graph is memory-hungry: one row fans out to n_occ chains x # greedy_k*greedy_n_occ candidate-scoring samples PER JUMP, so a full 1024-row critic # batch (or the 4096-row startup probe) OOMs a shared GPU. Evaluate in fixed 256-row # chunks — same math, one retrace, ~16x smaller live buffers. def genq_q_batch(obs, goal_obs, acts, _chunk=256): s = np.asarray(to_genq_state(obs), dtype=np.float32) g = np.asarray(to_target_goal(goal_obs), dtype=np.float32) a = np.clip(np.asarray(acts, dtype=np.float32), -1, 1) assert len(s) % _chunk == 0, f"critic batch {len(s)} not divisible by chunk {_chunk}" outs = [] for i in range(0, len(s), _chunk): gkey[0], sub = jax.random.split(gkey[0]) outs.append(np.asarray(genq_q_fn(jnp.asarray(s[i:i + _chunk]), jnp.asarray(a[i:i + _chunk]), jnp.asarray(g[i:i + _chunk]), sub))) return np.concatenate(outs)
train_ds = GCDataset(Dataset.create(**train_dataset), config) _pb = train_ds.sample(4096) _q = genq_q_batch(_pb["observations"], _pb["value_goals"], _pb["actions"]) print(f"[genq-rec] recursive Gen-Q Q @ value_goals: mean={_q.mean():.4f} std={_q.std():.4f}", flush=True)
vtag = f"_{variant_tag}" if variant_tag else "" run = wandb.init(project="gen-q-policy-improvement", name=f"gciql_genq_rec_{beta_tag}{vtag}-{env_id}-{actor_loss}-a{alpha}" f"-tau{expectile}-n{n_occ}-s{seed}", mode=wandb_mode, tags=["gciql_genq_rec", env_id], config=dict(method="gciql_genq_rec", env=env_id, seed=seed, actor_loss=actor_loss, alpha=alpha, expectile=expectile, n_occ=n_occ, sigma=sig_scalar, beta=recursive_beta, gamma=recursive_gamma, stop_prob=p_stop, max_depth=max_depth, steps_per_jump=steps_per_jump, midpoint_bc_loss=bc_loss, midpoint_awr_alpha=midpoint_awr_alpha, greedy_k=greedy_k, adv_norm=adv_norm, readout_tau=readout_tau, target_variant=target_variant, sigma_aux=sigma_aux, mixed=bool(meta.get("mixed", False)), genq_npz=os.path.basename(genq_npz), train_steps=train_steps), settings=wandb.Settings(start_method="thread")) print(f"[genq-rec] WANDB_URL {run.get_url()}", flush=True) wandb.log({"genq/q_mean": float(_q.mean()), "genq/q_std": float(_q.std())}, step=0)
ex = train_ds.sample(2) agent = GCIQLGenQAgent.create(seed, ex["observations"], ex["actions"], config) eval_success = _make_eval_fn(env, config, evaluate, jax) out = os.path.join(_result_dir(env_id, seed), f"gciql_genq_rec_{beta_tag}{vtag}.json") curve = []
def dump(sr, per): json.dump({"method": "gciql_genq_rec", "env": env_id, "seed": seed, "actor_loss": actor_loss, "alpha": alpha, "expectile": expectile, "n_occ": n_occ, "sigma": sig_scalar, "beta": recursive_beta, "gamma": recursive_gamma, "stop_prob": p_stop, "max_depth": max_depth, "steps_per_jump": steps_per_jump, "midpoint_bc_loss": bc_loss, "midpoint_awr_alpha": midpoint_awr_alpha, "greedy_k": greedy_k, "adv_norm": adv_norm, "readout_tau": readout_tau, "target_variant": target_variant, "sigma_aux": sigma_aux, "mixed": bool(meta.get("mixed", False)), "genq_npz": os.path.basename(genq_npz), "success_rate": sr, "best_sr": (max(v for _, v in curve) if curve else sr), "per_task": per, "curve": curve, "train_steps": train_steps, "wall_clock_sec": round(time.time() - t0, 1), "wandb_url": run.get_url()}, open(out, "w"), indent=2)
for i in tqdm.trange(1, train_steps + 1, smoothing=0.1, dynamic_ncols=True): batch = train_ds.sample(config["batch_size"]) batch["genq_q_value"] = genq_q_batch(batch["observations"], batch["value_goals"], batch["actions"]) agent, info = agent.update(batch) if i % 1000 == 0: wandb.log({f"train/{k}": float(v) for k, v in info.items() if np.ndim(np.asarray(v)) == 0}, step=i) if eval_interval > 0 and i % eval_interval == 0: sr, per = eval_success(agent, eval_episodes_periodic) curve.append((i, sr)) wandb.log({"eval/success_rate": sr, "eval/peak": max(v for _, v in curve)}, step=i) print(f"[genq-rec] step {i} sr={sr:.3f} (peak {max(v for _, v in curve):.3f})", flush=True) dump(sr, per)
sr, per = eval_success(agent, eval_episodes) curve.append((train_steps, sr)) dump(sr, per) print(f"[genq-rec] {env_id} beta={recursive_beta} FINAL sr={sr:.3f} " f"best={max(v for _, v in curve):.3f} -> {out}", flush=True) wandb.finish() return out1234567891011121314151617"""Goal-conditioned behavior cloning baseline (GCBC) — JAX-only.
This is the plain behavior-cloning baseline for the policy-improvement story: a goal-conditionedGaussian policy pi(a | s, g) trained by maximum likelihood on the offline dataset, with NO criticand NO policy improvement. It is the floor that GCIQL and Gen-Q-GCIQL must beat.
We reuse OGBench's reference GCBC agent unchanged (it is pure JAX/Flax and is the canonical baselinethe OGBench paper reports), and only re-export it under the names this package uses. Goal-conditioning is first-class: the actor takes g as input exactly as in OGBench GCBC."""from agents.gcbc import GCBCAgent, get_config
# Public aliases for this package.GCBCAgent = GCBCAgentget_config = get_config
__all__ = ["GCBCAgent", "get_config"]123version https://git-lfs.github.com/spec/v1oid sha256:3c41480074e5840b3d6b19a4413b501898da1bb9b300794d2d55e839f57342c6size 1260620123456789101112131415161718#!/bin/bash# Confirm the CompPlan horizon fix at FULL budget (m=1024, 50ep): nearer subgoals# beta[0.92,0.96], replan 12, n=5, on the td-free triple + quad occupancies.set -uo pipefailSCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)R=$(cd -- "$SCRIPT_DIR/.." && pwd)PY=${PYTHON:-"$R/.ogbench_venv/bin/python"}CKPT_ROOT=${GENQ_CKPT_ROOT:-/proj/inf-scaling/zwhong/gen_q/ckpt}export XLA_PYTHON_CLIENT_PREALLOCATE=false PYTHONUNBUFFERED=1 MUJOCO_GL=eglcd "$R"; mkdir -p results/comp_fixedfor cell in triple quad; do echo "########## FIXED $cell beta[0.92,0.96] replan12 n5 m1024 50ep ##########" "$PY" -u ogbench_genq/comp_plan_combined_eval.py --ckpt "$CKPT_ROOT/comp_tdfree/${cell}.pkl" \ --plan_n 5 --plan_m 1024 --episodes 50 \ --beta_lo 0.92 --beta_hi 0.96 --gamma_eval 0.995 --replan_every 12 \ --out "results/comp_fixed/${cell}_fixed.json" 2>&1 | grep -E "FINAL" | tail -2doneecho "[fixed] DONE"12345678910111213141516171819202122232425262728293031323334#!/bin/bash# INVESTIGATE the CompPlan gap: does making sub-goals NEARBY (reachable by a weak# base) + replanning faster lift td-free triple composition above the current 0.048?# Eval-only sweep on the trained td-free occupancy (ckpt/comp_tdfree/triple.pkl).# Hypothesis: beta in [0.98,0.99] puts waypoints ~50-100 steps out (as hard as the# goal); shorter beta -> nearer waypoints -> composition can chain.set -uo pipefailSCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)R=$(cd -- "$SCRIPT_DIR/.." && pwd)PY=${PYTHON:-"$R/.ogbench_venv/bin/python"}CKPT_ROOT=${GENQ_CKPT_ROOT:-/proj/inf-scaling/zwhong/gen_q/ckpt}CK=$CKPT_ROOT/comp_tdfree/triple.pklexport XLA_PYTHON_CLIENT_PREALLOCATE=false PYTHONUNBUFFERED=1 MUJOCO_GL=eglcd "$R"; mkdir -p results/comp_sweep# tag beta_lo beta_hi replan plan_nCFGS=( "baseline 0.98 0.99 25 4" "mid 0.92 0.96 15 4" "near 0.85 0.92 10 6" "vnear 0.80 0.90 8 6" "near8 0.90 0.95 10 8")for row in "${CFGS[@]}"; do set -- $row; TAG=$1; BLO=$2; BHI=$3; RE=$4; N=$5 echo "########## SWEEP $TAG beta=[$BLO,$BHI] replan=$RE n=$N ##########" "$PY" -u ogbench_genq/comp_plan_combined_eval.py --ckpt "$CK" \ --plan_n "$N" --plan_m 256 --episodes 20 \ --beta_lo "$BLO" --beta_hi "$BHI" --gamma_eval 0.995 --replan_every "$RE" \ --out "results/comp_sweep/triple_${TAG}.json" 2>&1 | grep -E "FINAL|task [0-9]:" | tail -6doneecho "[sweep] DONE"for f in results/comp_sweep/triple_*.json; do "$PY" -c "import json;r=json.load(open('$f'));print(' $(basename $f)',r.get('success_rate'),r.get('per_task'))" 2>/dev/null || truedone123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329#!/usr/bin/env python3"""Faithful reproduction of CompPlan — "Compositional Planning with Jumpy WorldModels" (arXiv:2602.19634) — on STATE OGBench cube. See doc/COMPPLAN_REPRO.md forthe full spec, quoted equations, and every documented gap-choice.
Targets (GC-BC base): cube-3 0.09->0.92, cube-4 0.00->0.76.
Pieces (all here): 1. GC-BC base policy pi_g(a|s,g). 2. Jumpy GHM = successor measure over FULL STATES via a conditional flow field v(X|s,a,g,gamma), trained by the td-hc loss (Eq.5): term1 on the full batch, TD/consistency terms 2-3 on a 12.5% sub-batch vs an EMA target, with partial/ full flow sampling; 10% of goals masked to also learn the UNCONDITIONAL GHM. 3. GSP planner: propose subgoal sequences from the UNCONDITIONAL GHM, score by the Lemma-1 composed value, execute a_1~pi_{z1}(s), replan (receding horizon)."""import argparseimport functoolsimport osimport pickleimport sys
import numpy as np
def _ends(terminals): term = np.asarray(terminals); ends = np.where(term > 0)[0] end_of = np.zeros(len(term), np.int64); prev = 0 for e in ends: end_of[prev:e + 1] = e + 1; prev = e + 1 if prev < len(term): end_of[prev:] = len(term) return end_of
def build_argparser(): ap = argparse.ArgumentParser() ap.add_argument("--env", required=True) ap.add_argument("--latents", default=None) ap.add_argument("--out", required=True) ap.add_argument("--train_steps", type=int, default=3000000) ap.add_argument("--save_every", type=int, default=500000, help="periodic checkpoint + GHM reach diagnostic") ap.add_argument("--gamma_diag", type=float, default=0.99) ap.add_argument("--batch", type=int, default=256) ap.add_argument("--cons_batch", type=int, default=32) # 12.5% of 256 ap.add_argument("--lr", type=float, default=1e-4) ap.add_argument("--hidden", type=int, default=512) ap.add_argument("--layers", type=int, default=4) ap.add_argument("--flow_steps", type=int, default=16) # Euler steps for sampling ap.add_argument("--gamma_min", type=float, default=0.95) ap.add_argument("--gamma_max", type=float, default=0.997) # cube goals ~150-300 steps -> need long horizon ap.add_argument("--uncond_mask", type=float, default=0.10) ap.add_argument("--ema", type=float, default=0.999) # slower target = stable bootstrap ap.add_argument("--cons_after", type=int, default=100000, help="warm up term1 (flow-matching) alone before the TD/consistency legs") ap.add_argument("--cons_ramp", type=int, default=300000, help="linearly ramp the consistency weight 0->1 over this many steps (no shock)") ap.add_argument("--cons_weight", type=float, default=1.0) ap.add_argument("--huber", type=float, default=1.0, help="Huber delta on consistency residuals") ap.add_argument("--grad_clip", type=float, default=0.5) ap.add_argument("--x_clip", type=float, default=4.0, help="clip flow samples during integration") ap.add_argument("--tau", type=float, default=0.15) # goal-hit kernel width (z-space) ap.add_argument("--p_curgoal", type=float, default=0.2) ap.add_argument("--p_trajgoal", type=float, default=0.5) ap.add_argument("--p_randomgoal", type=float, default=0.3) ap.add_argument("--gcbc_steps", type=int, default=500000) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--eval_only", action="store_true") ap.add_argument("--episodes", type=int, default=50) ap.add_argument("--plan_n", type=int, default=4) ap.add_argument("--plan_m", type=int, default=1024) ap.add_argument("--beta_lo", type=float, default=0.98) # sub-policy horizons ap.add_argument("--beta_hi", type=float, default=0.99) ap.add_argument("--gamma_eval", type=float, default=0.99) ap.add_argument("--replan_every", type=int, default=25) ap.add_argument("--smoke", action="store_true") return ap
def main(): a = build_argparser().parse_args() if a.smoke: a.train_steps = 60; a.gcbc_steps = 60; a.batch = 32; a.cons_batch = 8 a.flow_steps = 4; a.episodes = 2; a.plan_m = 16
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import jax, jax.numpy as jnp, optax, flax.linen as nn from genq import target_extractors
print(f"[comp_plan] env={a.env} devices={jax.devices()}", flush=True) rng = np.random.default_rng(a.seed)
# ---------- data: full state S, action A, reward-slice X=extract_target(S) ---------- if a.latents and os.path.exists(a.latents): d = np.load(a.latents) S = np.asarray(d["state_h"], np.float32); X = np.asarray(d["z"], np.float32) A = np.clip(np.asarray(d["actions"], np.float32), -1, 1) end_of = _ends(d["terminals"]) else: import ogbench _e, ds, _ = ogbench.make_env_and_datasets(a.env) S = np.asarray(ds["observations"], np.float32) X = target_extractors.extract_target(a.env, S).astype(np.float32) A = np.clip(np.asarray(ds["actions"], np.float32), -1, 1) end_of = _ends(ds["terminals"]) N, s_dim = S.shape; x_dim = X.shape[1]; a_dim = A.shape[1] # which state dims are the reward slice (X is exactly a slice of S). Use many # rows + enforce UNIQUENESS so two near-equal cube coords can't collide onto the # same state dim (that silently corrupted cube-quadruple with a 256-row probe). probe = min(20000, N) tgt_idx = []; used = set() for j in range(x_dim): diffs = np.abs(S[:probe] - X[:probe, j:j + 1]).sum(0) for c in np.argsort(diffs): if int(c) not in used and diffs[c] < 1e-2: tgt_idx.append(int(c)); used.add(int(c)); break else: raise AssertionError(f"no unique state dim matches reward-slice col {j}") tgt_idx = np.array(tgt_idx, np.int64) assert len(set(tgt_idx.tolist())) == x_dim, f"duplicate target indices {tgt_idx.tolist()}" assert np.allclose(S[:probe][:, tgt_idx], X[:probe], atol=1e-4), "target-slice index recovery failed" print(f"[comp_plan] N={N} s_dim={s_dim} x_dim={x_dim} a_dim={a_dim} tgt_idx={tgt_idx.tolist()}", flush=True)
s_mu, s_sd = S.mean(0), S.std(0) + 1e-6 x_mu, x_sd = X.mean(0), X.std(0) + 1e-6 a_mu, a_sd = A.mean(0), A.std(0) + 1e-6 Sn = ((S - s_mu) / s_sd).astype(np.float32) Xn = ((X - x_mu) / x_sd).astype(np.float32) An = ((A - a_mu) / a_sd).astype(np.float32) s_mu_j, s_sd_j = jnp.asarray(s_mu), jnp.asarray(s_sd) x_mu_j, x_sd_j = jnp.asarray(x_mu), jnp.asarray(x_sd) tgt_idx_j = jnp.asarray(tgt_idx) nxt = np.minimum(np.arange(N) + 1, end_of - 1)
def slice_target_norm(Sn_batch): """normalized full state -> normalized reward-slice (cube positions).""" s_real = Sn_batch * s_sd_j + s_mu_j x_real = s_real[:, tgt_idx_j] return (x_real - x_mu_j) / x_sd_j
def hindsight_goals(t): n = len(t); final = end_of[t] - 1 off = rng.geometric(1.0 - 0.99, size=n); traj = np.minimum(t + off, final) randi = rng.integers(0, N, n); u = rng.random(n) is_cur = u < a.p_curgoal is_traj = (u >= a.p_curgoal) & (u < a.p_curgoal + a.p_trajgoal) return np.where(is_cur, t, np.where(is_traj, traj, randi))
# ---------------- networks ---------------- def disc_embed(g): return jnp.stack([g, 1.0 - g, -jnp.log(jnp.clip(1.0 - g, 1e-6, 1.0))], -1)
class GCBC(nn.Module): @nn.compact def __call__(self, s, g): h = jnp.concatenate([s, g], -1) for _ in range(3): h = nn.relu(nn.Dense(a.hidden)(h)) return jnp.tanh(nn.Dense(a_dim)(h))
class Flow(nn.Module): """v(X|s,a,g,gamma) over FULL states. g may be masked (unconditional GHM).""" @nn.compact def __call__(self, xt, t, s, act, g, gam, gmask): gcond = jnp.concatenate([g * gmask[:, None], gmask[:, None]], -1) c = jnp.concatenate([s, act, gcond, disc_embed(gam), jnp.sin(t * jnp.pi)[:, None], t[:, None]], -1) for _ in range(2): c = nn.swish(nn.Dense(a.hidden)(c)) h = xt for _ in range(a.layers): h = nn.Dense(a.hidden)(jnp.concatenate([h, xt], -1)) sc = nn.Dense(a.hidden)(c); sh = nn.Dense(a.hidden)(c) h = nn.swish(h * (1.0 + sc) + sh) return nn.Dense(s_dim)(h) # velocity in FULL-state space
gcbc, flow = GCBC(), Flow() key = jax.random.PRNGKey(a.seed); k1, k2 = jax.random.split(key) p_bc = gcbc.init(k1, jnp.zeros((1, s_dim)), jnp.zeros((1, x_dim))) p_fl = flow.init(k2, jnp.zeros((1, s_dim)), jnp.zeros((1,)), jnp.zeros((1, s_dim)), jnp.zeros((1, a_dim)), jnp.zeros((1, x_dim)), jnp.full((1,), 0.99), jnp.ones((1,))) p_bar = jax.tree_util.tree_map(lambda z: z, p_fl) txb = optax.adam(a.lr); ob = txb.init(p_bc) txf = optax.chain(optax.clip_by_global_norm(a.grad_clip), optax.adam(a.lr)); of = txf.init(p_fl)
def vfield(pp, xt, t, s, act, g, gam, gmask): return flow.apply(pp, xt, t, s, act, g, gam, gmask)
def flow_to(pp, s, act, g, gam, gmask, k, t_end, steps): """Euler-integrate dX/dt=v from X0~N(0,I) to per-sample time t_end (full state).""" B = s.shape[0]; x = jax.random.normal(k, (B, s_dim)) dt = t_end / steps for i in range(steps): tt = (i / steps) * t_end x = x + dt[:, None] * vfield(pp, x, tt, s, act, g, gam, gmask) x = jnp.clip(x, -a.x_clip, a.x_clip) # keep Euler stable pre-convergence return x
# ---------------- GC-BC ---------------- @jax.jit def bc_step(p, o, s, g, act): def loss(p): return jnp.mean((gcbc.apply(p, s, g) - act) ** 2) l, gr = jax.value_and_grad(loss)(p); u, o = txb.update(gr, o, p) return optax.apply_updates(p, u), o, l
def bc_mode(pb, s_n, g_n): return gcbc.apply(pb, s_n, g_n)
# ---------------- td-hc flow (Eq. 5) ---------------- @jax.jit def flow_step(pf, pbar, pb, o, k, cons_on, s, act, sp, g, gmask, # main batch (term1) cs, cact, csp, cg, cgmask): # consistency sub-batch (terms 2,3) B = s.shape[0]; Bc = cs.shape[0] ks = jax.random.split(k, 12) gam = jax.random.uniform(ks[0], (B,), minval=a.gamma_min, maxval=a.gamma_max)
# term 1: one-step conditional flow-matching to the FULL next state s' t1 = jax.random.uniform(ks[1], (B,)); x0 = jax.random.normal(ks[2], (B, s_dim)) Xt1 = (1 - t1)[:, None] * x0 + t1[:, None] * sp def term1(pp): v = vfield(pp, Xt1, t1, s, act, g, gam, gmask) return jnp.mean((1 - gam)[:, None] * (v - (sp - x0)) ** 2)
# consistency legs on the sub-batch cgam = jax.random.uniform(ks[3], (Bc,), minval=a.gamma_min, maxval=a.gamma_max) cbeta = a.gamma_min + jax.random.uniform(ks[4], (Bc,)) * (cgam - a.gamma_min) # U[gmin,gam] cap = bc_mode(pb, csp, cg) # a' = pi_g(s',g) # term 2: X_t ~ partial beta-model flow at (s',a'); match v(.|s,a,gam) to vbar(.|s',a',beta) t2 = jax.random.uniform(ks[5], (Bc,)) Xt2 = flow_to(pbar, csp, cap, cg, cbeta, cgmask, ks[6], t2, a.flow_steps) Xt2 = jax.lax.stop_gradient(Xt2) def huber(r): d = a.huber; absr = jnp.abs(r) return jnp.where(absr < d, 0.5 * r ** 2, d * (absr - 0.5 * d)) def term2(pp): v = vfield(pp, Xt2, t2, cs, cact, cg, cgam, cgmask) vb = jax.lax.stop_gradient(vfield(pbar, Xt2, t2, csp, cap, cg, cbeta, cgmask)) coef = cgam * (1 - cgam) / (1 - cbeta) return jnp.mean(coef[:, None] * huber(v - vb)) # term 3: S+ ~ full beta-model @ (s',a'); a+=pi_g(S+); X_t ~ partial gamma-model @ (S+,a+) Splus = jax.lax.stop_gradient( flow_to(pbar, csp, cap, cg, cbeta, cgmask, ks[7], jnp.ones((Bc,)), a.flow_steps)) aplus = bc_mode(pb, Splus, cg) # a+ = pi_g(S+, g) t3 = jax.random.uniform(ks[8], (Bc,)) Xt3 = jax.lax.stop_gradient( flow_to(pbar, Splus, aplus, cg, cgam, cgmask, ks[9], t3, a.flow_steps)) def term3(pp): v = vfield(pp, Xt3, t3, cs, cact, cg, cgam, cgmask) vb = jax.lax.stop_gradient(vfield(pbar, Xt3, t3, Splus, aplus, cg, cgam, cgmask)) coef = cgam * (cgam - cbeta) / (1 - cbeta) return jnp.mean(coef[:, None] * huber(v - vb))
def loss(pp): return term1(pp) + a.cons_weight * cons_on * (term2(pp) + term3(pp)) l, gr = jax.value_and_grad(loss)(pf); u, o = txf.update(gr, o, pf) pf2 = optax.apply_updates(pf, u) pbar2 = jax.tree_util.tree_map(lambda tb, tn: a.ema * tb + (1 - a.ema) * tn, pbar, pf2) return pf2, pbar2, o, l
# ---- GHM reach diagnostic: does the goal-conditioned occupancy reach the goal? ---- @jax.jit def ghm_reach(pf, pb, sn, gn, key): an = gcbc.apply(pb, sn, gn) B = sn.shape[0]; x = jax.random.normal(key, (B, s_dim)); dt = 1.0 / a.flow_steps gamv = jnp.full((B,), a.gamma_diag); gm = jnp.ones((B,)) for i in range(a.flow_steps): tt = jnp.full((B,), i * dt) x = jnp.clip(x + dt * vfield(pf, x, tt, sn, an, gn, gamv, gm), -a.x_clip, a.x_clip) xt = slice_target_norm(x) # sampled future's cube slice d2 = jnp.sum((xt - gn) ** 2, -1) reach = jnp.mean(jnp.exp(-d2 / (x_dim * 2 * a.tau ** 2))) # reward toward the goal return reach
def save_ckpt(path, pf, pbar): os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, "wb") as f: pickle.dump(dict(p_bc=jax.device_get(p_bc), p_fl=jax.device_get(pf), p_bar=jax.device_get(pbar), s_mu=s_mu, s_sd=s_sd, x_mu=x_mu, x_sd=x_sd, a_mu=a_mu, a_sd=a_sd, tgt_idx=tgt_idx, env=a.env, s_dim=s_dim, x_dim=x_dim, a_dim=a_dim, args=vars(a)), f)
if not a.eval_only: import tqdm for it in tqdm.trange(1, a.gcbc_steps + 1, desc="gcbc", dynamic_ncols=True): idx = rng.integers(0, N, a.batch); gi = hindsight_goals(idx) p_bc, ob, lb = bc_step(p_bc, ob, jnp.asarray(Sn[idx]), jnp.asarray(Xn[gi]), jnp.asarray(An[idx])) if it % 20000 == 0: print(f"[gcbc] {it} loss={float(lb):.4f}", flush=True) for it in tqdm.trange(1, a.train_steps + 1, desc="tdhc", dynamic_ncols=True): idx = rng.integers(0, N, a.batch); gi = hindsight_goals(idx); spi = nxt[idx] ci = rng.integers(0, N, a.cons_batch); cgi = hindsight_goals(ci); cspi = nxt[ci] gm = (rng.random(a.batch) >= a.uncond_mask).astype(np.float32) cgm = (rng.random(a.cons_batch) >= a.uncond_mask).astype(np.float32) k = jax.random.fold_in(key, it) cons_on = jnp.float32(min(1.0, max(0.0, (it - a.cons_after) / a.cons_ramp))) p_fl, p_bar, of, lf = flow_step( p_fl, p_bar, p_bc, of, k, cons_on, jnp.asarray(Sn[idx]), jnp.asarray(An[idx]), jnp.asarray(Sn[spi]), jnp.asarray(Xn[gi]), jnp.asarray(gm), jnp.asarray(Sn[ci]), jnp.asarray(An[ci]), jnp.asarray(Sn[cspi]), jnp.asarray(Xn[cgi]), jnp.asarray(cgm)) if it % 10000 == 0: print(f"[tdhc] {it} loss={float(lf):.4f}", flush=True) if it % a.save_every == 0: ridx = rng.integers(0, N, 512); rgi = hindsight_goals(ridx) rr = rng.integers(0, N, 512) reach = float(ghm_reach(p_fl, p_bc, jnp.asarray(Sn[ridx]), jnp.asarray(Xn[rgi]), jax.random.fold_in(key, 7 * it))) floor = float(jnp.mean(jnp.exp( -jnp.sum((jnp.asarray(Xn[rr]) - jnp.asarray(Xn[rgi])) ** 2, -1) / (x_dim * 2 * a.tau ** 2)))) print(f"[tdhc-diag] {it} reach={reach:.4f} floor={floor:.4f} " f"(reach>>floor => GHM resolves goals)", flush=True) save_ckpt(a.out.replace(".pkl", f"_step{it}.pkl"), p_fl, p_bar) os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) with open(a.out, "wb") as f: pickle.dump(dict(p_bc=jax.device_get(p_bc), p_fl=jax.device_get(p_fl), p_bar=jax.device_get(p_bar), s_mu=s_mu, s_sd=s_sd, x_mu=x_mu, x_sd=x_sd, a_mu=a_mu, a_sd=a_sd, tgt_idx=tgt_idx, env=a.env, s_dim=s_dim, x_dim=x_dim, a_dim=a_dim, args=vars(a)), f) print(f"[comp_plan] saved {a.out}", flush=True) return print("[comp_plan] eval GSP planner: see comp_plan_eval.py", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299#!/usr/bin/env python3"""CompPlan reproduction, COMBINED with the VERIFIED OGBench reference GC-BC.
This is comp_plan.py's audited td-hc GHM + GSP planner, but with the base policyswapped for OGBench's *standard* GCBC (agents/gcbc.py) loaded from a trainedcheckpoint -- the policy whose zero-shot success matches the paper's reportednumber. The previous in-file GCBC was a deterministic tanh+MSE head over anaction-NORMALIZED target, which saturated and scored 0.000; the reference actoris a linear-mean unit-variance Gaussian (== MSE on the mean, NO tanh, NO actionnorm) conditioned on FULL-STATE goals. See doc/COMPPLAN_REPRO.md.
Key wiring differences vs comp_plan.py: * base policy pi_g = frozen reference GCActor. RAW observations + RAW full-state goals in, RAW actions in [-1,1] out (OGBench does not normalize observations). * GHM goal-conditioning is a FULL STATE (s_dim), matching the paper's z in S and the actor's goal space (comp_plan.py conditioned the occupancy on the x-slice). * actions that condition the flow are RAW (no a_mu/a_sd normalization).The GHM itself (td-hc Eq.5: term1 + EMA-target consistency terms 2/3, 10% uncondmask, 12.5% consistency sub-batch) is reused verbatim -- it was audited as faithful."""import argparseimport osimport pickleimport sys
import numpy as np
IMPLS = os.environ.get("OGBENCH_IMPLS", "/u/zwhong/ogbench_ref/impls")
def _ends(terminals): term = np.asarray(terminals); ends = np.where(term > 0)[0] end_of = np.zeros(len(term), np.int64); prev = 0 for e in ends: end_of[prev:e + 1] = e + 1; prev = e + 1 if prev < len(term): end_of[prev:] = len(term) return end_of
def build_argparser(): ap = argparse.ArgumentParser() ap.add_argument("--env", required=True) ap.add_argument("--gcbc_ckpt", required=True, help="glob to the reference GCBC run dir (contains params_<epoch>.pkl)") ap.add_argument("--gcbc_epoch", type=int, default=1000000) ap.add_argument("--out", required=True) ap.add_argument("--train_steps", type=int, default=2000000) ap.add_argument("--save_every", type=int, default=500000) ap.add_argument("--gamma_diag", type=float, default=0.99) ap.add_argument("--batch", type=int, default=256) ap.add_argument("--cons_batch", type=int, default=32) ap.add_argument("--lr", type=float, default=1e-4) ap.add_argument("--hidden", type=int, default=512) ap.add_argument("--layers", type=int, default=4) ap.add_argument("--flow_steps", type=int, default=16) ap.add_argument("--gamma_min", type=float, default=0.95) ap.add_argument("--gamma_max", type=float, default=0.997) ap.add_argument("--uncond_mask", type=float, default=0.10) ap.add_argument("--ema", type=float, default=0.999) ap.add_argument("--cons_after", type=int, default=100000) ap.add_argument("--cons_ramp", type=int, default=300000) ap.add_argument("--cons_weight", type=float, default=0.5) ap.add_argument("--huber", type=float, default=1.0) ap.add_argument("--grad_clip", type=float, default=0.5) ap.add_argument("--x_clip", type=float, default=4.0) ap.add_argument("--tau", type=float, default=0.15) # actor goals: OGBench GCBC uses 100% future-in-trajectory (uniform), no random. ap.add_argument("--seed", type=int, default=0) ap.add_argument("--smoke", action="store_true") return ap
def load_reference_actor(env, s_dim, a_dim, ckpt_glob, epoch): """Reconstruct OGBench GCBCAgent, restore params, return (actor_def, actor_params).""" sys.path.insert(0, IMPLS) import jax.numpy as jnp from agents.gcbc import GCBCAgent, get_config from utils.flax_utils import restore_agent from utils.networks import GCActor
config = get_config() config["encoder"] = None ex_obs = np.zeros((1, s_dim), np.float32) ex_act = np.zeros((1, a_dim), np.float32) agent = GCBCAgent.create(0, ex_obs, ex_act, config) agent = restore_agent(agent, ckpt_glob, epoch) # actor params live under the ModuleDict submodule 'modules_actor' params = agent.network.params actor_params = params["modules_actor"] actor_def = GCActor( hidden_dims=tuple(config["actor_hidden_dims"]), action_dim=a_dim, state_dependent_std=False, const_std=config["const_std"], tanh_squash=False, gc_encoder=None, )
def pi_mode(raw_s, raw_g): # RAW obs + RAW full-state goal -> RAW action mode, clipped dist = actor_def.apply({"params": actor_params}, raw_s, raw_g, temperature=0.0) return jnp.clip(dist.mode(), -1.0, 1.0)
return actor_def, actor_params, pi_mode
def main(): a = build_argparser().parse_args() if a.smoke: a.train_steps = 60; a.batch = 32; a.cons_batch = 8 a.flow_steps = 4; a.cons_after = 10; a.cons_ramp = 20; a.save_every = 40
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import jax, jax.numpy as jnp, optax, flax.linen as nn from genq import target_extractors
print(f"[combined] env={a.env} devices={jax.devices()}", flush=True) rng = np.random.default_rng(a.seed)
import ogbench _e, ds, _ = ogbench.make_env_and_datasets(a.env) S = np.asarray(ds["observations"], np.float32) # RAW observations X = target_extractors.extract_target(a.env, S).astype(np.float32) A = np.clip(np.asarray(ds["actions"], np.float32), -1, 1) # RAW actions in [-1,1] end_of = _ends(ds["terminals"]) N, s_dim = S.shape; x_dim = X.shape[1]; a_dim = A.shape[1]
# recover which state dims are the reward slice (uniqueness-enforced) probe = min(20000, N); tgt_idx = []; used = set() for j in range(x_dim): diffs = np.abs(S[:probe] - X[:probe, j:j + 1]).sum(0) for c in np.argsort(diffs): if int(c) not in used and diffs[c] < 1e-2: tgt_idx.append(int(c)); used.add(int(c)); break else: raise AssertionError(f"no unique state dim matches reward-slice col {j}") tgt_idx = np.array(tgt_idx, np.int64) assert np.allclose(S[:probe][:, tgt_idx], X[:probe], atol=1e-4) print(f"[combined] N={N} s_dim={s_dim} x_dim={x_dim} a_dim={a_dim} tgt_idx={tgt_idx.tolist()}", flush=True)
# state normalization (GHM internal only; policy sees RAW). goals are full states. s_mu, s_sd = S.mean(0), S.std(0) + 1e-6 x_mu, x_sd = X.mean(0), X.std(0) + 1e-6 Sn = ((S - s_mu) / s_sd).astype(np.float32) s_mu_j, s_sd_j = jnp.asarray(s_mu), jnp.asarray(s_sd) x_mu_j, x_sd_j = jnp.asarray(x_mu), jnp.asarray(x_sd) tgt_idx_j = jnp.asarray(tgt_idx) nxt = np.minimum(np.arange(N) + 1, end_of - 1)
def unnorm_s(sn): return sn * s_sd_j + s_mu_j def slice_target_norm(sn): x_real = unnorm_s(sn)[:, tgt_idx_j] return (x_real - x_mu_j) / x_sd_j
# OGBench GCBC actor goals: 100% future-in-trajectory, uniform (actor_geom_sample=False) def actor_goals_uniform(t): final = end_of[t] - 1 return np.where(final > t, rng.integers(t + 1, np.maximum(final + 1, t + 2)), t)
# ---------- frozen reference base policy ---------- actor_def, actor_params, pi_mode = load_reference_actor( a.env, s_dim, a_dim, a.gcbc_ckpt, a.gcbc_epoch)
def pi_mode_from_norm(sn, gn): # normalized state+goal -> RAW action return pi_mode(unnorm_s(sn), unnorm_s(gn))
# ---------- GHM flow over FULL states, conditioned on FULL-state goal ---------- def disc_embed(g): return jnp.stack([g, 1.0 - g, -jnp.log(jnp.clip(1.0 - g, 1e-6, 1.0))], -1)
class Flow(nn.Module): @nn.compact def __call__(self, xt, t, s, act, g, gam, gmask): # g is FULL state (s_dim) gcond = jnp.concatenate([g * gmask[:, None], gmask[:, None]], -1) c = jnp.concatenate([s, act, gcond, disc_embed(gam), jnp.sin(t * jnp.pi)[:, None], t[:, None]], -1) for _ in range(2): c = nn.swish(nn.Dense(a.hidden)(c)) h = xt for _ in range(a.layers): h = nn.Dense(a.hidden)(jnp.concatenate([h, xt], -1)) sc = nn.Dense(a.hidden)(c); sh = nn.Dense(a.hidden)(c) h = nn.swish(h * (1.0 + sc) + sh) return nn.Dense(s_dim)(h)
flow = Flow() key = jax.random.PRNGKey(a.seed) p_fl = flow.init(key, jnp.zeros((1, s_dim)), jnp.zeros((1,)), jnp.zeros((1, s_dim)), jnp.zeros((1, a_dim)), jnp.zeros((1, s_dim)), jnp.full((1,), 0.99), jnp.ones((1,))) p_bar = jax.tree_util.tree_map(lambda z: z, p_fl) txf = optax.chain(optax.clip_by_global_norm(a.grad_clip), optax.adam(a.lr)); of = txf.init(p_fl)
def vfield(pp, xt, t, s, act, g, gam, gmask): return flow.apply(pp, xt, t, s, act, g, gam, gmask)
def flow_to(pp, s, act, g, gam, gmask, k, t_end, steps): B = s.shape[0]; x = jax.random.normal(k, (B, s_dim)); dt = t_end / steps for i in range(steps): tt = (i / steps) * t_end x = x + dt[:, None] * vfield(pp, x, tt, s, act, g, gam, gmask) x = jnp.clip(x, -a.x_clip, a.x_clip) return x
@jax.jit def flow_step(pf, pbar, o, k, cons_on, s, act, sp, g, gmask, cs, cact, csp, cg, cgmask): B = s.shape[0]; Bc = cs.shape[0]; ks = jax.random.split(k, 12) gam = jax.random.uniform(ks[0], (B,), minval=a.gamma_min, maxval=a.gamma_max) # term1: one-step flow-match to FULL next state s' t1 = jax.random.uniform(ks[1], (B,)); x0 = jax.random.normal(ks[2], (B, s_dim)) Xt1 = (1 - t1)[:, None] * x0 + t1[:, None] * sp def term1(pp): v = vfield(pp, Xt1, t1, s, act, g, gam, gmask) return jnp.mean((1 - gam)[:, None] * (v - (sp - x0)) ** 2) # consistency legs cgam = jax.random.uniform(ks[3], (Bc,), minval=a.gamma_min, maxval=a.gamma_max) cbeta = a.gamma_min + jax.random.uniform(ks[4], (Bc,)) * (cgam - a.gamma_min) cap = pi_mode_from_norm(csp, cg) # a' = pi_g(s',g) (RAW action) t2 = jax.random.uniform(ks[5], (Bc,)) Xt2 = jax.lax.stop_gradient(flow_to(pbar, csp, cap, cg, cbeta, cgmask, ks[6], t2, a.flow_steps)) def huber(r): d = a.huber; absr = jnp.abs(r) return jnp.where(absr < d, 0.5 * r ** 2, d * (absr - 0.5 * d)) def term2(pp): v = vfield(pp, Xt2, t2, cs, cact, cg, cgam, cgmask) vb = jax.lax.stop_gradient(vfield(pbar, Xt2, t2, csp, cap, cg, cbeta, cgmask)) coef = cgam * (1 - cgam) / (1 - cbeta) return jnp.mean(coef[:, None] * huber(v - vb)) Splus = jax.lax.stop_gradient( flow_to(pbar, csp, cap, cg, cbeta, cgmask, ks[7], jnp.ones((Bc,)), a.flow_steps)) aplus = pi_mode_from_norm(Splus, cg) # a+ = pi_g(S+,g) t3 = jax.random.uniform(ks[8], (Bc,)) Xt3 = jax.lax.stop_gradient( flow_to(pbar, Splus, aplus, cg, cgam, cgmask, ks[9], t3, a.flow_steps)) def term3(pp): v = vfield(pp, Xt3, t3, cs, cact, cg, cgam, cgmask) vb = jax.lax.stop_gradient(vfield(pbar, Xt3, t3, Splus, aplus, cg, cgam, cgmask)) coef = cgam * (cgam - cbeta) / (1 - cbeta) return jnp.mean(coef[:, None] * huber(v - vb)) def loss(pp): return term1(pp) + a.cons_weight * cons_on * (term2(pp) + term3(pp)) l, gr = jax.value_and_grad(loss)(pf); u, o = txf.update(gr, o, pf) pf2 = optax.apply_updates(pf, u) pbar2 = jax.tree_util.tree_map(lambda tb, tn: a.ema * tb + (1 - a.ema) * tn, pbar, pf2) return pf2, pbar2, o, l
# GHM reach diagnostic: does goal-conditioned occupancy reach the goal slice? @jax.jit def ghm_reach(pf, sn, gn, key): an = pi_mode_from_norm(sn, gn) B = sn.shape[0]; x = jax.random.normal(key, (B, s_dim)); dt = 1.0 / a.flow_steps gamv = jnp.full((B,), a.gamma_diag); gm = jnp.ones((B,)) for i in range(a.flow_steps): tt = jnp.full((B,), i * dt) x = jnp.clip(x + dt * vfield(pf, x, tt, sn, an, gn, gamv, gm), -a.x_clip, a.x_clip) xt = slice_target_norm(x); gt = slice_target_norm(gn) d2 = jnp.sum((xt - gt) ** 2, -1) return jnp.mean(jnp.exp(-d2 / (x_dim * 2 * a.tau ** 2)))
def save_ckpt(path, pf, pbar): os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, "wb") as f: pickle.dump(dict(p_fl=jax.device_get(pf), p_bar=jax.device_get(pbar), actor_params=jax.device_get(actor_params), s_mu=s_mu, s_sd=s_sd, x_mu=x_mu, x_sd=x_sd, tgt_idx=tgt_idx, env=a.env, s_dim=s_dim, x_dim=x_dim, a_dim=a_dim, actor_hidden=list(actor_def.hidden_dims), args=vars(a)), f)
import tqdm for it in tqdm.trange(1, a.train_steps + 1, desc="tdhc", dynamic_ncols=True): idx = rng.integers(0, N, a.batch); gi = actor_goals_uniform(idx); spi = nxt[idx] ci = rng.integers(0, N, a.cons_batch); cgi = actor_goals_uniform(ci); cspi = nxt[ci] gm = (rng.random(a.batch) >= a.uncond_mask).astype(np.float32) cgm = (rng.random(a.cons_batch) >= a.uncond_mask).astype(np.float32) k = jax.random.fold_in(key, it) cons_on = jnp.float32(min(1.0, max(0.0, (it - a.cons_after) / a.cons_ramp))) p_fl, p_bar, of, lf = flow_step( p_fl, p_bar, of, k, cons_on, jnp.asarray(Sn[idx]), jnp.asarray(A[idx]), jnp.asarray(Sn[spi]), jnp.asarray(Sn[gi]), jnp.asarray(gm), jnp.asarray(Sn[ci]), jnp.asarray(A[ci]), jnp.asarray(Sn[cspi]), jnp.asarray(Sn[cgi]), jnp.asarray(cgm)) if it % 10000 == 0: print(f"[tdhc] {it} loss={float(lf):.4f}", flush=True) if it % a.save_every == 0: ridx = rng.integers(0, N, 512); rgi = actor_goals_uniform(ridx); rr = rng.integers(0, N, 512) reach = float(ghm_reach(p_fl, jnp.asarray(Sn[ridx]), jnp.asarray(Sn[rgi]), jax.random.fold_in(key, 7 * it))) gt = slice_target_norm(jnp.asarray(Sn[rgi])); rt = slice_target_norm(jnp.asarray(Sn[rr])) floor = float(jnp.mean(jnp.exp(-jnp.sum((rt - gt) ** 2, -1) / (x_dim * 2 * a.tau ** 2)))) print(f"[tdhc-diag] {it} reach={reach:.4f} floor={floor:.4f}", flush=True) save_ckpt(a.out.replace(".pkl", f"_step{it}.pkl"), p_fl, p_bar) os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) save_ckpt(a.out, p_fl, p_bar) print(f"[combined] saved {a.out}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184#!/usr/bin/env python3"""GSP planner + env rollout for the COMBINED CompPlan (comp_plan_combined.py):verified OGBench reference GC-BC base + audited td-hc GHM, FULL-STATE goals.
Planner per replan (Lemma 1 + Eq. 6): 1. PROPOSE m subgoal sequences (full states) from the UNCONDITIONAL GHM: z_0=s; for i: a=pi_g(z_{i-1}, g_final_state); z_i ~ m_uncond_{beta_i}(.|z_{i-1},a) 2. SCORE by Lemma-1 composed value through the GOAL-CONDITIONED occupancy toward each subgoal z_k (full state); reward = goal-hit kernel on the cube slice. 3. Execute pi_{z_1} = reference GC-BC toward subgoal z_1 (full state), replan.
--zero_shot forces plan_n=1 -> plain reference GC-BC toward g_final (should match thepaper's ~0.09 cube-triple baseline). --oracle_score isolates Lemma-1 scoring."""import argparseimport osimport pickleimport sys
import numpy as np
IMPLS = os.environ.get("OGBENCH_IMPLS", "/u/zwhong/ogbench_ref/impls")
def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--episodes", type=int, default=50) ap.add_argument("--plan_n", type=int, default=4) ap.add_argument("--plan_m", type=int, default=1024) ap.add_argument("--beta_lo", type=float, default=0.98) ap.add_argument("--beta_hi", type=float, default=0.99) ap.add_argument("--gamma_eval", type=float, default=0.99) ap.add_argument("--replan_every", type=int, default=25) ap.add_argument("--flow_steps", type=int, default=16) ap.add_argument("--tau", type=float, default=0.15) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", default=None) ap.add_argument("--zero_shot", action="store_true") ap.add_argument("--oracle_score", action="store_true") a = ap.parse_args() if a.zero_shot: a.plan_n = 1
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, IMPLS) import jax, jax.numpy as jnp, flax.linen as nn, ogbench from genq import target_extractors from utils.networks import GCActor
C = pickle.load(open(a.ckpt, "rb")) env_id = C["env"]; s_dim = C["s_dim"]; x_dim = C["x_dim"]; a_dim = C["a_dim"] hidden = C["args"]["hidden"]; layers = C["args"]["layers"] s_mu = jnp.asarray(C["s_mu"]); s_sd = jnp.asarray(C["s_sd"]) x_mu = jnp.asarray(C["x_mu"]); x_sd = jnp.asarray(C["x_sd"]) tgt_idx = jnp.asarray(C["tgt_idx"]) p_fl = C["p_fl"]; actor_params = C["actor_params"] actor_hidden = tuple(C["actor_hidden"]) print(f"[comb-eval] env={env_id} n={a.plan_n} m={a.plan_m} beta=[{a.beta_lo},{a.beta_hi}] " f"gamma={a.gamma_eval} replan={a.replan_every} zero_shot={a.zero_shot} " f"oracle={a.oracle_score}", flush=True)
# ---- reference GC-BC actor (RAW obs + RAW full-state goal -> RAW action) ---- actor_def = GCActor(hidden_dims=actor_hidden, action_dim=a_dim, state_dependent_std=False, const_std=True, tanh_squash=False, gc_encoder=None)
@jax.jit def pi_mode(raw_s, raw_g): dist = actor_def.apply({"params": actor_params}, raw_s, raw_g, temperature=0.0) return jnp.clip(dist.mode(), -1.0, 1.0)
def disc_embed(g): return jnp.stack([g, 1.0 - g, -jnp.log(jnp.clip(1.0 - g, 1e-6, 1.0))], -1)
class Flow(nn.Module): @nn.compact def __call__(self, xt, t, s, act, g, gam, gmask): # g full state (s_dim) gcond = jnp.concatenate([g * gmask[:, None], gmask[:, None]], -1) c = jnp.concatenate([s, act, gcond, disc_embed(gam), jnp.sin(t * jnp.pi)[:, None], t[:, None]], -1) for _ in range(2): c = nn.swish(nn.Dense(hidden)(c)) h = xt for _ in range(layers): h = nn.Dense(hidden)(jnp.concatenate([h, xt], -1)) sc = nn.Dense(hidden)(c); sh = nn.Dense(hidden)(c) h = nn.swish(h * (1.0 + sc) + sh) return nn.Dense(s_dim)(h)
flow = Flow()
def s_norm(s): return (s - s_mu) / s_sd def s_unnorm(sn): return sn * s_sd + s_mu def target_of(sn): # normalized full state -> norm cube slice return (s_unnorm(sn)[:, tgt_idx] - x_mu) / x_sd
@jax.jit def flow_sample(sn, an, gn, gam, gmask, key): # gn full state (m,s_dim) B = sn.shape[0]; x = jax.random.normal(key, (B, s_dim)); dt = 1.0 / a.flow_steps gamv = jnp.full((B,), gam) for i in range(a.flow_steps): tt = jnp.full((B,), i * dt) x = x + dt * flow.apply(p_fl, x, tt, sn, an, gn, gamv, gmask) return x
def reward(sn, g_slice_n): xt = target_of(sn); d2 = jnp.sum((xt - g_slice_n[None, :]) ** 2, -1) return jnp.exp(-d2 / (x_dim * 2 * a.tau ** 2))
def lemma_weights(betas, gamma): w = []; prod = 1.0 for k in range(len(betas)): w.append((1 - gamma) / (1 - betas[k]) * prod) prod *= (gamma - betas[k]) / (1 - betas[k]) return np.asarray(w, np.float32)
rng = np.random.default_rng(a.seed); keyc = [jax.random.PRNGKey(a.seed + 5)]
def plan(s_np, g_full_np, g_slice_np): """return z1 (full state, RAW) of best subgoal sequence. g_full = task goal state.""" m, n = a.plan_m, a.plan_n sn0 = s_norm(jnp.asarray(s_np[None])) gfull_n = s_norm(jnp.asarray(g_full_np[None])) # normalized goal state gsl = (jnp.asarray(g_slice_np) - x_mu) / x_sd betas = rng.uniform(a.beta_lo, a.beta_hi, n).astype(np.float32) w = lemma_weights(betas, a.gamma_eval) cur = jnp.repeat(sn0, m, 0) gm0 = jnp.zeros((m,)); gdummy = jnp.zeros((m, s_dim)) gfull_rep = jnp.repeat(gfull_n, m, 0) Z = [] for i in range(n): keyc[0], k = jax.random.split(keyc[0]) a_prop = pi_mode(s_unnorm(cur), s_unnorm(gfull_rep)) # a ~ pi_g(z_{i-1}, g_final) zi = flow_sample(cur, a_prop, gdummy, float(betas[i]), gm0, k) Z.append(zi); cur = zi if a.oracle_score: Qo = reward(Z[-1], gsl); best = int(jnp.argmax(Qo)) return np.asarray(s_unnorm(Z[0][best][None])[0]), float(jnp.max(Qo)) Splus = jnp.repeat(sn0, m, 0); gm1 = jnp.ones((m,)); Q = jnp.zeros((m,)) for k in range(n): zk = Z[k] # subgoal-k full state (m,s_dim) keyc[0], kk = jax.random.split(keyc[0]) a_in = pi_mode(s_unnorm(Splus), s_unnorm(zk)) # a ~ pi_{z_k}(S+_{k-1}) Splus = flow_sample(Splus, a_in, zk, float(betas[k]), gm1, kk) Q = Q + w[k] * reward(Splus, gsl) Q = Q / (1 - a.gamma_eval); best = int(jnp.argmax(Q)) return np.asarray(s_unnorm(Z[0][best][None])[0]), float(jnp.max(Q))
env = ogbench.make_env_and_datasets(env_id, env_only=True) task_infos = getattr(env.unwrapped, "task_infos", None) or env.task_infos n_tasks = len(task_infos); per_task = [] for tid in range(1, n_tasks + 1): succ = 0 for ep in range(a.episodes): obs, info = env.reset(options=dict(task_id=tid, render_goal=False)) goal = np.asarray(info.get("goal"), np.float32) # full goal state g_slice = target_extractors.extract_target(env_id, goal[None])[0] z1 = None; done = False; step = 0; ep_succ = 0 while not done: if step % a.replan_every == 0: z1, _q = plan(np.asarray(obs, np.float32), goal, g_slice.astype(np.float32)) act = np.asarray(pi_mode(jnp.asarray(obs[None].astype(np.float32)), jnp.asarray(z1[None].astype(np.float32))))[0] obs, rew, term, trunc, info = env.step(np.clip(act, -1, 1)) done = term or trunc; step += 1 if info.get("success", 0): ep_succ = 1; break succ += ep_succ sr = succ / a.episodes; per_task.append(sr) print(f"[comb-eval] task {tid}: sr={sr:.3f} ({succ}/{a.episodes})", flush=True) overall = float(np.mean(per_task)) print(f"[comb-eval] {env_id} n={a.plan_n} FINAL sr={overall:.3f} per-task={per_task}", flush=True) if a.out: os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) import json json.dump(dict(env=env_id, plan_n=a.plan_n, plan_m=a.plan_m, gamma_eval=a.gamma_eval, zero_shot=a.zero_shot, oracle_score=a.oracle_score, success_rate=overall, per_task=per_task, method="comp_plan_combined"), open(a.out, "w"), indent=2)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204#!/usr/bin/env python3"""GSP compositional planner + env rollout for the CompPlan reproduction(see comp_plan.py / doc/COMPPLAN_REPRO.md). STATE OGBench cube, render-free.
Planner (Lemma 1 + Eq. 6), per replan: 1. PROPOSE m candidate subgoal sequences (full states) from the UNCONDITIONAL GHM: z_0=s; for i=1..n: a=pi_g(z_{i-1}, g_final); z_i ~ m_uncond_{beta_i}(.|z_{i-1},a) 2. SCORE each by the composed value (Lemma 1), rolling through the GOAL-CONDITIONED occupancy toward each subgoal z_k: S+_0=s; for k=1..n: a=pi_{z_k}(S+_{k-1}); S+_k ~ m^{pi_{z_k}}_{beta_k}(.|S+_{k-1},a) Qhat = (1-gamma)^-1 sum_k w_k r(S+_k; g_final), w_k per Definition 1. 3. Pick the best sequence; execute pi_{z_1} (GC-BC toward subgoal z_1) for `replan_every` steps (receding horizon), then replan.
Baseline: --plan_n 1 reduces to the zero-shot GC-BC policy toward g_final."""import argparseimport osimport pickleimport sys
import numpy as np
def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--episodes", type=int, default=50) ap.add_argument("--plan_n", type=int, default=4) ap.add_argument("--plan_m", type=int, default=1024) ap.add_argument("--beta_lo", type=float, default=0.98) ap.add_argument("--beta_hi", type=float, default=0.99) ap.add_argument("--gamma_eval", type=float, default=0.995) ap.add_argument("--replan_every", type=int, default=25) ap.add_argument("--flow_steps", type=int, default=16) ap.add_argument("--tau", type=float, default=0.15) ap.add_argument("--max_steps", type=int, default=0, help="0=env default") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", default=None) ap.add_argument("--zero_shot", action="store_true", help="force plan_n=1 (GC-BC only)") ap.add_argument("--oracle_score", action="store_true", help="score subgoal sequences by true dist-to-goal (isolate Lemma-1 scoring)") a = ap.parse_args() if a.zero_shot: a.plan_n = 1
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import jax, jax.numpy as jnp, flax.linen as nn, ogbench from genq import target_extractors
with open(a.ckpt, "rb") as f: C = pickle.load(f) env_id = C["env"]; s_dim = C["s_dim"]; x_dim = C["x_dim"]; a_dim = C["a_dim"] hidden = C["args"]["hidden"]; layers = C["args"]["layers"] s_mu = jnp.asarray(C["s_mu"]); s_sd = jnp.asarray(C["s_sd"]) x_mu = jnp.asarray(C["x_mu"]); x_sd = jnp.asarray(C["x_sd"]) a_mu = np.asarray(C["a_mu"]); a_sd = np.asarray(C["a_sd"]) tgt_idx = jnp.asarray(C["tgt_idx"]) p_bc = C["p_bc"]; p_fl = C["p_fl"] print(f"[cp-eval] env={env_id} n={a.plan_n} m={a.plan_m} beta=[{a.beta_lo},{a.beta_hi}] " f"gamma={a.gamma_eval} replan={a.replan_every}", flush=True)
def disc_embed(g): return jnp.stack([g, 1.0 - g, -jnp.log(jnp.clip(1.0 - g, 1e-6, 1.0))], -1)
class GCBC(nn.Module): @nn.compact def __call__(self, s, g): h = jnp.concatenate([s, g], -1) for _ in range(3): h = nn.relu(nn.Dense(hidden)(h)) return jnp.tanh(nn.Dense(a_dim)(h))
class Flow(nn.Module): @nn.compact def __call__(self, xt, t, s, act, g, gam, gmask): gcond = jnp.concatenate([g * gmask[:, None], gmask[:, None]], -1) c = jnp.concatenate([s, act, gcond, disc_embed(gam), jnp.sin(t * jnp.pi)[:, None], t[:, None]], -1) for _ in range(2): c = nn.swish(nn.Dense(hidden)(c)) h = xt for _ in range(layers): h = nn.Dense(hidden)(jnp.concatenate([h, xt], -1)) sc = nn.Dense(hidden)(c); sh = nn.Dense(hidden)(c) h = nn.swish(h * (1.0 + sc) + sh) return nn.Dense(s_dim)(h)
gcbc, flow = GCBC(), Flow()
def s_norm(s): return (s - s_mu) / s_sd def s_unnorm(sn): return sn * s_sd + s_mu def target_of(sn): # normalized full state -> normalized cube-pos slice return (s_unnorm(sn)[:, tgt_idx] - x_mu) / x_sd
@jax.jit def bc(sn, gn): return gcbc.apply(p_bc, sn, gn)
@jax.jit def flow_sample(sn, an, gn, gam, gmask, key): B = sn.shape[0]; x = jax.random.normal(key, (B, s_dim)); dt = 1.0 / a.flow_steps gamv = jnp.full((B,), gam) for i in range(a.flow_steps): tt = jnp.full((B,), i * dt) x = x + dt * flow.apply(p_fl, x, tt, sn, an, gn, gamv, gmask) return x # normalized full-state sample
def reward(sn, g_slice_n): # goal-hit kernel on cube positions xt = target_of(sn) d2 = jnp.sum((xt - g_slice_n[None, :]) ** 2, -1) return jnp.exp(-d2 / (x_dim * 2 * a.tau ** 2))
# Lemma-1 weights for beta schedule def lemma_weights(betas, gamma): w = []; prod = 1.0 for k in range(len(betas)): wk = (1 - gamma) / (1 - betas[k]) * prod w.append(wk) prod *= (gamma - betas[k]) / (1 - betas[k]) return np.asarray(w, np.float32)
rng = np.random.default_rng(a.seed) keyc = [jax.random.PRNGKey(a.seed + 5)]
def plan(s_np, g_slice_np): """return z1 (full state, unnormalized) of the best sequence.""" m, n = a.plan_m, a.plan_n sn0 = s_norm(jnp.asarray(s_np[None])) # (1,s_dim) gsl = (jnp.asarray(g_slice_np) - x_mu) / x_sd # normalized goal slice betas = rng.uniform(a.beta_lo, a.beta_hi, n).astype(np.float32) w = lemma_weights(betas, a.gamma_eval) # (n,) # ---- 1. propose m subgoal sequences from the UNCONDITIONAL GHM ---- cur = jnp.repeat(sn0, m, 0) # (m,s_dim) gm0 = jnp.zeros((m,)) # unconditional gdummy = jnp.zeros((m, x_dim)) gfull = jnp.repeat(gsl[None], m, 0) # goal for pi_g proposal action Z = [] for i in range(n): keyc[0], k = jax.random.split(keyc[0]) a_prop = bc(cur, gfull) # a ~ pi_g(z_{i-1}, g_final) zi = flow_sample(cur, a_prop, gdummy, float(betas[i]), gm0, k) Z.append(zi); cur = zi # (m,s_dim) # ---- 2a. ORACLE scoring: pick the sequence whose LAST subgoal is closest # to the final goal (true distance) -- isolates Lemma-1 scoring from the # proposal+execution. If composition works here but not with Lemma-1, the # scoring is the blocker. ---- if a.oracle_score: Qo = reward(Z[-1], gsl) # last subgoal -> final goal best = int(jnp.argmax(Qo)) return np.asarray(s_unnorm(Z[0][best][None])[0]), float(jnp.max(Qo)) # ---- 2. score each sequence by Lemma-1 composed value ---- Splus = jnp.repeat(sn0, m, 0) # S+_0 = s gm1 = jnp.ones((m,)) Q = jnp.zeros((m,)) for k in range(n): zk = Z[k]; gk = target_of(zk) # subgoal-k goal slice (m,x) keyc[0], kk = jax.random.split(keyc[0]) a_in = bc(Splus, gk) # a ~ pi_{z_k}(S+_{k-1}) Splus = flow_sample(Splus, a_in, gk, float(betas[k]), gm1, kk) r = reward(Splus, gsl) # toward FINAL goal Q = Q + w[k] * r Q = Q / (1 - a.gamma_eval) best = int(jnp.argmax(Q)) z1 = np.asarray(s_unnorm(Z[0][best][None])[0]) return z1, float(jnp.max(Q))
# ---------- env rollout ---------- env = ogbench.make_env_and_datasets(env_id, env_only=True) task_infos = getattr(env.unwrapped, "task_infos", None) or env.task_infos n_tasks = len(task_infos) per_task = [] for tid in range(1, n_tasks + 1): succ = 0 for ep in range(a.episodes): obs, info = env.reset(options=dict(task_id=tid, render_goal=False)) goal = info.get("goal"); g_slice = target_extractors.extract_target(env_id, np.asarray(goal)[None])[0] z1 = None; done = False; step = 0; ep_succ = 0 while not done: if step % a.replan_every == 0: z1, _q = plan(np.asarray(obs, np.float32), g_slice.astype(np.float32)) gk = (target_extractors.extract_target(env_id, z1[None])[0] - np.asarray(C["x_mu"])) / np.asarray(C["x_sd"]) act = np.asarray(bc(s_norm(jnp.asarray(obs[None].astype(np.float32))), jnp.asarray(gk[None].astype(np.float32))))[0] act = np.clip(act * a_sd + a_mu, -1, 1) obs, rew, term, trunc, info = env.step(act) done = term or trunc; step += 1 if info.get("success", 0): ep_succ = 1; break succ += ep_succ sr = succ / a.episodes; per_task.append(sr) print(f"[cp-eval] task {tid}: sr={sr:.3f} ({succ}/{a.episodes})", flush=True) overall = float(np.mean(per_task)) print(f"[cp-eval] {env_id} n={a.plan_n} FINAL sr={overall:.3f} per-task={per_task}", flush=True) if a.out: os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) import json json.dump(dict(env=env_id, plan_n=a.plan_n, plan_m=a.plan_m, gamma_eval=a.gamma_eval, beta=[a.beta_lo, a.beta_hi], success_rate=overall, per_task=per_task, method="comp_plan_gsp"), open(a.out, "w"), indent=2)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224#!/usr/bin/env python3"""CompPlan with our TD-FREE successor measure (Gen-Q / RSM), replacing td-hc.
Same as comp_plan_combined.py (verified frozen reference GC-BC base + full-stateGHM + GSP planner) EXCEPT the occupancy training objective. Instead of the td-hcbootstrap (Eq.5 terms 2/3 vs an EMA target on a consistency sub-batch), we learnthe discounted successor measure by MONTE CARLO, exactly as in the Gen-Q thesis:
gamma ~ U[gmin, gmax] k ~ Geom(1-gamma) # P(k) = (1-gamma) gamma^k, k>=0 S+ = s_{t+k} (realized future FULL state from the offline trajectory) loss = E || v(X_t | s, a, z, gamma) - (S+ - X_0) ||^2 , X_t=(1-t)X_0 + t S+
NO reward, NO bootstrap, NO EMA target, NO consistency legs. The geometric horizonsampling *is* the discount; a single flow-matching loss learns m_gamma(.|s,a,z) forall gamma. Goal z is a hindsight full-state goal (10% masked -> unconditional GHMfor subgoal proposals). Checkpoint format is identical to comp_plan_combined.py, socomp_plan_combined_eval.py evaluates it unchanged (GSP planner is occupancy-agnostic)."""import argparseimport osimport pickleimport sys
import numpy as np
IMPLS = os.environ.get("OGBENCH_IMPLS", "/u/zwhong/ogbench_ref/impls")
def _ends(terminals): term = np.asarray(terminals); ends = np.where(term > 0)[0] end_of = np.zeros(len(term), np.int64); prev = 0 for e in ends: end_of[prev:e + 1] = e + 1; prev = e + 1 if prev < len(term): end_of[prev:] = len(term) return end_of
def build_argparser(): ap = argparse.ArgumentParser() ap.add_argument("--env", required=True) ap.add_argument("--gcbc_ckpt", required=True) ap.add_argument("--gcbc_epoch", type=int, default=1000000) ap.add_argument("--out", required=True) ap.add_argument("--train_steps", type=int, default=2000000) ap.add_argument("--save_every", type=int, default=500000) ap.add_argument("--gamma_diag", type=float, default=0.99) ap.add_argument("--batch", type=int, default=256) ap.add_argument("--lr", type=float, default=1e-4) ap.add_argument("--hidden", type=int, default=512) ap.add_argument("--layers", type=int, default=4) ap.add_argument("--flow_steps", type=int, default=16) ap.add_argument("--gamma_min", type=float, default=0.95) ap.add_argument("--gamma_max", type=float, default=0.997) # long horizon; MC is stable, no bootstrap ap.add_argument("--uncond_mask", type=float, default=0.10) ap.add_argument("--grad_clip", type=float, default=1.0) ap.add_argument("--x_clip", type=float, default=4.0) ap.add_argument("--tau", type=float, default=0.15) ap.add_argument("--kmax", type=int, default=600, help="clamp geometric horizon (episode length)") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--smoke", action="store_true") return ap
def load_reference_actor(s_dim, a_dim, ckpt_glob, epoch): sys.path.insert(0, IMPLS) import jax.numpy as jnp from agents.gcbc import GCBCAgent, get_config from utils.flax_utils import restore_agent from utils.networks import GCActor config = get_config(); config["encoder"] = None agent = GCBCAgent.create(0, np.zeros((1, s_dim), np.float32), np.zeros((1, a_dim), np.float32), config) agent = restore_agent(agent, ckpt_glob, epoch) actor_params = agent.network.params["modules_actor"] actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]), action_dim=a_dim, state_dependent_std=False, const_std=config["const_std"], tanh_squash=False, gc_encoder=None)
def pi_mode(raw_s, raw_g): dist = actor_def.apply({"params": actor_params}, raw_s, raw_g, temperature=0.0) return jnp.clip(dist.mode(), -1.0, 1.0) return actor_def, actor_params, pi_mode
def main(): a = build_argparser().parse_args() if a.smoke: a.train_steps = 60; a.batch = 32; a.flow_steps = 4; a.save_every = 40
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import jax, jax.numpy as jnp, optax, flax.linen as nn from genq import target_extractors print(f"[tdfree] env={a.env} devices={jax.devices()}", flush=True) rng = np.random.default_rng(a.seed)
import ogbench _e, ds, _ = ogbench.make_env_and_datasets(a.env) S = np.asarray(ds["observations"], np.float32) X = target_extractors.extract_target(a.env, S).astype(np.float32) A = np.clip(np.asarray(ds["actions"], np.float32), -1, 1) end_of = _ends(ds["terminals"]) N, s_dim = S.shape; x_dim = X.shape[1]; a_dim = A.shape[1]
probe = min(20000, N); tgt_idx = []; used = set() for j in range(x_dim): diffs = np.abs(S[:probe] - X[:probe, j:j + 1]).sum(0) for c in np.argsort(diffs): if int(c) not in used and diffs[c] < 1e-2: tgt_idx.append(int(c)); used.add(int(c)); break else: raise AssertionError(f"no unique state dim matches reward-slice col {j}") tgt_idx = np.array(tgt_idx, np.int64) assert np.allclose(S[:probe][:, tgt_idx], X[:probe], atol=1e-4) print(f"[tdfree] N={N} s_dim={s_dim} x_dim={x_dim} a_dim={a_dim} tgt_idx={tgt_idx.tolist()}", flush=True)
s_mu, s_sd = S.mean(0), S.std(0) + 1e-6 x_mu, x_sd = X.mean(0), X.std(0) + 1e-6 Sn = ((S - s_mu) / s_sd).astype(np.float32) s_mu_j, s_sd_j = jnp.asarray(s_mu), jnp.asarray(s_sd) x_mu_j, x_sd_j = jnp.asarray(x_mu), jnp.asarray(x_sd) tgt_idx_j = jnp.asarray(tgt_idx)
def unnorm_s(sn): return sn * s_sd_j + s_mu_j def slice_target_norm(sn): return (unnorm_s(sn)[:, tgt_idx_j] - x_mu_j) / x_sd_j
def actor_goals_uniform(t): final = end_of[t] - 1 return np.where(final > t, rng.integers(t + 1, np.maximum(final + 1, t + 2)), t)
def geometric_future(t, gam): """S+ = s_{t+k}, k ~ Geom(1-gam) (>=0), clamped to trajectory end and kmax.""" p = np.clip(1.0 - gam, 1e-4, 1.0) k = rng.geometric(p) - 1 # numpy geometric is >=1 -> shift to >=0 k = np.minimum(k, a.kmax) return np.minimum(t + k, end_of[t] - 1)
actor_def, actor_params, pi_mode = load_reference_actor(s_dim, a_dim, a.gcbc_ckpt, a.gcbc_epoch)
def disc_embed(g): return jnp.stack([g, 1.0 - g, -jnp.log(jnp.clip(1.0 - g, 1e-6, 1.0))], -1)
class Flow(nn.Module): @nn.compact def __call__(self, xt, t, s, act, g, gam, gmask): # g FULL state (s_dim) gcond = jnp.concatenate([g * gmask[:, None], gmask[:, None]], -1) c = jnp.concatenate([s, act, gcond, disc_embed(gam), jnp.sin(t * jnp.pi)[:, None], t[:, None]], -1) for _ in range(2): c = nn.swish(nn.Dense(a.hidden)(c)) h = xt for _ in range(a.layers): h = nn.Dense(a.hidden)(jnp.concatenate([h, xt], -1)) sc = nn.Dense(a.hidden)(c); sh = nn.Dense(a.hidden)(c) h = nn.swish(h * (1.0 + sc) + sh) return nn.Dense(s_dim)(h)
flow = Flow(); key = jax.random.PRNGKey(a.seed) p_fl = flow.init(key, jnp.zeros((1, s_dim)), jnp.zeros((1,)), jnp.zeros((1, s_dim)), jnp.zeros((1, a_dim)), jnp.zeros((1, s_dim)), jnp.full((1,), 0.99), jnp.ones((1,))) txf = optax.chain(optax.clip_by_global_norm(a.grad_clip), optax.adam(a.lr)); of = txf.init(p_fl)
def vfield(pp, xt, t, s, act, g, gam, gmask): return flow.apply(pp, xt, t, s, act, g, gam, gmask)
# ---- TD-FREE Monte-Carlo occupancy loss (single flow-matching term) ---- @jax.jit def mc_step(pf, o, k, s, act, splus, g, gam, gmask): B = s.shape[0]; ks = jax.random.split(k, 2) t = jax.random.uniform(ks[0], (B,)); x0 = jax.random.normal(ks[1], (B, s_dim)) Xt = (1 - t)[:, None] * x0 + t[:, None] * splus def loss(pp): v = vfield(pp, Xt, t, s, act, g, gam, gmask) return jnp.mean((v - (splus - x0)) ** 2) # geometric horizon = the discount l, gr = jax.value_and_grad(loss)(pf); u, o = txf.update(gr, o, pf) return optax.apply_updates(pf, u), o, l
def flow_to_reach(pf, sn, gn, key): an = pi_mode(unnorm_s(sn), unnorm_s(gn)) B = sn.shape[0]; x = jax.random.normal(key, (B, s_dim)); dt = 1.0 / a.flow_steps gamv = jnp.full((B,), a.gamma_diag); gm = jnp.ones((B,)) for i in range(a.flow_steps): tt = jnp.full((B,), i * dt) x = jnp.clip(x + dt * vfield(pf, x, tt, sn, an, gn, gamv, gm), -a.x_clip, a.x_clip) return x reach_jit = jax.jit(flow_to_reach)
def save_ckpt(path, pf): os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, "wb") as f: pickle.dump(dict(p_fl=jax.device_get(pf), p_bar=jax.device_get(pf), actor_params=jax.device_get(actor_params), s_mu=s_mu, s_sd=s_sd, x_mu=x_mu, x_sd=x_sd, tgt_idx=tgt_idx, env=a.env, s_dim=s_dim, x_dim=x_dim, a_dim=a_dim, actor_hidden=list(actor_def.hidden_dims), args=vars(a)), f)
import tqdm for it in tqdm.trange(1, a.train_steps + 1, desc="tdfree", dynamic_ncols=True): idx = rng.integers(0, N, a.batch) gam = rng.uniform(a.gamma_min, a.gamma_max, a.batch).astype(np.float32) spi = geometric_future(idx, gam) # MC geometric-horizon future gi = actor_goals_uniform(idx) # hindsight full-state goal gm = (rng.random(a.batch) >= a.uncond_mask).astype(np.float32) k = jax.random.fold_in(key, it) p_fl, of, lf = mc_step(p_fl, of, k, jnp.asarray(Sn[idx]), jnp.asarray(A[idx]), jnp.asarray(Sn[spi]), jnp.asarray(Sn[gi]), jnp.asarray(gam), jnp.asarray(gm)) if it % 10000 == 0: print(f"[tdfree] {it} loss={float(lf):.4f}", flush=True) if it % a.save_every == 0: ridx = rng.integers(0, N, 512); rgi = actor_goals_uniform(ridx); rr = rng.integers(0, N, 512) xr = reach_jit(p_fl, jnp.asarray(Sn[ridx]), jnp.asarray(Sn[rgi]), jax.random.fold_in(key, 7 * it)) xt = slice_target_norm(xr); gt = slice_target_norm(jnp.asarray(Sn[rgi])) reach = float(jnp.mean(jnp.exp(-jnp.sum((xt - gt) ** 2, -1) / (x_dim * 2 * a.tau ** 2)))) rt = slice_target_norm(jnp.asarray(Sn[rr])) floor = float(jnp.mean(jnp.exp(-jnp.sum((rt - gt) ** 2, -1) / (x_dim * 2 * a.tau ** 2)))) print(f"[tdfree-diag] {it} reach={reach:.4f} floor={floor:.4f}", flush=True) save_ckpt(a.out.replace(".pkl", f"_step{it}.pkl"), p_fl) save_ckpt(a.out, p_fl) print(f"[tdfree] saved {a.out}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304"""Test-time planning with the learned occupancy (owner directive: 'if actor gradientis slow consider using awr or just plan at test time using the learned occupancy').
Deployment-time Q-filter, fully decoupled from training: load a saved actor pickle anda saved occupancy checkpoint, sample K candidate actions from the actor at each envstep, score each with the goal-likelihood read-out gl(s, a_i, g) on the occupancy, andexecute the argmax. No actor gradient through the generative model anywhere — theoccupancy is trained by pure supervised MLE, the actor by whatever produced the pickle(BC / DDPG+BC / AWR), and ALL selection pressure beyond that is applied here with Ksamples at inference. This is the third policy-improvement recipe in CLAUDE.md and themaximally-scalable extraction: training is two supervised fits, improvement is search.
Usage (login node submits; GPUs via bsub): python ogbench_genq/eval_plan.py --env_id puzzle-3x3-play-v0 \ --actor_pkl ogbench_genq/checkpoints/actor_ddpg2_1M_rec_puzzle.pkl \ --occ_npz ogbench_genq/checkpoints/m9_genq_mixb_gmrt_puzzle_3x3_play_v0.genqjax.npz \ --plan_k 1 8 32 --episodes 50 --variant_tag plan_rec_m9"""import argparseimport jsonimport osimport pickleimport sysimport time
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))from ogbench_genq._runner import OGBENCH_IMPLS, _result_dir, _setup_paths
def main(): ap = argparse.ArgumentParser() ap.add_argument("--env_id", default="puzzle-3x3-play-v0") ap.add_argument("--actor_pkl", required=True) ap.add_argument("--occ_npz", default=None, help="occupancy npz (torch-key). Optional when every --plan_k " "is 1: the plain-actor official eval never queries gl " "(needed after the 2026-07-14 checkpoint purge removed " "all saved occupancies)") ap.add_argument("--plan_k", type=int, nargs="+", default=[1, 8, 32]) ap.add_argument("--plan_sigma", type=float, default=0.2, help="candidate proposals = actor mode + sigma * N(0,1) (trust " "region; the mode itself is always candidate 0). The actor's " "own temperature-1 distribution has std 1.0 (const_std), " "which is near-uniform in [-1,1] and lets argmax exploit " "occupancy-model errors — the test-time analogue of the " "one-sided optimism seen at generated midpoints in training.") ap.add_argument("--plan_pess", type=int, default=1, help="min over this many independent gl evaluations per candidate " "(read-out pessimism; 1 = plain mean over orders)") ap.add_argument("--plan_bc", type=float, default=0.0, help="density-penalized scoring: argmax of log gl - plan_bc * " "||a - mode||^2 / 2, mirroring the training objective's BC " "anchor (the buffer the raw argmax lacks; 0 = raw gl)") ap.add_argument("--episodes", type=int, default=50) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--n_orders", type=int, default=16) ap.add_argument("--gamma", type=float, default=0.99) ap.add_argument("--read_gamma", type=float, default=0.0, help="gamma column value for discount-conditioned occupancies " "(0 = occupancy has no gamma feature)") ap.add_argument("--occ_hidden", type=int, default=256) ap.add_argument("--occ_layers", type=int, default=3) ap.add_argument("--occ_time_dim", type=int, default=64) ap.add_argument("--occ_T", type=int, default=100) ap.add_argument("--variant_tag", default="plan") ap.add_argument("--vec", type=int, default=25, help="number of parallel envs for the plain-actor (K=1) " "rollouts. OGBench episodes are fixed-length " "(truncation at max_episode_steps, success never " "early-terminates), so N envs finish in lockstep and " "per-round counting is unbiased. 1 = sequential " "reference loop. K>1 planning always uses the " "sequential path.") a = ap.parse_args()
_setup_paths(OGBENCH_IMPLS) import jax import jax.numpy as jnp from utils.env_utils import make_env_and_datasets from utils.evaluation import evaluate from utils.networks import GCActor import target_extractors from train_genq_jax import cosine_abar, make_model
# the gl Q-filter (plan_k > 1) assumes the all-bit puzzle target; the # plain K=1 official protocol is env-agnostic (any env with an extractor) assert a.env_id.startswith("puzzle") or max(a.plan_k) <= 1, \ "plan_k > 1 (gl Q-filter) assumes the all-bit puzzle target" t0 = time.time() env, train_dataset, _ = make_env_and_datasets(a.env_id, frame_stack=None) obs_dim = train_dataset["observations"].shape[1] a_dim = train_dataset["actions"].shape[1] tgt = lambda o: target_extractors.extract_target(a.env_id, np.asarray(o)).astype(np.float32) n_bits = target_extractors.get_target_dim(a.env_id)
# ---- occupancy from npz (torch-key format, same loader as the warm start) ---- if a.occ_npz is None: assert max(a.plan_k) <= 1, \ "--occ_npz is required for plan_k > 1 (the Q-filter queries gl)" d = np.load(a.occ_npz) if a.occ_npz else None if d is not None: cond_mean = jnp.asarray(d["cond_mean"]) cond_std = jnp.asarray(d["cond_std"]) cond_dim = int(cond_mean.shape[0]) spec_on = cond_dim == obs_dim + a_dim + n_bits + 1 assert spec_on or cond_dim == obs_dim + a_dim + n_bits, \ f"cond_dim {cond_dim} does not match obs+act+bits(+1)" if spec_on: assert a.read_gamma > 0, "discount-conditioned occupancy needs --read_gamma" occ_model = make_model(cond_dim, n_bits, a.occ_hidden, a.occ_layers, a.occ_time_dim) occ_params = occ_model.init(jax.random.PRNGKey(0), jnp.zeros((1, 2 * n_bits)), jnp.zeros((1,)), jnp.zeros((1, cond_dim))) pt = occ_params["params"]
def _ld(name, k2): pt[name]["kernel"] = jnp.asarray(d[f"{k2}.weight"].T) pt[name]["bias"] = jnp.asarray(d[f"{k2}.bias"])
_ld("time_emb_1", "time_emb.1"); _ld("time_emb_3", "time_emb.3") _ld("cond_emb_0", "cond_emb.0"); _ld("x_emb", "x_emb"); _ld("out", "out") for li in range(a.occ_layers): _ld(f"trunk_{li}", f"trunk.{2 * li}") occ_ema = {"params": pt}
# ---- gl read-out (teacher-forced any-order unmasking; identical to # genq_joint) ---- abar = cosine_abar(a.occ_T) kappas = np.arange(n_bits, dtype=np.float64) / n_bits ts_frac = jnp.asarray(np.array( [(1 + int(np.argmin(np.abs(abar - k)))) / a.occ_T for k in kappas], dtype=np.float32)) n_orders = a.n_orders
@jax.jit def gl_q(s, act_b, g, k): parts = [s, act_b, g] if spec_on: parts.append(jnp.full((s.shape[0], 1), a.read_gamma)) c = (jnp.concatenate(parts, -1) - cond_mean) / cond_std B = c.shape[0] cc = jnp.repeat(c, n_orders, axis=0) BO = B * n_orders g01 = jnp.round(jnp.clip(jnp.repeat(g, n_orders, axis=0), 0.0, 1.0)) k, sub = jax.random.split(k) orders = jnp.argsort(jax.random.uniform(sub, (BO, n_bits)), axis=-1) rows = jnp.arange(BO)
def step(carry, i): x, m, logp = carry out = occ_model.apply(occ_ema, jnp.concatenate([x, m], -1), jnp.full((BO,), ts_frac[i]), cc) idx = orders[:, i] logit = out[rows, idx] gbit = g01[rows, idx] logp = logp + gbit * jax.nn.log_sigmoid(logit) + \ (1 - gbit) * jax.nn.log_sigmoid(-logit) x = x.at[rows, idx].set(2.0 * gbit - 1.0) m = m.at[rows, idx].set(0.0) return (x, m, logp), None
init = (jnp.zeros((BO, n_bits)), jnp.ones((BO, n_bits)), jnp.zeros((BO,))) (_, _, logp), _ = jax.lax.scan(step, init, jnp.arange(n_bits)) return jnp.exp(logp).reshape(B, n_orders).mean(-1)
gkey = [jax.random.PRNGKey(a.seed + 999)]
def genq_q_batch(obs_b, goal_obs, acts, _chunk=512): s = np.asarray(obs_b, dtype=np.float32) g = tgt(np.asarray(goal_obs)) acts = np.clip(np.asarray(acts, dtype=np.float32), -1, 1) reps = [] for _ in range(a.plan_pess): outs = [] for i in range(0, len(s), _chunk): gkey[0], sub = jax.random.split(gkey[0]) outs.append(np.asarray(gl_q(jnp.asarray(s[i:i + _chunk]), jnp.asarray(acts[i:i + _chunk]), jnp.asarray(g[i:i + _chunk]), sub))) reps.append(np.concatenate(outs)) return np.stack(reps).min(0)
# ---- actor from pickle (ddpg2 saves {"modules_actor": ...}; r3 saves the full # agent network params, which also contain modules_actor) ---- with open(a.actor_pkl, "rb") as f: blob = pickle.load(f) config = dict(blob["config"]) ap_params = blob["params"]["modules_actor"] actor_def = GCActor(hidden_dims=tuple(config["actor_hidden_dims"]), action_dim=a_dim, state_dependent_std=False, const_std=config["const_std"])
class _PklActor: def sample_actions(self, observations, goals=None, seed=None, temperature=1.0): dist = actor_def.apply({"params": ap_params}, jnp.asarray(observations), jnp.asarray(goals), temperature=max(temperature, 1e-6)) if temperature == 0.0: return np.clip(np.asarray(dist.mode()), -1, 1) return np.clip(np.asarray(dist.sample(seed=seed)), -1, 1)
actor = _PklActor()
class _PlanPolicy: """Trust-region Q-filter: candidates = actor mode + sigma-scaled Gaussian perturbations (mode always included), executed action = gl argmax."""
def __init__(self, k, sigma): self.k, self.sigma = k, sigma self.rng = np.random.default_rng(a.seed + 4242)
def sample_actions(self, observations, goals=None, seed=None, temperature=0.0): mode = actor.sample_actions(observations, goals=goals, temperature=0.0) cand = mode[None] + self.sigma * self.rng.standard_normal( (self.k, a_dim)).astype(np.float32) cand[0] = mode cand = np.clip(cand, -1, 1) obs_k = np.repeat(np.asarray(observations)[None], self.k, axis=0) goal_k = np.repeat(np.asarray(goals)[None], self.k, axis=0) q = genq_q_batch(obs_k, goal_k, cand) score = np.log(np.maximum(q, 1e-9)) if a.plan_bc > 0: score = score - a.plan_bc * ((cand - mode[None]) ** 2).sum(-1) / 2.0 return cand[int(np.argmax(score))]
task_infos = env.unwrapped.task_infos if hasattr(env.unwrapped, "task_infos") \ else env.task_infos n_tasks = len(task_infos)
# ---- vectorized plain-actor rollouts (K=1 official protocol) ---- # OGBench episodes are fixed-length (success is a state predicate; episodes # end only by truncation), so all N sub-envs finish each round in lockstep: # per-round counting introduces no episode-length bias, and success is read # from the final step's info exactly like the sequential reference loop. vec_env = None if max(a.plan_k) <= 1 and a.vec > 1: import gymnasium as gym import ogbench
n_vec = min(a.vec, a.episodes) vec_env = gym.vector.AsyncVectorEnv( [(lambda: ogbench.make_env_and_datasets(a.env_id, env_only=True)) for _ in range(n_vec)])
def vec_eval_task(tid, episodes): succ = [] rounds = -(-episodes // n_vec) for r in range(rounds): obs, infos = vec_env.reset(options=dict(task_id=tid)) goals = np.asarray(infos["goal"], dtype=np.float32) done = np.zeros(n_vec, dtype=bool) last_succ = np.zeros(n_vec, dtype=np.float32) while not done.all(): acts = actor.sample_actions(observations=obs, goals=goals, temperature=0.0) obs, _, term, trunc, infos = vec_env.step(acts) step_done = np.asarray(term) | np.asarray(trunc) if "success" in infos: s = np.asarray(infos["success"], dtype=np.float32) newly = step_done & ~done last_succ[newly] = s[newly] done |= step_done take = n_vec if r < rounds - 1 else episodes - (rounds - 1) * n_vec succ.extend(last_succ[:take].tolist()) return float(np.mean(succ))
results = {} for k in a.plan_k: agent = actor if k <= 1 else _PlanPolicy(k, a.plan_sigma) per = [] for tid in range(1, n_tasks + 1): if k <= 1 and vec_env is not None: per.append(vec_eval_task(tid, a.episodes)) else: # sequential reference loop (planner path / --vec 1 fallback) ei, _, _ = evaluate(agent=agent, env=env, task_id=tid, config=config, num_eval_episodes=a.episodes, num_video_episodes=0, video_frame_skip=3, eval_temperature=0.0, eval_gaussian=None) per.append(float(ei.get("success", 0.0))) sr = float(np.mean(per)) results[f"k{k}"] = {"success_rate": sr, "per_task": per} print(f"[plan] K={k}: sr={sr:.3f} per-task={[round(p, 3) for p in per]}", flush=True) if vec_env is not None: vec_env.close()
out = os.path.join(_result_dir(a.env_id, a.seed), f"eval_plan_{a.variant_tag}.json") json.dump({"method": "eval_plan", "env": a.env_id, "seed": a.seed, "actor_pkl": os.path.basename(a.actor_pkl), "occ_npz": os.path.basename(a.occ_npz) if a.occ_npz else None, "plan_k": a.plan_k, "plan_sigma": a.plan_sigma, "plan_pess": a.plan_pess, "plan_bc": a.plan_bc, "episodes": a.episodes, "n_orders": a.n_orders, "read_gamma": a.read_gamma, "results": results, "wall_clock_sec": round(time.time() - t0, 1)}, open(out, "w"), indent=2) print(f"[plan] -> {out}", flush=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144{ "method": "rsm", "readout": "elbo", "env": "antmaze-giant-navigate-v0", "seed": 0, "alpha": 3.0, "gamma": 0.995, "recursion": "prob", "rec_after": 100000, "rec_beta": 0.98, "rec_guard": "tails", "gamma_spectrum_lo": 0.95, "latent": false, "success_rate": 0.0, "best_sr": 0.04, "per_task": [ 0.0, 0.0, 0.0, 0.0, 0.0 ], "curve": [ [ 25000, 0.0 ], [ 50000, 0.0 ], [ 75000, 0.013333333333333332 ], [ 100000, 0.0 ], [ 125000, 0.0 ], [ 150000, 0.0 ], [ 175000, 0.0 ], [ 200000, 0.0 ], [ 225000, 0.0 ], [ 250000, 0.0 ], [ 275000, 0.0 ], [ 300000, 0.0 ], [ 325000, 0.0 ], [ 350000, 0.013333333333333332 ], [ 375000, 0.013333333333333332 ], [ 400000, 0.0 ], [ 425000, 0.0 ], [ 450000, 0.013333333333333332 ], [ 475000, 0.0 ], [ 500000, 0.0 ], [ 525000, 0.013333333333333332 ], [ 550000, 0.0 ], [ 575000, 0.0 ], [ 600000, 0.04 ], [ 625000, 0.013333333333333332 ], [ 650000, 0.0 ], [ 675000, 0.0 ], [ 700000, 0.0 ], [ 725000, 0.0 ] ], "train_steps": 2000000, "wall_clock_sec": 130091.3, "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/a0sx772c"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148{ "method": "rsm", "readout": "elbo", "env": "antmaze-giant-navigate-v0", "seed": 0, "alpha": 3.0, "gamma": 0.99, "recursion": "prob", "rec_after": 100000, "rec_beta": 0.98, "rec_guard": "tails", "gamma_spectrum_lo": 0.95, "latent": false, "success_rate": 0.013333333333333332, "best_sr": 0.013333333333333332, "per_task": [ 0.0, 0.0, 0.0, 0.0, 0.06666666666666667 ], "curve": [ [ 25000, 0.0 ], [ 50000, 0.0 ], [ 75000, 0.0 ], [ 100000, 0.0 ], [ 125000, 0.0 ], [ 150000, 0.0 ], [ 175000, 0.0 ], [ 200000, 0.013333333333333332 ], [ 225000, 0.0 ], [ 250000, 0.0 ], [ 275000, 0.013333333333333332 ], [ 300000, 0.0 ], [ 325000, 0.013333333333333332 ], [ 350000, 0.0 ], [ 375000, 0.0 ], [ 400000, 0.0 ], [ 425000, 0.0 ], [ 450000, 0.013333333333333332 ], [ 475000, 0.0 ], [ 500000, 0.0 ], [ 525000, 0.013333333333333332 ], [ 550000, 0.0 ], [ 575000, 0.0 ], [ 600000, 0.0 ], [ 625000, 0.0 ], [ 650000, 0.0 ], [ 675000, 0.0 ], [ 700000, 0.0 ], [ 725000, 0.0 ], [ 750000, 0.013333333333333332 ] ], "train_steps": 2000000, "wall_clock_sec": 129364.6, "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/lujhc11a"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "method": "gcbc", "env": "antmaze-large-navigate-v0", "seed": 0, "success_rate": 0.344, "best_sr": 0.3866666666666667, "per_task": [ 0.36, 0.12, 0.7, 0.24, 0.3 ], "curve": [ [ 50000, 0.12 ], [ 100000, 0.2533333333333333 ], [ 150000, 0.26666666666666666 ], [ 200000, 0.29333333333333333 ], [ 250000, 0.3866666666666667 ], [ 300000, 0.27999999999999997 ], [ 300000, 0.344 ] ], "train_steps": 300000, "wall_clock_sec": 4834.3, "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/a3pgu3xx"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "method": "gciql", "env": "antmaze-large-navigate-v0", "seed": 0, "actor_loss": "ddpgbc", "alpha": 0.3, "expectile": 0.9, "success_rate": 0.368, "best_sr": 0.368, "per_task": [ 0.2, 0.3, 0.8, 0.26, 0.28 ], "curve": [ [ 50000, 0.13333333333333333 ], [ 100000, 0.2 ], [ 150000, 0.24 ], [ 200000, 0.22666666666666666 ], [ 250000, 0.31999999999999995 ], [ 300000, 0.29333333333333333 ], [ 350000, 0.22666666666666666 ], [ 400000, 0.3333333333333333 ], [ 450000, 0.30666666666666664 ], [ 500000, 0.36 ], [ 500000, 0.368 ] ], "train_steps": 500000, "wall_clock_sec": 9021.3, "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/fwtpn0oh"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{ "method": "gciql_genq", "env": "antmaze-large-navigate-v0", "seed": 0, "actor_loss": "awr", "alpha": 10.0, "expectile": 0.5, "n_occ": 16, "sigma": 5.0, "ensemble": true, "latent": false, "genq_npz": "m9_genq_antmaze_large_navigate_v0.genqjax.npz", "success_rate": 0.45600000000000007, "best_sr": 0.48, "per_task": [ 0.54, 0.3, 0.76, 0.24, 0.44 ], "curve": [ [ 50000, 0.12 ], [ 100000, 0.2533333333333333 ], [ 150000, 0.2533333333333333 ], [ 200000, 0.48 ], [ 250000, 0.48 ], [ 300000, 0.4133333333333333 ], [ 300000, 0.45600000000000007 ] ], "train_steps": 300000, "wall_clock_sec": 11519.9, "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/qcricwc3"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859{ "method": "gciql_genq_rec", "env": "antmaze-large-navigate-v0", "seed": 0, "actor_loss": "awr", "alpha": 30.0, "expectile": 0.9, "n_occ": 16, "sigma": 5.0, "beta": 0.9, "gamma": 0.99, "stop_prob": 0.09090909090909101, "max_depth": 33, "steps_per_jump": 10, "midpoint_bc_loss": 0.4479009509086609, "genq_npz": "m9_genq_rec_antmaze_large_navigate_v0_b09.genqjax.npz", "success_rate": 0.348, "best_sr": 0.348, "per_task": [ 0.04, 0.2, 0.74, 0.44, 0.32 ], "curve": [ [ 50000, 0.12000000000000002 ], [ 100000, 0.2533333333333333 ], [ 150000, 0.27999999999999997 ], [ 200000, 0.3466666666666666 ], [ 250000, 0.31999999999999995 ], [ 300000, 0.27999999999999997 ], [ 300000, 0.348 ] ], "train_steps": 300000, "wall_clock_sec": 18955.2, "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/6o20ves0"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859{ "method": "gciql_genq_rec", "env": "antmaze-large-navigate-v0", "seed": 0, "actor_loss": "awr", "alpha": 30.0, "expectile": 0.9, "n_occ": 16, "sigma": 5.0, "beta": 0.95, "gamma": 0.99, "stop_prob": 0.1919191919191919, "max_depth": 16, "steps_per_jump": 10, "midpoint_bc_loss": 0.45333102345466614, "genq_npz": "m9_genq_rec_antmaze_large_navigate_v0_b095.genqjax.npz", "success_rate": 0.404, "best_sr": 0.42666666666666664, "per_task": [ 0.46, 0.02, 0.86, 0.3, 0.38 ], "curve": [ [ 50000, 0.13333333333333333 ], [ 100000, 0.17333333333333334 ], [ 150000, 0.27999999999999997 ], [ 200000, 0.31999999999999995 ], [ 250000, 0.3466666666666666 ], [ 300000, 0.42666666666666664 ], [ 300000, 0.404 ] ], "train_steps": 300000, "wall_clock_sec": 10568.9, "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/f2fsodt8"}1234567891011121314151617181920212223242526272829{ "method": "eval_plan", "env": "antmaze-large-navigate-v0", "seed": 0, "actor_pkl": "best_rsm_antmaze_lg_a3_s200k_p427.pkl", "occ_npz": null, "plan_k": [ 1 ], "plan_sigma": 0.2, "plan_pess": 1, "plan_bc": 0.0, "episodes": 50, "n_orders": 16, "read_gamma": 0.0, "results": { "k1": { "success_rate": 0.324, "per_task": [ 0.1, 0.14, 0.66, 0.36, 0.36 ] } }, "wall_clock_sec": 155.3}1234567891011121314151617181920212223242526272829{ "method": "eval_plan", "env": "antmaze-large-navigate-v0", "seed": 1, "actor_pkl": "best_rsm_antmaze_lg_a3_s200k_p427.pkl", "occ_npz": null, "plan_k": [ 1 ], "plan_sigma": 0.2, "plan_pess": 1, "plan_bc": 0.0, "episodes": 50, "n_orders": 16, "read_gamma": 0.0, "results": { "k1": { "success_rate": 0.368, "per_task": [ 0.12, 0.1, 0.7, 0.4, 0.52 ] } }, "wall_clock_sec": 155.0}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194{ "method": "rsm", "readout": "elbo", "env": "antmaze-large-navigate-v0", "seed": 0, "alpha": 3.0, "recursion": "prob", "rec_after": 100000, "rec_beta": 0.98, "rec_guard": "tails", "gamma_spectrum_lo": 0.95, "latent": false, "success_rate": 0.332, "best_sr": 0.44000000000000006, "final_last_step": 0.2919999999999999, "final_best_ckpt": 0.332, "best_ckpt_periodic_sr": 0.44000000000000006, "per_task": [ 0.08, 0.26, 0.72, 0.26, 0.34 ], "curve": [ [ 25000, 0.07999999999999999 ], [ 50000, 0.16 ], [ 75000, 0.36 ], [ 100000, 0.3333333333333333 ], [ 125000, 0.16 ], [ 150000, 0.32 ], [ 175000, 0.26666666666666666 ], [ 200000, 0.30666666666666664 ], [ 225000, 0.2533333333333333 ], [ 250000, 0.30666666666666664 ], [ 275000, 0.30666666666666664 ], [ 300000, 0.3333333333333333 ], [ 325000, 0.44000000000000006 ], [ 350000, 0.2533333333333333 ], [ 375000, 0.36 ], [ 400000, 0.3466666666666666 ], [ 425000, 0.3866666666666666 ], [ 450000, 0.28 ], [ 475000, 0.43999999999999995 ], [ 500000, 0.36 ], [ 525000, 0.27999999999999997 ], [ 550000, 0.3333333333333333 ], [ 575000, 0.3466666666666667 ], [ 600000, 0.30666666666666664 ], [ 625000, 0.31999999999999995 ], [ 650000, 0.27999999999999997 ], [ 675000, 0.26666666666666666 ], [ 700000, 0.31999999999999995 ], [ 725000, 0.2666666666666667 ], [ 750000, 0.30666666666666664 ], [ 775000, 0.30666666666666664 ], [ 800000, 0.3866666666666666 ], [ 825000, 0.2 ], [ 850000, 0.31999999999999995 ], [ 875000, 0.29333333333333333 ], [ 900000, 0.36 ], [ 925000, 0.16 ], [ 950000, 0.3733333333333333 ], [ 975000, 0.26666666666666666 ], [ 1000000, 0.30666666666666664 ], [ 1000000, 0.2919999999999999 ] ], "train_steps": 1000000, "wall_clock_sec": 133762.9, "wandb_url": "https://wandb.ai/improbableai_zwh/gen-q-policy-improvement/runs/jvmp4pt4"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "method": "gcbc", "env": "antmaze-large-navigate-v0", "seed": 1, "success_rate": 0.276, "best_sr": 0.27999999999999997, "per_task": [ 0.04, 0.14, 0.74, 0.28, 0.18 ], "curve": [ [ 50000, 0.18666666666666668 ], [ 100000, 0.2533333333333333 ], [ 150000, 0.27999999999999997 ], [ 200000, 0.26666666666666666 ], [ 250000, 0.24 ], [ 300000, 0.26666666666666666 ], [ 300000, 0.276 ] ], "train_steps": 300000, "wall_clock_sec": 2712.0, "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/htojrxdh"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "method": "gciql", "env": "antmaze-large-navigate-v0", "seed": 1, "actor_loss": "ddpgbc", "alpha": 0.3, "expectile": 0.9, "success_rate": 0.25999999999999995, "best_sr": 0.3466666666666667, "per_task": [ 0.1, 0.12, 0.74, 0.16, 0.18 ], "curve": [ [ 50000, 0.04 ], [ 100000, 0.17333333333333334 ], [ 150000, 0.17333333333333334 ], [ 200000, 0.18666666666666668 ], [ 250000, 0.18666666666666668 ], [ 300000, 0.2533333333333333 ], [ 350000, 0.24 ], [ 400000, 0.3466666666666667 ], [ 450000, 0.29333333333333333 ], [ 500000, 0.27999999999999997 ], [ 500000, 0.25999999999999995 ] ], "train_steps": 500000, "wall_clock_sec": 4703.2, "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/9tz7godd"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{ "method": "gciql_genq", "env": "antmaze-large-navigate-v0", "seed": 1, "actor_loss": "awr", "alpha": 10.0, "expectile": 0.5, "n_occ": 16, "sigma": 5.0, "ensemble": true, "latent": false, "genq_npz": "m9_genq_antmaze_large_navigate_v0.genqjax.npz", "success_rate": 0.38, "best_sr": 0.38, "per_task": [ 0.24, 0.26, 0.86, 0.16, 0.38 ], "curve": [ [ 50000, 0.18666666666666665 ], [ 100000, 0.14666666666666667 ], [ 150000, 0.2533333333333333 ], [ 200000, 0.2533333333333333 ], [ 250000, 0.37333333333333335 ], [ 300000, 0.31999999999999995 ], [ 300000, 0.38 ] ], "train_steps": 300000, "wall_clock_sec": 6016.8, "wandb_url": "https://wandb.ai/ibm-bv/gen-q-policy-improvement/runs/obm35koe"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859{ "method": "gciql_genq_rec", "env": "antmaze-large-navigate-v0", "seed": 1, "actor_loss": "awr", "alpha": 30.0, "expectile": 0.9, "n_occ": 16, "sigma": 5.0, "beta": 0.9, "gamma": 0.99, "stop_prob": 0.09090909090909101, "max_depth": 33, "steps_per_jump": 10, "midpoint_bc_loss": 0.44771894812583923, "genq_npz": "m9_genq_rec_antmaze_large_navigate_v0_b09.genqjax.npz", "success_rate": 0.3, "best_sr": 0.36, "per_task": [ 0.28, 0.08, 0.7, 0.18, 0.26 ], "curve": [ [ 50000, 0.12 ], [ 100000, 0.18666666666666668 ], [ 150000, 0.36 ], [ 200000, 0.30666666666666664 ], [ 250000, 0.29333333333333333 ], [ 300000, 0.29333333333333333 ], [ 300000, 0.3 ] ], "train_steps": 300000, "wall_clock_sec": 18967.7, "wandb_url": "https://wandb.ai/dashora7/gen-q-policy-improvement/runs/bfwdl057"}gen_q_rsm/misc/lewm/train_dinowm.pyAdded+331
gen_q_rsm/misc/results/tdflow_comparison_report.mdAdded+222
gen_q_rsm/misc/results/tdflow_fair_antmaze_dense_hindsight.jsonAdded+219
gen_q_rsm/misc/results/tdflow_fair_antmaze_sparse_hindsight.jsonAdded+219
gen_q_rsm/misc/results/tdflow_fair_pm_fresh_truth_dense_hindsight.jsonAdded
gen_q_rsm/misc/results/tdflow_fair_pm_fresh_truth_sparse_hindsight.jsonAdded
gen_q_rsm/misc/results/tdflow_fair_pointmaze_dense_hindsight.jsonAdded+219
gen_q_rsm/misc/results/tdflow_fair_pointmaze_sparse_hindsight.jsonAdded+219
gen_q_rsm/misc/results/tdflow_gpu_antmaze_dense_hindsight.jsonAdded+189
gen_q_rsm/misc/results/tdflow_gpu_antmaze_sparse_hindsight.jsonAdded+189
gen_q_rsm/misc/results/tdflow_gpu_pointmaze_dense_hindsight.jsonAdded+189
gen_q_rsm/misc/results/tdflow_gpu_pointmaze_sparse_hindsight.jsonAdded+189
gen_q_rsm/ogbench_genq/ABLATION.mdAdded+33
gen_q_rsm/ogbench_genq/DESIGN.mdAdded+185
gen_q_rsm/ogbench_genq/README.mdAdded+307
gen_q_rsm/ogbench_genq/RECIPE.mdAdded+89
gen_q_rsm/ogbench_genq/RESULTS.mdAdded+320
gen_q_rsm/ogbench_genq/VISUAL_COORDFREE_RESULTS.mdAdded+340
gen_q_rsm/ogbench_genq/VISUAL_OCCUPANCY_RECURSION.mdAdded+215
gen_q_rsm/ogbench_genq/VISUAL_RECURSION.mdAdded+166
gen_q_rsm/ogbench_genq/__init__.pyAdded
gen_q_rsm/ogbench_genq/_runner.pyAdded+884
gen_q_rsm/ogbench_genq/bc.pyAdded+17
gen_q_rsm/ogbench_genq/checkpoints/m9_genq_mixb_gmst_puzzle_3x3_play_v0.genqjax.npzAdded+3
gen_q_rsm/ogbench_genq/comp_fixed_eval.shAdded+18
gen_q_rsm/ogbench_genq/comp_horizon_sweep.shAdded+34
gen_q_rsm/ogbench_genq/comp_plan.pyAdded+329
gen_q_rsm/ogbench_genq/comp_plan_combined.pyAdded+299
gen_q_rsm/ogbench_genq/comp_plan_combined_eval.pyAdded+184
gen_q_rsm/ogbench_genq/comp_plan_eval.pyAdded+204
gen_q_rsm/ogbench_genq/comp_plan_tdfree.pyAdded+224
gen_q_rsm/ogbench_genq/eval_plan.pyAdded+304
gen_q_rsm/ogbench_genq/experiments/antmaze-giant-navigate-v0/results/0/rsm_g995_a3.jsonAdded+144
gen_q_rsm/ogbench_genq/experiments/antmaze-giant-navigate-v0/results/0/rsm_g99_a3.jsonAdded+148
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/figures/suc.pngAdded

gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gcbc.jsonAdded+47
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql.jsonAdded+66
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq.jsonAdded+55
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq_rec_b09.jsonAdded+59
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq_rec_b09.json.doneAdded
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq_rec_b095.jsonAdded+59
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/gciql_genq_rec_b095.json.doneAdded
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/official_rsm_antmaze_lg_a3_s200k_p427_read1.jsonAdded+29
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/official_rsm_antmaze_lg_a3_s200k_p427_read2.jsonAdded+29
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/0/rsm_a3.jsonAdded+194
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gcbc.jsonAdded+47
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gciql.jsonAdded+66
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gciql_genq.jsonAdded+55
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gciql_genq_rec_b09.jsonAdded+59
gen_q_rsm/ogbench_genq/experiments/antmaze-large-navigate-v0/results/1/gciql_genq_rec_b09.json.doneAdded