File size: 7,525 Bytes
ae1ed83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | #!/usr/bin/env python3
"""Build the subset feature cache for TRACE-VLA validation Phase C.
Same encoding contract as build_feature_cache.py (frozen TIPSv2,
rot180 orientation correction on dataset frames, 224 px, 2x2 pooling
to 64 patches, both cameras, fp16), but for the 12-task validation
subset of trace_validation/PLAN.md section 3:
- 9 train tasks (dataset indices 31, 32, 38, 24, 22, 28, 19, 12, 18):
first 12 episodes per task in dataset order; episodes 0-9 form the
train split, episodes 10-11 the validation split.
- 3 Long tasks (dataset indices 4, 5, 0): first 3 episodes each,
demo-only (never trained on).
State/action statistics are computed over the train split episodes
only. Output: feature_cache_subset.pt next to feature_cache.pt, with
per-episode "split" fields and the split episode lists in meta.
"""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from trace_vla.anchor import TipsAnchor # noqa: E402
EXP = Path.home() / "sera_v4_experiments"
TRAIN_DS = [31, 32, 38, 24, 22, 28, 19, 12, 18]
DEMO_DS = [4, 5, 0]
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():
ap = argparse.ArgumentParser()
ap.add_argument("--train-episodes", type=int, default=10)
ap.add_argument("--val-episodes", type=int, default=2)
ap.add_argument("--demo-episodes", type=int, default=3)
ap.add_argument("--out", default=str(EXP / "trace_vla"
/ "feature_cache_subset.pt"))
ap.add_argument("--encode-batch", type=int, default=32)
args = ap.parse_args()
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))])
split_of = {}
for t in TRAIN_DS:
eps = sorted(e for e in range(len(ep_len)) if ep_task[e] == t)
n_tr = args.train_episodes
for e in eps[:n_tr]:
split_of[e] = "train"
for e in eps[n_tr:n_tr + args.val_episodes]:
split_of[e] = "val"
for t in DEMO_DS:
eps = sorted(e for e in range(len(ep_len)) if ep_task[e] == t)
for e in eps[:args.demo_episodes]:
split_of[e] = "demo"
selected = sorted(split_of)
print(f"selected {len(selected)} episodes "
f"({sum(1 for v in split_of.values() if v == 'train')} train, "
f"{sum(1 for v in split_of.values() if v == 'val')} val, "
f"{sum(1 for v in split_of.values() if v == 'demo')} demo)")
train_eps = [e for e, s in split_of.items() if s == "train"]
rows = np.isin(ep_col, train_eps)
states = np.stack(full.hf_dataset["observation.state"])[rows].astype(np.float64)
actions = np.stack(full.hf_dataset["action"])[rows].astype(np.float64)
stats = {
"state_mean": torch.tensor(states.mean(0), dtype=torch.float32),
"state_std": torch.tensor(states.std(0), dtype=torch.float32),
"action_mean": torch.tensor(actions.mean(0), dtype=torch.float32),
"action_std": torch.tensor(actions.std(0), dtype=torch.float32),
}
print(f"stats over {rows.sum()} train frames")
texts = task_texts(meta)
device = "cuda" if torch.cuda.is_available() else "cpu"
anchor = TipsAnchor("google/tipsv2-b14").to(device)
text_emb = {t: anchor.encode_text([texts[t]])[0].cpu().float()
for t in TRAIN_DS + DEMO_DS}
ds = LeRobotDataset("lerobot/libero", revision="v3.0",
episodes=selected, video_backend="pyav")
per_ep = {e: {} for e in selected}
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,
enabled=(device == "cuda")):
pooled = anchor.encode_patches(flat)
pooled = pooled.float().reshape(n, 2, 64, 768).half().cpu()
for i, (e, f) in enumerate(buf_refs):
per_ep[e][f] = pooled[i]
buf_imgs.clear()
buf_refs.clear()
for i in range(len(ds)):
item = ds[i]
e = int(item["episode_index"])
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((e, f))
if len(buf_imgs) >= args.encode_batch:
flush()
if i % 3000 == 0:
print(f" frame {i}/{len(ds)}", flush=True)
flush()
feats, sts, acts, episodes = [], [], [], []
offset = 0
full_states = np.stack(full.hf_dataset["observation.state"])
full_actions = np.stack(full.hf_dataset["action"])
for e in selected:
frames = per_ep[e]
length = int(ep_len[e])
assert len(frames) == length, f"ep {e}: {len(frames)} != {length}"
for f in range(length):
feats.append(frames[f])
g0 = int(starts[e])
sts.append(torch.tensor(full_states[g0:g0 + length], dtype=torch.float32))
acts.append(torch.tensor(full_actions[g0:g0 + length], dtype=torch.float32))
episodes.append({"start": offset, "length": length,
"episode_id": int(e), "task_index": int(ep_task[e]),
"split": split_of[e]})
offset += length
cache = {
"features": torch.stack(feats),
"states": torch.cat(sts),
"actions": torch.cat(acts),
"episodes": episodes,
"text_emb": text_emb,
"stats": stats,
"meta": {
"dataset": "lerobot/libero", "revision": "v3.0",
"orientation": "rot180 applied to dataset frames",
"image_size": 224,
"train_tasks_ds": TRAIN_DS, "demo_tasks_ds": DEMO_DS,
"train_episode_ids": sorted(train_eps),
"val_episode_ids": sorted(e for e, s in split_of.items()
if s == "val"),
"demo_episode_ids": sorted(e for e, s in split_of.items()
if s == "demo"),
},
}
out = Path(args.out)
torch.save(cache, out)
print(f"saved {out} ({out.stat().st_size / 1e9:.2f} GB), "
f"features {tuple(cache['features'].shape)}")
if __name__ == "__main__":
main()
|