trace-vla-code / code /sera_v4 /tools /build_demo_store.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
7.31 kB
#!/usr/bin/env python3
"""FEW-SHOT PHASE 1: build the demo store (WORKLOG spec).
For every episode of the 30 tasks of Spatial/Object/Goal:
- frames uniformly subsampled to <= v4_demo_frames (64);
- both cameras encoded by the model's OWN frozen TIPSv2 vision
encoder (tips.encode_image) on images passed through the
checkpoint's own preprocessor — the identical path training
observations take;
- per frame per camera, 6 tokens kept: token 0 (CLS), token 1
(register), and the 1024 patch tokens mean-pooled over a
2x2 grid of 16x16 blocks -> 4 tokens. Stored fp16 [F,2,6,768];
- per subsampled frame: raw action (7) + raw state (8).
Also stores ep_task for all 1693 episodes, per-task TRAIN pools
for the 21 train tasks (mirroring make_train_eval_datasets: per
task, the last ceil(eval_split) episodes of the ascending list
are the trainer's eval split and are excluded), and the split
itself. LIBERO-10 episodes are indexed in ep_task but carry no
tokens (E1 does not use them).
Output: ~/sera_v4_experiments/fewshot/demo_store.pt
"""
import math
import time
from pathlib import Path
import numpy as np
import torch
import lerobot.policies.sera_vla_v3.processor_sera_vla_v3 # noqa: F401
from lerobot.datasets.lerobot_dataset import LeRobotDataset, LeRobotDatasetMetadata
from lerobot.policies.factory import make_pre_post_processors
from lerobot.policies.sera_vla_v3.configuration_sera_vla_v3 import (
SERAVLAV3Config,
)
from lerobot.policies.sera_vla_v3.modeling_sera_vla_v3 import SERAVLAV3Policy
INIT = Path.home() / "sera_v4_experiments" / "init_quest" / "pretrained_model"
OUT = Path.home() / "sera_v4_experiments/fewshot"
OUT.mkdir(parents=True, exist_ok=True)
MAXF = 64
EVAL_SPLIT = 0.1
HELDOUT = {38, 32, 36, 19, 18, 11, 22, 28, 25} # dataset task_index
SUITE_TASKS = set(range(10, 40))
TRAIN_TASKS = sorted(SUITE_TASKS - HELDOUT)
meta = LeRobotDatasetMetadata("lerobot/libero", revision="v3.0")
TASK_STR = {int(ti): str(s) for s, ti in zip(meta.tasks.index,
meta.tasks["task_index"])}
hf_meta = meta.episodes
ep_len_all = np.array(hf_meta["length"])
n_ep = len(ep_len_all)
print(f"episodes: {n_ep}", flush=True)
ds = LeRobotDataset("lerobot/libero", revision="v3.0", video_backend="pyav")
hf = ds.hf_dataset
ep_col = np.array(hf["episode_index"])
frame_col = np.array(hf["frame_index"])
task_col = np.array(hf["task_index"])
# Episode -> task from the per-frame task_index column (the v3
# episodes metadata carries no task column).
ep_task_all = np.zeros(n_ep, dtype=np.int64)
_starts = np.zeros(n_ep + 1, dtype=np.int64)
np.cumsum(ep_len_all, out=_starts[1:])
for _e in range(n_ep):
_seg = task_col[_starts[_e]:_starts[_e + 1]]
assert (_seg == _seg[0]).all(), f"episode {_e} spans tasks"
ep_task_all[_e] = _seg[0]
act_col = hf["action"]
state_col = hf["observation.state"]
ep_start = np.zeros(n_ep + 1, dtype=np.int64)
np.cumsum(ep_len_all, out=ep_start[1:])
assert (ep_col[ep_start[:-1]] == np.arange(n_ep)).all()
assert (frame_col[ep_start[:-1]] == 0).all()
cfg = SERAVLAV3Config.from_pretrained(str(INIT))
pol = SERAVLAV3Policy(cfg)
from safetensors.torch import load_file
sd = load_file(str(INIT / "model.safetensors"))
missing, unexpected = pol.load_state_dict(sd, strict=False)
bad = [k for k in missing
if not k.startswith(("model.cc_", "model.ar_", "model.demo_"))]
assert not bad and not unexpected, (bad[:5], unexpected[:5])
pre, _ = make_pre_post_processors(cfg, pretrained_path=str(INIT))
pol._preprocessor = pre
pol.cuda().eval()
tips = pol.model.tips
def encode_frames(ep: int, frames: np.ndarray) -> torch.Tensor:
"""-> [F, 2, 6, 768] fp16 pooled frozen-encoder tokens."""
rows = (ep_start[ep] + frames).tolist()
items = ds.__getitems__(rows)
if isinstance(items, dict):
imgs = {0: items["observation.images.image"],
1: items["observation.images.image2"]}
else: # list of per-frame item dicts
imgs = {0: torch.stack([it["observation.images.image"]
for it in items]),
1: torch.stack([it["observation.images.image2"]
for it in items])}
states = torch.tensor(np.array([state_col[r] for r in rows])).float()
batch = {
"observation.images.image": imgs[0],
"observation.images.image2": imgs[1],
"observation.state": states,
"action": torch.zeros(len(rows), 7),
"task": [TASK_STR[int(ep_task_all[ep])]] * len(rows),
}
processed = pre({k: (v.cuda() if isinstance(v, torch.Tensor) else v)
for k, v in batch.items()})
out = torch.empty(len(rows), 2, 6, 768, dtype=torch.float16)
for cam, key in ((0, "observation.images.image"),
(1, "observation.images.image2")):
x = processed[key] # [F, 3, 448, 448]
toks = []
with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):
for i in range(0, x.shape[0], 128):
enc = tips.encode_image(x[i:i + 128])
n = x[i:i + 128].shape[0]
cls = enc.cls_token.float().reshape(n, -1, 768)
reg = enc.register_tokens.float().reshape(n, -1, 768)
patches = enc.patch_tokens.float().reshape(n, 32, 32, 768)
assert cls.shape[1] + reg.shape[1] == 2, \
(cls.shape, reg.shape)
pooled = patches.reshape(n, 2, 16, 2, 16, 768).mean(dim=(2, 4))
pooled = pooled.reshape(n, 4, 768)
toks.append(torch.cat([cls, reg, pooled], dim=1).cpu())
out[:, cam] = torch.cat(toks).half()
return out
vis, act, sta, nframes = [None] * n_ep, [None] * n_ep, [None] * n_ep, [0] * n_ep
target_eps = [e for e in range(n_ep) if int(ep_task_all[e]) in SUITE_TASKS]
t0 = time.time()
for k, ep in enumerate(target_eps):
L = int(ep_len_all[ep])
F = min(MAXF, L)
frames = np.unique(np.linspace(0, L - 1, F).round().astype(np.int64))
vis[ep] = encode_frames(ep, frames)
rows = (ep_start[ep] + frames).tolist()
act[ep] = torch.tensor(np.array([act_col[r] for r in rows])).float()
sta[ep] = torch.tensor(np.array([state_col[r] for r in rows])).float()
nframes[ep] = len(frames)
if (k + 1) % 100 == 0 or k == 0:
el = time.time() - t0
print(f"[{k + 1}/{len(target_eps)}] ep {ep} F={len(frames)} "
f"elapsed {el:.0f}s eta {el / (k + 1) * len(target_eps):.0f}s",
flush=True)
train_pools = {}
for t in TRAIN_TASKS:
eps = sorted(e for e in range(n_ep) if int(ep_task_all[e]) == t)
n_eval = math.ceil(EVAL_SPLIT * len(eps))
train_pools[t] = torch.tensor(eps[: len(eps) - n_eval], dtype=torch.long)
assert len(train_pools[t]) >= 2
store = {
"vis": vis, "act": act, "state": sta, "frames": nframes,
"ep_task": torch.tensor(ep_task_all, dtype=torch.long),
"ep_len": torch.tensor(ep_len_all, dtype=torch.long),
"train_pools": train_pools,
"train_tasks": TRAIN_TASKS,
"heldout_tasks": sorted(HELDOUT),
"max_frames": MAXF,
}
torch.save(store, OUT / "demo_store.pt")
size_gb = (OUT / "demo_store.pt").stat().st_size / 1e9
print(f"store saved: {size_gb:.2f} GB, {len(target_eps)} episodes encoded, "
f"{time.time() - t0:.0f}s total")