trace-vla-code / code /trace_validation /scripts /eval_r6_oneshot_obj7.py
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
6.41 kB
#!/usr/bin/env python3
"""One-shot held-out test: R6 @30k (EMA) on LIBERO Object #7.
Mirrors the C02 held-out Object #7 test of 2026-11-21
(eval_trace_heldout.py: condition correct, demo = first train-split
episode of ds25, video-only, seed 0, init states 0/1/2, cap 280) but
with the R6 policy (TracePolicyV4 + adaptive horizon) run exactly as
the R6 ladder eval ran it (df_eval_arms.rollout_h conventions:
settle, post-settle base positions, candidate masks from simulator
poses at every replan, torch.manual_seed(1234) per rollout).
Policy cache = feature_cache_subset_plus25.pt: its stats are
bit-identical to cache_df_r2.pt (verified 2026-11-22, max diff 0.0)
and it carries the ds25 demo episodes the v1 held-out test used.
Young's order 2026-11-22 11:26: Object #7 only, 3 episodes, report
per episode, dashboard per episode, run alongside the R6 200k
phase-1 job without touching it.
"""
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_validation" / "scripts"))
from df_eval_arms import TracePolicyV4, EXP, DF # noqa: E402
from eval_trace_heldout import make_env # noqa: E402
from v2_scene import free_objects, object_positions, settle # noqa: E402
from df_expert import goal_in # noqa: E402
from v2_dash import merge_item # noqa: E402
TARGET = "milk_1"
DS = 25
CAP = 280
OUT = (EXP / "trace_validation" / "results"
/ "eval_r6_30k_oneshot_object7.json")
def rollout(env, init_state, policy):
torch.manual_seed(1234)
obs = env.reset()
obs = env.set_init_state(init_state)
obs = settle(env)
base = object_positions(obs)
names = [n for n in free_objects(env.env.sim, base)
if n != "basket_1"]
policy.attach(env, names)
demo_ctx = policy.demo_tensors(DS, "correct")
policy.reset()
a_mean, a_std = (policy.stats["action_mean"],
policy.stats["action_std"])
min_d = 1e9
first_approach = None
max_lift = {n: 0.0 for n in names}
success = False
steps = 0
chunk, pooled_prev, s_norm_prev = None, None, None
actions_done = []
used, horizon, prev_horizon = 0, 0, 4
for step in range(CAP):
if chunk is None or used >= horizon:
chunk, pooled, s_norm, horizon = policy.act_h(
obs, DS, demo_ctx)
if step > 0:
last_norm = (torch.as_tensor(
actions_done[-prev_horizon]) - a_mean) / a_std
policy.push_history(pooled_prev, s_norm_prev,
last_norm)
pooled_prev, s_norm_prev = pooled, s_norm
prev_horizon = horizon
used = 0
action = chunk[used]
used += 1
obs, _, done, _ = env.step(action.tolist())
actions_done.append(action)
steps = step + 1
eef = np.asarray(obs["robot0_eef_pos"], dtype=np.float64)
pos = object_positions(obs)
if TARGET in pos:
min_d = min(min_d,
float(np.linalg.norm(eef - pos[TARGET])))
if first_approach is None:
for n in names:
if float(np.linalg.norm(eef - pos[n])) < 0.075:
first_approach = n
break
for n in names:
lift = float(pos[n][2] - base[n][2])
if lift > max_lift[n]:
max_lift[n] = lift
if env.check_success():
success = True
break
if done:
break
grasped = [n for n in names if max_lift[n] > 0.04]
try:
placed = bool(goal_in(env, TARGET))
except Exception:
placed = None
return {"success": bool(success),
"placed_in_basket_end": placed,
"first_approach": first_approach,
"grasped_correct": TARGET in grasped,
"grasped_wrong": [n for n in grasped if n != TARGET],
"max_lift_target": round(max_lift.get(TARGET, 0.0), 4),
"min_dist_target": round(min_d, 4),
"steps": steps}
def grasp_label(r):
if r["grasped_correct"]:
return "grasp đúng sữa"
if r["grasped_wrong"]:
return "grasp sai: " + ",".join(r["grasped_wrong"])
return "không grasp"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--episodes", type=int, default=3)
args = ap.parse_args()
cache = torch.load(EXP / "trace_vla"
/ "feature_cache_subset_plus25.pt",
weights_only=False)
ckpt = DF / "runs" / "r6_30k" / "ckpt_30000.pt"
policy = TracePolicyV4(str(ckpt), cache)
env, init_states = make_env("libero_object", 7)
results = {"ckpt": str(ckpt), "task": "libero_object:7",
"ds_index": DS, "condition": "correct",
"model": "R6@30k EMA, one-shot",
"episodes": []}
if OUT.exists():
prev = json.loads(OUT.read_text())
if prev.get("ckpt") == str(ckpt):
results = prev
done = len(results["episodes"])
for ep_i in range(done, args.episodes):
t0 = time.time()
r = rollout(env, init_states[ep_i], policy)
r["ep"] = ep_i
r["seconds"] = round(time.time() - t0, 1)
results["episodes"].append(r)
OUT.write_text(json.dumps(results, indent=1))
n_succ = sum(1 for e in results["episodes"] if e["success"])
metrics = {"Task": "Object #7 (milk) — held-out thật",
"Model": "R6@30k EMA · one-shot",
"Episode": f"{ep_i + 1}/{args.episodes}",
"Success tổng": f"{n_succ}/{ep_i + 1}"}
for e in results["episodes"]:
metrics[f"Ep {e['ep']}"] = (
f"success={e['success']} · {grasp_label(e)} · "
f"đặt vào giỏ={e['placed_in_basket_end']}")
merge_item("data_factory.oneshot_r6_30k", {
"status": ("running" if ep_i < args.episodes - 1
else "done"),
"pct": round(100.0 * (ep_i + 1) / args.episodes, 1),
"metrics": metrics})
print(f"EP {ep_i} DONE", json.dumps(r), flush=True)
env.close()
print("ALL DONE", flush=True)
if __name__ == "__main__":
main()