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91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#!/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()