ProWorld / debug /debug_pusht_rollout.py
lzhts1's picture
Upload 7 files
567e51a verified
Raw
History Blame Contribute Delete
22.5 kB
#!/usr/bin/env python3
"""Measure PushT latent rollout drift under ground-truth action replay.
The script freezes a trained HyperbolicJEPA checkpoint, samples real PushT
trajectory windows, and compares autoregressive latent predictions against
encoded future frames. Teacher-forced one-step errors are reported alongside
autoregressive errors to separate local model error from compounding drift.
"""
from __future__ import annotations
import argparse
import csv
import json
import sys
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import h5py
import numpy as np
import torch
import torch.nn.functional as F
ROOT_DIR = Path(__file__).resolve().parents[1]
if str(ROOT_DIR) not in sys.path:
sys.path.insert(0, str(ROOT_DIR))
import stable_worldmodel as swm
from omegaconf import OmegaConf
from eval_hyperbolic import _load_hyperbolic_policy_model
from utils import resolve_runtime_device
IMAGENET_MEAN = torch.tensor([0.485, 0.456, 0.406], dtype=torch.float32).view(1, 3, 1, 1)
IMAGENET_STD = torch.tensor([0.229, 0.224, 0.225], dtype=torch.float32).view(1, 3, 1, 1)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--policy", required=True, help="Hyperbolic checkpoint prefix or file.")
parser.add_argument(
"--dataset",
default="pusht/pusht_expert_train",
help="PushT H5 path or stable-worldmodel cache-relative dataset name.",
)
parser.add_argument("--cache-dir", default="", help="Override the stable-worldmodel cache directory.")
parser.add_argument("--output-dir", default="", help="Output directory below cache when relative.")
parser.add_argument("--device", default="auto", help="Runtime device: auto, cuda, npu, or cpu.")
parser.add_argument("--num-sequences", type=int, default=512)
parser.add_argument("--context-blocks", type=int, default=3)
parser.add_argument("--max-blocks", type=int, default=5)
parser.add_argument("--frameskip", type=int, default=5)
parser.add_argument("--encode-batch-size", type=int, default=128)
parser.add_argument("--seed", type=int, default=42)
return parser.parse_args()
def resolve_cache_dir(cache_dir: str) -> Path:
return Path(cache_dir).expanduser() if cache_dir else Path(swm.data.utils.get_cache_dir())
def resolve_h5_path(dataset_name: str, cache_dir: Path) -> Path:
raw = Path(dataset_name).expanduser()
candidates = [raw]
if not raw.is_absolute():
candidates.extend([cache_dir / raw, cache_dir / "pusht" / raw])
expanded = []
for candidate in candidates:
expanded.append(candidate)
if candidate.suffix.lower() != ".h5":
expanded.append(Path(f"{candidate}.h5"))
seen = set()
for candidate in expanded:
candidate = candidate.resolve()
if candidate in seen:
continue
seen.add(candidate)
if candidate.is_file():
return candidate
tried = ", ".join(str(path) for path in expanded)
raise FileNotFoundError(f"Could not resolve PushT H5 dataset. Tried: {tried}")
def resolve_output_dir(args: argparse.Namespace, cache_dir: Path) -> Path:
if args.output_dir:
output_dir = Path(args.output_dir).expanduser()
return output_dir if output_dir.is_absolute() else cache_dir / output_dir
policy_stem = Path(str(args.policy).rstrip("/")).stem
return cache_dir / "debug" / "pusht_rollout" / policy_stem
def preprocess_pixels(pixels: np.ndarray, *, image_size: int, device: str) -> torch.Tensor:
tensor = torch.as_tensor(pixels)
if tensor.ndim != 4:
raise ValueError(f"Expected pixels with four dimensions, got shape={tuple(tensor.shape)}.")
if tensor.shape[-1] in {1, 3, 4}:
tensor = tensor.permute(0, 3, 1, 2)
elif tensor.shape[1] not in {1, 3, 4}:
raise ValueError(f"Could not infer pixel channel axis from shape={tuple(tensor.shape)}.")
if tensor.shape[1] == 4:
tensor = tensor[:, :3]
if tensor.shape[1] == 1:
tensor = tensor.expand(-1, 3, -1, -1)
tensor = tensor.to(device=device, dtype=torch.float32)
if pixels.dtype == np.uint8 or float(tensor.detach().amax().cpu()) > 1.5:
tensor = tensor / 255.0
if tuple(tensor.shape[-2:]) != (image_size, image_size):
tensor = F.interpolate(
tensor,
size=(image_size, image_size),
mode="bilinear",
align_corners=False,
antialias=True,
)
return (tensor - IMAGENET_MEAN.to(device)) / IMAGENET_STD.to(device)
def load_metadata(h5_file: h5py.File) -> tuple[np.ndarray, np.ndarray]:
episode_key = "episode_idx" if "episode_idx" in h5_file else "ep_idx"
if episode_key not in h5_file:
raise KeyError("Dataset must contain episode_idx or ep_idx.")
episode_idx = np.asarray(h5_file[episode_key], dtype=np.int64).reshape(-1)
if "step_idx" in h5_file:
step_idx = np.asarray(h5_file["step_idx"], dtype=np.int64).reshape(-1)
else:
step_idx = np.empty(len(episode_idx), dtype=np.int64)
for episode_id in np.unique(episode_idx):
rows = np.flatnonzero(episode_idx == episode_id)
step_idx[rows] = np.arange(len(rows), dtype=np.int64)
return episode_idx, step_idx
def build_episode_rows(episode_idx: np.ndarray, step_idx: np.ndarray) -> list[np.ndarray]:
episodes = []
for episode_id in np.unique(episode_idx):
rows = np.flatnonzero(episode_idx == episode_id)
rows = rows[np.argsort(step_idx[rows])]
if len(rows) > 1 and not np.all(np.diff(step_idx[rows]) == 1):
print(f"[debug-pusht] skipping episode={int(episode_id)} with non-contiguous step_idx", flush=True)
continue
episodes.append(rows)
return episodes
def sample_windows(
episodes: list[np.ndarray],
*,
count: int,
required_raw_steps: int,
rng: np.random.Generator,
) -> np.ndarray:
eligible = [rows for rows in episodes if len(rows) >= required_raw_steps]
if not eligible:
raise ValueError(
f"No episode contains the required {required_raw_steps} raw steps."
)
valid_counts = np.asarray([len(rows) - required_raw_steps + 1 for rows in eligible], dtype=np.int64)
cumulative = np.cumsum(valid_counts)
total = int(cumulative[-1])
if count > total:
print(
f"[debug-pusht] requested {count} windows but only {total} are available; using all.",
flush=True,
)
sampled = np.arange(total, dtype=np.int64)
else:
sampled = rng.choice(total, size=count, replace=False)
window_rows = []
for flat_index in sampled.tolist():
episode_pos = int(np.searchsorted(cumulative, flat_index, side="right"))
previous = int(cumulative[episode_pos - 1]) if episode_pos > 0 else 0
start = int(flat_index - previous)
window_rows.append(eligible[episode_pos][start : start + required_raw_steps])
return np.stack(window_rows)
def normalize_and_chunk_actions(
raw_actions: np.ndarray,
window_rows: np.ndarray,
*,
num_blocks: int,
frameskip: int,
) -> tuple[torch.Tensor, dict[str, Any]]:
actions = torch.from_numpy(np.asarray(raw_actions, dtype=np.float32).reshape(len(raw_actions), -1))
valid_actions = actions[~torch.isnan(actions).any(dim=1)]
action_mean = valid_actions.mean(dim=0, keepdim=True)
action_std = valid_actions.std(dim=0, keepdim=True).clamp_min(1e-6)
actions = torch.nan_to_num((actions - action_mean) / action_std, 0.0)
block_rows = []
for block_index in range(num_blocks):
start = block_index * frameskip
block_rows.append(window_rows[:, start : start + frameskip])
block_rows = np.stack(block_rows, axis=1)
chunks = actions[torch.from_numpy(block_rows)].reshape(len(window_rows), num_blocks, -1)
stats = {
"raw_action_dim": int(actions.shape[-1]),
"chunked_action_dim": int(chunks.shape[-1]),
"action_mean": action_mean.squeeze(0).tolist(),
"action_std": action_std.squeeze(0).tolist(),
}
return chunks, stats
def image_size_from_model(model) -> int:
value = getattr(model.encoder.config, "image_size", 224)
return int(value[0] if isinstance(value, (list, tuple)) else value)
@torch.inference_mode()
def encode_rows(
model,
h5_file: h5py.File,
rows: np.ndarray,
*,
image_size: int,
batch_size: int,
device: str,
) -> dict[str, torch.Tensor]:
unique_rows = np.unique(rows.reshape(-1))
encoded_chunks: dict[str, list[torch.Tensor]] = {
"emb": [],
"hyp_tangent": [],
"hyp_emb": [],
}
for start in range(0, len(unique_rows), batch_size):
end = min(start + batch_size, len(unique_rows))
selected_rows = unique_rows[start:end]
pixels = np.asarray(h5_file["pixels"][selected_rows])
pixel_tensor = preprocess_pixels(pixels, image_size=image_size, device=device)
encoded = model.encode({"pixels": pixel_tensor.unsqueeze(1)})
for key in encoded_chunks:
encoded_chunks[key].append(encoded[key][:, 0].float().cpu())
print(f"[debug-pusht] encoded rows {end}/{len(unique_rows)}", end="\r", flush=True)
print("", flush=True)
positions = np.searchsorted(unique_rows, rows)
positions = torch.from_numpy(positions)
return {
key: torch.cat(chunks, dim=0)[positions]
for key, chunks in encoded_chunks.items()
}
def summarize(values: torch.Tensor) -> dict[str, float]:
values = values.detach().float().cpu()
return {
"mean": float(values.mean()),
"std": float(values.std(unbiased=False)),
"median": float(values.median()),
"p90": float(torch.quantile(values, 0.90)),
}
def metric_row(
*,
block: int,
frameskip: int,
mode: str,
euclidean_mse: torch.Tensor,
tangent_mse: torch.Tensor,
lorentz_dist: torch.Tensor,
predicted_euclidean_norm: torch.Tensor,
target_euclidean_norm: torch.Tensor,
predicted_tangent_norm: torch.Tensor,
target_tangent_norm: torch.Tensor,
) -> dict[str, Any]:
return {
"block": int(block),
"raw_action_steps": int(block * frameskip),
"mode": mode,
"euclidean_mse": summarize(euclidean_mse),
"tangent_mse": summarize(tangent_mse),
"lorentz_dist": summarize(lorentz_dist),
"predicted_euclidean_norm": summarize(predicted_euclidean_norm),
"target_euclidean_norm": summarize(target_euclidean_norm),
"predicted_tangent_norm": summarize(predicted_tangent_norm),
"target_tangent_norm": summarize(target_tangent_norm),
}
def flatten_summary_row(row: dict[str, Any], *, frameskip: int) -> dict[str, Any]:
flattened = {
"block": row["block"],
"raw_action_steps": int(row["block"]) * int(frameskip),
"mode": row["mode"],
}
for metric_name, stats in row.items():
if not isinstance(stats, dict):
continue
for stat_name, value in stats.items():
flattened[f"{metric_name}_{stat_name}"] = value
return flattened
@torch.inference_mode()
def measure_rollout_drift(
model,
true_latents: dict[str, torch.Tensor],
action_chunks: torch.Tensor,
*,
context_blocks: int,
max_blocks: int,
frameskip: int,
device: str,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
true_emb = true_latents["emb"].to(device)
true_tangent = true_latents["hyp_tangent"].to(device)
true_hyp = true_latents["hyp_emb"].to(device)
action_chunks = action_chunks.to(device)
action_embeddings = model.action_encoder(action_chunks)
autoregressive_context = true_emb[:, :context_blocks].clone()
summary_rows = []
sequence_rows = []
for step_index in range(max_blocks):
block = step_index + 1
act_context = action_embeddings[:, step_index : step_index + context_blocks]
target_index = context_blocks + step_index
target_emb = true_emb[:, target_index]
target_tangent = true_tangent[:, target_index]
target_hyp = true_hyp[:, target_index]
autoregressive_pred = model.predict(
autoregressive_context[:, -context_blocks:],
act_context,
)[:, -1]
autoregressive_context = torch.cat(
[autoregressive_context, autoregressive_pred.unsqueeze(1)],
dim=1,
)
teacher_context = true_emb[:, step_index : step_index + context_blocks]
teacher_pred = model.predict(teacher_context, act_context)[:, -1]
for mode, predicted_emb in (
("autoregressive", autoregressive_pred),
("teacher_forced", teacher_pred),
):
predicted_tangent, predicted_hyp = model.to_hyperbolic(predicted_emb.unsqueeze(1))
predicted_tangent = predicted_tangent[:, 0]
predicted_hyp = predicted_hyp[:, 0]
euclidean_mse = (predicted_emb - target_emb).square().mean(dim=-1)
tangent_mse = (predicted_tangent - target_tangent).square().mean(dim=-1)
lorentz_dist = model.manifold.dist(predicted_hyp, target_hyp)
predicted_euclidean_norm = predicted_emb.norm(dim=-1)
target_euclidean_norm = target_emb.norm(dim=-1)
predicted_tangent_norm = predicted_tangent.norm(dim=-1)
target_tangent_norm = target_tangent.norm(dim=-1)
summary_rows.append(
metric_row(
block=block,
frameskip=frameskip,
mode=mode,
euclidean_mse=euclidean_mse,
tangent_mse=tangent_mse,
lorentz_dist=lorentz_dist,
predicted_euclidean_norm=predicted_euclidean_norm,
target_euclidean_norm=target_euclidean_norm,
predicted_tangent_norm=predicted_tangent_norm,
target_tangent_norm=target_tangent_norm,
)
)
for sequence_index in range(len(euclidean_mse)):
sequence_rows.append(
{
"sequence": int(sequence_index),
"block": int(block),
"raw_action_steps": int(block * frameskip),
"mode": mode,
"euclidean_mse": float(euclidean_mse[sequence_index]),
"tangent_mse": float(tangent_mse[sequence_index]),
"lorentz_dist": float(lorentz_dist[sequence_index]),
"predicted_euclidean_norm": float(predicted_euclidean_norm[sequence_index]),
"target_euclidean_norm": float(target_euclidean_norm[sequence_index]),
"predicted_tangent_norm": float(predicted_tangent_norm[sequence_index]),
"target_tangent_norm": float(target_tangent_norm[sequence_index]),
}
)
return summary_rows, sequence_rows
def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
if not rows:
return
with path.open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
def save_plot(path: Path, summary_rows: list[dict[str, Any]], *, frameskip: int) -> None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
metrics = (
("euclidean_mse", "Euclidean latent MSE"),
("tangent_mse", "Tangent latent MSE"),
("lorentz_dist", "Lorentz distance"),
)
colors = {
"autoregressive": "#d1495b",
"teacher_forced": "#00798c",
}
fig, axes = plt.subplots(1, 3, figsize=(13.2, 4.1), constrained_layout=True)
for axis, (metric_key, title) in zip(axes, metrics):
for mode in ("autoregressive", "teacher_forced"):
selected = [row for row in summary_rows if row["mode"] == mode]
x = [int(row["block"]) * int(frameskip) for row in selected]
y = [row[metric_key]["mean"] for row in selected]
yerr = [row[metric_key]["std"] for row in selected]
axis.plot(x, y, marker="o", linewidth=2, color=colors[mode], label=mode.replace("_", " "))
axis.fill_between(
x,
np.asarray(y) - np.asarray(yerr),
np.asarray(y) + np.asarray(yerr),
color=colors[mode],
alpha=0.14,
)
axis.set_title(title)
axis.set_xlabel("oracle action replay steps")
axis.grid(alpha=0.25)
axes[0].set_ylabel("error")
axes[-1].legend(frameon=False)
fig.savefig(path, dpi=180)
plt.close(fig)
def json_ready(value: Any) -> Any:
if isinstance(value, dict):
return {str(key): json_ready(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [json_ready(item) for item in value]
if isinstance(value, np.ndarray):
return value.tolist()
if isinstance(value, np.generic):
return value.item()
return value
def load_model(
*,
policy: str,
cache_dir: Path,
action_dim: int,
device: str,
):
cfg = OmegaConf.create(
{
"cache_dir": str(cache_dir),
"policy": policy,
"checkpoint": {
"force_rebuild": True,
"strict": True,
},
}
)
dataset_stub = SimpleNamespace(get_dim=lambda key: action_dim)
return _load_hyperbolic_policy_model(cfg, dataset_stub, device)
def main() -> None:
args = parse_args()
if args.context_blocks < 1 or args.max_blocks < 1 or args.frameskip < 1:
raise ValueError("context-blocks, max-blocks, and frameskip must be positive.")
cache_dir = resolve_cache_dir(args.cache_dir)
h5_path = resolve_h5_path(args.dataset, cache_dir)
output_dir = resolve_output_dir(args, cache_dir)
output_dir.mkdir(parents=True, exist_ok=True)
runtime_device = resolve_runtime_device(args.device)
rng = np.random.default_rng(args.seed)
print(f"[debug-pusht] device={runtime_device}", flush=True)
print(f"[debug-pusht] dataset={h5_path}", flush=True)
print(f"[debug-pusht] policy={args.policy}", flush=True)
with h5py.File(h5_path, "r") as h5_file:
if "pixels" not in h5_file or "action" not in h5_file:
raise KeyError("Dataset must contain pixels and action.")
episode_idx, step_idx = load_metadata(h5_file)
episodes = build_episode_rows(episode_idx, step_idx)
raw_actions = np.asarray(h5_file["action"], dtype=np.float32)
action_dim = int(raw_actions.reshape(len(raw_actions), -1).shape[-1])
model = load_model(
policy=args.policy,
cache_dir=cache_dir,
action_dim=action_dim,
device=runtime_device,
)
image_size = image_size_from_model(model)
required_raw_steps = (args.context_blocks + args.max_blocks - 1) * args.frameskip + 1
window_rows = sample_windows(
episodes,
count=args.num_sequences,
required_raw_steps=required_raw_steps,
rng=rng,
)
observation_rows = window_rows[
:,
np.arange(args.context_blocks + args.max_blocks) * args.frameskip,
]
true_latents = encode_rows(
model,
h5_file,
observation_rows,
image_size=image_size,
batch_size=args.encode_batch_size,
device=runtime_device,
)
action_chunks, action_stats = normalize_and_chunk_actions(
raw_actions,
window_rows,
num_blocks=args.context_blocks + args.max_blocks - 1,
frameskip=args.frameskip,
)
expected_action_dim = int(model.action_encoder.patch_embed.in_channels)
if int(action_chunks.shape[-1]) != expected_action_dim:
raise ValueError(
f"Chunked action dim={int(action_chunks.shape[-1])}, but model expects "
f"{expected_action_dim}. Check --frameskip and the dataset action protocol."
)
summary_rows, sequence_rows = measure_rollout_drift(
model,
true_latents,
action_chunks,
context_blocks=args.context_blocks,
max_blocks=args.max_blocks,
frameskip=args.frameskip,
device=runtime_device,
)
flattened_summary = [
flatten_summary_row(row, frameskip=args.frameskip)
for row in summary_rows
]
summary = {
"policy": args.policy,
"dataset": str(h5_path),
"device": runtime_device,
"num_sequences": int(len(window_rows)),
"context_blocks": int(args.context_blocks),
"max_blocks": int(args.max_blocks),
"frameskip": int(args.frameskip),
"raw_steps_per_max_rollout": int(args.max_blocks * args.frameskip),
"required_raw_steps_per_window": int(required_raw_steps),
"image_size": int(image_size),
"action": action_stats,
"sampled_start_rows": window_rows[:, 0].tolist(),
"metrics": summary_rows,
}
summary_path = output_dir / "rollout_drift_summary.json"
summary_csv_path = output_dir / "rollout_drift_summary.csv"
sequence_csv_path = output_dir / "rollout_drift_per_sequence.csv"
plot_path = output_dir / "rollout_drift.png"
summary_path.write_text(json.dumps(json_ready(summary), indent=2), encoding="utf-8")
write_csv(summary_csv_path, flattened_summary)
write_csv(sequence_csv_path, sequence_rows)
save_plot(plot_path, summary_rows, frameskip=args.frameskip)
print(f"[debug-pusht] wrote {summary_path}", flush=True)
print(f"[debug-pusht] wrote {summary_csv_path}", flush=True)
print(f"[debug-pusht] wrote {sequence_csv_path}", flush=True)
print(f"[debug-pusht] wrote {plot_path}", flush=True)
for row in flattened_summary:
print(
f"[debug-pusht] mode={row['mode']:<14} block={row['block']} "
f"raw_steps={row['raw_action_steps']:>2} "
f"euc_mse={row['euclidean_mse_mean']:.6f} "
f"tan_mse={row['tangent_mse_mean']:.6f} "
f"lorentz={row['lorentz_dist_mean']:.6f}",
flush=True,
)
if __name__ == "__main__":
main()