#!/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 SWAP_A = "milk_1" SWAP_B = "orange_juice_1" SWAP_JOINTS = ("milk_1_joint0", "orange_juice_1_joint0") # Swap test (Young's request 19:52 21/11/2026): after the official # init state is set, swap the xy positions of milk_1 and # orange_juice_1 (each keeps its own z and orientation quaternion), # so the milk stands exactly where the juice was and vice versa. # Readout: does the EEF go to the milk's NEW position (the juice's # old spot) or stay biased to the milk's OLD position (where the # juice now stands, possibly grasping the juice by mistake)? SETTLE_STEPS = 5 def run_episode(env, init_state, policy, ds_index, condition, demo_ctx, cap, video_path=None, record_actions=False, shadow=None, swap=False, first_frame_path=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() # Swap extension (Young's request 19:52 21/11/2026): after the # official init state is set and BEFORE the first policy step, # swap the xy of milk_1 and orange_juice_1 (z and orientation of # each object kept), zero velocities, settle a few zero-action # steps (not counted, not recorded), save the first frame. Also # tracks how close the EEF ever gets (xy) to the milk's NEW # position (= juice's original spot) vs its ORIGINAL position # (where the juice now stands) - the key behavioural readout. swap_info = None eef_min_new = None eef_min_old = None if swap: sim = env.env.sim orig_a = np.asarray(obs[SWAP_A + "_pos"], dtype=np.float64).ravel().copy() orig_b = np.asarray(obs[SWAP_B + "_pos"], dtype=np.float64).ravel().copy() qa = sim.data.get_joint_qpos(SWAP_JOINTS[0]).copy() qb = sim.data.get_joint_qpos(SWAP_JOINTS[1]).copy() qa_new = qa.copy(); qa_new[0] = qb[0]; qa_new[1] = qb[1] qb_new = qb.copy(); qb_new[0] = qa[0]; qb_new[1] = qa[1] sim.data.set_joint_qpos(SWAP_JOINTS[0], qa_new) sim.data.set_joint_qpos(SWAP_JOINTS[1], qb_new) for j in SWAP_JOINTS: try: sim.data.set_joint_qvel(j, np.zeros(6)) except Exception: pass sim.forward() for _ in range(SETTLE_STEPS): obs, _, _, _ = env.step([0.0] * 7) settled_a = np.asarray(obs[SWAP_A + "_pos"], dtype=np.float64).ravel().copy() settled_b = np.asarray(obs[SWAP_B + "_pos"], dtype=np.float64).ravel().copy() swap_info = { "swap_pair": [SWAP_A, SWAP_B], "orig_pos_a": [round(float(v), 4) for v in orig_a], "orig_pos_b": [round(float(v), 4) for v in orig_b], "settled_pos_a": [round(float(v), 4) for v in settled_a], "settled_pos_b": [round(float(v), 4) for v in settled_b], "swap_dist": round( float(np.linalg.norm(orig_b[:2] - orig_a[:2])), 4), } if first_frame_path is not None: import cv2 cv2.imwrite(str(first_frame_path), np.asarray(obs["agentview_image"])[:, :, ::-1]) print("SWAP", json.dumps(swap_info), flush=True) frames = [] actions_done = [] success = False shadow_success = False # Held-out extension (defensive, never breaks the episode): track # the max z-lift of every non-robot object position in obs, so the # report can say whether anything was grasped/lifted and what. obj_z0, obj_lift = {}, {} try: for k, v in obs.items(): if k.endswith("_pos") and not k.startswith("robot0"): arr = np.asarray(v, dtype=np.float64).ravel() if arr.size >= 3: obj_z0[k] = float(arr[2]) obj_lift[k] = 0.0 except Exception: obj_z0, obj_lift = {}, {} 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 swap_info is not None: try: eef = np.asarray(obs["robot0_eef_pos"], dtype=np.float64).ravel() d_new = float(np.linalg.norm( eef[:2] - np.asarray(swap_info["settled_pos_a"])[:2])) d_old = float(np.linalg.norm( eef[:2] - np.asarray(swap_info["orig_pos_a"])[:2])) eef_min_new = d_new if eef_min_new is None \ else min(eef_min_new, d_new) eef_min_old = d_old if eef_min_old is None \ else min(eef_min_old, d_old) except Exception: pass if obj_z0: try: for k, z0 in obj_z0.items(): arr = np.asarray(obs[k], dtype=np.float64).ravel() lift = float(arr[2]) - z0 if lift > obj_lift[k]: obj_lift[k] = lift except Exception: pass 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 swap_info is not None: out["swap"] = swap_info try: out["milk_final_pos"] = [round(float(v), 4) for v in np.asarray(obs[SWAP_A + "_pos"], dtype=np.float64).ravel()] out["juice_final_pos"] = [round(float(v), 4) for v in np.asarray(obs[SWAP_B + "_pos"], dtype=np.float64).ravel()] out["basket_final_pos"] = [round(float(v), 4) for v in np.asarray(obs["basket_1_pos"], dtype=np.float64).ravel()] except Exception: pass if eef_min_new is not None: out["eef_min_dist_xy_to_new_milk"] = round(eef_min_new, 4) out["eef_min_dist_xy_to_old_milk"] = round(eef_min_old, 4) if obj_lift: out["obj_max_lift"] = {k: round(v, 4) for k, v in obj_lift.items()} out["lifted_objects"] = [k for k, v in obj_lift.items() if v > 0.04] 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_plus25.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": {}, "swap": {"pair": [SWAP_A, SWAP_B], "settle_steps": SETTLE_STEPS}} 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() ff_path = None if args.videos: ff_path = Path(args.videos) / \ f"{suite_name}_{bench_idx}_ep{ep_i}_firstframe.png" 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, swap=True, first_frame_path=ff_path) 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()