File size: 22,527 Bytes
567e51a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 | #!/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()
|