File size: 17,485 Bytes
9ffd3e8
 
 
 
 
 
 
025ca56
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fad6045
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
fad6045
 
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fad6045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
025ca56
 
 
 
 
 
 
f064d1b
025ca56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
025ca56
9ffd3e8
 
 
 
 
 
 
025ca56
9ffd3e8
fad6045
025ca56
9ffd3e8
 
025ca56
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""Write and upload the model card (README.md) of the trained policy's Hub repo.

Reads the simulation test (eval_policy.py's eval_results.json) and the training
facts given on the command line, and replaces the default card LeRobot pushed.

Run:  .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 annotations

import argparse
import json
from pathlib import Path


def card(a, ev: dict) -> str:
    s = ev["summary"]
    rows = lambda key: "\n".join(f"| {k} | {v['success_percent']}% | {v['episodes']} |" for k, v in s["by"][key].items())
    return f"""---
library_name: lerobot
license: apache-2.0
base_model: lerobot/smolvla_base
pipeline_tag: robotics
tags:
- lerobot
- smolvla
- so101
- chess
- robotics
- simulation
- pick-and-place
---

# chess_phase_smolvla

[SmolVLA](https://huggingface.co/lerobot/smolvla_base) fine-tuned to move a chess piece with
an **SO-101** arm, trained entirely in simulation (MuJoCo). It is the "hand" of a
chess-playing robot: a separate "brain" chooses the move and marks it on the camera
images; this policy only has to move the marked piece.

**Status: first training run, not yet working.** In a closed-loop test in simulation it
completed {s['success_percent']}% of {s['episodes']} moves (details below). It learned the general
motion (reach into the board, descend, close, lift) but not how to find the marked piece in
new scenes. 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 fixed camera above the board, is fed to the model as `camera1`.
  - `observation.images.wrist`, the official SO-101 wrist camera, is fed as `camera2`.
  - The piece to move has a **translucent red square** drawn over its square. The target
    square, or the capture tray, has a **translucent blue square**. Both are drawn on the
    images before they reach the policy.
  - `observation.state`: 5 arm joints in degrees and the gripper 0-100. These are LeRobot's
    SO-101 follower 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 50 steps.
- **Important: the images must look like the training video.** Every training frame went
  through H.264 video (4:2:0 chroma, CRF 30). That washes out the small red and blue squares,
  and the policy looks for them in that washed-out form. Fed raw frames, it did not move at
  all; after the same encode and decode, it reaches for the board. Pass every live frame,
  from the simulator or a real camera, through the same round trip first. The
  `training_look()` function in the project's `sim/camera_effects.py` does this.

## Test in simulation

{s['episodes']} closed-loop episodes. Every one used a new random scene: board and tray
layout, lighting, colours, clutter and overhead camera view. None of these scenes were
seen in training, and every move was checked to be doable by the scripted expert. An
episode counts as a success if all three hold:
- the piece ends within 6 mm of the target square, or in the tray;
- it is upright;
- no other piece moved more than 2 mm.

Each episode had a {s['seconds_limit']:.0f} s limit.

**Success: {s['success_percent']}%**

What goes wrong:
- The arm reaches into the board and makes grasping motions, but over the wrong part of the
  board, often knocking neighbouring pieces.
- The closest attempt left the piece {a.best_mm} mm from its square.
- The most likely reasons:
  - **The squares are tiny.** A square is about 15 pixels in the overhead view and about 10
    after SmolVLA resizes the image to 512 px. Video compression washes it out further.
  - **The variety is extreme for 2,000 episodes.** The camera goes anywhere, and board sizes,
    angles and sides all vary.
  - **Training was short.** 20,000 steps is about 2 epochs, with the vision encoder frozen.

Next steps to try:
- Larger or outlined target markers.
- Frames stored at higher quality, or the same compression applied everywhere (it is already
  needed at test time).
- A narrower set of camera views first, then widening them.
- More steps, and fine-tuning the vision encoder too.

| piece | success | episodes |
|---|---|---|
{rows('piece')}

| destination | success | episodes |
|---|---|---|
{rows('destination')}

| side the robot plays | success | episodes |
|---|---|---|
{rows('robot_plays')}

| arm colour | success | episodes |
|---|---|---|
{rows('arm_colour')}

| main light | success | episodes |
|---|---|---|
{rows('key_light')}

## Training data

The data is **{a.episodes} successful episodes ({a.frames} frames)** of a scripted inverse-kinematics
expert, recorded at 30 fps. The expert passes {a.expert_success}% of its grasp validation across
random layouts. Failed episodes were discarded. Randomised in every episode:

- **Board and tray:** the board has 22-25 mm squares and a 6-22 mm border, and is 3-20 mm thick.
  The robot plays white or black. The board's angle and position vary within the arm's
  reach, and the tray varies in side, angle, size and colour.
- **Table:** it slides so that its edges and corners, with the floor below, come into view.
  It varies from matte to glossy, with varied floors and walls.
- **Lighting:** one to four lamps (window, ceiling, desk lamp and sun) at 2700-6500 K, from
  dim to bright, with and without shadows.
- **Colours:** the arm (white most often), the pieces and the board.
- **Clutter:** a laptop, a phone, a mug, a notebook, a pen and cables around the board.
- **Overhead camera:** placed anywhere a person would mount it at home, 35-80 cm above the
  board and up to 45 degrees from vertical, from any side except behind the robot, with a
  38-62 degree lens. The wrist and rover cameras vary only by small mounting errors.
- **Webcam effects:** auto-exposure, white balance, blur, noise, JPEG compression and vignetting.
- **Pieces and physics:** several Staunton piece sets scaled to the squares, pieces up to 3 mm
  off-centre, and varied piece mass and friction.

## Training

The base model is `lerobot/smolvla_base`, fine-tuned for {a.steps} steps at batch {a.batch} on one
RTX 4090 in {a.hours} h. It uses LeRobot {a.lerobot} with the default SmolVLA settings: the
vision encoder is frozen and only the action expert is trained.

## Use

```python
from lerobot.policies.smolvla.modeling_smolvla import SmolVLAPolicy
policy = SmolVLAPolicy.from_pretrained("{a.repo_id}")
```

Load the pre- and post-processors saved with the model using `make_pre_post_processors`.
They rename the camera keys to `camera1` and `camera2` and apply the training
normalisation. Pass the observations under the names listed above.

## Limitations

- **Simulation only.** Real-arm results will differ. Real demonstrations are the next step.
- **Board geometry.** The board must be 22-25 mm per square, flush against the robot's
  6 cm high base, and within reach. The capture tray must be beside it.
- **The overlay is required.** Without the red and blue squares on the images, the policy
  does not know what to move.
"""


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 model trained on the varied data.",
        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"] >= 80
    notes = (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 else
              f"**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: lerobot
license: apache-2.0
pipeline_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 to
    bottom, 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; the
    target 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-101
    follower 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 the
  markers keep their colour. For the closest match, pass live frames through the same encode
  and 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 robot
  plays 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 and
  blue 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 in
training. 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`. They
apply 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)
    ap.add_argument("--frames", required=True)
    ap.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
    from huggingface_hub import HfApi

    HfApi().upload_file(path_or_fileobj=text.encode(), path_in_repo="README.md", repo_id=a.repo_id,
                        repo_type="model", commit_message="Model card: training data and simulation test")
    print(f"card uploaded to https://huggingface.co/{a.repo_id}")


if __name__ == "__main__":
    main()