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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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
#!/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


MOVE_OBJECT = "milk_1"
MOVE_JOINT = "milk_1_joint0"
# Target v2: front-centre strip (0.00, -0.23), ~12 cm lateral (+x)
# from the original spot. The v1 target (-0.24, -0.18) was INVALID:
# the milk came to rest perched at z=0.0685 (vs 0.035 on the table),
# apparently on the corner of the chocolate_pudding box, and was
# never graspable. v2 keeps >= ~9.8 cm centre distance from the
# nearest object (butter) with no plan-view overlap, and the settle
# check below flags any episode whose resting z is off the table.
MOVE_TARGET_XY = (0.00, -0.23)
SETTLE_STEPS = 5


def run_episode(env, init_state, policy, ds_index, condition, demo_ctx,
                cap, video_path=None, record_actions=False, shadow=None,
                move_xy=None, 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()
    # Moved-object extension (Young's request 19:40 21/11/2026): after
    # the official init state is set and BEFORE the first policy step,
    # teleport milk_1 to a new absolute xy on the table (same target
    # for every episode), zero its velocity, let it settle for a few
    # zero-action steps (not counted, not recorded), and save the
    # first frame as visual evidence. Also tracks how close the EEF
    # ever gets (xy) to the NEW vs the ORIGINAL milk position, which
    # is the key behavioural readout of this test.
    move_info = None
    eef_min_new = None
    eef_min_old = None
    if move_xy is not None:
        sim = env.env.sim
        orig = np.asarray(obs[MOVE_OBJECT + "_pos"],
                          dtype=np.float64).ravel().copy()
        qpos = sim.data.get_joint_qpos(MOVE_JOINT).copy()
        qpos[0] = float(move_xy[0])
        qpos[1] = float(move_xy[1])
        sim.data.set_joint_qpos(MOVE_JOINT, qpos)
        try:
            sim.data.set_joint_qvel(MOVE_JOINT, np.zeros(6))
        except Exception:
            pass
        sim.forward()
        for _ in range(SETTLE_STEPS):
            obs, _, _, _ = env.step([0.0] * 7)
        settled = np.asarray(obs[MOVE_OBJECT + "_pos"],
                             dtype=np.float64).ravel().copy()
        move_info = {
            "object": MOVE_OBJECT,
            "orig_pos": [round(float(v), 4) for v in orig],
            "target_xy": [float(move_xy[0]), float(move_xy[1])],
            "settled_pos": [round(float(v), 4) for v in settled],
            "offset_xy": [round(float(settled[0] - orig[0]), 4),
                          round(float(settled[1] - orig[1]), 4)],
            "offset_dist": round(
                float(np.linalg.norm(settled[:2] - orig[:2])), 4),
            "settle_z_ok": bool(abs(float(settled[2] - orig[2])) <= 0.01),
        }
        if not move_info["settle_z_ok"]:
            print("MOVE WARNING: settled z differs from table z by",
                  round(float(settled[2] - orig[2]), 4),
                  "- object may be perched, episode contaminated",
                  flush=True)
        if first_frame_path is not None:
            import cv2
            cv2.imwrite(str(first_frame_path),
                        np.asarray(obs["agentview_image"])[:, :, ::-1])
        print("MOVE", json.dumps(move_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 move_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(move_info["settled_pos"])[:2]))
                d_old = float(np.linalg.norm(
                    eef[:2] - np.asarray(move_info["orig_pos"])[: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 move_info is not None:
        out["move"] = move_info
        try:
            out["milk_final_pos"] = [round(float(v), 4) for v in
                                     np.asarray(obs[MOVE_OBJECT + "_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"] = round(eef_min_new, 4)
            out["eef_min_dist_xy_to_old"] = 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": {},
               "moved": {"object": MOVE_OBJECT,
                         "target_xy": list(MOVE_TARGET_XY),
                         "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,
                            move_xy=MOVE_TARGET_XY,
                            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()