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
14.7 kB
#!/usr/bin/env python3
"""Closed-loop evaluation harness for TRACE-VLA checkpoints.
Independent implementation against the standard LIBERO API, built
for the TRACE-VLA validation protocol (Phase C evals, the section
18.5 demo-dependency test, and the A02 open-loop reproduction check).
Conditions and conventions mirror the program's earlier harness:
- benchmark tasks addressed by (suite, benchmark index); the dataset
index is resolved through env_dataset_task_mapping.json;
- init states: the task's official init states, index = episode no.;
- seed 0; step caps: spatial 280, object 280, goal 300, libero_10
600 (the caps observed in the program's earlier evals);
- env frames are fed to the anchor AS RENDERED: the training
features were built from dataset frames after the rot180
correction, which puts them in env orientation (see PLAN A01);
- the policy replans every 4 env steps (spec section 12) and
executes the first 4 actions of each sampled chunk;
- demo: first train-split episode of the task from
feature_cache_subset.pt (main camera), or first demo-split
episode for the Long tasks;
- conditions: correct | nodemo | swapped | shuffled (section 18.5).
For "swapped", success is scored against BOTH the original goal
and the swapped demo's goal (two envs stepped in lockstep with
the same actions is not possible - instead the same rollout is
scored by check_success on the original env, and the swapped
task's success predicate is evaluated on a shadow env that
receives the same action sequence).
--reproduce: run one closed-loop episode; if it succeeds, reset to
the same init state and replay the recorded actions open-loop;
report whether success reproduces (A02 replacement, option 2).
"""
import argparse
import json
import sys
import time
from pathlib import Path
import numpy as np
import torch
sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))
from trace_vla.config import TraceConfig # noqa: E402
from trace_vla.data import subsample_indices # noqa: E402
from trace_vla.model import TraceVLA # noqa: E402
EXP = Path.home() / "sera_v4_experiments"
DEVICE = "cuda"
CAPS = {"libero_spatial": 280, "libero_object": 280,
"libero_goal": 300, "libero_10": 600}
ARM_CFG = {
"base": TraceConfig(use_echo_loss=False),
"rawmem": TraceConfig(delta_use_residuals=False, use_echo_loss=False),
"delta": TraceConfig(use_echo_loss=False),
"full": TraceConfig(),
}
def build_state(obs):
from scipy.spatial.transform import Rotation
pos = np.asarray(obs["robot0_eef_pos"], dtype=np.float64)
quat = np.asarray(obs["robot0_eef_quat"], dtype=np.float64)
rotvec = Rotation.from_quat(quat).as_rotvec()
grip = np.asarray(obs["robot0_gripper_qpos"], dtype=np.float64)
return np.concatenate([pos, rotvec, grip]).astype(np.float32)
class TracePolicy:
def __init__(self, ckpt_path, arm, cache):
cfg = ARM_CFG[arm]
self.model = TraceVLA(cfg, load_anchor=True).to(DEVICE).eval()
ckpt = torch.load(ckpt_path, weights_only=False)
# Training ran with load_anchor=False (cached features), so
# checkpoints carry no anchor weights; the eval model's
# anchor is freshly loaded from the same frozen backbone.
# Assert that ONLY anchor keys are missing and nothing is
# unexpected, so a real checkpoint mismatch still fails loud.
missing, unexpected = self.model.load_state_dict(
ckpt["ema"], strict=False)
assert not unexpected, \
f"unexpected ckpt keys: {unexpected[:5]}"
bad = [k for k in missing if not k.startswith("anchor.")]
assert not bad, f"non-anchor keys missing from ckpt: {bad[:5]}"
self.stats = cache["stats"]
self.text_emb = cache["text_emb"]
self.cache = cache
self.history = []
def reset(self):
self.history = []
@torch.no_grad()
def demo_tensors(self, ds_index, condition, swapped_ds=None):
eps = [ep for ep in self.cache["episodes"]
if ep["task_index"] == ds_index
and ep["split"] in ("train", "demo")]
ep = eps[0]
feats = self.cache["features"][ep["start"]:ep["start"] + ep["length"], 0]
idx = subsample_indices(ep["length"])
demo = feats[idx].float()
if condition == "shuffled":
demo = demo[torch.randperm(demo.shape[0],
generator=torch.Generator()
.manual_seed(5))]
mask = torch.ones(demo.shape[0], dtype=torch.bool)
times = idx.float() / 10.0
return (demo.unsqueeze(0).to(DEVICE), mask.unsqueeze(0).to(DEVICE),
times.unsqueeze(0).to(DEVICE))
@torch.no_grad()
def act(self, obs, ds_index, condition, demo_ctx):
imgs = torch.stack([
torch.as_tensor(np.asarray(obs["agentview_image"]))
.permute(2, 0, 1),
torch.as_tensor(np.asarray(obs["robot0_eye_in_hand_image"]))
.permute(2, 0, 1)]).float().to(DEVICE) / 255.0
pooled = self.model.anchor.encode_patches(imgs) # [2,64,768]
state_raw = build_state(obs)
s_mean, s_std = self.stats["state_mean"], self.stats["state_std"]
state_norm = (torch.as_tensor(state_raw) - s_mean) / s_std
# Mirror the training convention (data.py _query_fields):
# history ALWAYS has exactly history_len=3 slots, most recent
# first; missing slots are zero with elapsed 0.0 and mask
# False. Passing fewer slots crashes build_history against
# history_pos_emb (H=3) - the original code passed H=0 at
# episode start and H<3 for the first two replans.
entries = list(self.history)
while len(entries) < 3:
entries.append((torch.zeros(2, 64, 768), torch.zeros(8),
torch.zeros(7), 0.0, False))
hp = torch.stack([h[0] for h in entries])
hs = torch.stack([h[1] for h in entries])
ha = torch.stack([h[2] for h in entries])
he = torch.tensor([h[3] for h in entries])
hm = torch.tensor([h[4] for h in entries])
hist = (hp.unsqueeze(0).to(DEVICE), hs.unsqueeze(0).to(DEVICE),
ha.unsqueeze(0).to(DEVICE), he.unsqueeze(0).to(DEVICE),
hm.unsqueeze(0).to(DEVICE))
text = None
if condition in ("textonly", "hybrid"):
text = self.text_emb[ds_index].unsqueeze(0).to(DEVICE)
ctx = self.model.compute_context(
pooled.unsqueeze(0), text, state_norm.unsqueeze(0).to(DEVICE),
hist, demo_memory=demo_ctx[0] if demo_ctx else None,
window_mask=demo_ctx[1] if demo_ctx else None)
chunk, _ = self.model.sample_actions(ctx, 1, DEVICE)
a_mean, a_std = self.stats["action_mean"], self.stats["action_std"]
actions = (chunk[0].cpu() * a_std + a_mean).numpy()
return actions, pooled.cpu(), state_norm.cpu()
def push_history(self, pooled, state_norm, last_action_norm):
entry = (pooled, state_norm, last_action_norm, 0.4, True)
self.history = ([entry] + self.history)[:3]
# Rebuild elapsed/mask in adapter order (most recent first).
fixed = []
for i, h in enumerate(self.history):
fixed.append((h[0], h[1], h[2], 0.4 * (i + 1), True))
self.history = fixed
def make_env(suite_name, task_idx):
import os
from libero.libero import benchmark, get_libero_path
from libero.libero.envs import OffScreenRenderEnv
suite = benchmark.get_benchmark_dict()[suite_name]()
task = suite.get_task(task_idx)
bddl = os.path.join(get_libero_path("bddl_files"),
task.problem_folder, task.bddl_file)
env = OffScreenRenderEnv(bddl_file_name=bddl, camera_heights=256,
camera_widths=256,
camera_names=["agentview",
"robot0_eye_in_hand"])
env.seed(0)
init_states = suite.get_task_init_states(task_idx)
return env, init_states
def run_episode(env, init_state, policy, ds_index, condition, demo_ctx,
cap, video_path=None, record_actions=False, shadow=None):
obs = env.reset()
obs = env.set_init_state(init_state)
if shadow is not None:
s_env, s_init = shadow
s_obs = s_env.reset()
s_obs = s_env.set_init_state(s_init)
policy.reset()
frames = []
actions_done = []
success = False
shadow_success = False
chunk, pooled, s_norm = None, None, None
a_mean, a_std = policy.stats["action_mean"], policy.stats["action_std"]
for step in range(cap):
if step % 4 == 0:
chunk, pooled, s_norm = policy.act(obs, ds_index, condition,
demo_ctx)
if step > 0:
last_norm = (torch.as_tensor(actions_done[-4])
- a_mean) / a_std
policy.push_history(pooled_prev, s_norm_prev, last_norm)
pooled_prev, s_norm_prev = pooled, s_norm
action = chunk[step % 4]
obs, _, done, _ = env.step(action.tolist())
actions_done.append(action)
if shadow is not None:
s_obs, _, _, _ = s_env.step(action.tolist())
if s_env.check_success():
shadow_success = True
if video_path is not None:
frames.append(np.asarray(obs["agentview_image"]))
if env.check_success():
success = True
break
if done:
break
if video_path is not None and frames:
import cv2
h, w = frames[0].shape[:2]
wr = cv2.VideoWriter(str(video_path),
cv2.VideoWriter_fourcc(*"mp4v"), 10, (w, h))
for fr in frames:
wr.write(fr[:, :, ::-1])
wr.release()
out = {"success": success, "steps": len(actions_done)}
if shadow is not None:
out["shadow_success"] = shadow_success
if record_actions:
out["actions"] = [a.tolist() for a in actions_done]
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", required=True)
ap.add_argument("--arm", required=True, choices=list(ARM_CFG))
ap.add_argument("--tasks", required=True,
help="comma list of suite:bench_idx, e.g. "
"libero_goal:3,libero_object:0")
ap.add_argument("--episodes", type=int, default=3)
ap.add_argument("--condition", default="correct",
choices=["correct", "nodemo", "swapped", "shuffled",
"textonly", "hybrid"])
ap.add_argument("--out", required=True)
ap.add_argument("--videos", default=None)
ap.add_argument("--reproduce", action="store_true")
args = ap.parse_args()
cache = torch.load(EXP / "trace_vla" / "feature_cache_subset.pt",
weights_only=False)
mapping = json.loads((EXP / "fewshot" / "env_dataset_task_mapping.json")
.read_text())
policy = TracePolicy(args.ckpt, args.arm, cache)
results = {"ckpt": args.ckpt, "arm": args.arm,
"condition": args.condition, "tasks": {}}
specs = []
suite_offset = {"libero_10": 0, "libero_goal": 10,
"libero_object": 20, "libero_spatial": 30}
for spec in args.tasks.split(","):
suite_name, bench_idx = spec.split(":")
bench_idx = int(bench_idx)
# Mapping keys are "suite#bench_idx" and values are the
# WITHIN-SUITE dataset index; add the suite offset for the
# global dataset task index.
ds_index = suite_offset[suite_name] + \
mapping[f"{suite_name}#{bench_idx}"]
specs.append((spec, suite_name, bench_idx, ds_index))
for si, (spec, suite_name, bench_idx, ds_index) in enumerate(specs):
env, init_states = make_env(suite_name, bench_idx)
demo_ctx = None
shadow_spec = None
if args.condition == "swapped":
shadow_spec = specs[(si + 1) % len(specs)]
mem, wm, _ = policy.model.encode_demo(
*policy.demo_tensors(shadow_spec[3], "correct"))
demo_ctx = (mem, wm)
elif args.condition not in ("nodemo", "textonly"):
mem, wm, _ = policy.model.encode_demo(
*policy.demo_tensors(ds_index, args.condition))
demo_ctx = (mem, wm)
eps_out = []
for ep_i in range(args.episodes):
video = None
if args.videos:
Path(args.videos).mkdir(parents=True, exist_ok=True)
video = Path(args.videos) / f"{suite_name}_{bench_idx}_ep{ep_i}.mp4"
shadow = None
s_env = None
if shadow_spec is not None:
s_env, s_inits = make_env(shadow_spec[1], shadow_spec[2])
shadow = (s_env, s_inits[ep_i])
t0 = time.time()
r = run_episode(env, init_states[ep_i], policy, ds_index,
args.condition, demo_ctx, CAPS[suite_name],
video_path=video,
record_actions=args.reproduce,
shadow=shadow)
if s_env is not None:
s_env.close()
r["seconds"] = round(time.time() - t0, 1)
if args.reproduce and r["success"]:
env2, _ = make_env(suite_name, bench_idx)
obs = env2.reset()
obs = env2.set_init_state(init_states[ep_i])
ok = False
for a in r["actions"]:
obs, _, _, _ = env2.step(a)
if env2.check_success():
ok = True
break
r["replay_reproduces"] = ok
env2.close()
eps_out.append(r)
print(spec, f"ep{ep_i}", r["success"], r["steps"], flush=True)
env.close()
results["tasks"][spec] = {
"ds_index": ds_index,
"successes": sum(1 for e in eps_out if e["success"]),
"shadow_successes": sum(1 for e in eps_out
if e.get("shadow_success")),
"episodes": [{k: v for k, v in e.items() if k != "actions"}
for e in eps_out],
}
Path(args.out).write_text(json.dumps(results, indent=1))
print(json.dumps({k: v["successes"] for k, v in
results["tasks"].items()}, indent=1))
if __name__ == "__main__":
main()