#!/usr/bin/env python3 """Monitor a build_lap_selected.py run: the selected train chunks vs a uniform random draw with the same per-episode counts from the same candidates. AC2 tokens are a metric only (selection never uses them). Reports, per dataset and pooled: static share, effective number of per-arm motion types, AC2 token coverage (tokens present in >= 1 / 20 / 100 chunks), normalized token entropy, mean distinct tokens per chunk and, pooled, the mean count of the tokens that are rarest (bottom decile) under the random draw. Writes /selection_report.json. """ import argparse import json import sys from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent WORKSPACE = HERE.parents[1] AC2 = WORKSPACE / "external/actioncodec2" for path in (AC2 / "abc130k", WORKSPACE, WORKSPACE / "external/Loong/src", HERE): sys.path.insert(0, str(path)) from build_lap_selected import HELD_OUT_TASK_INDEX # noqa: E402 DATASETS = ("abc130k_zheyuan", "molmo_yam", "worldengine", "agibot_beta", "agibot26") TOKENIZER = AC2 / "checkpoints/abc130k_molmo_we_agibot-ac2-t0.005-r0.04-g0.05-v2048-sv1536-tf0.5/tokenizer" TOKEN_OFFSET, VOCAB = 4096, 2048 def effective(values): _, counts = np.unique(values, return_counts=True) p = counts / counts.sum() return float(np.exp(-(p * np.log(p)).sum())) def token_sets(codec, store, rows): """Distinct AC2 token ids per chunk; the 61-row 60 Hz window becomes AC2's (2 arms, 31 rows @30 Hz, 7).""" import ac2_abc130k rows = np.sort(rows) out = [] for lo in range(0, len(rows), 8192): w = np.asarray(store[rows[lo:lo + 8192]], np.float32) w30 = np.stack([w[:, ::2, 0:7], w[:, ::2, 8:15]], axis=1) out += [np.unique(t) - TOKEN_OFFSET for t in ac2_abc130k.encode(codec, w30, fps=30.0)] return out def token_counts(sets): ids = np.concatenate(sets) if ids.min() < 0 or ids.max() >= VOCAB: raise ValueError("unexpected AC2 token ids") return np.bincount(ids, minlength=VOCAB) def token_metrics(sets): c = token_counts(sets) p = c[c > 0] / c.sum() return {"tokens_ge1": int((c >= 1).sum()), "tokens_ge20": int((c >= 20).sum()), "tokens_ge100": int((c >= 100).sum()), "token_entropy_norm": float(-(p * np.log(p)).sum() / np.log(VOCAB)), "distinct_tokens_per_chunk": float(np.mean([len(s) for s in sets]))} def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--work-dir", type=Path, default=Path("/tmp/lehongw2/lap_selected_work")) ap.add_argument("--datasets", nargs="+", default=list(DATASETS)) ap.add_argument("--seed", type=int, default=0) a = ap.parse_args() import ac2_abc130k codec = ac2_abc130k.load(str(TOKENIZER)) rng = np.random.default_rng(a.seed) report, pooled = {}, {"selected": [], "random": []} for d in a.datasets: work = a.work_dir / d c, sel = np.load(work / "candidates.npz"), np.load(work / "selection.npz") rows = json.loads((work / "episodes.json").read_text())["rows"] episode, static, types = c["episode"], c["static"], c["types"] held = HELD_OUT_TASK_INDEX.get(d, set()) train_ep = np.array([r["split"] == "train" and r["task_index"] not in held for r in rows]) pool = (sel["weight"] > 0) & train_ep[episode] # the candidates the weighted draw chose from selected = sel["chosen"][pool[sel["chosen"]]] counts = np.bincount(episode[selected], minlength=len(rows)) order = np.flatnonzero(pool) cuts = np.r_[0, np.flatnonzero(np.diff(episode[order])) + 1, len(order)] baseline = np.concatenate([rng.choice(order[lo:hi], counts[episode[order[lo]]], replace=False) for lo, hi in zip(cuts[:-1], cuts[1:]) if counts[episode[order[lo]]]]) store = np.load(work / "candidates.npy", mmap_mode="r") report[d] = {} for name, idx in (("selected", selected), ("random", baseline)): sets = token_sets(codec, store, idx) pooled[name] += sets report[d][name] = {"chunks": int(len(idx)), "static_share": float(static[idx].mean()), "effective_types_left_right": [effective(types[idx, 0]), effective(types[idx, 1])], **token_metrics(sets)} print(d, json.dumps(report[d]), flush=True) reference = token_counts(pooled["random"]) rare = np.flatnonzero((reference > 0) & (reference <= np.quantile(reference[reference > 0], 0.1))) report["pooled"] = {name: {**token_metrics(sets), "rarest_decile_mean_count": float(token_counts(sets)[rare].mean())} for name, sets in pooled.items()} print("pooled", json.dumps(report["pooled"]), flush=True) (a.work_dir / "selection_report.json").write_text(json.dumps(report, indent=1) + "\n") if __name__ == "__main__": main()