trace-vla-code / code /sera_v4 /tools /build_cache.py
phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report
b4396f0 verified
Raw History Blame Contribute Delete
4.16 kB
#!/usr/bin/env python3
"""Build the shared routing-measurement cache for SERA-v4 Stage 1.
Replicates the P1 diagnostics manifest (sera_skill_diagnostics): for each of
the 40 dataset tasks, the first 4 episodes; windows at 10% / 45% / 80% of the
episode length (phase labels = time-window heuristic: approach / manipulation
/ placement); 8 consecutive frames per window. 40*4*3 = 480 windows, 3,840 obs.
For each window we store the FIRST frame's raw observations (the routing
decision is per-sample in this trunk, so one frame per window suffices for
routing statistics; P1 captured all 8 frames of each window — we keep all 8
to stay exactly comparable).
Output: cache.pt with raw image tensors (as returned by LeRobotDataset),
states, task strings, and manifest metadata. Preprocessing (resize 448 +
normalize) is applied later, per checkpoint, with that checkpoint's own
processor pipeline — identical to the P1 method.
"""
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from huggingface_hub import snapshot_download
from lerobot.datasets.lerobot_dataset import LeRobotDataset
OUT = Path.home() / "sera_v4_experiments" / "measurement"
WINDOWS = [(0.10, "approach"), (0.45, "manipulation"), (0.80, "placement")]
def main():
OUT.mkdir(parents=True, exist_ok=True)
snap = Path(snapshot_download("lerobot/libero", repo_type="dataset", revision="v3.0"))
tasks_df = pd.read_parquet(snap / "meta" / "tasks.parquet")
task_names = [name for name, _ in sorted(zip(tasks_df.index, tasks_df["task_index"]),
key=lambda kv: kv[1])]
assert len(task_names) == 40
# Episode -> task/length from the frame-level data parquets (the episodes
# parquet in this format carries no task column).
data_files = sorted((snap / "data").rglob("*.parquet"))
frames = pd.concat(
[pd.read_parquet(f, columns=["episode_index", "frame_index", "task_index"])
for f in data_files],
ignore_index=True,
)
eps = (frames.groupby("episode_index")
.agg(task_index=("task_index", "first"), length=("frame_index", "max"))
.reset_index())
eps["length"] = eps["length"] + 1
eps = eps.sort_values("episode_index").reset_index(drop=True)
print("episodes table:", eps.shape)
manifest = []
for task_idx in range(40):
task_eps = eps[eps["task_index"] == task_idx].head(4)
assert len(task_eps) == 4, f"task {task_idx} has {len(task_eps)} episodes"
for _, row in task_eps.iterrows():
ep = int(row["episode_index"])
length = int(row["length"])
for frac, phase in WINDOWS:
start = min(int(frac * length), max(0, length - 8))
manifest.append({
"episode_index": ep, "frame_index": start, "phase": phase,
"task_index": task_idx, "task": task_names[task_idx],
})
print("manifest windows:", len(manifest))
images1, images2, states, tasks = [], [], [], []
by_episode: dict[int, LeRobotDataset] = {}
for i, m in enumerate(manifest):
ep = m["episode_index"]
if ep not in by_episode:
by_episode[ep] = LeRobotDataset("lerobot/libero", revision="v3.0", episodes=[ep],
video_backend="pyav")
ds = by_episode[ep]
start = m["frame_index"]
for j in range(start, start + 8):
item = ds[j]
images1.append(item["observation.images.image"])
images2.append(item["observation.images.image2"])
states.append(item["observation.state"])
tasks.append(m["task"])
if i % 100 == 0:
print("window", i, "/", len(manifest), flush=True)
cache = {
"manifest": manifest,
"image": torch.stack(images1),
"image2": torch.stack(images2),
"state": torch.stack(states),
"task": tasks,
}
torch.save(cache, OUT / "cache.pt")
print("cache saved:", {k: (v.shape if torch.is_tensor(v) else len(v)) for k, v in cache.items()})
if __name__ == "__main__":
main()