#!/usr/bin/env python """Visualize PushT progress hierarchy in the Poincare ball. Example: python debug/visualize_pusht_poincare_hierarchy.py \ --policy /data_nvme/user/zliu681/le-wm-main/lewm_cache/pusht/hyperbolic_pusht_stable_trial2/lewm_hyperbolic_pusht_stable_epoch_10_state.ckpt \ --num-trajectories 8 \ --window 80 """ from __future__ import annotations import argparse import json import sys from pathlib import Path import h5py import matplotlib.pyplot as plt import numpy as np import torch import torch.nn.functional as F from omegaconf import OmegaConf, open_dict REPO_ROOT = Path(__file__).resolve().parents[1] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) import stable_worldmodel as swm # noqa: E402 from train_hyperbolic import ( # noqa: E402 build_hyperbolic_world_model, ensure_hyperbolic_defaults, ) from utils import get_img_preprocessor # noqa: E402 def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Draw goal-conditioned PushT Poincare progress hierarchy.", ) parser.add_argument( "--policy", required=True, help="Path to a hyperbolic *_state.ckpt, *_weights.ckpt, *_object.ckpt, or run directory.", ) parser.add_argument( "--config", default=None, help="Optional config.yaml path. By default, use config.yaml beside the checkpoint.", ) parser.add_argument( "--dataset", default=None, help="Optional h5 dataset path. By default, resolve cfg.data.dataset.name under lewm_cache.", ) parser.add_argument("--pixel-key", default="pixels") parser.add_argument("--num-trajectories", type=int, default=8) parser.add_argument( "--candidate-episodes", type=int, default=48, help="Number of episodes to scan before selecting representative windows.", ) parser.add_argument( "--windows-per-episode", type=int, default=4, help="Only used with --window-mode scan.", ) parser.add_argument("--window", type=int, default=80) parser.add_argument("--stride", type=int, default=2) parser.add_argument("--seed", type=int, default=0) parser.add_argument( "--window-mode", choices=("scan", "tail", "random"), default="scan", help=( "scan searches several subwindows per episode; tail uses the final window; " "random samples one window inside each episode." ), ) parser.add_argument( "--selection", choices=("radius_corr", "radius_gain", "random"), default="radius_corr", help="How to select final displayed windows from candidates.", ) parser.add_argument( "--projection", choices=("goal_aligned", "global_goal_pca"), default="goal_aligned", help=( "goal_aligned maps each hindsight goal to +x independently; " "global_goal_pca uses the first goal direction and one global orthogonal PCA axis." ), ) parser.add_argument("--device", default="auto") parser.add_argument( "--output-dir", default=None, help="Default: lewm_cache/debug/pusht_poincare_hierarchy/", ) parser.add_argument("--dpi", type=int, default=220) parser.add_argument("--plot-3d", action="store_true") return parser.parse_args() def resolve_device(device: str) -> torch.device: if device == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") return torch.device(device) def resolve_policy_path(policy: str) -> Path: path = Path(policy) if path.is_dir(): candidates = sorted(path.glob("*_state.ckpt")) candidates += sorted(path.glob("*_weights.ckpt")) candidates += sorted(path.glob("*.ckpt")) if not candidates: raise FileNotFoundError(f"No checkpoint found under policy directory: {path}") return candidates[-1] if path.name.endswith("_object.ckpt"): state_path = path.with_name(path.name.replace("_object.ckpt", "_state.ckpt")) if state_path.exists(): return state_path weights_path = path.with_name(path.name.replace("_object.ckpt", "_weights.ckpt")) if weights_path.exists(): return weights_path return path def resolve_config_path(policy_path: Path, config_arg: str | None) -> Path: if config_arg is not None: config_path = Path(config_arg) else: config_path = policy_path.parent / "config.yaml" if not config_path.exists(): raise FileNotFoundError( f"Could not find config.yaml at {config_path}. Pass --config explicitly." ) return config_path def resolve_dataset_path(cfg, dataset_arg: str | None) -> Path: if dataset_arg: dataset_path = Path(dataset_arg) if dataset_path.exists(): return dataset_path raise FileNotFoundError(f"Dataset path does not exist: {dataset_path}") dataset_name = str(cfg.data.dataset.name).replace("\\", "/") cache_dir = Path(swm.data.utils.get_cache_dir()) candidates = [ cache_dir / f"{dataset_name}.h5", cache_dir / dataset_name, ] for candidate in candidates: if candidate.exists(): return candidate raise FileNotFoundError( "Could not resolve dataset from cfg.data.dataset.name=" f"{dataset_name!r}. Tried: {', '.join(str(c) for c in candidates)}" ) def resolve_output_dir(policy_path: Path, output_dir: str | None) -> Path: if output_dir: return Path(output_dir) cache_dir = Path(swm.data.utils.get_cache_dir()) return cache_dir / "debug" / "pusht_poincare_hierarchy" / policy_path.stem def infer_action_dim(h5_file: h5py.File) -> int: if "action" not in h5_file: raise KeyError("Expected action key in dataset to infer action_dim.") action_shape = h5_file["action"].shape if len(action_shape) < 2: raise ValueError(f"Unexpected action shape: {action_shape}") return int(action_shape[-1]) def load_model(policy_path: Path, cfg, action_dim: int, device: torch.device): ensure_hyperbolic_defaults(cfg) with open_dict(cfg): cfg.wm.action_dim = int(action_dim) model = build_hyperbolic_world_model(cfg, action_dim=int(action_dim)) checkpoint = torch.load(policy_path, map_location="cpu", weights_only=False) if hasattr(checkpoint, "state_dict"): state = checkpoint.state_dict() elif isinstance(checkpoint, dict) and "model_state_dict" in checkpoint: state = checkpoint["model_state_dict"] elif isinstance(checkpoint, dict) and "state_dict" in checkpoint: state = checkpoint["state_dict"] elif isinstance(checkpoint, dict) and all(torch.is_tensor(v) for v in checkpoint.values()): state = checkpoint else: raise TypeError( "Unsupported checkpoint format. Prefer a portable *_state.ckpt checkpoint." ) stripped = {} for key, value in state.items(): if key.startswith("model."): stripped[key[len("model.") :]] = value else: stripped[key] = value missing, unexpected = model.load_state_dict(stripped, strict=False) print( f"[poincare] loaded {policy_path} | " f"missing={len(missing)} unexpected={len(unexpected)}", flush=True, ) if missing: print(f"[poincare] first missing keys: {missing[:8]}", flush=True) if unexpected: print(f"[poincare] first unexpected keys: {unexpected[:8]}", flush=True) return model.to(device).eval() def dataset_length(h5_file: h5py.File, pixel_key: str) -> int: if pixel_key in h5_file: return int(h5_file[pixel_key].shape[0]) for key in h5_file.keys(): value = h5_file[key] if isinstance(value, h5py.Dataset) and len(value.shape) > 0: return int(value.shape[0]) raise ValueError("Could not infer dataset length.") def episode_bounds(h5_file: h5py.File, pixel_key: str) -> list[tuple[int, int]]: total = dataset_length(h5_file, pixel_key) if "ep_offset" in h5_file and "ep_len" in h5_file: starts = np.asarray(h5_file["ep_offset"][:], dtype=np.int64).reshape(-1) lengths = np.asarray(h5_file["ep_len"][:], dtype=np.int64).reshape(-1) if starts.shape == lengths.shape: ends = starts + lengths bounds = [ (int(start), int(end)) for start, end in zip(starts, ends) if 0 <= int(start) < int(end) <= total ] if bounds: return bounds for key in ("episode_ends", "episode_end", "ends"): if key in h5_file: ends = np.asarray(h5_file[key][:], dtype=np.int64) starts = np.concatenate([[0], ends[:-1]]) return [(int(s), int(e)) for s, e in zip(starts, ends) if int(e) > int(s)] if "episode_idx" in h5_file: episode_idx = np.asarray(h5_file["episode_idx"][:], dtype=np.int64).reshape(-1) if episode_idx.shape[0] == total: change_points = np.flatnonzero(episode_idx[1:] != episode_idx[:-1]) + 1 ends = np.concatenate([change_points, [total]]).astype(np.int64) starts = np.concatenate([[0], ends[:-1]]) bounds = [ (int(start), int(end)) for start, end in zip(starts, ends) if int(end) > int(start) ] if bounds: return bounds if "step_idx" in h5_file: step_idx = np.asarray(h5_file["step_idx"][:], dtype=np.int64).reshape(-1) if step_idx.shape[0] == total: starts = np.flatnonzero(step_idx == 0).astype(np.int64) if starts.size: ends = np.concatenate([starts[1:], [total]]).astype(np.int64) bounds = [ (int(start), int(end)) for start, end in zip(starts, ends) if int(end) > int(start) ] if bounds: return bounds done = np.zeros(total, dtype=bool) found_done = False for key in ("terminals", "terminal", "timeouts", "timeout", "dones", "done"): if key in h5_file: value = np.asarray(h5_file[key][:], dtype=bool).reshape(-1) if value.shape[0] == total: done |= value found_done = True if found_done: ends = (np.flatnonzero(done) + 1).astype(np.int64) if len(ends) == 0 or int(ends[-1]) != total: ends = np.concatenate([ends, [total]]) starts = np.concatenate([[0], ends[:-1]]) return [(int(s), int(e)) for s, e in zip(starts, ends) if int(e) > int(s)] return [(0, total)] def choose_candidate_windows( bounds: list[tuple[int, int]], *, num_trajectories: int, candidate_episodes: int, windows_per_episode: int, window: int, stride: int, mode: str, rng: np.random.Generator, ) -> list[tuple[int, int, int, int]]: min_len = max(2, int(window)) valid = [(s, e) for s, e in bounds if e - s >= min_len] if not valid: raise ValueError( f"No episode is long enough for window={window}. " f"Longest episode length={max((e - s for s, e in bounds), default=0)}" ) sample_count = num_trajectories if mode != "scan" else max(num_trajectories, candidate_episodes) order = rng.permutation(len(valid))[: min(sample_count, len(valid))] windows = [] for local_idx in order: ep_start, ep_end = valid[int(local_idx)] max_start = ep_end - window if mode == "scan": if windows_per_episode <= 1: starts = [max_start] else: starts = np.linspace( ep_start, max_start, num=max(1, int(windows_per_episode)), ).round().astype(np.int64) starts = list(dict.fromkeys(int(s) for s in starts)) elif mode == "tail": starts = [max_start] else: starts = [int(rng.integers(ep_start, max_start + 1))] for start in starts: start = int(max(ep_start, min(start, max_start))) end = start + window rows = np.arange(start, end, max(1, int(stride)), dtype=np.int64) if rows[-1] != end - 1: rows = np.concatenate([rows, [end - 1]]) windows.append((ep_start, ep_end, int(rows[0]), int(rows[-1]))) unique = [] seen = set() for item in windows: if item not in seen: seen.add(item) unique.append(item) return unique def score_poincare_window(poincare: np.ndarray) -> dict[str, float]: progress = np.linspace(0.0, 1.0, poincare.shape[0], dtype=np.float64) radius = np.linalg.norm(poincare, axis=1) if radius.size < 2 or np.std(radius) < 1e-8: corr = float("nan") else: corr = float(np.corrcoef(progress, radius)[0, 1]) early = radius[progress <= 0.25] late = radius[progress >= 0.75] early_mean = float(np.mean(early)) if early.size else float("nan") late_mean = float(np.mean(late)) if late.size else float("nan") return { "radius_corr": corr, "radius_gain": late_mean - early_mean, "early_radius": early_mean, "late_radius": late_mean, "radius_min": float(np.min(radius)), "radius_max": float(np.max(radius)), "radius_spread": float(np.max(radius) - np.min(radius)), "goal_radius": float(np.linalg.norm(poincare[-1])), } def select_candidate_indices( candidate_scores: list[dict[str, float]], *, selection: str, num_trajectories: int, rng: np.random.Generator, ) -> list[int]: if selection == "random": order = rng.permutation(len(candidate_scores)) return [int(i) for i in order[:num_trajectories]] def finite(value: float, fallback: float = -1e9) -> float: return float(value) if np.isfinite(value) else fallback if selection == "radius_gain": key = lambda i: ( finite(candidate_scores[i]["radius_gain"]), finite(candidate_scores[i]["radius_corr"]), finite(candidate_scores[i]["radius_spread"]), ) else: key = lambda i: ( finite(candidate_scores[i]["radius_corr"]), finite(candidate_scores[i]["radius_gain"]), finite(candidate_scores[i]["radius_spread"]), ) ranked = sorted(range(len(candidate_scores)), key=key, reverse=True) return [int(i) for i in ranked[:num_trajectories]] def write_candidate_summary(path: Path, rows: list[dict]) -> None: fields = [ "candidate", "selected", "traj", "episode_start", "episode_end", "first_row", "last_row", "radius_corr", "radius_gain", "early_radius", "late_radius", "radius_min", "radius_max", "radius_spread", "goal_radius", ] with path.open("w", newline="") as handle: handle.write(",".join(fields) + "\n") for row in rows: handle.write(",".join(str(row.get(field, "")) for field in fields) + "\n") def pixel_tensor(raw: np.ndarray) -> torch.Tensor: x = torch.from_numpy(np.asarray(raw)) if x.ndim != 4: raise ValueError(f"Expected pixels with 4 dims, got shape={tuple(x.shape)}") if x.shape[-1] in (1, 3): x = x.permute(0, 3, 1, 2) return x.contiguous() def preprocess_pixels(raw_pixels: np.ndarray, cfg, pixel_key: str) -> torch.Tensor: pixels = pixel_tensor(raw_pixels) transform = get_img_preprocessor( source=pixel_key, target="pixels", img_size=int(cfg.img_size), resize=True, ) try: return transform({pixel_key: pixels})["pixels"] except Exception as exc: print( "[poincare] get_img_preprocessor failed; using simple float resize fallback. " f"Reason: {exc}", flush=True, ) pixels = pixels.float() if pixels.max() > 1.5: pixels = pixels / 255.0 return F.interpolate( pixels, size=(int(cfg.img_size), int(cfg.img_size)), mode="bilinear", align_corners=False, ) def encoder_features(model, pixels: torch.Tensor) -> torch.Tensor: output = model.encoder(pixels) if torch.is_tensor(output): return output if hasattr(output, "last_hidden_state"): hidden = output.last_hidden_state if hidden.ndim == 3: return hidden[:, 0] return hidden if hasattr(output, "pooler_output") and output.pooler_output is not None: return output.pooler_output if isinstance(output, (tuple, list)) and output: first = output[0] if torch.is_tensor(first) and first.ndim == 3: return first[:, 0] return first raise TypeError(f"Unsupported encoder output type: {type(output)!r}") @torch.no_grad() def encode_poincare( model, raw_pixels: np.ndarray, cfg, pixel_key: str, device: torch.device, chunk_size: int = 32, ) -> np.ndarray: pixels = preprocess_pixels(raw_pixels, cfg, pixel_key) poincare_chunks = [] for start in range(0, pixels.size(0), chunk_size): batch = pixels[start : start + chunk_size].to(device) features = encoder_features(model, batch) emb = model.projector(features) hyperbolic = model.to_hyperbolic(emb) if isinstance(hyperbolic, tuple): hyp = hyperbolic[-1] else: hyp = hyperbolic poincare = model.manifold.to_poincare(hyp) poincare_chunks.append(poincare.detach().cpu().float().numpy()) return np.concatenate(poincare_chunks, axis=0) def unit(v: np.ndarray, eps: float = 1e-8) -> np.ndarray: norm = float(np.linalg.norm(v)) if norm < eps: out = np.zeros_like(v) out[0] = 1.0 return out return v / norm def first_principal_axis(x: np.ndarray, fallback: np.ndarray) -> np.ndarray: if x.shape[0] < 2 or np.allclose(x, 0.0): return fallback centered = x - x.mean(axis=0, keepdims=True) try: _, _, vh = np.linalg.svd(centered, full_matrices=False) return unit(vh[0]) except np.linalg.LinAlgError: return fallback def project_goal_aligned(p: np.ndarray) -> tuple[np.ndarray, float]: goal = p[-1] x_axis = unit(goal) x = p @ x_axis residual = p - x[:, None] * x_axis[None, :] fallback = np.zeros_like(x_axis) fallback[0] = 1.0 if abs(float(np.dot(fallback, x_axis))) > 0.9 and fallback.size > 1: fallback = np.zeros_like(x_axis) fallback[1] = 1.0 fallback = unit(fallback - np.dot(fallback, x_axis) * x_axis) y_axis = first_principal_axis(residual, fallback) y_axis = unit(y_axis - np.dot(y_axis, x_axis) * x_axis) y = p @ y_axis if y[-1] < 0: y = -y return np.stack([x, y], axis=1), float(np.linalg.norm(goal)) def project_global_goal_pca(all_p: list[np.ndarray]) -> tuple[list[np.ndarray], list[float]]: goals = np.stack([p[-1] for p in all_p], axis=0) x_axis = unit(goals.mean(axis=0)) residuals = [] for p in all_p: x = p @ x_axis residuals.append(p - x[:, None] * x_axis[None, :]) y_axis = first_principal_axis(np.concatenate(residuals, axis=0), np.roll(x_axis, 1)) y_axis = unit(y_axis - np.dot(y_axis, x_axis) * x_axis) coords = [] goal_radii = [] for p in all_p: coords.append(np.stack([p @ x_axis, p @ y_axis], axis=1)) goal_radii.append(float(np.linalg.norm(p[-1]))) return coords, goal_radii def radius_metrics(records: list[dict]) -> dict: progress = np.asarray([row["progress"] for row in records], dtype=np.float64) radius = np.asarray([row["radius"] for row in records], dtype=np.float64) if progress.size < 2 or np.std(radius) < 1e-8: corr = float("nan") else: corr = float(np.corrcoef(progress, radius)[0, 1]) early = radius[progress <= 0.25] mid = radius[(progress > 0.25) & (progress < 0.75)] late = radius[progress >= 0.75] return { "radius_progress_pearson": corr, "early_radius_mean": float(np.mean(early)) if early.size else float("nan"), "mid_radius_mean": float(np.mean(mid)) if mid.size else float("nan"), "late_radius_mean": float(np.mean(late)) if late.size else float("nan"), "num_points": int(progress.size), } def write_csv(path: Path, records: list[dict]) -> None: fields = [ "traj", "episode_start", "episode_end", "row", "local_t", "progress", "radius", "x", "y", ] with path.open("w", newline="") as handle: handle.write(",".join(fields) + "\n") for row in records: handle.write(",".join(str(row[field]) for field in fields) + "\n") def plot_disk(ax, records_by_traj: list[list[dict]], goal_radii: list[float]) -> None: theta = np.linspace(0, 2 * np.pi, 400) ax.plot(np.cos(theta), np.sin(theta), color="0.25", lw=1.1) ax.axhline(0, color="0.85", lw=0.8) ax.axvline(0, color="0.85", lw=0.8) cmap = plt.get_cmap("viridis") for rows in records_by_traj: xy = np.asarray([[row["x"], row["y"]] for row in rows], dtype=np.float64) prog = np.asarray([row["progress"] for row in rows], dtype=np.float64) colors = cmap(prog) for i in range(len(xy) - 1): ax.plot( xy[i : i + 2, 0], xy[i : i + 2, 1], color=colors[i], alpha=0.55, lw=1.5, ) ax.scatter(xy[:, 0], xy[:, 1], c=prog, cmap="viridis", s=14, alpha=0.85) if len(xy) > 3: for idx in np.linspace(1, len(xy) - 2, 3).astype(int): ax.annotate( "", xy=xy[idx + 1], xytext=xy[idx], arrowprops={ "arrowstyle": "->", "color": colors[idx], "lw": 1.0, "alpha": 0.85, }, ) goal_radius = float(np.mean(goal_radii)) if goal_radii else 0.0 ax.scatter( [goal_radius], [0.0], marker="*", s=260, c="#ffd33d", edgecolors="black", linewidths=1.2, zorder=10, label="hindsight goal", ) ax.set_aspect("equal") ax.set_xlim(-1.03, 1.03) ax.set_ylim(-1.03, 1.03) ax.set_xlabel("goal direction") ax.set_ylabel("orthogonal progress direction") ax.set_title("Goal-aligned Poincare disk") ax.legend(loc="lower right", frameon=False, fontsize=8) def plot_radius(ax, records_by_traj: list[list[dict]]) -> None: all_progress = [] all_radius = [] for rows in records_by_traj: progress = np.asarray([row["progress"] for row in rows], dtype=np.float64) radius = np.asarray([row["radius"] for row in rows], dtype=np.float64) all_progress.append(progress) all_radius.append(radius) ax.plot(progress, radius, color="0.65", alpha=0.55, lw=1.0) grid = np.linspace(0.0, 1.0, 100) interp = [] for progress, radius in zip(all_progress, all_radius): interp.append(np.interp(grid, progress, radius)) if interp: stack = np.stack(interp, axis=0) mean = stack.mean(axis=0) std = stack.std(axis=0) ax.plot(grid, mean, color="#d9485f", lw=2.2, label="mean") ax.fill_between(grid, mean - std, mean + std, color="#d9485f", alpha=0.16) ax.set_xlabel("normalized trajectory progress") ax.set_ylabel("full Poincare radius") ax.set_title("Radius should increase with progress") ax.set_ylim(0.0, 1.03) ax.grid(True, alpha=0.25) ax.legend(frameon=False, fontsize=8) def plot_stage_boxes(ax, records: list[dict]) -> None: stages = [[], [], []] for row in records: progress = float(row["progress"]) if progress <= 0.25: stages[0].append(float(row["radius"])) elif progress < 0.75: stages[1].append(float(row["radius"])) else: stages[2].append(float(row["radius"])) ax.boxplot( stages, labels=["early", "middle", "late"], patch_artist=True, boxprops={"facecolor": "#d6eef7", "edgecolor": "0.35"}, medianprops={"color": "#d9485f", "linewidth": 1.6}, ) ax.set_ylabel("full Poincare radius") ax.set_title("Radial hierarchy by stage") ax.set_ylim(0.0, 1.03) ax.grid(axis="y", alpha=0.25) def plot_3d_ball(path: Path, records_by_traj: list[list[dict]], dpi: int) -> None: from mpl_toolkits.mplot3d import Axes3D # noqa: F401 fig = plt.figure(figsize=(6.5, 6.0)) ax = fig.add_subplot(111, projection="3d") u = np.linspace(0, 2 * np.pi, 50) v = np.linspace(0, np.pi, 25) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones_like(u), np.cos(v)) ax.plot_wireframe(x, y, z, color="0.85", linewidth=0.4, alpha=0.45) cmap = plt.get_cmap("viridis") for rows in records_by_traj: xy = np.asarray([[row["x"], row["y"]] for row in rows], dtype=np.float64) radius = np.asarray([row["radius"] for row in rows], dtype=np.float64) progress = np.asarray([row["progress"] for row in rows], dtype=np.float64) z_coord = np.sqrt(np.maximum(radius**2 - np.sum(xy**2, axis=1), 0.0)) ax.plot(xy[:, 0], xy[:, 1], z_coord, color="0.2", alpha=0.35, lw=1.0) ax.scatter(xy[:, 0], xy[:, 1], z_coord, c=progress, cmap="viridis", s=14) ax.set_xlim(-1.0, 1.0) ax.set_ylim(-1.0, 1.0) ax.set_zlim(0.0, 1.0) ax.set_xlabel("goal direction") ax.set_ylabel("orthogonal direction") ax.set_zlabel("remaining radius") ax.set_title("Poincare ball view") fig.tight_layout() fig.savefig(path, dpi=dpi) plt.close(fig) def main() -> None: args = parse_args() rng = np.random.default_rng(args.seed) device = resolve_device(args.device) policy_path = resolve_policy_path(args.policy) config_path = resolve_config_path(policy_path, args.config) cfg = OmegaConf.load(config_path) dataset_path = resolve_dataset_path(cfg, args.dataset) output_dir = resolve_output_dir(policy_path, args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) with h5py.File(dataset_path, "r") as h5_file: pixel_key = args.pixel_key if pixel_key not in h5_file: pixel_candidates = [key for key in h5_file.keys() if str(key).startswith("pixels")] if not pixel_candidates: raise KeyError(f"Pixel key {pixel_key!r} not found and no pixels* key exists.") pixel_key = pixel_candidates[0] print(f"[poincare] using pixel key {pixel_key!r}", flush=True) action_dim = infer_action_dim(h5_file) model = load_model(policy_path, cfg, action_dim=action_dim, device=device) bounds = episode_bounds(h5_file, pixel_key) candidate_windows = choose_candidate_windows( bounds, num_trajectories=int(args.num_trajectories), candidate_episodes=int(args.candidate_episodes), windows_per_episode=int(args.windows_per_episode), window=int(args.window), stride=int(args.stride), mode=str(args.window_mode), rng=rng, ) candidate_poincare = [] candidate_rows = [] candidate_meta = [] candidate_scores = [] for candidate_idx, (ep_start, ep_end, first_row, last_row) in enumerate(candidate_windows): rows = np.arange(first_row, last_row + 1, max(1, int(args.stride)), dtype=np.int64) if rows[-1] != last_row: rows = np.concatenate([rows, [last_row]]) raw_pixels = h5_file[pixel_key][rows] poincare = encode_poincare(model, raw_pixels, cfg, pixel_key, device) score = score_poincare_window(poincare) candidate_poincare.append(poincare) candidate_rows.append(rows) candidate_meta.append((candidate_idx, ep_start, ep_end)) candidate_scores.append(score) print( f"[poincare] encoded candidate={candidate_idx} episode=({ep_start},{ep_end}) " f"rows=({int(rows[0])},{int(rows[-1])}) points={len(rows)} " f"corr={score['radius_corr']:.3f} gain={score['radius_gain']:.3f}", flush=True, ) selected_indices = select_candidate_indices( candidate_scores, selection=str(args.selection), num_trajectories=min(int(args.num_trajectories), len(candidate_scores)), rng=rng, ) selected_set = set(selected_indices) candidate_summary_rows = [] selected_rank = {candidate_idx: rank for rank, candidate_idx in enumerate(selected_indices)} for candidate_idx, ((_, ep_start, ep_end), rows, score) in enumerate( zip(candidate_meta, candidate_rows, candidate_scores) ): candidate_summary_rows.append( { "candidate": int(candidate_idx), "selected": int(candidate_idx in selected_set), "traj": selected_rank.get(candidate_idx, ""), "episode_start": int(ep_start), "episode_end": int(ep_end), "first_row": int(rows[0]), "last_row": int(rows[-1]), **score, } ) write_candidate_summary(output_dir / "candidate_window_scores.csv", candidate_summary_rows) all_poincare = [candidate_poincare[i] for i in selected_indices] row_arrays = [candidate_rows[i] for i in selected_indices] meta = [ (display_idx, candidate_meta[candidate_idx][1], candidate_meta[candidate_idx][2]) for display_idx, candidate_idx in enumerate(selected_indices) ] print( "[poincare] selected candidates: " + ", ".join( f"{idx}(corr={candidate_scores[idx]['radius_corr']:.3f}, " f"gain={candidate_scores[idx]['radius_gain']:.3f})" for idx in selected_indices ), flush=True, ) if args.projection == "goal_aligned": coords = [] goal_radii = [] for poincare in all_poincare: projected, goal_radius = project_goal_aligned(poincare) coords.append(projected) goal_radii.append(goal_radius) else: coords, goal_radii = project_global_goal_pca(all_poincare) records = [] records_by_traj = [] for (traj_idx, ep_start, ep_end), rows, poincare, xy in zip( meta, row_arrays, all_poincare, coords ): progress = np.linspace(0.0, 1.0, len(rows), dtype=np.float64) radius = np.linalg.norm(poincare, axis=1) traj_records = [] for local_t, (row, prog, rad, point) in enumerate(zip(rows, progress, radius, xy)): record = { "traj": int(traj_idx), "episode_start": int(ep_start), "episode_end": int(ep_end), "row": int(row), "local_t": int(local_t), "progress": float(prog), "radius": float(rad), "x": float(point[0]), "y": float(point[1]), } traj_records.append(record) records.append(record) records_by_traj.append(traj_records) metrics = radius_metrics(records) metrics.update( { "policy": str(policy_path), "config": str(config_path), "dataset": str(dataset_path), "pixel_key": str(args.pixel_key), "projection": str(args.projection), "selection": str(args.selection), "window_mode": str(args.window_mode), "num_candidates": int(len(candidate_scores)), "num_trajectories": len(records_by_traj), "window": int(args.window), "stride": int(args.stride), "goal_radius_mean": float(np.mean(goal_radii)) if goal_radii else float("nan"), "goal_radius_std": float(np.std(goal_radii)) if goal_radii else float("nan"), } ) write_csv(output_dir / "poincare_progress_points.csv", records) with (output_dir / "poincare_progress_metrics.json").open("w") as handle: json.dump(metrics, handle, indent=2) fig, axes = plt.subplots(1, 3, figsize=(15.2, 4.8), constrained_layout=True) plot_disk(axes[0], records_by_traj, goal_radii) plot_radius(axes[1], records_by_traj) plot_stage_boxes(axes[2], records) fig.suptitle("PushT goal-conditioned progress hierarchy in the Poincare ball") figure_path = output_dir / "pusht_poincare_progress_hierarchy.png" fig.savefig(figure_path, dpi=int(args.dpi)) fig.savefig(output_dir / "pusht_poincare_progress_hierarchy.pdf") plt.close(fig) if bool(args.plot_3d): plot_3d_ball(output_dir / "pusht_poincare_progress_hierarchy_3d.png", records_by_traj, int(args.dpi)) print(f"[poincare] wrote {figure_path}", flush=True) print(f"[poincare] metrics: {json.dumps(metrics, indent=2)}", flush=True) if __name__ == "__main__": main()