#!/usr/bin/env python3 """Build the ActionCodec2 token map for sera-vla-v4_1 (SPEC in WORKLOG). Fits the official ActionCodec2 first-order EEF tokenizer (variant paper-o1-5mm-4k-2bin-1p2ms: 5 mm / 0.02 rad tolerances, binary gripper, Set-BPE vocab 4,096) on the TRAIN split of lerobot/libero at native fps 10 — merges fit on train episodes only — then encodes, for every (episode, frame), the token stream of the 16-step action window starting at that frame in two clamping variants: base: window clamped at the episode end; seg: window clamped at the DATA V2 segment end (train frames; identical to base on eval episodes). The v4_1 training forward picks the variant whose clamping matches the batch item's action_is_pad pattern, so DATA V2 segment samples get segment-pure token targets while base samples keep full-window targets. Stored LIBERO commands are converted to physical units (x0.05 m translation, x0.5 rad rotation-vector, gripper stored -1=open/+1=closed -> codec open-command (1-g)/2) before encoding. EEF token ids are remapped from the artifact's [4096, 8192) band to [0, 4096); the policy adds the offset back before decode. Outputs (in ~/sera_v4_experiments/quest_probe/): acodec2_tokenizer/ fitted AutoProcessor artifact acodec2_map.npz tok_base_ids/len, tok_seg_ids/len [1693, MAXFR, LMAX], ep_len, train/eval episode lists, id_offset, vocab acodec2_map_summary.json atoms, vocab used, tokens/step acodec2_fit_report.json raw codec training report """ import glob import json import math import os import time from collections import defaultdict import numpy as np import pandas as pd SNAP = os.path.expanduser( "~/.cache/huggingface/hub/datasets--lerobot--libero/snapshots/" "a1aaacb7f6cd6ee5fb43120f673cebb0cfea7dd4" ) OUT_DIR = os.path.expanduser("~/sera_v4_experiments/quest_probe") FPS = 10 WIN = 16 LMAX_CAP = 160 CHUNK = 8192 def to_phys(a: np.ndarray) -> np.ndarray: out = np.empty_like(a) out[:, 0:3] = a[:, 0:3] * 0.05 out[:, 3:6] = a[:, 3:6] * 0.5 out[:, 6] = (1.0 - a[:, 6]) / 2.0 return out def main() -> None: os.makedirs(OUT_DIR, exist_ok=True) t00 = time.time() files = sorted(glob.glob(SNAP + "/data/chunk-000/*.parquet")) frames = pd.concat( [pd.read_parquet(f, columns=["episode_index", "frame_index", "task_index", "action"]) for f in files], ignore_index=True, ) frames = frames.sort_values(["episode_index", "frame_index"]).reset_index(drop=True) act = np.stack(frames["action"].to_numpy()).astype(np.float32) ep_arr = frames["episode_index"].to_numpy() starts = np.flatnonzero(np.r_[True, ep_arr[1:] != ep_arr[:-1]]) ends = np.r_[starts[1:], len(ep_arr)] ep_rows = {} for s, e in zip(starts.tolist(), ends.tolist()): ep_rows[int(ep_arr[s])] = (int(s), int(e)) all_eps = sorted(ep_rows) n_ep = max(all_eps) + 1 ep_len = np.zeros(n_ep, dtype=np.int64) for ep, (s, e) in ep_rows.items(): ep_len[ep] = e - s maxfr = int(ep_len.max()) print(f"episodes={len(all_eps)} frames={len(frames)} maxfr={maxfr}", flush=True) seg = np.load(os.path.join(OUT_DIR, "segment_map.npz")) train_eps = [int(x) for x in seg["train_eps"].tolist()] train_set = set(train_eps) eval_eps = [ep for ep in all_eps if ep not in train_set] seg_end_of = { int(k): int(v) for k, v in zip(seg["frame_key"].tolist(), seg["frame_seg_end"].tolist()) } print(f"split: {len(train_eps)} train / {len(eval_eps)} eval", flush=True) phys_eps = {} for ep in all_eps: s, e = ep_rows[ep] phys_eps[ep] = to_phys(act[s:e]) from transformers import AutoProcessor codec = AutoProcessor.from_pretrained( "ZibinDong/ActionCodec2", variant="paper-o1-5mm-4k-2bin-1p2ms", action_space="single_eef_delta", trust_remote_code=True, ) t0 = time.time() out = codec.fit([phys_eps[ep] for ep in train_eps], fps=FPS, progress=False) if out is not None: codec = out fit_s = time.time() - t0 rep = getattr(codec, "training_report", {}) with open(os.path.join(OUT_DIR, "acodec2_fit_report.json"), "w") as f: json.dump(rep, f, indent=1, default=str) eef_rep = rep.get("profiles", {}).get("eef", {}) if isinstance(rep, dict) else {} print(f"fit done in {fit_s:.1f}s; eef vocab={eef_rep.get('vocab_size')} " f"tokens/action(train, episode-level)={eef_rep.get('tokens_per_action')}", flush=True) codec.save_pretrained(os.path.join(OUT_DIR, "acodec2_tokenizer")) # ---- encode windows, grouped by window length ---- def encode_group(windows): """windows: list of (L,7) arrays of equal L -> list of id lists.""" res = [] for i in range(0, len(windows), CHUNK): batch = np.stack(windows[i:i + CHUNK]) res.extend(codec.encode(batch, fps=FPS)) return res variants = {"base": {}, "seg": {}} for name in ("base", "seg"): by_len = defaultdict(list) keys_by_len = defaultdict(list) for ep in all_eps: s, e = ep_rows[ep] n = e - s arr = phys_eps[ep] for fr in range(n): if name == "base": ln = min(WIN, n - fr) else: se = seg_end_of.get(ep * 100000 + fr) ln = min(WIN, n - fr) if se is None else min(WIN, se - fr + 1) by_len[ln].append(arr[fr:fr + ln]) keys_by_len[ln].append((ep, fr)) store = {} for ln in sorted(by_len): toks = encode_group(by_len[ln]) assert len(toks) == len(keys_by_len[ln]) for key, tk in zip(keys_by_len[ln], toks): store[key] = tk variants[name] = store tot_tok = sum(len(v) for v in store.values()) tot_step = sum(min(WIN, ep_len[ep] - fr) for (ep, fr) in store) print(f"{name}: {len(store)} windows, {tot_tok} tokens, " f"window tokens/step={tot_tok / tot_step:.4f}", flush=True) all_ids = np.concatenate( [np.asarray(v, dtype=np.int64) for v in variants["base"].values() if v] ) id_min, id_max = int(all_ids.min()), int(all_ids.max()) print(f"base id range: [{id_min}, {id_max}]", flush=True) assert id_min >= 4096 and id_max < 8192, ( f"EEF ids not confined to [4096, 8192): [{id_min}, {id_max}] — remap assumption broken" ) OFFSET = 4096 lens = [len(v) for v in variants["base"].values()] + [len(v) for v in variants["seg"].values()] lmax = int(max(lens)) print(f"token length per window: mean={np.mean(lens):.2f} p50={np.percentile(lens, 50):.0f} " f"p95={np.percentile(lens, 95):.0f} p99={np.percentile(lens, 99):.0f} max={lmax}", flush=True) assert lmax <= LMAX_CAP, f"window token length {lmax} exceeds cap {LMAX_CAP}" arrays = {} for name in ("base", "seg"): ids = np.zeros((n_ep, maxfr, lmax), dtype=np.int32) ln_arr = np.zeros((n_ep, maxfr), dtype=np.int16) for (ep, fr), tk in variants[name].items(): remapped = np.asarray(tk, dtype=np.int64) - OFFSET ids[ep, fr, :len(tk)] = remapped ln_arr[ep, fr] = len(tk) arrays[f"tok_{name}_ids"] = ids arrays[f"tok_{name}_len"] = ln_arr np.savez_compressed( os.path.join(OUT_DIR, "acodec2_map.npz"), ep_len=ep_len, train_eps=np.asarray(train_eps), eval_eps=np.asarray(eval_eps), id_offset=np.int64(OFFSET), vocab=np.int64(4096), **arrays, ) # ---- episode-level tokens/step (paper-comparable) + vocab usage ---- def episode_tokens_per_step(eps): tt = 0 for ep in eps: tt += len(codec.encode(phys_eps[ep][None], fps=FPS)[0]) ts = sum(int(ep_len[ep]) for ep in eps) return tt / ts, tt, ts tr_tps, tr_t, tr_s = episode_tokens_per_step(train_eps) ev_tps, ev_t, ev_s = episode_tokens_per_step(eval_eps) used = np.unique( np.concatenate([np.asarray(v) for v in variants["base"].values() if v]) ) summary = { "fit_seconds": fit_s, "fit_episodes": len(train_eps), "eef_vocab_size": eef_rep.get("vocab_size"), "primitive_atoms": eef_rep.get("primitive_atoms"), "physical_bins": eef_rep.get("physical_bins"), "eef_spatial_vocab_size": eef_rep.get("temporal", {}).get("spatial_vocab_size") if isinstance(eef_rep.get("temporal"), dict) else None, "vocab_used_train_windows": int(len(used)), "id_offset": OFFSET, "id_range_raw": [id_min, id_max], "tokens_per_step_episode_level": {"train": tr_tps, "eval": ev_tps}, "tokens_per_step_window_level": { name: sum(len(v) for v in variants[name].values()) / sum(min(WIN, ep_len[ep] - fr) for (ep, fr) in variants[name]) for name in ("base", "seg") }, "window_token_length": { "mean": float(np.mean(lens)), "p50": float(np.percentile(lens, 50)), "p95": float(np.percentile(lens, 95)), "p99": float(np.percentile(lens, 99)), "max": lmax, }, "total_seconds": time.time() - t00, } with open(os.path.join(OUT_DIR, "acodec2_map_summary.json"), "w") as f: json.dump(summary, f, indent=1) print(json.dumps(summary, indent=1), flush=True) print("BUILD DONE", flush=True) if __name__ == "__main__": main()