TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report
b4396f0 verified Download code/sera_v4/tools/build_segment_map.py from phammminhhieu/trace-vla-code: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/phammminhhieu/trace-vla-code/resolve/main/code/sera_v4/tools/build_segment_map.py
- Command line
-
hf download hf://phammminhhieu/trace-vla-code/code/sera_v4/tools/build_segment_map.py
-
curl -L -o build_segment_map.py https://huggingface.co/phammminhhieu/trace-vla-code/resolve/main/code/sera_v4/tools/build_segment_map.py
13.6 kB
| #!/usr/bin/env python3 | |
| """Build the gripper-event segment map for DATA V2 (SPEC in WORKLOG). | |
| Segments: debounced gripper-command sign changes on action[6]; | |
| segment k ends at boundary k (the switching frame belongs to the | |
| segment it completes); the tail after the last boundary merges | |
| into the last segment. Typing walks an ordered per-task sub-goal | |
| list: a segment ending in a transition INTO closed takes the | |
| current sub-goal's grasp phrase; INTO open takes its release | |
| phrase and advances the pointer. Train episodes only (factory | |
| split replicated: per task, last ceil(0.1*n) episodes held out). | |
| Outputs (in ~/sera_v4_experiments/quest_probe/): | |
| segment_map.npz — segments + per-frame table + comp3 anchors | |
| segment_map_summary.json — distributions for verification | |
| segment_spotcheck.txt — 10 random episodes vs gripper trace | |
| """ | |
| import glob | |
| import json | |
| import math | |
| import os | |
| 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") | |
| DEBOUNCE = 3 | |
| EVAL_SPLIT = 0.1 | |
| # (grasp_phrase, release_phrase) per sub-goal, in execution order. | |
| SUBGOALS = { | |
| 0: [("pick up the white mug", "put the white mug on the left plate"), | |
| ("pick up the yellow and white mug", "put the yellow and white mug on the right plate")], | |
| 1: [("pick up the white mug", "put the white mug on the plate"), | |
| ("pick up the chocolate pudding", "put the chocolate pudding to the right of the plate")], | |
| 2: [("pick up the yellow and white mug", "put the yellow and white mug in the microwave"), | |
| ("close the microwave", "close the microwave")], | |
| 3: [("turn on the stove", "turn on the stove"), | |
| ("pick up the moka pot", "put the moka pot on the stove")], | |
| 4: [("pick up the alphabet soup", "put the alphabet soup in the basket"), | |
| ("pick up the cream cheese box", "put the cream cheese box in the basket")], | |
| 5: [("pick up the alphabet soup", "put the alphabet soup in the basket"), | |
| ("pick up the tomato sauce", "put the tomato sauce in the basket")], | |
| 6: [("pick up the moka pot", "put the moka pot on the stove"), | |
| ("pick up the moka pot", "put the moka pot on the stove")], | |
| 7: [("pick up the cream cheese box", "put the cream cheese box in the basket"), | |
| ("pick up the butter", "put the butter in the basket")], | |
| 8: [("pick up the black bowl", "put the black bowl in the bottom drawer of the cabinet"), | |
| ("close the drawer", "close the drawer")], | |
| 9: [("pick up the book", "place the book in the back compartment of the caddy")], | |
| 10: [("pick up the bowl", "put the bowl on the plate")], | |
| 11: [("pick up the wine bottle", "put the wine bottle on the rack")], | |
| 12: [("open the top drawer", "open the top drawer"), | |
| ("pick up the bowl", "put the bowl inside the top drawer")], | |
| 13: [("pick up the cream cheese", "put the cream cheese in the bowl")], | |
| 14: [("pick up the wine bottle", "put the wine bottle on top of the cabinet")], | |
| 15: [("push the plate to the front of the stove", "push the plate to the front of the stove")], | |
| 16: [("turn on the stove", "turn on the stove")], | |
| 17: [("pick up the bowl", "put the bowl on the stove")], | |
| 18: [("pick up the bowl", "put the bowl on top of the cabinet")], | |
| 19: [("open the middle drawer of the cabinet", "open the middle drawer of the cabinet")], | |
| } | |
| _OBJ = ["orange juice", "ketchup", "cream cheese", "bbq sauce", "alphabet soup", | |
| "milk", "salad dressing", "butter", "tomato sauce", "chocolate pudding"] | |
| for i, x in enumerate(_OBJ): | |
| SUBGOALS[20 + i] = [(f"pick up the {x}", f"place the {x} in the basket")] | |
| _SPATIAL = ["next to the cookie box", "in the top drawer of the wooden cabinet", | |
| "on the ramekin", "on the stove", "between the plate and the ramekin", | |
| "on the cookie box", "next to the plate", "next to the ramekin", | |
| "from table center", "on the wooden cabinet"] | |
| for i, q in enumerate(_SPATIAL): | |
| SUBGOALS[30 + i] = [(f"pick up the black bowl {q}", "place the black bowl on the plate")] | |
| def seg_type(phrase: str) -> str: | |
| if phrase.startswith("pick up"): | |
| return "pick" | |
| if phrase.startswith(("put ", "place ")): | |
| return "place" | |
| if phrase.startswith("open"): | |
| return "open" | |
| if phrase.startswith("close"): | |
| return "close" | |
| if phrase.startswith("turn on"): | |
| return "turn_on" | |
| if phrase.startswith("push"): | |
| return "push" | |
| return "other" | |
| def hash_coin(ep: int, frame: int, salt: int) -> bool: | |
| h = ((ep * 2654435761) ^ (frame * 40503) ^ (salt * 974711)) & 0xFFFFFFFF | |
| return (h % 1000) < 500 | |
| def debounced_runs(state: np.ndarray) -> list[tuple[int, bool]]: | |
| """Return [(start_frame, is_closed)] runs of the debounced state.""" | |
| runs = [] | |
| cur = bool(state[0]) | |
| start = 0 | |
| i = 1 | |
| n = len(state) | |
| while i < n: | |
| if bool(state[i]) != cur: | |
| # candidate transition at i; confirm persistence | |
| j = i | |
| while j < n and bool(state[j]) != cur and j - i < DEBOUNCE: | |
| j += 1 | |
| if j - i >= DEBOUNCE or j == n: | |
| runs.append((start, cur)) | |
| start = i | |
| cur = bool(state[i]) | |
| i = j | |
| continue | |
| i = j # blip: skip the short opposite run | |
| continue | |
| i += 1 | |
| runs.append((start, cur)) | |
| return runs | |
| def main() -> None: | |
| os.makedirs(OUT_DIR, exist_ok=True) | |
| tasks = pd.read_parquet(SNAP + "/meta/tasks.parquet") | |
| # tasks.parquet: index = instruction string, column task_index = id | |
| task_text = {int(r["task_index"]): str(idx) for idx, r in tasks.iterrows()} | |
| 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) | |
| grip = act[:, 6] | |
| uniq = np.unique(np.round(grip, 3)) | |
| print("gripper unique values (rounded):", uniq[:10], "... total", len(uniq)) | |
| closed_is_positive = True # determined below from episode starts | |
| first_vals = [] | |
| for ep, grp in frames.groupby("episode_index"): | |
| first_vals.append(grp["action"].iloc[0][6]) | |
| first_vals = np.array(first_vals) | |
| open_val = 1.0 if np.mean(first_vals > 0) > 0.5 else -1.0 | |
| # episodes start OPEN; open_val is the value at frame 0 for most episodes | |
| closed_is_positive = open_val < 0 | |
| print(f"frame-0 gripper: mean={first_vals.mean():.3f}; open_val={open_val:+.0f} " | |
| f"-> closed is {'positive' if closed_is_positive else 'negative'}") | |
| is_closed_all = grip > 0 if closed_is_positive else grip < 0 | |
| ep_arr = frames["episode_index"].to_numpy() | |
| fr_arr = frames["frame_index"].to_numpy() | |
| tk_arr = frames["task_index"].to_numpy() | |
| # episode -> (row slice, task) | |
| ep_rows: dict[int, tuple[int, int, int]] = {} | |
| starts = np.flatnonzero(np.r_[True, ep_arr[1:] != ep_arr[:-1]]) | |
| ends = np.r_[starts[1:], len(ep_arr)] | |
| for s, e in zip(starts, ends): | |
| ep_rows[int(ep_arr[s])] = (int(s), int(e), int(tk_arr[s])) | |
| all_eps = sorted(ep_rows) | |
| print("episodes:", len(all_eps), "frames:", len(frames)) | |
| # replicate factory split: group by task (ascending ep order), hold out last ceil(0.1n) | |
| by_task: dict[int, list[int]] = {} | |
| for ep in all_eps: | |
| by_task.setdefault(ep_rows[ep][2], []).append(ep) | |
| train_eps, eval_eps = [], [] | |
| for t, eps in sorted(by_task.items()): | |
| n_eval = math.ceil(len(eps) * EVAL_SPLIT) | |
| train_eps.extend(eps[: len(eps) - n_eval]) | |
| eval_eps.extend(eps[len(eps) - n_eval:]) | |
| train_set = set(train_eps) | |
| print(f"split: {len(train_eps)} train / {len(eval_eps)} eval episodes") | |
| phrases: list[str] = [] | |
| phrase_id: dict[str, int] = {} | |
| def pid(p: str) -> int: | |
| if p not in phrase_id: | |
| phrase_id[p] = len(phrases) | |
| phrases.append(p) | |
| return phrase_id[p] | |
| seg_ep, seg_start, seg_end, seg_pid, seg_typ = [], [], [], [], [] | |
| frame_key, frame_pid, frame_seg_end = [], [], [] | |
| anch_ep, anch_fr, anch_tk, anch_end, anch_pid = [], [], [], [], [] | |
| segs_per_ep = {} | |
| first_trans_closed = 0 | |
| eps_with_trans = 0 | |
| for ep in train_eps: | |
| s, e, tk = ep_rows[ep] | |
| state = is_closed_all[s:e] | |
| n = e - s | |
| runs = debounced_runs(state) | |
| # segments: seg j = [run_j.start, run_{j+1}.start] inclusive; last run merges into previous | |
| bounds = [] # (start, end_inclusive, end_state_closed or None) | |
| if len(runs) == 1: | |
| bounds.append((0, n - 1, None)) | |
| else: | |
| for j in range(len(runs) - 1): | |
| st = runs[j][0] | |
| en = runs[j + 1][0] # switching frame belongs to this segment | |
| if j == len(runs) - 2: | |
| en = n - 1 # merge tail run into last segment | |
| bounds.append((st, en, runs[j + 1][1])) | |
| eps_with_trans += 1 | |
| if runs[1][1]: | |
| first_trans_closed += 1 | |
| subgoals = SUBGOALS[tk] | |
| g = 0 | |
| ep_seg_ids = [] | |
| for (st, en, end_closed) in bounds: | |
| if end_closed is None: | |
| ph = subgoals[min(g, len(subgoals) - 1)][0] | |
| elif end_closed: | |
| ph = subgoals[min(g, len(subgoals) - 1)][0] | |
| else: | |
| ph = subgoals[min(g, len(subgoals) - 1)][1] | |
| g += 1 | |
| sid = len(seg_ep) | |
| ep_seg_ids.append(sid) | |
| seg_ep.append(ep) | |
| seg_start.append(st) | |
| seg_end.append(en) | |
| seg_pid.append(pid(ph)) | |
| seg_typ.append(seg_type(ph)) | |
| for f in range(st, en + 1): | |
| frame_key.append(ep * 100000 + f) | |
| frame_pid.append(seg_pid[-1]) | |
| frame_seg_end.append(en) | |
| if hash_coin(ep, f, salt=7): # comp3 anchor subsample 1/2 | |
| anch_ep.append(ep) | |
| anch_fr.append(f) | |
| anch_tk.append(tk) | |
| anch_end.append(en) | |
| anch_pid.append(seg_pid[-1]) | |
| segs_per_ep[ep] = len(bounds) | |
| seg_len = np.array(seg_end) - np.array(seg_start) + 1 | |
| from collections import Counter | |
| type_counts = Counter(seg_typ) | |
| spe = Counter(segs_per_ep.values()) | |
| summary = { | |
| "train_episodes": len(train_eps), | |
| "eval_episodes": len(eval_eps), | |
| "total_segments": len(seg_ep), | |
| "segments_per_episode_hist": {str(k): v for k, v in sorted(spe.items())}, | |
| "segment_length_frames": { | |
| "min": int(seg_len.min()), "p25": float(np.percentile(seg_len, 25)), | |
| "median": float(np.percentile(seg_len, 50)), | |
| "p75": float(np.percentile(seg_len, 75)), "max": int(seg_len.max()), | |
| "mean": float(seg_len.mean()), | |
| }, | |
| "segments_by_type": dict(type_counts), | |
| "comp3_anchors_after_half_subsample": len(anch_ep), | |
| "episodes_with_gripper_transition": eps_with_trans, | |
| "first_transition_into_closed": first_trans_closed, | |
| "unique_phrases": len(phrases), | |
| } | |
| print(json.dumps(summary, indent=1)) | |
| np.savez_compressed( | |
| os.path.join(OUT_DIR, "segment_map.npz"), | |
| seg_ep=np.array(seg_ep), seg_start=np.array(seg_start), seg_end=np.array(seg_end), | |
| seg_pid=np.array(seg_pid), phrases=np.array(phrases), | |
| frame_key=np.array(frame_key), frame_pid=np.array(frame_pid), | |
| frame_seg_end=np.array(frame_seg_end), | |
| anch_ep=np.array(anch_ep), anch_fr=np.array(anch_fr), anch_tk=np.array(anch_tk), | |
| anch_end=np.array(anch_end), anch_pid=np.array(anch_pid), | |
| train_eps=np.array(sorted(train_set)), | |
| ) | |
| with open(os.path.join(OUT_DIR, "segment_map_summary.json"), "w") as f: | |
| json.dump(summary, f, indent=1) | |
| # spot-check: 10 random train episodes vs raw gripper trace (run-length) | |
| rng = np.random.default_rng(7) | |
| picks = rng.choice(train_eps, size=10, replace=False) | |
| lines = [] | |
| seg_by_ep: dict[int, list[int]] = {} | |
| for sid, ep in enumerate(seg_ep): | |
| seg_by_ep.setdefault(ep, []).append(sid) | |
| for ep in sorted(int(p) for p in picks): | |
| s, e, tk = ep_rows[ep] | |
| raw = is_closed_all[s:e] | |
| rle = [] | |
| cur, cnt = bool(raw[0]), 1 | |
| for v in raw[1:]: | |
| if bool(v) == cur: | |
| cnt += 1 | |
| else: | |
| rle.append(("C" if cur else "O") + str(cnt)) | |
| cur, cnt = bool(v), 1 | |
| rle.append(("C" if cur else "O") + str(cnt)) | |
| lines.append(f"EP {ep} task {tk}: {task_text[tk]}") | |
| lines.append(" gripper RLE (O=open,C=closed): " + " ".join(rle)) | |
| for sid in seg_by_ep[ep]: | |
| lines.append( | |
| f" seg [{seg_start[sid]:4d}..{seg_end[sid]:4d}] {seg_typ[sid]:8s} " | |
| f"\"{phrases[seg_pid[sid]]}\"" | |
| ) | |
| with open(os.path.join(OUT_DIR, "segment_spotcheck.txt"), "w") as f: | |
| f.write("\n".join(lines) + "\n") | |
| print("spotcheck written;", len(picks), "episodes") | |
| print("parse table check — task 30:", SUBGOALS[30], "| task 12:", SUBGOALS[12]) | |
| if __name__ == "__main__": | |
| main() | |