trace-vla-code / code /sera_v4 /tools /build_jedi_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
5.25 kB
#!/usr/bin/env python3
"""JEDI-LITE offline store (spec: research report section 7.2 +
WORKLOG "JEDI-LITE" pre-registration).
Built from the existing demo_store.pt (no new encoder passes):
for every suite episode (30 tasks of Spatial/Object/Goal):
- pool_feat[e]: [F, 768] fp16 — the frozen TIPSv2 tokens of the
demo store mean-pooled over (camera, token) per store frame.
This is the prediction TARGET space of the JEPA-lite loss and
the current-frame feature the predictor conditions on.
- keyframes[e]: store-frame indices of stage boundaries,
defined ONLY from signals recorded in the demos themselves
(no simulator privilege): gripper-action changepoints
(|delta gripper| > 0.5 between consecutive store frames) and
end-effector speed local minima (state[0:3] positions; a real
pause: local minimum below half the episode median speed);
the final frame F-1 is always a keyframe. Keyframes closer
than 2 store frames are merged (the later one wins, except
F-1 which is always kept).
- next_kf[e]: [F] long — for each store frame s, the first
keyframe strictly after s, else F-1 (the "next-stage
keyframe" the predictor must predict).
- signature[e]: tuple of keyframe positions normalized by
F-1 and rounded to 0.1 — two episodes of the same task with
different signatures are different "processes" for the
counterfactual process negative.
- proc_pool[e]: for a sample episode e of a train task, the
TRAIN-pool episodes of the same task whose signature differs
from e's; fallback (flagged in proc_fallback[e]) = the whole
train pool minus e when no different-signature episode
exists.
Output: ~/sera_v4_experiments/fewshot/jedi_store.pt
CPU only; safe to run while the GPU is busy.
"""
import time
from pathlib import Path
import numpy as np
import torch
FS = Path.home() / "sera_v4_experiments" / "fewshot"
t0 = time.time()
store = torch.load(FS / "demo_store.pt", map_location="cpu",
weights_only=False)
vis, act, sta = store["vis"], store["act"], store["state"]
ep_task, ep_len = store["ep_task"], store["ep_len"]
train_pools, train_tasks = store["train_pools"], store["train_tasks"]
n_ep = len(ep_task)
pool_feat = [None] * n_ep
keyframes = [None] * n_ep
next_kf = [None] * n_ep
signature = [None] * n_ep
n_kf = []
for e in range(n_ep):
if vis[e] is None:
continue
F = int(store["frames"][e])
v = vis[e].float() # [F, 2, 6, 768]
pool_feat[e] = v.mean(dim=(1, 2)).half() # [F, 768]
a = act[e].float() # [F, 7]
s = sta[e].float() # [F, 8]
kf = set()
# Gripper changepoints (action gripper = last channel).
grip = a[:, -1]
for t in range(1, F):
if abs(float(grip[t]) - float(grip[t - 1])) > 0.5:
kf.add(t)
# EE speed local minima (a pause ends a stage).
pos = s[:, 0:3]
if F >= 4:
speed = (pos[1:] - pos[:-1]).norm(dim=-1) # [F-1]
med = float(speed.median())
for t in range(1, F - 2):
if (float(speed[t]) < float(speed[t - 1])
and float(speed[t]) <= float(speed[t + 1])
and float(speed[t]) < 0.5 * med):
kf.add(t + 1)
kf.add(F - 1)
# Merge keyframes closer than 2 store frames (later wins).
merged = []
for k in sorted(kf):
if merged and k - merged[-1] < 2 and k != F - 1:
merged[-1] = k
else:
merged.append(k)
if merged[-1] != F - 1:
merged.append(F - 1)
keyframes[e] = torch.tensor(merged, dtype=torch.long)
n_kf.append(len(merged))
nk = torch.empty(F, dtype=torch.long)
for si in range(F):
later = [k for k in merged if k > si]
nk[si] = later[0] if later else F - 1
next_kf[e] = nk
signature[e] = tuple(round(k / max(F - 1, 1), 1) for k in merged)
proc_pool = {}
proc_fallback = {}
for t in train_tasks:
pool = [int(x) for x in train_pools[t].tolist()]
for e in pool + [e for e in range(n_ep)
if int(ep_task[e]) == t and e not in pool]:
diff = [x for x in pool
if x != e and signature[x] != signature[e]]
if diff:
proc_pool[e] = torch.tensor(diff, dtype=torch.long)
proc_fallback[e] = False
else:
rest = [x for x in pool if x != e]
proc_pool[e] = torch.tensor(rest, dtype=torch.long)
proc_fallback[e] = True
out = {
"pool_feat": pool_feat,
"keyframes": keyframes,
"next_kf": next_kf,
"signature": signature,
"proc_pool": proc_pool,
"proc_fallback": proc_fallback,
"ep_task": ep_task,
"ep_len": ep_len,
"frames": store["frames"],
"train_pools": train_pools,
"train_tasks": train_tasks,
}
torch.save(out, FS / "jedi_store.pt")
n_suites = sum(1 for e in range(n_ep) if pool_feat[e] is not None)
n_fb = sum(1 for v in proc_fallback.values() if v)
print(f"jedi store saved: {n_suites} episodes, keyframes/ep "
f"mean {np.mean(n_kf):.1f} min {min(n_kf)} max {max(n_kf)}, "
f"proc-pool fallback episodes {n_fb}/{len(proc_fallback)}, "
f"{(FS / 'jedi_store.pt').stat().st_size / 1e6:.0f} MB, "
f"{time.time() - t0:.0f}s")