Ali-Uraish commited on
Commit
025ca56
·
verified ·
1 Parent(s): c44c2d3

chess-sim code: baseline profile, diagnostics, grasp inspection, correction demos

Browse files
chess-sim/code/sim/collect_recovery.py CHANGED
@@ -45,6 +45,49 @@ OPEN, CLOSING = 4.0, 3.0
45
  MISALIGNED_M = 0.0025 # holds happen within about 1 mm, failures 4-6 mm off (grasp inspection)
46
 
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  def worker(k, quota, args, shard_root, repo_id, queue):
49
  import warnings
50
 
@@ -138,11 +181,18 @@ def worker(k, quota, args, shard_root, repo_id, queue):
138
  hand = {n: w.base_pos(d, n) for n in w.pieces}
139
  p, R = pinch()
140
  err = p - plan.grasp_point
141
- info = dict(kind=kind, trigger=st["trigger"], handover_s=round(st["handover"] / fps, 2), trigger_h_mm=round(1000 * trigger_h, 1),
142
  pinch_error_mm=[round(1000 * float(x), 1) for x in err])
143
- # The teacher takes over. After a failed grasp: open where it is, then rise clear.
144
  frames = 0
145
- if kind == "failed_grasp":
 
 
 
 
 
 
 
146
  from expert import Trajectory
147
 
148
  ex.speed = 1.0
@@ -163,7 +213,8 @@ def worker(k, quota, args, shard_root, repo_id, queue):
163
  for q, g, ph in zip(traj.q, traj.g, traj.phase):
164
  runner._step_frame(q, g, task, rec, ph, lambda phase: None)
165
  frames += len(traj)
166
- res = runner.run(task, int(rng.integers(2**62)), recorder=rec, look_s=args.look_s)
 
167
  whole = runner._judge(task, hand, watched, {}, frames + res.frames, 0.0)
168
  if not (res.success and whole.success):
169
  outcomes["teacher recovery failed: " + (res.reason or whole.reason).split(":")[0][:40]] += 1
@@ -199,6 +250,9 @@ def main():
199
  ap.add_argument("--seconds", type=float, default=14.0, help="policy time before giving up on a trigger")
200
  ap.add_argument("--look-s", type=float, default=0.5, help="teacher holds still above the piece this long")
201
  ap.add_argument("--pre-grasp-fraction", type=float, default=0.5)
 
 
 
202
  args = ap.parse_args()
203
  root = (ROOT / args.root).resolve()
204
  shards = root.parent / (root.name + "_shards")
@@ -256,7 +310,8 @@ def main():
256
  attempts = sum(s["attempts"] for s in summaries.values())
257
  summary = dict(episodes=offset, attempts=attempts, success_rate=round(offset / max(attempts, 1), 4),
258
  outcomes=dict(outcomes), minutes=round((time.time() - t0) / 60, 1), workers=n,
259
- policy=args.policy, look_s=args.look_s, config=cfg)
 
260
  (root / "phase2_summary.json").write_text(json.dumps(summary, indent=2))
261
  ds = LeRobotDataset("local/so101_chess_recovery", root=root)
262
  print(f"loaded {root}: {ds.num_episodes} episodes, {ds.num_frames} frames")
 
45
  MISALIGNED_M = 0.0025 # holds happen within about 1 mm, failures 4-6 mm off (grasp inspection)
46
 
47
 
48
+ def correction_pick(runner, task, plan, lift_first: bool):
49
+ """Style v2: the teacher's grasp from where the arm is, never rising to its approach
50
+ height and never pausing. Optionally reopen and lift just clear of the piece's top
51
+ (after a misaligned close), then line up sideways at that height (turning the jaws to
52
+ the expert's yaw, or the opposite one if closer), descend straight down, close. The
53
+ motion is collision-checked; returns a PickPlan, or None if no yaw works."""
54
+ import numpy as np
55
+
56
+ from expert import PickPlan, PlanningFailed, Trajectory, wrap
57
+
58
+ ex, d, w = runner.expert, runner.d, runner.w
59
+ q = d.qpos[ex.kin.qadr].copy()
60
+ g = float(d.qpos[runner.grip_qadr])
61
+ p, R = ex.kin.pose(q, plan.offset)
62
+ yaw_now = float(np.arctan2(R[1, 0], R[0, 0]))
63
+ ex._sync_planning(d, ignored=(task.target,))
64
+ vs = ex.e["vertical_speed"]
65
+ top = w.base_pos(d, task.target)[2] + w.height[w.kind[task.target]]
66
+ open_q = plan.grasp.open_q
67
+ for yaw in sorted((plan.yaw, plan.yaw + np.pi), key=lambda y: abs(wrap(y - yaw_now))):
68
+ try:
69
+ traj = Trajectory()
70
+ q1, p1, g1 = q, p, g
71
+ if lift_first:
72
+ ex._hold(traj, q, g, open_q, 0.3, "reopen")
73
+ p1 = np.r_[p[:2], max(p[2] + 0.005, top + 0.003)]
74
+ q1 = ex._cart_move(traj, q, p, p1, yaw_now, yaw_now, plan.offset, open_q, open_q, "clear", vs, 0.3, 1.0)
75
+ g1 = open_q
76
+ above = np.r_[plan.grasp_point[:2], p1[2]]
77
+ q2 = ex._cart_move(traj, q1, p1, above, yaw_now, yaw, plan.offset, g1, open_q, "align", vs, 0.3, 1.5)
78
+ q3 = ex._cart_move(traj, q2, above, plan.grasp_point, yaw, yaw, plan.offset, open_q, open_q, "descend",
79
+ vs, 0.3, 1.8)
80
+ ex._hold(traj, q3, open_q, open_q, 0.1, "descend")
81
+ if not ex._collision_free(traj):
82
+ raise PlanningFailed("collision")
83
+ ex._hold(traj, q3, open_q, ex.close_q, 0.45, "close")
84
+ ex._hold(traj, q3, ex.close_q, ex.close_q, 0.25, "close")
85
+ return PickPlan(traj, yaw, plan.grasp, plan.offset, plan.grasp_point, q3)
86
+ except PlanningFailed:
87
+ continue
88
+ return None
89
+
90
+
91
  def worker(k, quota, args, shard_root, repo_id, queue):
92
  import warnings
93
 
 
181
  hand = {n: w.base_pos(d, n) for n in w.pieces}
182
  p, R = pinch()
183
  err = p - plan.grasp_point
184
+ info = dict(kind=kind, style=args.style, trigger=st["trigger"], handover_s=round(st["handover"] / fps, 2), trigger_h_mm=round(1000 * trigger_h, 1),
185
  pinch_error_mm=[round(1000 * float(x), 1) for x in err])
186
+ # The teacher takes over.
187
  frames = 0
188
+ if args.style == "v2":
189
+ pick = correction_pick(runner, task, plan, lift_first=kind == "failed_grasp")
190
+ if pick is None:
191
+ outcomes["no collision-free correction"] += 1
192
+ rec.discard()
193
+ continue
194
+ res = runner.run(task, int(rng.integers(2**62)), recorder=rec, pick=pick)
195
+ elif kind == "failed_grasp": # v1: open where it is, rise clear, then plan a fresh pick
196
  from expert import Trajectory
197
 
198
  ex.speed = 1.0
 
213
  for q, g, ph in zip(traj.q, traj.g, traj.phase):
214
  runner._step_frame(q, g, task, rec, ph, lambda phase: None)
215
  frames += len(traj)
216
+ if args.style == "v1":
217
+ res = runner.run(task, int(rng.integers(2**62)), recorder=rec, look_s=args.look_s)
218
  whole = runner._judge(task, hand, watched, {}, frames + res.frames, 0.0)
219
  if not (res.success and whole.success):
220
  outcomes["teacher recovery failed: " + (res.reason or whole.reason).split(":")[0][:40]] += 1
 
250
  ap.add_argument("--seconds", type=float, default=14.0, help="policy time before giving up on a trigger")
251
  ap.add_argument("--look-s", type=float, default=0.5, help="teacher holds still above the piece this long")
252
  ap.add_argument("--pre-grasp-fraction", type=float, default=0.5)
253
+ ap.add_argument("--style", choices=["v1", "v2"], default="v2",
254
+ help="v1: the teacher replans from its approach height and pauses to look (made the policy "
255
+ "hover); v2: lines up from where the arm is and goes straight down, no pause")
256
  args = ap.parse_args()
257
  root = (ROOT / args.root).resolve()
258
  shards = root.parent / (root.name + "_shards")
 
310
  attempts = sum(s["attempts"] for s in summaries.values())
311
  summary = dict(episodes=offset, attempts=attempts, success_rate=round(offset / max(attempts, 1), 4),
312
  outcomes=dict(outcomes), minutes=round((time.time() - t0) / 60, 1), workers=n,
313
+ policy=args.policy, style=args.style, look_s=args.look_s if args.style == "v1" else 0.0,
314
+ config=cfg)
315
  (root / "phase2_summary.json").write_text(json.dumps(summary, indent=2))
316
  ds = LeRobotDataset("local/so101_chess_recovery", root=root)
317
  print(f"loaded {root}: {ds.num_episodes} episodes, {ds.num_frames} frames")
chess-sim/code/sim/episode.py CHANGED
@@ -236,9 +236,10 @@ class EpisodeRunner:
236
  mujoco.mj_step(self.m, self.d)
237
  monitor(phase)
238
 
239
- def run(self, task: Task, rng_seed: int, recorder=None, look_s: float = 0.0) -> Result:
240
  """Execute the primitive from the current (set-up) state. `look_s` holds the hand
241
- still above the piece, jaws open, before the descent (the wrist camera sees it)."""
 
242
  rng = np.random.default_rng(rng_seed)
243
  d, w = self.d, self.w
244
  start = {n: w.base_pos(d, n) for n in w.pieces}
@@ -262,7 +263,7 @@ class EpisodeRunner:
262
 
263
  frames = 0
264
  try:
265
- pick = self.expert.plan_pick(d, task.target, rng)
266
  except PlanningFailed as exc:
267
  return Result(False, f"plan {exc}")
268
  if look_s > 0:
 
236
  mujoco.mj_step(self.m, self.d)
237
  monitor(phase)
238
 
239
+ def run(self, task: Task, rng_seed: int, recorder=None, look_s: float = 0.0, pick=None) -> Result:
240
  """Execute the primitive from the current (set-up) state. `look_s` holds the hand
241
+ still above the piece, jaws open, before the descent (the wrist camera sees it).
242
+ `pick`: a ready PickPlan to execute instead of planning one."""
243
  rng = np.random.default_rng(rng_seed)
244
  d, w = self.d, self.w
245
  start = {n: w.base_pos(d, n) for n in w.pieces}
 
263
 
264
  frames = 0
265
  try:
266
+ pick = pick or self.expert.plan_pick(d, task.target, rng)
267
  except PlanningFailed as exc:
268
  return Result(False, f"plan {exc}")
269
  if look_s > 0:
chess-sim/code/sim/model_card.py CHANGED
@@ -5,6 +5,8 @@ facts given on the command line, and replaces the default card LeRobot pushed.
5
 
6
  Run: .venv/bin/python sim/model_card.py --repo-id Machanize/chess_phase_smolvla \
7
  --eval sim/reports/policy_eval/eval_results.json --episodes 2000 --frames 600000 --steps 20000 ...
 
 
8
  """
9
  from __future__ import annotations
10
 
@@ -163,8 +165,162 @@ normalisation. Pass the observations under the names listed above.
163
  """
164
 
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  def main():
167
  ap = argparse.ArgumentParser(description=__doc__)
 
168
  ap.add_argument("--repo-id", required=True)
169
  ap.add_argument("--eval", required=True)
170
  ap.add_argument("--episodes", required=True)
@@ -172,12 +328,13 @@ def main():
172
  ap.add_argument("--steps", required=True)
173
  ap.add_argument("--batch", required=True)
174
  ap.add_argument("--hours", required=True)
175
- ap.add_argument("--expert-success", required=True)
176
  ap.add_argument("--lerobot", default="0.4.4")
177
  ap.add_argument("--best-mm", dest="best_mm", default="-")
 
178
  ap.add_argument("--dry-run", action="store_true")
179
  a = ap.parse_args()
180
- text = card(a, json.loads(Path(a.eval).read_text()))
181
  if a.dry_run:
182
  print(text)
183
  return
 
5
 
6
  Run: .venv/bin/python sim/model_card.py --repo-id Machanize/chess_phase_smolvla \
7
  --eval sim/reports/policy_eval/eval_results.json --episodes 2000 --frames 600000 --steps 20000 ...
8
+ .venv/bin/python sim/model_card.py --kind baseline --repo-id Machanize/chess_phase_smolvla_baseline \
9
+ --eval sim/reports/baseline_eval/smolvla/eval_results.json --episodes 300 --frames 89008 ...
10
  """
11
  from __future__ import annotations
12
 
 
165
  """
166
 
167
 
168
+ VARIANTS = {
169
+ "baseline": dict(
170
+ front="base_model: lerobot/smolvla_base\ntags:\n- lerobot\n- smolvla",
171
+ intro="[SmolVLA](https://huggingface.co/lerobot/smolvla_base) trained to move a chess piece with an\n"
172
+ "**SO-101** arm in one fixed simulated scene (MuJoCo). It is the simple baseline of the\n"
173
+ "chess robot's \"hand\": first get reliable closed-loop success in the easiest setting, then add\n"
174
+ "variety back one change at a time. Trained fresh from `lerobot/smolvla_base`, not from the\n"
175
+ "earlier `Machanize/chess_phase_smolvla`.",
176
+ cams=" Fed to the model as `camera{n}`.", chunk=50,
177
+ data="`Machanize/playful`, folder `chess-sim/datasets/baseline_v1` (private): **{episodes} successful\n"
178
+ "episodes ({frames} frames)** of a scripted inverse-kinematics expert at 30 fps, about\n"
179
+ "{per_move} per move. The expert's start pose and speed vary slightly between episodes.",
180
+ train="From `lerobot/smolvla_base`, {steps} steps at batch {batch} on one RTX 4090 in {hours} h, LeRobot\n"
181
+ "{lerobot}, default SmolVLA settings (vision encoder frozen, action expert trained). Overhead and\n"
182
+ "wrist cameras are renamed to `camera1` and `camera2`.",
183
+ use="from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy\n"
184
+ "policy = SmolVLAPolicy.from_pretrained(\"{repo_id}\")"),
185
+ "r2": dict(
186
+ front="base_model: Machanize/chess_phase_smolvla_baseline\ntags:\n- lerobot\n- smolvla\n- dagger",
187
+ intro="[SmolVLA](https://huggingface.co/lerobot/smolvla_base) for moving a chess piece with an **SO-101**\n"
188
+ "arm in one fixed simulated scene (MuJoCo), fine-tuned on corrections of its own mistakes.\n"
189
+ "It continues from `Machanize/chess_phase_smolvla_baseline`, which found the marked piece\n"
190
+ "reliably but closed its jaws 4-6 mm off when it failed. The correction data (DAgger-style)\n"
191
+ "shows the scripted teacher taking over from the states that policy actually got into:\n"
192
+ "holding still above the piece to look through the wrist camera, lining up and grasping,\n"
193
+ "or, after a misaligned close, reopening, rising, looking and grasping again.",
194
+ cams=" Fed to the model as `camera{n}`.", chunk=50,
195
+ data="`Machanize/playful`, folders `chess-sim/datasets/baseline_v1` and\n"
196
+ "`chess-sim/datasets/baseline_recovery_v1` (private), merged: **{episodes} episodes ({frames}\n"
197
+ "frames)**. That is the baseline's 300 full expert demonstrations plus 120 corrections, in which\n"
198
+ "the baseline policy drove and the teacher took over just before the grasp (85) or the moment\n"
199
+ "the policy started closing more than 2.5 mm off (35). Only the teacher's part is recorded.",
200
+ train="From `Machanize/chess_phase_smolvla_baseline`, {steps} more steps at batch {batch} on one RTX 4090\n"
201
+ "in {hours} h, LeRobot {lerobot}, default SmolVLA settings (vision encoder frozen). Overhead and\n"
202
+ "wrist cameras are renamed to `camera1` and `camera2`.",
203
+ use="from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy\n"
204
+ "policy = SmolVLAPolicy.from_pretrained(\"{repo_id}\")"),
205
+ "act": dict(
206
+ front="tags:\n- lerobot\n- act",
207
+ intro="[ACT](https://huggingface.co/papers/2304.13705) (Action Chunking with Transformers) trained from\n"
208
+ "scratch to move a chess piece with an **SO-101** arm in one fixed simulated scene (MuJoCo).\n"
209
+ "It is the comparison for `Machanize/chess_phase_smolvla_baseline`: the same data, a\n"
210
+ "smaller policy without a vision-language model.",
211
+ cams="", chunk=100,
212
+ data="`Machanize/playful`, folder `chess-sim/datasets/baseline_v1` (private): **{episodes} successful\n"
213
+ "episodes ({frames} frames)** of a scripted inverse-kinematics expert at 30 fps, about\n"
214
+ "{per_move} per move. The expert's start pose and speed vary slightly between episodes.",
215
+ train="ACT from scratch (ResNet-18 image backbone pretrained on ImageNet), {steps} steps at batch\n"
216
+ "{batch} on one RTX 4090 in {hours} h, LeRobot {lerobot} defaults (chunks of 100 actions). The\n"
217
+ "camera keys are used as they are.",
218
+ use="from lerobot.policies.act.modeling_act import ACTPolicy\n"
219
+ "policy = ACTPolicy.from_pretrained(\"{repo_id}\")"),
220
+ }
221
+
222
+
223
+ def card_baseline(a, ev: dict) -> str:
224
+ s = ev["summary"]
225
+ v = VARIANTS[a.kind]
226
+ fill = dict(episodes=a.episodes, frames=a.frames, per_move=int(a.episodes) // 10, steps=a.steps, batch=a.batch,
227
+ hours=a.hours, lerobot=a.lerobot, repo_id=a.repo_id)
228
+ reach = s["reach"]
229
+ moves = "\n".join(f"| {k} | {v2['success_percent']}% | {v2['episodes']} |" for k, v2 in s["by"]["move"].items())
230
+ works = s["success_percent"] >= 80
231
+ notes = (Path(a.notes).read_text().strip() + "\n\n") if a.notes else ""
232
+ status = (f"**Status: works in simulation on its ten moves.** In a closed-loop test it completed "
233
+ f"{s['success_percent']}% of {s['episodes']} moves (details below)." if works else
234
+ f"**Status: not yet reliable.** In a closed-loop test it completed {s['success_percent']}% of "
235
+ f"{s['episodes']} moves (details below).")
236
+ name = a.repo_id.split("/")[-1]
237
+ return f"""---
238
+ library_name: lerobot
239
+ license: apache-2.0
240
+ pipeline_tag: robotics
241
+ {v['front']}
242
+ - so101
243
+ - chess
244
+ - robotics
245
+ - simulation
246
+ - pick-and-place
247
+ ---
248
+
249
+ # {name}
250
+
251
+ {v['intro']}
252
+
253
+ {status} It has not been run on a real arm.
254
+
255
+ ## What it does
256
+
257
+ - **Input:** two 640x480 camera images and the arm's joint positions, at 30 Hz.
258
+ - `observation.images.overhead`: a webcam 65 cm straight above the board, 44 degrees top to
259
+ bottom, the arm at the top edge of the image.{v['cams'].format(n=1)}
260
+ - `observation.images.wrist`: the official SO-101 wrist camera.{v['cams'].format(n=2)}
261
+ - The piece to move has a **red square with an opaque outline** drawn over its square; the
262
+ target square has a **blue** one. Both are drawn on the images before they reach the policy.
263
+ - `observation.state`: 5 arm joints in degrees and the gripper 0-100 (LeRobot's SO-101
264
+ follower units with `use_degrees=True`).
265
+ - The instruction is always "move the piece on the red square to the blue square".
266
+ - **Output:** the next joint targets in the same units, in chunks of {v['chunk']} steps.
267
+ - The training video was stored at high quality (H.264, CRF 18, full 4:4:4 colour), so the
268
+ markers keep their colour. For the closest match, pass live frames through the same encode
269
+ and decode (`training_look(image, 18, "yuv444p")` in the project's `sim/camera_effects.py`).
270
+
271
+ ## The scene (all fixed)
272
+
273
+ - Board with 25 mm squares, square to the robot and flush against its 6 cm deck; the robot
274
+ plays black. One Staunton set, black and white pieces, centred in their squares. White arm.
275
+ - Tray on the right, one table, the same two lamps, no clutter, a clean camera image.
276
+ - Ten moves from the start position: e7e5, d7d5, g8f6, b8c6, c7c5 (the robot's side) and e2e4,
277
+ d2d4, g1f3, b1c3, c2c4 (the far side). The start is the same every time and only the red and
278
+ blue squares change, so doing different moves correctly shows it reads the markers.
279
+
280
+ ## Test in simulation
281
+
282
+ {s['episodes']} closed-loop episodes, each a random one of the ten moves from seeds not used in
283
+ training. An episode counts as a success if the piece ends within 6 mm of the target square,
284
+ upright, and no other piece moved more than 2 mm. {s['seconds_limit']:.0f} s limit.
285
+
286
+ **Success: {s['success_percent']}%**
287
+
288
+ - Gripper within half a square of the marked piece: {reach['within_half_square_percent']}% of episodes
289
+ (median closest approach {reach['median_closest_mm']} mm).
290
+ - Marked piece lifted: {reach['lifted_percent']}%.
291
+
292
+ | move | success | episodes |
293
+ |---|---|---|
294
+ {moves}
295
+
296
+ {notes}## Training data
297
+
298
+ {v['data'].format(**fill)}
299
+
300
+ ## Training
301
+
302
+ {v['train'].format(**fill)}
303
+
304
+ ## Use
305
+
306
+ ```python
307
+ {v['use'].format(**fill)}
308
+ ```
309
+
310
+ Load the pre- and post-processors saved with the model using `make_pre_post_processors`. They
311
+ apply the training normalisation{" and rename the camera keys" if v['cams'] else ""}.
312
+
313
+ ## Limitations
314
+
315
+ - **Simulation only**, one scene, ten moves. Other moves, board positions, camera views,
316
+ lighting or piece sets are untested and expected to fail until the variety is added back.
317
+ - The overlay is required: without the red and blue squares it does not know what to move.
318
+ """
319
+
320
+
321
  def main():
322
  ap = argparse.ArgumentParser(description=__doc__)
323
+ ap.add_argument("--kind", choices=["varied", "baseline", "r2", "act"], default="varied")
324
  ap.add_argument("--repo-id", required=True)
325
  ap.add_argument("--eval", required=True)
326
  ap.add_argument("--episodes", required=True)
 
328
  ap.add_argument("--steps", required=True)
329
  ap.add_argument("--batch", required=True)
330
  ap.add_argument("--hours", required=True)
331
+ ap.add_argument("--expert-success", default="-")
332
  ap.add_argument("--lerobot", default="0.4.4")
333
  ap.add_argument("--best-mm", dest="best_mm", default="-")
334
+ ap.add_argument("--notes", help="markdown file inserted before the training data section")
335
  ap.add_argument("--dry-run", action="store_true")
336
  a = ap.parse_args()
337
+ text = (card if a.kind == "varied" else card_baseline)(a, json.loads(Path(a.eval).read_text()))
338
  if a.dry_run:
339
  print(text)
340
  return