""" Repack the Isaac stack HDF5s into flat uint8 memmaps at training resolution. Why this exists --------------- The source images are gzip-compressed with (20, 50, 50, 1) chunks. Reading one 200x200 frame touches ~48 compressed chunks, and each of those chunks spans 20 frames in time -- so 19/20 of every decompression is discarded. Training visits frames in shuffled order, so that waste is paid on nearly every sample, and it doubled when the wrist camera was added. After this repack, reading frame N is a seek to a byte offset. There is no decompression and no resize in the worker, because the frames are stored already scaled to `--image_size`. The two cameras together are ~84 GB, which the page cache holds comfortably on a 2 TB machine, so epochs after the first read from RAM. Layout written to --out_dir --------------------------- table_cam.npy (N, H, W, 3) uint8 frames, already resized wrist_cam.npy (N, H, W, 3) uint8 actions.npy (N, A) float32 /data/demo_i/actions state.npy (N, S) float32 concatenated state_keys, RAW index.json episode table + provenance Rows are laid out demo by demo in the same deterministic order as `scan_episodes` (sorted by file path, then demo index), so a demo's frame t lives at row `row_start + t`. That is the ordering `splits/stack_sim_v0_split.json` indexes into, so an existing split stays valid. `state.npy` is stored RAW -- quaternion canonicalization is applied at load time so that `dataset.canonicalize_quat` remains a config flag rather than something baked into the files. Usage ----- /work/amin-a/venvs/lilawam/bin/python -m utils.pack_stack_dataset \ --dataset_dir /work/amin-a/srlwam/data/stack/sim/v0 \ --out_dir /work/amin-a/srlwam/data/stack/sim/v0_packed \ --image_size 192 192 \ --cameras table_cam wrist_cam Then set `dataset.packed_dir` in the config. Nothing here modifies the source files. """ import argparse import json import logging import os import shutil import sys import time 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__)))) from dataloader.isaac_stack_dataset import scan_episodes # noqa: E402 logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", handlers=[logging.StreamHandler(sys.stdout)]) logger = logging.getLogger(__name__) def parse_args(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--dataset_dir", required=True) p.add_argument("--out_dir", required=True) p.add_argument("--cameras", nargs="+", default=["table_cam", "wrist_cam"], help="Cameras to pack. The first is the primary view.") p.add_argument("--image_size", nargs=2, type=int, default=[192, 192], metavar=("W", "H"), help="Target size, must match dataset.image_size in the config") p.add_argument("--state_keys", nargs="+", default=["eef_pos", "eef_quat", "gripper_pos"]) p.add_argument("--action_key", default="actions") p.add_argument("--file_glob", default="**/*.hdf5") p.add_argument("--verify", type=int, default=64, help="Randomly re-check this many frames against the source after packing") p.add_argument("--dry_run", action="store_true", help="Report sizes and free space, write nothing") return p.parse_args() 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}") episodes = scan_episodes(args.dataset_dir, args.file_glob) lengths = [ep["length"] for ep in episodes] total = int(sum(lengths)) # Row offsets follow the scan order, which is what the split file indexes into. row_starts, acc = [], 0 for n in lengths: row_starts.append(acc) acc += n frame_bytes = H * W * 3 img_bytes = total * frame_bytes * len(args.cameras) logger.info(f"{len(episodes)} demos, {total} frames") for cam in args.cameras: logger.info(f" {cam}.npy -> ({total}, {H}, {W}, 3) uint8 = " f"{total * frame_bytes / 1e9:.1f} GB") 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 / 1e9:.1f} GB, free {free / 1e9:.1f} GB") if free < need: raise SystemExit(f"Not enough space: need ~{need / 1e9:.1f} GB, have {free / 1e9:.1f} GB") if args.dry_run: logger.info("--dry_run: nothing written") return # Probe dimensions from the first demo so the state/action widths are not guessed. with h5py.File(episodes[0]["hdf5_path"], "r") as f: g = f["data"][episodes[0]["demo_name"]] action_dim = int(g[args.action_key].shape[1]) state_dims = {} for k in args.state_keys: v = g["obs"][k] state_dims[k] = 1 if v.ndim == 1 else int(v.shape[1]) 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 args.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 current_path, handle = None, None try: for ei, ep in enumerate(episodes): if ep["hdf5_path"] != current_path: if handle is not None: handle.close() handle = h5py.File(ep["hdf5_path"], "r") current_path = ep["hdf5_path"] g = handle["data"][ep["demo_name"]] obs = g["obs"] n = ep["length"] lo = row_starts[ei] act_array[lo:lo + n] = np.asarray(g[args.action_key][:n], dtype=np.float32) parts = [] for k in args.state_keys: v = np.asarray(obs[k][:n], dtype=np.float32) parts.append(v[:, None] if v.ndim == 1 else v) state_array[lo:lo + n] = np.concatenate(parts, axis=1) for cam in args.cameras: # One sequential read per demo: every gzip chunk is decompressed exactly # once here, which is the whole point of doing this offline. frames = obs[cam][:n] if frames.shape[1] != H or frames.shape[2] != W: out = cam_arrays[cam][lo:lo + n] for i in range(n): out[i] = cv2.resize(frames[i], (W, H), interpolation=cv2.INTER_AREA) else: cam_arrays[cam][lo:lo + n] = frames done += n if (ei + 1) % 100 == 0 or ei == len(episodes) - 1: el = time.time() - t0 rate = done / max(el, 1e-6) logger.info(f"[{ei + 1}/{len(episodes)}] {done}/{total} frames " f"| {rate:.0f} fps | ETA {(total - done) / max(rate, 1e-6) / 60:.1f} min") finally: if handle is not None: handle.close() 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": list(args.cameras), "state_keys": list(args.state_keys), "state_dims": state_dims, "action_key": args.action_key, "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", "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) 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) def verify(args, episodes, row_starts, W, H): """Re-read random frames from the source and compare against the packed copy.""" rng = np.random.RandomState(0) cams = {cam: np.load(os.path.join(args.out_dir, f"{cam}.npy"), mmap_mode="r") for cam in args.cameras} acts = np.load(os.path.join(args.out_dir, "actions.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: g = f["data"][ep["demo_name"]] if not np.allclose(np.asarray(g[args.action_key][t], dtype=np.float32), acts[row], atol=0): logger.error(f"action mismatch at {ep['demo_name']} t={t}") bad += 1 for cam in args.cameras: src = g["obs"][cam][t] if src.shape[0] != H or src.shape[1] != W: src = cv2.resize(src, (W, H), interpolation=cv2.INTER_AREA) if not np.array_equal(src, cams[cam][row]): logger.error(f"{cam} mismatch at {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()