Upload 7 files
Browse files- debug/README.md +50 -0
- debug/__init__.py +1 -0
- debug/__pycache__/extract_rollout_figure_frames.cpython-312.pyc +0 -0
- debug/debug_pusht_rollout.py +589 -0
- debug/debug_puzzle.py +414 -0
- debug/extract_rollout_figure_frames.py +288 -0
- debug/visualize_pusht_poincare_hierarchy.py +933 -0
debug/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Debug Tools
|
| 2 |
+
|
| 3 |
+
## Puzzle Eval-Stack Oracle Replay
|
| 4 |
+
|
| 5 |
+
The previous root-level `debug_puzzle.py` now lives in this directory. Run it
|
| 6 |
+
from the repository root:
|
| 7 |
+
|
| 8 |
+
```bash
|
| 9 |
+
MUJOCO_GL=egl python debug/debug_puzzle.py --config-name=puzzle
|
| 10 |
+
```
|
| 11 |
+
|
| 12 |
+
## PushT Multi-Step Latent Rollout Drift
|
| 13 |
+
|
| 14 |
+
`debug_pusht_rollout.py` freezes a trained HyperbolicJEPA checkpoint and replays
|
| 15 |
+
ground-truth PushT actions from the offline dataset. It compares each predicted
|
| 16 |
+
latent against the encoded real future frame for blocks `1...5`.
|
| 17 |
+
|
| 18 |
+
The script writes:
|
| 19 |
+
|
| 20 |
+
- `rollout_drift.png`: Euclidean, tangent-space, and Lorentz error curves.
|
| 21 |
+
- `rollout_drift_summary.json`: run metadata and aggregated metrics.
|
| 22 |
+
- `rollout_drift_summary.csv`: aggregated metrics for plotting or tables.
|
| 23 |
+
- `rollout_drift_per_sequence.csv`: per-window metrics for deeper analysis.
|
| 24 |
+
|
| 25 |
+
Each curve contains two modes:
|
| 26 |
+
|
| 27 |
+
- `autoregressive`: append each predicted latent and continue rollout.
|
| 28 |
+
- `teacher_forced`: restart each one-step prediction from real encoded frames.
|
| 29 |
+
|
| 30 |
+
Interpretation:
|
| 31 |
+
|
| 32 |
+
- Low teacher-forced error with rapidly rising autoregressive error indicates
|
| 33 |
+
compounding rollout drift.
|
| 34 |
+
- High error from block 1 indicates a one-step dynamics or action-protocol
|
| 35 |
+
issue.
|
| 36 |
+
- Similar low curves with poor planning SR point toward candidate sampling or
|
| 37 |
+
goal-cost alignment instead of dynamics quality.
|
| 38 |
+
|
| 39 |
+
Example:
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
MUJOCO_GL=egl python debug/debug_pusht_rollout.py \
|
| 43 |
+
--policy /data_nvme/user/zliu681/le-wm-main/lewm_cache/pusht/hyperbolic_pusht/lewm_hyperbolic_pusht_epoch_10 \
|
| 44 |
+
--dataset pusht/pusht_expert_train \
|
| 45 |
+
--device auto \
|
| 46 |
+
--num-sequences 512 \
|
| 47 |
+
--context-blocks 3 \
|
| 48 |
+
--max-blocks 5 \
|
| 49 |
+
--frameskip 5
|
| 50 |
+
```
|
debug/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Standalone diagnostic tools for LeWM experiments."""
|
debug/__pycache__/extract_rollout_figure_frames.cpython-312.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
debug/debug_pusht_rollout.py
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Measure PushT latent rollout drift under ground-truth action replay.
|
| 3 |
+
|
| 4 |
+
The script freezes a trained HyperbolicJEPA checkpoint, samples real PushT
|
| 5 |
+
trajectory windows, and compares autoregressive latent predictions against
|
| 6 |
+
encoded future frames. Teacher-forced one-step errors are reported alongside
|
| 7 |
+
autoregressive errors to separate local model error from compounding drift.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import csv
|
| 14 |
+
import json
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from types import SimpleNamespace
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import h5py
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
|
| 25 |
+
ROOT_DIR = Path(__file__).resolve().parents[1]
|
| 26 |
+
if str(ROOT_DIR) not in sys.path:
|
| 27 |
+
sys.path.insert(0, str(ROOT_DIR))
|
| 28 |
+
|
| 29 |
+
import stable_worldmodel as swm
|
| 30 |
+
from omegaconf import OmegaConf
|
| 31 |
+
|
| 32 |
+
from eval_hyperbolic import _load_hyperbolic_policy_model
|
| 33 |
+
from utils import resolve_runtime_device
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
IMAGENET_MEAN = torch.tensor([0.485, 0.456, 0.406], dtype=torch.float32).view(1, 3, 1, 1)
|
| 37 |
+
IMAGENET_STD = torch.tensor([0.229, 0.224, 0.225], dtype=torch.float32).view(1, 3, 1, 1)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def parse_args() -> argparse.Namespace:
|
| 41 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 42 |
+
parser.add_argument("--policy", required=True, help="Hyperbolic checkpoint prefix or file.")
|
| 43 |
+
parser.add_argument(
|
| 44 |
+
"--dataset",
|
| 45 |
+
default="pusht/pusht_expert_train",
|
| 46 |
+
help="PushT H5 path or stable-worldmodel cache-relative dataset name.",
|
| 47 |
+
)
|
| 48 |
+
parser.add_argument("--cache-dir", default="", help="Override the stable-worldmodel cache directory.")
|
| 49 |
+
parser.add_argument("--output-dir", default="", help="Output directory below cache when relative.")
|
| 50 |
+
parser.add_argument("--device", default="auto", help="Runtime device: auto, cuda, npu, or cpu.")
|
| 51 |
+
parser.add_argument("--num-sequences", type=int, default=512)
|
| 52 |
+
parser.add_argument("--context-blocks", type=int, default=3)
|
| 53 |
+
parser.add_argument("--max-blocks", type=int, default=5)
|
| 54 |
+
parser.add_argument("--frameskip", type=int, default=5)
|
| 55 |
+
parser.add_argument("--encode-batch-size", type=int, default=128)
|
| 56 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 57 |
+
return parser.parse_args()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def resolve_cache_dir(cache_dir: str) -> Path:
|
| 61 |
+
return Path(cache_dir).expanduser() if cache_dir else Path(swm.data.utils.get_cache_dir())
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def resolve_h5_path(dataset_name: str, cache_dir: Path) -> Path:
|
| 65 |
+
raw = Path(dataset_name).expanduser()
|
| 66 |
+
candidates = [raw]
|
| 67 |
+
if not raw.is_absolute():
|
| 68 |
+
candidates.extend([cache_dir / raw, cache_dir / "pusht" / raw])
|
| 69 |
+
|
| 70 |
+
expanded = []
|
| 71 |
+
for candidate in candidates:
|
| 72 |
+
expanded.append(candidate)
|
| 73 |
+
if candidate.suffix.lower() != ".h5":
|
| 74 |
+
expanded.append(Path(f"{candidate}.h5"))
|
| 75 |
+
|
| 76 |
+
seen = set()
|
| 77 |
+
for candidate in expanded:
|
| 78 |
+
candidate = candidate.resolve()
|
| 79 |
+
if candidate in seen:
|
| 80 |
+
continue
|
| 81 |
+
seen.add(candidate)
|
| 82 |
+
if candidate.is_file():
|
| 83 |
+
return candidate
|
| 84 |
+
tried = ", ".join(str(path) for path in expanded)
|
| 85 |
+
raise FileNotFoundError(f"Could not resolve PushT H5 dataset. Tried: {tried}")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def resolve_output_dir(args: argparse.Namespace, cache_dir: Path) -> Path:
|
| 89 |
+
if args.output_dir:
|
| 90 |
+
output_dir = Path(args.output_dir).expanduser()
|
| 91 |
+
return output_dir if output_dir.is_absolute() else cache_dir / output_dir
|
| 92 |
+
policy_stem = Path(str(args.policy).rstrip("/")).stem
|
| 93 |
+
return cache_dir / "debug" / "pusht_rollout" / policy_stem
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def preprocess_pixels(pixels: np.ndarray, *, image_size: int, device: str) -> torch.Tensor:
|
| 97 |
+
tensor = torch.as_tensor(pixels)
|
| 98 |
+
if tensor.ndim != 4:
|
| 99 |
+
raise ValueError(f"Expected pixels with four dimensions, got shape={tuple(tensor.shape)}.")
|
| 100 |
+
if tensor.shape[-1] in {1, 3, 4}:
|
| 101 |
+
tensor = tensor.permute(0, 3, 1, 2)
|
| 102 |
+
elif tensor.shape[1] not in {1, 3, 4}:
|
| 103 |
+
raise ValueError(f"Could not infer pixel channel axis from shape={tuple(tensor.shape)}.")
|
| 104 |
+
if tensor.shape[1] == 4:
|
| 105 |
+
tensor = tensor[:, :3]
|
| 106 |
+
if tensor.shape[1] == 1:
|
| 107 |
+
tensor = tensor.expand(-1, 3, -1, -1)
|
| 108 |
+
|
| 109 |
+
tensor = tensor.to(device=device, dtype=torch.float32)
|
| 110 |
+
if pixels.dtype == np.uint8 or float(tensor.detach().amax().cpu()) > 1.5:
|
| 111 |
+
tensor = tensor / 255.0
|
| 112 |
+
if tuple(tensor.shape[-2:]) != (image_size, image_size):
|
| 113 |
+
tensor = F.interpolate(
|
| 114 |
+
tensor,
|
| 115 |
+
size=(image_size, image_size),
|
| 116 |
+
mode="bilinear",
|
| 117 |
+
align_corners=False,
|
| 118 |
+
antialias=True,
|
| 119 |
+
)
|
| 120 |
+
return (tensor - IMAGENET_MEAN.to(device)) / IMAGENET_STD.to(device)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def load_metadata(h5_file: h5py.File) -> tuple[np.ndarray, np.ndarray]:
|
| 124 |
+
episode_key = "episode_idx" if "episode_idx" in h5_file else "ep_idx"
|
| 125 |
+
if episode_key not in h5_file:
|
| 126 |
+
raise KeyError("Dataset must contain episode_idx or ep_idx.")
|
| 127 |
+
episode_idx = np.asarray(h5_file[episode_key], dtype=np.int64).reshape(-1)
|
| 128 |
+
|
| 129 |
+
if "step_idx" in h5_file:
|
| 130 |
+
step_idx = np.asarray(h5_file["step_idx"], dtype=np.int64).reshape(-1)
|
| 131 |
+
else:
|
| 132 |
+
step_idx = np.empty(len(episode_idx), dtype=np.int64)
|
| 133 |
+
for episode_id in np.unique(episode_idx):
|
| 134 |
+
rows = np.flatnonzero(episode_idx == episode_id)
|
| 135 |
+
step_idx[rows] = np.arange(len(rows), dtype=np.int64)
|
| 136 |
+
return episode_idx, step_idx
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def build_episode_rows(episode_idx: np.ndarray, step_idx: np.ndarray) -> list[np.ndarray]:
|
| 140 |
+
episodes = []
|
| 141 |
+
for episode_id in np.unique(episode_idx):
|
| 142 |
+
rows = np.flatnonzero(episode_idx == episode_id)
|
| 143 |
+
rows = rows[np.argsort(step_idx[rows])]
|
| 144 |
+
if len(rows) > 1 and not np.all(np.diff(step_idx[rows]) == 1):
|
| 145 |
+
print(f"[debug-pusht] skipping episode={int(episode_id)} with non-contiguous step_idx", flush=True)
|
| 146 |
+
continue
|
| 147 |
+
episodes.append(rows)
|
| 148 |
+
return episodes
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def sample_windows(
|
| 152 |
+
episodes: list[np.ndarray],
|
| 153 |
+
*,
|
| 154 |
+
count: int,
|
| 155 |
+
required_raw_steps: int,
|
| 156 |
+
rng: np.random.Generator,
|
| 157 |
+
) -> np.ndarray:
|
| 158 |
+
eligible = [rows for rows in episodes if len(rows) >= required_raw_steps]
|
| 159 |
+
if not eligible:
|
| 160 |
+
raise ValueError(
|
| 161 |
+
f"No episode contains the required {required_raw_steps} raw steps."
|
| 162 |
+
)
|
| 163 |
+
valid_counts = np.asarray([len(rows) - required_raw_steps + 1 for rows in eligible], dtype=np.int64)
|
| 164 |
+
cumulative = np.cumsum(valid_counts)
|
| 165 |
+
total = int(cumulative[-1])
|
| 166 |
+
if count > total:
|
| 167 |
+
print(
|
| 168 |
+
f"[debug-pusht] requested {count} windows but only {total} are available; using all.",
|
| 169 |
+
flush=True,
|
| 170 |
+
)
|
| 171 |
+
sampled = np.arange(total, dtype=np.int64)
|
| 172 |
+
else:
|
| 173 |
+
sampled = rng.choice(total, size=count, replace=False)
|
| 174 |
+
|
| 175 |
+
window_rows = []
|
| 176 |
+
for flat_index in sampled.tolist():
|
| 177 |
+
episode_pos = int(np.searchsorted(cumulative, flat_index, side="right"))
|
| 178 |
+
previous = int(cumulative[episode_pos - 1]) if episode_pos > 0 else 0
|
| 179 |
+
start = int(flat_index - previous)
|
| 180 |
+
window_rows.append(eligible[episode_pos][start : start + required_raw_steps])
|
| 181 |
+
return np.stack(window_rows)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def normalize_and_chunk_actions(
|
| 185 |
+
raw_actions: np.ndarray,
|
| 186 |
+
window_rows: np.ndarray,
|
| 187 |
+
*,
|
| 188 |
+
num_blocks: int,
|
| 189 |
+
frameskip: int,
|
| 190 |
+
) -> tuple[torch.Tensor, dict[str, Any]]:
|
| 191 |
+
actions = torch.from_numpy(np.asarray(raw_actions, dtype=np.float32).reshape(len(raw_actions), -1))
|
| 192 |
+
valid_actions = actions[~torch.isnan(actions).any(dim=1)]
|
| 193 |
+
action_mean = valid_actions.mean(dim=0, keepdim=True)
|
| 194 |
+
action_std = valid_actions.std(dim=0, keepdim=True).clamp_min(1e-6)
|
| 195 |
+
actions = torch.nan_to_num((actions - action_mean) / action_std, 0.0)
|
| 196 |
+
|
| 197 |
+
block_rows = []
|
| 198 |
+
for block_index in range(num_blocks):
|
| 199 |
+
start = block_index * frameskip
|
| 200 |
+
block_rows.append(window_rows[:, start : start + frameskip])
|
| 201 |
+
block_rows = np.stack(block_rows, axis=1)
|
| 202 |
+
chunks = actions[torch.from_numpy(block_rows)].reshape(len(window_rows), num_blocks, -1)
|
| 203 |
+
stats = {
|
| 204 |
+
"raw_action_dim": int(actions.shape[-1]),
|
| 205 |
+
"chunked_action_dim": int(chunks.shape[-1]),
|
| 206 |
+
"action_mean": action_mean.squeeze(0).tolist(),
|
| 207 |
+
"action_std": action_std.squeeze(0).tolist(),
|
| 208 |
+
}
|
| 209 |
+
return chunks, stats
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def image_size_from_model(model) -> int:
|
| 213 |
+
value = getattr(model.encoder.config, "image_size", 224)
|
| 214 |
+
return int(value[0] if isinstance(value, (list, tuple)) else value)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@torch.inference_mode()
|
| 218 |
+
def encode_rows(
|
| 219 |
+
model,
|
| 220 |
+
h5_file: h5py.File,
|
| 221 |
+
rows: np.ndarray,
|
| 222 |
+
*,
|
| 223 |
+
image_size: int,
|
| 224 |
+
batch_size: int,
|
| 225 |
+
device: str,
|
| 226 |
+
) -> dict[str, torch.Tensor]:
|
| 227 |
+
unique_rows = np.unique(rows.reshape(-1))
|
| 228 |
+
encoded_chunks: dict[str, list[torch.Tensor]] = {
|
| 229 |
+
"emb": [],
|
| 230 |
+
"hyp_tangent": [],
|
| 231 |
+
"hyp_emb": [],
|
| 232 |
+
}
|
| 233 |
+
for start in range(0, len(unique_rows), batch_size):
|
| 234 |
+
end = min(start + batch_size, len(unique_rows))
|
| 235 |
+
selected_rows = unique_rows[start:end]
|
| 236 |
+
pixels = np.asarray(h5_file["pixels"][selected_rows])
|
| 237 |
+
pixel_tensor = preprocess_pixels(pixels, image_size=image_size, device=device)
|
| 238 |
+
encoded = model.encode({"pixels": pixel_tensor.unsqueeze(1)})
|
| 239 |
+
for key in encoded_chunks:
|
| 240 |
+
encoded_chunks[key].append(encoded[key][:, 0].float().cpu())
|
| 241 |
+
print(f"[debug-pusht] encoded rows {end}/{len(unique_rows)}", end="\r", flush=True)
|
| 242 |
+
print("", flush=True)
|
| 243 |
+
|
| 244 |
+
positions = np.searchsorted(unique_rows, rows)
|
| 245 |
+
positions = torch.from_numpy(positions)
|
| 246 |
+
return {
|
| 247 |
+
key: torch.cat(chunks, dim=0)[positions]
|
| 248 |
+
for key, chunks in encoded_chunks.items()
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def summarize(values: torch.Tensor) -> dict[str, float]:
|
| 253 |
+
values = values.detach().float().cpu()
|
| 254 |
+
return {
|
| 255 |
+
"mean": float(values.mean()),
|
| 256 |
+
"std": float(values.std(unbiased=False)),
|
| 257 |
+
"median": float(values.median()),
|
| 258 |
+
"p90": float(torch.quantile(values, 0.90)),
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def metric_row(
|
| 263 |
+
*,
|
| 264 |
+
block: int,
|
| 265 |
+
frameskip: int,
|
| 266 |
+
mode: str,
|
| 267 |
+
euclidean_mse: torch.Tensor,
|
| 268 |
+
tangent_mse: torch.Tensor,
|
| 269 |
+
lorentz_dist: torch.Tensor,
|
| 270 |
+
predicted_euclidean_norm: torch.Tensor,
|
| 271 |
+
target_euclidean_norm: torch.Tensor,
|
| 272 |
+
predicted_tangent_norm: torch.Tensor,
|
| 273 |
+
target_tangent_norm: torch.Tensor,
|
| 274 |
+
) -> dict[str, Any]:
|
| 275 |
+
return {
|
| 276 |
+
"block": int(block),
|
| 277 |
+
"raw_action_steps": int(block * frameskip),
|
| 278 |
+
"mode": mode,
|
| 279 |
+
"euclidean_mse": summarize(euclidean_mse),
|
| 280 |
+
"tangent_mse": summarize(tangent_mse),
|
| 281 |
+
"lorentz_dist": summarize(lorentz_dist),
|
| 282 |
+
"predicted_euclidean_norm": summarize(predicted_euclidean_norm),
|
| 283 |
+
"target_euclidean_norm": summarize(target_euclidean_norm),
|
| 284 |
+
"predicted_tangent_norm": summarize(predicted_tangent_norm),
|
| 285 |
+
"target_tangent_norm": summarize(target_tangent_norm),
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def flatten_summary_row(row: dict[str, Any], *, frameskip: int) -> dict[str, Any]:
|
| 290 |
+
flattened = {
|
| 291 |
+
"block": row["block"],
|
| 292 |
+
"raw_action_steps": int(row["block"]) * int(frameskip),
|
| 293 |
+
"mode": row["mode"],
|
| 294 |
+
}
|
| 295 |
+
for metric_name, stats in row.items():
|
| 296 |
+
if not isinstance(stats, dict):
|
| 297 |
+
continue
|
| 298 |
+
for stat_name, value in stats.items():
|
| 299 |
+
flattened[f"{metric_name}_{stat_name}"] = value
|
| 300 |
+
return flattened
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
@torch.inference_mode()
|
| 304 |
+
def measure_rollout_drift(
|
| 305 |
+
model,
|
| 306 |
+
true_latents: dict[str, torch.Tensor],
|
| 307 |
+
action_chunks: torch.Tensor,
|
| 308 |
+
*,
|
| 309 |
+
context_blocks: int,
|
| 310 |
+
max_blocks: int,
|
| 311 |
+
frameskip: int,
|
| 312 |
+
device: str,
|
| 313 |
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
| 314 |
+
true_emb = true_latents["emb"].to(device)
|
| 315 |
+
true_tangent = true_latents["hyp_tangent"].to(device)
|
| 316 |
+
true_hyp = true_latents["hyp_emb"].to(device)
|
| 317 |
+
action_chunks = action_chunks.to(device)
|
| 318 |
+
action_embeddings = model.action_encoder(action_chunks)
|
| 319 |
+
|
| 320 |
+
autoregressive_context = true_emb[:, :context_blocks].clone()
|
| 321 |
+
summary_rows = []
|
| 322 |
+
sequence_rows = []
|
| 323 |
+
|
| 324 |
+
for step_index in range(max_blocks):
|
| 325 |
+
block = step_index + 1
|
| 326 |
+
act_context = action_embeddings[:, step_index : step_index + context_blocks]
|
| 327 |
+
target_index = context_blocks + step_index
|
| 328 |
+
target_emb = true_emb[:, target_index]
|
| 329 |
+
target_tangent = true_tangent[:, target_index]
|
| 330 |
+
target_hyp = true_hyp[:, target_index]
|
| 331 |
+
|
| 332 |
+
autoregressive_pred = model.predict(
|
| 333 |
+
autoregressive_context[:, -context_blocks:],
|
| 334 |
+
act_context,
|
| 335 |
+
)[:, -1]
|
| 336 |
+
autoregressive_context = torch.cat(
|
| 337 |
+
[autoregressive_context, autoregressive_pred.unsqueeze(1)],
|
| 338 |
+
dim=1,
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
teacher_context = true_emb[:, step_index : step_index + context_blocks]
|
| 342 |
+
teacher_pred = model.predict(teacher_context, act_context)[:, -1]
|
| 343 |
+
|
| 344 |
+
for mode, predicted_emb in (
|
| 345 |
+
("autoregressive", autoregressive_pred),
|
| 346 |
+
("teacher_forced", teacher_pred),
|
| 347 |
+
):
|
| 348 |
+
predicted_tangent, predicted_hyp = model.to_hyperbolic(predicted_emb.unsqueeze(1))
|
| 349 |
+
predicted_tangent = predicted_tangent[:, 0]
|
| 350 |
+
predicted_hyp = predicted_hyp[:, 0]
|
| 351 |
+
euclidean_mse = (predicted_emb - target_emb).square().mean(dim=-1)
|
| 352 |
+
tangent_mse = (predicted_tangent - target_tangent).square().mean(dim=-1)
|
| 353 |
+
lorentz_dist = model.manifold.dist(predicted_hyp, target_hyp)
|
| 354 |
+
predicted_euclidean_norm = predicted_emb.norm(dim=-1)
|
| 355 |
+
target_euclidean_norm = target_emb.norm(dim=-1)
|
| 356 |
+
predicted_tangent_norm = predicted_tangent.norm(dim=-1)
|
| 357 |
+
target_tangent_norm = target_tangent.norm(dim=-1)
|
| 358 |
+
summary_rows.append(
|
| 359 |
+
metric_row(
|
| 360 |
+
block=block,
|
| 361 |
+
frameskip=frameskip,
|
| 362 |
+
mode=mode,
|
| 363 |
+
euclidean_mse=euclidean_mse,
|
| 364 |
+
tangent_mse=tangent_mse,
|
| 365 |
+
lorentz_dist=lorentz_dist,
|
| 366 |
+
predicted_euclidean_norm=predicted_euclidean_norm,
|
| 367 |
+
target_euclidean_norm=target_euclidean_norm,
|
| 368 |
+
predicted_tangent_norm=predicted_tangent_norm,
|
| 369 |
+
target_tangent_norm=target_tangent_norm,
|
| 370 |
+
)
|
| 371 |
+
)
|
| 372 |
+
for sequence_index in range(len(euclidean_mse)):
|
| 373 |
+
sequence_rows.append(
|
| 374 |
+
{
|
| 375 |
+
"sequence": int(sequence_index),
|
| 376 |
+
"block": int(block),
|
| 377 |
+
"raw_action_steps": int(block * frameskip),
|
| 378 |
+
"mode": mode,
|
| 379 |
+
"euclidean_mse": float(euclidean_mse[sequence_index]),
|
| 380 |
+
"tangent_mse": float(tangent_mse[sequence_index]),
|
| 381 |
+
"lorentz_dist": float(lorentz_dist[sequence_index]),
|
| 382 |
+
"predicted_euclidean_norm": float(predicted_euclidean_norm[sequence_index]),
|
| 383 |
+
"target_euclidean_norm": float(target_euclidean_norm[sequence_index]),
|
| 384 |
+
"predicted_tangent_norm": float(predicted_tangent_norm[sequence_index]),
|
| 385 |
+
"target_tangent_norm": float(target_tangent_norm[sequence_index]),
|
| 386 |
+
}
|
| 387 |
+
)
|
| 388 |
+
return summary_rows, sequence_rows
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 392 |
+
if not rows:
|
| 393 |
+
return
|
| 394 |
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
| 395 |
+
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
|
| 396 |
+
writer.writeheader()
|
| 397 |
+
writer.writerows(rows)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def save_plot(path: Path, summary_rows: list[dict[str, Any]], *, frameskip: int) -> None:
|
| 401 |
+
import matplotlib
|
| 402 |
+
|
| 403 |
+
matplotlib.use("Agg")
|
| 404 |
+
import matplotlib.pyplot as plt
|
| 405 |
+
|
| 406 |
+
metrics = (
|
| 407 |
+
("euclidean_mse", "Euclidean latent MSE"),
|
| 408 |
+
("tangent_mse", "Tangent latent MSE"),
|
| 409 |
+
("lorentz_dist", "Lorentz distance"),
|
| 410 |
+
)
|
| 411 |
+
colors = {
|
| 412 |
+
"autoregressive": "#d1495b",
|
| 413 |
+
"teacher_forced": "#00798c",
|
| 414 |
+
}
|
| 415 |
+
fig, axes = plt.subplots(1, 3, figsize=(13.2, 4.1), constrained_layout=True)
|
| 416 |
+
for axis, (metric_key, title) in zip(axes, metrics):
|
| 417 |
+
for mode in ("autoregressive", "teacher_forced"):
|
| 418 |
+
selected = [row for row in summary_rows if row["mode"] == mode]
|
| 419 |
+
x = [int(row["block"]) * int(frameskip) for row in selected]
|
| 420 |
+
y = [row[metric_key]["mean"] for row in selected]
|
| 421 |
+
yerr = [row[metric_key]["std"] for row in selected]
|
| 422 |
+
axis.plot(x, y, marker="o", linewidth=2, color=colors[mode], label=mode.replace("_", " "))
|
| 423 |
+
axis.fill_between(
|
| 424 |
+
x,
|
| 425 |
+
np.asarray(y) - np.asarray(yerr),
|
| 426 |
+
np.asarray(y) + np.asarray(yerr),
|
| 427 |
+
color=colors[mode],
|
| 428 |
+
alpha=0.14,
|
| 429 |
+
)
|
| 430 |
+
axis.set_title(title)
|
| 431 |
+
axis.set_xlabel("oracle action replay steps")
|
| 432 |
+
axis.grid(alpha=0.25)
|
| 433 |
+
axes[0].set_ylabel("error")
|
| 434 |
+
axes[-1].legend(frameon=False)
|
| 435 |
+
fig.savefig(path, dpi=180)
|
| 436 |
+
plt.close(fig)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def json_ready(value: Any) -> Any:
|
| 440 |
+
if isinstance(value, dict):
|
| 441 |
+
return {str(key): json_ready(item) for key, item in value.items()}
|
| 442 |
+
if isinstance(value, (list, tuple)):
|
| 443 |
+
return [json_ready(item) for item in value]
|
| 444 |
+
if isinstance(value, np.ndarray):
|
| 445 |
+
return value.tolist()
|
| 446 |
+
if isinstance(value, np.generic):
|
| 447 |
+
return value.item()
|
| 448 |
+
return value
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def load_model(
|
| 452 |
+
*,
|
| 453 |
+
policy: str,
|
| 454 |
+
cache_dir: Path,
|
| 455 |
+
action_dim: int,
|
| 456 |
+
device: str,
|
| 457 |
+
):
|
| 458 |
+
cfg = OmegaConf.create(
|
| 459 |
+
{
|
| 460 |
+
"cache_dir": str(cache_dir),
|
| 461 |
+
"policy": policy,
|
| 462 |
+
"checkpoint": {
|
| 463 |
+
"force_rebuild": True,
|
| 464 |
+
"strict": True,
|
| 465 |
+
},
|
| 466 |
+
}
|
| 467 |
+
)
|
| 468 |
+
dataset_stub = SimpleNamespace(get_dim=lambda key: action_dim)
|
| 469 |
+
return _load_hyperbolic_policy_model(cfg, dataset_stub, device)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def main() -> None:
|
| 473 |
+
args = parse_args()
|
| 474 |
+
if args.context_blocks < 1 or args.max_blocks < 1 or args.frameskip < 1:
|
| 475 |
+
raise ValueError("context-blocks, max-blocks, and frameskip must be positive.")
|
| 476 |
+
cache_dir = resolve_cache_dir(args.cache_dir)
|
| 477 |
+
h5_path = resolve_h5_path(args.dataset, cache_dir)
|
| 478 |
+
output_dir = resolve_output_dir(args, cache_dir)
|
| 479 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 480 |
+
runtime_device = resolve_runtime_device(args.device)
|
| 481 |
+
rng = np.random.default_rng(args.seed)
|
| 482 |
+
|
| 483 |
+
print(f"[debug-pusht] device={runtime_device}", flush=True)
|
| 484 |
+
print(f"[debug-pusht] dataset={h5_path}", flush=True)
|
| 485 |
+
print(f"[debug-pusht] policy={args.policy}", flush=True)
|
| 486 |
+
|
| 487 |
+
with h5py.File(h5_path, "r") as h5_file:
|
| 488 |
+
if "pixels" not in h5_file or "action" not in h5_file:
|
| 489 |
+
raise KeyError("Dataset must contain pixels and action.")
|
| 490 |
+
episode_idx, step_idx = load_metadata(h5_file)
|
| 491 |
+
episodes = build_episode_rows(episode_idx, step_idx)
|
| 492 |
+
raw_actions = np.asarray(h5_file["action"], dtype=np.float32)
|
| 493 |
+
action_dim = int(raw_actions.reshape(len(raw_actions), -1).shape[-1])
|
| 494 |
+
|
| 495 |
+
model = load_model(
|
| 496 |
+
policy=args.policy,
|
| 497 |
+
cache_dir=cache_dir,
|
| 498 |
+
action_dim=action_dim,
|
| 499 |
+
device=runtime_device,
|
| 500 |
+
)
|
| 501 |
+
image_size = image_size_from_model(model)
|
| 502 |
+
required_raw_steps = (args.context_blocks + args.max_blocks - 1) * args.frameskip + 1
|
| 503 |
+
window_rows = sample_windows(
|
| 504 |
+
episodes,
|
| 505 |
+
count=args.num_sequences,
|
| 506 |
+
required_raw_steps=required_raw_steps,
|
| 507 |
+
rng=rng,
|
| 508 |
+
)
|
| 509 |
+
observation_rows = window_rows[
|
| 510 |
+
:,
|
| 511 |
+
np.arange(args.context_blocks + args.max_blocks) * args.frameskip,
|
| 512 |
+
]
|
| 513 |
+
true_latents = encode_rows(
|
| 514 |
+
model,
|
| 515 |
+
h5_file,
|
| 516 |
+
observation_rows,
|
| 517 |
+
image_size=image_size,
|
| 518 |
+
batch_size=args.encode_batch_size,
|
| 519 |
+
device=runtime_device,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
action_chunks, action_stats = normalize_and_chunk_actions(
|
| 523 |
+
raw_actions,
|
| 524 |
+
window_rows,
|
| 525 |
+
num_blocks=args.context_blocks + args.max_blocks - 1,
|
| 526 |
+
frameskip=args.frameskip,
|
| 527 |
+
)
|
| 528 |
+
expected_action_dim = int(model.action_encoder.patch_embed.in_channels)
|
| 529 |
+
if int(action_chunks.shape[-1]) != expected_action_dim:
|
| 530 |
+
raise ValueError(
|
| 531 |
+
f"Chunked action dim={int(action_chunks.shape[-1])}, but model expects "
|
| 532 |
+
f"{expected_action_dim}. Check --frameskip and the dataset action protocol."
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
summary_rows, sequence_rows = measure_rollout_drift(
|
| 536 |
+
model,
|
| 537 |
+
true_latents,
|
| 538 |
+
action_chunks,
|
| 539 |
+
context_blocks=args.context_blocks,
|
| 540 |
+
max_blocks=args.max_blocks,
|
| 541 |
+
frameskip=args.frameskip,
|
| 542 |
+
device=runtime_device,
|
| 543 |
+
)
|
| 544 |
+
flattened_summary = [
|
| 545 |
+
flatten_summary_row(row, frameskip=args.frameskip)
|
| 546 |
+
for row in summary_rows
|
| 547 |
+
]
|
| 548 |
+
summary = {
|
| 549 |
+
"policy": args.policy,
|
| 550 |
+
"dataset": str(h5_path),
|
| 551 |
+
"device": runtime_device,
|
| 552 |
+
"num_sequences": int(len(window_rows)),
|
| 553 |
+
"context_blocks": int(args.context_blocks),
|
| 554 |
+
"max_blocks": int(args.max_blocks),
|
| 555 |
+
"frameskip": int(args.frameskip),
|
| 556 |
+
"raw_steps_per_max_rollout": int(args.max_blocks * args.frameskip),
|
| 557 |
+
"required_raw_steps_per_window": int(required_raw_steps),
|
| 558 |
+
"image_size": int(image_size),
|
| 559 |
+
"action": action_stats,
|
| 560 |
+
"sampled_start_rows": window_rows[:, 0].tolist(),
|
| 561 |
+
"metrics": summary_rows,
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
summary_path = output_dir / "rollout_drift_summary.json"
|
| 565 |
+
summary_csv_path = output_dir / "rollout_drift_summary.csv"
|
| 566 |
+
sequence_csv_path = output_dir / "rollout_drift_per_sequence.csv"
|
| 567 |
+
plot_path = output_dir / "rollout_drift.png"
|
| 568 |
+
summary_path.write_text(json.dumps(json_ready(summary), indent=2), encoding="utf-8")
|
| 569 |
+
write_csv(summary_csv_path, flattened_summary)
|
| 570 |
+
write_csv(sequence_csv_path, sequence_rows)
|
| 571 |
+
save_plot(plot_path, summary_rows, frameskip=args.frameskip)
|
| 572 |
+
|
| 573 |
+
print(f"[debug-pusht] wrote {summary_path}", flush=True)
|
| 574 |
+
print(f"[debug-pusht] wrote {summary_csv_path}", flush=True)
|
| 575 |
+
print(f"[debug-pusht] wrote {sequence_csv_path}", flush=True)
|
| 576 |
+
print(f"[debug-pusht] wrote {plot_path}", flush=True)
|
| 577 |
+
for row in flattened_summary:
|
| 578 |
+
print(
|
| 579 |
+
f"[debug-pusht] mode={row['mode']:<14} block={row['block']} "
|
| 580 |
+
f"raw_steps={row['raw_action_steps']:>2} "
|
| 581 |
+
f"euc_mse={row['euclidean_mse_mean']:.6f} "
|
| 582 |
+
f"tan_mse={row['tangent_mse_mean']:.6f} "
|
| 583 |
+
f"lorentz={row['lorentz_dist_mean']:.6f}",
|
| 584 |
+
flush=True,
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
if __name__ == "__main__":
|
| 589 |
+
main()
|
debug/debug_puzzle.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Eval-stack oracle replay for OGBench Puzzle.
|
| 3 |
+
|
| 4 |
+
This script runs the same stable_worldmodel.World evaluation stack used by
|
| 5 |
+
eval_puzzle.py, including dataset goal construction, static goal-info
|
| 6 |
+
injection, callables, video writing, and success accounting. The only
|
| 7 |
+
difference is the policy: instead of a world model planner, it replays the
|
| 8 |
+
ground-truth dataset action at each environment step.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import faulthandler
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
os.environ.setdefault("MUJOCO_GL", "egl")
|
| 21 |
+
|
| 22 |
+
ROOT_DIR = Path(__file__).resolve().parents[1]
|
| 23 |
+
if str(ROOT_DIR) not in sys.path:
|
| 24 |
+
sys.path.insert(0, str(ROOT_DIR))
|
| 25 |
+
|
| 26 |
+
import hydra
|
| 27 |
+
import numpy as np
|
| 28 |
+
import stable_worldmodel as swm
|
| 29 |
+
import torch
|
| 30 |
+
from omegaconf import DictConfig, ListConfig, OmegaConf, open_dict
|
| 31 |
+
|
| 32 |
+
from eval import (
|
| 33 |
+
_resolve_safe_row_limit,
|
| 34 |
+
_resolve_world_env_name,
|
| 35 |
+
evaluate_from_dataset_with_progress,
|
| 36 |
+
get_dataset,
|
| 37 |
+
get_episodes_length,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class DatasetActionReplayPolicy:
|
| 42 |
+
"""Policy that returns preloaded dataset actions one eval step at a time."""
|
| 43 |
+
|
| 44 |
+
def __init__(self, actions: np.ndarray):
|
| 45 |
+
actions = np.asarray(actions, dtype=np.float32)
|
| 46 |
+
if actions.ndim != 3:
|
| 47 |
+
raise ValueError(f"actions must have shape (num_envs, steps, action_dim), got {actions.shape}")
|
| 48 |
+
self.actions = actions
|
| 49 |
+
self.step_idx = 0
|
| 50 |
+
|
| 51 |
+
def reset(self) -> None:
|
| 52 |
+
self.step_idx = 0
|
| 53 |
+
|
| 54 |
+
def get_action(self, infos: dict[str, Any]):
|
| 55 |
+
action_idx = min(self.step_idx, self.actions.shape[1] - 1)
|
| 56 |
+
actions = self.actions[:, action_idx]
|
| 57 |
+
self.step_idx += 1
|
| 58 |
+
return actions
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _to_numpy(value: Any) -> np.ndarray:
|
| 62 |
+
if torch.is_tensor(value):
|
| 63 |
+
return value.detach().cpu().numpy()
|
| 64 |
+
return np.asarray(value)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _jsonify(value: Any) -> Any:
|
| 68 |
+
if isinstance(value, dict):
|
| 69 |
+
return {str(k): _jsonify(v) for k, v in value.items()}
|
| 70 |
+
if isinstance(value, (list, tuple)):
|
| 71 |
+
return [_jsonify(v) for v in value]
|
| 72 |
+
if isinstance(value, np.ndarray):
|
| 73 |
+
return value.tolist()
|
| 74 |
+
if isinstance(value, np.generic):
|
| 75 |
+
return value.item()
|
| 76 |
+
if torch.is_tensor(value):
|
| 77 |
+
return value.detach().cpu().tolist()
|
| 78 |
+
return value
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _debug_node(cfg: DictConfig):
|
| 82 |
+
node = cfg.get("debug", {})
|
| 83 |
+
return {} if node is None else node
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _debug_get(cfg: DictConfig, key: str, default: Any) -> Any:
|
| 87 |
+
node = _debug_node(cfg)
|
| 88 |
+
if isinstance(node, DictConfig):
|
| 89 |
+
return node.get(key, default)
|
| 90 |
+
if isinstance(node, dict):
|
| 91 |
+
return node.get(key, default)
|
| 92 |
+
return default
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _parse_row_indices(value: Any) -> list[int]:
|
| 96 |
+
if value is None:
|
| 97 |
+
return []
|
| 98 |
+
if isinstance(value, (list, tuple, ListConfig)):
|
| 99 |
+
return [int(v) for v in value]
|
| 100 |
+
|
| 101 |
+
text = str(value).strip()
|
| 102 |
+
if not text:
|
| 103 |
+
return []
|
| 104 |
+
if text.startswith("[") and text.endswith("]"):
|
| 105 |
+
text = text[1:-1]
|
| 106 |
+
return [int(part.strip()) for part in text.split(",") if part.strip()]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _as_bool(value: Any, default: bool) -> bool:
|
| 110 |
+
if value is None:
|
| 111 |
+
return default
|
| 112 |
+
if isinstance(value, bool):
|
| 113 |
+
return value
|
| 114 |
+
text = str(value).strip().lower()
|
| 115 |
+
if text in {"1", "true", "yes", "y", "on"}:
|
| 116 |
+
return True
|
| 117 |
+
if text in {"0", "false", "no", "n", "off"}:
|
| 118 |
+
return False
|
| 119 |
+
return default
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _dataset_columns(dataset) -> tuple[str, np.ndarray, np.ndarray]:
|
| 123 |
+
ep_key = "episode_idx" if "episode_idx" in dataset.column_names else "ep_idx"
|
| 124 |
+
episode_idx = _to_numpy(dataset.get_col_data(ep_key)).reshape(-1)
|
| 125 |
+
step_idx = _to_numpy(dataset.get_col_data("step_idx")).reshape(-1)
|
| 126 |
+
if len(episode_idx) != len(step_idx):
|
| 127 |
+
raise ValueError(f"len({ep_key})={len(episode_idx)} but len(step_idx)={len(step_idx)}")
|
| 128 |
+
return ep_key, episode_idx, step_idx
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _select_rows(dataset, cfg: DictConfig) -> tuple[np.ndarray, np.ndarray, np.ndarray, dict[str, Any]]:
|
| 132 |
+
ep_key, episode_idx_col, step_idx_col = _dataset_columns(dataset)
|
| 133 |
+
safe_row_limit, row_counts = _resolve_safe_row_limit(dataset, [ep_key, "step_idx"])
|
| 134 |
+
episode_idx_col = episode_idx_col[:safe_row_limit]
|
| 135 |
+
step_idx_col = step_idx_col[:safe_row_limit]
|
| 136 |
+
|
| 137 |
+
ep_indices, _ = np.unique(episode_idx_col, return_index=True)
|
| 138 |
+
episode_len = get_episodes_length(dataset, ep_indices)
|
| 139 |
+
max_start_idx_dict = {
|
| 140 |
+
int(ep_id): int(episode_len[i] - int(cfg.eval.goal_offset_steps) - 1)
|
| 141 |
+
for i, ep_id in enumerate(ep_indices)
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
require_budget_actions = _as_bool(_debug_get(cfg, "require_eval_budget_actions", True), True)
|
| 145 |
+
if require_budget_actions:
|
| 146 |
+
budget_max_start = {
|
| 147 |
+
int(ep_id): int(episode_len[i] - int(cfg.eval.eval_budget) - 1)
|
| 148 |
+
for i, ep_id in enumerate(ep_indices)
|
| 149 |
+
}
|
| 150 |
+
max_start_idx_dict = {
|
| 151 |
+
ep_id: min(max_start_idx_dict[ep_id], budget_max_start[ep_id])
|
| 152 |
+
for ep_id in max_start_idx_dict
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
max_start_per_row = np.array(
|
| 156 |
+
[max_start_idx_dict.get(int(ep_id), -1) for ep_id in episode_idx_col],
|
| 157 |
+
dtype=np.int64,
|
| 158 |
+
)
|
| 159 |
+
valid_mask = step_idx_col <= max_start_per_row
|
| 160 |
+
valid_indices = np.nonzero(valid_mask)[0].astype(np.int64)
|
| 161 |
+
|
| 162 |
+
explicit_rows = _parse_row_indices(_debug_get(cfg, "start_indices", ""))
|
| 163 |
+
preferred_candidate_groups: list[np.ndarray] | None = None
|
| 164 |
+
if explicit_rows:
|
| 165 |
+
candidate_indices = np.asarray(explicit_rows, dtype=np.int64)
|
| 166 |
+
bad = candidate_indices[(candidate_indices < 0) | (candidate_indices >= safe_row_limit)]
|
| 167 |
+
if len(bad):
|
| 168 |
+
raise ValueError(f"Explicit debug.start_indices outside dataset bounds: {bad.tolist()}")
|
| 169 |
+
not_valid = candidate_indices[~valid_mask[candidate_indices]]
|
| 170 |
+
if len(not_valid):
|
| 171 |
+
raise ValueError(
|
| 172 |
+
"Explicit debug.start_indices do not have enough future context "
|
| 173 |
+
f"(goal_offset/eval_budget): {not_valid.tolist()}"
|
| 174 |
+
)
|
| 175 |
+
num_eval = len(candidate_indices)
|
| 176 |
+
else:
|
| 177 |
+
num_eval = int(cfg.eval.num_eval)
|
| 178 |
+
candidate_indices = valid_indices
|
| 179 |
+
|
| 180 |
+
prefer_button_change = _as_bool(_debug_get(cfg, "prefer_button_change", True), True)
|
| 181 |
+
button_key = str(_debug_get(cfg, "button_key", "button_states"))
|
| 182 |
+
if prefer_button_change and button_key in dataset.column_names:
|
| 183 |
+
buttons = _to_numpy(dataset.get_col_data(button_key))[:safe_row_limit]
|
| 184 |
+
buttons = buttons.reshape(buttons.shape[0], -1)
|
| 185 |
+
goal_rows = candidate_indices + int(cfg.eval.goal_offset_steps)
|
| 186 |
+
in_bounds = goal_rows < len(buttons)
|
| 187 |
+
candidate_indices = candidate_indices[in_bounds]
|
| 188 |
+
goal_rows = goal_rows[in_bounds]
|
| 189 |
+
changed_mask = np.any(buttons[goal_rows] != buttons[candidate_indices], axis=1)
|
| 190 |
+
changed = candidate_indices[changed_mask]
|
| 191 |
+
unchanged = candidate_indices[~changed_mask]
|
| 192 |
+
candidate_indices = np.concatenate([changed, unchanged])
|
| 193 |
+
if len(changed):
|
| 194 |
+
preferred_candidate_groups = [changed, unchanged]
|
| 195 |
+
|
| 196 |
+
if len(candidate_indices) < num_eval:
|
| 197 |
+
raise ValueError(f"Not enough valid oracle starts: requested {num_eval}, found {len(candidate_indices)}")
|
| 198 |
+
|
| 199 |
+
rng = np.random.default_rng(int(cfg.seed))
|
| 200 |
+
if explicit_rows:
|
| 201 |
+
ordered_candidates = candidate_indices
|
| 202 |
+
elif preferred_candidate_groups is not None:
|
| 203 |
+
ordered_candidates = np.concatenate(
|
| 204 |
+
[rng.permutation(group) for group in preferred_candidate_groups if len(group)]
|
| 205 |
+
)
|
| 206 |
+
else:
|
| 207 |
+
ordered_candidates = rng.permutation(candidate_indices)
|
| 208 |
+
|
| 209 |
+
selected_rows = ordered_candidates[:num_eval].astype(np.int64, copy=False)
|
| 210 |
+
eval_episodes = episode_idx_col[selected_rows].astype(np.int64)
|
| 211 |
+
eval_start_idx = step_idx_col[selected_rows].astype(np.int64)
|
| 212 |
+
|
| 213 |
+
info = {
|
| 214 |
+
"safe_row_limit": int(safe_row_limit),
|
| 215 |
+
"row_counts": {str(k): int(v) for k, v in row_counts.items()},
|
| 216 |
+
"valid_start_count": int(len(valid_indices)),
|
| 217 |
+
"explicit_start_indices": [int(v) for v in explicit_rows],
|
| 218 |
+
"require_eval_budget_actions": bool(require_budget_actions),
|
| 219 |
+
}
|
| 220 |
+
return selected_rows, eval_episodes, eval_start_idx, info
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _resolve_action_row(
|
| 224 |
+
episode_idx_col: np.ndarray,
|
| 225 |
+
step_idx_col: np.ndarray,
|
| 226 |
+
ep_id: int,
|
| 227 |
+
step: int,
|
| 228 |
+
expected_row: int,
|
| 229 |
+
lookup: dict[tuple[int, int], int] | None,
|
| 230 |
+
) -> tuple[int, dict[tuple[int, int], int] | None]:
|
| 231 |
+
if (
|
| 232 |
+
0 <= expected_row < len(episode_idx_col)
|
| 233 |
+
and int(episode_idx_col[expected_row]) == ep_id
|
| 234 |
+
and int(step_idx_col[expected_row]) == step
|
| 235 |
+
):
|
| 236 |
+
return int(expected_row), lookup
|
| 237 |
+
|
| 238 |
+
if lookup is None:
|
| 239 |
+
lookup = {}
|
| 240 |
+
for row, (row_ep, row_step) in enumerate(zip(episode_idx_col, step_idx_col)):
|
| 241 |
+
lookup.setdefault((int(row_ep), int(row_step)), int(row))
|
| 242 |
+
|
| 243 |
+
key = (int(ep_id), int(step))
|
| 244 |
+
if key not in lookup:
|
| 245 |
+
raise KeyError(f"Could not find dataset row for episode={ep_id}, step={step}")
|
| 246 |
+
return int(lookup[key]), lookup
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _build_oracle_actions(
|
| 250 |
+
dataset,
|
| 251 |
+
selected_rows: np.ndarray,
|
| 252 |
+
eval_episodes: np.ndarray,
|
| 253 |
+
eval_start_idx: np.ndarray,
|
| 254 |
+
eval_budget: int,
|
| 255 |
+
action_key: str,
|
| 256 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 257 |
+
_, episode_idx_col, step_idx_col = _dataset_columns(dataset)
|
| 258 |
+
actions_col = _to_numpy(dataset.get_col_data(action_key))
|
| 259 |
+
if actions_col.ndim == 1:
|
| 260 |
+
actions_col = actions_col.reshape(-1, 1)
|
| 261 |
+
|
| 262 |
+
action_dim = int(actions_col.shape[-1])
|
| 263 |
+
actions = np.empty((len(selected_rows), eval_budget, action_dim), dtype=np.float32)
|
| 264 |
+
action_rows = np.empty((len(selected_rows), eval_budget), dtype=np.int64)
|
| 265 |
+
|
| 266 |
+
lookup = None
|
| 267 |
+
for env_idx, row in enumerate(selected_rows.tolist()):
|
| 268 |
+
ep_id = int(eval_episodes[env_idx])
|
| 269 |
+
start_step = int(eval_start_idx[env_idx])
|
| 270 |
+
for t in range(eval_budget):
|
| 271 |
+
action_row, lookup = _resolve_action_row(
|
| 272 |
+
episode_idx_col=episode_idx_col,
|
| 273 |
+
step_idx_col=step_idx_col,
|
| 274 |
+
ep_id=ep_id,
|
| 275 |
+
step=start_step + t,
|
| 276 |
+
expected_row=int(row) + t,
|
| 277 |
+
lookup=lookup,
|
| 278 |
+
)
|
| 279 |
+
actions[env_idx, t] = actions_col[action_row].astype(np.float32, copy=False)
|
| 280 |
+
action_rows[env_idx, t] = action_row
|
| 281 |
+
|
| 282 |
+
return actions, action_rows
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _button_summary(dataset, selected_rows: np.ndarray, cfg: DictConfig) -> dict[str, Any]:
|
| 286 |
+
button_key = str(_debug_get(cfg, "button_key", "button_states"))
|
| 287 |
+
if button_key not in dataset.column_names:
|
| 288 |
+
return {"has_button_states": False}
|
| 289 |
+
|
| 290 |
+
buttons = _to_numpy(dataset.get_col_data(button_key))
|
| 291 |
+
buttons = buttons.reshape(buttons.shape[0], -1)
|
| 292 |
+
goal_rows = selected_rows + int(cfg.eval.goal_offset_steps)
|
| 293 |
+
valid = goal_rows < len(buttons)
|
| 294 |
+
if not np.all(valid):
|
| 295 |
+
goal_rows = goal_rows[valid]
|
| 296 |
+
selected_rows = selected_rows[valid]
|
| 297 |
+
start_buttons = buttons[selected_rows]
|
| 298 |
+
goal_buttons = buttons[goal_rows]
|
| 299 |
+
changed = np.any(start_buttons != goal_buttons, axis=1)
|
| 300 |
+
return {
|
| 301 |
+
"has_button_states": True,
|
| 302 |
+
"button_key": button_key,
|
| 303 |
+
"button_changed_to_goal_count": int(np.count_nonzero(changed)),
|
| 304 |
+
"button_changed_to_goal_fraction": float(np.mean(changed)) if len(changed) else 0.0,
|
| 305 |
+
"button_start": start_buttons.tolist(),
|
| 306 |
+
"button_goal": goal_buttons.tolist(),
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _default_out_dir(cfg: DictConfig) -> Path:
|
| 311 |
+
debug_out = _debug_get(cfg, "out_dir", "")
|
| 312 |
+
if debug_out:
|
| 313 |
+
return Path(os.path.expandvars(str(debug_out))).expanduser()
|
| 314 |
+
cache_dir = Path(str(cfg.get("cache_dir", "") or swm.data.utils.get_cache_dir()))
|
| 315 |
+
return cache_dir / "debug_puzzle_eval_stack"
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@hydra.main(version_base=None, config_path="../config/eval", config_name="puzzle")
|
| 319 |
+
def main(cfg: DictConfig):
|
| 320 |
+
faulthandler.enable(all_threads=True)
|
| 321 |
+
|
| 322 |
+
with open_dict(cfg):
|
| 323 |
+
if "cache_dir" not in cfg:
|
| 324 |
+
cfg.cache_dir = ""
|
| 325 |
+
cfg.world.env_name = _resolve_world_env_name(str(cfg.world.env_name))
|
| 326 |
+
cfg.world.max_episode_steps = 2 * int(cfg.eval.eval_budget)
|
| 327 |
+
|
| 328 |
+
dataset = get_dataset(cfg, cfg.eval.dataset_name)
|
| 329 |
+
selected_rows, eval_episodes, eval_start_idx, selection_info = _select_rows(dataset, cfg)
|
| 330 |
+
|
| 331 |
+
with open_dict(cfg):
|
| 332 |
+
cfg.eval.num_eval = int(len(selected_rows))
|
| 333 |
+
cfg.world.num_envs = int(len(selected_rows))
|
| 334 |
+
|
| 335 |
+
action_key = str(_debug_get(cfg, "action_key", "action"))
|
| 336 |
+
if action_key not in dataset.column_names:
|
| 337 |
+
raise KeyError(f"Action key '{action_key}' not found. Available columns: {dataset.column_names}")
|
| 338 |
+
oracle_actions, action_rows = _build_oracle_actions(
|
| 339 |
+
dataset=dataset,
|
| 340 |
+
selected_rows=selected_rows,
|
| 341 |
+
eval_episodes=eval_episodes,
|
| 342 |
+
eval_start_idx=eval_start_idx,
|
| 343 |
+
eval_budget=int(cfg.eval.eval_budget),
|
| 344 |
+
action_key=action_key,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
world_image_shape = (
|
| 348 |
+
int(cfg.world.get("height", cfg.eval.img_size)),
|
| 349 |
+
int(cfg.world.get("width", cfg.eval.img_size)),
|
| 350 |
+
)
|
| 351 |
+
world = swm.World(**cfg.world, image_shape=world_image_shape)
|
| 352 |
+
policy = DatasetActionReplayPolicy(oracle_actions)
|
| 353 |
+
world.set_policy(policy)
|
| 354 |
+
|
| 355 |
+
out_dir = _default_out_dir(cfg)
|
| 356 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 357 |
+
|
| 358 |
+
print(f"[debug-puzzle] mode=eval-stack-oracle", flush=True)
|
| 359 |
+
print(f"[debug-puzzle] dataset={cfg.eval.dataset_name}", flush=True)
|
| 360 |
+
print(f"[debug-puzzle] env={cfg.world.env_name}", flush=True)
|
| 361 |
+
print(f"[debug-puzzle] selected_rows={selected_rows.tolist()}", flush=True)
|
| 362 |
+
print(f"[debug-puzzle] episodes={eval_episodes.tolist()}", flush=True)
|
| 363 |
+
print(f"[debug-puzzle] start_steps={eval_start_idx.tolist()}", flush=True)
|
| 364 |
+
print(f"[debug-puzzle] oracle_actions_shape={list(oracle_actions.shape)}", flush=True)
|
| 365 |
+
|
| 366 |
+
policy.reset()
|
| 367 |
+
metrics = evaluate_from_dataset_with_progress(
|
| 368 |
+
world=world,
|
| 369 |
+
dataset=dataset,
|
| 370 |
+
episodes_idx=eval_episodes.tolist(),
|
| 371 |
+
start_steps=eval_start_idx.tolist(),
|
| 372 |
+
goal_offset_steps=int(cfg.eval.goal_offset_steps),
|
| 373 |
+
eval_budget=int(cfg.eval.eval_budget),
|
| 374 |
+
callables=OmegaConf.to_container(cfg.eval.get("callables"), resolve=True),
|
| 375 |
+
save_video=bool(cfg.eval.get("save_video", True)),
|
| 376 |
+
video_path=out_dir,
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
summary = {
|
| 380 |
+
"mode": "eval-stack-oracle",
|
| 381 |
+
"dataset_name": str(cfg.eval.dataset_name),
|
| 382 |
+
"env_name": str(cfg.world.env_name),
|
| 383 |
+
"num_eval": int(len(selected_rows)),
|
| 384 |
+
"goal_offset_steps": int(cfg.eval.goal_offset_steps),
|
| 385 |
+
"eval_budget": int(cfg.eval.eval_budget),
|
| 386 |
+
"selected_rows": selected_rows.tolist(),
|
| 387 |
+
"episodes": eval_episodes.tolist(),
|
| 388 |
+
"start_steps": eval_start_idx.tolist(),
|
| 389 |
+
"selection": selection_info,
|
| 390 |
+
"oracle_policy": {
|
| 391 |
+
"action_key": action_key,
|
| 392 |
+
"actions_shape": list(oracle_actions.shape),
|
| 393 |
+
"steps_consumed": int(policy.step_idx),
|
| 394 |
+
"first_action_rows": action_rows[:, : min(5, action_rows.shape[1])].tolist(),
|
| 395 |
+
"last_action_rows": action_rows[:, max(0, action_rows.shape[1] - 5) :].tolist(),
|
| 396 |
+
},
|
| 397 |
+
"button_summary": _button_summary(dataset, selected_rows, cfg),
|
| 398 |
+
"metrics": _jsonify(metrics),
|
| 399 |
+
"video_dir": str(out_dir),
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
summary_path = out_dir / "eval_stack_oracle_summary.json"
|
| 403 |
+
summary_path.write_text(json.dumps(summary, indent=2))
|
| 404 |
+
|
| 405 |
+
print("[debug-puzzle] metrics:", json.dumps(_jsonify(metrics), indent=2), flush=True)
|
| 406 |
+
print(f"[debug-puzzle] wrote {summary_path}", flush=True)
|
| 407 |
+
|
| 408 |
+
close_fn = getattr(world.envs, "close", None)
|
| 409 |
+
if callable(close_fn):
|
| 410 |
+
close_fn()
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
if __name__ == "__main__":
|
| 414 |
+
main()
|
debug/extract_rollout_figure_frames.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Extract context and prediction panels from a four-grid rollout mp4.
|
| 3 |
+
|
| 4 |
+
The eval videos produced by eval.py/eval_hyperbolic.py use this layout:
|
| 5 |
+
|
| 6 |
+
top-left: model-controlled rollout frame
|
| 7 |
+
bottom-left: dataset/reference real trajectory frame
|
| 8 |
+
top-right: goal frame
|
| 9 |
+
bottom-right: goal frame
|
| 10 |
+
|
| 11 |
+
This script crops the left panels and saves them with explicit context vs.
|
| 12 |
+
open-loop-prediction names so paper figures do not mix the two groups.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def parse_steps(value: str) -> list[int]:
|
| 23 |
+
steps = []
|
| 24 |
+
for item in str(value).split(","):
|
| 25 |
+
item = item.strip()
|
| 26 |
+
if not item:
|
| 27 |
+
continue
|
| 28 |
+
steps.append(int(item))
|
| 29 |
+
if not steps:
|
| 30 |
+
raise argparse.ArgumentTypeError("Expected at least one comma-separated step.")
|
| 31 |
+
return steps
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def parse_args() -> argparse.Namespace:
|
| 35 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 36 |
+
parser.add_argument("--video", required=True, type=Path, help="Path to rollout_*.mp4.")
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--output-dir",
|
| 39 |
+
type=Path,
|
| 40 |
+
default=None,
|
| 41 |
+
help="Default: <video_parent>/<video_stem>_figure_frames",
|
| 42 |
+
)
|
| 43 |
+
parser.add_argument("--context-steps", type=parse_steps, default=parse_steps("0,5,10"))
|
| 44 |
+
parser.add_argument(
|
| 45 |
+
"--prediction-steps",
|
| 46 |
+
type=parse_steps,
|
| 47 |
+
default=parse_steps("15,20,25,30,35"),
|
| 48 |
+
)
|
| 49 |
+
parser.add_argument(
|
| 50 |
+
"--imagined-label",
|
| 51 |
+
default="imagined",
|
| 52 |
+
help="Name used for the model rollout row. Use 'rollout' if you want stricter wording.",
|
| 53 |
+
)
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--save-composite",
|
| 56 |
+
action=argparse.BooleanOptionalAction,
|
| 57 |
+
default=False,
|
| 58 |
+
help="Also save a paper-style composite grid.",
|
| 59 |
+
)
|
| 60 |
+
parser.add_argument("--composite-name", default="context_vs_prediction_grid.png")
|
| 61 |
+
parser.add_argument("--dpi", type=int, default=220)
|
| 62 |
+
return parser.parse_args()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def read_frame(reader, index: int) -> np.ndarray:
|
| 66 |
+
import numpy as np
|
| 67 |
+
|
| 68 |
+
try:
|
| 69 |
+
frame = reader.get_data(index)
|
| 70 |
+
except IndexError as exc:
|
| 71 |
+
raise IndexError(f"Video does not contain frame index {index}.") from exc
|
| 72 |
+
frame = np.asarray(frame)
|
| 73 |
+
if frame.ndim != 3 or frame.shape[-1] < 3:
|
| 74 |
+
raise ValueError(f"Unexpected video frame shape at index {index}: {frame.shape}")
|
| 75 |
+
return frame[..., :3].astype(np.uint8, copy=False)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def crop_left_panels(frame: np.ndarray) -> dict[str, np.ndarray]:
|
| 79 |
+
height, width = frame.shape[:2]
|
| 80 |
+
if height < 2 or width < 2:
|
| 81 |
+
raise ValueError(f"Frame is too small to crop: {frame.shape}")
|
| 82 |
+
mid_h = height // 2
|
| 83 |
+
mid_w = width // 2
|
| 84 |
+
return {
|
| 85 |
+
"rollout": frame[:mid_h, :mid_w],
|
| 86 |
+
"real": frame[mid_h : 2 * mid_h, :mid_w],
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def save_png(path: Path, frame: np.ndarray) -> None:
|
| 91 |
+
from PIL import Image
|
| 92 |
+
|
| 93 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 94 |
+
Image.fromarray(frame).save(path)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def extract_frames(args: argparse.Namespace) -> tuple[Path, dict]:
|
| 98 |
+
video_path = args.video.expanduser().resolve()
|
| 99 |
+
if not video_path.is_file():
|
| 100 |
+
raise FileNotFoundError(f"Video not found: {video_path}")
|
| 101 |
+
|
| 102 |
+
output_dir = (
|
| 103 |
+
args.output_dir.expanduser().resolve()
|
| 104 |
+
if args.output_dir is not None
|
| 105 |
+
else video_path.parent / f"{video_path.stem}_figure_frames"
|
| 106 |
+
)
|
| 107 |
+
context_dir = output_dir / "context_input"
|
| 108 |
+
prediction_dir = output_dir / "open_loop_prediction"
|
| 109 |
+
|
| 110 |
+
manifest = {
|
| 111 |
+
"video": str(video_path),
|
| 112 |
+
"layout": {
|
| 113 |
+
"source": "four-grid eval mp4",
|
| 114 |
+
"real_panel": "bottom-left",
|
| 115 |
+
"imagined_panel": "top-left",
|
| 116 |
+
},
|
| 117 |
+
"context_steps": list(args.context_steps),
|
| 118 |
+
"prediction_steps": list(args.prediction_steps),
|
| 119 |
+
"frames": [],
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
import imageio
|
| 123 |
+
|
| 124 |
+
reader = imageio.get_reader(video_path)
|
| 125 |
+
try:
|
| 126 |
+
groups = [
|
| 127 |
+
("context_input", context_dir, args.context_steps),
|
| 128 |
+
("open_loop_prediction", prediction_dir, args.prediction_steps),
|
| 129 |
+
]
|
| 130 |
+
for group_name, group_dir, steps in groups:
|
| 131 |
+
for local_index, step in enumerate(steps, start=1):
|
| 132 |
+
frame = read_frame(reader, int(step))
|
| 133 |
+
panels = crop_left_panels(frame)
|
| 134 |
+
entries = [
|
| 135 |
+
("real", panels["real"]),
|
| 136 |
+
(str(args.imagined_label), panels["rollout"]),
|
| 137 |
+
]
|
| 138 |
+
for row_name, panel in entries:
|
| 139 |
+
filename = f"{group_name}_{local_index:02d}_{row_name}_t{int(step):03d}.png"
|
| 140 |
+
out_path = group_dir / row_name / filename
|
| 141 |
+
save_png(out_path, panel)
|
| 142 |
+
manifest["frames"].append(
|
| 143 |
+
{
|
| 144 |
+
"group": group_name,
|
| 145 |
+
"index": int(local_index),
|
| 146 |
+
"row": row_name,
|
| 147 |
+
"step": int(step),
|
| 148 |
+
"path": str(out_path),
|
| 149 |
+
}
|
| 150 |
+
)
|
| 151 |
+
finally:
|
| 152 |
+
reader.close()
|
| 153 |
+
|
| 154 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 155 |
+
with (output_dir / "manifest.json").open("w") as handle:
|
| 156 |
+
json.dump(manifest, handle, indent=2)
|
| 157 |
+
|
| 158 |
+
return output_dir, manifest
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _load_manifest_image(frame_entry: dict) -> np.ndarray:
|
| 162 |
+
import numpy as np
|
| 163 |
+
from PIL import Image
|
| 164 |
+
|
| 165 |
+
return np.asarray(Image.open(frame_entry["path"]).convert("RGB"))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def save_composite(output_dir: Path, manifest: dict, composite_name: str, dpi: int) -> Path:
|
| 169 |
+
import matplotlib.pyplot as plt
|
| 170 |
+
|
| 171 |
+
context_steps = list(manifest["context_steps"])
|
| 172 |
+
prediction_steps = list(manifest["prediction_steps"])
|
| 173 |
+
all_steps = context_steps + prediction_steps
|
| 174 |
+
n_context = len(context_steps)
|
| 175 |
+
n_prediction = len(prediction_steps)
|
| 176 |
+
n_total = len(all_steps)
|
| 177 |
+
gap_units = 0.45
|
| 178 |
+
|
| 179 |
+
by_key = {
|
| 180 |
+
(entry["group"], entry["row"], int(entry["index"])): entry
|
| 181 |
+
for entry in manifest["frames"]
|
| 182 |
+
}
|
| 183 |
+
imagined_rows = sorted(
|
| 184 |
+
{
|
| 185 |
+
entry["row"]
|
| 186 |
+
for entry in manifest["frames"]
|
| 187 |
+
if entry["row"] != "real"
|
| 188 |
+
}
|
| 189 |
+
)
|
| 190 |
+
imagined_row = imagined_rows[0] if imagined_rows else "imagined"
|
| 191 |
+
|
| 192 |
+
sample = _load_manifest_image(manifest["frames"][0])
|
| 193 |
+
aspect = sample.shape[1] / sample.shape[0]
|
| 194 |
+
tile_h = 1.0
|
| 195 |
+
tile_w = aspect
|
| 196 |
+
fig_w = max(8.0, n_total * 1.35 * aspect + 2.2)
|
| 197 |
+
fig_h = 3.8
|
| 198 |
+
|
| 199 |
+
fig = plt.figure(figsize=(fig_w, fig_h))
|
| 200 |
+
left_margin = 0.10
|
| 201 |
+
right_margin = 0.02
|
| 202 |
+
top_margin = 0.20
|
| 203 |
+
bottom_margin = 0.18
|
| 204 |
+
row_gap = 0.055
|
| 205 |
+
available_w = 1.0 - left_margin - right_margin
|
| 206 |
+
available_h = 1.0 - top_margin - bottom_margin
|
| 207 |
+
unit_w = available_w / (n_total + gap_units)
|
| 208 |
+
axis_w = unit_w
|
| 209 |
+
axis_h = (available_h - row_gap) / 2.0
|
| 210 |
+
|
| 211 |
+
def x_for_column(column: int) -> float:
|
| 212 |
+
extra_gap = gap_units if column >= n_context else 0.0
|
| 213 |
+
return left_margin + (column + extra_gap) * unit_w
|
| 214 |
+
|
| 215 |
+
row_y = {
|
| 216 |
+
"real": bottom_margin + axis_h + row_gap,
|
| 217 |
+
imagined_row: bottom_margin,
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
context_entries = [("context_input", i + 1, step) for i, step in enumerate(context_steps)]
|
| 221 |
+
prediction_entries = [
|
| 222 |
+
("open_loop_prediction", i + 1, step)
|
| 223 |
+
for i, step in enumerate(prediction_steps)
|
| 224 |
+
]
|
| 225 |
+
column_entries = context_entries + prediction_entries
|
| 226 |
+
|
| 227 |
+
for col, (group_name, local_index, step) in enumerate(column_entries):
|
| 228 |
+
for row_name in ("real", imagined_row):
|
| 229 |
+
entry = by_key[(group_name, row_name, local_index)]
|
| 230 |
+
ax = fig.add_axes([x_for_column(col), row_y[row_name], axis_w, axis_h])
|
| 231 |
+
ax.imshow(_load_manifest_image(entry))
|
| 232 |
+
ax.set_xticks([])
|
| 233 |
+
ax.set_yticks([])
|
| 234 |
+
for spine in ax.spines.values():
|
| 235 |
+
spine.set_linewidth(1.2)
|
| 236 |
+
spine.set_color("black")
|
| 237 |
+
if row_name == imagined_row:
|
| 238 |
+
label = f"T = {step}" if col == 0 else f"{step}"
|
| 239 |
+
ax.set_xlabel(label, fontsize=15, labelpad=6)
|
| 240 |
+
|
| 241 |
+
context_center = (
|
| 242 |
+
x_for_column(0) + x_for_column(n_context - 1) + axis_w
|
| 243 |
+
) / 2.0
|
| 244 |
+
prediction_center = (
|
| 245 |
+
x_for_column(n_context) + x_for_column(n_total - 1) + axis_w
|
| 246 |
+
) / 2.0
|
| 247 |
+
fig.text(context_center, 0.95, "Context Input", ha="center", va="top", fontsize=19)
|
| 248 |
+
fig.text(
|
| 249 |
+
prediction_center,
|
| 250 |
+
0.95,
|
| 251 |
+
"Open Loop Prediction",
|
| 252 |
+
ha="center",
|
| 253 |
+
va="top",
|
| 254 |
+
fontsize=19,
|
| 255 |
+
)
|
| 256 |
+
fig.text(0.045, row_y["real"] + axis_h / 2, "Real", rotation=90, ha="center", va="center", fontsize=17)
|
| 257 |
+
fig.text(
|
| 258 |
+
0.045,
|
| 259 |
+
row_y[imagined_row] + axis_h / 2,
|
| 260 |
+
imagined_row.capitalize(),
|
| 261 |
+
rotation=90,
|
| 262 |
+
ha="center",
|
| 263 |
+
va="center",
|
| 264 |
+
fontsize=17,
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
composite_path = output_dir / composite_name
|
| 268 |
+
fig.savefig(composite_path, dpi=dpi, bbox_inches="tight", pad_inches=0.06)
|
| 269 |
+
plt.close(fig)
|
| 270 |
+
return composite_path
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def main() -> None:
|
| 274 |
+
args = parse_args()
|
| 275 |
+
output_dir, manifest = extract_frames(args)
|
| 276 |
+
print(f"[extract] wrote frames to {output_dir}", flush=True)
|
| 277 |
+
if args.save_composite:
|
| 278 |
+
composite_path = save_composite(
|
| 279 |
+
output_dir,
|
| 280 |
+
manifest,
|
| 281 |
+
args.composite_name,
|
| 282 |
+
int(args.dpi),
|
| 283 |
+
)
|
| 284 |
+
print(f"[extract] wrote composite figure to {composite_path}", flush=True)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
if __name__ == "__main__":
|
| 288 |
+
main()
|
debug/visualize_pusht_poincare_hierarchy.py
ADDED
|
@@ -0,0 +1,933 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Visualize PushT progress hierarchy in the Poincare ball.
|
| 3 |
+
|
| 4 |
+
Example:
|
| 5 |
+
python debug/visualize_pusht_poincare_hierarchy.py \
|
| 6 |
+
--policy /data_nvme/user/zliu681/le-wm-main/lewm_cache/pusht/hyperbolic_pusht_stable_trial2/lewm_hyperbolic_pusht_stable_epoch_10_state.ckpt \
|
| 7 |
+
--num-trajectories 8 \
|
| 8 |
+
--window 80
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import h5py
|
| 19 |
+
import matplotlib.pyplot as plt
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from omegaconf import OmegaConf, open_dict
|
| 24 |
+
|
| 25 |
+
REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 26 |
+
if str(REPO_ROOT) not in sys.path:
|
| 27 |
+
sys.path.insert(0, str(REPO_ROOT))
|
| 28 |
+
|
| 29 |
+
import stable_worldmodel as swm # noqa: E402
|
| 30 |
+
from train_hyperbolic import ( # noqa: E402
|
| 31 |
+
build_hyperbolic_world_model,
|
| 32 |
+
ensure_hyperbolic_defaults,
|
| 33 |
+
)
|
| 34 |
+
from utils import get_img_preprocessor # noqa: E402
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def parse_args() -> argparse.Namespace:
|
| 38 |
+
parser = argparse.ArgumentParser(
|
| 39 |
+
description="Draw goal-conditioned PushT Poincare progress hierarchy.",
|
| 40 |
+
)
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--policy",
|
| 43 |
+
required=True,
|
| 44 |
+
help="Path to a hyperbolic *_state.ckpt, *_weights.ckpt, *_object.ckpt, or run directory.",
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--config",
|
| 48 |
+
default=None,
|
| 49 |
+
help="Optional config.yaml path. By default, use config.yaml beside the checkpoint.",
|
| 50 |
+
)
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
"--dataset",
|
| 53 |
+
default=None,
|
| 54 |
+
help="Optional h5 dataset path. By default, resolve cfg.data.dataset.name under lewm_cache.",
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument("--pixel-key", default="pixels")
|
| 57 |
+
parser.add_argument("--num-trajectories", type=int, default=8)
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--candidate-episodes",
|
| 60 |
+
type=int,
|
| 61 |
+
default=48,
|
| 62 |
+
help="Number of episodes to scan before selecting representative windows.",
|
| 63 |
+
)
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"--windows-per-episode",
|
| 66 |
+
type=int,
|
| 67 |
+
default=4,
|
| 68 |
+
help="Only used with --window-mode scan.",
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument("--window", type=int, default=80)
|
| 71 |
+
parser.add_argument("--stride", type=int, default=2)
|
| 72 |
+
parser.add_argument("--seed", type=int, default=0)
|
| 73 |
+
parser.add_argument(
|
| 74 |
+
"--window-mode",
|
| 75 |
+
choices=("scan", "tail", "random"),
|
| 76 |
+
default="scan",
|
| 77 |
+
help=(
|
| 78 |
+
"scan searches several subwindows per episode; tail uses the final window; "
|
| 79 |
+
"random samples one window inside each episode."
|
| 80 |
+
),
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--selection",
|
| 84 |
+
choices=("radius_corr", "radius_gain", "random"),
|
| 85 |
+
default="radius_corr",
|
| 86 |
+
help="How to select final displayed windows from candidates.",
|
| 87 |
+
)
|
| 88 |
+
parser.add_argument(
|
| 89 |
+
"--projection",
|
| 90 |
+
choices=("goal_aligned", "global_goal_pca"),
|
| 91 |
+
default="goal_aligned",
|
| 92 |
+
help=(
|
| 93 |
+
"goal_aligned maps each hindsight goal to +x independently; "
|
| 94 |
+
"global_goal_pca uses the first goal direction and one global orthogonal PCA axis."
|
| 95 |
+
),
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument("--device", default="auto")
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
"--output-dir",
|
| 100 |
+
default=None,
|
| 101 |
+
help="Default: lewm_cache/debug/pusht_poincare_hierarchy/<checkpoint_stem>",
|
| 102 |
+
)
|
| 103 |
+
parser.add_argument("--dpi", type=int, default=220)
|
| 104 |
+
parser.add_argument("--plot-3d", action="store_true")
|
| 105 |
+
return parser.parse_args()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def resolve_device(device: str) -> torch.device:
|
| 109 |
+
if device == "auto":
|
| 110 |
+
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 111 |
+
return torch.device(device)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def resolve_policy_path(policy: str) -> Path:
|
| 115 |
+
path = Path(policy)
|
| 116 |
+
if path.is_dir():
|
| 117 |
+
candidates = sorted(path.glob("*_state.ckpt"))
|
| 118 |
+
candidates += sorted(path.glob("*_weights.ckpt"))
|
| 119 |
+
candidates += sorted(path.glob("*.ckpt"))
|
| 120 |
+
if not candidates:
|
| 121 |
+
raise FileNotFoundError(f"No checkpoint found under policy directory: {path}")
|
| 122 |
+
return candidates[-1]
|
| 123 |
+
|
| 124 |
+
if path.name.endswith("_object.ckpt"):
|
| 125 |
+
state_path = path.with_name(path.name.replace("_object.ckpt", "_state.ckpt"))
|
| 126 |
+
if state_path.exists():
|
| 127 |
+
return state_path
|
| 128 |
+
weights_path = path.with_name(path.name.replace("_object.ckpt", "_weights.ckpt"))
|
| 129 |
+
if weights_path.exists():
|
| 130 |
+
return weights_path
|
| 131 |
+
|
| 132 |
+
return path
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def resolve_config_path(policy_path: Path, config_arg: str | None) -> Path:
|
| 136 |
+
if config_arg is not None:
|
| 137 |
+
config_path = Path(config_arg)
|
| 138 |
+
else:
|
| 139 |
+
config_path = policy_path.parent / "config.yaml"
|
| 140 |
+
if not config_path.exists():
|
| 141 |
+
raise FileNotFoundError(
|
| 142 |
+
f"Could not find config.yaml at {config_path}. Pass --config explicitly."
|
| 143 |
+
)
|
| 144 |
+
return config_path
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def resolve_dataset_path(cfg, dataset_arg: str | None) -> Path:
|
| 148 |
+
if dataset_arg:
|
| 149 |
+
dataset_path = Path(dataset_arg)
|
| 150 |
+
if dataset_path.exists():
|
| 151 |
+
return dataset_path
|
| 152 |
+
raise FileNotFoundError(f"Dataset path does not exist: {dataset_path}")
|
| 153 |
+
|
| 154 |
+
dataset_name = str(cfg.data.dataset.name).replace("\\", "/")
|
| 155 |
+
cache_dir = Path(swm.data.utils.get_cache_dir())
|
| 156 |
+
candidates = [
|
| 157 |
+
cache_dir / f"{dataset_name}.h5",
|
| 158 |
+
cache_dir / dataset_name,
|
| 159 |
+
]
|
| 160 |
+
for candidate in candidates:
|
| 161 |
+
if candidate.exists():
|
| 162 |
+
return candidate
|
| 163 |
+
raise FileNotFoundError(
|
| 164 |
+
"Could not resolve dataset from cfg.data.dataset.name="
|
| 165 |
+
f"{dataset_name!r}. Tried: {', '.join(str(c) for c in candidates)}"
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def resolve_output_dir(policy_path: Path, output_dir: str | None) -> Path:
|
| 170 |
+
if output_dir:
|
| 171 |
+
return Path(output_dir)
|
| 172 |
+
cache_dir = Path(swm.data.utils.get_cache_dir())
|
| 173 |
+
return cache_dir / "debug" / "pusht_poincare_hierarchy" / policy_path.stem
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def infer_action_dim(h5_file: h5py.File) -> int:
|
| 177 |
+
if "action" not in h5_file:
|
| 178 |
+
raise KeyError("Expected action key in dataset to infer action_dim.")
|
| 179 |
+
action_shape = h5_file["action"].shape
|
| 180 |
+
if len(action_shape) < 2:
|
| 181 |
+
raise ValueError(f"Unexpected action shape: {action_shape}")
|
| 182 |
+
return int(action_shape[-1])
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def load_model(policy_path: Path, cfg, action_dim: int, device: torch.device):
|
| 186 |
+
ensure_hyperbolic_defaults(cfg)
|
| 187 |
+
with open_dict(cfg):
|
| 188 |
+
cfg.wm.action_dim = int(action_dim)
|
| 189 |
+
|
| 190 |
+
model = build_hyperbolic_world_model(cfg, action_dim=int(action_dim))
|
| 191 |
+
checkpoint = torch.load(policy_path, map_location="cpu", weights_only=False)
|
| 192 |
+
|
| 193 |
+
if hasattr(checkpoint, "state_dict"):
|
| 194 |
+
state = checkpoint.state_dict()
|
| 195 |
+
elif isinstance(checkpoint, dict) and "model_state_dict" in checkpoint:
|
| 196 |
+
state = checkpoint["model_state_dict"]
|
| 197 |
+
elif isinstance(checkpoint, dict) and "state_dict" in checkpoint:
|
| 198 |
+
state = checkpoint["state_dict"]
|
| 199 |
+
elif isinstance(checkpoint, dict) and all(torch.is_tensor(v) for v in checkpoint.values()):
|
| 200 |
+
state = checkpoint
|
| 201 |
+
else:
|
| 202 |
+
raise TypeError(
|
| 203 |
+
"Unsupported checkpoint format. Prefer a portable *_state.ckpt checkpoint."
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
stripped = {}
|
| 207 |
+
for key, value in state.items():
|
| 208 |
+
if key.startswith("model."):
|
| 209 |
+
stripped[key[len("model.") :]] = value
|
| 210 |
+
else:
|
| 211 |
+
stripped[key] = value
|
| 212 |
+
|
| 213 |
+
missing, unexpected = model.load_state_dict(stripped, strict=False)
|
| 214 |
+
print(
|
| 215 |
+
f"[poincare] loaded {policy_path} | "
|
| 216 |
+
f"missing={len(missing)} unexpected={len(unexpected)}",
|
| 217 |
+
flush=True,
|
| 218 |
+
)
|
| 219 |
+
if missing:
|
| 220 |
+
print(f"[poincare] first missing keys: {missing[:8]}", flush=True)
|
| 221 |
+
if unexpected:
|
| 222 |
+
print(f"[poincare] first unexpected keys: {unexpected[:8]}", flush=True)
|
| 223 |
+
|
| 224 |
+
return model.to(device).eval()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def dataset_length(h5_file: h5py.File, pixel_key: str) -> int:
|
| 228 |
+
if pixel_key in h5_file:
|
| 229 |
+
return int(h5_file[pixel_key].shape[0])
|
| 230 |
+
for key in h5_file.keys():
|
| 231 |
+
value = h5_file[key]
|
| 232 |
+
if isinstance(value, h5py.Dataset) and len(value.shape) > 0:
|
| 233 |
+
return int(value.shape[0])
|
| 234 |
+
raise ValueError("Could not infer dataset length.")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def episode_bounds(h5_file: h5py.File, pixel_key: str) -> list[tuple[int, int]]:
|
| 238 |
+
total = dataset_length(h5_file, pixel_key)
|
| 239 |
+
|
| 240 |
+
if "ep_offset" in h5_file and "ep_len" in h5_file:
|
| 241 |
+
starts = np.asarray(h5_file["ep_offset"][:], dtype=np.int64).reshape(-1)
|
| 242 |
+
lengths = np.asarray(h5_file["ep_len"][:], dtype=np.int64).reshape(-1)
|
| 243 |
+
if starts.shape == lengths.shape:
|
| 244 |
+
ends = starts + lengths
|
| 245 |
+
bounds = [
|
| 246 |
+
(int(start), int(end))
|
| 247 |
+
for start, end in zip(starts, ends)
|
| 248 |
+
if 0 <= int(start) < int(end) <= total
|
| 249 |
+
]
|
| 250 |
+
if bounds:
|
| 251 |
+
return bounds
|
| 252 |
+
|
| 253 |
+
for key in ("episode_ends", "episode_end", "ends"):
|
| 254 |
+
if key in h5_file:
|
| 255 |
+
ends = np.asarray(h5_file[key][:], dtype=np.int64)
|
| 256 |
+
starts = np.concatenate([[0], ends[:-1]])
|
| 257 |
+
return [(int(s), int(e)) for s, e in zip(starts, ends) if int(e) > int(s)]
|
| 258 |
+
|
| 259 |
+
if "episode_idx" in h5_file:
|
| 260 |
+
episode_idx = np.asarray(h5_file["episode_idx"][:], dtype=np.int64).reshape(-1)
|
| 261 |
+
if episode_idx.shape[0] == total:
|
| 262 |
+
change_points = np.flatnonzero(episode_idx[1:] != episode_idx[:-1]) + 1
|
| 263 |
+
ends = np.concatenate([change_points, [total]]).astype(np.int64)
|
| 264 |
+
starts = np.concatenate([[0], ends[:-1]])
|
| 265 |
+
bounds = [
|
| 266 |
+
(int(start), int(end))
|
| 267 |
+
for start, end in zip(starts, ends)
|
| 268 |
+
if int(end) > int(start)
|
| 269 |
+
]
|
| 270 |
+
if bounds:
|
| 271 |
+
return bounds
|
| 272 |
+
|
| 273 |
+
if "step_idx" in h5_file:
|
| 274 |
+
step_idx = np.asarray(h5_file["step_idx"][:], dtype=np.int64).reshape(-1)
|
| 275 |
+
if step_idx.shape[0] == total:
|
| 276 |
+
starts = np.flatnonzero(step_idx == 0).astype(np.int64)
|
| 277 |
+
if starts.size:
|
| 278 |
+
ends = np.concatenate([starts[1:], [total]]).astype(np.int64)
|
| 279 |
+
bounds = [
|
| 280 |
+
(int(start), int(end))
|
| 281 |
+
for start, end in zip(starts, ends)
|
| 282 |
+
if int(end) > int(start)
|
| 283 |
+
]
|
| 284 |
+
if bounds:
|
| 285 |
+
return bounds
|
| 286 |
+
|
| 287 |
+
done = np.zeros(total, dtype=bool)
|
| 288 |
+
found_done = False
|
| 289 |
+
for key in ("terminals", "terminal", "timeouts", "timeout", "dones", "done"):
|
| 290 |
+
if key in h5_file:
|
| 291 |
+
value = np.asarray(h5_file[key][:], dtype=bool).reshape(-1)
|
| 292 |
+
if value.shape[0] == total:
|
| 293 |
+
done |= value
|
| 294 |
+
found_done = True
|
| 295 |
+
|
| 296 |
+
if found_done:
|
| 297 |
+
ends = (np.flatnonzero(done) + 1).astype(np.int64)
|
| 298 |
+
if len(ends) == 0 or int(ends[-1]) != total:
|
| 299 |
+
ends = np.concatenate([ends, [total]])
|
| 300 |
+
starts = np.concatenate([[0], ends[:-1]])
|
| 301 |
+
return [(int(s), int(e)) for s, e in zip(starts, ends) if int(e) > int(s)]
|
| 302 |
+
|
| 303 |
+
return [(0, total)]
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def choose_candidate_windows(
|
| 307 |
+
bounds: list[tuple[int, int]],
|
| 308 |
+
*,
|
| 309 |
+
num_trajectories: int,
|
| 310 |
+
candidate_episodes: int,
|
| 311 |
+
windows_per_episode: int,
|
| 312 |
+
window: int,
|
| 313 |
+
stride: int,
|
| 314 |
+
mode: str,
|
| 315 |
+
rng: np.random.Generator,
|
| 316 |
+
) -> list[tuple[int, int, int, int]]:
|
| 317 |
+
min_len = max(2, int(window))
|
| 318 |
+
valid = [(s, e) for s, e in bounds if e - s >= min_len]
|
| 319 |
+
if not valid:
|
| 320 |
+
raise ValueError(
|
| 321 |
+
f"No episode is long enough for window={window}. "
|
| 322 |
+
f"Longest episode length={max((e - s for s, e in bounds), default=0)}"
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
sample_count = num_trajectories if mode != "scan" else max(num_trajectories, candidate_episodes)
|
| 326 |
+
order = rng.permutation(len(valid))[: min(sample_count, len(valid))]
|
| 327 |
+
windows = []
|
| 328 |
+
for local_idx in order:
|
| 329 |
+
ep_start, ep_end = valid[int(local_idx)]
|
| 330 |
+
max_start = ep_end - window
|
| 331 |
+
if mode == "scan":
|
| 332 |
+
if windows_per_episode <= 1:
|
| 333 |
+
starts = [max_start]
|
| 334 |
+
else:
|
| 335 |
+
starts = np.linspace(
|
| 336 |
+
ep_start,
|
| 337 |
+
max_start,
|
| 338 |
+
num=max(1, int(windows_per_episode)),
|
| 339 |
+
).round().astype(np.int64)
|
| 340 |
+
starts = list(dict.fromkeys(int(s) for s in starts))
|
| 341 |
+
elif mode == "tail":
|
| 342 |
+
starts = [max_start]
|
| 343 |
+
else:
|
| 344 |
+
starts = [int(rng.integers(ep_start, max_start + 1))]
|
| 345 |
+
|
| 346 |
+
for start in starts:
|
| 347 |
+
start = int(max(ep_start, min(start, max_start)))
|
| 348 |
+
end = start + window
|
| 349 |
+
rows = np.arange(start, end, max(1, int(stride)), dtype=np.int64)
|
| 350 |
+
if rows[-1] != end - 1:
|
| 351 |
+
rows = np.concatenate([rows, [end - 1]])
|
| 352 |
+
windows.append((ep_start, ep_end, int(rows[0]), int(rows[-1])))
|
| 353 |
+
|
| 354 |
+
unique = []
|
| 355 |
+
seen = set()
|
| 356 |
+
for item in windows:
|
| 357 |
+
if item not in seen:
|
| 358 |
+
seen.add(item)
|
| 359 |
+
unique.append(item)
|
| 360 |
+
return unique
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def score_poincare_window(poincare: np.ndarray) -> dict[str, float]:
|
| 364 |
+
progress = np.linspace(0.0, 1.0, poincare.shape[0], dtype=np.float64)
|
| 365 |
+
radius = np.linalg.norm(poincare, axis=1)
|
| 366 |
+
if radius.size < 2 or np.std(radius) < 1e-8:
|
| 367 |
+
corr = float("nan")
|
| 368 |
+
else:
|
| 369 |
+
corr = float(np.corrcoef(progress, radius)[0, 1])
|
| 370 |
+
|
| 371 |
+
early = radius[progress <= 0.25]
|
| 372 |
+
late = radius[progress >= 0.75]
|
| 373 |
+
early_mean = float(np.mean(early)) if early.size else float("nan")
|
| 374 |
+
late_mean = float(np.mean(late)) if late.size else float("nan")
|
| 375 |
+
return {
|
| 376 |
+
"radius_corr": corr,
|
| 377 |
+
"radius_gain": late_mean - early_mean,
|
| 378 |
+
"early_radius": early_mean,
|
| 379 |
+
"late_radius": late_mean,
|
| 380 |
+
"radius_min": float(np.min(radius)),
|
| 381 |
+
"radius_max": float(np.max(radius)),
|
| 382 |
+
"radius_spread": float(np.max(radius) - np.min(radius)),
|
| 383 |
+
"goal_radius": float(np.linalg.norm(poincare[-1])),
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def select_candidate_indices(
|
| 388 |
+
candidate_scores: list[dict[str, float]],
|
| 389 |
+
*,
|
| 390 |
+
selection: str,
|
| 391 |
+
num_trajectories: int,
|
| 392 |
+
rng: np.random.Generator,
|
| 393 |
+
) -> list[int]:
|
| 394 |
+
if selection == "random":
|
| 395 |
+
order = rng.permutation(len(candidate_scores))
|
| 396 |
+
return [int(i) for i in order[:num_trajectories]]
|
| 397 |
+
|
| 398 |
+
def finite(value: float, fallback: float = -1e9) -> float:
|
| 399 |
+
return float(value) if np.isfinite(value) else fallback
|
| 400 |
+
|
| 401 |
+
if selection == "radius_gain":
|
| 402 |
+
key = lambda i: (
|
| 403 |
+
finite(candidate_scores[i]["radius_gain"]),
|
| 404 |
+
finite(candidate_scores[i]["radius_corr"]),
|
| 405 |
+
finite(candidate_scores[i]["radius_spread"]),
|
| 406 |
+
)
|
| 407 |
+
else:
|
| 408 |
+
key = lambda i: (
|
| 409 |
+
finite(candidate_scores[i]["radius_corr"]),
|
| 410 |
+
finite(candidate_scores[i]["radius_gain"]),
|
| 411 |
+
finite(candidate_scores[i]["radius_spread"]),
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
ranked = sorted(range(len(candidate_scores)), key=key, reverse=True)
|
| 415 |
+
return [int(i) for i in ranked[:num_trajectories]]
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def write_candidate_summary(path: Path, rows: list[dict]) -> None:
|
| 419 |
+
fields = [
|
| 420 |
+
"candidate",
|
| 421 |
+
"selected",
|
| 422 |
+
"traj",
|
| 423 |
+
"episode_start",
|
| 424 |
+
"episode_end",
|
| 425 |
+
"first_row",
|
| 426 |
+
"last_row",
|
| 427 |
+
"radius_corr",
|
| 428 |
+
"radius_gain",
|
| 429 |
+
"early_radius",
|
| 430 |
+
"late_radius",
|
| 431 |
+
"radius_min",
|
| 432 |
+
"radius_max",
|
| 433 |
+
"radius_spread",
|
| 434 |
+
"goal_radius",
|
| 435 |
+
]
|
| 436 |
+
with path.open("w", newline="") as handle:
|
| 437 |
+
handle.write(",".join(fields) + "\n")
|
| 438 |
+
for row in rows:
|
| 439 |
+
handle.write(",".join(str(row.get(field, "")) for field in fields) + "\n")
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def pixel_tensor(raw: np.ndarray) -> torch.Tensor:
|
| 443 |
+
x = torch.from_numpy(np.asarray(raw))
|
| 444 |
+
if x.ndim != 4:
|
| 445 |
+
raise ValueError(f"Expected pixels with 4 dims, got shape={tuple(x.shape)}")
|
| 446 |
+
if x.shape[-1] in (1, 3):
|
| 447 |
+
x = x.permute(0, 3, 1, 2)
|
| 448 |
+
return x.contiguous()
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def preprocess_pixels(raw_pixels: np.ndarray, cfg, pixel_key: str) -> torch.Tensor:
|
| 452 |
+
pixels = pixel_tensor(raw_pixels)
|
| 453 |
+
transform = get_img_preprocessor(
|
| 454 |
+
source=pixel_key,
|
| 455 |
+
target="pixels",
|
| 456 |
+
img_size=int(cfg.img_size),
|
| 457 |
+
resize=True,
|
| 458 |
+
)
|
| 459 |
+
try:
|
| 460 |
+
return transform({pixel_key: pixels})["pixels"]
|
| 461 |
+
except Exception as exc:
|
| 462 |
+
print(
|
| 463 |
+
"[poincare] get_img_preprocessor failed; using simple float resize fallback. "
|
| 464 |
+
f"Reason: {exc}",
|
| 465 |
+
flush=True,
|
| 466 |
+
)
|
| 467 |
+
pixels = pixels.float()
|
| 468 |
+
if pixels.max() > 1.5:
|
| 469 |
+
pixels = pixels / 255.0
|
| 470 |
+
return F.interpolate(
|
| 471 |
+
pixels,
|
| 472 |
+
size=(int(cfg.img_size), int(cfg.img_size)),
|
| 473 |
+
mode="bilinear",
|
| 474 |
+
align_corners=False,
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def encoder_features(model, pixels: torch.Tensor) -> torch.Tensor:
|
| 479 |
+
output = model.encoder(pixels)
|
| 480 |
+
if torch.is_tensor(output):
|
| 481 |
+
return output
|
| 482 |
+
if hasattr(output, "last_hidden_state"):
|
| 483 |
+
hidden = output.last_hidden_state
|
| 484 |
+
if hidden.ndim == 3:
|
| 485 |
+
return hidden[:, 0]
|
| 486 |
+
return hidden
|
| 487 |
+
if hasattr(output, "pooler_output") and output.pooler_output is not None:
|
| 488 |
+
return output.pooler_output
|
| 489 |
+
if isinstance(output, (tuple, list)) and output:
|
| 490 |
+
first = output[0]
|
| 491 |
+
if torch.is_tensor(first) and first.ndim == 3:
|
| 492 |
+
return first[:, 0]
|
| 493 |
+
return first
|
| 494 |
+
raise TypeError(f"Unsupported encoder output type: {type(output)!r}")
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
@torch.no_grad()
|
| 498 |
+
def encode_poincare(
|
| 499 |
+
model,
|
| 500 |
+
raw_pixels: np.ndarray,
|
| 501 |
+
cfg,
|
| 502 |
+
pixel_key: str,
|
| 503 |
+
device: torch.device,
|
| 504 |
+
chunk_size: int = 32,
|
| 505 |
+
) -> np.ndarray:
|
| 506 |
+
pixels = preprocess_pixels(raw_pixels, cfg, pixel_key)
|
| 507 |
+
poincare_chunks = []
|
| 508 |
+
for start in range(0, pixels.size(0), chunk_size):
|
| 509 |
+
batch = pixels[start : start + chunk_size].to(device)
|
| 510 |
+
features = encoder_features(model, batch)
|
| 511 |
+
emb = model.projector(features)
|
| 512 |
+
hyperbolic = model.to_hyperbolic(emb)
|
| 513 |
+
if isinstance(hyperbolic, tuple):
|
| 514 |
+
hyp = hyperbolic[-1]
|
| 515 |
+
else:
|
| 516 |
+
hyp = hyperbolic
|
| 517 |
+
poincare = model.manifold.to_poincare(hyp)
|
| 518 |
+
poincare_chunks.append(poincare.detach().cpu().float().numpy())
|
| 519 |
+
return np.concatenate(poincare_chunks, axis=0)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def unit(v: np.ndarray, eps: float = 1e-8) -> np.ndarray:
|
| 523 |
+
norm = float(np.linalg.norm(v))
|
| 524 |
+
if norm < eps:
|
| 525 |
+
out = np.zeros_like(v)
|
| 526 |
+
out[0] = 1.0
|
| 527 |
+
return out
|
| 528 |
+
return v / norm
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def first_principal_axis(x: np.ndarray, fallback: np.ndarray) -> np.ndarray:
|
| 532 |
+
if x.shape[0] < 2 or np.allclose(x, 0.0):
|
| 533 |
+
return fallback
|
| 534 |
+
centered = x - x.mean(axis=0, keepdims=True)
|
| 535 |
+
try:
|
| 536 |
+
_, _, vh = np.linalg.svd(centered, full_matrices=False)
|
| 537 |
+
return unit(vh[0])
|
| 538 |
+
except np.linalg.LinAlgError:
|
| 539 |
+
return fallback
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def project_goal_aligned(p: np.ndarray) -> tuple[np.ndarray, float]:
|
| 543 |
+
goal = p[-1]
|
| 544 |
+
x_axis = unit(goal)
|
| 545 |
+
x = p @ x_axis
|
| 546 |
+
residual = p - x[:, None] * x_axis[None, :]
|
| 547 |
+
fallback = np.zeros_like(x_axis)
|
| 548 |
+
fallback[0] = 1.0
|
| 549 |
+
if abs(float(np.dot(fallback, x_axis))) > 0.9 and fallback.size > 1:
|
| 550 |
+
fallback = np.zeros_like(x_axis)
|
| 551 |
+
fallback[1] = 1.0
|
| 552 |
+
fallback = unit(fallback - np.dot(fallback, x_axis) * x_axis)
|
| 553 |
+
y_axis = first_principal_axis(residual, fallback)
|
| 554 |
+
y_axis = unit(y_axis - np.dot(y_axis, x_axis) * x_axis)
|
| 555 |
+
y = p @ y_axis
|
| 556 |
+
if y[-1] < 0:
|
| 557 |
+
y = -y
|
| 558 |
+
return np.stack([x, y], axis=1), float(np.linalg.norm(goal))
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def project_global_goal_pca(all_p: list[np.ndarray]) -> tuple[list[np.ndarray], list[float]]:
|
| 562 |
+
goals = np.stack([p[-1] for p in all_p], axis=0)
|
| 563 |
+
x_axis = unit(goals.mean(axis=0))
|
| 564 |
+
residuals = []
|
| 565 |
+
for p in all_p:
|
| 566 |
+
x = p @ x_axis
|
| 567 |
+
residuals.append(p - x[:, None] * x_axis[None, :])
|
| 568 |
+
y_axis = first_principal_axis(np.concatenate(residuals, axis=0), np.roll(x_axis, 1))
|
| 569 |
+
y_axis = unit(y_axis - np.dot(y_axis, x_axis) * x_axis)
|
| 570 |
+
|
| 571 |
+
coords = []
|
| 572 |
+
goal_radii = []
|
| 573 |
+
for p in all_p:
|
| 574 |
+
coords.append(np.stack([p @ x_axis, p @ y_axis], axis=1))
|
| 575 |
+
goal_radii.append(float(np.linalg.norm(p[-1])))
|
| 576 |
+
return coords, goal_radii
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def radius_metrics(records: list[dict]) -> dict:
|
| 580 |
+
progress = np.asarray([row["progress"] for row in records], dtype=np.float64)
|
| 581 |
+
radius = np.asarray([row["radius"] for row in records], dtype=np.float64)
|
| 582 |
+
if progress.size < 2 or np.std(radius) < 1e-8:
|
| 583 |
+
corr = float("nan")
|
| 584 |
+
else:
|
| 585 |
+
corr = float(np.corrcoef(progress, radius)[0, 1])
|
| 586 |
+
|
| 587 |
+
early = radius[progress <= 0.25]
|
| 588 |
+
mid = radius[(progress > 0.25) & (progress < 0.75)]
|
| 589 |
+
late = radius[progress >= 0.75]
|
| 590 |
+
return {
|
| 591 |
+
"radius_progress_pearson": corr,
|
| 592 |
+
"early_radius_mean": float(np.mean(early)) if early.size else float("nan"),
|
| 593 |
+
"mid_radius_mean": float(np.mean(mid)) if mid.size else float("nan"),
|
| 594 |
+
"late_radius_mean": float(np.mean(late)) if late.size else float("nan"),
|
| 595 |
+
"num_points": int(progress.size),
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
def write_csv(path: Path, records: list[dict]) -> None:
|
| 600 |
+
fields = [
|
| 601 |
+
"traj",
|
| 602 |
+
"episode_start",
|
| 603 |
+
"episode_end",
|
| 604 |
+
"row",
|
| 605 |
+
"local_t",
|
| 606 |
+
"progress",
|
| 607 |
+
"radius",
|
| 608 |
+
"x",
|
| 609 |
+
"y",
|
| 610 |
+
]
|
| 611 |
+
with path.open("w", newline="") as handle:
|
| 612 |
+
handle.write(",".join(fields) + "\n")
|
| 613 |
+
for row in records:
|
| 614 |
+
handle.write(",".join(str(row[field]) for field in fields) + "\n")
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def plot_disk(ax, records_by_traj: list[list[dict]], goal_radii: list[float]) -> None:
|
| 618 |
+
theta = np.linspace(0, 2 * np.pi, 400)
|
| 619 |
+
ax.plot(np.cos(theta), np.sin(theta), color="0.25", lw=1.1)
|
| 620 |
+
ax.axhline(0, color="0.85", lw=0.8)
|
| 621 |
+
ax.axvline(0, color="0.85", lw=0.8)
|
| 622 |
+
|
| 623 |
+
cmap = plt.get_cmap("viridis")
|
| 624 |
+
for rows in records_by_traj:
|
| 625 |
+
xy = np.asarray([[row["x"], row["y"]] for row in rows], dtype=np.float64)
|
| 626 |
+
prog = np.asarray([row["progress"] for row in rows], dtype=np.float64)
|
| 627 |
+
colors = cmap(prog)
|
| 628 |
+
for i in range(len(xy) - 1):
|
| 629 |
+
ax.plot(
|
| 630 |
+
xy[i : i + 2, 0],
|
| 631 |
+
xy[i : i + 2, 1],
|
| 632 |
+
color=colors[i],
|
| 633 |
+
alpha=0.55,
|
| 634 |
+
lw=1.5,
|
| 635 |
+
)
|
| 636 |
+
ax.scatter(xy[:, 0], xy[:, 1], c=prog, cmap="viridis", s=14, alpha=0.85)
|
| 637 |
+
if len(xy) > 3:
|
| 638 |
+
for idx in np.linspace(1, len(xy) - 2, 3).astype(int):
|
| 639 |
+
ax.annotate(
|
| 640 |
+
"",
|
| 641 |
+
xy=xy[idx + 1],
|
| 642 |
+
xytext=xy[idx],
|
| 643 |
+
arrowprops={
|
| 644 |
+
"arrowstyle": "->",
|
| 645 |
+
"color": colors[idx],
|
| 646 |
+
"lw": 1.0,
|
| 647 |
+
"alpha": 0.85,
|
| 648 |
+
},
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
goal_radius = float(np.mean(goal_radii)) if goal_radii else 0.0
|
| 652 |
+
ax.scatter(
|
| 653 |
+
[goal_radius],
|
| 654 |
+
[0.0],
|
| 655 |
+
marker="*",
|
| 656 |
+
s=260,
|
| 657 |
+
c="#ffd33d",
|
| 658 |
+
edgecolors="black",
|
| 659 |
+
linewidths=1.2,
|
| 660 |
+
zorder=10,
|
| 661 |
+
label="hindsight goal",
|
| 662 |
+
)
|
| 663 |
+
ax.set_aspect("equal")
|
| 664 |
+
ax.set_xlim(-1.03, 1.03)
|
| 665 |
+
ax.set_ylim(-1.03, 1.03)
|
| 666 |
+
ax.set_xlabel("goal direction")
|
| 667 |
+
ax.set_ylabel("orthogonal progress direction")
|
| 668 |
+
ax.set_title("Goal-aligned Poincare disk")
|
| 669 |
+
ax.legend(loc="lower right", frameon=False, fontsize=8)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def plot_radius(ax, records_by_traj: list[list[dict]]) -> None:
|
| 673 |
+
all_progress = []
|
| 674 |
+
all_radius = []
|
| 675 |
+
for rows in records_by_traj:
|
| 676 |
+
progress = np.asarray([row["progress"] for row in rows], dtype=np.float64)
|
| 677 |
+
radius = np.asarray([row["radius"] for row in rows], dtype=np.float64)
|
| 678 |
+
all_progress.append(progress)
|
| 679 |
+
all_radius.append(radius)
|
| 680 |
+
ax.plot(progress, radius, color="0.65", alpha=0.55, lw=1.0)
|
| 681 |
+
|
| 682 |
+
grid = np.linspace(0.0, 1.0, 100)
|
| 683 |
+
interp = []
|
| 684 |
+
for progress, radius in zip(all_progress, all_radius):
|
| 685 |
+
interp.append(np.interp(grid, progress, radius))
|
| 686 |
+
if interp:
|
| 687 |
+
stack = np.stack(interp, axis=0)
|
| 688 |
+
mean = stack.mean(axis=0)
|
| 689 |
+
std = stack.std(axis=0)
|
| 690 |
+
ax.plot(grid, mean, color="#d9485f", lw=2.2, label="mean")
|
| 691 |
+
ax.fill_between(grid, mean - std, mean + std, color="#d9485f", alpha=0.16)
|
| 692 |
+
|
| 693 |
+
ax.set_xlabel("normalized trajectory progress")
|
| 694 |
+
ax.set_ylabel("full Poincare radius")
|
| 695 |
+
ax.set_title("Radius should increase with progress")
|
| 696 |
+
ax.set_ylim(0.0, 1.03)
|
| 697 |
+
ax.grid(True, alpha=0.25)
|
| 698 |
+
ax.legend(frameon=False, fontsize=8)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def plot_stage_boxes(ax, records: list[dict]) -> None:
|
| 702 |
+
stages = [[], [], []]
|
| 703 |
+
for row in records:
|
| 704 |
+
progress = float(row["progress"])
|
| 705 |
+
if progress <= 0.25:
|
| 706 |
+
stages[0].append(float(row["radius"]))
|
| 707 |
+
elif progress < 0.75:
|
| 708 |
+
stages[1].append(float(row["radius"]))
|
| 709 |
+
else:
|
| 710 |
+
stages[2].append(float(row["radius"]))
|
| 711 |
+
ax.boxplot(
|
| 712 |
+
stages,
|
| 713 |
+
labels=["early", "middle", "late"],
|
| 714 |
+
patch_artist=True,
|
| 715 |
+
boxprops={"facecolor": "#d6eef7", "edgecolor": "0.35"},
|
| 716 |
+
medianprops={"color": "#d9485f", "linewidth": 1.6},
|
| 717 |
+
)
|
| 718 |
+
ax.set_ylabel("full Poincare radius")
|
| 719 |
+
ax.set_title("Radial hierarchy by stage")
|
| 720 |
+
ax.set_ylim(0.0, 1.03)
|
| 721 |
+
ax.grid(axis="y", alpha=0.25)
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def plot_3d_ball(path: Path, records_by_traj: list[list[dict]], dpi: int) -> None:
|
| 725 |
+
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
|
| 726 |
+
|
| 727 |
+
fig = plt.figure(figsize=(6.5, 6.0))
|
| 728 |
+
ax = fig.add_subplot(111, projection="3d")
|
| 729 |
+
u = np.linspace(0, 2 * np.pi, 50)
|
| 730 |
+
v = np.linspace(0, np.pi, 25)
|
| 731 |
+
x = np.outer(np.cos(u), np.sin(v))
|
| 732 |
+
y = np.outer(np.sin(u), np.sin(v))
|
| 733 |
+
z = np.outer(np.ones_like(u), np.cos(v))
|
| 734 |
+
ax.plot_wireframe(x, y, z, color="0.85", linewidth=0.4, alpha=0.45)
|
| 735 |
+
|
| 736 |
+
cmap = plt.get_cmap("viridis")
|
| 737 |
+
for rows in records_by_traj:
|
| 738 |
+
xy = np.asarray([[row["x"], row["y"]] for row in rows], dtype=np.float64)
|
| 739 |
+
radius = np.asarray([row["radius"] for row in rows], dtype=np.float64)
|
| 740 |
+
progress = np.asarray([row["progress"] for row in rows], dtype=np.float64)
|
| 741 |
+
z_coord = np.sqrt(np.maximum(radius**2 - np.sum(xy**2, axis=1), 0.0))
|
| 742 |
+
ax.plot(xy[:, 0], xy[:, 1], z_coord, color="0.2", alpha=0.35, lw=1.0)
|
| 743 |
+
ax.scatter(xy[:, 0], xy[:, 1], z_coord, c=progress, cmap="viridis", s=14)
|
| 744 |
+
|
| 745 |
+
ax.set_xlim(-1.0, 1.0)
|
| 746 |
+
ax.set_ylim(-1.0, 1.0)
|
| 747 |
+
ax.set_zlim(0.0, 1.0)
|
| 748 |
+
ax.set_xlabel("goal direction")
|
| 749 |
+
ax.set_ylabel("orthogonal direction")
|
| 750 |
+
ax.set_zlabel("remaining radius")
|
| 751 |
+
ax.set_title("Poincare ball view")
|
| 752 |
+
fig.tight_layout()
|
| 753 |
+
fig.savefig(path, dpi=dpi)
|
| 754 |
+
plt.close(fig)
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def main() -> None:
|
| 758 |
+
args = parse_args()
|
| 759 |
+
rng = np.random.default_rng(args.seed)
|
| 760 |
+
device = resolve_device(args.device)
|
| 761 |
+
|
| 762 |
+
policy_path = resolve_policy_path(args.policy)
|
| 763 |
+
config_path = resolve_config_path(policy_path, args.config)
|
| 764 |
+
cfg = OmegaConf.load(config_path)
|
| 765 |
+
dataset_path = resolve_dataset_path(cfg, args.dataset)
|
| 766 |
+
output_dir = resolve_output_dir(policy_path, args.output_dir)
|
| 767 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 768 |
+
|
| 769 |
+
with h5py.File(dataset_path, "r") as h5_file:
|
| 770 |
+
pixel_key = args.pixel_key
|
| 771 |
+
if pixel_key not in h5_file:
|
| 772 |
+
pixel_candidates = [key for key in h5_file.keys() if str(key).startswith("pixels")]
|
| 773 |
+
if not pixel_candidates:
|
| 774 |
+
raise KeyError(f"Pixel key {pixel_key!r} not found and no pixels* key exists.")
|
| 775 |
+
pixel_key = pixel_candidates[0]
|
| 776 |
+
print(f"[poincare] using pixel key {pixel_key!r}", flush=True)
|
| 777 |
+
|
| 778 |
+
action_dim = infer_action_dim(h5_file)
|
| 779 |
+
model = load_model(policy_path, cfg, action_dim=action_dim, device=device)
|
| 780 |
+
|
| 781 |
+
bounds = episode_bounds(h5_file, pixel_key)
|
| 782 |
+
candidate_windows = choose_candidate_windows(
|
| 783 |
+
bounds,
|
| 784 |
+
num_trajectories=int(args.num_trajectories),
|
| 785 |
+
candidate_episodes=int(args.candidate_episodes),
|
| 786 |
+
windows_per_episode=int(args.windows_per_episode),
|
| 787 |
+
window=int(args.window),
|
| 788 |
+
stride=int(args.stride),
|
| 789 |
+
mode=str(args.window_mode),
|
| 790 |
+
rng=rng,
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
candidate_poincare = []
|
| 794 |
+
candidate_rows = []
|
| 795 |
+
candidate_meta = []
|
| 796 |
+
candidate_scores = []
|
| 797 |
+
for candidate_idx, (ep_start, ep_end, first_row, last_row) in enumerate(candidate_windows):
|
| 798 |
+
rows = np.arange(first_row, last_row + 1, max(1, int(args.stride)), dtype=np.int64)
|
| 799 |
+
if rows[-1] != last_row:
|
| 800 |
+
rows = np.concatenate([rows, [last_row]])
|
| 801 |
+
raw_pixels = h5_file[pixel_key][rows]
|
| 802 |
+
poincare = encode_poincare(model, raw_pixels, cfg, pixel_key, device)
|
| 803 |
+
score = score_poincare_window(poincare)
|
| 804 |
+
candidate_poincare.append(poincare)
|
| 805 |
+
candidate_rows.append(rows)
|
| 806 |
+
candidate_meta.append((candidate_idx, ep_start, ep_end))
|
| 807 |
+
candidate_scores.append(score)
|
| 808 |
+
print(
|
| 809 |
+
f"[poincare] encoded candidate={candidate_idx} episode=({ep_start},{ep_end}) "
|
| 810 |
+
f"rows=({int(rows[0])},{int(rows[-1])}) points={len(rows)} "
|
| 811 |
+
f"corr={score['radius_corr']:.3f} gain={score['radius_gain']:.3f}",
|
| 812 |
+
flush=True,
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
selected_indices = select_candidate_indices(
|
| 816 |
+
candidate_scores,
|
| 817 |
+
selection=str(args.selection),
|
| 818 |
+
num_trajectories=min(int(args.num_trajectories), len(candidate_scores)),
|
| 819 |
+
rng=rng,
|
| 820 |
+
)
|
| 821 |
+
selected_set = set(selected_indices)
|
| 822 |
+
candidate_summary_rows = []
|
| 823 |
+
selected_rank = {candidate_idx: rank for rank, candidate_idx in enumerate(selected_indices)}
|
| 824 |
+
for candidate_idx, ((_, ep_start, ep_end), rows, score) in enumerate(
|
| 825 |
+
zip(candidate_meta, candidate_rows, candidate_scores)
|
| 826 |
+
):
|
| 827 |
+
candidate_summary_rows.append(
|
| 828 |
+
{
|
| 829 |
+
"candidate": int(candidate_idx),
|
| 830 |
+
"selected": int(candidate_idx in selected_set),
|
| 831 |
+
"traj": selected_rank.get(candidate_idx, ""),
|
| 832 |
+
"episode_start": int(ep_start),
|
| 833 |
+
"episode_end": int(ep_end),
|
| 834 |
+
"first_row": int(rows[0]),
|
| 835 |
+
"last_row": int(rows[-1]),
|
| 836 |
+
**score,
|
| 837 |
+
}
|
| 838 |
+
)
|
| 839 |
+
write_candidate_summary(output_dir / "candidate_window_scores.csv", candidate_summary_rows)
|
| 840 |
+
|
| 841 |
+
all_poincare = [candidate_poincare[i] for i in selected_indices]
|
| 842 |
+
row_arrays = [candidate_rows[i] for i in selected_indices]
|
| 843 |
+
meta = [
|
| 844 |
+
(display_idx, candidate_meta[candidate_idx][1], candidate_meta[candidate_idx][2])
|
| 845 |
+
for display_idx, candidate_idx in enumerate(selected_indices)
|
| 846 |
+
]
|
| 847 |
+
print(
|
| 848 |
+
"[poincare] selected candidates: "
|
| 849 |
+
+ ", ".join(
|
| 850 |
+
f"{idx}(corr={candidate_scores[idx]['radius_corr']:.3f}, "
|
| 851 |
+
f"gain={candidate_scores[idx]['radius_gain']:.3f})"
|
| 852 |
+
for idx in selected_indices
|
| 853 |
+
),
|
| 854 |
+
flush=True,
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
if args.projection == "goal_aligned":
|
| 858 |
+
coords = []
|
| 859 |
+
goal_radii = []
|
| 860 |
+
for poincare in all_poincare:
|
| 861 |
+
projected, goal_radius = project_goal_aligned(poincare)
|
| 862 |
+
coords.append(projected)
|
| 863 |
+
goal_radii.append(goal_radius)
|
| 864 |
+
else:
|
| 865 |
+
coords, goal_radii = project_global_goal_pca(all_poincare)
|
| 866 |
+
|
| 867 |
+
records = []
|
| 868 |
+
records_by_traj = []
|
| 869 |
+
for (traj_idx, ep_start, ep_end), rows, poincare, xy in zip(
|
| 870 |
+
meta, row_arrays, all_poincare, coords
|
| 871 |
+
):
|
| 872 |
+
progress = np.linspace(0.0, 1.0, len(rows), dtype=np.float64)
|
| 873 |
+
radius = np.linalg.norm(poincare, axis=1)
|
| 874 |
+
traj_records = []
|
| 875 |
+
for local_t, (row, prog, rad, point) in enumerate(zip(rows, progress, radius, xy)):
|
| 876 |
+
record = {
|
| 877 |
+
"traj": int(traj_idx),
|
| 878 |
+
"episode_start": int(ep_start),
|
| 879 |
+
"episode_end": int(ep_end),
|
| 880 |
+
"row": int(row),
|
| 881 |
+
"local_t": int(local_t),
|
| 882 |
+
"progress": float(prog),
|
| 883 |
+
"radius": float(rad),
|
| 884 |
+
"x": float(point[0]),
|
| 885 |
+
"y": float(point[1]),
|
| 886 |
+
}
|
| 887 |
+
traj_records.append(record)
|
| 888 |
+
records.append(record)
|
| 889 |
+
records_by_traj.append(traj_records)
|
| 890 |
+
|
| 891 |
+
metrics = radius_metrics(records)
|
| 892 |
+
metrics.update(
|
| 893 |
+
{
|
| 894 |
+
"policy": str(policy_path),
|
| 895 |
+
"config": str(config_path),
|
| 896 |
+
"dataset": str(dataset_path),
|
| 897 |
+
"pixel_key": str(args.pixel_key),
|
| 898 |
+
"projection": str(args.projection),
|
| 899 |
+
"selection": str(args.selection),
|
| 900 |
+
"window_mode": str(args.window_mode),
|
| 901 |
+
"num_candidates": int(len(candidate_scores)),
|
| 902 |
+
"num_trajectories": len(records_by_traj),
|
| 903 |
+
"window": int(args.window),
|
| 904 |
+
"stride": int(args.stride),
|
| 905 |
+
"goal_radius_mean": float(np.mean(goal_radii)) if goal_radii else float("nan"),
|
| 906 |
+
"goal_radius_std": float(np.std(goal_radii)) if goal_radii else float("nan"),
|
| 907 |
+
}
|
| 908 |
+
)
|
| 909 |
+
|
| 910 |
+
write_csv(output_dir / "poincare_progress_points.csv", records)
|
| 911 |
+
with (output_dir / "poincare_progress_metrics.json").open("w") as handle:
|
| 912 |
+
json.dump(metrics, handle, indent=2)
|
| 913 |
+
|
| 914 |
+
fig, axes = plt.subplots(1, 3, figsize=(15.2, 4.8), constrained_layout=True)
|
| 915 |
+
plot_disk(axes[0], records_by_traj, goal_radii)
|
| 916 |
+
plot_radius(axes[1], records_by_traj)
|
| 917 |
+
plot_stage_boxes(axes[2], records)
|
| 918 |
+
fig.suptitle("PushT goal-conditioned progress hierarchy in the Poincare ball")
|
| 919 |
+
|
| 920 |
+
figure_path = output_dir / "pusht_poincare_progress_hierarchy.png"
|
| 921 |
+
fig.savefig(figure_path, dpi=int(args.dpi))
|
| 922 |
+
fig.savefig(output_dir / "pusht_poincare_progress_hierarchy.pdf")
|
| 923 |
+
plt.close(fig)
|
| 924 |
+
|
| 925 |
+
if bool(args.plot_3d):
|
| 926 |
+
plot_3d_ball(output_dir / "pusht_poincare_progress_hierarchy_3d.png", records_by_traj, int(args.dpi))
|
| 927 |
+
|
| 928 |
+
print(f"[poincare] wrote {figure_path}", flush=True)
|
| 929 |
+
print(f"[poincare] metrics: {json.dumps(metrics, indent=2)}", flush=True)
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
if __name__ == "__main__":
|
| 933 |
+
main()
|