"""Close look at the policy's grasps: where the jaws are when it closes them, and what follows. For each episode (the settings profile's scene, a random one of its moves) the expert first plans its own grasp of the marked piece, without executing it: jaw yaw, pinch point and the offset of the pinch point in the gripper frame. The policy then drives. The moment it starts closing (gripper command below 3 of 100 after being open), the pinch point is compared with the expert's: - sideways error along the jaws' closing direction and across it (mm), - height error (mm, positive = too high), - jaw yaw error (deg, modulo 180: the jaws are nearly symmetric), - the piece's tilt, whether the arm already touches it or a neighbour, - how far any other piece had been pushed. It then watches 2 s more: lifted (8 mm), toppled (tilt over 45 deg), dropped. Writes grasp_report.md, grasp_results.json and wrist/overhead snapshots of the moment of closing for the failed lifts. Run: MUJOCO_GL=egl PHASE2_PROFILE=baseline .venv/bin/python sim/inspect_grasps.py \ --policy outputs/chess_phase_smolvla_baseline/checkpoints/last/pretrained_model --episodes 20 """ from __future__ import annotations import argparse import json import multiprocessing as mp import sys import time from pathlib import Path from queue import Empty HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) # Gripper command, LeRobot 0-100 units: about 10 at rest, 6-11 open around a piece, 0 closed. OPEN, CLOSING = 4.0, 3.0 def worker(k, n, args, queue): import warnings warnings.filterwarnings("ignore") import numpy as np import torch from PIL import Image from camera_effects import training_look from episode import EpisodeRunner, load_config from eval_policy import LIFT_M, drive, load_policy from lerobot_export import Recorder, video_settings from piece_sets import sample_piece_set torch.set_num_threads(2) cfg = load_config() crf, pix_fmt = video_settings(cfg) policy, pre, post, device = load_policy(args.policy) rng = np.random.default_rng([args.seed, k]) runner = EpisodeRunner(cfg, sample_piece_set(rng, cfg, f"inspect{k}"), render=True) m, d, w, ex = runner.m, runner.d, runner.w, runner.expert hand = {m.body("gripper").id, m.body("moving_jaw_so101_v1").id} for i in range(k, args.episodes, n): seed = int(rng.integers(2**62)) task = runner.setup(np.random.default_rng(seed)) saved = (d.qpos.copy(), d.qvel.copy(), d.act.copy(), d.ctrl.copy(), d.time) plan = ex.plan_pick(d, task.target, np.random.default_rng(seed)) # the expert's grasp, not executed d.qpos[:], d.qvel[:], d.act[:], d.ctrl[:] = saved[:4] d.time = saved[4] import mujoco mujoco.mj_forward(m, d) start = {p: w.base_pos(d, p) for p in w.pieces} axis = np.array([np.cos(plan.yaw), np.sin(plan.yaw)]) # jaw closing direction across = np.array([-axis[1], axis[0]]) rec = Recorder(cfg, None) rec.begin(runner, task, np.random.default_rng(seed ^ 0x5EED)) st = dict(open_max=0.0, close_f=None, info=None, snap=None) def touching(): out = set() for c in d.contact[:d.ncon]: for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)): if m.geom_bodyid[a] in hand and b in runner.piece_of_geom: out.add(runner.piece_of_geom[b]) return out def on_frame(f, a): g = float(a[5]) if st["close_f"] is None: st["open_max"] = max(st["open_max"], g) if st["open_max"] > OPEN and g < CLOSING: st["close_f"] = f q = d.qpos[ex.kin.qadr].copy() p, R = ex.kin.pose(q, plan.offset) err = p - plan.grasp_point yaw = np.arctan2(R[1, 0], R[0, 0]) dyaw = (np.degrees(yaw - plan.yaw) + 90) % 180 - 90 moved = max(float(np.linalg.norm(w.base_pos(d, n2) - start[n2])) for n2 in w.pieces if n2 != task.target and n2 in task.squares.values()) tl = touching() st["info"] = dict(along_mm=round(1000 * float(err[:2] @ axis), 1), across_mm=round(1000 * float(err[:2] @ across), 1), height_mm=round(1000 * float(err[2]), 1), yaw_err_deg=round(float(dyaw), 1), tilt_at_close_deg=round(float(w.tilt_deg(d, task.target)), 1), touching_target=task.target in tl, touching_neighbour=bool(tl - {task.target}), neighbour_moved_mm=round(1000 * moved, 1), t_close_s=round(f / 30, 2)) st["snap"] = [training_look(rec.observe(runner, c), crf, pix_fmt) for c in ("overhead", "wrist")] return False return f - st["close_f"] >= 60 # watch 2 s after the close starts r, met = drive(runner, task, policy, pre, post, device, cfg, args.seconds, seed ^ 0x5EED, stop_when_done=False, recorder=rec, on_frame=on_frame) tilt = float(w.tilt_deg(d, task.target)) lifted_now = bool(w.base_pos(d, task.target)[2] - start[task.target][2] > LIFT_M) out = dict(index=i, seed=seed, piece=w.kind[task.target], move=f"{task.source}-{task.dest.square}", expert_yaw_deg=round(float(np.degrees(plan.yaw)), 1), closed=st["close_f"] is not None, lifted=met["lifted"], held_after_2s=lifted_now, toppled=tilt > 45, closest_mm=met["closest_mm"], **(st["info"] or {})) out["outcome"] = ("never closed" if not out["closed"] else "toppled" if out["toppled"] else "lifted and held" if lifted_now else "lifted, then dropped" if met["lifted"] else "closed, not lifted") if st["snap"] is not None and out["outcome"] != "lifted and held": Image.fromarray(np.concatenate(st["snap"], 1)).save(Path(args.out) / f"close_{i:02d}_{out['move']}.jpg", quality=88) queue.put(out) runner.close() queue.put(None) def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--policy", required=True) ap.add_argument("--episodes", type=int, default=20) ap.add_argument("--workers", type=int, default=3) ap.add_argument("--seconds", type=float, default=14.0, help="give up if it never closes") ap.add_argument("--seed", type=int, default=4_000_003) ap.add_argument("--out", default=str(HERE / "reports" / "baseline_eval" / "grasp_inspection")) args = ap.parse_args() Path(args.out).mkdir(parents=True, exist_ok=True) ctx = mp.get_context("spawn") queue = ctx.Queue() procs = [ctx.Process(target=worker, args=(k, args.workers, args, queue)) for k in range(args.workers)] for p in procs: p.start() t0, results, finished = time.time(), [], 0 while finished < len(procs): try: r = queue.get(timeout=60) except Empty: if not any(p.is_alive() for p in procs): print("worker(s) crashed; reporting what finished", flush=True) break continue if r is None: finished += 1 continue results.append(r) print(f"{len(results)}/{args.episodes} {r['move']}: {r['outcome']}; along {r.get('along_mm')} across " f"{r.get('across_mm')} height {r.get('height_mm')} mm, yaw {r.get('yaw_err_deg')} deg", flush=True) for p in procs: p.join() import numpy as np results.sort(key=lambda r: r["index"]) closed = [r for r in results if r["closed"]] groups = {} for r in closed: groups.setdefault(r["outcome"], []).append(r) med = lambda rs, k: round(float(np.median([abs(r[k]) for r in rs])), 1) if rs else None table = {o: dict(episodes=len(rs), along_mm=med(rs, "along_mm"), across_mm=med(rs, "across_mm"), height_mm=round(float(np.median([r["height_mm"] for r in rs])), 1), yaw_err_deg=med(rs, "yaw_err_deg"), touching_before_close=sum(r["touching_target"] for r in rs), neighbour_touched=sum(r["touching_neighbour"] for r in rs)) for o, rs in groups.items()} summary = dict(policy=args.policy, episodes=len(results), never_closed=len(results) - len(closed), outcomes={o: len(rs) for o, rs in groups.items()}, by_outcome=table, minutes=round((time.time() - t0) / 60, 1)) (Path(args.out) / "grasp_results.json").write_text(json.dumps(dict(summary=summary, episodes=results), indent=1)) lines = ["# Grasp inspection", "", f"Policy `{args.policy}`, {len(results)} episodes. At the moment the policy starts closing the jaws, " "its pinch point is compared with the grasp the expert would make on the same piece. " "Errors: `along` is along the jaws' closing direction, `across` is sideways to it, `height` is " "positive when too high; medians of absolute values (height signed).", "", "| outcome | episodes | along mm | across mm | height mm | yaw err deg | arm on piece before closing | neighbour touched |", "|---|---|---|---|---|---|---|---|"] lines += [f"| {o} | {t['episodes']} | {t['along_mm']} | {t['across_mm']} | {t['height_mm']} | {t['yaw_err_deg']} | " f"{t['touching_before_close']} | {t['neighbour_touched']} |" for o, t in table.items()] lines += ["", f"Never closed within {args.seconds:.0f} s: {summary['never_closed']}.", "", "## Episodes", "", "| # | move | outcome | along | across | height | yaw err | tilt at close | " "on piece | neighbour | neighbour moved mm |", "|---|---|---|---|---|---|---|---|---|---|---|"] lines += [f"| {r['index']} | {r['move']} | {r['outcome']} | {r.get('along_mm', '-')} | {r.get('across_mm', '-')} | " f"{r.get('height_mm', '-')} | {r.get('yaw_err_deg', '-')} | {r.get('tilt_at_close_deg', '-')} | " f"{'yes' if r.get('touching_target') else 'no'} | {'yes' if r.get('touching_neighbour') else 'no'} | " f"{r.get('neighbour_moved_mm', '-')} |" for r in results] lines += ["", "Images `close_NN_.jpg`: overhead and wrist views at the moment of closing, for every " "episode that did not lift and hold the piece."] (Path(args.out) / "grasp_report.md").write_text("\n".join(lines) + "\n") print(json.dumps(summary, indent=1)) if __name__ == "__main__": main()