File size: 14,702 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
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
#!/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


def run_episode(env, init_state, policy, ds_index, condition, demo_ctx,
                cap, video_path=None, record_actions=False, shadow=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()
    frames = []
    actions_done = []
    success = False
    shadow_success = False
    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 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 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.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": {}}
    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()
            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)
            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()