playful / chess-sim /code /sim /model_card.py
Ali-Uraish's picture
Add files using upload-large-folder tool
f064d1b verified
Raw History Blame Contribute Delete
17.5 kB
"""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()