File size: 24,904 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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
#!/usr/bin/env python3
"""Data Factory — matched closed-loop eval of R0-R4 on DEV inits.

Suite (spec v2.0 section XV), run identically for every arm on
dev init states 20-24 of the 7 train scenes, pair-1 goals
(A = native goal object, B = first partner), seed 0, cap 280:

  P0 original layout, goal alternates A/B by init parity
  P1 target teleported 5 cm   (goal A)
  P2 target teleported 11 cm  (goal A)
  P3 target teleported 20 cm  (goal A; skipped+logged if infeasible)
  P4 A<->B swap, goals A and B (2 rollouts)
  P5 B placed at A's original position, A teleported 11 cm (goal A)
  P6 original layout, demo A vs demo B from the same init (2
     rollouts, each scored on its own demo's goal)

Intervention target positions are drawn from an RNG seeded per
(scene, init, condition, goal), so every arm faces byte-identical
scenes. Metrics per rollout (spec 15.2, kept separate): first-
approached object (selection), approach (min EEF-target distance
< 5 cm), min EEF distance to the true target and to the target's
original position, per-object lift vs the post-settle baseline
(grasp = lift > 4 cm), placement predicate at the end, full
success (native check_success for the scene's native goal,
LIBERO predicate otherwise — validated equivalent in df_audit).

R4 receives candidate masks from simulator poses at every replan
(oracle region proposer, the v2 design's documented eval-time
input; disclosed in the report). All other arms are pure v1.
Results append to results/df_eval_<arm>.jsonl (resumable).
"""
import argparse
import hashlib
import json
import sys
import time
from pathlib import Path

import numpy as np
import torch

sys.path.insert(0, str(Path(__file__).parent))
sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "trace_vla"))
from trace_vla.config import TraceConfig                      # noqa: E402
from trace_vla.model_v2 import TraceVLA2                      # noqa: E402
from trace_vla.model_v3 import TraceVLA3                      # noqa: E402
from trace_vla.model_v4 import TraceVLA4                      # noqa: E402
from eval_trace_heldout import TracePolicy, build_state, make_env  # noqa: E402
from df_expert import goal_in                                 # noqa: E402
from df_build_expand import pairs_for_scene                   # noqa: E402
from v2_scene import (candidate_masks, free_objects,          # noqa: E402
                      object_positions, settle, swap_objects,
                      teleport_object)
from v2_dash import merge_item                                # noqa: E402
from trace_vla.data import subsample_indices                  # noqa: E402
from df_data_raw import apply_named_state                     # noqa: E402

EXP = Path.home() / "sera_v4_experiments"
DF = EXP / "data_factory"
DEVICE = "cuda"
CAP = 280
TRAIN_SCENES = [0, 2, 3, 4, 6, 8, 9]
DEV_INITS = [20, 21, 22, 23, 24]
ARM_CKPT = {
    "r0": (EXP / "trace_validation" / "runs" / "rawmem"
           / "ckpt_05000.pt", "v1"),
    "r1": (DF / "runs" / "r1" / "ckpt_05000.pt", "v1"),
    "r2": (DF / "runs" / "r2" / "ckpt_05000.pt", "v1"),
    "r3": (DF / "runs" / "r3" / "ckpt_05000.pt", "v1"),
    "r4": (DF / "runs" / "r4" / "ckpt_05000.pt", "v2"),
    "r5": (DF / "runs" / "r5" / "ckpt_05000.pt", "v3"),
    "r6": (DF / "runs" / "r6" / "ckpt_05000.pt", "v4"),
    "r6_100k": (DF / "runs" / "r6_200k" / "ckpt_100000.pt", "v4m"),
    "r6_200k": (DF / "runs" / "r6_200k_p2" / "ckpt_200000.pt", "v4m"),
}
INV = json.loads((DF / "scene_inventory.json").read_text())
DS_OF_OBJ = {}
for bench_s, obj in INV["obj_of_task"].items():
    DS_OF_OBJ[obj] = 20 + json.loads(
        (EXP / "fewshot" / "env_dataset_task_mapping.json").read_text()
    )[f"libero_object#{bench_s}"]


class TracePolicyV2(TracePolicy):
    def __init__(self, ckpt_path, cache):
        cfg = TraceConfig(delta_use_residuals=False,
                          use_echo_loss=False)
        self.model = TraceVLA2(cfg, load_anchor=True).to(DEVICE).eval()
        ckpt = torch.load(ckpt_path, weights_only=False)
        missing, unexpected = self.model.load_state_dict(
            ckpt["ema"], strict=False)
        assert not unexpected, f"unexpected: {unexpected[:5]}"
        bad = [k for k in missing if not k.startswith("v1.anchor.")]
        assert not bad, f"non-anchor missing: {bad[:5]}"
        self.stats = cache["stats"]
        self.text_emb = cache["text_emb"]
        self.cache = cache
        self.history = []
        self.env = None
        self.names = None

    def attach(self, env, names):
        self.env, self.names = env, names

    @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.v1.anchor.encode_patches(imgs)
        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
        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))
        demo, fmask, ftimes = demo_ctx
        pos = object_positions(obs)
        masks, _ = candidate_masks(self.env.env.sim, pos, self.names)
        cand = torch.as_tensor(masks).float().unsqueeze(0).to(DEVICE)
        cvalid = torch.ones(1, len(self.names), dtype=torch.bool,
                            device=DEVICE)
        ctx, _aux = self.model.compute_context_v2(
            pooled.unsqueeze(0), None,
            state_norm.unsqueeze(0).to(DEVICE), hist,
            demo_pooled=demo, frame_mask=fmask, frame_times=ftimes,
            cand_mask=cand, cand_valid=cvalid)
        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()


class TracePolicyV3(TracePolicyV2):
    """R5 policy: TraceVLA3 (PDF core). Candidate masks come from
    simulator poses at every replan, same oracle region proposer
    as R4 (documented eval-time input, disclosed in the report).
    """

    CTX = "compute_context_v3"
    MODEL = TraceVLA3

    def __init__(self, ckpt_path, cache):
        cfg = TraceConfig(delta_use_residuals=False,
                          use_echo_loss=False)
        self.model = self.MODEL(cfg, load_anchor=True).to(DEVICE).eval()
        ckpt = torch.load(ckpt_path, weights_only=False)
        missing, unexpected = self.model.load_state_dict(
            ckpt["ema"], strict=False)
        assert not unexpected, f"unexpected: {unexpected[:5]}"
        bad = [k for k in missing if not k.startswith("v1.anchor.")]
        assert not bad, f"non-anchor missing: {bad[:5]}"
        self.stats = cache["stats"]
        self.text_emb = cache["text_emb"]
        self.cache = cache
        self.history = []
        self.env = None
        self.names = None

    @torch.no_grad()
    def act_aux(self, obs, ds_index, 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.v1.anchor.encode_patches(imgs)
        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
        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))
        demo, fmask, ftimes = demo_ctx
        pos = object_positions(obs)
        masks, _ = candidate_masks(self.env.env.sim, pos, self.names)
        cand = torch.as_tensor(masks).float().unsqueeze(0).to(DEVICE)
        cvalid = torch.ones(1, len(self.names), dtype=torch.bool,
                            device=DEVICE)
        ctx_fn = getattr(self.model, self.CTX)
        ctx, aux = ctx_fn(
            pooled.unsqueeze(0), None,
            state_norm.unsqueeze(0).to(DEVICE), hist,
            demo_pooled=demo, frame_mask=fmask, frame_times=ftimes,
            cand_mask=cand, cand_valid=cvalid)
        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(), aux

    @torch.no_grad()
    def act(self, obs, ds_index, condition, demo_ctx):
        actions, pooled, s_norm, _ = self.act_aux(obs, ds_index,
                                                  demo_ctx)
        return actions, pooled, s_norm


class TracePolicyV4(TracePolicyV3):
    """R6 policy: TraceVLA4 (PDF full) + adaptive execution
    horizon (PDF 11.2): the replan cadence follows the
    correspondence confidence — conf >= 0.8 executes 1 step,
    >= 0.55 executes 2 steps, otherwise 4 steps."""

    CTX = "compute_context_v4"
    MODEL = TraceVLA4

    @torch.no_grad()
    def act_h(self, obs, ds_index, demo_ctx):
        actions, pooled, s_norm, aux = self.act_aux(obs, ds_index,
                                                    demo_ctx)
        conf = float(aux["correspondence"]["confidence"][0, 0]) \
            if aux is not None else 0.0
        horizon = 1 if conf >= 0.8 else (2 if conf >= 0.55 else 4)
        return actions, pooled, s_norm, horizon


class TracePolicyV4M(TracePolicyV4):
    """R6 milestone policy (100k/200k): the anchor's vision blocks
    8-11 + final norm are the checkpoint's vision_top_ema (the
    encoder the milestone was trained with); demo features are
    recomputed from the raw200k store with that same encoder —
    cache features live in the old frozen space and must not be
    mixed in."""

    def __init__(self, ckpt_path, cache):
        super().__init__(ckpt_path, cache)
        ck = torch.load(ckpt_path, weights_only=False)
        apply_named_state(self.model.v1.anchor.tips.vision_encoder,
                          ck["vision_top_ema"])
        idx = json.loads((DF / "raw200k" / "raw200k_index.json")
                         .read_text())
        self._raw = np.memmap(DF / "raw200k" / "raw_images.dat",
                              dtype=np.uint8, mode="r",
                              shape=(idx["F"], 2, 224, 224, 3))

    @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]
        idx = subsample_indices(ep["length"])
        pos = ep["start"] + idx.numpy()
        imgs = torch.as_tensor(np.ascontiguousarray(
            self._raw[pos, 0])).to(DEVICE) \
            .permute(0, 3, 1, 2).float() / 255.0
        demo = self.model.v1.anchor.encode_patches(imgs)
        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))


def rollout_h(env, init_state, policy, goal_obj, demo_ds,
              intervene, native_goal):
    """Rollout with the R6 adaptive horizon: identical scenes,
    seeds and metrics to rollout(); only the replan cadence
    varies (that cadence IS the module under test, spec 8.3)."""
    torch.manual_seed(1234)
    obs = env.reset()
    obs = env.set_init_state(init_state)
    obs = settle(env)
    pos_pre = object_positions(obs)
    old_target = pos_pre[goal_obj].copy()
    if intervene is not None:
        obs = intervene(obs)
        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(demo_ds, "correct")
    policy.reset()
    a_mean, a_std = policy.stats["action_mean"], policy.stats["action_std"]
    min_d_target, min_d_old = 1e9, 1e9
    first_approach = None
    max_lift = {n: 0.0 for n in names}
    success = False
    chunk, pooled_prev, s_norm_prev = None, None, None
    actions_done = []
    used, horizon, prev_horizon = 0, 0, 4
    steps = 0
    for step in range(CAP):
        if chunk is None or used >= horizon:
            chunk, pooled, s_norm, horizon = policy.act_h(
                obs, demo_ds, demo_ctx)
            if step > 0:
                # mirror rollout(): history action = first action
                # of the previous chunk
                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)
        min_d_target = min(min_d_target,
                           float(np.linalg.norm(eef - pos[goal_obj])))
        min_d_old = min(min_d_old,
                        float(np.linalg.norm(eef - old_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 goal_in(env, goal_obj):
            success = True
            break
        if done:
            break
    grasped = [n for n in names if max_lift[n] > 0.04]
    return {
        "success": bool(success),
        "placement_end": bool(goal_in(env, goal_obj)),
        "native_check": bool(env.check_success())
        if goal_obj == native_goal else None,
        "first_approach": first_approach,
        "selection_correct": (first_approach == goal_obj)
        if first_approach is not None else None,
        "approached": bool(min_d_target < 0.05),
        "min_dist_target": round(min_d_target, 4),
        "min_dist_old": round(min_d_old, 4),
        "grasped_correct": bool(goal_obj in grasped),
        "grasped_wrong": [n for n in grasped if n != goal_obj],
        "steps": steps}


def reloc_xy(rng, orig_xy, others_xy, basket_xy, dist):
    angs = rng.uniform(0, 2 * np.pi, 32)
    for ang in angs:
        cand = orig_xy + dist * np.array([np.cos(ang), np.sin(ang)])
        if not (-0.30 <= cand[0] <= 0.22 and -0.34 <= cand[1] <= 0.20):
            continue
        if any(np.linalg.norm(cand - o) < 0.07 for o in others_xy):
            continue
        if basket_xy is not None \
                and np.linalg.norm(cand - basket_xy) < 0.12:
            continue
        return cand
    return None


def rollout(env, init_state, policy, kind, goal_obj, demo_ds,
            intervene, native_goal):
    torch.manual_seed(1234)
    obs = env.reset()
    obs = env.set_init_state(init_state)
    obs = settle(env)
    pos_pre = object_positions(obs)
    old_target = pos_pre[goal_obj].copy()
    if intervene is not None:
        obs = intervene(obs)
        obs = settle(env)
    base = object_positions(obs)
    names = [n for n in free_objects(env.env.sim, base)
             if n != "basket_1"]
    if kind in ("v2", "v3"):
        policy.attach(env, names)
    if kind in ("v2", "v3"):
        demo_ctx = policy.demo_tensors(demo_ds, "correct")
    else:
        mem, wm, _ = policy.model.encode_demo(
            *policy.demo_tensors(demo_ds, "correct"))
        demo_ctx = (mem, wm)
    policy.reset()
    a_mean, a_std = policy.stats["action_mean"], policy.stats["action_std"]
    min_d_target, min_d_old = 1e9, 1e9
    first_approach = None
    max_lift = {n: 0.0 for n in names}
    success = False
    chunk, pooled_prev, s_norm_prev = None, None, None
    actions_done = []
    steps = 0
    for step in range(CAP):
        if step % 4 == 0:
            chunk, pooled, s_norm = policy.act(
                obs, demo_ds, "correct", 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)
        steps = step + 1
        eef = np.asarray(obs["robot0_eef_pos"], dtype=np.float64)
        pos = object_positions(obs)
        min_d_target = min(min_d_target,
                           float(np.linalg.norm(eef - pos[goal_obj])))
        min_d_old = min(min_d_old,
                        float(np.linalg.norm(eef - old_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 goal_in(env, goal_obj):
            success = True
            break
        if done:
            break
    grasped = [n for n in names if max_lift[n] > 0.04]
    return {
        "success": bool(success),
        "placement_end": bool(goal_in(env, goal_obj)),
        "native_check": bool(env.check_success())
        if goal_obj == native_goal else None,
        "first_approach": first_approach,
        "selection_correct": (first_approach == goal_obj)
        if first_approach is not None else None,
        "approached": bool(min_d_target < 0.05),
        "min_dist_target": round(min_d_target, 4),
        "min_dist_old": round(min_d_old, 4),
        "grasped_correct": bool(goal_obj in grasped),
        "grasped_wrong": [n for n in grasped if n != goal_obj],
        "steps": steps}


def cond_seed(bench, init_idx, cond, goal):
    h = hashlib.sha256(
        f"{bench}|{init_idx}|{cond}|{goal}".encode()).hexdigest()
    return int(h[:8], 16)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("arm", choices=list(ARM_CKPT))
    args = ap.parse_args()
    arm = args.arm
    ckpt, kind = ARM_CKPT[arm]
    cache = torch.load(DF / "cache_df_r2.pt", weights_only=True,
                       mmap=True)
    if kind == "v2":
        policy = TracePolicyV2(str(ckpt), cache)
    elif kind == "v3":
        policy = TracePolicyV3(str(ckpt), cache)
    elif kind == "v4":
        policy = TracePolicyV4(str(ckpt), cache)
    elif kind == "v4m":
        policy = TracePolicyV4M(str(ckpt), cache)
    else:
        policy = TracePolicy(str(ckpt), "rawmem", cache)
    out_f = EXP / "trace_validation" / "results" / f"df_eval_{arm}.jsonl"
    done_keys = set()
    if out_f.exists():
        for line in out_f.read_text().splitlines():
            r = json.loads(line)
            done_keys.add((r["bench"], r["init"], r["cond"],
                           r["goal"]))
    total_plan = len(TRAIN_SCENES) * len(DEV_INITS) * 9
    n_done = len(done_keys)
    merge_item(f"data_factory.eval.{arm}", {
        "status": "running", "pct": round(100.0 * n_done / total_plan, 1)})
    for bench in TRAIN_SCENES:
        env, init_states = make_env("libero_object", bench)
        ga, gb = pairs_for_scene(bench)[0]
        native_goal = INV["obj_of_task"][str(bench)]
        for init_idx in DEV_INITS:
            # reference positions of the untouched layout
            obs = env.reset()
            obs = env.set_init_state(init_states[init_idx])
            obs = settle(env)
            pos0 = object_positions(obs)
            basket_xy = pos0["basket_1"][:2]
            others_all = [n for n in free_objects(env.env.sim, pos0)
                          if n != "basket_1"]

            def others_xy(skip):
                return [pos0[n][:2] for n in others_all if n != skip]

            jobs = []  # (cond, goal, intervene_fn or None, infeasible)
            g_par = ga if init_idx % 2 == 0 else gb
            jobs.append(("P0", g_par, None, False))
            for cond, dist in (("P1", 0.05), ("P2", 0.11),
                               ("P3", 0.20)):
                rng = np.random.default_rng(
                    cond_seed(bench, init_idx, cond, ga))
                xy = reloc_xy(rng, pos0[ga][:2], others_xy(ga),
                              basket_xy, dist)
                if xy is None:
                    jobs.append((cond, ga, None, True))
                else:
                    jobs.append((cond, ga,
                                 lambda o, x=xy: teleport_object(
                                     env, o, ga, x), False))
            jobs.append(("P4", ga,
                         lambda o: swap_objects(env, o, ga, gb), False))
            jobs.append(("P4", gb,
                         lambda o: swap_objects(env, o, ga, gb), False))
            rng = np.random.default_rng(
                cond_seed(bench, init_idx, "P5", ga))
            xy = reloc_xy(rng, pos0[ga][:2], others_xy(ga), basket_xy,
                          0.11)
            if xy is None:
                jobs.append(("P5", ga, None, True))
            else:
                def p5(o, x=xy):
                    o = teleport_object(env, o, gb, pos0[ga][:2])
                    return teleport_object(env, o, ga, x)
                jobs.append(("P5", ga, p5, False))
            jobs.append(("P6", ga, None, False))
            jobs.append(("P6", gb, None, False))

            for cond, goal, fn, infeasible in jobs:
                key = (bench, init_idx, cond, goal)
                if key in done_keys:
                    continue
                rec = {"arm": arm, "bench": bench, "init": init_idx,
                       "cond": cond, "goal": goal,
                       "ds": DS_OF_OBJ[goal]}
                if infeasible:
                    rec["infeasible"] = True
                else:
                    t0 = time.time()
                    if kind == "v4":
                        r = rollout_h(env, init_states[init_idx],
                                      policy, goal, DS_OF_OBJ[goal],
                                      fn, native_goal)
                    else:
                        r = rollout(env, init_states[init_idx], policy,
                                    kind, goal, DS_OF_OBJ[goal], fn,
                                    native_goal)
                    rec.update(r)
                    rec["seconds"] = round(time.time() - t0, 1)
                with open(out_f, "a") as f:
                    f.write(json.dumps(rec) + "\n")
                n_done += 1
                print(arm, bench, init_idx, cond, goal,
                      rec.get("success"), flush=True)
                merge_item(f"data_factory.eval.{arm}", {
                    "status": "running",
                    "pct": round(100.0 * n_done / total_plan, 1),
                    "metrics": {"Rollout xong": f"{n_done}/{total_plan}"}})
        env.close()
    merge_item(f"data_factory.eval.{arm}", {
        "status": "done", "pct": 100,
        "metrics": {"Rollout xong": f"{n_done}/{total_plan}"}})
    print(arm, "EVAL DONE", n_done, flush=True)


if __name__ == "__main__":
    main()