""" Convert the real-robot "stack" HDF5s into the same packed layout the sim data uses, mapping every convention onto the sim one so a sim checkpoint can be fine-tuned on them. Why this exists --------------- `utils/pack_stack_dataset.py` packs the Isaac Lab release. The real release (`stack/real/stack_v0/episode_*.hdf5`) describes the same task with a different schema, so it needs its own reader -- but it must produce a *byte-compatible* packed directory, because training reads the packed memmaps through the unchanged `IsaacStackDataset`. Schema differences, and what this script does about each ------------------------------------------------------- real sim (target) file layout 1 episode per file, at the root data/demo_/... primary camera obs/agentview_image 256x256 obs/table_cam 200x200 wrist camera obs/wrist_image 256x256 obs/wrist_cam 187x187 eef position obs/robot0_eef_pos (T, 3) obs/eef_pos (T, 3) eef orientation obs/robot0_eef_quat (T, 4) obs/eef_quat (T, 4) gripper state obs/gripper_width (T, 1) obs/gripper_pos (T, 2) actions (T, 7) (T, 7) Renames and the resize are mechanical. Three conversions are not, and each was measured on the data rather than assumed -- see `docs` in `index.json["transforms"]`: 1. **Gripper action sign is REVERSED.** In sim, `action[6] == +1` drives `gripper_pos` toward 0.04 (open) and `-1` toward 0.013 (closed). In the real data the same two values mean the opposite: `-1` holds the fingers at width 0.076 (open) and `+1` at 0.033 (closed). All 20 episodes agree. Left alone, a sim-pretrained policy would open the real gripper every time it meant to close it. -> `action[6] *= -1`. 2. **Gripper state is a width, not a finger pair.** Sim stores the two finger joints as `(+j, -j)` with `j` in [0, 0.04]; the real data stores the total width in [0.029, 0.080]. Half the width is the per-finger value, and it lands on the sim range almost exactly (real closed 0.0145 vs sim 0.0139, real open 0.0399 vs sim 0.0400) -- the two grippers hold comparably sized cubes. -> `(w/2, -w/2)`. 3. **Position actions are in different units.** Both are per-step Cartesian deltas, but the controllers realize a different fraction of the command: regressing the achieved displacement on the command gives a gain of 0.186 in sim and 0.901 on the real robot (pooled least squares; a std-ratio estimator agrees to ~7%). So one metre of motion is written as 5.4 action units in sim and 1.1 on the real robot. Feeding both to one normalizer without correcting for that puts real actions in ~12% of the range the pretrained action head emits into. -> position dims are multiplied by `--action_pos_scale` (default 0.901/0.186 = 4.844), which is a *unit* conversion, not a change of behaviour: after it, real actions still move ~1.5x less per step than sim demos do, which is a genuine difference in how fast the demonstrations are. DEPLOYMENT: a policy trained on this data emits sim-unit actions. Divide the three position dims by `action_pos_scale` (recorded in `index.json`) before sending them to the real controller. Rotation actions are **identically zero** in all 3748 real frames -- the operator drove position and gripper only -- so dims 3:6 are passed through untouched. They stay a constant input, which the normalizer maps into the sim range like any other value. Quaternions need no work: both releases already store `(x, y, z, w)` scalar-last. That was verified by forward kinematics on the real `robot0_joint_pos` (the flange pose from FK matches `robot0_eef_pos` to 0.0 m and the approach axis to 0.01 deg under scalar-last, versus 124 deg under scalar-first) and, for sim, by the requirement that a hand which descends to z = 0.026 m to grasp a cube at z = 0.015 m must point downward -- true for 100% of frames under scalar-last and 0% under scalar-first. As in the sim packer, the state is written RAW and canonicalization stays a load-time flag. Images are already RGB in both releases, so no channel swap is applied. Usage ----- /work/amin-a/venvs/lilawam/bin/python -m utils.pack_real_stack_dataset \ --dataset_dir /work/amin-a/srlwam/data/stack/real/stack_v0 \ --out_dir /work/amin-a/srlwam/data/stack/real/v0_packed \ --image_size 192 192 Writes ~830 MB. Then point `dataset.packed_dir` at --out_dir. """ import argparse import json import logging import os import re import shutil import sys import time from pathlib import Path import cv2 import h5py import numpy as np cv2.setNumThreads(0) sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", handlers=[logging.StreamHandler(sys.stdout)]) logger = logging.getLogger(__name__) # real obs key -> canonical sim camera name. The first entry is the primary view: it is # what the foresight loss is supervised on, so it has to be the table-facing camera to # match how the sim checkpoint was trained. CAMERA_MAP = [("agentview_image", "table_cam"), ("wrist_image", "wrist_cam")] # Measured controller gains (achieved displacement / commanded delta), pooled least # squares over all position dims: 20 real episodes and 100 sim demos. REAL_POS_GAIN = 0.9014 SIM_POS_GAIN = 0.1861 DEFAULT_POS_SCALE = REAL_POS_GAIN / SIM_POS_GAIN # 4.844 def parse_args(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--dataset_dir", required=True, help="Directory of episode_*.hdf5 files") p.add_argument("--out_dir", required=True) p.add_argument("--image_size", nargs=2, type=int, default=[192, 192], metavar=("W", "H"), help="Must match dataset.image_size in the config") p.add_argument("--file_glob", default="episode_*.hdf5") p.add_argument("--action_pos_scale", type=float, default=DEFAULT_POS_SCALE, help="Multiply action dims 0:3 by this to convert real controller units " "to sim ones. 1.0 disables. See the module docstring -- a policy " "trained on the scaled data must be divided by it at deployment.") p.add_argument("--no_flip_gripper_action", action="store_true", help="Do NOT reverse action[6]. Only for inspecting the raw convention; " "training on it would invert every grasp relative to sim.") p.add_argument("--verify", type=int, default=64, help="Randomly re-check this many frames against the source") p.add_argument("--dry_run", action="store_true") return p.parse_args() def scan_episodes(dataset_dir, file_glob="episode_*.hdf5"): """ One episode per file. Sorted by the integer in the filename, so the order is episode_0, episode_1, ..., episode_19 rather than the lexicographic episode_0, episode_1, episode_10 -- and, more importantly, is deterministic and independent of filesystem ordering, which is what makes the split reproducible. """ root = Path(dataset_dir) if not root.exists(): raise FileNotFoundError(f"dataset_dir not found: {root}") files = list(root.glob(file_glob)) if not files: raise ValueError(f"No files matched {file_glob} under {root}") def key(p): m = re.search(r"(\d+)", p.stem) return (int(m.group(1)) if m else -1, p.name) episodes = [] for path in sorted(files, key=key): with h5py.File(path, "r") as f: if "actions" not in f or "obs" not in f: logger.warning(f"Skipping {path.name}: no /actions or /obs") continue length = int(f.attrs.get("num_samples", f["actions"].shape[0])) episodes.append({ "hdf5_path": str(path), "demo_name": path.stem, # "episode_7"; the loader only logs it "length": length, "success": bool(f.attrs.get("success", True)), }) logger.info(f"Scanned {len(files)} files -> {len(episodes)} episodes") return episodes def build_state(obs, n): """[eef_pos(3) | eef_quat(4) | gripper_pos(2)] = 9 dims, in the sim layout, RAW.""" pos = np.asarray(obs["robot0_eef_pos"][:n], dtype=np.float32) quat = np.asarray(obs["robot0_eef_quat"][:n], dtype=np.float32) width = np.asarray(obs["gripper_width"][:n], dtype=np.float32).reshape(n, -1)[:, :1] half = width / 2.0 # per-finger value return np.concatenate([pos, quat, half, -half], axis=1) def build_actions(raw, n, pos_scale, flip_gripper): a = np.asarray(raw[:n], dtype=np.float32).copy() a[:, 0:3] *= pos_scale if flip_gripper: a[:, 6] *= -1.0 return a def main(): args = parse_args() W, H = args.image_size if W % 16 or H % 16: raise SystemExit(f"DINOv3 needs multiples of 16, got {W}x{H}") flip_gripper = not args.no_flip_gripper_action episodes = scan_episodes(args.dataset_dir, args.file_glob) lengths = [ep["length"] for ep in episodes] total = int(sum(lengths)) row_starts, acc = [], 0 for n in lengths: row_starts.append(acc) acc += n cameras = [dst for _, dst in CAMERA_MAP] frame_bytes = H * W * 3 img_bytes = total * frame_bytes * len(cameras) logger.info(f"{len(episodes)} episodes, {total} frames " f"({min(lengths)}-{max(lengths)} per episode)") for cam in cameras: logger.info(f" {cam}.npy -> ({total}, {H}, {W}, 3) uint8 = " f"{total * frame_bytes / 1e6:.0f} MB") logger.info(f"transforms: action[0:3] *= {args.action_pos_scale:.4f}, " f"action[6] *= {-1 if flip_gripper else 1}, " f"gripper_width -> (w/2, -w/2)") os.makedirs(args.out_dir, exist_ok=True) free = shutil.disk_usage(args.out_dir).free need = img_bytes * 1.02 logger.info(f"Need ~{need / 1e6:.0f} MB, free {free / 1e9:.1f} GB") if free < need: raise SystemExit(f"Not enough space: need ~{need / 1e6:.0f} MB") if args.dry_run: logger.info("--dry_run: nothing written") return with h5py.File(episodes[0]["hdf5_path"], "r") as f: action_dim = int(f["actions"].shape[1]) state_dims = {"eef_pos": 3, "eef_quat": 4, "gripper_pos": 2} state_dim = sum(state_dims.values()) logger.info(f"action_dim={action_dim}, state_dim={state_dim} {state_dims}") cam_arrays = { cam: np.lib.format.open_memmap(os.path.join(args.out_dir, f"{cam}.npy"), mode="w+", dtype=np.uint8, shape=(total, H, W, 3)) for cam in cameras } act_array = np.lib.format.open_memmap(os.path.join(args.out_dir, "actions.npy"), mode="w+", dtype=np.float32, shape=(total, action_dim)) state_array = np.lib.format.open_memmap(os.path.join(args.out_dir, "state.npy"), mode="w+", dtype=np.float32, shape=(total, state_dim)) t0 = time.time() done = 0 for ei, ep in enumerate(episodes): with h5py.File(ep["hdf5_path"], "r") as f: obs = f["obs"] n = ep["length"] lo = row_starts[ei] act_array[lo:lo + n] = build_actions(f["actions"], n, args.action_pos_scale, flip_gripper) state_array[lo:lo + n] = build_state(obs, n) for src, dst in CAMERA_MAP: frames = obs[src][:n] if frames.shape[1] != H or frames.shape[2] != W: out = cam_arrays[dst][lo:lo + n] for i in range(n): out[i] = cv2.resize(frames[i], (W, H), interpolation=cv2.INTER_AREA) else: cam_arrays[dst][lo:lo + n] = frames done += n el = time.time() - t0 logger.info(f"[{ei + 1}/{len(episodes)}] {ep['demo_name']} n={n} | " f"{done}/{total} frames | {done / max(el, 1e-6):.0f} fps") for a in list(cam_arrays.values()) + [act_array, state_array]: a.flush() index = { "dataset_dir": str(args.dataset_dir), "image_size": [W, H], "cameras": cameras, "state_keys": ["eef_pos", "eef_quat", "gripper_pos"], "state_dims": state_dims, "action_key": "actions", "action_dim": action_dim, "state_dim": state_dim, "num_episodes": len(episodes), "num_frames": total, "canonicalize_quat": False, # stored raw; applied at load time "resize_interpolation": "INTER_AREA", "source": "real", "transforms": { "docs": "Applied while packing, to put the real data in sim conventions.", "camera_map": {src: dst for src, dst in CAMERA_MAP}, "state_source_keys": ["robot0_eef_pos", "robot0_eef_quat", "gripper_width"], "gripper_state": "gripper_width -> (w/2, -w/2) to match the sim finger pair", "gripper_action_sign_flipped": flip_gripper, "gripper_action_note": "real -1 = open, sim +1 = open; flipped so +1 = open", "action_pos_scale": args.action_pos_scale, "action_pos_scale_note": ( "action[0:3] multiplied by this to convert real controller units to sim " "units (measured gains: real 0.9014, sim 0.1861). DIVIDE BY THIS at " "deployment before sending positions to the real controller."), "action_rot_note": "dims 3:6 are identically zero in the real data; untouched", "quaternion_order": "(x, y, z, w) scalar-last in both releases; not reordered", "channel_order": "RGB in both releases; not swapped", }, "episodes": [ {"hdf5_path": ep["hdf5_path"], "demo_name": ep["demo_name"], "length": ep["length"], "success": ep["success"], "row_start": row_starts[i]} for i, ep in enumerate(episodes) ], } tmp = os.path.join(args.out_dir, "index.json.tmp") with open(tmp, "w") as f: json.dump(index, f, indent=2) os.replace(tmp, os.path.join(args.out_dir, "index.json")) logger.info(f"Packed {total} frames in {(time.time() - t0) / 60:.1f} min -> {args.out_dir}") if args.verify > 0: verify(args, episodes, row_starts, W, H, flip_gripper) def verify(args, episodes, row_starts, W, H, flip_gripper): """Re-read random frames from the source, re-apply the transforms, and compare.""" rng = np.random.RandomState(0) cams = {dst: np.load(os.path.join(args.out_dir, f"{dst}.npy"), mmap_mode="r") for _, dst in CAMERA_MAP} acts = np.load(os.path.join(args.out_dir, "actions.npy"), mmap_mode="r") states = np.load(os.path.join(args.out_dir, "state.npy"), mmap_mode="r") bad = 0 for _ in range(args.verify): ei = rng.randint(len(episodes)) ep = episodes[ei] t = rng.randint(ep["length"]) row = row_starts[ei] + t with h5py.File(ep["hdf5_path"], "r") as f: n = ep["length"] exp_a = build_actions(f["actions"], n, args.action_pos_scale, flip_gripper)[t] if not np.allclose(exp_a, acts[row], atol=0): logger.error(f"action mismatch {ep['demo_name']} t={t}") bad += 1 exp_s = build_state(f["obs"], n)[t] if not np.allclose(exp_s, states[row], atol=0): logger.error(f"state mismatch {ep['demo_name']} t={t}") bad += 1 for src, dst in CAMERA_MAP: img = f["obs"][src][t] if img.shape[0] != H or img.shape[1] != W: img = cv2.resize(img, (W, H), interpolation=cv2.INTER_AREA) if not np.array_equal(img, cams[dst][row]): logger.error(f"{dst} mismatch {ep['demo_name']} t={t}") bad += 1 if bad: raise SystemExit(f"VERIFY FAILED: {bad} mismatches") logger.info(f"Verified {args.verify} random frames against the source: all match") if __name__ == "__main__": main()