File size: 19,439 Bytes
5a3fcf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
"""Step 2: turn each selected dataset into a training shard.

Per dataset (one worker process each; datasets are split over SLURM array tasks by frame count):
  1. Episode filters on the native-rate state and action (reasons are recorded per episode):
       non_finite         NaN or inf in state or action
       timestamps         timestamps not increasing, or a gap longer than 2.5 frames (dropped frames)
       too_short          fewer than max(chunk, min_seconds * target_fps) frames after resampling
       too_long           longer than max_seconds
       static             the arm barely moves: largest arm-joint range in the episode below static_frac x the
                          dataset's median of that quantity
       jump               a single-step change of an arm joint (state or action) above jump_frac x that joint's
                          scale, the 1-99 percentile range over the dataset floored at a quarter of the largest
                          arm joint's range (encoder glitch, wrap-around)
       video_*            a camera's video is unreadable, shorter than the episode, or off in time
  2. Resampling to target_fps by nearest frame (30 fps -> every 3rd frame at 10 Hz).
  3. Camera roles. The repository's slots follow SmolVLA's manual mapping: image = the main third-person view,
     image2 = the wrist camera when there is one (otherwise a second fixed view), image3 = usually a side view.
     The contributors' own names are not used: "laptop", "phone", "usb_front" are wrist cameras in some datasets;
     in one the camera named "wrist" is fixed and the one named "top" is on the gripper; in another the camera
     named "gripper" is a fixed side view. So:
       agent  = the first slot (image)
       wrist  = the first later slot whose still fraction is below still_max: the share of 64 px grey pixels whose
                brightness std over an episode (resampled frames, first 300) is below still_std grey levels,
                median over a few episodes. A fixed camera keeps its background still; a camera on the gripper
                keeps only its own fingers still.
       no wrist camera found: the wrist input is masked in training
     A single-camera dataset whose camera is nearly never still (< still_single) and moving (1 - correlation of
     frames 1 s apart >= move_single) is a wrist-only dataset and is dropped.
     Checked by eye (2026-11-18) on 31 two-camera datasets: the first slot was a fixed view in all 31; image2 still
     fraction 0.00-0.08 for the 14 wrist cameras, 0.28-0.81 for the 17 fixed second views. Thresholds were set on
     the first 21; the other 10, drawn at random afterwards, were all right too.
  4. Frames of the agent and wrist streams decoded and resized to res x res RGB (aspect ratio not kept; apply the
     same resize to the target robot's cameras).
  5. Per-dataset normalization statistics: state mean/std, absolute-action mean/std, and mean/std of the action
     relative to the current state over the chunk (a[t+k] - s[t], k < chunk). Std is floored at 1% of the joint's
     1-99 percentile range, so a joint that never moves does not blow up.

Output per dataset: <work>/shards/<contributor>__<name>/ with agent.u8 (N, res, res, 3), wrist.u8 (if a wrist camera
was found), arrays.npz (state, action at the resampled rate, episode id per frame), episodes.json, stats.json,
meta.json (roles, motion scores, drops by reason) and DONE. Datasets dropped as a whole, or failing, get
<work>/shards/_status/<id>.json. Re-running skips finished datasets. --delete-raw removes a dataset's raw data and
videos once it is kept or dropped (for disks smaller than raw + shards, ~0.8 TB).

    python scripts/preprocess.py --work $POPT_WORK --task $SLURM_ARRAY_TASK_ID --ntasks $SLURM_ARRAY_TASK_COUNT
"""
import argparse
import math
import multiprocessing as mp
import os
import shutil
import sys
import time
import traceback

import av
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from popt.common import (ARM, dataset_check, original_camera_names, read_json, read_jsonl,  # noqa: E402
                         rgb_streams, work_dirs, write_json)

A = None  # parsed arguments, set in main() and inherited by the worker processes


class VideoError(Exception):
    pass


def safe_id(d: str) -> str:
    return d.replace("/", "__")


# ----------------------------------------------------------------------------------------------- reading

def load_episode(raw_d: str, info: dict, e: int):
    chunk = e // info.get("chunks_size", 1000)
    t = pq.read_table(os.path.join(raw_d, info["data_path"].format(episode_chunk=chunk, episode_index=e)))
    n = t.num_rows

    def mat(name, width):
        col = t.column(name).combine_chunks()
        ty = col.type
        if pa.types.is_list(ty) or pa.types.is_large_list(ty) or pa.types.is_fixed_size_list(ty):
            col = col.flatten()
        return np.asarray(col.to_numpy(zero_copy_only=False), np.float64).reshape(n, width)

    return mat("observation.state", 6), mat("action", 6), mat("timestamp", 1)[:, 0]


def video_path(raw_d: str, info: dict, key: str, e: int) -> str:
    chunk = e // info.get("chunks_size", 1000)
    return os.path.join(raw_d, info["video_path"].format(episode_chunk=chunk, video_key=key, episode_index=e))


def decode(path: str, idx: np.ndarray, size: int, fmt: str, fps: float) -> np.ndarray:
    """Frames at native indices idx (sorted), resized to size x size. Frame i is the i-th decoded frame; its
    presentation time must agree with i / fps within 1.5 frames."""
    want = np.zeros(int(idx[-1]) + 1, bool)
    want[idx] = True
    out, t0 = [], None
    try:
        with av.open(path) as c:
            s = c.streams.video[0]
            s.thread_type = "AUTO"
            s.codec_context.thread_count = A.decode_threads
            for i, fr in enumerate(c.decode(s)):
                if i >= len(want):
                    break
                if fr.time is not None:
                    t0 = fr.time if t0 is None else t0
                    if abs(fr.time - t0 - i / fps) > 1.5 / fps:
                        raise VideoError("video_time_mismatch")
                if want[i]:
                    out.append(fr.to_ndarray(width=size, height=size, format=fmt, interpolation="AREA"))
    except VideoError:
        raise
    except Exception as e:  # noqa: BLE001
        raise VideoError("video_error") from e
    if len(out) != len(idx):
        raise VideoError("video_missing_frames")
    return np.stack(out)


# ----------------------------------------------------------------------------------------------- one dataset

def process(d: str) -> dict:
    D = work_dirs(A.work)
    final = os.path.join(D["shards"], safe_id(d))
    status_p = os.path.join(D["shards"], "_status", safe_id(d) + ".json")
    if os.path.exists(os.path.join(final, "DONE")):
        free_raw(d)
        return {"dataset": d, "status": "done_before"}
    t_start = time.time()
    tmp = final + ".tmp"
    shutil.rmtree(tmp, ignore_errors=True)
    try:
        r = _process(d, tmp)
    except Exception:  # noqa: BLE001
        shutil.rmtree(tmp, ignore_errors=True)
        r = {"dataset": d, "status": "failed", "error": traceback.format_exc()[-3000:]}
    r["seconds"] = round(time.time() - t_start, 1)
    if r["status"] == "kept":
        write_json(os.path.join(tmp, "meta.json"), r)
        open(os.path.join(tmp, "DONE"), "w").close()
        os.replace(tmp, final)
        if os.path.exists(status_p):
            os.remove(status_p)
    else:
        shutil.rmtree(tmp, ignore_errors=True)
        write_json(status_p, r)
    if r["status"] in ("kept", "dropped"):
        free_raw(d)
    return {k: r[k] for k in ("dataset", "status", "seconds") if k in r} | ({"reason": r["reason"]} if "reason" in r else {})


def free_raw(d: str):
    """--delete-raw: remove a finished dataset's data/ and videos/ from raw/ (meta/ stays for re-runs and the report;
    a failed dataset keeps its files so a re-run can retry it)."""
    if A.delete_raw:
        for sub in ("data", "videos"):
            shutil.rmtree(os.path.join(work_dirs(A.work)["raw"], d, sub), ignore_errors=True)


def _process(d: str, tmp: str) -> dict:
    D = work_dirs(A.work)
    raw_d = os.path.join(D["raw"], d)
    info = read_json(os.path.join(raw_d, "meta", "info.json"))
    reason = dataset_check(info, A.target_fps)
    if reason:
        return {"dataset": d, "status": "dropped", "reason": reason}
    fps, tf = float(info["fps"]), A.target_fps
    min_frames = max(A.chunk, math.ceil(A.min_seconds * tf))
    episodes = read_jsonl(os.path.join(raw_d, "meta", "episodes.jsonl"))
    tasks = {t["task_index"]: t["task"] for t in read_jsonl(os.path.join(raw_d, "meta", "tasks.jsonl"))}
    dropped: dict[int, str] = {}

    # pass 1: state and action filters
    cand = []
    for ep in episodes:
        e = int(ep["episode_index"])
        try:
            S, Ac, ts = load_episode(raw_d, info, e)
        except Exception:  # noqa: BLE001
            dropped[e] = "bad_parquet"
            continue
        n = len(S)
        if n < 2 or not (np.isfinite(S).all() and np.isfinite(Ac).all() and np.isfinite(ts).all()):
            dropped[e] = "non_finite" if n >= 2 else "too_short"
            continue
        dt = np.diff(ts)
        if (dt <= 0).any() or dt.max() > 2.5 / fps:
            dropped[e] = "timestamps"
            continue
        if (n - 1) / fps > A.max_seconds:
            dropped[e] = "too_long"
            continue
        m = int(math.floor((n - 1) * tf / fps + 1e-9)) + 1
        idx = np.minimum(np.round(np.arange(m) * fps / tf).astype(np.int64), n - 1)
        if m < min_frames:
            dropped[e] = "too_short"
            continue
        cand.append({"e": e, "idx": idx, "S": S, "A": Ac, "task": "; ".join(ep.get("tasks") or []) or None,
                     "arm_range": float((S[:, ARM].max(0) - S[:, ARM].min(0)).max()),
                     "step_s": np.abs(np.diff(S[:, ARM], axis=0)).max(0),
                     "step_a": np.abs(np.diff(Ac[:, ARM], axis=0)).max(0)})
    if cand:
        allS = np.concatenate([c["S"][:, ARM] for c in cand])
        p1, p99 = np.percentile(allS, [1, 99], axis=0)
        jrange = np.maximum(p99 - p1, 0.25 * (p99 - p1).max())  # a joint that barely moves must not make noise a jump
        jrange = np.maximum(jrange, 1e-6)
        med = float(np.median([c["arm_range"] for c in cand]))
        keep = []
        for c in cand:
            if c["arm_range"] < A.static_frac * med:
                dropped[c["e"]] = "static"
            elif (c["step_s"] > A.jump_frac * jrange).any() or (c["step_a"] > A.jump_frac * jrange).any():
                dropped[c["e"]] = "jump"
            else:
                keep.append(c)
        cand = keep
    if not cand:
        return {"dataset": d, "status": "dropped", "reason": "no_episodes_left", "episodes_dropped": by_reason(dropped)}

    # pass 2: camera roles (slot order + a moving-camera test on the second slot)
    streams = rgb_streams(info)
    names = original_camera_names(SUMMARY, d)
    slot = lambda k: k.split(".")[-1]  # noqa: E731
    sample = [cand[int(k)] for k in np.unique(np.linspace(0, len(cand) - 1, min(A.role_episodes, len(cand))).round())]
    scores = {s: camera_stats(raw_d, info, s, sample, fps) for s in streams}
    agent, wrist = streams[0], None
    if len(streams) == 1:
        st, mv = scores[agent]["still"], scores[agent]["move"]
        if st < A.still_single and mv >= A.move_single:
            return {"dataset": d, "status": "dropped", "reason": "only_wrist_camera", "motion_scores": scores}
    else:
        for s in streams[1:]:
            if scores[s]["still"] < A.still_max:
                wrist = s
                break

    # pass 3: decode, resize, write
    os.makedirs(tmp)
    fa = open(os.path.join(tmp, "agent.u8"), "wb")
    fw = open(os.path.join(tmp, "wrist.u8"), "wb") if wrist else None
    eps, S_out, A_out, E_out, start = [], [], [], [], 0
    for c in cand:
        try:
            ia = decode(video_path(raw_d, info, agent, c["e"]), c["idx"], A.res, "rgb24", fps)
            iw = decode(video_path(raw_d, info, wrist, c["e"]), c["idx"], A.res, "rgb24", fps) if wrist else None
        except VideoError as err:
            dropped[c["e"]] = str(err)
            continue
        fa.write(ia.tobytes())
        if fw:
            fw.write(iw.tobytes())
        L = len(c["idx"])
        eps.append({"source_episode": c["e"], "start": start, "length": L, "task": c["task"]})
        S_out.append(c["S"][c["idx"]]); A_out.append(c["A"][c["idx"]]); E_out.append(np.full(L, len(eps) - 1, np.int32))
        start += L
    fa.close()
    if fw:
        fw.close()
    if not eps:
        shutil.rmtree(tmp, ignore_errors=True)
        return {"dataset": d, "status": "dropped", "reason": "no_episodes_left", "episodes_dropped": by_reason(dropped)}
    S, Ac, E = np.concatenate(S_out), np.concatenate(A_out), np.concatenate(E_out)
    np.savez(os.path.join(tmp, "arrays.npz"), state=S.astype(np.float32), action=Ac.astype(np.float32), ep=E)
    write_json(os.path.join(tmp, "episodes.json"), eps)
    write_json(os.path.join(tmp, "stats.json"), norm_stats(S, Ac, eps))
    return {"dataset": d, "status": "kept", "frames": int(len(S)), "episodes": len(eps),
            "episodes_dropped": by_reason(dropped), "dropped_episode_list": {str(k): v for k, v in sorted(dropped.items())},
            "source_fps": fps, "target_fps": tf, "res": A.res, "chunk": A.chunk,
            "agent": agent, "wrist": wrist, "agent_name": names.get(slot(agent)), "wrist_name": names.get(slot(wrist)) if wrist else None,
            "camera_names": {slot(s): names.get(slot(s)) for s in streams}, "motion_scores": scores,
            "hours_resampled": round(len(S) / tf / 3600, 3), "tasks": sorted({t for t in tasks.values()})}


def camera_stats(raw_d: str, info: dict, key: str, sample: list, fps: float) -> dict:
    """On grey 64 px resampled frames (first 300 per episode), median over the sampled episodes:
      still  share of pixels whose brightness std over the episode is below still_std grey levels
      move   1 - correlation of frames 1 s apart (blank frames skipped)
    NaN when no episode decodes."""
    k = max(1, round(A.target_fps))
    still, move = [], []
    for c in sample:
        try:
            g = decode(video_path(raw_d, info, key, c["e"]), c["idx"][:300], 64, "gray", fps).astype(np.float32)
        except VideoError:
            continue
        still.append(float((g.std(0) < A.still_std).mean()))
        g = g.reshape(len(g), -1)
        g = g - g.mean(1, keepdims=True)
        sd = np.sqrt((g ** 2).mean(1))
        pairs = [(i, i + k) for i in range(0, len(g) - k, 2) if sd[i] > 2 and sd[i + k] > 2]
        if pairs:
            move.append(float(np.mean([1 - (g[i] * g[j]).mean() / (sd[i] * sd[j]) for i, j in pairs])))
    med = lambda v: float(np.median(v)) if v else float("nan")  # noqa: E731
    return {"still": med(still), "move": med(move)}


def by_reason(dropped: dict) -> dict:
    out = {}
    for r in dropped.values():
        out[r] = out.get(r, 0) + 1
    return out


def norm_stats(S: np.ndarray, Ac: np.ndarray, eps: list) -> dict:
    p1, p99 = np.percentile(S, [1, 99], axis=0)
    floor = np.maximum(0.01 * (p99 - p1), 1e-3)
    n, s1, s2 = 0, np.zeros(6), np.zeros(6)
    for ep in eps:
        a, st = Ac[ep["start"]:ep["start"] + ep["length"]], S[ep["start"]:ep["start"] + ep["length"]]
        for k in range(min(A.chunk, len(a))):
            dlt = a[k:] - st[:len(a) - k]
            n += len(dlt); s1 += dlt.sum(0); s2 += (dlt ** 2).sum(0)
    dmean = s1 / n
    dstd = np.sqrt(np.maximum(s2 / n - dmean ** 2, 0))
    f = lambda x: [float(v) for v in x]  # noqa: E731
    return {"state_mean": f(S.mean(0)), "state_std": f(np.maximum(S.std(0), floor)),
            "action_mean": f(Ac.mean(0)), "action_std": f(np.maximum(Ac.std(0), floor)),
            "delta_mean": f(dmean), "delta_std": f(np.maximum(dstd, floor)),
            "state_p1": f(p1), "state_p99": f(p99), "frames": int(len(S))}


# ----------------------------------------------------------------------------------------------- main

SUMMARY = None


def main():
    global A, SUMMARY
    p = argparse.ArgumentParser()
    p.add_argument("--work", default=os.environ.get("POPT_WORK"), required=os.environ.get("POPT_WORK") is None)
    p.add_argument("--task", type=int, default=0, help="array task index")
    p.add_argument("--ntasks", type=int, default=1, help="number of array tasks")
    p.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) // 2), help="datasets in parallel")
    p.add_argument("--decode-threads", type=int, default=2)
    p.add_argument("--only", default="", help="comma-separated dataset ids")
    p.add_argument("--target-fps", type=int, default=int(os.environ.get("TARGET_FPS", 10)))
    p.add_argument("--res", type=int, default=int(os.environ.get("RES", 256)))
    p.add_argument("--chunk", type=int, default=int(os.environ.get("CHUNK", 16)))
    p.add_argument("--min-seconds", type=float, default=2.0)
    p.add_argument("--max-seconds", type=float, default=600.0)
    p.add_argument("--static-frac", type=float, default=0.1)
    p.add_argument("--jump-frac", type=float, default=0.5)
    p.add_argument("--still-std", type=float, default=6.0, help="grey-level std under which a pixel counts as still")
    p.add_argument("--still-max", type=float, default=0.2, help="a later slot with a still fraction below this is the wrist camera")
    p.add_argument("--still-single", type=float, default=0.05, help="single camera: still fraction below this ...")
    p.add_argument("--move-single", type=float, default=0.3, help="... and move score above this = a wrist camera: drop")
    p.add_argument("--role-episodes", type=int, default=3)
    p.add_argument("--delete-raw", action="store_true",
                   help="delete each dataset's raw data and videos once its shard is written or it is dropped")
    A = p.parse_args()
    D = work_dirs(A.work)
    os.makedirs(os.path.join(D["shards"], "_status"), exist_ok=True)
    sel = read_json(D["selection"])
    assert sel["target_fps"] == A.target_fps, (sel["target_fps"], A.target_fps)
    sp = os.path.join(D["raw"], "PROCESSING_SUMMARY.json")
    SUMMARY = read_json(sp) if os.path.exists(sp) else None
    dsets = [s for s in A.only.split(",") if s] or sel["kept"]
    # split over array tasks by frame count (largest first onto the least loaded task)
    frames = {d: read_json(os.path.join(D["raw"], d, "meta", "info.json")).get("total_frames", 0) for d in dsets}
    bins = [[0, []] for _ in range(A.ntasks)]
    for d in sorted(dsets, key=lambda d: (-frames[d], d)):
        b = min(bins, key=lambda b: b[0])
        b[0] += frames[d]; b[1].append(d)
    mine = bins[A.task][1]
    print(f"task {A.task}/{A.ntasks}: {len(mine)} datasets, {bins[A.task][0]} source frames, {A.workers} workers", flush=True)
    t0 = time.time()
    with mp.get_context("fork").Pool(A.workers, maxtasksperchild=4) as pool:
        for k, r in enumerate(pool.imap_unordered(process, mine)):
            print(f"[{k + 1}/{len(mine)} {time.time() - t0:.0f}s] {r}", flush=True)
    print("preprocess task done", flush=True)


if __name__ == "__main__":
    main()