| |
| """ |
| Offline physical probing for HyperbolicJEPA checkpoints. |
| |
| The world model is frozen. A linear/MLP probe is trained on top of one selected |
| representation and evaluated with raw MSE plus normalized MSE. |
| |
| Example: |
| python probe_hyperbolic_mse.py \ |
| --policy /data_nvme/user/zliu681/le-wm-main/lewm_cache/ogbench/Experiment/hyperbolic_exp_antmaze/lewm_hyperbolic_epoch_100 \ |
| --dataset-name ogbench_antmaze_visual_h5/visual-antmaze-large-navigate-v0 \ |
| --target-keys observation \ |
| --representation tangent \ |
| --device auto \ |
| --num-samples 50000 \ |
| --epochs 20 |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| from pathlib import Path |
|
|
| import h5py |
| import numpy as np |
| import torch |
| import torch.nn.functional as F |
| from omegaconf import OmegaConf |
| from torch import nn |
| from torch.utils.data import DataLoader |
|
|
| from module import ARPredictor, Embedder, MLP, SIGReg |
| from probe_lewm_mse import ( |
| H5RowProbeDataset, |
| cache_dir_from_args, |
| collate_rows, |
| load_targets_for_stats, |
| make_probe, |
| progress_iter, |
| preprocess_pixels, |
| resolve_h5_path, |
| ) |
| from train_hyperbolic import ( |
| AdaptiveEntailmentConeLoss, |
| HyperbolicJEPA, |
| LorentzContrastiveLoss, |
| LorentzManifold, |
| build_hyperbolic_world_model, |
| ensure_hyperbolic_defaults, |
| ) |
| from utils import resolve_runtime_device |
|
|
|
|
| def parse_args(): |
| parser = argparse.ArgumentParser(description="Train a frozen HyperbolicJEPA physical probe.") |
| parser.add_argument("--policy", type=str, required=True, help="Checkpoint prefix, checkpoint file, or run dir.") |
| parser.add_argument("--dataset-name", type=str, required=True, help="H5 dataset name under STABLEWM_HOME, or full .h5 path.") |
| parser.add_argument( |
| "--target-keys", |
| type=str, |
| default="observation", |
| help="Comma-separated H5 columns to predict, e.g. observation or qpos,qvel.", |
| ) |
| parser.add_argument( |
| "--representation", |
| type=str, |
| default="tangent", |
| choices=("tangent", "lorentz", "euclidean"), |
| help="Probe input: tangent=hyp_tangent, lorentz=hyp_emb, euclidean=pre-hyperbolic emb.", |
| ) |
| parser.add_argument("--cache-dir", type=str, default="", help="Overrides stable_worldmodel cache dir lookup.") |
| parser.add_argument("--device", type=str, default="auto") |
| parser.add_argument("--img-size", type=int, default=224) |
| parser.add_argument("--num-samples", type=int, default=50000) |
| parser.add_argument("--batch-size", type=int, default=256) |
| parser.add_argument("--epochs", type=int, default=20) |
| parser.add_argument("--lr", type=float, default=1e-3) |
| parser.add_argument("--weight-decay", type=float, default=1e-4) |
| parser.add_argument("--hidden-dim", type=int, default=512, help="0 means linear probe.") |
| parser.add_argument("--num-layers", type=int, default=2, help="Number of hidden layers when hidden_dim > 0.") |
| parser.add_argument("--train-frac", type=float, default=0.8) |
| parser.add_argument("--val-frac", type=float, default=0.1) |
| parser.add_argument("--seed", type=int, default=3072) |
| parser.add_argument("--num-workers", type=int, default=0) |
| parser.add_argument("--strict", action=argparse.BooleanOptionalAction, default=True) |
| parser.add_argument("--output", type=str, default="", help="Optional JSON metrics path.") |
| return parser.parse_args() |
|
|
|
|
| def register_hyperbolic_checkpoint_aliases(): |
| import __main__ as main_mod |
|
|
| objects = ( |
| HyperbolicJEPA, |
| LorentzManifold, |
| LorentzContrastiveLoss, |
| AdaptiveEntailmentConeLoss, |
| ARPredictor, |
| Embedder, |
| MLP, |
| SIGReg, |
| ) |
| for obj in objects: |
| setattr(main_mod, obj.__name__, obj) |
|
|
| if hasattr(torch.serialization, "add_safe_globals"): |
| torch.serialization.add_safe_globals(list(objects)) |
|
|
|
|
| def _add_prefix_candidates(candidates: list[Path], prefix: Path) -> None: |
| text = str(prefix) |
| for suffix in ("_state.ckpt", "_object.ckpt", "_weights.ckpt"): |
| if text.endswith(suffix): |
| _add_prefix_candidates(candidates, Path(text[: -len(suffix)])) |
| return |
| if text.endswith(".ckpt"): |
| candidates.append(prefix) |
| return |
|
|
| candidates.append(Path(f"{text}_state.ckpt")) |
| candidates.append(Path(f"{text}_object.ckpt")) |
| candidates.append(Path(f"{text}_weights.ckpt")) |
|
|
|
|
| def policy_artifact_candidates(policy_name: str, cache_dir: Path) -> list[tuple[Path, Path]]: |
| raw = Path(policy_name) |
| candidates: list[Path] = [] |
|
|
| _add_prefix_candidates(candidates, raw) |
| _add_prefix_candidates(candidates, cache_dir / raw) |
|
|
| for item in (raw, cache_dir / raw): |
| if item.is_file(): |
| candidates.append(item) |
| if item.is_dir(): |
| candidates.extend(sorted(item.glob("*_state.ckpt"))) |
| candidates.extend(sorted(item.glob("*_object.ckpt"))) |
| weights = sorted(item.glob("*_weights.ckpt")) |
| if len(weights) == 1: |
| candidates.append(weights[0]) |
| parent = item.parent |
| if parent.is_dir(): |
| weights = sorted(parent.glob("*_weights.ckpt")) |
| if len(weights) == 1: |
| candidates.append(weights[0]) |
|
|
| seen = set() |
| resolved: list[tuple[Path, Path]] = [] |
| for candidate in candidates: |
| candidate = Path(candidate) |
| if candidate in seen or not candidate.is_file(): |
| continue |
| seen.add(candidate) |
| config_path = candidate.parent / "config.yaml" |
| if config_path.is_file(): |
| resolved.append((candidate, config_path)) |
|
|
| if resolved: |
| return resolved |
|
|
| raise FileNotFoundError( |
| f"Could not resolve checkpoint/config for policy '{policy_name}' under cache '{cache_dir}'." |
| ) |
|
|
|
|
| def infer_action_dim(h5_path: Path, train_cfg) -> int: |
| cfg_value = getattr(train_cfg.wm, "action_dim", None) |
| if cfg_value is not None: |
| return int(cfg_value) |
|
|
| with h5py.File(h5_path, "r") as h5: |
| if "action" not in h5: |
| raise KeyError(f"Cannot infer action_dim because '{h5_path}' has no action column.") |
| shape = h5["action"].shape |
| if len(shape) <= 1: |
| return 1 |
| return int(np.prod(shape[1:], dtype=np.int64)) |
|
|
|
|
| def _state_dict_from_checkpoint(checkpoint, checkpoint_path: Path): |
| if isinstance(checkpoint, dict) and "state_dict" in checkpoint: |
| state_dict = checkpoint["state_dict"] |
| elif isinstance(checkpoint, dict): |
| state_dict = checkpoint |
| else: |
| raise TypeError( |
| f"Unsupported checkpoint type '{type(checkpoint).__name__}' for '{checkpoint_path}'." |
| ) |
|
|
| if any(key.startswith("model.") for key in state_dict.keys()): |
| state_dict = { |
| key[len("model."):]: value |
| for key, value in state_dict.items() |
| if key.startswith("model.") |
| } |
| return state_dict |
|
|
|
|
| def load_hyperbolic_model(args, h5_path: Path, cache_dir: Path, device: str) -> nn.Module: |
| register_hyperbolic_checkpoint_aliases() |
| failures = [] |
|
|
| for checkpoint_path, config_path in policy_artifact_candidates(args.policy, cache_dir): |
| print(f"[probe] trying checkpoint={checkpoint_path} config={config_path}", flush=True) |
| train_cfg = OmegaConf.load(config_path) |
| ensure_hyperbolic_defaults(train_cfg) |
| action_dim = infer_action_dim(h5_path, train_cfg) |
| model = build_hyperbolic_world_model(train_cfg, action_dim=action_dim) |
|
|
| try: |
| checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) |
| if isinstance(checkpoint, nn.Module): |
| model = checkpoint |
| else: |
| state_dict = _state_dict_from_checkpoint(checkpoint, checkpoint_path) |
| missing, unexpected = model.load_state_dict(state_dict, strict=bool(args.strict)) |
| print( |
| f"[probe] loaded state checkpoint strict={bool(args.strict)} " |
| f"missing={len(missing)} unexpected={len(unexpected)}", |
| flush=True, |
| ) |
| if missing: |
| print(f"[probe] missing keys: {missing}", flush=True) |
| if unexpected: |
| print(f"[probe] unexpected keys: {unexpected}", flush=True) |
| except ModuleNotFoundError as exc: |
| if exc.name == "torch_npu" or str(exc.name).startswith("torch_npu."): |
| failures.append(f"{checkpoint_path}: requires torch_npu during object deserialization") |
| print( |
| f"[probe] checkpoint {checkpoint_path} requires torch_npu; trying next candidate.", |
| flush=True, |
| ) |
| continue |
| raise |
| except Exception as exc: |
| failures.append(f"{checkpoint_path}: {type(exc).__name__}: {exc}") |
| print(f"[probe] failed checkpoint {checkpoint_path}: {exc}", flush=True) |
| continue |
|
|
| if not hasattr(model, "encode") and hasattr(model, "model"): |
| model = model.model |
| if not hasattr(model, "encode"): |
| raise TypeError(f"Loaded model does not expose encode(info): {type(model).__name__}") |
| model = model.to(device).eval() |
| model.requires_grad_(False) |
| model.interpolate_pos_encoding = True |
| return model |
|
|
| failure_details = "\n".join(f" - {failure}" for failure in failures) |
| raise RuntimeError(f"Failed to load hyperbolic model. Tried:\n{failure_details}") |
|
|
|
|
| @torch.no_grad() |
| def encode_batch( |
| model: nn.Module, |
| pixels: torch.Tensor, |
| img_size: int, |
| device: str, |
| representation: str, |
| ) -> torch.Tensor: |
| pixels = preprocess_pixels(pixels, img_size=img_size, device=device) |
| output = model.encode({"pixels": pixels.unsqueeze(1)}) |
| if representation == "tangent": |
| key = "hyp_tangent" |
| elif representation == "lorentz": |
| key = "hyp_emb" |
| elif representation == "euclidean": |
| key = "emb" |
| else: |
| raise ValueError(f"Unknown representation: {representation}") |
| return output[key][:, -1].detach().float() |
|
|
|
|
| def evaluate_probe(model, probe, loader, mean, std, args, device: str) -> dict[str, float]: |
| sq_error_sum = None |
| norm_sq_error_sum = None |
| pred_sum = None |
| target_sum = None |
| pred_sq_sum = None |
| target_sq_sum = None |
| pred_target_sum = None |
| sample_count = 0 |
| with torch.no_grad(): |
| for pixels, target in loader: |
| target = target.to(device, non_blocking=True) |
| target = torch.nan_to_num(target, nan=0.0, posinf=0.0, neginf=0.0) |
| emb = encode_batch(model, pixels, args.img_size, device, args.representation) |
| pred_norm = probe(emb) |
| target_norm = (target - mean) / std |
| pred = pred_norm * std + mean |
|
|
| sq_error = (pred - target).pow(2).sum(dim=0).detach() |
| norm_sq_error = (pred_norm - target_norm).pow(2).sum(dim=0).detach() |
| pred_batch_sum = pred.sum(dim=0).detach() |
| target_batch_sum = target.sum(dim=0).detach() |
| pred_batch_sq_sum = pred.pow(2).sum(dim=0).detach() |
| target_batch_sq_sum = target.pow(2).sum(dim=0).detach() |
| pred_target_batch_sum = (pred * target).sum(dim=0).detach() |
|
|
| if sq_error_sum is None: |
| sq_error_sum = torch.zeros_like(sq_error) |
| norm_sq_error_sum = torch.zeros_like(norm_sq_error) |
| pred_sum = torch.zeros_like(pred_batch_sum) |
| target_sum = torch.zeros_like(target_batch_sum) |
| pred_sq_sum = torch.zeros_like(pred_batch_sq_sum) |
| target_sq_sum = torch.zeros_like(target_batch_sq_sum) |
| pred_target_sum = torch.zeros_like(pred_target_batch_sum) |
|
|
| sq_error_sum += sq_error |
| norm_sq_error_sum += norm_sq_error |
| pred_sum += pred_batch_sum |
| target_sum += target_batch_sum |
| pred_sq_sum += pred_batch_sq_sum |
| target_sq_sum += target_batch_sq_sum |
| pred_target_sum += pred_target_batch_sum |
| sample_count += int(target.size(0)) |
|
|
| sample_count = max(1, sample_count) |
| mse_per_dim = sq_error_sum / sample_count |
| norm_mse_per_dim = norm_sq_error_sum / sample_count |
|
|
| cov = pred_target_sum - pred_sum * target_sum / sample_count |
| pred_var = pred_sq_sum - pred_sum.pow(2) / sample_count |
| target_var = target_sq_sum - target_sum.pow(2) / sample_count |
| denom = pred_var.clamp_min(0).sqrt() * target_var.clamp_min(0).sqrt() |
| valid = denom > 1e-12 |
| if bool(valid.any().item()): |
| pearson_per_dim = cov[valid] / denom[valid] |
| pearson_r = pearson_per_dim.mean() |
| pearson_r_std = pearson_per_dim.std(unbiased=False) |
| else: |
| pearson_r = torch.tensor(0.0, device=device) |
| pearson_r_std = torch.tensor(0.0, device=device) |
|
|
| return { |
| "mse": float(mse_per_dim.mean().item()), |
| "mse_std": float(mse_per_dim.std(unbiased=False).item()), |
| "normalized_mse": float(norm_mse_per_dim.mean().item()), |
| "normalized_mse_std": float(norm_mse_per_dim.std(unbiased=False).item()), |
| "pearson_r": float(pearson_r.item()), |
| "pearson_r_std": float(pearson_r_std.item()), |
| } |
|
|
|
|
| def train_one_probe( |
| *, |
| probe_name: str, |
| hidden_dim: int, |
| num_layers: int, |
| model, |
| train_loader, |
| val_loader, |
| test_loader, |
| target_dim: int, |
| mean, |
| std, |
| args, |
| device: str, |
| ) -> dict: |
| first_pixels, _ = next(iter(train_loader)) |
| first_emb = encode_batch(model, first_pixels, args.img_size, device, args.representation) |
| probe = make_probe( |
| input_dim=int(first_emb.shape[-1]), |
| output_dim=target_dim, |
| hidden_dim=hidden_dim, |
| num_layers=num_layers, |
| ).to(device) |
| optimizer = torch.optim.AdamW(probe.parameters(), lr=args.lr, weight_decay=args.weight_decay) |
|
|
| best_state = None |
| best_val = float("inf") |
| for epoch in range(1, args.epochs + 1): |
| probe.train() |
| train_loss = 0.0 |
| train_count = 0 |
| batch_iter = progress_iter( |
| train_loader, |
| desc=f"probe:{probe_name}:epoch{epoch:03d}", |
| total=len(train_loader), |
| leave=False, |
| ) |
| for pixels, target in batch_iter: |
| target = target.to(device, non_blocking=True) |
| target = torch.nan_to_num(target, nan=0.0, posinf=0.0, neginf=0.0) |
| with torch.no_grad(): |
| emb = encode_batch(model, pixels, args.img_size, device, args.representation) |
| pred = probe(emb) |
| target_norm = (target - mean) / std |
| loss = F.mse_loss(pred, target_norm) |
|
|
| optimizer.zero_grad(set_to_none=True) |
| loss.backward() |
| optimizer.step() |
|
|
| train_loss += loss.item() * target.numel() |
| train_count += target.numel() |
| if hasattr(batch_iter, "set_postfix"): |
| batch_iter.set_postfix(norm_mse=f"{train_loss / max(1, train_count):.4f}") |
|
|
| probe.eval() |
| val_metrics = evaluate_probe(model, probe, val_loader, mean, std, args, device) |
| train_norm_mse = train_loss / max(1, train_count) |
| print( |
| f"[probe:{probe_name}] epoch={epoch:03d} train_norm_mse={train_norm_mse:.6f} " |
| f"val_mse={val_metrics['mse']:.6f} val_r={val_metrics['pearson_r']:.6f}", |
| flush=True, |
| ) |
| if val_metrics["normalized_mse"] < best_val: |
| best_val = val_metrics["normalized_mse"] |
| best_state = {key: value.detach().cpu() for key, value in probe.state_dict().items()} |
|
|
| if best_state is not None: |
| probe.load_state_dict(best_state) |
| probe.eval() |
| return { |
| "hidden_dim": int(hidden_dim), |
| "num_layers": int(num_layers), |
| "val": evaluate_probe(model, probe, val_loader, mean, std, args, device), |
| "test": evaluate_probe(model, probe, test_loader, mean, std, args, device), |
| } |
|
|
|
|
| def main(): |
| args = parse_args() |
| cache_dir = cache_dir_from_args(args) |
| h5_path = resolve_h5_path(args.dataset_name, cache_dir) |
| target_keys = [key.strip() for key in args.target_keys.split(",") if key.strip()] |
|
|
| with h5py.File(h5_path, "r") as h5: |
| missing = [key for key in ["pixels", *target_keys] if key not in h5] |
| if missing: |
| raise KeyError(f"{h5_path} missing required keys: {missing}. Available: {list(h5.keys())}") |
| row_count = min(int(h5["pixels"].shape[0]), *(int(h5[key].shape[0]) for key in target_keys)) |
|
|
| rng = np.random.default_rng(args.seed) |
| sample_count = min(int(args.num_samples), row_count) |
| indices = rng.choice(row_count, size=sample_count, replace=False) |
| rng.shuffle(indices) |
|
|
| n_train = int(sample_count * args.train_frac) |
| n_val = int(sample_count * args.val_frac) |
| n_train = max(1, min(n_train, sample_count)) |
| n_val = max(1, min(n_val, sample_count - n_train)) |
| train_idx = np.sort(indices[:n_train]) |
| val_idx = np.sort(indices[n_train : n_train + n_val]) |
| test_idx = np.sort(indices[n_train + n_val :]) |
| if len(test_idx) == 0: |
| test_idx = val_idx |
|
|
| train_targets = load_targets_for_stats(h5_path, train_idx, target_keys) |
| target_mean_np = np.nanmean(train_targets, axis=0, keepdims=True).astype(np.float32) |
| target_std_np = np.nanstd(train_targets, axis=0, keepdims=True).astype(np.float32) |
| target_std_np = np.maximum(target_std_np, 1e-6) |
| target_dim = int(train_targets.shape[1]) |
|
|
| device = resolve_runtime_device(args.device, allow_fallback=True) |
| print( |
| f"[probe] dataset={h5_path} rows={row_count} sampled={sample_count} " |
| f"train={len(train_idx)} val={len(val_idx)} test={len(test_idx)} target_dim={target_dim}", |
| flush=True, |
| ) |
| print( |
| f"[probe] target_keys={target_keys} representation={args.representation} device={device}", |
| flush=True, |
| ) |
|
|
| model = load_hyperbolic_model(args, h5_path, cache_dir, device) |
|
|
| train_loader = DataLoader( |
| H5RowProbeDataset(h5_path, train_idx, target_keys), |
| batch_size=args.batch_size, |
| shuffle=True, |
| num_workers=args.num_workers, |
| collate_fn=collate_rows, |
| pin_memory=device.startswith("cuda"), |
| ) |
| val_loader = DataLoader( |
| H5RowProbeDataset(h5_path, val_idx, target_keys), |
| batch_size=args.batch_size, |
| shuffle=False, |
| num_workers=args.num_workers, |
| collate_fn=collate_rows, |
| pin_memory=device.startswith("cuda"), |
| ) |
| test_loader = DataLoader( |
| H5RowProbeDataset(h5_path, test_idx, target_keys), |
| batch_size=args.batch_size, |
| shuffle=False, |
| num_workers=args.num_workers, |
| collate_fn=collate_rows, |
| pin_memory=device.startswith("cuda"), |
| ) |
|
|
| mean = torch.from_numpy(target_mean_np).to(device) |
| std = torch.from_numpy(target_std_np).to(device) |
|
|
| probe_results = { |
| "linear": train_one_probe( |
| probe_name="linear", |
| hidden_dim=0, |
| num_layers=0, |
| model=model, |
| train_loader=train_loader, |
| val_loader=val_loader, |
| test_loader=test_loader, |
| target_dim=target_dim, |
| mean=mean, |
| std=std, |
| args=args, |
| device=device, |
| ), |
| "mlp": train_one_probe( |
| probe_name="mlp", |
| hidden_dim=int(args.hidden_dim), |
| num_layers=int(args.num_layers), |
| model=model, |
| train_loader=train_loader, |
| val_loader=val_loader, |
| test_loader=test_loader, |
| target_dim=target_dim, |
| mean=mean, |
| std=std, |
| args=args, |
| device=device, |
| ), |
| } |
|
|
| metrics = { |
| "policy": args.policy, |
| "dataset": str(h5_path), |
| "target_keys": target_keys, |
| "representation": args.representation, |
| "num_samples": sample_count, |
| "train_samples": int(len(train_idx)), |
| "val_samples": int(len(val_idx)), |
| "test_samples": int(len(test_idx)), |
| "probes": probe_results, |
| } |
| for probe_name, result in probe_results.items(): |
| test = result["test"] |
| print( |
| f"[probe:{probe_name}] test_mse={test['mse']:.6f} +/- {test['mse_std']:.6f} " |
| f"test_r={test['pearson_r']:.6f}", |
| flush=True, |
| ) |
| print("[probe] final metrics:") |
| print(json.dumps(metrics, indent=2, sort_keys=True)) |
|
|
| if args.output: |
| output_path = Path(args.output) |
| output_path.parent.mkdir(parents=True, exist_ok=True) |
| output_path.write_text(json.dumps(metrics, indent=2, sort_keys=True)) |
| print(f"[probe] wrote {output_path}", flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|