Ali-Uraish commited on
Commit
ffefb64
·
verified ·
1 Parent(s): 624ade3

code: grasp_trace, drive substep hook, SIM_OFFSAMPLES switch

Browse files
chess-sim/code/sim/episode.py CHANGED
@@ -93,6 +93,11 @@ class EpisodeRunner:
93
  self.renderers = None
94
  if render:
95
  ds = cfg["dataset"]
 
 
 
 
 
96
  self.renderers = {c: mujoco.Renderer(self.m, ds["image_height"], ds["image_width"]) for c in ds["cameras"]}
97
  self.scene_option = mujoco.MjvOption()
98
  self.scene_option.geomgroup[3] = 0 # contact hulls never appear in policy images
 
93
  self.renderers = None
94
  if render:
95
  ds = cfg["dataset"]
96
+ # SIM_OFFSAMPLES=0 turns the offscreen anti-aliasing off: with it on (4 samples, as the
97
+ # data was rendered) the GPU shades a few wrist-camera edge pixels differently from run
98
+ # to run, which is enough to change closed-loop outcomes (sim/reports/grasp_trace).
99
+ if os.environ.get("SIM_OFFSAMPLES") is not None:
100
+ self.m.vis.quality.offsamples = int(os.environ["SIM_OFFSAMPLES"])
101
  self.renderers = {c: mujoco.Renderer(self.m, ds["image_height"], ds["image_width"]) for c in ds["cameras"]}
102
  self.scene_option = mujoco.MjvOption()
103
  self.scene_option.geomgroup[3] = 0 # contact hulls never appear in policy images
chess-sim/code/sim/eval_policy.py CHANGED
@@ -94,11 +94,12 @@ def rebuild_check(info: dict, task, rec: dict) -> list[str]:
94
 
95
 
96
  def drive(runner, task, policy, pre, post, device, cfg, seconds, rec_rng_seed, video=None, stop_when_done=True,
97
- recorder=None, on_frame=None):
98
  """Let the policy drive from the set-up state. Returns (Result, metrics).
99
 
100
  `recorder`: an already begun Recorder to render through (its dataset is not written).
101
- `on_frame(f, action)`: called after every step; returning True stops the drive there."""
 
102
  import mujoco
103
  import numpy as np
104
  from lerobot.utils.control_utils import predict_action
@@ -134,8 +135,10 @@ def drive(runner, task, policy, pre, post, device, cfg, seconds, rec_rng_seed, v
134
  a = a.squeeze().float().cpu().numpy()
135
  d.ctrl[:5] = np.radians(a[:5])
136
  d.ctrl[5] = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo)
137
- for _ in range(runner.n_sub):
138
  mujoco.mj_step(runner.m, d)
 
 
139
  frames += 1
140
  g = d.site_xpos[site].copy()
141
  path.append(g)
 
94
 
95
 
96
  def drive(runner, task, policy, pre, post, device, cfg, seconds, rec_rng_seed, video=None, stop_when_done=True,
97
+ recorder=None, on_frame=None, on_substep=None):
98
  """Let the policy drive from the set-up state. Returns (Result, metrics).
99
 
100
  `recorder`: an already begun Recorder to render through (its dataset is not written).
101
+ `on_frame(f, action)`: called after every step; returning True stops the drive there.
102
+ `on_substep(f, k)`: called after every physics substep k of frame f."""
103
  import mujoco
104
  import numpy as np
105
  from lerobot.utils.control_utils import predict_action
 
135
  a = a.squeeze().float().cpu().numpy()
136
  d.ctrl[:5] = np.radians(a[:5])
137
  d.ctrl[5] = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo)
138
+ for k in range(runner.n_sub):
139
  mujoco.mj_step(runner.m, d)
140
+ if on_substep is not None:
141
+ on_substep(f, k)
142
  frames += 1
143
  g = d.site_xpos[site].copy()
144
  path.append(g)
chess-sim/code/sim/grasp_trace.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grasp traces and repeatability of a policy in the settings profile's scene.
2
+
3
+ repeat Runs a few identical episodes several times under three conditions and reports
4
+ whether, where and why repeats diverge:
5
+ same_process one process, the episodes repeated back to back
6
+ separate one process per repeat, running in parallel (as eval_policy does)
7
+ deterministic like separate, with torch deterministic algorithms, TF32 off and
8
+ a fixed cuBLAS workspace
9
+ Each run builds a fresh simulator and pins the episode (seed, move, the expert's
10
+ plan), the policy's sampling seed and the simulator reset exactly as eval_policy
11
+ does. Per frame it keeps a hash of the images the policy saw and the commanded and
12
+ actual joints, so the first divergence can be attributed to the inputs (simulation,
13
+ rendering) or to the policy (same inputs, different outputs).
14
+
15
+ trace Runs episodes and records every frame: commanded and actual joints; the jaw's
16
+ pinch point relative to where the marked piece stands now, along and across the
17
+ jaw's actual closing direction; the jaw yaw against the expert's; the gripper's
18
+ lean; the physical fingertip gap (mm, from the jaw geometry) commanded and actual;
19
+ the piece's pose and tilt; action-chunk boundaries. Every physics substep: the first
20
+ contact of the arm with the marked piece (before or after closing began), of the arm
21
+ with another piece, and of the marked piece with another piece; the first tilt past
22
+ 5 and 45 degrees. A fingertip touch at the grasp (within 3 mm of the grasp height
23
+ and 2.5 mm sideways) before closing is the intended contact, recorded separately.
24
+ Closing begins where the gripper command starts its ramp down within 20 mm above
25
+ the grasp point. Failures are classified by what happened first (see classify),
26
+ and slow (4x) replays of pawn failures are written with the measurements overlaid.
27
+
28
+ Run: MUJOCO_GL=egl PHASE2_PROFILE=baseline .venv/bin/python sim/grasp_trace.py repeat \
29
+ --policy models/baseline --indices 3,7,12 --repeats 5 --out sim/reports/grasp_trace/repeat
30
+ MUJOCO_GL=egl PHASE2_PROFILE=baseline .venv/bin/python sim/grasp_trace.py trace \
31
+ --policy models/baseline --episodes 40 --workers 6 --seed 8000003 --out sim/reports/grasp_trace/trace
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import hashlib
37
+ import io
38
+ import json
39
+ import multiprocessing as mp
40
+ import os
41
+ import sys
42
+ import time
43
+ from collections import Counter, defaultdict
44
+ from pathlib import Path
45
+ from queue import Empty
46
+
47
+ HERE = Path(__file__).resolve().parent
48
+ sys.path.insert(0, str(HERE))
49
+ OPEN, CLOSING = 4.0, 3.0 # gripper command, LeRobot 0-100 units (see eval_policy)
50
+
51
+
52
+ # ---------------------------------------------------------------------------- setup
53
+ def set_deterministic():
54
+ """Deterministic torch/CUDA settings; call before torch touches CUDA."""
55
+ os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
56
+ import torch
57
+
58
+ torch.use_deterministic_algorithms(True, warn_only=True)
59
+ torch.backends.cudnn.deterministic = True
60
+ torch.backends.cudnn.benchmark = False
61
+ torch.backends.cuda.matmul.allow_tf32 = False
62
+ torch.backends.cudnn.allow_tf32 = False
63
+
64
+
65
+ def episode(runner, seed: int, i: int):
66
+ """Episode i of `seed` exactly as eval_policy sets it up: the move (checked doable by
67
+ the expert), the expert's own grasp plan, and the policy's sampling seed."""
68
+ import mujoco
69
+ import numpy as np
70
+
71
+ erng = np.random.default_rng([seed, i])
72
+ for _ in range(20):
73
+ ep_seed = int(erng.integers(2**62))
74
+ task = runner.setup(np.random.default_rng(ep_seed))
75
+ if runner.run(task, ep_seed).success:
76
+ break
77
+ task = runner.setup(np.random.default_rng(ep_seed))
78
+ d = runner.d
79
+ saved = (d.qpos.copy(), d.qvel.copy(), d.act.copy(), d.ctrl.copy(), d.time)
80
+ plan = runner.expert.plan_pick(d, task.target, np.random.default_rng(ep_seed))
81
+ d.qpos[:], d.qvel[:], d.act[:], d.ctrl[:] = saved[:4]
82
+ d.time = saved[4]
83
+ mujoco.mj_forward(runner.m, d)
84
+ return task, ep_seed, int(erng.integers(2**31)), plan
85
+
86
+
87
+ def gap_table(expert, heights_mm=(2.0, 10.0)):
88
+ """Gripper angle -> physical gap (mm) between the fixed and moving fingertips, averaged
89
+ over heights_mm above the fingertip (from the expert's jaw geometry)."""
90
+ import numpy as np
91
+
92
+ jaws = expert.jaws
93
+ rel = np.linspace(heights_mm[0], heights_mm[1], 5) / 1000
94
+ fixed = np.interp(rel, jaws.heights, jaws.fixed_inner)
95
+ qs = np.linspace(-0.3, 1.3, 161)
96
+ gaps = []
97
+ for q in qs:
98
+ inner, _ = jaws.moving_profile(q, rel)
99
+ gaps.append(float(np.nanmean(inner - fixed)) * 1000 if np.any(~np.isnan(inner)) else np.nan)
100
+ return qs, np.array(gaps)
101
+
102
+
103
+ class JpegFrames(list):
104
+ """Frames kept as JPEG bytes (drive() appends the images the policy saw)."""
105
+
106
+ def append(self, img):
107
+ from PIL import Image
108
+
109
+ buf = io.BytesIO()
110
+ Image.fromarray(img).save(buf, "JPEG", quality=85)
111
+ super().append(buf.getvalue())
112
+
113
+
114
+ class HashFrames(list):
115
+ """Frames kept as an md5 of their bytes (for repeatability)."""
116
+
117
+ def append(self, img):
118
+ import numpy as np
119
+
120
+ super().append(hashlib.md5(np.ascontiguousarray(img).tobytes()).hexdigest())
121
+
122
+
123
+ # ---------------------------------------------------------------------------- tracing
124
+ class Tracer:
125
+ def __init__(self, runner, task, plan, policy, capture=False):
126
+ import mujoco
127
+ import numpy as np
128
+
129
+ self.r, self.task, self.plan, self.policy = runner, task, plan, policy
130
+ m, d, w, ex = runner.m, runner.d, runner.w, runner.expert
131
+ self.target = task.target
132
+ self.others = set(task.squares.values()) - {task.target}
133
+ self.base0 = w.base_pos(d, task.target).copy()
134
+ self.grasp_rel = plan.grasp_point - self.base0
135
+ self.hand = {m.body("gripper").id, m.body("moving_jaw_so101_v1").id}
136
+ self.qs, self.gaps = gap_table(ex)
137
+ self.n_steps = policy.config.n_action_steps
138
+ self.rows, self.events, self.parts = [], {}, {}
139
+ self.open_max, self.closing = 0.0, False
140
+ self.cmd_hist = []
141
+ self.capture = capture
142
+ self.side = []
143
+ if capture:
144
+ self.cam = mujoco.MjvCamera()
145
+ self.cam.type = mujoco.mjtCamera.mjCAMERA_FREE
146
+ self.cam.lookat[:] = plan.grasp_point
147
+ self.cam.distance = 0.16
148
+ self.cam.azimuth = float(np.degrees(plan.yaw)) + 90.0 # looking across the closing direction
149
+ self.cam.elevation = -12.0
150
+ self.side_renderer = mujoco.Renderer(m, 240, 320)
151
+
152
+ def close(self):
153
+ if self.capture:
154
+ self.side_renderer.close()
155
+
156
+ def _event(self, key, t, part=None):
157
+ if key not in self.events:
158
+ self.events[key] = t
159
+ if part is not None:
160
+ self.parts[key] = part
161
+
162
+ def _at_grasp(self):
163
+ """Pinch point within 3 mm of the grasp height and 2.5 mm sideways of the piece."""
164
+ import numpy as np
165
+
166
+ r, d, ex = self.r, self.r.d, self.r.expert
167
+ pinch, _ = ex.kin.pose(d.qpos[ex.kin.qadr].copy(), self.plan.offset)
168
+ err = pinch - (r.w.base_pos(d, self.target) + self.grasp_rel)
169
+ return abs(err[2]) < 0.003 and np.linalg.norm(err[:2]) < 0.0025
170
+
171
+ def on_substep(self, f, k):
172
+ r, d = self.r, self.r.d
173
+ m = r.m
174
+ t = f + (k + 1) / r.n_sub
175
+ for c in d.contact[:d.ncon]:
176
+ for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)):
177
+ pb = r.piece_of_geom.get(b)
178
+ if pb is None:
179
+ continue
180
+ if a in r.arm_geoms:
181
+ part = "finger" if m.geom_bodyid[a] in self.hand else m.body(m.geom_bodyid[a]).name
182
+ if pb == self.target:
183
+ if self.closing:
184
+ self._event("arm_target_closing", t, part)
185
+ elif part == "finger" and self._at_grasp():
186
+ self._event("finger_touch_at_grasp", t, part) # the intended contact (fixed finger 0.8 mm off)
187
+ else:
188
+ self._event("arm_target_open", t, part)
189
+ elif pb in self.others:
190
+ self._event("arm_neighbour", t, f"{part}->{pb}")
191
+ elif r.piece_of_geom.get(a) == self.target and pb in self.others:
192
+ self._event("target_neighbour", t, pb)
193
+ tilt = r.w.tilt_deg(d, self.target)
194
+ if tilt > 5:
195
+ self._event("tilt5", t)
196
+ if tilt > 45:
197
+ self._event("tilt45", t)
198
+
199
+ def on_frame(self, f, a):
200
+ import numpy as np
201
+
202
+ r, d, w, ex, plan = self.r, self.r.d, self.r.w, self.r.expert, self.plan
203
+ a = np.asarray(a, float)
204
+ q = d.qpos[ex.kin.qadr].copy()
205
+ pinch, R = ex.kin.pose(q, plan.offset)
206
+ grasp_now_ = w.base_pos(d, self.target) + self.grasp_rel
207
+ # Closing begins where the command starts its ramp down near the piece (within 20 mm
208
+ # above the grasp point): 1 unit below its maximum of the last half second. The
209
+ # approach also lowers the command (rest ~10 to open ~6), but higher up.
210
+ self.cmd_hist.append(a[5])
211
+ self.open_max = max(self.open_max, a[5])
212
+ if (not self.closing and self.open_max > OPEN and pinch[2] - grasp_now_[2] < 0.020
213
+ and a[5] < max(self.cmd_hist[-15:]) - 1.0):
214
+ self.closing = True
215
+ self._event("close_start", float(f))
216
+ if a[5] < CLOSING:
217
+ self._event("close_cmd3", float(f)) # eval_policy's close marker
218
+ pinch_cmd, _ = ex.kin.pose(np.radians(a[:5]), plan.offset)
219
+ lo, hi = r.grip_range
220
+ gq = float(d.qpos[r.grip_qadr])
221
+ gq_cmd = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo)
222
+ base = w.base_pos(d, self.target)
223
+ grasp_now = base + self.grasp_rel
224
+ err = pinch - grasp_now
225
+ xj = np.r_[R[:2, 0], 0.0]
226
+ xj /= max(np.linalg.norm(xj), 1e-9)
227
+ yj = np.array([-xj[1], xj[0], 0.0])
228
+ yaw = float(np.arctan2(R[1, 0], R[0, 0]))
229
+ dyaw = np.degrees(yaw - plan.yaw)
230
+ self.rows.append(dict(
231
+ f=f, cmd=a.copy(), act=r.to_lerobot(d.qpos[r.qadr]).astype(float), pinch=pinch.copy(),
232
+ track_mm=1000 * float(np.linalg.norm(pinch_cmd - pinch)),
233
+ lat_mm=1000 * float(np.linalg.norm(err[:2])), along_mm=1000 * float(err @ xj),
234
+ across_mm=1000 * float(err @ yj), height_mm=1000 * float(err[2]),
235
+ yaw=yaw, yaw_err180=float((dyaw + 90) % 180 - 90), yaw_err360=float((dyaw + 180) % 360 - 180),
236
+ lean_deg=float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))),
237
+ gap_mm=float(np.interp(gq, self.qs, self.gaps)), gap_cmd_mm=float(np.interp(gq_cmd, self.qs, self.gaps)),
238
+ piece=base.copy(), piece_moved_mm=1000 * float(np.linalg.norm(base[:2] - self.base0[:2])),
239
+ tilt=float(w.tilt_deg(d, self.target)),
240
+ new_chunk=len(self.policy._queues["action"]) == self.n_steps - 1,
241
+ closing=self.closing))
242
+ if self.capture:
243
+ self.side_renderer.update_scene(d, camera=self.cam, scene_option=r.scene_option)
244
+ buf = io.BytesIO()
245
+ from PIL import Image
246
+
247
+ Image.fromarray(self.side_renderer.render()).save(buf, "JPEG", quality=85)
248
+ self.side.append(buf.getvalue())
249
+ return False
250
+
251
+ def arrays(self):
252
+ import numpy as np
253
+
254
+ keys = self.rows[0].keys()
255
+ return {k: np.array([row[k] for row in self.rows]) for k in keys}
256
+
257
+
258
+ def classify(A: dict, events: dict, parts: dict, fps: int = 30) -> dict:
259
+ """What happened first, and the signals around it.
260
+
261
+ The onset is the earliest of: the arm touching the marked piece before the jaws began
262
+ closing, the arm touching another piece, the marked piece touching another piece, or
263
+ the marked piece tilting past 5 deg, all before closing began. If none happened, it is
264
+ the start of closing. Signals in the half second up to the onset:
265
+ - rotating: the jaw turned faster than 45 deg/s while the pinch point was within 30 mm
266
+ of the grasp point;
267
+ - sideways: at the onset the pinch point moved sideways more than twice as fast as
268
+ vertically, and faster than 10 mm/s;
269
+ - lag: the pinch point of the commanded joints was more than 3 mm from the actual one;
270
+ - offset: when closing began, the pinch point was more than 2 mm (sideways) from the
271
+ grasp point on the piece where it stands.
272
+ """
273
+ import numpy as np
274
+
275
+ close = events.get("close_start")
276
+ pre = [(events[k], k) for k in ("arm_target_open", "arm_neighbour", "target_neighbour", "tilt5")
277
+ if k in events and (close is None or events[k] < close)]
278
+ if pre:
279
+ t0, first = min(pre)
280
+ stage = "before closing"
281
+ elif close is not None:
282
+ t0, first, stage = close, "close_start", "at closing"
283
+ else:
284
+ return dict(onset="never closed, nothing touched", first=None, t0=None, flags={})
285
+ n = len(A["f"])
286
+ f0 = min(int(t0), n - 1)
287
+ lo = max(0, f0 - fps // 2)
288
+ yaw = np.unwrap(A["yaw"])
289
+ rate = np.abs(np.diff(yaw, prepend=yaw[0])) * fps
290
+ dist = np.hypot(A["lat_mm"], A["height_mm"])
291
+ near = dist[lo:f0 + 1] < 30
292
+ rotating = bool(np.any(np.degrees(rate[lo:f0 + 1])[near] > 45)) if near.any() else False
293
+ v = np.diff(A["pinch"], axis=0, prepend=A["pinch"][:1]) * fps
294
+ k0 = max(1, f0 - 2)
295
+ h_speed = float(np.mean(np.linalg.norm(v[k0:f0 + 1, :2], axis=1)))
296
+ v_speed = float(np.mean(np.abs(v[k0:f0 + 1, 2])))
297
+ sideways = h_speed > 2 * v_speed and h_speed > 0.010
298
+ lag = bool(A["track_mm"][f0] > 3.0)
299
+ fc = min(int(close), n - 1) if close is not None else None
300
+ lat_close = float(A["lat_mm"][fc]) if fc is not None else None
301
+ offset = lat_close is not None and lat_close > 2.0
302
+ if stage == "before closing":
303
+ if rotating:
304
+ onset = "wrist rotates near the piece"
305
+ elif sideways:
306
+ onset = "hand approaches sideways"
307
+ else:
308
+ onset = "descends onto the piece off-centre"
309
+ else:
310
+ onset = "jaws close around an offset piece" if offset else "closed centred; failed later"
311
+ chunks = np.flatnonzero(A["new_chunk"])
312
+ near_chunk = bool(np.any(np.abs(chunks - f0) <= 5)) if len(chunks) else False
313
+ return dict(onset=onset, first=first, first_part=parts.get(first), t0_s=round(t0 / fps, 2), stage=stage,
314
+ flags=dict(rotating=rotating, sideways=sideways, lag=lag, offset=offset),
315
+ h_speed_mm_s=round(1000 * h_speed, 1), v_speed_mm_s=round(1000 * v_speed, 1),
316
+ track_mm_at_onset=round(float(A["track_mm"][f0]), 2),
317
+ lat_mm_at_onset=round(float(A["lat_mm"][f0]), 2), height_mm_at_onset=round(float(A["height_mm"][f0]), 1),
318
+ yaw_err180_at_onset=round(float(A["yaw_err180"][f0]), 1),
319
+ 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),
320
+ chunk_within_5_frames=near_chunk)
321
+
322
+
323
+ def write_replay(path, policy_frames, side_frames, A, events, info, f0, fps=30, slow=4, before=60, after=60):
324
+ """Slow replay around frame f0: the images the policy saw (overhead, wrist), a close-up
325
+ side view, and the measurements of each frame."""
326
+ import av
327
+ import numpy as np
328
+ from PIL import Image, ImageDraw
329
+
330
+ n = min(len(side_frames), len(A["f"]), len(policy_frames))
331
+ lo, hi = max(0, f0 - before), min(n, f0 + after)
332
+ ev_frames = {k: int(v) for k, v in events.items()}
333
+ with av.open(str(path), "w") as container:
334
+ stream = container.add_stream("libx264", rate=fps)
335
+ stream.width, stream.height, stream.pix_fmt = 960, 360, "yuv420p"
336
+ stream.options = {"crf": "23"}
337
+ for f in range(lo, hi):
338
+ top = np.asarray(Image.open(io.BytesIO(policy_frames[f])).convert("RGB")) # 240 x 640 (overhead | wrist)
339
+ side = np.asarray(Image.open(io.BytesIO(side_frames[f])).convert("RGB")) # 240 x 320
340
+ canvas = Image.new("RGB", (960, 360), (18, 18, 18))
341
+ canvas.paste(Image.fromarray(top), (0, 0))
342
+ canvas.paste(Image.fromarray(side), (640, 0))
343
+ pen = ImageDraw.Draw(canvas)
344
+ lines = [f"{info} t={f / fps:5.2f}s frame {f}{' NEW CHUNK' if A['new_chunk'][f] else ''}",
345
+ 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}),"
346
+ 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",
347
+ 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"
348
+ f" piece moved {A['piece_moved_mm'][f]:5.1f} mm, tilt {A['tilt'][f]:5.1f} deg",
349
+ "events: " + ", ".join(f"{k} @{v / fps:.2f}s" for k, v in sorted(events.items(), key=lambda x: x[1])
350
+ if ev_frames[k] <= f) or "events: none yet"]
351
+ for j, line in enumerate(lines):
352
+ pen.text((8, 248 + 26 * j), line, fill=(255, 235, 120) if j == 3 else (230, 230, 230))
353
+ if any(ev_frames[k] == f for k in events):
354
+ pen.rectangle([0, 0, 959, 239], outline=(255, 60, 60), width=4)
355
+ frame = av.VideoFrame.from_ndarray(np.asarray(canvas), format="rgb24")
356
+ for _ in range(slow):
357
+ for packet in stream.encode(frame):
358
+ container.mux(packet)
359
+ for packet in stream.encode():
360
+ container.mux(packet)
361
+
362
+
363
+ # ---------------------------------------------------------------------------- workers
364
+ def run_one(runner, cfg, bundle, seed, i, seconds, capture=False, hashes=False):
365
+ import numpy as np
366
+ import torch
367
+
368
+ from eval_policy import drive
369
+
370
+ policy, pre, post, device = bundle
371
+ task, ep_seed, torch_seed, plan = episode(runner, seed, i)
372
+ tr = Tracer(runner, task, plan, policy, capture=capture)
373
+ frames = HashFrames() if hashes else (JpegFrames() if capture else None)
374
+ torch.manual_seed(torch_seed)
375
+ res, met = drive(runner, task, policy, pre, post, device, cfg, seconds, ep_seed ^ 0x5EED, frames,
376
+ on_frame=tr.on_frame, on_substep=tr.on_substep)
377
+ tr.close()
378
+ A = tr.arrays()
379
+ head = dict(index=i, ep_seed=ep_seed, torch_seed=torch_seed, move=f"{task.source}-{task.dest.square}",
380
+ piece=runner.w.kind[task.target], plan_yaw_deg=round(float(np.degrees(plan.yaw)), 1),
381
+ plan_grasp_mm=[round(1000 * float(x), 3) for x in plan.grasp_point], success=bool(res.success),
382
+ reason=res.reason, frames=res.frames, lifted=bool(met["lifted"]))
383
+ return head, A, tr, frames
384
+
385
+
386
+ def repeat_worker(condition, reps, args, indices, queue):
387
+ if condition == "deterministic":
388
+ set_deterministic()
389
+ import warnings
390
+
391
+ warnings.filterwarnings("ignore")
392
+ import numpy as np
393
+ import torch
394
+
395
+ from episode import EpisodeRunner, load_config
396
+ from eval_policy import load_policy
397
+ from piece_sets import sample_piece_set
398
+
399
+ torch.set_num_threads(2)
400
+ cfg = load_config()
401
+ bundle = load_policy(args.policy)
402
+ out = Path(args.out) / "runs"
403
+ out.mkdir(parents=True, exist_ok=True)
404
+ for rep in reps:
405
+ for i in indices:
406
+ runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([args.seed, 10**9 + i // 5]), cfg, "rep"),
407
+ render=True)
408
+ head, A, tr, hashes = run_one(runner, cfg, bundle, args.seed, i, args.seconds, hashes=True)
409
+ runner.close()
410
+ np.savez_compressed(out / f"{condition}_rep{rep}_ep{i:03d}.npz", cmd=A["cmd"], act=A["act"],
411
+ hashes=np.array(list(hashes)))
412
+ queue.put(dict(condition=condition, rep=rep, pid=os.getpid(), **head, events=tr.events))
413
+ queue.put(None)
414
+
415
+
416
+ def trace_worker(k, n, args, queue):
417
+ import warnings
418
+
419
+ warnings.filterwarnings("ignore")
420
+ import numpy as np
421
+ import torch
422
+
423
+ from episode import EpisodeRunner, load_config
424
+ from eval_policy import load_policy
425
+ from piece_sets import sample_piece_set
426
+
427
+ torch.set_num_threads(2)
428
+ cfg = load_config()
429
+ bundle = load_policy(args.policy)
430
+ out = Path(args.out)
431
+ (out / "traces").mkdir(parents=True, exist_ok=True)
432
+ (out / "replays").mkdir(parents=True, exist_ok=True)
433
+ runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([args.seed, 10**9]), cfg, "trace"), render=True)
434
+ for i in range(k * args.episodes // n, (k + 1) * args.episodes // n):
435
+ head, A, tr, frames = run_one(runner, cfg, bundle, args.seed, i, args.seconds, capture=args.replays)
436
+ c = classify(A, tr.events, tr.parts)
437
+ np.savez_compressed(out / "traces" / f"ep{i:03d}.npz", **A)
438
+ replay = None
439
+ if args.replays and not head["success"] and head["piece"] == "pawn" and c.get("t0_s") is not None:
440
+ replay = f"replays/ep{i:03d}_{head['move']}_{c['onset'].split()[0]}.mp4"
441
+ write_replay(out / replay, frames, tr.side, A, tr.events,
442
+ f"ep {i} {head['piece']} {head['move']} ({c['onset']})", int(c["t0_s"] * 30))
443
+ queue.put(dict(**head, events={k2: round(v / 30, 3) for k2, v in tr.events.items()}, parts=tr.parts,
444
+ classification=c, replay=replay))
445
+ runner.close()
446
+ queue.put(None)
447
+
448
+
449
+ def collect(procs, queue, label):
450
+ results, finished = [], 0
451
+ while finished < len(procs):
452
+ try:
453
+ r = queue.get(timeout=120)
454
+ except Empty:
455
+ if not any(p.is_alive() for p in procs):
456
+ print(f"{label}: worker(s) crashed", flush=True)
457
+ break
458
+ continue
459
+ if r is None:
460
+ finished += 1
461
+ continue
462
+ results.append(r)
463
+ print(f"{label}: {r.get('condition', '')} {r.get('rep', '')} ep {r['index']} {r['move']} "
464
+ f"{'ok' if r['success'] else 'fail'} {r.get('classification', {}).get('onset', '')}", flush=True)
465
+ for p in procs:
466
+ p.join()
467
+ return results
468
+
469
+
470
+ # ---------------------------------------------------------------------------- reports
471
+ def repeat_report(args, results):
472
+ import numpy as np
473
+
474
+ runs = Path(args.out) / "runs"
475
+ load = lambda c, rep, i: np.load(runs / f"{c}_rep{rep}_ep{i:03d}.npz")
476
+ by = defaultdict(dict)
477
+ for r in results:
478
+ by[(r["condition"], r["index"])][r["rep"]] = r
479
+ rows = []
480
+ for (cond, i), reps in sorted(by.items()):
481
+ ref = load(cond, min(reps), i)
482
+ for rep, r in sorted(reps.items()):
483
+ x = load(cond, rep, i)
484
+ n = min(len(x["cmd"]), len(ref["cmd"]))
485
+ dcmd = np.abs(x["cmd"][:n] - ref["cmd"][:n]).max(axis=1)
486
+ hn = min(len(x["hashes"]), len(ref["hashes"]))
487
+ hdiff = np.flatnonzero(x["hashes"][:hn] != ref["hashes"][:hn])
488
+ cdiff = np.flatnonzero(dcmd > 1e-4)
489
+ rows.append(dict(condition=cond, index=i, rep=rep, move=r["move"], success=r["success"],
490
+ same_episode=(r["ep_seed"], r["torch_seed"], r["plan_grasp_mm"]) ==
491
+ (reps[min(reps)]["ep_seed"], reps[min(reps)]["torch_seed"], reps[min(reps)]["plan_grasp_mm"]),
492
+ first_input_diff=int(hdiff[0]) if len(hdiff) else None,
493
+ first_action_diff=int(cdiff[0]) if len(cdiff) else None,
494
+ action_diff_at_first=float(dcmd[cdiff[0]]) if len(cdiff) else 0.0,
495
+ max_action_diff=float(dcmd.max()) if n else 0.0))
496
+ # Across conditions: each repeat against same_process repeat 0.
497
+ cross = []
498
+ for (cond, i), reps in sorted(by.items()):
499
+ if cond == "same_process" or ("same_process", i) not in by:
500
+ continue
501
+ ref = load("same_process", 0, i)
502
+ for rep in sorted(reps):
503
+ x = load(cond, rep, i)
504
+ n = min(len(x["cmd"]), len(ref["cmd"]))
505
+ cd = np.flatnonzero(np.abs(x["cmd"][:n] - ref["cmd"][:n]).max(axis=1) > 1e-4)
506
+ hn = min(len(x["hashes"]), len(ref["hashes"]))
507
+ hd = np.flatnonzero(x["hashes"][:hn] != ref["hashes"][:hn])
508
+ cross.append(dict(condition=cond, index=i, rep=rep, first_input_diff=int(hd[0]) if len(hd) else None,
509
+ first_action_diff=int(cd[0]) if len(cd) else None))
510
+ (Path(args.out) / "repeat_results.json").write_text(json.dumps(dict(results=results, rows=rows, cross=cross), indent=1, default=str))
511
+ lines = ["# Repeatability", "",
512
+ f"Policy `{args.policy}`, episodes {args.indices} of seed {args.seed}, {args.repeats} repeats per condition. "
513
+ "Each run builds a fresh simulator and pins the episode seed, move, expert plan and the policy's sampling "
514
+ "seed as eval_policy does. `first input diff`: first frame whose policy images differ from repeat 0 "
515
+ "(md5 of the downsampled images); `first action diff`: first frame whose commanded joints differ by more "
516
+ "than 1e-4 (degrees or gripper units).", "",
517
+ "| condition | episode | move | outcomes (repeat 0..n) | identical episode setup | first input diff (frames) | first action diff (frames) | max action diff |",
518
+ "|---|---|---|---|---|---|---|---|"]
519
+ grouped = defaultdict(list)
520
+ for row in rows:
521
+ grouped[(row["condition"], row["index"])].append(row)
522
+ for (cond, i), rs in grouped.items():
523
+ rs = sorted(rs, key=lambda x: x["rep"])
524
+ lines.append(f"| {cond} | {i} | {rs[0]['move']} | {''.join('S' if x['success'] else 'F' for x in rs)} | "
525
+ f"{all(x['same_episode'] for x in rs)} | {[x['first_input_diff'] for x in rs[1:]]} | "
526
+ f"{[x['first_action_diff'] for x in rs[1:]]} | {max(x['max_action_diff'] for x in rs):.3g} |")
527
+ if cross:
528
+ lines += ["", "## Against `same_process` repeat 0", "",
529
+ "| condition | episode | repeat | first input diff | first action diff |", "|---|---|---|---|---|"]
530
+ lines += [f"| {c['condition']} | {c['index']} | {c['rep']} | {c['first_input_diff']} | {c['first_action_diff']} |" for c in cross]
531
+ (Path(args.out) / "repeat_report.md").write_text("\n".join(lines) + "\n")
532
+ print("\n".join(lines))
533
+
534
+
535
+ def trace_report(args, results):
536
+ import numpy as np
537
+
538
+ out = Path(args.out)
539
+ results.sort(key=lambda r: r["index"])
540
+ (out / "trace_results.json").write_text(json.dumps(results, indent=1, default=str))
541
+ fails = [r for r in results if not r["success"]]
542
+ oks = [r for r in results if r["success"]]
543
+ lines = ["# Grasp traces", "",
544
+ f"Policy `{args.policy}`, {len(results)} episodes of seed {args.seed} (not the development or final sets). "
545
+ f"{len(oks)} succeeded, {len(fails)} failed.", "",
546
+ "Onset = what happened first (see `classify` in `sim/grasp_trace.py`): the arm touching the marked piece "
547
+ "before the jaws began closing, touching another piece, the marked piece touching another piece, or tilting "
548
+ "past 5 deg, before closing began; otherwise the start of closing. Contacts are checked every physics step.", "",
549
+ "## Failures by onset", "", "| onset | pawn | knight | total |", "|---|---|---|---|"]
550
+ onsets = Counter((r["classification"]["onset"], r["piece"]) for r in fails)
551
+ for o in sorted({k[0] for k in onsets}):
552
+ lines.append(f"| {o} | {onsets[(o, 'pawn')]} | {onsets[(o, 'knight')]} | {onsets[(o, 'pawn')] + onsets[(o, 'knight')]} |")
553
+ firsts = Counter((r["classification"].get("first"), r["classification"].get("first_part")) for r in fails)
554
+ lines += ["", "First event of each failure (event, part that touched):", ""]
555
+ lines += [f"- {k[0]} ({k[1]}): {v}" for k, v in firsts.most_common()]
556
+ flag = lambda rs, k: sum(r["classification"].get("flags", {}).get(k, False) for r in rs)
557
+ lines += ["", "## Signals", "", "| signal | failures | successes |", "|---|---|---|"]
558
+ for k, label in (("rotating", "jaw turning > 45 deg/s within 30 mm of the grasp point, up to the onset"),
559
+ ("sideways", "pinch point moving mostly sideways at the onset"),
560
+ ("lag", "commanded vs actual pinch point > 3 mm at the onset"),
561
+ ("offset", "> 2 mm sideways from the piece when closing began")):
562
+ lines.append(f"| {label} | {flag(fails, k)}/{len(fails)} | {flag(oks, k)}/{len(oks)} |")
563
+ med = lambda rs, key: round(float(np.median([r["classification"][key] for r in rs
564
+ if r["classification"].get(key) is not None])), 2) if rs else None
565
+ lines += ["", "| measure | failures (median) | successes (median) |", "|---|---|---|"]
566
+ for key, label in (("lat_mm_at_close", "sideways error when closing began (mm)"),
567
+ ("track_mm_at_onset", "command vs actual at the onset (mm)"),
568
+ ("lat_mm_at_onset", "sideways error at the onset (mm)"),
569
+ ("height_mm_at_onset", "height above the grasp point at the onset (mm)"),
570
+ ("yaw_err180_at_onset", "jaw yaw vs the expert's, mod 180, at the onset (deg)"),
571
+ ("gap_mm_at_onset", "fingertip gap at the onset (mm)"),
572
+ ("h_speed_mm_s", "sideways speed at the onset (mm/s)"),
573
+ ("v_speed_mm_s", "vertical speed at the onset (mm/s)")):
574
+ lines.append(f"| {label} | {med(fails, key)} | {med(oks, key)} |")
575
+ near = sum(r["classification"].get("chunk_within_5_frames", False) for r in fails)
576
+ lines += ["", f"A new action chunk started within 5 frames of the onset in {near}/{len(fails)} failures "
577
+ "(by chance about 11/50 = 22% with 50-step chunks).", "",
578
+ "## Episodes", "", "| # | move | result | onset | first event | at (s) | sideways at close (mm) | replay |",
579
+ "|---|---|---|---|---|---|---|---|"]
580
+ for r in results:
581
+ c = r["classification"]
582
+ lines.append(f"| {r['index']} | {r['piece']} {r['move']} | {'ok' if r['success'] else 'fail'} | {c['onset']} | "
583
+ f"{c.get('first')} ({c.get('first_part')}) | {c.get('t0_s')} | {c.get('lat_mm_at_close')} | "
584
+ f"{r['replay'] or ''} |")
585
+ (out / "trace_report.md").write_text("\n".join(lines) + "\n")
586
+ print("\n".join(lines))
587
+
588
+
589
+ def main():
590
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
591
+ ap.add_argument("mode", choices=["repeat", "trace"])
592
+ ap.add_argument("--policy", required=True)
593
+ ap.add_argument("--seed", type=int, default=8_000_003)
594
+ ap.add_argument("--seconds", type=float, default=20.0)
595
+ ap.add_argument("--out", required=True)
596
+ ap.add_argument("--indices", default="", help="repeat: episode indices of --seed")
597
+ ap.add_argument("--repeats", type=int, default=5, help="repeat: processes for separate and deterministic")
598
+ ap.add_argument("--same-repeats", type=int, default=3, help="repeat: back-to-back repeats in one process")
599
+ ap.add_argument("--conditions", default="same_process,separate,deterministic")
600
+ ap.add_argument("--episodes", type=int, default=40)
601
+ ap.add_argument("--workers", type=int, default=6)
602
+ ap.add_argument("--replays", action="store_true")
603
+ args = ap.parse_args()
604
+ Path(args.out).mkdir(parents=True, exist_ok=True)
605
+ ctx = mp.get_context("spawn")
606
+ t0 = time.time()
607
+ if args.mode == "repeat":
608
+ indices = [int(x) for x in args.indices.split(",")]
609
+ conds = args.conditions.split(",")
610
+ results = []
611
+ # same_process runs alongside separate; deterministic after (GPU memory: 1 + repeats processes at a time).
612
+ batches = [[c for c in conds if c in ("same_process", "separate")], [c for c in conds if c == "deterministic"]]
613
+ for batch in batches:
614
+ if not batch:
615
+ continue
616
+ queue = ctx.Queue()
617
+ procs = []
618
+ for cond in batch:
619
+ if cond == "same_process":
620
+ procs.append(ctx.Process(target=repeat_worker, args=(cond, list(range(args.same_repeats)), args, indices, queue)))
621
+ else:
622
+ procs += [ctx.Process(target=repeat_worker, args=(cond, [rep], args, indices, queue))
623
+ for rep in range(args.repeats)]
624
+ for p in procs:
625
+ p.start()
626
+ results += collect(procs, queue, "repeat")
627
+ repeat_report(args, results)
628
+ else:
629
+ queue = ctx.Queue()
630
+ procs = [ctx.Process(target=trace_worker, args=(k, args.workers, args, queue)) for k in range(args.workers)]
631
+ for p in procs:
632
+ p.start()
633
+ trace_report(args, collect(procs, queue, "trace"))
634
+ print(f"done in {(time.time() - t0) / 60:.1f} min")
635
+
636
+
637
+ if __name__ == "__main__":
638
+ main()