trace-vla-code / code /trace_validation /scripts /build_plus25_cache.py
phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report (part 2)
ae1ed83 verified
Raw History Blame Contribute Delete
5.53 kB
#!/usr/bin/env python3
"""Extend the TRACE subset feature cache with ONE held-out task demo.
Built for Young's 19:32 21/11/2026 request: run TRACE C02 on a truly
held-out task. Object #7 (dataset index 25, "pick up the milk and
place it in the basket") is NOT in the 12-task subset C02 trained on.
This script loads feature_cache_subset.pt UNCHANGED (same stats, same
episodes - C02's training/eval conditions stay bit-identical), encodes
the FIRST episode of ds25 in dataset order with the identical contract
as build_subset_cache.py (frozen TIPSv2 google/tipsv2-b14, rot180 on
dataset frames, both cameras, 2x2 pooling to 64 patches, fp16), marks
it split="demo" (demo-only, never trained on), and saves the result
as a NEW file feature_cache_subset_plus25.pt. The original cache is
not modified.
"""
import json
from pathlib import Path
import numpy as np
import torch
import sys
sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))
from trace_vla.anchor import TipsAnchor # noqa: E402
EXP = Path.home() / "sera_v4_experiments"
TARGET_DS = 25
def task_texts(meta):
import pandas as pd
cand = [Path(meta.root) / "meta" / "tasks.parquet"] if \
getattr(meta, "root", None) else []
cand += list(Path.home().glob(
".cache/huggingface/lerobot/lerobot/libero/meta/tasks.parquet"))
for path in cand:
if path.exists():
df = pd.read_parquet(path)
cols = {c.lower(): c for c in df.columns}
ti = cols.get("task_index", df.columns[0])
tx = cols.get("task", df.columns[-1])
return {int(r[ti]): str(r[tx]) for _, r in df.iterrows()}
raise RuntimeError("cannot resolve task texts")
def main():
from lerobot.datasets.lerobot_dataset import LeRobotDataset, \
LeRobotDatasetMetadata
meta = LeRobotDatasetMetadata("lerobot/libero", revision="v3.0")
ep_len = np.array(meta.episodes["length"])
full = LeRobotDataset("lerobot/libero", revision="v3.0",
video_backend="pyav")
task_col = np.array(full.hf_dataset["task_index"])
ep_col = np.array(full.hf_dataset["episode_index"])
starts = np.zeros(len(ep_len) + 1, dtype=np.int64)
np.cumsum(ep_len, out=starts[1:])
ep_task = np.array([task_col[starts[e]] for e in range(len(ep_len))])
eps = sorted(e for e in range(len(ep_len)) if ep_task[e] == TARGET_DS)
demo_ep = eps[0]
length = int(ep_len[demo_ep])
print(f"ds{TARGET_DS}: {len(eps)} episodes, first = ep {demo_ep} "
f"({length} frames)")
texts = task_texts(meta)
print(f"official task text: {texts[TARGET_DS]!r}")
device = "cuda"
anchor = TipsAnchor("google/tipsv2-b14").to(device)
ds = LeRobotDataset("lerobot/libero", revision="v3.0",
episodes=[demo_ep], video_backend="pyav")
per_frame = {}
buf_imgs, buf_refs = [], []
def flush():
if not buf_imgs:
return
imgs = torch.stack(buf_imgs).to(device)
n = imgs.shape[0]
flat = imgs.flatten(0, 1).float()
with torch.autocast("cuda", dtype=torch.bfloat16):
pooled = anchor.encode_patches(flat)
pooled = pooled.float().reshape(n, 2, 64, 768).half().cpu()
for i, f in enumerate(buf_refs):
per_frame[f] = pooled[i]
buf_imgs.clear()
buf_refs.clear()
for i in range(len(ds)):
item = ds[i]
f = int(item["frame_index"])
img = torch.flip(item["observation.images.image"], dims=(-2, -1))
img2 = torch.flip(item["observation.images.image2"], dims=(-2, -1))
buf_imgs.append(torch.stack([img, img2]))
buf_refs.append(f)
if len(buf_imgs) >= 32:
flush()
flush()
assert len(per_frame) == length, f"{len(per_frame)} != {length}"
new_feats = torch.stack([per_frame[f] for f in range(length)])
print(f"encoded features {tuple(new_feats.shape)} {new_feats.dtype}")
g0 = int(starts[demo_ep])
full_states = np.stack(full.hf_dataset["observation.state"])
full_actions = np.stack(full.hf_dataset["action"])
new_states = torch.tensor(full_states[g0:g0 + length],
dtype=torch.float32)
new_actions = torch.tensor(full_actions[g0:g0 + length],
dtype=torch.float32)
cache = torch.load(EXP / "trace_vla" / "feature_cache_subset.pt",
weights_only=False)
old_total = int(cache["features"].shape[0])
cache["features"] = torch.cat([cache["features"], new_feats], dim=0)
cache["states"] = torch.cat([cache["states"], new_states], dim=0)
cache["actions"] = torch.cat([cache["actions"], new_actions], dim=0)
cache["episodes"].append({"start": old_total, "length": length,
"episode_id": int(demo_ep),
"task_index": TARGET_DS, "split": "demo"})
cache["text_emb"][TARGET_DS] = anchor.encode_text(
[texts[TARGET_DS]])[0].cpu().float()
cache["meta"]["plus25_extension"] = (
f"appended demo-only episode {demo_ep} of ds{TARGET_DS} "
f"({texts[TARGET_DS]!r}) for held-out eval; stats and all "
"subset episodes unchanged")
out = EXP / "trace_vla" / "feature_cache_subset_plus25.pt"
torch.save(cache, out)
print(f"saved {out} ({out.stat().st_size / 1e9:.2f} GB), "
f"features {tuple(cache['features'].shape)}, "
f"episodes {len(cache['episodes'])}")
if __name__ == "__main__":
main()