Download code/build_lap_uniform.py from LehongWu/sft_lap_data-1128: direct link, hf CLI and curl.
- Browser
- Download file 27.9 kB
-
https://huggingface.co/datasets/LehongWu/sft_lap_data-1128/resolve/main/code/build_lap_uniform.py
- Command line
-
hf download hf://datasets/LehongWu/sft_lap_data-1128/code/build_lap_uniform.py
-
curl -L -o build_lap_uniform.py https://huggingface.co/datasets/LehongWu/sft_lap_data-1128/resolve/main/code/build_lap_uniform.py
27.9 kB
| #!/usr/bin/env python3 | |
| """LAP with uniform, download-efficient chunk sampling (2026-11-28): abc130k_zheyuan, molmo_yam, worldengine, agibot26. | |
| The text protocol is unchanged (annotate_lap.chunk_record: per-arm tool-frame poses rounded to 1 cm / 5 deg / 10%, | |
| relative to the measured start pose); what changes from build_lap_selected.py (2026-11-25) is which chunks are used | |
| and that every chunk gives both directions: | |
| files The low-dim streams live in parquet files of many episodes each (S3 for molmo_yam, worldengine and | |
| agibot26; HF huzheyuan/abc130k_v3_{train,val} for abc130k_zheyuan, the source of its prepared release), so | |
| downloads are saved by picking whole files. The files are shuffled (seeded) and taken in that order while | |
| they hold a train-split episode of a task that has fewer than ceil(--episode-fraction x its prepared | |
| train-split episodes) picked; files without train-split episodes (validation-only files) are taken in the | |
| same order until they hold that fraction of their episodes. Every prepared episode in a picked file is | |
| used, whatever its split. -> <work-dir>/<dataset>/files.json | |
| windows Each picked file is downloaded, read and deleted; every whole-second chunk [t, t+1] of its episodes is a | |
| candidate: the (61, 16) float16 cartesian_tool window at 60 Hz (the same Loong path as | |
| build_lap_selected.py) plus its static / junk features. -> candidates.npy, candidates.npz, episodes.json | |
| select The dataset's chunk quota (QUOTAS) is drawn uniformly: rate = quota / usable train candidates of the | |
| picked episodes; each episode gets rate x its candidates (systematic rounding, exact total) drawn | |
| uniformly without replacement. val and val_ood (abc130k's held-out tasks) episodes use the same rate. | |
| No motion weighting, no static cap. -> selection.npz, selection.json | |
| label actions.npy, episodes.jsonl (lap-episode-v2 chunks without "direction": each gives a LAP-A2L and a | |
| LAP-L2A record, with the chunk's own horizon and L2A rate), meta.json under <out-root>/<dataset>/<RUN>. | |
| convert convert_annotation_lap_to_sft_json.convert (split rules of the IDM manifests; val capped per task) into | |
| <out-root>/<dataset>/sft_json/<RUN>/. | |
| QUOTAS are 1.5M samples / 2 directions = 750,000 chunks, split over the datasets in proportion to their usable train | |
| candidates (the 2026-11-25 counts: every whole-second chunk of every prepared train episode), i.e. the same chance | |
| (11.84%) for every chunk of the four datasets. Agibot Beta is not built (wrist-camera axis bug). | |
| Usage (one dataset per call; run_lap_uniform.sh runs all four): | |
| python build_lap_uniform.py --dataset molmo_yam --release-root /tmp/action-lang-align-v3/hf \ | |
| --out-root /tmp/lap-sft-1128/hf --workers 48 | |
| """ | |
| import argparse | |
| from collections import Counter, defaultdict | |
| from concurrent.futures import ProcessPoolExecutor | |
| import json | |
| import math | |
| import multiprocessing | |
| import os | |
| from pathlib import Path | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import numpy as np | |
| HERE = Path(__file__).resolve().parent | |
| WORKSPACE = HERE.parents[1] | |
| for path in (WORKSPACE, WORKSPACE / "external/Loong/src", HERE): | |
| if str(path) not in sys.path: | |
| sys.path.insert(0, str(path)) | |
| import build_lap_selected as selected # noqa: E402 | |
| from build_lap_selected import SAMPLES, file_sha256, starts_for, systematic, window_features # noqa: E402 | |
| from action_language_alignment.vllm_action_annotation import prepared_datasets # noqa: E402 | |
| import annotate_lap as lap # noqa: E402 | |
| RUN = "annotate_lap-uniform2dir-261128" | |
| SCHEMA = "lap-episode-v2" | |
| DATASETS = ("abc130k_zheyuan", "molmo_yam", "worldengine", "agibot26") | |
| TRAIN_CANDIDATES = {"abc130k_zheyuan": 3055650, "molmo_yam": 939145, "worldengine": 1630080, "agibot26": 711548} | |
| CHUNKS = 750_000 # x 2 directions = 1.5M train samples | |
| def quotas(total=CHUNKS, candidates=TRAIN_CANDIDATES): | |
| """Chunks per dataset in proportion to its train candidates (largest remainder, exact total).""" | |
| pool = sum(candidates.values()) | |
| exact = {name: total * n / pool for name, n in candidates.items()} | |
| out = {name: int(v) for name, v in exact.items()} | |
| for name in sorted(exact, key=lambda k: exact[k] - out[k], reverse=True)[:total - sum(out.values())]: | |
| out[name] += 1 | |
| return out | |
| QUOTAS = quotas() # abc130k_zheyuan 361,677, molmo_yam 111,161, worldengine 192,941, agibot26 84,221 | |
| HF_ABC = "huzheyuan/abc130k_v3_{split}" | |
| BUCKET = selected.BUCKET | |
| # ------------------------------------------------------------------------------------------- files stage | |
| def episode_rows(spec, release_root): | |
| """Prepared chunk_index rows with their source file (S3 key or HF path) and group (train / val / val_ood).""" | |
| held = selected.HELD_OUT_TASK_INDEX.get(spec.name, set()) | |
| rows = [] | |
| with open(release_root / spec.name / "meta/prepared/chunk_index.jsonl", encoding="utf-8") as stream: | |
| for line in stream: | |
| r = json.loads(line) | |
| if r.get("excluded"): | |
| continue | |
| task_index = r.get("task_index", r.get("task_id")) | |
| if spec.action_format == "canonical20": | |
| source, source_episode = r["data_key"], r["source_episode_index"] | |
| else: | |
| c, f = r["data"]["chunk_index"], r["data"]["file_index"] | |
| if spec.name == "abc130k_zheyuan": # the HF repo of the split; the prepared release's source | |
| source = f"hf:{HF_ABC.format(split=r['split'])}:data/chunk-{c:03d}/file-{f:03d}.parquet" | |
| else: | |
| source = f"pretrain_v2/data/{spec.name}_v3ar/{spec.name}_v3/data/chunk-{c:03d}/file-{f:03d}.parquet" | |
| source_episode = r["episode_index"] | |
| group = "val" if r["split"] == "val" else ("val_ood" if task_index in held else "train") | |
| rows.append({"split": r["split"], "group": group, "episode_index": r["episode_index"], "uuid": r["uuid"], | |
| "task": r["task"], "task_index": task_index, "length": r["length"], | |
| "source": source, "source_episode": source_episode}) | |
| rows.sort(key=lambda r: (r["split"], r["episode_index"])) | |
| return rows | |
| def pick_files(rows, fraction, rng): | |
| """Whole source files: per task, at least ceil(fraction x its train-split episodes); see the module docstring.""" | |
| by_file = defaultdict(list) | |
| for r in rows: | |
| by_file[r["source"]].append(r) | |
| order = [str(s) for s in rng.permutation(sorted(by_file))] | |
| total = Counter(r["task"] for r in rows if r["split"] == "train") | |
| target = {task: math.ceil(fraction * n) for task, n in total.items()} | |
| have, picked = Counter(), [] | |
| for source in order: | |
| tasks = Counter(r["task"] for r in by_file[source] if r["split"] == "train") | |
| if any(have[task] < target[task] for task in tasks): | |
| picked.append(source) | |
| have.update(tasks) | |
| val_only = [s for s in order if not any(r["split"] == "train" for r in by_file[s])] | |
| goal, got = math.ceil(fraction * sum(len(by_file[s]) for s in val_only)), 0 | |
| for source in val_only: | |
| if got >= goal: | |
| break | |
| picked.append(source) | |
| got += len(by_file[source]) | |
| return sorted(picked), {task: (have[task], total[task]) for task in sorted(total)} | |
| def source_sizes(spec, sources): | |
| """Bytes of each source file (one S3 listing per prefix, or the HF tree).""" | |
| sizes = {} | |
| if spec.name == "abc130k_zheyuan": | |
| from huggingface_hub import HfApi | |
| api = HfApi() | |
| for split in ("train", "val"): | |
| repo = HF_ABC.format(split=split) | |
| for f in api.list_repo_tree(repo, repo_type="dataset", path_in_repo="data", recursive=True): | |
| if getattr(f, "size", None): | |
| sizes[f"hf:{repo}:{f.path}"] = f.size | |
| else: | |
| prefix = (f"pretrain_v2/data/agibot26_v3ar/" if spec.name == "agibot26" | |
| else f"pretrain_v2/data/{spec.name}_v3ar/{spec.name}_v3/data/") | |
| listing = subprocess.run(["aws", "s3", "ls", "--recursive", f"s3://{BUCKET}/{prefix}"], check=True, | |
| capture_output=True, text=True).stdout | |
| for line in listing.splitlines(): | |
| parts = line.split() | |
| if len(parts) == 4 and parts[3].endswith(".parquet"): | |
| sizes[parts[3]] = int(parts[2]) | |
| missing = [s for s in sources if s not in sizes] | |
| if missing: | |
| raise ValueError(f"{len(missing)} source files are not in the listing, e.g. {missing[0]}") | |
| return {s: sizes[s] for s in sources} | |
| def hf_revisions(spec): | |
| if spec.name != "abc130k_zheyuan": | |
| return {} | |
| from huggingface_hub import HfApi | |
| api = HfApi() | |
| return {HF_ABC.format(split=s): api.dataset_info(HF_ABC.format(split=s)).sha for s in ("train", "val")} | |
| def stage_files(spec, work, release_root, fraction, seed): | |
| if (work / "files.json").exists(): | |
| print(f"[files] {spec.name}: reusing files.json", flush=True) | |
| return | |
| rows = episode_rows(spec, release_root) | |
| picked, coverage = pick_files(rows, fraction, np.random.default_rng([seed, 0])) | |
| all_sources = sorted({r["source"] for r in rows}) | |
| sizes = source_sizes(spec, all_sources) | |
| keep = set(picked) | |
| used = [r for r in rows if r["source"] in keep] | |
| groups = {g: (sum(r["group"] == g for r in used), sum(r["group"] == g for r in rows)) for g in ("train", "val", "val_ood")} | |
| summary = { | |
| "episode_fraction": fraction, "seed": seed, "files": [len(picked), len(all_sources)], | |
| "bytes": [sum(sizes[s] for s in picked), sum(sizes.values())], | |
| "episodes": {g: list(v) for g, v in groups.items()}, | |
| "task_coverage_min_max": [min(h / t for h, t in coverage.values()), max(h / t for h, t in coverage.values())], | |
| "hf_revisions": hf_revisions(spec), | |
| } | |
| work.mkdir(parents=True, exist_ok=True) | |
| (work / "files.json").write_text(json.dumps({"summary": summary, "picked": picked, "rows": used, | |
| "coverage": coverage, "sizes": sizes}) + "\n") | |
| print(f"[files] {spec.name}: {json.dumps(summary)}", flush=True) | |
| # ------------------------------------------------------------------------------------------- windows stage | |
| def download(source, tmp, revisions): | |
| """The source parquet as a local file in a fresh temporary folder (the caller deletes the folder).""" | |
| folder = Path(tempfile.mkdtemp(dir=tmp)) | |
| if source.startswith("hf:"): | |
| from huggingface_hub import hf_hub_download | |
| _, repo, name = source.split(":", 2) | |
| for attempt in range(4): | |
| try: | |
| return folder, Path(hf_hub_download(repo, name, repo_type="dataset", revision=revisions[repo], | |
| local_dir=folder)) | |
| except Exception: # noqa: BLE001 - retried, then raised | |
| if attempt == 3: | |
| raise | |
| time.sleep(10 * (attempt + 1)) | |
| local = folder / "file.parquet" | |
| for attempt in range(4): | |
| r = subprocess.run(["aws", "s3", "cp", "--only-show-errors", f"s3://{BUCKET}/{source}", str(local)], | |
| capture_output=True, text=True) | |
| if r.returncode == 0: | |
| return folder, local | |
| time.sleep(10 * (attempt + 1)) | |
| raise RuntimeError(f"download failed: {r.stderr.strip()[-300:]}") | |
| def read_streams(job): | |
| """{episode key: (states, commands, frame_index, timestamp)} of one source file.""" | |
| import pyarrow as pa | |
| import pyarrow.compute as pc | |
| import pyarrow.parquet as pq | |
| spec = prepared_datasets.get(job["dataset"]) | |
| cols = (["episode_index", "frame_index", "timestamp", "observation.state", "action"] | |
| if spec.action_format == "canonical20" else | |
| ["episode_index", "frame_index", "timestamp", "joint_state", "joint_action"]) | |
| folder, local = download(job["source"], job["tmp"], job["revisions"]) | |
| try: | |
| table = pq.read_table(local, columns=cols) | |
| finally: | |
| shutil.rmtree(folder, ignore_errors=True) | |
| wanted = sorted({e["source_episode"] for e in job["episodes"]}) | |
| table = table.filter(pc.is_in(table["episode_index"], value_set=pa.array(wanted))) | |
| ep = table["episode_index"].to_numpy() | |
| out = {} | |
| for e in job["episodes"]: | |
| part = table.take(np.flatnonzero(ep == e["source_episode"])) | |
| fi = part["frame_index"].to_numpy() | |
| order = np.argsort(fi) | |
| out[e["key"]] = (np.asarray(part[cols[3]].to_pylist(), np.float64)[order], | |
| np.asarray(part[cols[4]].to_pylist(), np.float64)[order], | |
| fi[order], part["timestamp"].to_numpy()[order]) | |
| return out | |
| def windows_job(job): | |
| """One source file: write its episodes' candidate windows into the shared store; return features.""" | |
| import torch | |
| torch.set_num_threads(1) | |
| from action_language_alignment import agibot_actions | |
| from action_language_alignment.abc130k_actions import CartesianEpisode | |
| dataset, fps = job["dataset"], job["fps"] | |
| try: | |
| streams = read_streams(job) | |
| except Exception as exc: # noqa: BLE001 - every episode of the file is recorded as failed | |
| return {e["key"]: {"error": f"{type(exc).__name__}: {exc}"} for e in job["episodes"]} | |
| store = np.load(job["store"], mmap_mode="r+") | |
| results = {} | |
| for e in job["episodes"]: | |
| try: | |
| states, commands, fi, ts = streams[e["key"]] | |
| if not np.array_equal(fi, np.arange(e["length"])): | |
| raise ValueError(f"frame_index is not 0..{e['length'] - 1} ({len(fi)} rows)") | |
| if np.abs(ts - ts[0] - fi / fps).max() > 1e-3: | |
| raise ValueError(f"timestamps are off the {fps} FPS grid") | |
| if dataset == "agibot26": | |
| episode = selected.CanonicalEpisode(agibot_actions.canonicalize(commands, dataset), | |
| agibot_actions.canonicalize(states, dataset), fps) | |
| else: | |
| episode = CartesianEpisode(commands, states, fps, SAMPLES, ["cartesian_tool"]) | |
| values = np.stack([episode.window(int(t) * fps, "cartesian_tool") for t in e["starts"]]).astype(np.float16) | |
| store[e["row"]:e["row"] + len(values)] = values | |
| static, _, junk = window_features(values) | |
| ok = np.ones(len(values), bool) | |
| for i, v in enumerate(values): | |
| try: | |
| lap.validate_window(v) | |
| except ValueError: | |
| ok[i] = False | |
| results[e["key"]] = {"static": static, "junk": junk | ~ok} | |
| except Exception as exc: # noqa: BLE001 | |
| results[e["key"]] = {"error": f"{type(exc).__name__}: {exc}"} | |
| store.flush() | |
| del store | |
| return results | |
| def stage_windows(spec, work, workers, tmp): | |
| if (work / "candidates.npz").exists(): | |
| print(f"[windows] {spec.name}: reusing {work}", flush=True) | |
| return | |
| info = json.loads((work / "files.json").read_text()) | |
| rows, revisions = info["rows"], info["summary"]["hf_revisions"] | |
| fps = spec.native_fps | |
| offset, plan = 0, [] | |
| for k, r in enumerate(rows): | |
| starts = starts_for(r["length"], fps) | |
| plan.append({"key": k, "row": offset, "starts": starts.tolist(), "length": r["length"], | |
| "source_episode": r["source_episode"]}) | |
| offset += len(starts) | |
| total = offset | |
| store_path = work / "candidates.npy" | |
| np.lib.format.open_memmap(store_path, mode="w+", dtype=np.float16, shape=(total, SAMPLES, 16)).flush() | |
| by_source = defaultdict(list) | |
| for r, p in zip(rows, plan): | |
| by_source[r["source"]].append(p) | |
| jobs = [{"dataset": spec.name, "fps": fps, "source": s, "episodes": eps, "store": str(store_path), "tmp": tmp, | |
| "revisions": revisions} for s, eps in sorted(by_source.items())] | |
| print(f"[windows] {spec.name}: {len(rows):,} episodes, {total:,} candidate windows, {len(jobs)} files, " | |
| f"{workers} workers", flush=True) | |
| static = np.zeros(total, bool) | |
| junk = np.ones(total, bool) | |
| errors = {} | |
| started = last = time.monotonic() | |
| done = 0 | |
| with ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn")) as pool: | |
| for result in pool.map(windows_job, jobs, chunksize=1): | |
| for key, f in result.items(): | |
| p = plan[key] | |
| sl = slice(p["row"], p["row"] + len(p["starts"])) | |
| if "error" in f: | |
| errors[rows[key]["uuid"]] = f["error"] | |
| continue | |
| static[sl], junk[sl] = f["static"], f["junk"] | |
| done += 1 | |
| now = time.monotonic() | |
| if now - last > 60 or done == len(jobs): | |
| last = now | |
| print(f"[windows] {spec.name}: {done}/{len(jobs)} files, {now - started:.0f}s, " | |
| f"{len(errors)} failed episodes", flush=True) | |
| episode = np.concatenate([np.full(len(p["starts"]), k) for k, p in enumerate(plan)]) | |
| start = np.concatenate([p["starts"] for p in plan]).astype(np.int64) | |
| np.savez(work / "candidates.npz", episode=episode, start=start, static=static, junk=junk) | |
| (work / "episodes.json").write_text(json.dumps({"rows": rows, "errors": errors}) + "\n") | |
| print(f"[windows] {spec.name}: done; static {static[~junk].mean():.2%}, junk {junk.mean():.3%}, " | |
| f"{len(errors)} failed episodes", flush=True) | |
| # ------------------------------------------------------------------------------------------- select stage | |
| def draw_uniform(episode, groups, rate, rng): | |
| """For each boolean mask in groups: per-episode counts round(rate x candidates) (systematic), drawn uniformly.""" | |
| chosen = [] | |
| for group in groups: | |
| ids = np.flatnonzero(group) | |
| if not len(ids): | |
| continue | |
| cuts = np.r_[0, np.flatnonzero(np.diff(episode[ids])) + 1, len(ids)] | |
| sizes = np.diff(cuts) | |
| counts = np.minimum(systematic(rate * sizes, rng), sizes) | |
| for lo, hi, q in zip(cuts[:-1], cuts[1:], counts): | |
| if q: | |
| chosen.extend(rng.choice(ids[lo:hi], size=q, replace=False).tolist()) | |
| return np.sort(np.array(chosen, np.int64)) | |
| def stage_select(spec, work, quota, seed): | |
| if (work / "selection.npz").exists(): | |
| print(f"[select] {spec.name}: reusing selection.npz", flush=True) | |
| return | |
| c = np.load(work / "candidates.npz") | |
| info = json.loads((work / "episodes.json").read_text()) | |
| rows, errors = info["rows"], info["errors"] | |
| episode, static, junk = c["episode"], c["static"], c["junk"] | |
| failed = np.array([r["uuid"] in errors for r in rows], bool) | |
| group = np.array([r["group"] for r in rows]) | |
| usable = ~junk & ~failed[episode] | |
| train = usable & (group == "train")[episode] | |
| n_train = int(train.sum()) | |
| if quota > n_train: | |
| raise ValueError(f"quota {quota} exceeds {n_train} usable train candidates of the picked episodes") | |
| rate = quota / n_train | |
| rng = np.random.default_rng([seed, 1]) | |
| chosen = draw_uniform(episode, [train, usable & (group == "val")[episode], usable & (group == "val_ood")[episode]], | |
| rate, rng) | |
| picked_train = train[chosen] | |
| summary = {"quota": quota, "train_candidates": n_train, "rate": rate, "selected_train": int(picked_train.sum()), | |
| "selected_val": int(((group == "val")[episode][chosen]).sum()), | |
| "selected_val_ood": int(((group == "val_ood")[episode][chosen]).sum()), | |
| "train_episodes_with_chunks": int(len(np.unique(episode[chosen][picked_train]))), | |
| "static_share_train": float(static[chosen][picked_train].mean()), | |
| "static_share_pool": float(static[train].mean()), | |
| "failed_episodes": len(errors), "junk_share": float(junk.mean())} | |
| if summary["selected_train"] != quota: | |
| raise RuntimeError(f"drew {summary['selected_train']} train chunks, expected {quota}") | |
| np.savez(work / "selection.npz", chosen=chosen, rate=rate) | |
| (work / "selection.json").write_text(json.dumps(summary, indent=1) + "\n") | |
| print(f"[select] {spec.name}: {json.dumps(summary)}", flush=True) | |
| # ------------------------------------------------------------------------------------------- label stage | |
| def label_job(job): | |
| store = np.load(job["store"], mmap_mode="r") | |
| records = [] | |
| for r in job["episodes"]: | |
| chunks = [] | |
| for cand, start, out_row, static in r["chunks"]: | |
| values = np.asarray(store[cand], np.float16) | |
| lap.validate_window(values) | |
| rec = lap.chunk_record(r["uuid"], start, out_row, values) # no "direction": both records | |
| rec["selection"] = {"static": static} | |
| chunks.append(rec) | |
| records.append({"annotation_schema": SCHEMA, "dataset": job["dataset"], "fps": job["fps"], | |
| "split": r["split"], "episode_index": r["episode_index"], "episode_uuid": r["uuid"], | |
| "task": r["task"], "task_index": r["task_index"], "length": r["length"], | |
| "source_file": r["source"], "annotation_frame": "tool", "chunks": chunks}) | |
| return records | |
| def stage_label(spec, work, out, release_root, fraction, seed, workers): | |
| if (out / "meta.json").exists(): | |
| print(f"[label] {spec.name}: {out} exists", flush=True) | |
| return | |
| c = np.load(work / "candidates.npz") | |
| chosen = np.load(work / "selection.npz")["chosen"] | |
| rows = json.loads((work / "episodes.json").read_text())["rows"] | |
| errors = json.loads((work / "episodes.json").read_text())["errors"] | |
| files = json.loads((work / "files.json").read_text())["summary"] | |
| summary = json.loads((work / "selection.json").read_text()) | |
| episode, start, static = c["episode"], c["start"], c["static"] | |
| out.mkdir(parents=True, exist_ok=True) | |
| tmp_actions = out / "actions.tmp.npy" | |
| src = np.load(work / "candidates.npy", mmap_mode="r") | |
| actions = np.lib.format.open_memmap(tmp_actions, mode="w+", dtype=np.float16, shape=(len(chosen), SAMPLES, 16)) | |
| for lo in range(0, len(chosen), 65536): | |
| actions[lo:lo + 65536] = src[chosen[lo:lo + 65536]] | |
| actions.flush() | |
| del actions | |
| per_episode = defaultdict(list) | |
| for out_row, cand in enumerate(chosen): | |
| per_episode[int(episode[cand])].append((int(cand), int(start[cand]), out_row, bool(static[cand]))) | |
| episodes = [{**rows[k], "chunks": per_episode[k]} for k in sorted(per_episode)] | |
| jobs = [{"store": str(work / "candidates.npy"), "dataset": spec.name, "fps": spec.native_fps, | |
| "episodes": episodes[i:i + 200]} for i in range(0, len(episodes), 200)] | |
| counts = {"episodes": defaultdict(int), "chunks": defaultdict(int)} | |
| tmp_records = out / "episodes.jsonl.tmp" | |
| with open(tmp_records, "w", encoding="utf-8") as stream, ProcessPoolExecutor( | |
| workers, mp_context=multiprocessing.get_context("spawn")) as pool: | |
| for records in pool.map(label_job, jobs): | |
| for record in records: | |
| stream.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n") | |
| counts["episodes"][record["split"]] += 1 | |
| counts["chunks"][record["split"]] += len(record["chunks"]) | |
| digest = file_sha256(tmp_actions) | |
| tmp_actions.replace(out / "actions.npy") | |
| tmp_records.replace(out / "episodes.jsonl") | |
| chunk_index = release_root / spec.name / "meta/prepared/chunk_index.jsonl" | |
| meta = { | |
| "annotation_schema": SCHEMA, "dataset": spec.name, "frame": "tool", "fps": spec.native_fps, | |
| "chunk_index": f"{spec.name}/meta/prepared/chunk_index.jsonl of HF LehongWu/sft_data-action_lang_align-v3-1124", | |
| "chunk_index_sha256": file_sha256(chunk_index), | |
| "chunk_rule": ("uniform: whole source files picked per task (episode fraction), then every whole-second chunk " | |
| "of their episodes drawn at one rate per dataset (build_lap_uniform.py)"), | |
| "directions": "both: every chunk gives one LAP-A2L and one LAP-L2A record", | |
| "selection": {"episode_fraction": fraction, "seed": seed, "files": files, "summary": summary, | |
| "val_and_val_ood": "episodes of the picked files, uniform at the train rate"}, | |
| "horizons_seconds": list(lap.HORIZONS), "horizon_seed": lap.HORIZON_SEED, | |
| "l2a_fps": list(lap.L2A_FPS), "l2a_seed": lap.L2A_SEED, "label_precision": lap.LABEL_PRECISION, | |
| "label_reference": "measured-start", "label_timestamps": "exact-offset-seconds", | |
| "gripper": "absolute fraction-open target", "training_samples": lap.TRAINING_SAMPLES, | |
| "action_store": {"file": "actions.npy", "shape": [int(len(chosen)), SAMPLES, 16], "valid_rows": int(len(chosen)), | |
| "dtype": "float16", "fps": 60, "normalized": False, "sha256": digest}, | |
| "counts": {k: dict(v) for k, v in counts.items()}, | |
| "failed_episodes": errors, | |
| } | |
| (out / "meta.json").write_text(json.dumps(meta, indent=2) + "\n") | |
| print(f"[label] {spec.name}: {json.dumps(meta['counts'])} -> {out}", flush=True) | |
| # ------------------------------------------------------------------------------------------- convert stage | |
| def stage_convert(spec, out, sft_dir, release_root): | |
| if (sft_dir / out.name / "meta.json").exists(): | |
| print(f"[convert] {spec.name}: {sft_dir / out.name} exists", flush=True) | |
| return | |
| import convert_annotation_lap_to_sft_json as convert | |
| convert.idm.select_dataset(spec.name) | |
| episode_index = release_root / spec.name / "meta/prepared/episode_index.jsonl" # abc130k's held-out task names | |
| convert.convert(out, sft_dir, None, split_config={"episode_index": episode_index}) | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument("--dataset", choices=DATASETS, required=True) | |
| p.add_argument("--release-root", type=Path, required=True, | |
| help="download of HF LehongWu/sft_data-action_lang_align-v3-1124 (<dataset>/meta/prepared/)") | |
| p.add_argument("--out-root", type=Path, required=True, help="<dataset>/<RUN>/ and <dataset>/sft_json/<RUN>/") | |
| p.add_argument("--work-dir", type=Path, default=Path("/tmp/lehongw2/lap_uniform_work")) | |
| p.add_argument("--tmp", default="/tmp/lehongw2/lap_uniform_download", help="parquet scratch (deleted per file)") | |
| p.add_argument("--workers", type=int, default=48) | |
| p.add_argument("--episode-fraction", type=float, default=1 / 3) | |
| p.add_argument("--quota", type=int, default=None, help="train chunks (default: QUOTAS[dataset])") | |
| p.add_argument("--seed", type=int, default=1128) | |
| p.add_argument("--stages", nargs="+", default=["files", "windows", "select", "label", "convert"]) | |
| a = p.parse_args() | |
| for name in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"): | |
| os.environ[name] = "1" | |
| spec = prepared_datasets.get(a.dataset) | |
| work, out = a.work_dir / a.dataset, a.out_root / a.dataset / RUN | |
| release_root = a.release_root.resolve() | |
| Path(a.tmp).mkdir(parents=True, exist_ok=True) | |
| if "files" in a.stages: | |
| stage_files(spec, work, release_root, a.episode_fraction, a.seed) | |
| if "windows" in a.stages: | |
| stage_windows(spec, work, a.workers, a.tmp) | |
| if "select" in a.stages: | |
| stage_select(spec, work, a.quota or QUOTAS[a.dataset], a.seed) | |
| if "label" in a.stages: | |
| stage_label(spec, work, out, release_root, a.episode_fraction, a.seed, a.workers) | |
| if "convert" in a.stages: | |
| stage_convert(spec, out, a.out_root / a.dataset / "sft_json", release_root) | |
| if __name__ == "__main__": | |
| main() | |