File size: 6,425 Bytes
d94c87e | 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 | """Build a smaller LeRobot v2.1 dataset from `pick_and_place-300`, for episode-count studies.
openpi's `create_torch_dataset` never passes lerobot's `episodes=` argument, and even if it
did, the pinned lerobot builds `episode_data_index` *positionally* over the subset while
`__getitem__` indexes it with the row's original `episode_index` -- so any subset that is not
a prefix of 0..N-1 raises IndexError. The only safe way to train on a subset is to
materialise a renumbered dataset. That is what this does.
uv run python scripts/make_subset.py DST --positives 100 --negatives 27 [--seed 0]
uv run python scripts/make_subset.py DST --episodes 0,1,2,5,9
Videos are hardlinked when possible (no extra disk), copied otherwise.
"""
import argparse, json, os, pathlib, shutil, sys
import pyarrow as pa
import pyarrow.parquet as pq
# Right hand action never moves -> deliberate negative sample (incomplete scene).
NEGATIVES = [51,52,53,54,55,56,57,58,59,60,61,62,63,65,66,67,68,69,70,71,72,73,74,76,77,78,79]
# Session boundaries, from where the original per-parquet episode_index reset.
SESSION_STARTS = [0, 80, 131, 174, 184, 311, 338]
def session_of(ep, n_total):
bounds = SESSION_STARTS + [n_total]
for k in range(len(SESSION_STARTS)):
if bounds[k] <= ep < bounds[k + 1]:
return k
raise ValueError(ep)
def stratified(pool, k, n_total, seed):
"""Take k episodes spread proportionally across recording sessions.
Sessions differ in left-arm rest pose, table position, basket and lighting, so a
contiguous prefix would silently train on one visual domain.
"""
import random
rng = random.Random(seed)
by_sess = {}
for e in pool:
by_sess.setdefault(session_of(e, n_total), []).append(e)
picked, quota_rem = [], k
sess_keys = sorted(by_sess)
# proportional quota, largest-remainder so the total lands exactly on k
exact = {s: k * len(by_sess[s]) / len(pool) for s in sess_keys}
base = {s: int(exact[s]) for s in sess_keys}
for s in sess_keys:
take = min(base[s], len(by_sess[s]))
picked += rng.sample(by_sess[s], take)
quota_rem -= take
leftovers = [e for e in pool if e not in set(picked)]
picked += rng.sample(leftovers, min(quota_rem, len(leftovers)))
return sorted(picked)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("dst")
ap.add_argument("--src", default=str(pathlib.Path(__file__).resolve().parent.parent))
ap.add_argument("--positives", type=int, default=None)
ap.add_argument("--negatives", type=int, default=None)
ap.add_argument("--episodes", default=None, help="explicit comma-separated source episode ids")
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
SRC, DST = pathlib.Path(a.src), pathlib.Path(a.dst)
src_files = sorted((SRC / "data" / "chunk-000").glob("episode_*.parquet"))
n_total = len(src_files)
eps_meta = {json.loads(l)["episode_index"]: json.loads(l) for l in open(SRC / "meta/episodes.jsonl")}
stats_meta = {json.loads(l)["episode_index"]: json.loads(l) for l in open(SRC / "meta/episodes_stats.jsonl")}
negs = [e for e in NEGATIVES if e < n_total]
poss = [e for e in range(n_total) if e not in set(negs)]
if a.episodes:
chosen = sorted(int(x) for x in a.episodes.split(","))
else:
np_ = len(poss) if a.positives is None else min(a.positives, len(poss))
nn_ = len(negs) if a.negatives is None else min(a.negatives, len(negs))
chosen = sorted(stratified(poss, np_, n_total, a.seed) + stratified(negs, nn_, n_total, a.seed))
if DST.exists():
sys.exit(f"refusing to overwrite existing {DST}")
(DST / "meta").mkdir(parents=True)
(DST / "data" / "chunk-000").mkdir(parents=True)
info = json.load(open(SRC / "meta/info.json"))
cams = [k for k, f in info["features"].items() if f["dtype"] == "video"]
for c in cams:
(DST / "videos" / "chunk-000" / c).mkdir(parents=True)
offset, total, new_eps, new_stats, linked, copied = 0, 0, [], [], 0, 0
for new_i, src_i in enumerate(chosen):
t = pq.read_table(SRC / f"data/chunk-000/episode_{src_i:06d}.parquet")
n = t.num_rows
for name, vals in (("episode_index", [new_i] * n), ("index", list(range(offset, offset + n)))):
j = t.schema.get_field_index(name)
t = t.set_column(j, t.schema.field(j), pa.array(vals, type=t.schema.field(j).type))
pq.write_table(t, DST / f"data/chunk-000/episode_{new_i:06d}.parquet")
for c in cams:
s = SRC / f"videos/chunk-000/{c}/episode_{src_i:06d}.mp4"
d = DST / f"videos/chunk-000/{c}/episode_{new_i:06d}.mp4"
try:
os.link(s, d); linked += 1
except OSError:
shutil.copy2(s, d); copied += 1
e = dict(eps_meta[src_i]); e["episode_index"] = new_i; new_eps.append(e)
st = dict(stats_meta[src_i]); st["episode_index"] = new_i; new_stats.append(st)
offset += n; total += n
with open(DST / "meta/episodes.jsonl", "w") as f:
for e in new_eps: f.write(json.dumps(e) + "\n")
with open(DST / "meta/episodes_stats.jsonl", "w") as f:
for s in new_stats: f.write(json.dumps(s) + "\n")
shutil.copy2(SRC / "meta/tasks.jsonl", DST / "meta/tasks.jsonl")
if (SRC / "meta/modality.json").exists():
shutil.copy2(SRC / "meta/modality.json", DST / "meta/modality.json")
info["total_episodes"] = len(chosen)
info["total_frames"] = total
info["total_videos"] = len(chosen) * len(cams)
info["splits"] = {"train": f"0:{len(chosen)}"}
info["subset_of"] = {"source": str(SRC), "source_episodes": chosen}
json.dump(info, open(DST / "meta/info.json", "w"), indent=4)
n_neg = len([e for e in chosen if e in set(negs)])
per_sess = {}
for e in chosen: per_sess[session_of(e, n_total)] = per_sess.get(session_of(e, n_total), 0) + 1
print(f"-> {DST}")
print(f" episodes {len(chosen)} ({len(chosen)-n_neg} positive + {n_neg} negative) frames {total}"
f" = {total/20/3600:.2f} h @20Hz")
print(f" videos: {linked} hardlinked, {copied} copied")
print(f" episodes per recording session: {dict(sorted(per_sess.items()))}")
print(f" epochs at batch 32: 30k steps = {32*30000/total:.1f}, 15k = {32*15000/total:.1f}")
if __name__ == "__main__":
main()
|