Download code/build_lap_selected.py from LehongWu/sft_lap_data-1128: direct link, hf CLI and curl.
- Browser
- Download file 27.3 kB
-
https://huggingface.co/datasets/LehongWu/sft_lap_data-1128/resolve/main/code/build_lap_selected.py
- Command line
-
hf download hf://datasets/LehongWu/sft_lap_data-1128/code/build_lap_selected.py
-
curl -L -o build_lap_selected.py https://huggingface.co/datasets/LehongWu/sft_lap_data-1128/resolve/main/code/build_lap_selected.py
27.3 kB
| #!/usr/bin/env python3 | |
| """LAP with soft, tokenizer-agnostic chunk selection (abc130k_zheyuan, molmo_yam, worldengine, agibot_beta, agibot26). | |
| Instead of annotate_lap.py's "up to 32 random chunks per episode", every whole-second chunk [t, t+1] of every | |
| prepared episode is a candidate, and a fixed number of train chunks per dataset is drawn with mild preference for | |
| uncommon motion and against near-duplicates. The text is still computed from the actions (annotate_lap.chunk_record). | |
| Stages (per dataset; each stage's output is reused if present): | |
| windows every candidate's (61, 16) float16 cartesian_tool window at 60 Hz (the same Loong path as | |
| annotate_lap.py; Agibot builds the episode from its canonical20 Cartesian streams, downloaded per | |
| parquet file from S3) plus three features per window: | |
| static LAP's own definition: both arms read "pose static" with an unchanged gripper at every | |
| eighth-second label point t + i/8 s (1 cm / 5 degrees / 10% rounding, no deadband) | |
| type per arm, the sign (-, 0, +) of each of the 7 rounded dims at t+1 s (3^7 types per arm) | |
| junk non-finite, a 15 Hz step > 0.25 m or > 1.0 rad, or > 1.0 m from the start | |
| -> <work-dir>/<dataset>/candidates.npy, candidates.npz | |
| select train episodes (held-out tasks excluded): quota = --quota items, spread over episodes in | |
| proportion to their candidate count (systematic rounding, exact total). Weight per candidate | |
| (sqrt(q_left * q_right))^-gamma / median, clipped to [floor, ceiling], where q is how common that arm's | |
| type is among the dataset's train candidates; static candidates share one weight that makes them | |
| about --static-share of the expected picks. Within an episode, picks are drawn proportional to weight, | |
| and each pick multiplies the remaining candidates' weights by sqrt(repeat) per arm with the same type. | |
| val episodes and held-out-task train episodes (val_ood): uniform random at the same rate, so | |
| evaluation follows the natural distribution. Each chunk gets one direction, LAP-A2L or LAP-L2A (50/50, | |
| seeded by uuid and start). -> <work-dir>/<dataset>/selection.npz | |
| label <output-root>/actions.npy (the selected windows), episodes.jsonl (lap-episode-v2: annotate_lap's chunk | |
| records plus "direction" and "selection"), meta.json. convert_annotation_lap_to_sft_json.py --dataset | |
| <name> turns them into LAP-A2L / LAP-L2A manifests (one item per chunk, its direction). | |
| Usage: | |
| python build_lap_selected.py --dataset molmo_yam --quota 112110 --workers 16 | |
| """ | |
| import argparse | |
| from collections import defaultdict | |
| from concurrent.futures import ProcessPoolExecutor | |
| import hashlib | |
| import json | |
| import math | |
| import multiprocessing | |
| import os | |
| from pathlib import Path | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import numpy as np | |
| WORKSPACE = Path(__file__).resolve().parents[2] | |
| for path in (WORKSPACE, WORKSPACE / "external/Loong/src", Path(__file__).resolve().parent): | |
| if str(path) not in sys.path: | |
| sys.path.insert(0, str(path)) | |
| from action_language_alignment.vllm_action_annotation import prepared_datasets # noqa: E402 | |
| import annotate_lap as lap # noqa: E402 | |
| SCHEMA = "lap-episode-v2" | |
| BUCKET = "cmu-aire-loong-data" | |
| SAMPLES = lap.STORE_SAMPLES # 61 rows at 60 Hz | |
| # IDM train items / 2 (2026-11-25 manifests), so IDM : LAP = 2 : 1 per dataset | |
| QUOTAS = {"abc130k_zheyuan": 320691, "molmo_yam": 112110, "worldengine": 202236, | |
| "agibot_beta": 173466, "agibot26": 87909} | |
| HELD_OUT_TASK_INDEX = {"abc130k_zheyuan": {39, 79, 119, 159}} # convert_annotation_idm_to_sft_json VAL_OOD_TASK_IDS | |
| LABEL_POSITIONS = [7.5 * i for i in range(1, 9)] # t + i/8 s on the 60 Hz rows | |
| ARMS = (0, 8) | |
| # ------------------------------------------------------------------------------------------- features | |
| def window_features(w): | |
| """w (N, 61, 16) -> static (N,), type (N, 2) int, junk (N,). Vectorized; rotation between rows is | |
| interpolated on the rotation vector (annotate_lap uses SLERP; identical at this rounding but for rare ties).""" | |
| from scipy.spatial.transform import Rotation | |
| w = w.astype(np.float64) | |
| n = len(w) | |
| finite = np.isfinite(w).all((1, 2)) | |
| w = np.where(finite[:, None, None], w, 0.0) | |
| static = np.ones(n, bool) | |
| types = np.zeros((n, 2), np.int64) | |
| for a, off in enumerate(ARMS): | |
| p, r, g = w[:, :, off:off + 3], w[:, :, off + 3:off + 6], w[:, :, off + 6] | |
| def units(pos, rot, grip): | |
| cm = np.round(pos * 100) | |
| deg = np.round(Rotation.from_rotvec(rot.reshape(-1, 3)).as_euler("xyz", degrees=True).reshape(rot.shape) / 5) | |
| gr = np.round((grip - g[:, :1]) / 0.1) | |
| return np.concatenate([cm, deg, gr[..., None]], -1) | |
| lo = np.floor(LABEL_POSITIONS).astype(int) | |
| hi = np.ceil(LABEL_POSITIONS).astype(int) | |
| alpha = (np.array(LABEL_POSITIONS) - lo)[None, :, None] | |
| pos = (1 - alpha) * p[:, lo] + alpha * p[:, hi] | |
| rot = (1 - alpha) * r[:, lo] + alpha * r[:, hi] | |
| u = units(pos, rot, g[:, lo]) # gripper target is held (row lo), as in describe_timestamp | |
| static &= (u == 0).all((1, 2)) | |
| end = units(p[:, 60:61], r[:, 60:61], g[:, 60:61])[:, 0] | |
| types[:, a] = ((np.sign(end) + 1) * 3 ** np.arange(7)).sum(1) | |
| step_t = np.linalg.norm(np.diff(w[:, ::4][..., [0, 1, 2, 8, 9, 10]].reshape(n, -1, 2, 3), axis=1), axis=-1).max((1, 2)) | |
| step_r = np.linalg.norm(np.diff(w[:, ::4][..., [3, 4, 5, 11, 12, 13]].reshape(n, -1, 2, 3), axis=1), axis=-1).max((1, 2)) | |
| far = np.linalg.norm(w[..., [0, 1, 2, 8, 9, 10]].reshape(n, SAMPLES, 2, 3), axis=-1).max((1, 2)) | |
| junk = ~finite | (step_t > 0.25) | (step_r > 1.0) | (far > 1.0) | |
| return static, types, junk | |
| # ------------------------------------------------------------------------------------------- windows stage | |
| def starts_for(length, fps): | |
| """Whole-second starts whose 61-sample 60 Hz window needs no padding (30 FPS reads rows 30t..30t+31).""" | |
| last = fps + (1 if fps == 30 else 0) | |
| return np.arange(max(0, (length - 1 - last) // fps + 1)) if length - 1 >= last else np.zeros(0, int) | |
| class CanonicalEpisode: | |
| """CartesianEpisode for streams that are already canonical20 absolute Cartesian (Agibot).""" | |
| def __init__(self, actions, states, native_fps): | |
| import torch | |
| from loong.data.hetero_stride import StridedHeteroActionChunkDataset | |
| from loong.data.lerobot import Episode | |
| from loong.data.norm_stats import NormStats | |
| episode = Episode(action=actions.astype(np.float32), state=states.astype(np.float32), num_arms=2, | |
| native_fps=native_fps) | |
| self.frame_count = len(actions) | |
| self.dataset = StridedHeteroActionChunkDataset([episode], action_horizon=SAMPLES, action_frame="tool", | |
| cart_stride_auto=False, | |
| norm_stats=NormStats(-torch.ones(24), torch.ones(24))) | |
| def window(self, frame, representation="cartesian_tool"): | |
| from loong.data.lerobot import GROUP_CART | |
| return np.concatenate([self.dataset._raw_group(0, frame, arm, GROUP_CART) for arm in range(2)], axis=1) | |
| def _read_parquet(job): | |
| """{episode key: (states, commands, frame_index, timestamp)} of one source parquet file.""" | |
| import pyarrow as pa | |
| import pyarrow.compute as pc | |
| import pyarrow.parquet as pq | |
| dataset, source, episodes, tmp = job["dataset"], job["source"], job["episodes"], job["tmp"] | |
| spec = prepared_datasets.get(dataset) | |
| cartesian = spec.action_format == "canonical20" | |
| local = None | |
| if cartesian: | |
| local = Path(tmp) / source.replace("/", "__") # full key: every repo has its own file-000.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: | |
| break | |
| time.sleep(5 * (attempt + 1)) | |
| else: | |
| raise RuntimeError(f"download failed: {r.stderr.strip()[-300:]}") | |
| path, cols = local, ["episode_index", "frame_index", "timestamp", "observation.state", "action"] | |
| else: | |
| path, cols = source, ["episode_index", "frame_index", "timestamp", "joint_state", "joint_action"] | |
| try: | |
| table = pq.read_table(path, columns=cols) | |
| wanted = sorted({e["source_episode"] for e in episodes}) | |
| table = table.filter(pc.is_in(table["episode_index"], value_set=pa.array(wanted))) | |
| finally: | |
| if local is not None: | |
| local.unlink(missing_ok=True) | |
| ep = table["episode_index"].to_numpy() | |
| out = {} | |
| for e in episodes: | |
| m = np.flatnonzero(ep == e["source_episode"]) | |
| part = table.take(m) | |
| 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 parquet 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"] | |
| results = {} | |
| try: | |
| streams = _read_parquet(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+") | |
| 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 in ("agibot_beta", "agibot26"): | |
| episode = 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, types, junk = window_features(values) | |
| ok = np.array([True] * len(values)) | |
| for i, v in enumerate(values): | |
| try: | |
| lap.validate_window(v) | |
| except ValueError: | |
| ok[i] = False | |
| results[e["key"]] = {"static": static, "types": types, "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 episode_rows(spec, limit_files=None): | |
| """Prepared chunk_index rows (train + val), with their source parquet and source episode number.""" | |
| rows = [] | |
| with open(spec.chunk_index, encoding="utf-8") as stream: | |
| for line in stream: | |
| r = json.loads(line) | |
| if r.get("excluded"): | |
| continue | |
| if spec.action_format == "canonical20": | |
| source, source_episode = r["data_key"], r["source_episode_index"] | |
| else: | |
| source = str(spec.parquet_path(r["split"], r["data"]["chunk_index"], r["data"]["file_index"])) | |
| source_episode = r["episode_index"] | |
| rows.append({"split": r["split"], "episode_index": r["episode_index"], "uuid": r["uuid"], | |
| "task": r["task"], "task_index": r.get("task_index", r.get("task_id")), | |
| "length": r["length"], "source": source, "source_episode": source_episode}) | |
| if limit_files: # testing: only the episodes of the first N source files of each split | |
| keep = {s for split in ("train", "val") | |
| for s in sorted({r["source"] for r in rows if r["split"] == split})[:limit_files]} | |
| rows = [r for r in rows if r["source"] in keep] | |
| rows.sort(key=lambda r: (r["split"], r["episode_index"])) | |
| return rows | |
| def stage_windows(spec, work, workers, tmp, limit_files=None): | |
| if (work / "candidates.npz").exists(): | |
| print(f"[windows] {spec.name}: reusing {work}", flush=True) | |
| return | |
| fps = spec.native_fps | |
| rows = episode_rows(spec, limit_files) | |
| 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 | |
| work.mkdir(parents=True, exist_ok=True) | |
| 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} | |
| 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) | |
| types = np.zeros((total, 2), np.int64) | |
| 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], types[sl], junk[sl] = f["static"], f["types"], 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)]) if total else np.zeros(0, int) | |
| start = np.concatenate([p["starts"] for p in plan]).astype(np.int64) if total else np.zeros(0, int) | |
| np.savez(work / "candidates.npz", episode=episode, start=start, static=static, types=types, 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 systematic(x, rng): | |
| """Integer counts with each count in {floor(x), ceil(x)} and the total equal to round(sum(x)).""" | |
| c = np.cumsum(x) | |
| u = rng.random() | |
| edges = np.floor(np.r_[0, c] + u) | |
| return np.diff(edges).astype(int) | |
| def freq(values): | |
| _, inverse, counts = np.unique(values, return_inverse=True, return_counts=True) | |
| return counts[inverse] / len(values) | |
| def direction(uuid, start, seed): | |
| h = hashlib.sha256(json.dumps([seed, uuid, int(start), "direction"]).encode()).digest() | |
| return "LAP-A2L" if h[0] % 2 == 0 else "LAP-L2A" | |
| def draw(episode, types, weight, train, other, rate, a): | |
| """Per-episode weighted draw (train) and uniform draw (val / val_ood) at the same rate; fixed seed.""" | |
| rng = np.random.default_rng(a.seed) | |
| chosen = [] | |
| for group, uniform in ((train, False), (other, True)): | |
| 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) | |
| quotas = np.minimum(systematic(rate * sizes, rng), sizes) | |
| for (lo, hi), q in zip(zip(cuts[:-1], cuts[1:]), quotas): | |
| cand = ids[lo:hi] | |
| ww = weight[cand].copy() | |
| tl, tr = types[cand, 0], types[cand, 1] | |
| for _ in range(q): | |
| i = rng.choice(len(cand), p=ww / ww.sum()) | |
| chosen.append(cand[i]) | |
| ww[i] = 0 | |
| if not uniform and a.repeat != 1: | |
| ww *= math.sqrt(a.repeat) ** ((tl == tl[i]).astype(int) + (tr == tr[i]).astype(int)) | |
| if ww.sum() <= 0: | |
| break | |
| return np.sort(np.array(chosen, np.int64)) | |
| def stage_select(spec, work, quota, a): | |
| 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, types, junk = c["episode"], c["static"], c["types"], c["junk"] | |
| held = HELD_OUT_TASK_INDEX.get(spec.name, set()) | |
| failed = np.array([rows[k]["uuid"] in errors for k in range(len(rows))], bool) | |
| split = np.array([rows[k]["split"] for k in range(len(rows))]) | |
| weighted_ep = (split == "train") & ~np.array([rows[k]["task_index"] in held for k in range(len(rows))]) | |
| usable = ~junk & ~failed[episode] | |
| train = usable & weighted_ep[episode] | |
| n_train = int(train.sum()) | |
| if quota > n_train: | |
| raise ValueError(f"quota {quota} exceeds {n_train} usable train candidates") | |
| rate = quota / n_train | |
| weight = np.zeros(len(episode)) | |
| t = np.flatnonzero(train) | |
| w = np.sqrt(freq(types[t, 0]) * freq(types[t, 1])) ** -a.gamma | |
| moving = ~static[t] | |
| w = np.clip(w / np.median(w[moving]), a.floor, a.ceiling) | |
| if (~moving).any() and moving.any(): | |
| w[~moving] = min(a.static_share / (1 - a.static_share) * w[moving].sum() / (~moving).sum(), 1.0) | |
| weight[t] = w | |
| other = usable & ~weighted_ep[episode] | |
| weight[other] = 1.0 | |
| for attempt in range(8): # static share is a hard limit: halve the static weight until the draw respects it | |
| chosen = draw(episode, types, weight, train, other, rate, a) | |
| share = float(static[chosen][train[chosen]].mean()) | |
| if share <= a.static_share or not static[t].any(): | |
| break | |
| print(f"[select] {spec.name}: static share {share:.4%} > {a.static_share:.2%}; halving the static weight", | |
| flush=True) | |
| weight[t[~moving]] *= 0.5 | |
| else: | |
| raise RuntimeError(f"static share {share:.4%} still above {a.static_share:.2%}") | |
| n_sel_train = int(train[chosen].sum()) | |
| np.savez(work / "selection.npz", chosen=chosen, weight=weight, rate=rate) | |
| summary = {"quota": quota, "train_candidates": n_train, "rate": rate, "selected_train": n_sel_train, | |
| "selected_other": int(len(chosen) - n_sel_train), | |
| "static_share_train": float(static[chosen][train[chosen]].mean()), | |
| "static_share_pool": float(static[t].mean()), | |
| "weight_ess": float(w.sum() ** 2 / (w ** 2).sum() / len(w)), | |
| "effective_types_per_arm": [float(np.exp(-(p * np.log(p)).sum())) for p in | |
| (np.unique(types[chosen][train[chosen], k], return_counts=True)[1] / | |
| n_sel_train for k in (0, 1))]} | |
| (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 i, (cand, start, out_row, weight, direction_, static) in enumerate(r["chunks"]): | |
| values = np.asarray(store[cand], np.float16) | |
| lap.validate_window(values) | |
| rec = lap.chunk_record(r["uuid"], start, out_row, values) | |
| rec["direction"] = direction_ | |
| rec["selection"] = {"weight": round(weight, 4), "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"], | |
| "annotation_frame": "tool", "chunks": chunks}) | |
| return records | |
| def file_sha256(path): | |
| digest = hashlib.sha256() | |
| with open(path, "rb") as stream: | |
| for block in iter(lambda: stream.read(8 << 20), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def stage_label(spec, work, out, a): | |
| if (out / "meta.json").exists(): | |
| print(f"[label] {spec.name}: {out} exists", flush=True) | |
| return | |
| c = np.load(work / "candidates.npz") | |
| sel = np.load(work / "selection.npz") | |
| info = json.loads((work / "episodes.json").read_text()) | |
| rows = info["rows"] | |
| chosen, weight = sel["chosen"], sel["weight"] | |
| 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): | |
| k = int(episode[cand]) | |
| per_episode[k].append((int(cand), int(start[cand]), out_row, float(weight[cand]), | |
| direction(rows[k]["uuid"], start[cand], a.seed), 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), "directions": defaultdict(int)} | |
| tmp_records = out / "episodes.jsonl.tmp" | |
| with open(tmp_records, "w", encoding="utf-8") as stream, ProcessPoolExecutor( | |
| a.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"]) | |
| for ch in record["chunks"]: | |
| counts["directions"][ch["direction"]] += 1 | |
| digest = file_sha256(tmp_actions) | |
| tmp_actions.replace(out / "actions.npy") | |
| tmp_records.replace(out / "episodes.jsonl") | |
| summary = json.loads((work / "selection.json").read_text()) | |
| meta = { | |
| "annotation_schema": SCHEMA, "dataset": spec.name, "frame": "tool", "fps": spec.native_fps, | |
| "chunk_index": str(spec.chunk_index), "chunk_index_sha256": file_sha256(spec.chunk_index), | |
| "chunk_rule": "every whole-second chunk is a candidate; soft per-arm motion-type selection (build_lap_selected.py)", | |
| "selection": {"quota": summary["quota"], "gamma": a.gamma, "floor": a.floor, "ceiling": a.ceiling, | |
| "repeat": a.repeat, "static_share": a.static_share, "seed": a.seed, "summary": summary, | |
| "val_and_val_ood": "uniform random 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": info["errors"], | |
| } | |
| (out / "meta.json").write_text(json.dumps(meta, indent=2) + "\n") | |
| print(f"[label] {spec.name}: {json.dumps(meta['counts'])} -> {out}", flush=True) | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument("--dataset", choices=prepared_datasets.NAMES, required=True) | |
| p.add_argument("--quota", type=int, default=None, help="train chunks (default: QUOTAS[dataset])") | |
| p.add_argument("--output-root", type=Path, default=None, | |
| help="default: data/<dataset>/annotate_lap-selected-soft_arm-261125") | |
| p.add_argument("--work-dir", type=Path, default=Path("/tmp/lehongw2/lap_selected_work"), | |
| help="candidate windows (regenerable, node-local)") | |
| p.add_argument("--tmp", default="/tmp/lehongw2/lap_selected_download", help="Agibot parquet scratch") | |
| p.add_argument("--workers", type=int, default=16) | |
| p.add_argument("--gamma", type=float, default=0.3) | |
| p.add_argument("--floor", type=float, default=0.5) | |
| p.add_argument("--ceiling", type=float, default=3.0) | |
| p.add_argument("--repeat", type=float, default=0.5) | |
| p.add_argument("--static-share", type=float, default=0.005) | |
| p.add_argument("--seed", type=int, default=0) | |
| p.add_argument("--stages", nargs="+", default=["windows", "select", "label"]) | |
| p.add_argument("--limit-files", type=int, default=None, help="testing: first N source files per split") | |
| 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) | |
| quota = a.quota or QUOTAS[a.dataset] | |
| work = a.work_dir / a.dataset | |
| out = a.output_root or spec.data_dir / "annotate_lap-selected-soft_arm-261125" | |
| Path(a.tmp).mkdir(parents=True, exist_ok=True) | |
| if "windows" in a.stages: | |
| stage_windows(spec, work, a.workers, a.tmp, a.limit_files) | |
| if "select" in a.stages: | |
| stage_select(spec, work, quota, a) | |
| if "label" in a.stages: | |
| stage_label(spec, work, out, a) | |
| if __name__ == "__main__": | |
| main() | |