File size: 10,374 Bytes
b6f2e18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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()