File size: 6,411 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
#!/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()