"""Closed-loop test of a trained policy in simulation. Each test episode is set up exactly like a dataset episode (random layout, piece set, lighting, colours, clutter, cameras and move) from seeds the dataset never used, and is kept only if the scripted expert can do it. The policy then drives the arm at 30 Hz from the overhead and wrist images (through the same webcam look and red/blue squares as the data, then the same H.264 round trip the dataset videos went through, see camera_effects.training_look) and the joint state, for up to --seconds. Success is judged as for the expert: the piece within 6 mm of the destination square (or in the tray), upright, and no other piece moved more than 2 mm. With --scenes, the episodes are instead rebuilt from a dataset's phase2_episodes.jsonl (its seed, piece set and board are recorded), so the policy is tested on scenes it was trained on. The rebuilt scene is compared with the record (board, tray, overhead camera, move) and the expert is run on it once as a check. Besides success, every episode records how close the gripper came to the marked piece (`closest_mm`, in the board plane), whether that piece was lifted, and which square the gripper was over at its lowest point. Writes eval_report.md, eval_results.json and eval_video.mp4 (first episodes, overhead and wrist side by side) to --out. Run: MUJOCO_GL=egl .venv/bin/python sim/eval_policy.py --policy Machanize/chess_phase_smolvla --episodes 100 MUJOCO_GL=egl .venv/bin/python sim/eval_policy.py --policy Machanize/chess_phase_smolvla \ --scenes data/varied_2000_notes.jsonl --episodes 30 --out sim/reports/diagnose/training_scenes """ from __future__ import annotations import argparse import json import multiprocessing as mp import os import sys import time from collections import defaultdict from pathlib import Path from queue import Empty HERE = Path(__file__).resolve().parent LIFT_M = 0.008 # the expert lifts pawns about 13 mm, knights about 36 mm sys.path.insert(0, str(HERE)) def load_policy(path: str, n_action_steps: int | None = None, expert_fp32: bool = False): """The policy, its pre/post processors and the torch device. `n_action_steps` overrides how many steps of each predicted chunk are executed before predicting again. `expert_fp32`: run SmolVLA's action expert in float32. Loading otherwise rounds it to bfloat16 (the checkpoint stores it in float32); its weights are reloaded from the file at full precision.""" import torch from lerobot.configs.policies import PreTrainedConfig from lerobot.policies.factory import get_policy_class, make_pre_post_processors device = torch.device("cuda" if torch.cuda.is_available() else "cpu") pcfg = PreTrainedConfig.from_pretrained(path) pcfg.pretrained_path = path pcfg.device = device.type if n_action_steps: pcfg.n_action_steps = n_action_steps policy = get_policy_class(pcfg.type).from_pretrained(path, config=pcfg) if expert_fp32: from safetensors.torch import load_file policy.model.vlm_with_expert.lm_expert.float() weights = load_file(str(Path(path) / "model.safetensors")) expert = {k: v for k, v in weights.items() if ".lm_expert." in k} missing, unexpected = policy.load_state_dict(expert, strict=False) assert expert and not unexpected, "action expert weights not found in model.safetensors" policy.to(device).eval() pre, post = make_pre_post_processors(policy_cfg=pcfg, pretrained_path=path, preprocessor_overrides={"device_processor": {"device": device.type}}) return policy, pre, post, device def piece_set_from_record(rec: dict): """The piece set and board of a recorded episode (dimensions are kept to 0.1 mm).""" from chess_world import KINDS from make_scene import PIECES, Layout from piece_sets import PieceSet, foot_mm dims = rec["piece_set_dims"] layout = Layout(**{k: (tuple(x / 1000 for x in v) if isinstance(v, list) else v / 1000) for k, v in dims["layout"].items()}) width = {k: dims[k]["foot_mm"] / foot_mm(k) for k in KINDS} height = {k: dims[k]["height_mm"] / (PIECES[k]["height_m"] * 1000) for k in KINDS} return PieceSet(rec["piece_set"], width, height, layout) def rebuild_check(info: dict, task, rec: dict) -> list[str]: """Differences between a rebuilt episode and its record (empty if it matches).""" import numpy as np out = [] for key in ("board", "tray"): if np.abs(np.subtract(info[key]["centre_m"], rec[key]["centre_m"])).max() > 0.001: out.append(f"{key} centre {info[key]['centre_m']} vs {rec[key]['centre_m']}") a, b = info["overhead"], rec["overhead"] if isinstance(a, dict) != isinstance(b, dict) or (isinstance(a, dict) and any( abs(a[k] - b[k]) > 0.5 for k in ("tilt_deg", "azimuth_deg", "roll_deg", "fovy_deg"))): out.append(f"overhead {a} vs {b}") if task.source != rec["source"] or (task.dest.square or "bin") != rec["destination"]: out.append(f"move {task.source}->{task.dest.square or 'bin'} vs {rec['source']}->{rec['destination']}") return out def drive(runner, task, policy, pre, post, device, cfg, seconds, rec_rng_seed, video=None, stop_when_done=True, recorder=None, on_frame=None, on_substep=None, replan_near=None, near_height=0.07, fast=False): """Let the policy drive from the set-up state. Returns (Result, metrics). `recorder`: an already begun Recorder to render through (its dataset is not written). `on_frame(f, action)`: called after every step; returning True stops the drive there. `on_substep(f, k)`: called after every physics substep k of frame f. `replan_near`: while the gripper frame is within `near_height` (m) of the board surface, predict a new chunk after this many steps of the current one instead of all of them (the rest of the chunk is dropped). A real arm knows this height from its joint angles. `fast`: render only the frames where the policy predicts a new chunk (it ignores the images of the others); the next action of the current chunk is taken from its queue and postprocessed as predict_action does. Without camera noise (the baseline profile) the results are identical.""" import mujoco import numpy as np import torch from lerobot.utils.control_utils import predict_action from camera_effects import training_look from lerobot_export import Recorder, video_settings crf, pix_fmt = video_settings(cfg) fps = cfg["dataset"]["fps"] rec = recorder if rec is None: rec = Recorder(cfg, None) rec.begin(runner, task, np.random.default_rng(rec_rng_seed)) d, w = runner.d, runner.w start = {p: w.base_pos(d, p) for p in w.pieces} watched = [p for p in task.squares.values() if p != task.target] lo, hi = runner.grip_range home = np.array(cfg["expert"]["home"]) site = runner.m.site("gripperframe").id src = w.square_center(task.source) closest, lowest, lifted, placed_at = np.inf, (np.inf, None), False, None path = [] policy.reset() frames, predictions = 0, 0 n_steps = policy.config.n_action_steps for f in range(int(seconds * fps)): queue = policy._queues["action"] if hasattr(policy, "_queues") else None if replan_near and queue is not None and len(queue) > 0: near = d.site_xpos[site][2] - w.board_top < near_height if near and n_steps - len(queue) >= replan_near: queue.clear() # predict afresh from the current images if queue is not None and len(queue) == 0: predictions += 1 if fast and video is None and queue is not None and len(queue) > 0: with torch.inference_mode(): a = post(queue.popleft()) else: over, wrist = (training_look(rec.observe(runner, c), crf, pix_fmt) for c in ("overhead", "wrist")) if video is not None: video.append(np.concatenate([over[::2, ::2], wrist[::2, ::2]], axis=1)) obs = {"observation.images.overhead": over, "observation.images.wrist": wrist, "observation.state": runner.to_lerobot(d.qpos[runner.qadr])} a = predict_action(obs, policy, device, pre, post, use_amp=False, task=cfg["dataset"]["instruction"], robot_type="so101_follower") a = a.squeeze().float().cpu().numpy() d.ctrl[:5] = np.radians(a[:5]) d.ctrl[5] = lo + np.clip(a[5], 0, 100) / 100 * (hi - lo) for k in range(runner.n_sub): mujoco.mj_step(runner.m, d) if on_substep is not None: on_substep(f, k) frames += 1 g = d.site_xpos[site].copy() path.append(g) closest = min(closest, float(np.linalg.norm(g[:2] - src[:2]))) if g[2] < lowest[0]: lowest = (float(g[2]), w.square_at(g)) lifted |= bool(w.base_pos(d, task.target)[2] - start[task.target][2] > LIFT_M) if on_frame is not None and on_frame(f, a): break # Done once the piece has been set down and the arm is back near rest. if stop_when_done and f % 15 == 0 and f > 60: r = runner._judge(task, start, watched, {}, frames, 0.0) near_home = np.abs(d.qpos[runner.expert.kin.qadr] - home).max() < 0.35 if r.success and placed_at is None: placed_at = f if placed_at is not None and near_home: break r = runner._judge(task, start, watched, {}, frames, 0.0) metrics = dict(closest_mm=round(1000 * closest, 1), lifted=lifted, predictions=predictions, lowest_mm=round(1000 * (lowest[0] - w.board_top), 1), lowest_square=lowest[1], path=np.array(path)) return r, metrics OPEN, CLOSING = 4.0, 3.0 # gripper command, LeRobot 0-100 units: open around a piece 6-11, closed 0 def worker(k, n, args, jobs, queue): import warnings warnings.filterwarnings("ignore") import mujoco import numpy as np import torch from episode import EpisodeRunner, load_config from piece_sets import sample_piece_set torch.set_num_threads(2) # several workers share the CPU; torch would take every core cfg = load_config() policy, pre, post, device = load_policy(args.policy, args.n_action_steps, args.expert_fp32) runner, block_now = None, None # Each worker takes a contiguous slice, and every episode (its piece set, scene, move and the # policy's sampling noise) comes from (seed, episode index) alone: the same --seed gives the same # episodes whatever the number of workers, so models can be compared on identical scenes. for i in range(k * args.episodes // n, (k + 1) * args.episodes // n): extra = {} erng = np.random.default_rng([args.seed, i]) if jobs: # a recorded training episode rec = jobs[i] if runner is not None: runner.close() runner = EpisodeRunner(cfg, piece_set_from_record(rec), render=True) ep_seed = rec["seed"] task = runner.setup(np.random.default_rng(ep_seed)) extra = dict(episode_index=rec["episode_index"], rebuild_diffs=rebuild_check(runner.episode_info, task, rec), expert_ok=runner.run(task, ep_seed).success) else: block = i // args.per_set if block != block_now: if runner is not None: runner.close() runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([args.seed, 10**9 + block]), cfg, f"eval_{block}"), render=True) block_now = block for _ in range(20): # a move the expert can do 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)) info = dict(runner.episode_info) m_, d, w, ex = runner.m, runner.d, runner.w, runner.expert # The expert's grasp of the marked piece (planned, not executed), to measure where the # policy's jaws are when it starts closing. saved = (d.qpos.copy(), d.qvel.copy(), d.act.copy(), d.ctrl.copy(), d.time) try: plan = ex.plan_pick(d, task.target, np.random.default_rng(ep_seed)) except Exception: plan = None d.qpos[:], d.qvel[:], d.act[:], d.ctrl[:] = saved[:4] d.time = saved[4] mujoco.mj_forward(m_, d) st = dict(open_max=0.0, close=None) def on_frame(f, a): if plan is None or st["close"] is not None: return False st["open_max"] = max(st["open_max"], float(a[5])) if st["open_max"] > OPEN and a[5] < CLOSING: pnt, _ = ex.kin.pose(d.qpos[ex.kin.qadr].copy(), plan.offset) err = pnt - plan.grasp_point axis = np.array([np.cos(plan.yaw), np.sin(plan.yaw)]) st["close"] = dict(close_t_s=round(f / 30, 2), close_lateral_mm=round(1000 * float(np.linalg.norm(err[:2])), 1), close_along_mm=round(1000 * float(err[:2] @ axis), 1), close_across_mm=round(1000 * float(err[0] * -axis[1] + err[1] * axis[0]), 1), close_height_mm=round(1000 * float(err[2]), 1)) return False video = [] if i < args.video_episodes else None torch.manual_seed(int(erng.integers(2**31))) # the policy's sampling noise, per episode t0 = time.time() r, m = drive(runner, task, policy, pre, post, device, cfg, args.seconds, ep_seed ^ 0x5EED, video, on_frame=on_frame, replan_near=args.replan_near, near_height=args.near_height_mm / 1000, fast=args.fast) m.pop("path") queue.put(dict(index=i, success=bool(r.success), reason=r.reason, frames=r.frames, seconds=round(time.time() - t0, 1), piece=w.kind[task.target], source=task.source, destination=task.dest.square or "bin", move_kind=task.kind, centre_error_mm=r.centre_error_mm, robot_plays=info["board"]["robot_plays"], arm_colour=info["arm_colour"], key_light=info["lights"]["key"], floor=info["floor"], overhead=info["overhead"], square_mm=round(w.square_size * 1000, 1), disturbed=bool(r.disturbed), max_disturbance_mm=r.max_disturbance_mm, closed=st["close"] is not None, **(st["close"] or {}), **m, **extra, video=video if video else None)) queue.put(None) def pick_scenes(path: str, count: int) -> list[dict]: """`count` recorded episodes spread evenly over the file.""" recs = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()] for i, r in enumerate(recs): r.setdefault("episode_index", i) step = len(recs) / count return [recs[int(i * step)] for i in range(count)] def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--policy", required=True, help="Hugging Face repo id or local path of the trained policy") ap.add_argument("--episodes", type=int, default=100) ap.add_argument("--workers", type=int, default=6) ap.add_argument("--seconds", type=float, default=20.0, help="time limit per episode") ap.add_argument("--per-set", type=int, default=5, help="episodes per random piece set and board") ap.add_argument("--seed", type=int, default=1_000_003, help="never used by generate_dataset (seeds 0 and 1)") ap.add_argument("--scenes", help="phase2_episodes.jsonl of a dataset: rebuild its episodes instead") ap.add_argument("--video-episodes", type=int, default=6) ap.add_argument("--n-action-steps", type=int, help="replan after this many steps of each chunk (default: as trained)") ap.add_argument("--replan-near", type=int, help="near the board, replan after this many steps of each chunk") ap.add_argument("--near-height-mm", type=float, default=70.0, help="gripper-frame height above the board that counts as near") ap.add_argument("--fast", action="store_true", help="render only the frames the policy predicts from (see drive)") ap.add_argument("--expert-fp32", action="store_true", help="run the action expert in float32 (see load_policy)") ap.add_argument("--out", default=str(HERE / "reports" / "policy_eval")) args = ap.parse_args() out = Path(args.out) out.mkdir(parents=True, exist_ok=True) jobs = pick_scenes(args.scenes, args.episodes) if args.scenes else None ctx = mp.get_context("spawn") queue = ctx.Queue() procs = [ctx.Process(target=worker, args=(k, args.workers, args, jobs, queue)) for k in range(args.workers)] for p in procs: p.start() t0, results, finished = time.time(), [], 0 # One line per finished episode, written as it arrives, so a stopped run can still be paired. partial = out / "eval_episodes.jsonl" partial.unlink(missing_ok=True) while finished < len(procs): try: r = queue.get(timeout=60) except Empty: if not any(p.is_alive() for p in procs): # a worker crashed without reporting print(f"{sum(p.exitcode != 0 for p in procs)} worker(s) crashed; reporting what finished", flush=True) break continue if r is None: finished += 1 continue results.append(r) with partial.open("a") as f: f.write(json.dumps({k: v for k, v in r.items() if k != "video"}, default=lambda o: o.item() if hasattr(o, "item") else str(o)) + "\n") ok = sum(x["success"] for x in results) print(f"{len(results)}/{args.episodes} [ep {r['index']}]: {'ok ' if r['success'] else 'fail'} {r['piece']} {r['source']}->{r['destination']} " f"closest {r['closest_mm']} mm, lifted {r['lifted']} ({r['frames']} frames) | " f"{ok}/{len(results)} = {100 * ok / len(results):.1f}%", flush=True) for p in procs: p.join() results.sort(key=lambda r: r["index"]) clips = [r.pop("video") for r in results] import numpy as np clips = [c for c in clips if c] if clips: import av with av.open(str(out / "eval_video.mp4"), "w") as container: stream = container.add_stream("libx264", rate=30) stream.height, stream.width = clips[0][0].shape[:2] stream.pix_fmt = "yuv420p" stream.options = {"crf": "23"} for clip in clips: for frame in clip: for packet in stream.encode(av.VideoFrame.from_ndarray(np.ascontiguousarray(frame), format="rgb24")): container.mux(packet) for packet in stream.encode(): container.mux(packet) rate = lambda rs: round(100 * sum(r["success"] for r in rs) / max(len(rs), 1), 1) groups = {} for key in ("piece", "move_kind", "robot_plays", "arm_colour", "key_light", "floor"): g = defaultdict(list) for r in results: g[r[key]].append(r) groups[key] = {k: dict(success_percent=rate(v), episodes=len(v)) for k, v in sorted(g.items())} dest = defaultdict(list) for r in results: dest["tray" if r["destination"] == "bin" else "square"].append(r) groups["destination"] = {k: dict(success_percent=rate(v), episodes=len(v)) for k, v in dest.items()} if not jobs: moves = defaultdict(list) for r in results: moves[f"{r['source']}-{r['destination']}"].append(r) groups["move"] = {k: dict(success_percent=rate(v), episodes=len(v)) for k, v in sorted(moves.items())} closest = np.array([r["closest_mm"] for r in results]) reach = dict(median_closest_mm=round(float(np.median(closest)), 1), within_half_square_percent=round(100 * float(np.mean(closest < 12.5)), 1), lifted_percent=round(100 * float(np.mean([r["lifted"] for r in results])), 1), lowest_over_source_percent=round(100 * float(np.mean([r["lowest_square"] == r["source"] for r in results])), 1)) closed = [r for r in results if r.get("close_lateral_mm") is not None] med = lambda rs, key: round(float(np.median([r[key] for r in rs])), 1) if rs else None precision = dict(closed_percent=round(100 * len(closed) / max(len(results), 1), 1), median_close_lateral_mm=med(closed, "close_lateral_mm"), median_close_lateral_mm_success=med([r for r in closed if r["success"]], "close_lateral_mm"), median_close_lateral_mm_failure=med([r for r in closed if not r["success"]], "close_lateral_mm"), close_within_2mm_percent=round(100 * sum(r["close_lateral_mm"] <= 2 for r in closed) / max(len(closed), 1), 1), median_close_height_mm=med(closed, "close_height_mm"), disturbed_percent=round(100 * sum(r["disturbed"] for r in results) / max(len(results), 1), 1)) pieces = {} for kind in sorted({r["piece"] for r in results}): rs = [r for r in results if r["piece"] == kind] cs = [r for r in rs if r.get("close_lateral_mm") is not None] pieces[kind] = dict(episodes=len(rs), success_percent=rate(rs), lifted_percent=round(100 * sum(r["lifted"] for r in rs) / len(rs), 1), median_close_lateral_mm=med(cs, "close_lateral_mm"), disturbed_percent=round(100 * sum(r["disturbed"] for r in rs) / len(rs), 1)) summary = dict(policy=args.policy, profile=os.environ.get("PHASE2_PROFILE"), n_action_steps=args.n_action_steps, replan_near=args.replan_near, near_height_mm=args.near_height_mm, offsamples=os.environ.get("SIM_OFFSAMPLES"), seed=args.seed, precision=precision, pieces=pieces, episodes=len(results), success_percent=rate(results), seconds_limit=args.seconds, minutes=round((time.time() - t0) / 60, 1), reach=reach, by=groups) if jobs: summary["training_scenes"] = dict( source=args.scenes, rebuilt_exactly=sum(not r["rebuild_diffs"] for r in results), expert_ok=sum(r["expert_ok"] for r in results)) (out / "eval_results.json").write_text(json.dumps(dict(summary=summary, episodes=results), indent=1, default=lambda o: o.item() if hasattr(o, "item") else str(o))) where = ("scenes rebuilt from the training data (`" + Path(args.scenes).name + "`)" if jobs else f"the `{summary['profile']}` settings profile's scene from seeds not used for training" if summary["profile"] else "random layouts, lighting, colours, clutter and camera views from seeds not used for training; " "each move checked doable by the expert") lines = [f"# Policy evaluation in simulation", "", f"Policy `{args.policy}`, {len(results)} closed-loop episodes on {where}." + (f" Replanning every {args.n_action_steps} steps." if args.n_action_steps else "") + (f" Near the board (gripper within {args.near_height_mm:.0f} mm), replanning every {args.replan_near} steps." if args.replan_near else "") + (f" Anti-aliasing samples: {os.environ.get('SIM_OFFSAMPLES')}." if os.environ.get("SIM_OFFSAMPLES") else ""), "", f"**Success: {summary['success_percent']}%** (piece within 6 mm of the target square or in the tray, " f"upright, nothing else moved more than 2 mm; {args.seconds:.0f} s limit).", "", "## Reach", "", f"- Median closest approach of the gripper to the marked piece (board plane): {reach['median_closest_mm']} mm " f"(a square is about {np.median([r['square_mm'] for r in results]):.0f} mm).", f"- Gripper within half a square of the marked piece: {reach['within_half_square_percent']}% of episodes.", f"- Marked piece lifted more than 8 mm: {reach['lifted_percent']}%.", f"- Gripper's lowest point was over the marked square: {reach['lowest_over_source_percent']}%.", "", "## Grasp precision", "", "Where the jaws are when the policy starts closing (command below 3 of 100), against the grasp the " "scripted expert would make on the same piece.", "", f"- Closed on the piece's square in {precision['closed_percent']}% of episodes.", f"- Median sideways error at closing: {precision['median_close_lateral_mm']} mm " f"(successes {precision['median_close_lateral_mm_success']}, failures {precision['median_close_lateral_mm_failure']}); " f"within 2 mm in {precision['close_within_2mm_percent']}%. Median height error {precision['median_close_height_mm']} mm.", f"- Another piece moved more than 2 mm in {precision['disturbed_percent']}% of episodes.", "", "| piece | episodes | success % | lifted % | median closing error mm | disturbed % |", "|---|---|---|---|---|---|"] lines += [f"| {k} | {v['episodes']} | {v['success_percent']} | {v['lifted_percent']} | {v['median_close_lateral_mm']} | " f"{v['disturbed_percent']} |" for k, v in pieces.items()] + [""] lines += [f"Episodes from seed {args.seed}: the same seed gives the same episodes for any number of workers.", ""] if jobs: ts = summary["training_scenes"] lines += [f"Rebuild check: {ts['rebuilt_exactly']} of {len(results)} scenes matched their record " f"(board, tray, overhead camera, move); the expert completed {ts['expert_ok']} of {len(results)} " f"rebuilt scenes.", ""] for key, title in (("move", "By move"), ("piece", "By piece"), ("destination", "By destination"), ("move_kind", "By move kind"), ("robot_plays", "By side the robot plays"), ("arm_colour", "By arm colour"), ("key_light", "By main light"), ("floor", "By floor")): if key not in groups: continue lines += [f"## {title}", "", "| | success % | episodes |", "|---|---|---|"] lines += [f"| {k} | {v['success_percent']} | {v['episodes']} |" for k, v in groups[key].items()] + [""] lines += ["## Episodes", "", "| # | move | success | closest mm | lifted | lowest over | reason |", "|---|---|---|---|---|---|---|"] lines += [f"| {r.get('episode_index', r['index'])} | {r['piece']} {r['source']}-{r['destination']} | " f"{'yes' if r['success'] else 'no'} | {r['closest_mm']} | {'yes' if r['lifted'] else 'no'} | " f"{r['lowest_square'] or '-'} | {r['reason']} |" for r in results] (out / "eval_report.md").write_text("\n".join(lines) + "\n") print(json.dumps({k: v for k, v in summary.items() if k != "by"}, indent=1)) if __name__ == "__main__": main()