File size: 7,126 Bytes
ae1ed83 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | #!/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_video.json")
VID = EXP / "trace_validation" / "results" / "videos_r6_obj7"
VID.mkdir(parents=True, exist_ok=True)
def rollout(env, init_state, policy, ep_idx):
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()
frames = []
def grab(o):
av = np.asarray(o["agentview_image"]).copy()
if "robot0_eye_in_hand_image" in o:
wr_img = np.asarray(o["robot0_eye_in_hand_image"]).copy()
frames.append(np.concatenate([av, wr_img], axis=1))
else:
frames.append(av)
grab(obs)
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)
grab(obs)
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
import cv2
vname = f"r6_30k_obj7_ep{ep_idx}.mp4"
vpath = VID / vname
hh, ww = frames[0].shape[:2]
wr = cv2.VideoWriter(str(vpath), cv2.VideoWriter_fourcc(*"mp4v"),
10, (ww, hh))
for fr in frames:
wr.write(fr[:, :, ::-1])
wr.release()
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,
"video": vname,
"n_frames": len(frames),
"video_bytes": vpath.stat().st_size}
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": []}
done = 0
for ep_i in range(done, args.episodes):
t0 = time.time()
r = rollout(env, init_states[ep_i], policy, ep_i)
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()
|