#!/usr/bin/env python3 """Eval-stack oracle replay for OGBench Puzzle. This script runs the same stable_worldmodel.World evaluation stack used by eval_puzzle.py, including dataset goal construction, static goal-info injection, callables, video writing, and success accounting. The only difference is the policy: instead of a world model planner, it replays the ground-truth dataset action at each environment step. """ from __future__ import annotations import faulthandler import json import os import sys from pathlib import Path from typing import Any os.environ.setdefault("MUJOCO_GL", "egl") ROOT_DIR = Path(__file__).resolve().parents[1] if str(ROOT_DIR) not in sys.path: sys.path.insert(0, str(ROOT_DIR)) import hydra import numpy as np import stable_worldmodel as swm import torch from omegaconf import DictConfig, ListConfig, OmegaConf, open_dict from eval import ( _resolve_safe_row_limit, _resolve_world_env_name, evaluate_from_dataset_with_progress, get_dataset, get_episodes_length, ) class DatasetActionReplayPolicy: """Policy that returns preloaded dataset actions one eval step at a time.""" def __init__(self, actions: np.ndarray): actions = np.asarray(actions, dtype=np.float32) if actions.ndim != 3: raise ValueError(f"actions must have shape (num_envs, steps, action_dim), got {actions.shape}") self.actions = actions self.step_idx = 0 def reset(self) -> None: self.step_idx = 0 def get_action(self, infos: dict[str, Any]): action_idx = min(self.step_idx, self.actions.shape[1] - 1) actions = self.actions[:, action_idx] self.step_idx += 1 return actions def _to_numpy(value: Any) -> np.ndarray: if torch.is_tensor(value): return value.detach().cpu().numpy() return np.asarray(value) def _jsonify(value: Any) -> Any: if isinstance(value, dict): return {str(k): _jsonify(v) for k, v in value.items()} if isinstance(value, (list, tuple)): return [_jsonify(v) for v in value] if isinstance(value, np.ndarray): return value.tolist() if isinstance(value, np.generic): return value.item() if torch.is_tensor(value): return value.detach().cpu().tolist() return value def _debug_node(cfg: DictConfig): node = cfg.get("debug", {}) return {} if node is None else node def _debug_get(cfg: DictConfig, key: str, default: Any) -> Any: node = _debug_node(cfg) if isinstance(node, DictConfig): return node.get(key, default) if isinstance(node, dict): return node.get(key, default) return default def _parse_row_indices(value: Any) -> list[int]: if value is None: return [] if isinstance(value, (list, tuple, ListConfig)): return [int(v) for v in value] text = str(value).strip() if not text: return [] if text.startswith("[") and text.endswith("]"): text = text[1:-1] return [int(part.strip()) for part in text.split(",") if part.strip()] def _as_bool(value: Any, default: bool) -> bool: if value is None: return default if isinstance(value, bool): return value text = str(value).strip().lower() if text in {"1", "true", "yes", "y", "on"}: return True if text in {"0", "false", "no", "n", "off"}: return False return default def _dataset_columns(dataset) -> tuple[str, np.ndarray, np.ndarray]: ep_key = "episode_idx" if "episode_idx" in dataset.column_names else "ep_idx" episode_idx = _to_numpy(dataset.get_col_data(ep_key)).reshape(-1) step_idx = _to_numpy(dataset.get_col_data("step_idx")).reshape(-1) if len(episode_idx) != len(step_idx): raise ValueError(f"len({ep_key})={len(episode_idx)} but len(step_idx)={len(step_idx)}") return ep_key, episode_idx, step_idx def _select_rows(dataset, cfg: DictConfig) -> tuple[np.ndarray, np.ndarray, np.ndarray, dict[str, Any]]: ep_key, episode_idx_col, step_idx_col = _dataset_columns(dataset) safe_row_limit, row_counts = _resolve_safe_row_limit(dataset, [ep_key, "step_idx"]) episode_idx_col = episode_idx_col[:safe_row_limit] step_idx_col = step_idx_col[:safe_row_limit] ep_indices, _ = np.unique(episode_idx_col, return_index=True) episode_len = get_episodes_length(dataset, ep_indices) max_start_idx_dict = { int(ep_id): int(episode_len[i] - int(cfg.eval.goal_offset_steps) - 1) for i, ep_id in enumerate(ep_indices) } require_budget_actions = _as_bool(_debug_get(cfg, "require_eval_budget_actions", True), True) if require_budget_actions: budget_max_start = { int(ep_id): int(episode_len[i] - int(cfg.eval.eval_budget) - 1) for i, ep_id in enumerate(ep_indices) } max_start_idx_dict = { ep_id: min(max_start_idx_dict[ep_id], budget_max_start[ep_id]) for ep_id in max_start_idx_dict } max_start_per_row = np.array( [max_start_idx_dict.get(int(ep_id), -1) for ep_id in episode_idx_col], dtype=np.int64, ) valid_mask = step_idx_col <= max_start_per_row valid_indices = np.nonzero(valid_mask)[0].astype(np.int64) explicit_rows = _parse_row_indices(_debug_get(cfg, "start_indices", "")) preferred_candidate_groups: list[np.ndarray] | None = None if explicit_rows: candidate_indices = np.asarray(explicit_rows, dtype=np.int64) bad = candidate_indices[(candidate_indices < 0) | (candidate_indices >= safe_row_limit)] if len(bad): raise ValueError(f"Explicit debug.start_indices outside dataset bounds: {bad.tolist()}") not_valid = candidate_indices[~valid_mask[candidate_indices]] if len(not_valid): raise ValueError( "Explicit debug.start_indices do not have enough future context " f"(goal_offset/eval_budget): {not_valid.tolist()}" ) num_eval = len(candidate_indices) else: num_eval = int(cfg.eval.num_eval) candidate_indices = valid_indices prefer_button_change = _as_bool(_debug_get(cfg, "prefer_button_change", True), True) button_key = str(_debug_get(cfg, "button_key", "button_states")) if prefer_button_change and button_key in dataset.column_names: buttons = _to_numpy(dataset.get_col_data(button_key))[:safe_row_limit] buttons = buttons.reshape(buttons.shape[0], -1) goal_rows = candidate_indices + int(cfg.eval.goal_offset_steps) in_bounds = goal_rows < len(buttons) candidate_indices = candidate_indices[in_bounds] goal_rows = goal_rows[in_bounds] changed_mask = np.any(buttons[goal_rows] != buttons[candidate_indices], axis=1) changed = candidate_indices[changed_mask] unchanged = candidate_indices[~changed_mask] candidate_indices = np.concatenate([changed, unchanged]) if len(changed): preferred_candidate_groups = [changed, unchanged] if len(candidate_indices) < num_eval: raise ValueError(f"Not enough valid oracle starts: requested {num_eval}, found {len(candidate_indices)}") rng = np.random.default_rng(int(cfg.seed)) if explicit_rows: ordered_candidates = candidate_indices elif preferred_candidate_groups is not None: ordered_candidates = np.concatenate( [rng.permutation(group) for group in preferred_candidate_groups if len(group)] ) else: ordered_candidates = rng.permutation(candidate_indices) selected_rows = ordered_candidates[:num_eval].astype(np.int64, copy=False) eval_episodes = episode_idx_col[selected_rows].astype(np.int64) eval_start_idx = step_idx_col[selected_rows].astype(np.int64) info = { "safe_row_limit": int(safe_row_limit), "row_counts": {str(k): int(v) for k, v in row_counts.items()}, "valid_start_count": int(len(valid_indices)), "explicit_start_indices": [int(v) for v in explicit_rows], "require_eval_budget_actions": bool(require_budget_actions), } return selected_rows, eval_episodes, eval_start_idx, info def _resolve_action_row( episode_idx_col: np.ndarray, step_idx_col: np.ndarray, ep_id: int, step: int, expected_row: int, lookup: dict[tuple[int, int], int] | None, ) -> tuple[int, dict[tuple[int, int], int] | None]: if ( 0 <= expected_row < len(episode_idx_col) and int(episode_idx_col[expected_row]) == ep_id and int(step_idx_col[expected_row]) == step ): return int(expected_row), lookup if lookup is None: lookup = {} for row, (row_ep, row_step) in enumerate(zip(episode_idx_col, step_idx_col)): lookup.setdefault((int(row_ep), int(row_step)), int(row)) key = (int(ep_id), int(step)) if key not in lookup: raise KeyError(f"Could not find dataset row for episode={ep_id}, step={step}") return int(lookup[key]), lookup def _build_oracle_actions( dataset, selected_rows: np.ndarray, eval_episodes: np.ndarray, eval_start_idx: np.ndarray, eval_budget: int, action_key: str, ) -> tuple[np.ndarray, np.ndarray]: _, episode_idx_col, step_idx_col = _dataset_columns(dataset) actions_col = _to_numpy(dataset.get_col_data(action_key)) if actions_col.ndim == 1: actions_col = actions_col.reshape(-1, 1) action_dim = int(actions_col.shape[-1]) actions = np.empty((len(selected_rows), eval_budget, action_dim), dtype=np.float32) action_rows = np.empty((len(selected_rows), eval_budget), dtype=np.int64) lookup = None for env_idx, row in enumerate(selected_rows.tolist()): ep_id = int(eval_episodes[env_idx]) start_step = int(eval_start_idx[env_idx]) for t in range(eval_budget): action_row, lookup = _resolve_action_row( episode_idx_col=episode_idx_col, step_idx_col=step_idx_col, ep_id=ep_id, step=start_step + t, expected_row=int(row) + t, lookup=lookup, ) actions[env_idx, t] = actions_col[action_row].astype(np.float32, copy=False) action_rows[env_idx, t] = action_row return actions, action_rows def _button_summary(dataset, selected_rows: np.ndarray, cfg: DictConfig) -> dict[str, Any]: button_key = str(_debug_get(cfg, "button_key", "button_states")) if button_key not in dataset.column_names: return {"has_button_states": False} buttons = _to_numpy(dataset.get_col_data(button_key)) buttons = buttons.reshape(buttons.shape[0], -1) goal_rows = selected_rows + int(cfg.eval.goal_offset_steps) valid = goal_rows < len(buttons) if not np.all(valid): goal_rows = goal_rows[valid] selected_rows = selected_rows[valid] start_buttons = buttons[selected_rows] goal_buttons = buttons[goal_rows] changed = np.any(start_buttons != goal_buttons, axis=1) return { "has_button_states": True, "button_key": button_key, "button_changed_to_goal_count": int(np.count_nonzero(changed)), "button_changed_to_goal_fraction": float(np.mean(changed)) if len(changed) else 0.0, "button_start": start_buttons.tolist(), "button_goal": goal_buttons.tolist(), } def _default_out_dir(cfg: DictConfig) -> Path: debug_out = _debug_get(cfg, "out_dir", "") if debug_out: return Path(os.path.expandvars(str(debug_out))).expanduser() cache_dir = Path(str(cfg.get("cache_dir", "") or swm.data.utils.get_cache_dir())) return cache_dir / "debug_puzzle_eval_stack" @hydra.main(version_base=None, config_path="../config/eval", config_name="puzzle") def main(cfg: DictConfig): faulthandler.enable(all_threads=True) with open_dict(cfg): if "cache_dir" not in cfg: cfg.cache_dir = "" cfg.world.env_name = _resolve_world_env_name(str(cfg.world.env_name)) cfg.world.max_episode_steps = 2 * int(cfg.eval.eval_budget) dataset = get_dataset(cfg, cfg.eval.dataset_name) selected_rows, eval_episodes, eval_start_idx, selection_info = _select_rows(dataset, cfg) with open_dict(cfg): cfg.eval.num_eval = int(len(selected_rows)) cfg.world.num_envs = int(len(selected_rows)) action_key = str(_debug_get(cfg, "action_key", "action")) if action_key not in dataset.column_names: raise KeyError(f"Action key '{action_key}' not found. Available columns: {dataset.column_names}") oracle_actions, action_rows = _build_oracle_actions( dataset=dataset, selected_rows=selected_rows, eval_episodes=eval_episodes, eval_start_idx=eval_start_idx, eval_budget=int(cfg.eval.eval_budget), action_key=action_key, ) world_image_shape = ( int(cfg.world.get("height", cfg.eval.img_size)), int(cfg.world.get("width", cfg.eval.img_size)), ) world = swm.World(**cfg.world, image_shape=world_image_shape) policy = DatasetActionReplayPolicy(oracle_actions) world.set_policy(policy) out_dir = _default_out_dir(cfg) out_dir.mkdir(parents=True, exist_ok=True) print(f"[debug-puzzle] mode=eval-stack-oracle", flush=True) print(f"[debug-puzzle] dataset={cfg.eval.dataset_name}", flush=True) print(f"[debug-puzzle] env={cfg.world.env_name}", flush=True) print(f"[debug-puzzle] selected_rows={selected_rows.tolist()}", flush=True) print(f"[debug-puzzle] episodes={eval_episodes.tolist()}", flush=True) print(f"[debug-puzzle] start_steps={eval_start_idx.tolist()}", flush=True) print(f"[debug-puzzle] oracle_actions_shape={list(oracle_actions.shape)}", flush=True) policy.reset() metrics = evaluate_from_dataset_with_progress( world=world, dataset=dataset, episodes_idx=eval_episodes.tolist(), start_steps=eval_start_idx.tolist(), goal_offset_steps=int(cfg.eval.goal_offset_steps), eval_budget=int(cfg.eval.eval_budget), callables=OmegaConf.to_container(cfg.eval.get("callables"), resolve=True), save_video=bool(cfg.eval.get("save_video", True)), video_path=out_dir, ) summary = { "mode": "eval-stack-oracle", "dataset_name": str(cfg.eval.dataset_name), "env_name": str(cfg.world.env_name), "num_eval": int(len(selected_rows)), "goal_offset_steps": int(cfg.eval.goal_offset_steps), "eval_budget": int(cfg.eval.eval_budget), "selected_rows": selected_rows.tolist(), "episodes": eval_episodes.tolist(), "start_steps": eval_start_idx.tolist(), "selection": selection_info, "oracle_policy": { "action_key": action_key, "actions_shape": list(oracle_actions.shape), "steps_consumed": int(policy.step_idx), "first_action_rows": action_rows[:, : min(5, action_rows.shape[1])].tolist(), "last_action_rows": action_rows[:, max(0, action_rows.shape[1] - 5) :].tolist(), }, "button_summary": _button_summary(dataset, selected_rows, cfg), "metrics": _jsonify(metrics), "video_dir": str(out_dir), } summary_path = out_dir / "eval_stack_oracle_summary.json" summary_path.write_text(json.dumps(summary, indent=2)) print("[debug-puzzle] metrics:", json.dumps(_jsonify(metrics), indent=2), flush=True) print(f"[debug-puzzle] wrote {summary_path}", flush=True) close_fn = getattr(world.envs, "close", None) if callable(close_fn): close_fn() if __name__ == "__main__": main()