chess-sim code: baseline profile, diagnostics, grasp inspection, correction demos
Browse filesFiles changed (3)
44 unmodified lines45464748495087 unmodified lines13813914014114214314414514614714814 unmodified lines16316416516616716816929 unmodified lines19920020120220320451 unmodified lines25625725825926026126244 unmodified linesMISALIGNED_M = 0.0025 # holds happen within about 1 mm, failures 4-6 mm off (grasp inspection)def worker(k, quota, args, shard_root, repo_id, queue):import warnings87 unmodified lineshand = {n: w.base_pos(d, n) for n in w.pieces}p, R = pinch()err = p - plan.grasp_pointinfo = dict(kind=kind, trigger=st["trigger"], handover_s=round(st["handover"] / fps, 2), trigger_h_mm=round(1000 * trigger_h, 1),pinch_error_mm=[round(1000 * float(x), 1) for x in err])# The teacher takes over. After a failed grasp: open where it is, then rise clear.frames = 0if kind == "failed_grasp":from expert import Trajectoryex.speed = 1.014 unmodified linesfor q, g, ph in zip(traj.q, traj.g, traj.phase):runner._step_frame(q, g, task, rec, ph, lambda phase: None)frames += len(traj)res = runner.run(task, int(rng.integers(2**62)), recorder=rec, look_s=args.look_s)whole = runner._judge(task, hand, watched, {}, frames + res.frames, 0.0)if not (res.success and whole.success):outcomes["teacher recovery failed: " + (res.reason or whole.reason).split(":")[0][:40]] += 129 unmodified linesap.add_argument("--seconds", type=float, default=14.0, help="policy time before giving up on a trigger")ap.add_argument("--look-s", type=float, default=0.5, help="teacher holds still above the piece this long")ap.add_argument("--pre-grasp-fraction", type=float, default=0.5)args = ap.parse_args()root = (ROOT / args.root).resolve()shards = root.parent / (root.name + "_shards")51 unmodified linesattempts = sum(s["attempts"] for s in summaries.values())summary = dict(episodes=offset, attempts=attempts, success_rate=round(offset / max(attempts, 1), 4),outcomes=dict(outcomes), minutes=round((time.time() - t0) / 60, 1), workers=n,policy=args.policy, look_s=args.look_s, config=cfg)(root / "phase2_summary.json").write_text(json.dumps(summary, indent=2))ds = LeRobotDataset("local/so101_chess_recovery", root=root)print(f"loaded {root}: {ds.num_episodes} episodes, {ds.num_frames} frames")44 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929387 unmodified lines18118218318418518618718818919019119219319419519619719814 unmodified lines21321421521621721821922029 unmodified lines25025125225325425525625725851 unmodified lines31031131231331431531631744 unmodified linesMISALIGNED_M = 0.0025 # holds happen within about 1 mm, failures 4-6 mm off (grasp inspection)def correction_pick(runner, task, plan, lift_first: bool):"""Style v2: the teacher's grasp from where the arm is, never rising to its approachheight and never pausing. Optionally reopen and lift just clear of the piece's top(after a misaligned close), then line up sideways at that height (turning the jaws tothe expert's yaw, or the opposite one if closer), descend straight down, close. Themotion is collision-checked; returns a PickPlan, or None if no yaw works."""import numpy as npfrom expert import PickPlan, PlanningFailed, Trajectory, wrapex, d, w = runner.expert, runner.d, runner.wq = d.qpos[ex.kin.qadr].copy()g = float(d.qpos[runner.grip_qadr])p, R = ex.kin.pose(q, plan.offset)yaw_now = float(np.arctan2(R[1, 0], R[0, 0]))ex._sync_planning(d, ignored=(task.target,))vs = ex.e["vertical_speed"]top = w.base_pos(d, task.target)[2] + w.height[w.kind[task.target]]open_q = plan.grasp.open_qfor yaw in sorted((plan.yaw, plan.yaw + np.pi), key=lambda y: abs(wrap(y - yaw_now))):try:traj = Trajectory()q1, p1, g1 = q, p, gif lift_first:ex._hold(traj, q, g, open_q, 0.3, "reopen")p1 = np.r_[p[:2], max(p[2] + 0.005, top + 0.003)]q1 = ex._cart_move(traj, q, p, p1, yaw_now, yaw_now, plan.offset, open_q, open_q, "clear", vs, 0.3, 1.0)g1 = open_qabove = np.r_[plan.grasp_point[:2], p1[2]]q2 = ex._cart_move(traj, q1, p1, above, yaw_now, yaw, plan.offset, g1, open_q, "align", vs, 0.3, 1.5)q3 = ex._cart_move(traj, q2, above, plan.grasp_point, yaw, yaw, plan.offset, open_q, open_q, "descend",vs, 0.3, 1.8)ex._hold(traj, q3, open_q, open_q, 0.1, "descend")if not ex._collision_free(traj):raise PlanningFailed("collision")ex._hold(traj, q3, open_q, ex.close_q, 0.45, "close")ex._hold(traj, q3, ex.close_q, ex.close_q, 0.25, "close")return PickPlan(traj, yaw, plan.grasp, plan.offset, plan.grasp_point, q3)except PlanningFailed:continuereturn Nonedef worker(k, quota, args, shard_root, repo_id, queue):import warnings87 unmodified lineshand = {n: w.base_pos(d, n) for n in w.pieces}p, R = pinch()err = p - plan.grasp_pointinfo = dict(kind=kind, style=args.style, trigger=st["trigger"], handover_s=round(st["handover"] / fps, 2), trigger_h_mm=round(1000 * trigger_h, 1),pinch_error_mm=[round(1000 * float(x), 1) for x in err])# The teacher takes over.frames = 0if args.style == "v2":pick = correction_pick(runner, task, plan, lift_first=kind == "failed_grasp")if pick is None:outcomes["no collision-free correction"] += 1rec.discard()continueres = runner.run(task, int(rng.integers(2**62)), recorder=rec, pick=pick)elif kind == "failed_grasp": # v1: open where it is, rise clear, then plan a fresh pickfrom expert import Trajectoryex.speed = 1.014 unmodified linesfor q, g, ph in zip(traj.q, traj.g, traj.phase):runner._step_frame(q, g, task, rec, ph, lambda phase: None)frames += len(traj)if args.style == "v1":res = runner.run(task, int(rng.integers(2**62)), recorder=rec, look_s=args.look_s)whole = runner._judge(task, hand, watched, {}, frames + res.frames, 0.0)if not (res.success and whole.success):outcomes["teacher recovery failed: " + (res.reason or whole.reason).split(":")[0][:40]] += 129 unmodified linesap.add_argument("--seconds", type=float, default=14.0, help="policy time before giving up on a trigger")ap.add_argument("--look-s", type=float, default=0.5, help="teacher holds still above the piece this long")ap.add_argument("--pre-grasp-fraction", type=float, default=0.5)ap.add_argument("--style", choices=["v1", "v2"], default="v2",help="v1: the teacher replans from its approach height and pauses to look (made the policy ""hover); v2: lines up from where the arm is and goes straight down, no pause")args = ap.parse_args()root = (ROOT / args.root).resolve()shards = root.parent / (root.name + "_shards")51 unmodified linesattempts = sum(s["attempts"] for s in summaries.values())summary = dict(episodes=offset, attempts=attempts, success_rate=round(offset / max(attempts, 1), 4),outcomes=dict(outcomes), minutes=round((time.time() - t0) / 60, 1), workers=n,policy=args.policy, style=args.style, look_s=args.look_s if args.style == "v1" else 0.0,config=cfg)(root / "phase2_summary.json").write_text(json.dumps(summary, indent=2))ds = LeRobotDataset("local/so101_chess_recovery", root=root)print(f"loaded {root}: {ds.num_episodes} episodes, {ds.num_frames} frames")
235 unmodified lines23623723823924024124224324417 unmodified lines262263264265266267268235 unmodified linesmujoco.mj_step(self.m, self.d)monitor(phase)def run(self, task: Task, rng_seed: int, recorder=None, look_s: float = 0.0) -> Result:"""Execute the primitive from the current (set-up) state. `look_s` holds the handstill above the piece, jaws open, before the descent (the wrist camera sees it)."""rng = np.random.default_rng(rng_seed)d, w = self.d, self.wstart = {n: w.base_pos(d, n) for n in w.pieces}17 unmodified linesframes = 0try:pick = self.expert.plan_pick(d, task.target, rng)except PlanningFailed as exc:return Result(False, f"plan {exc}")if look_s > 0:235 unmodified lines23623723823924024124224324424517 unmodified lines263264265266267268269235 unmodified linesmujoco.mj_step(self.m, self.d)monitor(phase)def run(self, task: Task, rng_seed: int, recorder=None, look_s: float = 0.0, pick=None) -> Result:"""Execute the primitive from the current (set-up) state. `look_s` holds the handstill above the piece, jaws open, before the descent (the wrist camera sees it).`pick`: a ready PickPlan to execute instead of planning one."""rng = np.random.default_rng(rng_seed)d, w = self.d, self.wstart = {n: w.base_pos(d, n) for n in w.pieces}17 unmodified linesframes = 0try:pick = pick or self.expert.plan_pick(d, task.target, rng)except PlanningFailed as exc:return Result(False, f"plan {exc}")if look_s > 0:
4 unmodified lines5678910152 unmodified lines1631641651661671681691701 unmodified line1721731741751761771781791801811821834 unmodified linesRun: .venv/bin/python sim/model_card.py --repo-id Machanize/chess_phase_smolvla \--eval sim/reports/policy_eval/eval_results.json --episodes 2000 --frames 600000 --steps 20000 ..."""from __future__ import annotations152 unmodified lines"""def main():ap = argparse.ArgumentParser(description=__doc__)ap.add_argument("--repo-id", required=True)ap.add_argument("--eval", required=True)ap.add_argument("--episodes", required=True)1 unmodified lineap.add_argument("--steps", required=True)ap.add_argument("--batch", required=True)ap.add_argument("--hours", required=True)ap.add_argument("--expert-success", required=True)ap.add_argument("--lerobot", default="0.4.4")ap.add_argument("--best-mm", dest="best_mm", default="-")ap.add_argument("--dry-run", action="store_true")a = ap.parse_args()text = card(a, json.loads(Path(a.eval).read_text()))if a.dry_run:print(text)return4 unmodified lines56789101112152 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253261 unmodified line3283293303313323333343353363373383393404 unmodified linesRun: .venv/bin/python sim/model_card.py --repo-id Machanize/chess_phase_smolvla \--eval sim/reports/policy_eval/eval_results.json --episodes 2000 --frames 600000 --steps 20000 ....venv/bin/python sim/model_card.py --kind baseline --repo-id Machanize/chess_phase_smolvla_baseline \--eval sim/reports/baseline_eval/smolvla/eval_results.json --episodes 300 --frames 89008 ..."""from __future__ import annotations152 unmodified lines"""VARIANTS = {"baseline": dict(front="base_model: lerobot/smolvla_base\ntags:\n- lerobot\n- smolvla",intro="[SmolVLA](https://huggingface.co/lerobot/smolvla_base) trained to move a chess piece with an\n""**SO-101** arm in one fixed simulated scene (MuJoCo). It is the simple baseline of the\n""chess robot's \"hand\": first get reliable closed-loop success in the easiest setting, then add\n""variety back one change at a time. Trained fresh from `lerobot/smolvla_base`, not from the\n""earlier `Machanize/chess_phase_smolvla`.",cams=" Fed to the model as `camera{n}`.", chunk=50,data="`Machanize/playful`, folder `chess-sim/datasets/baseline_v1` (private): **{episodes} successful\n""episodes ({frames} frames)** of a scripted inverse-kinematics expert at 30 fps, about\n""{per_move} per move. The expert's start pose and speed vary slightly between episodes.",train="From `lerobot/smolvla_base`, {steps} steps at batch {batch} on one RTX 4090 in {hours} h, LeRobot\n""{lerobot}, default SmolVLA settings (vision encoder frozen, action expert trained). Overhead and\n""wrist cameras are renamed to `camera1` and `camera2`.",use="from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy\n""policy = SmolVLAPolicy.from_pretrained(\"{repo_id}\")"),"r2": dict(front="base_model: Machanize/chess_phase_smolvla_baseline\ntags:\n- lerobot\n- smolvla\n- dagger",intro="[SmolVLA](https://huggingface.co/lerobot/smolvla_base) for moving a chess piece with an **SO-101**\n""arm in one fixed simulated scene (MuJoCo), fine-tuned on corrections of its own mistakes.\n""It continues from `Machanize/chess_phase_smolvla_baseline`, which found the marked piece\n""reliably but closed its jaws 4-6 mm off when it failed. The correction data (DAgger-style)\n""shows the scripted teacher taking over from the states that policy actually got into:\n""holding still above the piece to look through the wrist camera, lining up and grasping,\n""or, after a misaligned close, reopening, rising, looking and grasping again.",cams=" Fed to the model as `camera{n}`.", chunk=50,data="`Machanize/playful`, folders `chess-sim/datasets/baseline_v1` and\n""`chess-sim/datasets/baseline_recovery_v1` (private), merged: **{episodes} episodes ({frames}\n""frames)**. That is the baseline's 300 full expert demonstrations plus 120 corrections, in which\n""the baseline policy drove and the teacher took over just before the grasp (85) or the moment\n""the policy started closing more than 2.5 mm off (35). Only the teacher's part is recorded.",train="From `Machanize/chess_phase_smolvla_baseline`, {steps} more steps at batch {batch} on one RTX 4090\n""in {hours} h, LeRobot {lerobot}, default SmolVLA settings (vision encoder frozen). Overhead and\n""wrist cameras are renamed to `camera1` and `camera2`.",use="from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy\n""policy = SmolVLAPolicy.from_pretrained(\"{repo_id}\")"),"act": dict(front="tags:\n- lerobot\n- act",intro="[ACT](https://huggingface.co/papers/2304.13705) (Action Chunking with Transformers) trained from\n""scratch to move a chess piece with an **SO-101** arm in one fixed simulated scene (MuJoCo).\n""It is the comparison for `Machanize/chess_phase_smolvla_baseline`: the same data, a\n""smaller policy without a vision-language model.",cams="", chunk=100,data="`Machanize/playful`, folder `chess-sim/datasets/baseline_v1` (private): **{episodes} successful\n""episodes ({frames} frames)** of a scripted inverse-kinematics expert at 30 fps, about\n""{per_move} per move. The expert's start pose and speed vary slightly between episodes.",train="ACT from scratch (ResNet-18 image backbone pretrained on ImageNet), {steps} steps at batch\n""{batch} on one RTX 4090 in {hours} h, LeRobot {lerobot} defaults (chunks of 100 actions). The\n""camera keys are used as they are.",use="from lerobot.policies.act.modeling_act import ACTPolicy\n""policy = ACTPolicy.from_pretrained(\"{repo_id}\")"),}def card_baseline(a, ev: dict) -> str:s = ev["summary"]v = VARIANTS[a.kind]fill = dict(episodes=a.episodes, frames=a.frames, per_move=int(a.episodes) // 10, steps=a.steps, batch=a.batch,hours=a.hours, lerobot=a.lerobot, repo_id=a.repo_id)reach = s["reach"]moves = "\n".join(f"| {k} | {v2['success_percent']}% | {v2['episodes']} |" for k, v2 in s["by"]["move"].items())works = s["success_percent"] >= 80notes = (Path(a.notes).read_text().strip() + "\n\n") if a.notes else ""status = (f"**Status: works in simulation on its ten moves.** In a closed-loop test it completed "f"{s['success_percent']}% of {s['episodes']} moves (details below)." if works elsef"**Status: not yet reliable.** In a closed-loop test it completed {s['success_percent']}% of "f"{s['episodes']} moves (details below).")name = a.repo_id.split("/")[-1]return f"""---library_name: lerobotlicense: apache-2.0pipeline_tag: robotics{v['front']}- so101- chess- robotics- simulation- pick-and-place---# {name}{v['intro']}{status} It has not been run on a real arm.## What it does- **Input:** two 640x480 camera images and the arm's joint positions, at 30 Hz.- `observation.images.overhead`: a webcam 65 cm straight above the board, 44 degrees top tobottom, the arm at the top edge of the image.{v['cams'].format(n=1)}- `observation.images.wrist`: the official SO-101 wrist camera.{v['cams'].format(n=2)}- The piece to move has a **red square with an opaque outline** drawn over its square; thetarget square has a **blue** one. Both are drawn on the images before they reach the policy.- `observation.state`: 5 arm joints in degrees and the gripper 0-100 (LeRobot's SO-101follower units with `use_degrees=True`).- The instruction is always "move the piece on the red square to the blue square".- **Output:** the next joint targets in the same units, in chunks of {v['chunk']} steps.- The training video was stored at high quality (H.264, CRF 18, full 4:4:4 colour), so themarkers keep their colour. For the closest match, pass live frames through the same encodeand decode (`training_look(image, 18, "yuv444p")` in the project's `sim/camera_effects.py`).## The scene (all fixed)- Board with 25 mm squares, square to the robot and flush against its 6 cm deck; the robotplays black. One Staunton set, black and white pieces, centred in their squares. White arm.- Tray on the right, one table, the same two lamps, no clutter, a clean camera image.- Ten moves from the start position: e7e5, d7d5, g8f6, b8c6, c7c5 (the robot's side) and e2e4,d2d4, g1f3, b1c3, c2c4 (the far side). The start is the same every time and only the red andblue squares change, so doing different moves correctly shows it reads the markers.## Test in simulation{s['episodes']} closed-loop episodes, each a random one of the ten moves from seeds not used intraining. An episode counts as a success if the piece ends within 6 mm of the target square,upright, and no other piece moved more than 2 mm. {s['seconds_limit']:.0f} s limit.**Success: {s['success_percent']}%**- Gripper within half a square of the marked piece: {reach['within_half_square_percent']}% of episodes(median closest approach {reach['median_closest_mm']} mm).- Marked piece lifted: {reach['lifted_percent']}%.| move | success | episodes ||---|---|---|{moves}{notes}## Training data{v['data'].format(**fill)}## Training{v['train'].format(**fill)}## Use```python{v['use'].format(**fill)}```Load the pre- and post-processors saved with the model using `make_pre_post_processors`. Theyapply the training normalisation{" and rename the camera keys" if v['cams'] else ""}.## Limitations- **Simulation only**, one scene, ten moves. Other moves, board positions, camera views,lighting or piece sets are untested and expected to fail until the variety is added back.- The overlay is required: without the red and blue squares it does not know what to move."""def main():ap = argparse.ArgumentParser(description=__doc__)ap.add_argument("--kind", choices=["varied", "baseline", "r2", "act"], default="varied")ap.add_argument("--repo-id", required=True)ap.add_argument("--eval", required=True)ap.add_argument("--episodes", required=True)1 unmodified lineap.add_argument("--steps", required=True)ap.add_argument("--batch", required=True)ap.add_argument("--hours", required=True)ap.add_argument("--expert-success", default="-")ap.add_argument("--lerobot", default="0.4.4")ap.add_argument("--best-mm", dest="best_mm", default="-")ap.add_argument("--notes", help="markdown file inserted before the training data section")ap.add_argument("--dry-run", action="store_true")a = ap.parse_args()text = (card if a.kind == "varied" else card_baseline)(a, json.loads(Path(a.eval).read_text()))if a.dry_run:print(text)return
chess-sim/code/sim/collect_recovery.py+60-5
chess-sim/code/sim/episode.py+4-3
chess-sim/code/sim/model_card.py+159-2