"""Standalone loader for the FailBench v2 contact-prediction datasets. Pure ``h5py + numpy + scipy`` (+ optional ``torch`` for the Dataset wrapper) — it has ZERO dependency on the FailBench package, MuJoCo, or robosuite. Use it to load a trial and rebuild its agentview contact-heatmap target straight from the published HDF5 files. pip install h5py hdf5plugin numpy scipy pandas # torch optional, for the Dataset python load_failbench.py --data_root /path/to/failbench-robocasa-v2 \ --cache_root /path/to/failbench-robocasa-v2/target_cache ============================ THE ONE GOTCHA ============================ The arrays are Blosc(lz4)-compressed with the third-party HDF5 filter id 32001. You MUST ``import hdf5plugin`` BEFORE h5py opens any file, or reads fail with "can't open plugin directory". (``dataset.compression`` misleadingly reports ``None`` for this filter — the data IS compressed.) This module does it at the top, so always import this module (or hdf5plugin) before opening the files. ========================================================================= Repo layout this loader understands (either dataset): / v2/.h5 # RoboCasa: task files directly under v2/ v2/manifest_train.csv # RoboCasa train split (+ manifest.csv, quarantine.csv) v2//.h5 # LIBERO: split = libero_spatial|object|goal v2//manifest.csv / # == /target_cache /.h5 # per-trial //projection (N,3)[u,v,force] + failure_prob attr """ from __future__ import annotations import argparse from pathlib import Path import hdf5plugin # noqa: F401 — registers the Blosc filter; MUST precede h5py file open import h5py import numpy as np from scipy.ndimage import gaussian_filter # Default agentview grid (H, W). cam_agentview_size is stored as [W, H] = [320, 240]. DEFAULT_HW = (240, 320) # The per-trial dataset keys written by the pipeline. read_trial() returns whatever subset # of these (plus scalar/array attrs) a given trial actually has. _DATASET_KEYS = ( # 8-frame pre-failure window (T=8, 4 fps), agentview + wrist RGB/depth + proprio "window_frame_idx", "window_qpos", "window_qvel", "window_ee_pos", "window_gripper_ctrl", "window_agentview_rgb", "window_agentview_depth", "window_wrist_rgb", "window_wrist_depth", # goal-conditioning frames "goal_qpos", "goal_qvel", "goal_ee_pos", "goal_gripper_ctrl", "goal_offsets", # single pre-failure frame (v1-compatible) "pre_qpos", "pre_qvel", "pre_ee_pos", "pre_gripper_ctrl", "pre_target_qpos", "pre_rgb", "pre_depth", "robot0_eye_in_hand_rgb", "robot0_eye_in_hand_depth", # contacts recorded over the post-failure settle (world frame) "contact_positions", "contact_forces", "contact_force_world", "contact_time", "contact_geom_pairs", "contact_failure_id", "impacted_geom_ids", "geom_bodyid", # baseline (healthy-hold replay) contacts — used by the failure-induced filter "baseline_contact_geom_pairs", "baseline_contact_positions", # post-failure observations "post_agentview_rgb", "post_agentview_depth", "post_wrist_rgb", "post_wrist_depth", # agentview camera calibration (lets you project contacts yourself, no sim needed) "cam_agentview_pos", "cam_agentview_mat0", "cam_agentview_fovy", "cam_agentview_size", "cam_wrist_pos_window", "cam_wrist_mat0_window", "cam_wrist_fovy", "cam_wrist_size", # failure descriptor + object poses + settle state trajectory "failure_joints", "obj_names", "obj_pos_pre", "obj_quat_pre", "obj_pos_post", "obj_quat_post", "settle_step_idx", "settle_qpos", "settle_qvel", "settle_gripper_qpos", "settle_obj_pos", "settle_obj_quat", ) _SCALAR_ATTRS = ( "trial_id", "split", "task", "demo_key", "seed", "seed_idx", "bin_idx", "fail_idx", "traj_progress", "failure_mode", "failure_prob", "is_holding", "force_frame", "scene_table_z", ) _ARRAY_ATTRS = ("scene_aabb_min", "scene_aabb_max", "robot_geom_ids", "scene_entities_json") # --------------------------------------------------------------------------- paths def resolve_h5(data_root, split: str, task: str) -> Path: """Locate a task's v2 HDF5 by (split, task). Handles both repo layouts. NOTE: do NOT trust the manifest's ``h5_path`` column — it stores the absolute path of the original build machine. Always resolve relative to your local repo root. """ root = Path(data_root) / "v2" for cand in (root / f"{task}.h5", root / split / f"{task}.h5"): if cand.exists(): return cand raise FileNotFoundError(f"no v2 h5 for split={split} task={task} under {root}") def cache_h5(cache_root, split: str, task: str) -> Path: return Path(cache_root) / split / f"{task}.h5" def load_manifest(data_root): """Concatenate every manifest under ``v2/`` into one DataFrame (requires pandas). Prefers ``manifest_train.csv`` (RoboCasa train split); falls back to per-split ``manifest.csv`` (LIBERO). Adds no rows for ``quarantine.csv``. """ import pandas as pd root = Path(data_root) / "v2" paths = sorted(root.rglob("manifest_train.csv")) or sorted(root.rglob("manifest.csv")) if not paths: raise FileNotFoundError(f"no manifest*.csv under {root}") return pd.concat([pd.read_csv(p) for p in paths], ignore_index=True) # --------------------------------------------------------------------------- read def read_trial(h5_path, trial_id: str, keys=None) -> dict: """Load one trial group into a dict of numpy arrays + scalar/array attrs.""" want = set(keys) if keys is not None else set(_DATASET_KEYS) out: dict = {} with h5py.File(h5_path, "r", libver="latest", swmr=True) as f: grp = f[f"trials/{trial_id}"] for k in want: if k in grp: ds = grp[k] if h5py.check_string_dtype(ds.dtype) is not None: out[k] = [s.decode() if isinstance(s, bytes) else s for s in ds[:]] else: out[k] = ds[()] for k in _SCALAR_ATTRS + _ARRAY_ATTRS: if k in grp.attrs: v = grp.attrs[k] out[k] = v.decode() if isinstance(v, bytes) else v return out def trial_ids(h5_path) -> list: with h5py.File(h5_path, "r", libver="latest", swmr=True) as f: return sorted(f["trials"].keys()) if "trials" in f else [] # --------------------------------------------------------------------------- targets def heatmap_from_projection(cache_root, split: str, task: str, trial_id: str, *, hw=DEFAULT_HW, sigma_px: float = 4.0, log1p: bool = False) -> np.ndarray: """Rebuild the (H, W) contact-mass heatmap from the precomputed projection cache. The cache stores, per trial, an (N, 3) array of in-frame ``[u, v, force_mag]`` plus a scalar ``failure_prob`` attr (the contacts are already failure-induced-filtered). The dense target is ``scatter(force * failure_prob) -> Gaussian blur``. This matches the GPU training target (``build_target_from_projection``); pass ``log1p=True`` to match that path's default compression of the mass. """ H, W = hw out = np.zeros((H, W), np.float32) with h5py.File(cache_h5(cache_root, split, task), "r") as f: g = f[trial_id] proj = np.asarray(g["projection"], np.float32) # (N, 3) [u, v, force] fp = float(g.attrs.get("failure_prob", 1.0)) if proj.shape[0]: u = np.clip(proj[:, 0].astype(int), 0, W - 1) v = np.clip(proj[:, 1].astype(int), 0, H - 1) np.add.at(out, (v, u), proj[:, 2] * fp) if sigma_px > 0: out = gaussian_filter(out, sigma=sigma_px, mode="constant", cval=0.0) return np.log1p(out) if log1p else out def heatmap_from_contacts(trial: dict, *, sigma_px: float = 4.0, weighting: str = "force_prior") -> np.ndarray: """Rebuild the heatmap on-the-fly from raw contacts + camera calibration (no cache, no sim). Mirrors the reference projection exactly: the agentview camera looks down its own −Z; the image v-axis points down, so the rotation's Y-row is negated. ``weighting`` is one of ``force_prior`` (force × failure_prob), ``force``, or ``count``. Note this uses the raw recorded contacts (no failure-induced filtering); use the projection cache for the filtered training target. """ cam_pos = np.asarray(trial["cam_agentview_pos"], np.float64) R = np.asarray(trial["cam_agentview_mat0"], np.float64).reshape(3, 3).T.copy() R[1] = -R[1] W, H = (int(x) for x in trial["cam_agentview_size"]) fy = (H / 2.0) / np.tan(np.deg2rad(float(trial["cam_agentview_fovy"])) / 2.0) fx, cx, cy = fy, W / 2.0, H / 2.0 out = np.zeros((H, W), np.float32) pts = np.asarray(trial.get("contact_positions", np.zeros((0, 3))), np.float64) if pts.shape[0] == 0: return out p_cam = (pts - cam_pos) @ R.T depth = -p_cam[:, 2] front = depth > 1e-6 if not front.any(): return out u = fx * p_cam[front, 0] / depth[front] + cx v = fy * p_cam[front, 1] / depth[front] + cy inb = (u >= 0) & (u < W) & (v >= 0) & (v < H) if not inb.any(): return out if weighting == "count": w_all = np.ones(pts.shape[0], np.float32) else: f = trial.get("contact_force_world") if f is None: f = np.asarray(trial["contact_forces"])[:, :3] w_all = np.linalg.norm(np.asarray(f, np.float32), axis=1) if weighting == "force_prior": w_all = w_all * np.float32(trial.get("failure_prob", 1.0)) w = w_all[front][inb] np.add.at(out, (np.clip(v[inb].astype(int), 0, H - 1), np.clip(u[inb].astype(int), 0, W - 1)), w) return gaussian_filter(out, sigma=sigma_px, mode="constant", cval=0.0) if sigma_px > 0 else out # --------------------------------------------------------------------------- torch Dataset def make_dataset(data_root, cache_root=None, *, hw=DEFAULT_HW, sigma_px=4.0, log1p=False): """Return a ``torch.utils.data.Dataset`` over the manifest. Each item is ``{"trial": , "target": (H,W) float32}``. When ``cache_root`` is given the target comes from the projection cache (filtered, matches training); otherwise it is rebuilt on-the-fly from the raw contacts. """ import torch df = load_manifest(data_root) class _FailBenchV2(torch.utils.data.Dataset): def __len__(self): return len(df) def __getitem__(self, i): row = df.iloc[i] split, task, tid = row["split"], row["task"], row["trial_id"] trial = read_trial(resolve_h5(data_root, split, task), tid) if cache_root is not None: tgt = heatmap_from_projection(cache_root, split, task, tid, hw=hw, sigma_px=sigma_px, log1p=log1p) else: tgt = heatmap_from_contacts(trial, sigma_px=sigma_px) return {"trial": trial, "target": torch.from_numpy(np.ascontiguousarray(tgt))} return _FailBenchV2() # --------------------------------------------------------------------------- demo / self-test def _first_filtered_trial(cache_root, split, task): """First trial id in this task's cache whose (filtered) projection is non-empty.""" p = cache_h5(cache_root, split, task) if not p.exists(): return None with h5py.File(p, "r") as f: for tid in f.keys(): if f[tid]["projection"].shape[0] > 0: return tid return None def _demo(data_root, cache_root): df = load_manifest(data_root) print(f"manifest rows: {len(df)} | tasks: {df['task'].nunique()} | splits: {sorted(df['split'].unique())}") # pick a trial whose FAILURE-INDUCED (filtered) target is non-empty, so both the # on-the-fly and the cached heatmaps carry mass and the demo is meaningful. contact_rows = df[df["n_contacts"] > 0] if "n_contacts" in df.columns else df row = contact_rows.iloc[0] if cache_root: for _, r in contact_rows.iterrows(): tid_f = _first_filtered_trial(cache_root, r["split"], r["task"]) if tid_f is not None: row = r.copy(); row["trial_id"] = tid_f break split, task, tid = row["split"], row["task"], row["trial_id"] h5 = resolve_h5(data_root, split, task) print(f"\nloading {split}/{task}/{tid} from {h5.name}") trial = read_trial(h5, tid) for k in ("window_agentview_rgb", "pre_rgb", "contact_positions", "settle_qpos"): if k in trial: print(f" {k:24s} {np.asarray(trial[k]).shape} {np.asarray(trial[k]).dtype}") print(f" failure_mode={trial.get('failure_mode')} failure_prob={trial.get('failure_prob')}") live = heatmap_from_contacts(trial) print(f"\non-the-fly heatmap: shape={live.shape} sum={live.sum():.3f} max={live.max():.4f}") assert live.sum() > 0, "expected non-zero contact mass on a contact-bearing trial" if cache_root and cache_h5(cache_root, split, task).exists(): cached = heatmap_from_projection(cache_root, split, task, tid) print(f"cached (filtered) heatmap: shape={cached.shape} sum={cached.sum():.3f} max={cached.max():.4f}") print("\nOK — load + target rebuild verified.") if __name__ == "__main__": ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--data_root", required=True, help="repo root containing v2/") ap.add_argument("--cache_root", default=None, help="target_cache/ dir (optional)") args = ap.parse_args() _demo(args.data_root, args.cache_root)