File size: 33,251 Bytes
ffefb64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
"""Grasp traces and repeatability of a policy in the settings profile's scene.

repeat  Runs a few identical episodes several times under three conditions and reports
        whether, where and why repeats diverge:
          same_process   one process, the episodes repeated back to back
          separate       one process per repeat, running in parallel (as eval_policy does)
          deterministic  like separate, with torch deterministic algorithms, TF32 off and
                         a fixed cuBLAS workspace
        Each run builds a fresh simulator and pins the episode (seed, move, the expert's
        plan), the policy's sampling seed and the simulator reset exactly as eval_policy
        does. Per frame it keeps a hash of the images the policy saw and the commanded and
        actual joints, so the first divergence can be attributed to the inputs (simulation,
        rendering) or to the policy (same inputs, different outputs).

trace   Runs episodes and records every frame: commanded and actual joints; the jaw's
        pinch point relative to where the marked piece stands now, along and across the
        jaw's actual closing direction; the jaw yaw against the expert's; the gripper's
        lean; the physical fingertip gap (mm, from the jaw geometry) commanded and actual;
        the piece's pose and tilt; action-chunk boundaries. Every physics substep: the first
        contact of the arm with the marked piece (before or after closing began), of the arm
        with another piece, and of the marked piece with another piece; the first tilt past
        5 and 45 degrees. A fingertip touch at the grasp (within 3 mm of the grasp height
        and 2.5 mm sideways) before closing is the intended contact, recorded separately.
        Closing begins where the gripper command starts its ramp down within 20 mm above
        the grasp point. Failures are classified by what happened first (see classify),
        and slow (4x) replays of pawn failures are written with the measurements overlaid.

Run:  MUJOCO_GL=egl PHASE2_PROFILE=baseline .venv/bin/python sim/grasp_trace.py repeat \
          --policy models/baseline --indices 3,7,12 --repeats 5 --out sim/reports/grasp_trace/repeat
      MUJOCO_GL=egl PHASE2_PROFILE=baseline .venv/bin/python sim/grasp_trace.py trace \
          --policy models/baseline --episodes 40 --workers 6 --seed 8000003 --out sim/reports/grasp_trace/trace
"""
from __future__ import annotations

import argparse
import hashlib
import io
import json
import multiprocessing as mp
import os
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path
from queue import Empty

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
OPEN, CLOSING = 4.0, 3.0          # gripper command, LeRobot 0-100 units (see eval_policy)


# ---------------------------------------------------------------------------- setup
def set_deterministic():
    """Deterministic torch/CUDA settings; call before torch touches CUDA."""
    os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
    import torch

    torch.use_deterministic_algorithms(True, warn_only=True)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False


def episode(runner, seed: int, i: int):
    """Episode i of `seed` exactly as eval_policy sets it up: the move (checked doable by
    the expert), the expert's own grasp plan, and the policy's sampling seed."""
    import mujoco
    import numpy as np

    erng = np.random.default_rng([seed, i])
    for _ in range(20):
        ep_seed = int(erng.integers(2**62))
        task = runner.setup(np.random.default_rng(ep_seed))
        if runner.run(task, ep_seed).success:
            break
    task = runner.setup(np.random.default_rng(ep_seed))
    d = runner.d
    saved = (d.qpos.copy(), d.qvel.copy(), d.act.copy(), d.ctrl.copy(), d.time)
    plan = runner.expert.plan_pick(d, task.target, np.random.default_rng(ep_seed))
    d.qpos[:], d.qvel[:], d.act[:], d.ctrl[:] = saved[:4]
    d.time = saved[4]
    mujoco.mj_forward(runner.m, d)
    return task, ep_seed, int(erng.integers(2**31)), plan


def gap_table(expert, heights_mm=(2.0, 10.0)):
    """Gripper angle -> physical gap (mm) between the fixed and moving fingertips, averaged
    over heights_mm above the fingertip (from the expert's jaw geometry)."""
    import numpy as np

    jaws = expert.jaws
    rel = np.linspace(heights_mm[0], heights_mm[1], 5) / 1000
    fixed = np.interp(rel, jaws.heights, jaws.fixed_inner)
    qs = np.linspace(-0.3, 1.3, 161)
    gaps = []
    for q in qs:
        inner, _ = jaws.moving_profile(q, rel)
        gaps.append(float(np.nanmean(inner - fixed)) * 1000 if np.any(~np.isnan(inner)) else np.nan)
    return qs, np.array(gaps)


class JpegFrames(list):
    """Frames kept as JPEG bytes (drive() appends the images the policy saw)."""

    def append(self, img):
        from PIL import Image

        buf = io.BytesIO()
        Image.fromarray(img).save(buf, "JPEG", quality=85)
        super().append(buf.getvalue())


class HashFrames(list):
    """Frames kept as an md5 of their bytes (for repeatability)."""

    def append(self, img):
        import numpy as np

        super().append(hashlib.md5(np.ascontiguousarray(img).tobytes()).hexdigest())


# ---------------------------------------------------------------------------- tracing
class Tracer:
    def __init__(self, runner, task, plan, policy, capture=False):
        import mujoco
        import numpy as np

        self.r, self.task, self.plan, self.policy = runner, task, plan, policy
        m, d, w, ex = runner.m, runner.d, runner.w, runner.expert
        self.target = task.target
        self.others = set(task.squares.values()) - {task.target}
        self.base0 = w.base_pos(d, task.target).copy()
        self.grasp_rel = plan.grasp_point - self.base0
        self.hand = {m.body("gripper").id, m.body("moving_jaw_so101_v1").id}
        self.qs, self.gaps = gap_table(ex)
        self.n_steps = policy.config.n_action_steps
        self.rows, self.events, self.parts = [], {}, {}
        self.open_max, self.closing = 0.0, False
        self.cmd_hist = []
        self.capture = capture
        self.side = []
        if capture:
            self.cam = mujoco.MjvCamera()
            self.cam.type = mujoco.mjtCamera.mjCAMERA_FREE
            self.cam.lookat[:] = plan.grasp_point
            self.cam.distance = 0.16
            self.cam.azimuth = float(np.degrees(plan.yaw)) + 90.0       # looking across the closing direction
            self.cam.elevation = -12.0
            self.side_renderer = mujoco.Renderer(m, 240, 320)

    def close(self):
        if self.capture:
            self.side_renderer.close()

    def _event(self, key, t, part=None):
        if key not in self.events:
            self.events[key] = t
            if part is not None:
                self.parts[key] = part

    def _at_grasp(self):
        """Pinch point within 3 mm of the grasp height and 2.5 mm sideways of the piece."""
        import numpy as np

        r, d, ex = self.r, self.r.d, self.r.expert
        pinch, _ = ex.kin.pose(d.qpos[ex.kin.qadr].copy(), self.plan.offset)
        err = pinch - (r.w.base_pos(d, self.target) + self.grasp_rel)
        return abs(err[2]) < 0.003 and np.linalg.norm(err[:2]) < 0.0025

    def on_substep(self, f, k):
        r, d = self.r, self.r.d
        m = r.m
        t = f + (k + 1) / r.n_sub
        for c in d.contact[:d.ncon]:
            for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)):
                pb = r.piece_of_geom.get(b)
                if pb is None:
                    continue
                if a in r.arm_geoms:
                    part = "finger" if m.geom_bodyid[a] in self.hand else m.body(m.geom_bodyid[a]).name
                    if pb == self.target:
                        if self.closing:
                            self._event("arm_target_closing", t, part)
                        elif part == "finger" and self._at_grasp():
                            self._event("finger_touch_at_grasp", t, part)     # the intended contact (fixed finger 0.8 mm off)
                        else:
                            self._event("arm_target_open", t, part)
                    elif pb in self.others:
                        self._event("arm_neighbour", t, f"{part}->{pb}")
                elif r.piece_of_geom.get(a) == self.target and pb in self.others:
                    self._event("target_neighbour", t, pb)
        tilt = r.w.tilt_deg(d, self.target)
        if tilt > 5:
            self._event("tilt5", t)
        if tilt > 45:
            self._event("tilt45", t)

    def on_frame(self, f, a):
        import numpy as np

        r, d, w, ex, plan = self.r, self.r.d, self.r.w, self.r.expert, self.plan
        a = np.asarray(a, float)
        q = d.qpos[ex.kin.qadr].copy()
        pinch, R = ex.kin.pose(q, plan.offset)
        grasp_now_ = w.base_pos(d, self.target) + self.grasp_rel
        # Closing begins where the command starts its ramp down near the piece (within 20 mm
        # above the grasp point): 1 unit below its maximum of the last half second. The
        # approach also lowers the command (rest ~10 to open ~6), but higher up.
        self.cmd_hist.append(a[5])
        self.open_max = max(self.open_max, a[5])
        if (not self.closing and self.open_max > OPEN and pinch[2] - grasp_now_[2] < 0.020
                and a[5] < max(self.cmd_hist[-15:]) - 1.0):
            self.closing = True
            self._event("close_start", float(f))
        if a[5] < CLOSING:
            self._event("close_cmd3", float(f))              # eval_policy's close marker
        pinch_cmd, _ = ex.kin.pose(np.radians(a[:5]), plan.offset)
        lo, hi = r.grip_range
        gq = float(d.qpos[r.grip_qadr])
        gq_cmd = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo)
        base = w.base_pos(d, self.target)
        grasp_now = base + self.grasp_rel
        err = pinch - grasp_now
        xj = np.r_[R[:2, 0], 0.0]
        xj /= max(np.linalg.norm(xj), 1e-9)
        yj = np.array([-xj[1], xj[0], 0.0])
        yaw = float(np.arctan2(R[1, 0], R[0, 0]))
        dyaw = np.degrees(yaw - plan.yaw)
        self.rows.append(dict(
            f=f, cmd=a.copy(), act=r.to_lerobot(d.qpos[r.qadr]).astype(float), pinch=pinch.copy(),
            track_mm=1000 * float(np.linalg.norm(pinch_cmd - pinch)),
            lat_mm=1000 * float(np.linalg.norm(err[:2])), along_mm=1000 * float(err @ xj),
            across_mm=1000 * float(err @ yj), height_mm=1000 * float(err[2]),
            yaw=yaw, yaw_err180=float((dyaw + 90) % 180 - 90), yaw_err360=float((dyaw + 180) % 360 - 180),
            lean_deg=float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))),
            gap_mm=float(np.interp(gq, self.qs, self.gaps)), gap_cmd_mm=float(np.interp(gq_cmd, self.qs, self.gaps)),
            piece=base.copy(), piece_moved_mm=1000 * float(np.linalg.norm(base[:2] - self.base0[:2])),
            tilt=float(w.tilt_deg(d, self.target)),
            new_chunk=len(self.policy._queues["action"]) == self.n_steps - 1,
            closing=self.closing))
        if self.capture:
            self.side_renderer.update_scene(d, camera=self.cam, scene_option=r.scene_option)
            buf = io.BytesIO()
            from PIL import Image

            Image.fromarray(self.side_renderer.render()).save(buf, "JPEG", quality=85)
            self.side.append(buf.getvalue())
        return False

    def arrays(self):
        import numpy as np

        keys = self.rows[0].keys()
        return {k: np.array([row[k] for row in self.rows]) for k in keys}


def classify(A: dict, events: dict, parts: dict, fps: int = 30) -> dict:
    """What happened first, and the signals around it.

    The onset is the earliest of: the arm touching the marked piece before the jaws began
    closing, the arm touching another piece, the marked piece touching another piece, or
    the marked piece tilting past 5 deg, all before closing began. If none happened, it is
    the start of closing. Signals in the half second up to the onset:
    - rotating: the jaw turned faster than 45 deg/s while the pinch point was within 30 mm
      of the grasp point;
    - sideways: at the onset the pinch point moved sideways more than twice as fast as
      vertically, and faster than 10 mm/s;
    - lag: the pinch point of the commanded joints was more than 3 mm from the actual one;
    - offset: when closing began, the pinch point was more than 2 mm (sideways) from the
      grasp point on the piece where it stands.
    """
    import numpy as np

    close = events.get("close_start")
    pre = [(events[k], k) for k in ("arm_target_open", "arm_neighbour", "target_neighbour", "tilt5")
           if k in events and (close is None or events[k] < close)]
    if pre:
        t0, first = min(pre)
        stage = "before closing"
    elif close is not None:
        t0, first, stage = close, "close_start", "at closing"
    else:
        return dict(onset="never closed, nothing touched", first=None, t0=None, flags={})
    n = len(A["f"])
    f0 = min(int(t0), n - 1)
    lo = max(0, f0 - fps // 2)
    yaw = np.unwrap(A["yaw"])
    rate = np.abs(np.diff(yaw, prepend=yaw[0])) * fps
    dist = np.hypot(A["lat_mm"], A["height_mm"])
    near = dist[lo:f0 + 1] < 30
    rotating = bool(np.any(np.degrees(rate[lo:f0 + 1])[near] > 45)) if near.any() else False
    v = np.diff(A["pinch"], axis=0, prepend=A["pinch"][:1]) * fps
    k0 = max(1, f0 - 2)
    h_speed = float(np.mean(np.linalg.norm(v[k0:f0 + 1, :2], axis=1)))
    v_speed = float(np.mean(np.abs(v[k0:f0 + 1, 2])))
    sideways = h_speed > 2 * v_speed and h_speed > 0.010
    lag = bool(A["track_mm"][f0] > 3.0)
    fc = min(int(close), n - 1) if close is not None else None
    lat_close = float(A["lat_mm"][fc]) if fc is not None else None
    offset = lat_close is not None and lat_close > 2.0
    if stage == "before closing":
        if rotating:
            onset = "wrist rotates near the piece"
        elif sideways:
            onset = "hand approaches sideways"
        else:
            onset = "descends onto the piece off-centre"
    else:
        onset = "jaws close around an offset piece" if offset else "closed centred; failed later"
    chunks = np.flatnonzero(A["new_chunk"])
    near_chunk = bool(np.any(np.abs(chunks - f0) <= 5)) if len(chunks) else False
    return dict(onset=onset, first=first, first_part=parts.get(first), t0_s=round(t0 / fps, 2), stage=stage,
                flags=dict(rotating=rotating, sideways=sideways, lag=lag, offset=offset),
                h_speed_mm_s=round(1000 * h_speed, 1), v_speed_mm_s=round(1000 * v_speed, 1),
                track_mm_at_onset=round(float(A["track_mm"][f0]), 2),
                lat_mm_at_onset=round(float(A["lat_mm"][f0]), 2), height_mm_at_onset=round(float(A["height_mm"][f0]), 1),
                yaw_err180_at_onset=round(float(A["yaw_err180"][f0]), 1),
                gap_mm_at_onset=round(float(A["gap_mm"][f0]), 1), lat_mm_at_close=None if lat_close is None else round(lat_close, 2),
                chunk_within_5_frames=near_chunk)


def write_replay(path, policy_frames, side_frames, A, events, info, f0, fps=30, slow=4, before=60, after=60):
    """Slow replay around frame f0: the images the policy saw (overhead, wrist), a close-up
    side view, and the measurements of each frame."""
    import av
    import numpy as np
    from PIL import Image, ImageDraw

    n = min(len(side_frames), len(A["f"]), len(policy_frames))
    lo, hi = max(0, f0 - before), min(n, f0 + after)
    ev_frames = {k: int(v) for k, v in events.items()}
    with av.open(str(path), "w") as container:
        stream = container.add_stream("libx264", rate=fps)
        stream.width, stream.height, stream.pix_fmt = 960, 360, "yuv420p"
        stream.options = {"crf": "23"}
        for f in range(lo, hi):
            top = np.asarray(Image.open(io.BytesIO(policy_frames[f])).convert("RGB"))    # 240 x 640 (overhead | wrist)
            side = np.asarray(Image.open(io.BytesIO(side_frames[f])).convert("RGB"))     # 240 x 320
            canvas = Image.new("RGB", (960, 360), (18, 18, 18))
            canvas.paste(Image.fromarray(top), (0, 0))
            canvas.paste(Image.fromarray(side), (640, 0))
            pen = ImageDraw.Draw(canvas)
            lines = [f"{info}   t={f / fps:5.2f}s  frame {f}{'   NEW CHUNK' if A['new_chunk'][f] else ''}",
                     f"pinch vs piece: sideways {A['lat_mm'][f]:5.1f} mm (along {A['along_mm'][f]:+5.1f}, across {A['across_mm'][f]:+5.1f}),"
                     f" height {A['height_mm'][f]:+6.1f} mm   jaw yaw err {A['yaw_err360'][f]:+6.1f} deg   lean {A['lean_deg'][f]:4.1f} deg",
                     f"gap {A['gap_mm'][f]:5.1f} mm (commanded {A['gap_cmd_mm'][f]:5.1f})   command-vs-actual {A['track_mm'][f]:4.1f} mm"
                     f"   piece moved {A['piece_moved_mm'][f]:5.1f} mm, tilt {A['tilt'][f]:5.1f} deg",
                     "events: " + ", ".join(f"{k} @{v / fps:.2f}s" for k, v in sorted(events.items(), key=lambda x: x[1])
                                           if ev_frames[k] <= f) or "events: none yet"]
            for j, line in enumerate(lines):
                pen.text((8, 248 + 26 * j), line, fill=(255, 235, 120) if j == 3 else (230, 230, 230))
            if any(ev_frames[k] == f for k in events):
                pen.rectangle([0, 0, 959, 239], outline=(255, 60, 60), width=4)
            frame = av.VideoFrame.from_ndarray(np.asarray(canvas), format="rgb24")
            for _ in range(slow):
                for packet in stream.encode(frame):
                    container.mux(packet)
        for packet in stream.encode():
            container.mux(packet)


# ---------------------------------------------------------------------------- workers
def run_one(runner, cfg, bundle, seed, i, seconds, capture=False, hashes=False):
    import numpy as np
    import torch

    from eval_policy import drive

    policy, pre, post, device = bundle
    task, ep_seed, torch_seed, plan = episode(runner, seed, i)
    tr = Tracer(runner, task, plan, policy, capture=capture)
    frames = HashFrames() if hashes else (JpegFrames() if capture else None)
    torch.manual_seed(torch_seed)
    res, met = drive(runner, task, policy, pre, post, device, cfg, seconds, ep_seed ^ 0x5EED, frames,
                     on_frame=tr.on_frame, on_substep=tr.on_substep)
    tr.close()
    A = tr.arrays()
    head = dict(index=i, ep_seed=ep_seed, torch_seed=torch_seed, move=f"{task.source}-{task.dest.square}",
                piece=runner.w.kind[task.target], plan_yaw_deg=round(float(np.degrees(plan.yaw)), 1),
                plan_grasp_mm=[round(1000 * float(x), 3) for x in plan.grasp_point], success=bool(res.success),
                reason=res.reason, frames=res.frames, lifted=bool(met["lifted"]))
    return head, A, tr, frames


def repeat_worker(condition, reps, args, indices, queue):
    if condition == "deterministic":
        set_deterministic()
    import warnings

    warnings.filterwarnings("ignore")
    import numpy as np
    import torch

    from episode import EpisodeRunner, load_config
    from eval_policy import load_policy
    from piece_sets import sample_piece_set

    torch.set_num_threads(2)
    cfg = load_config()
    bundle = load_policy(args.policy)
    out = Path(args.out) / "runs"
    out.mkdir(parents=True, exist_ok=True)
    for rep in reps:
        for i in indices:
            runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([args.seed, 10**9 + i // 5]), cfg, "rep"),
                                   render=True)
            head, A, tr, hashes = run_one(runner, cfg, bundle, args.seed, i, args.seconds, hashes=True)
            runner.close()
            np.savez_compressed(out / f"{condition}_rep{rep}_ep{i:03d}.npz", cmd=A["cmd"], act=A["act"],
                                hashes=np.array(list(hashes)))
            queue.put(dict(condition=condition, rep=rep, pid=os.getpid(), **head, events=tr.events))
    queue.put(None)


def trace_worker(k, n, args, queue):
    import warnings

    warnings.filterwarnings("ignore")
    import numpy as np
    import torch

    from episode import EpisodeRunner, load_config
    from eval_policy import load_policy
    from piece_sets import sample_piece_set

    torch.set_num_threads(2)
    cfg = load_config()
    bundle = load_policy(args.policy)
    out = Path(args.out)
    (out / "traces").mkdir(parents=True, exist_ok=True)
    (out / "replays").mkdir(parents=True, exist_ok=True)
    runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([args.seed, 10**9]), cfg, "trace"), render=True)
    for i in range(k * args.episodes // n, (k + 1) * args.episodes // n):
        head, A, tr, frames = run_one(runner, cfg, bundle, args.seed, i, args.seconds, capture=args.replays)
        c = classify(A, tr.events, tr.parts)
        np.savez_compressed(out / "traces" / f"ep{i:03d}.npz", **A)
        replay = None
        if args.replays and not head["success"] and head["piece"] == "pawn" and c.get("t0_s") is not None:
            replay = f"replays/ep{i:03d}_{head['move']}_{c['onset'].split()[0]}.mp4"
            write_replay(out / replay, frames, tr.side, A, tr.events,
                         f"ep {i} {head['piece']} {head['move']} ({c['onset']})", int(c["t0_s"] * 30))
        queue.put(dict(**head, events={k2: round(v / 30, 3) for k2, v in tr.events.items()}, parts=tr.parts,
                       classification=c, replay=replay))
    runner.close()
    queue.put(None)


def collect(procs, queue, label):
    results, finished = [], 0
    while finished < len(procs):
        try:
            r = queue.get(timeout=120)
        except Empty:
            if not any(p.is_alive() for p in procs):
                print(f"{label}: worker(s) crashed", flush=True)
                break
            continue
        if r is None:
            finished += 1
            continue
        results.append(r)
        print(f"{label}: {r.get('condition', '')} {r.get('rep', '')} ep {r['index']} {r['move']} "
              f"{'ok' if r['success'] else 'fail'} {r.get('classification', {}).get('onset', '')}", flush=True)
    for p in procs:
        p.join()
    return results


# ---------------------------------------------------------------------------- reports
def repeat_report(args, results):
    import numpy as np

    runs = Path(args.out) / "runs"
    load = lambda c, rep, i: np.load(runs / f"{c}_rep{rep}_ep{i:03d}.npz")
    by = defaultdict(dict)
    for r in results:
        by[(r["condition"], r["index"])][r["rep"]] = r
    rows = []
    for (cond, i), reps in sorted(by.items()):
        ref = load(cond, min(reps), i)
        for rep, r in sorted(reps.items()):
            x = load(cond, rep, i)
            n = min(len(x["cmd"]), len(ref["cmd"]))
            dcmd = np.abs(x["cmd"][:n] - ref["cmd"][:n]).max(axis=1)
            hn = min(len(x["hashes"]), len(ref["hashes"]))
            hdiff = np.flatnonzero(x["hashes"][:hn] != ref["hashes"][:hn])
            cdiff = np.flatnonzero(dcmd > 1e-4)
            rows.append(dict(condition=cond, index=i, rep=rep, move=r["move"], success=r["success"],
                             same_episode=(r["ep_seed"], r["torch_seed"], r["plan_grasp_mm"]) ==
                                          (reps[min(reps)]["ep_seed"], reps[min(reps)]["torch_seed"], reps[min(reps)]["plan_grasp_mm"]),
                             first_input_diff=int(hdiff[0]) if len(hdiff) else None,
                             first_action_diff=int(cdiff[0]) if len(cdiff) else None,
                             action_diff_at_first=float(dcmd[cdiff[0]]) if len(cdiff) else 0.0,
                             max_action_diff=float(dcmd.max()) if n else 0.0))
    # Across conditions: each repeat against same_process repeat 0.
    cross = []
    for (cond, i), reps in sorted(by.items()):
        if cond == "same_process" or ("same_process", i) not in by:
            continue
        ref = load("same_process", 0, i)
        for rep in sorted(reps):
            x = load(cond, rep, i)
            n = min(len(x["cmd"]), len(ref["cmd"]))
            cd = np.flatnonzero(np.abs(x["cmd"][:n] - ref["cmd"][:n]).max(axis=1) > 1e-4)
            hn = min(len(x["hashes"]), len(ref["hashes"]))
            hd = np.flatnonzero(x["hashes"][:hn] != ref["hashes"][:hn])
            cross.append(dict(condition=cond, index=i, rep=rep, first_input_diff=int(hd[0]) if len(hd) else None,
                              first_action_diff=int(cd[0]) if len(cd) else None))
    (Path(args.out) / "repeat_results.json").write_text(json.dumps(dict(results=results, rows=rows, cross=cross), indent=1, default=str))
    lines = ["# Repeatability", "",
             f"Policy `{args.policy}`, episodes {args.indices} of seed {args.seed}, {args.repeats} repeats per condition. "
             "Each run builds a fresh simulator and pins the episode seed, move, expert plan and the policy's sampling "
             "seed as eval_policy does. `first input diff`: first frame whose policy images differ from repeat 0 "
             "(md5 of the downsampled images); `first action diff`: first frame whose commanded joints differ by more "
             "than 1e-4 (degrees or gripper units).", "",
             "| condition | episode | move | outcomes (repeat 0..n) | identical episode setup | first input diff (frames) | first action diff (frames) | max action diff |",
             "|---|---|---|---|---|---|---|---|"]
    grouped = defaultdict(list)
    for row in rows:
        grouped[(row["condition"], row["index"])].append(row)
    for (cond, i), rs in grouped.items():
        rs = sorted(rs, key=lambda x: x["rep"])
        lines.append(f"| {cond} | {i} | {rs[0]['move']} | {''.join('S' if x['success'] else 'F' for x in rs)} | "
                     f"{all(x['same_episode'] for x in rs)} | {[x['first_input_diff'] for x in rs[1:]]} | "
                     f"{[x['first_action_diff'] for x in rs[1:]]} | {max(x['max_action_diff'] for x in rs):.3g} |")
    if cross:
        lines += ["", "## Against `same_process` repeat 0", "",
                  "| condition | episode | repeat | first input diff | first action diff |", "|---|---|---|---|---|"]
        lines += [f"| {c['condition']} | {c['index']} | {c['rep']} | {c['first_input_diff']} | {c['first_action_diff']} |" for c in cross]
    (Path(args.out) / "repeat_report.md").write_text("\n".join(lines) + "\n")
    print("\n".join(lines))


def trace_report(args, results):
    import numpy as np

    out = Path(args.out)
    results.sort(key=lambda r: r["index"])
    (out / "trace_results.json").write_text(json.dumps(results, indent=1, default=str))
    fails = [r for r in results if not r["success"]]
    oks = [r for r in results if r["success"]]
    lines = ["# Grasp traces", "",
             f"Policy `{args.policy}`, {len(results)} episodes of seed {args.seed} (not the development or final sets). "
             f"{len(oks)} succeeded, {len(fails)} failed.", "",
             "Onset = what happened first (see `classify` in `sim/grasp_trace.py`): the arm touching the marked piece "
             "before the jaws began closing, touching another piece, the marked piece touching another piece, or tilting "
             "past 5 deg, before closing began; otherwise the start of closing. Contacts are checked every physics step.", "",
             "## Failures by onset", "", "| onset | pawn | knight | total |", "|---|---|---|---|"]
    onsets = Counter((r["classification"]["onset"], r["piece"]) for r in fails)
    for o in sorted({k[0] for k in onsets}):
        lines.append(f"| {o} | {onsets[(o, 'pawn')]} | {onsets[(o, 'knight')]} | {onsets[(o, 'pawn')] + onsets[(o, 'knight')]} |")
    firsts = Counter((r["classification"].get("first"), r["classification"].get("first_part")) for r in fails)
    lines += ["", "First event of each failure (event, part that touched):", ""]
    lines += [f"- {k[0]} ({k[1]}): {v}" for k, v in firsts.most_common()]
    flag = lambda rs, k: sum(r["classification"].get("flags", {}).get(k, False) for r in rs)
    lines += ["", "## Signals", "", "| signal | failures | successes |", "|---|---|---|"]
    for k, label in (("rotating", "jaw turning > 45 deg/s within 30 mm of the grasp point, up to the onset"),
                     ("sideways", "pinch point moving mostly sideways at the onset"),
                     ("lag", "commanded vs actual pinch point > 3 mm at the onset"),
                     ("offset", "> 2 mm sideways from the piece when closing began")):
        lines.append(f"| {label} | {flag(fails, k)}/{len(fails)} | {flag(oks, k)}/{len(oks)} |")
    med = lambda rs, key: round(float(np.median([r["classification"][key] for r in rs
                                                  if r["classification"].get(key) is not None])), 2) if rs else None
    lines += ["", "| measure | failures (median) | successes (median) |", "|---|---|---|"]
    for key, label in (("lat_mm_at_close", "sideways error when closing began (mm)"),
                       ("track_mm_at_onset", "command vs actual at the onset (mm)"),
                       ("lat_mm_at_onset", "sideways error at the onset (mm)"),
                       ("height_mm_at_onset", "height above the grasp point at the onset (mm)"),
                       ("yaw_err180_at_onset", "jaw yaw vs the expert's, mod 180, at the onset (deg)"),
                       ("gap_mm_at_onset", "fingertip gap at the onset (mm)"),
                       ("h_speed_mm_s", "sideways speed at the onset (mm/s)"),
                       ("v_speed_mm_s", "vertical speed at the onset (mm/s)")):
        lines.append(f"| {label} | {med(fails, key)} | {med(oks, key)} |")
    near = sum(r["classification"].get("chunk_within_5_frames", False) for r in fails)
    lines += ["", f"A new action chunk started within 5 frames of the onset in {near}/{len(fails)} failures "
              "(by chance about 11/50 = 22% with 50-step chunks).", "",
              "## Episodes", "", "| # | move | result | onset | first event | at (s) | sideways at close (mm) | replay |",
              "|---|---|---|---|---|---|---|---|"]
    for r in results:
        c = r["classification"]
        lines.append(f"| {r['index']} | {r['piece']} {r['move']} | {'ok' if r['success'] else 'fail'} | {c['onset']} | "
                     f"{c.get('first')} ({c.get('first_part')}) | {c.get('t0_s')} | {c.get('lat_mm_at_close')} | "
                     f"{r['replay'] or ''} |")
    (out / "trace_report.md").write_text("\n".join(lines) + "\n")
    print("\n".join(lines))


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("mode", choices=["repeat", "trace"])
    ap.add_argument("--policy", required=True)
    ap.add_argument("--seed", type=int, default=8_000_003)
    ap.add_argument("--seconds", type=float, default=20.0)
    ap.add_argument("--out", required=True)
    ap.add_argument("--indices", default="", help="repeat: episode indices of --seed")
    ap.add_argument("--repeats", type=int, default=5, help="repeat: processes for separate and deterministic")
    ap.add_argument("--same-repeats", type=int, default=3, help="repeat: back-to-back repeats in one process")
    ap.add_argument("--conditions", default="same_process,separate,deterministic")
    ap.add_argument("--episodes", type=int, default=40)
    ap.add_argument("--workers", type=int, default=6)
    ap.add_argument("--replays", action="store_true")
    args = ap.parse_args()
    Path(args.out).mkdir(parents=True, exist_ok=True)
    ctx = mp.get_context("spawn")
    t0 = time.time()
    if args.mode == "repeat":
        indices = [int(x) for x in args.indices.split(",")]
        conds = args.conditions.split(",")
        results = []
        # same_process runs alongside separate; deterministic after (GPU memory: 1 + repeats processes at a time).
        batches = [[c for c in conds if c in ("same_process", "separate")], [c for c in conds if c == "deterministic"]]
        for batch in batches:
            if not batch:
                continue
            queue = ctx.Queue()
            procs = []
            for cond in batch:
                if cond == "same_process":
                    procs.append(ctx.Process(target=repeat_worker, args=(cond, list(range(args.same_repeats)), args, indices, queue)))
                else:
                    procs += [ctx.Process(target=repeat_worker, args=(cond, [rep], args, indices, queue))
                              for rep in range(args.repeats)]
            for p in procs:
                p.start()
            results += collect(procs, queue, "repeat")
        repeat_report(args, results)
    else:
        queue = ctx.Queue()
        procs = [ctx.Process(target=trace_worker, args=(k, args.workers, args, queue)) for k in range(args.workers)]
        for p in procs:
            p.start()
        trace_report(args, collect(procs, queue, "trace"))
    print(f"done in {(time.time() - t0) / 60:.1f} min")


if __name__ == "__main__":
    main()