playful / chess-sim /code /sim /README.md
Ali-Uraish's picture
chess-sim: RL pilot summary and code (rl_env, rl_policy, rl_train, rl_check; eval_policy --fast/--expert-fp32)
d8e9a5e verified
|
Raw History Blame Contribute Delete
17.6 kB
# Simulation
MuJoCo scene for the SO-101 arm playing chess (Phase 1), and the scripted expert,
grasp validation, domain randomisation and LeRobot dataset export built on it
(Phase 2). No policy is trained here; that is Phase 3.
## Files
| File | Purpose |
|---|---|
| `make_scene.py` | Generates `chess_scene.xml` and the patched arm file. Board/robot layout parameters live at the top. |
| `scene_environment.py` | Finite worktable, room, robot enclosure, cables, camera stand, materials and trim. |
| `chess_scene.xml` | Generated. Do not edit by hand. |
| `render_scene.py` | Renders every camera to `renders/*.png`. |
| `check_reach.py` | Solves IK to every square and the bin using `--piece` grasp height. Kinematic reach only. |
| `prepare_chess_assets.py` | Rebuilds metre-scale visual/collision assets from vendored source STLs. Optional asset dependencies required. |
| `validate_scene.py` | Checks mesh scale, source hashes, collision fit at grasp sites, labels, and five seconds of stable settling. |
| `assets/chess/` | Detailed Staunton models, collision hulls, dimension/inertia manifest, and MIT attribution. See its README for calibration limits. |
| `assets/so101/so101_camera_upstream.xml` | Official SO-101 MJCF from TheRobotStudio/SO-ARM100, untouched except `meshdir`. |
| `assets/so101/so101.xml` | Generated patch: base raised onto the deck, `wrist` camera added, printed-part material finish adjusted. Meshes and mechanics retained. |
| `assets/environment/` | Vendored CC0 wood color maps and source attribution. |
| `prepare_gripper_assets.py` | Rebuilds the finger contact hulls in `assets/so101/collision/` (optional asset dependencies). |
| `prepare_arm_collision.py` | Rebuilds the convex-decomposition contact hulls of the bulky arm links in `assets/so101/collision/` (optional asset dependencies). |
| **Phase 2** | |
| `phase2_config.toml` | Every Phase 2 setting and randomisation range, in one file. |
| `kinematics.py` | IK: pinch point position, jaw yaw on the table, optional outward (or, negative, inward) tilt. |
| `grasp_geometry.py` | Exact jaw and piece profiles from the contact meshes; plans where the jaws close. |
| `chess_world.py` | Board, squares, tray and piece placement helpers. |
| `piece_sets.py` | Chess-set and board variants: piece size and proportions, square size, border, board thickness, tray size (make_scene.Layout), compiled with MjSpec. |
| `randomize.py` | Per-episode randomisation: board pose and side, tray, table position, lamps, colours, clutter and cables, cameras, masses, friction. |
| `camera_effects.py` | Webcam look on every image: auto-exposure, white balance, blur, noise, JPEG, vignetting. |
| `expert.py` | Scripted expert with collision-checked planning in a copy of the model. |
| `overlay.py` | Red source / blue destination squares drawn on camera images (sim and real). |
| `episode.py` | One episode: chess position, set-up, execution, success judgement. |
| `lerobot_export.py` | LeRobot v3.0 features and recorder. |
| `validate_expert.py` | Grasp validation over every piece on every square; writes `reports/`. |
| `generate_dataset.py` | Parallel dataset generation into LeRobot shards, merged at the end. `--seeds-from` repeats another dataset's episode seeds (same scenes, same order). |
| `review_video.py` | Side-by-side video of random dataset episodes, read back through LeRobot. |
| `make_train_view.py` | Training copy of a dataset with only the policy's cameras (overhead and wrist). |
| `eval_policy.py` | Closed-loop test of a trained policy in simulation: unseen random scenes, or `--scenes` to rebuild training episodes from `phase2_episodes.jsonl`; records reach, lift and success. |
| `phase2_baseline.toml` | Baseline settings profile, merged over `phase2_config.toml` with `PHASE2_PROFILE=baseline`: one fixed scene (overhead camera like the owner's, black and white pieces, white arm, fixed lamps, no clutter), outlined markers, 10 fixed moves, video at CRF 18 / 4:4:4. |
| `marker_test.py` | Marker dependence: same scene and start, red square moved over several pieces; does the gripper follow it? |
| `inspect_grasps.py` | Where the policy's jaws are when it starts closing, against the expert's grasp on the same piece. |
| `collect_recovery.py` | DAgger-style correction demonstrations: the policy drives, the scripted teacher takes over (before the grasp, at a misaligned close, after a failed lift) and only its part is recorded. `--style v2` lines up from where the arm is; `v1` (first attempt) replanned from the approach height with a pause and made the policy hover. |
| `phase2_dart.toml` | Perturbed (DART-style) teacher, merged after another profile (`PHASE2_PROFILE=baseline,dart`): in a share of episodes the executed approach drifts 2-10 mm off-centre and returns before the fingertips reach the piece, while the recorded actions stay the clean plan (`Expert.perturb_pick`). |
| `validate_dart.py` | The perturbed teacher against the plain one on the same scenes, without cameras: success, touches on the target before closing, contacts with neighbours. |
| `visual_probe.py` | Does the policy aim from the images? The teacher's hand frozen 40 and 20 mm above the piece, the piece moved 4 mm with the arm unchanged; how far each model's predicted grasp point follows it (1 = fully, 0 = ignores). Not yet run with a model. |
| `rl_env.py` | The simulator as an RL environment for a chunked policy: one step = one 50-frame chunk, scenes and success as eval_policy; VecChessEnv runs several in worker processes. |
| `rl_policy.py` | SmolVLA as a stochastic policy (ReinFlow noise at each denoising step), critic, stored prefixes, checkpoint with the baseline's processors. |
| `rl_train.py` | PPO fine-tuning over parallel simulators (per-element clipped ratios), validation curve, checkpoints. |
| `rl_check.py` | Checks before RL training: same as eval_policy, noise cost, likelihood, which weights change, save/reload. |
| `paired_compare.py` | Two `eval_policy.py` runs on the same scenes, paired by episode index: success, discordant scenes with an exact McNemar test, per piece and per move. |
| `train_policy.sh` / `train_act.sh` | SmolVLA (from the base model, or `BASE=` a checkpoint) and ACT training on the pod. |
| `reports/grasp_validation.md` | Latest validation report (and `.json` with every trial). |
## Scene layout (metres, arm base at origin, +x toward the human, +z up)
- Table: 120 x 80 x 4 cm wooden worktop on steel legs, centred at x=0.18. The top contact surface remains z=0; the room floor is z=-0.74. Pieces can now fall off the finite table.
- Rover deck: 20.8 x 18 x 6 cm fixed enclosure (x from -0.110 to 0.098) with an aluminum top plate, rubber feet, screws and ventilation details. Arm base sits at z=0.06. The front stops at the board's near edge: at 0.11 the board border ran under the deck and diagonal grasps on rank 8 put a finger over it. **The real rover body must not reach further forward than 9.8 cm from the arm axis below finger height.**
- Board: 20 cm playing area (8 x 2.5 cm squares) plus 1.2 cm border, centred at x = 0.21. Check per-piece reach with `check_reach.py`; this does not test approach collisions or grasp success.
- Robot plays black. Rank 8 is nearest the robot, file a on the robot's right (-y).
- Capture bin: 9 x 7 cm tray at (0.20, -0.18), with a visual felt liner and rounded rim. At the Phase 1 spot (0.13, -0.20) the forearm hit the rover camera stalk on 8 of 9 drop points.
- Rest pose (`home` keyframe and episode start/end): (0, -1.2, 0.95, 1.45, 0). The earlier pose put the gripper servo's contact hull inside the shoulder's.
- Physics timestep 1/600 s: exactly 20 steps per 30 fps frame. Piece contacts are stiff (solref 0.005, solimp 0.97/0.995) so the servo's full squeeze does not sink the jaws 2-3 mm into a piece.
- Fingers: each finger's single convex hull filled the gap between the jaws, so nothing could be pinched. `prepare_gripper_assets.py` replaces them with slab hulls that follow the real fingers within 0.01 mm; `validate_scene.py` checks this and that nothing else in the arm differs from upstream.
- Arm links: the single hulls of eight links were 1.7-4.3x the real part (wrist camera mount 4.3x, wrist motor holder 3.8x), so the folded arm "hit" itself in empty space. `prepare_arm_collision.py` replaces each with 12 CoACD convex pieces (now 1.05-1.7x, 96 hulls in all); `validate_scene.py` checks they contain every vertex of the real part, so they can be larger than the arm but never smaller. The STS3215 servos (1.1x) keep their single hull.
- Pieces: 32 free bodies named `w_pawn_e`, `b_king_e`, etc. Each has a `*_grasp` site at a narrow cross-section of its actual mesh. Heights range from 25.36 mm (pawn) to 46 mm (king), preserving the source proportions.
- Sites `sq_a1` … `sq_h8` on the board body give square centres; `board_center`, `bin_drop`.
## Cameras
| Name | Where | Role |
|---|---|---|
| `rover` | Camera stalk attached to the box's front-right corner; lens at (0.105, -0.14, 0.18), 90° vertical FOV, aimed at the board. | Rover-mounted board view; no external stand needed |
| `overhead` | Camera at (0.42, 0, 0.56), aimed at board centre; 40° vertical FOV. Supported by a table-mounted boom from (-0.16, 0.23). | Policy input 1, board reading between moves; all 64 square centres clear at home |
| `wrist` | On the official wrist camera mount, jaws at image bottom | Policy input 2, final approach |
| `side`, `human` | Fixed world cameras | Viewing only |
| `board_detail` | Closer fixed view of the board | Mesh inspection only |
| `scene` | Wide view including the table and camera rig | Scene inspection only |
Use `rover` + `wrist` for the rover camera pair. The `overhead` camera remains
available for stationary v1 setups. The new camera mount is a child of `rover_deck`,
so it moves with that platform; this scene still models a fixed platform, not rover
locomotion. Its stalk rises from the enclosure and offsets the lens 5 cm outboard
of the platform's right edge to avoid the parked arm. The housing and stalk have
collision geometry. The whole board and clearance for the pieces fit in frame;
pieces may occlude one another, and the moving arm can temporarily block the view.
`ROVER_CAMERA_POS` and `ROVER_CAMERA_FOV` are in `scene_environment.py`.
The view is written to `renders/rover.png`, with its pose in `renders/cameras.json`.
The overhead camera has **new extrinsics and FOV**, replacing the view that was
partly blocked by the arm. The wrist camera mounting transform is unchanged.
`render_scene.py` saves the actual camera poses, image dimensions and vertical FOV
to `renders/cameras.json`, using +x right, +y up, -z forward camera axes. The wrist
pose in that file is a snapshot after settling; it moves with the arm. Mirror the
overhead placement on the physical setup or replace it with measured calibration.
## Run
```
uv venv --python 3.11 .venv && uv pip install --python .venv/bin/python -e .
.venv/bin/python sim/make_scene.py # regenerate chess_scene.xml
.venv/bin/python sim/validate_scene.py # asset and settling checks
.venv/bin/python sim/check_reach.py --piece pawn # IK at pawn grasp height (also rook/knight/bishop/queen/king)
.venv/bin/python sim/render_scene.py # stills to sim/renders/
.venv/bin/python -m mujoco.viewer --mjcf sim/chess_scene.xml # interactive 3D viewer
```
Viewer note for macOS: launch the interactive viewer with plain `python`, not `mjpython`.
On this machine `mjpython -m mujoco.viewer` dies with `RuntimeError: Caught an unknown exception!`
inside `_Simulate` (seen with MuJoCo 3.2.7, 3.3.7 and 3.13.0 on macOS 26). `mjpython` is only
needed for `mujoco.viewer.launch_passive`, and offscreen rendering does not work under `mjpython`.
In the viewer, the `home` keyframe folds the arm and places all pieces.
After regenerating the scene, close and reopen any existing viewer to load the new assets.
Rendering also writes `all_views.png`, `board_detail.png`, `scene.png`, `piece_lineup.png`,
and `cameras.json`. These are direct MuJoCo renders without image enhancement.
The contact hulls use geom group 3; leave that group disabled in training cameras.
The scene uses matte surfaces and explicit ambient/key/fill lights. Infinite
mirror reflections were removed. Small hardware/cable/liner details are visual
approximations and do not introduce flexible-cable or felt contact physics.
The classic MuJoCo renderer uses Phong shading and hard shadow maps; this is a
more detailed training environment, not a scanned replica of a measured room.
## Phase 2: expert, validation, dataset
```
uv pip install --python .venv/bin/python -e '.[dataset]' # lerobot 0.4.4, python-chess
.venv/bin/python sim/validate_expert.py --workers 14 # ~25 min on the 4090 pod (14 CPU), writes sim/reports/
.venv/bin/python sim/generate_dataset.py --episodes 100 --overwrite # pilot, into data/so101_chess_sim
.venv/bin/python sim/review_video.py --episodes 10 # data/so101_chess_sim/review_10_episodes.mp4
.venv/bin/python sim/push_dataset.py --repo-id Machanize/playful --name pilot_60 # into chess-sim/ of the repo
```
Heavy runs go on a Runpod GPU pod (RTX 4090): set `MUJOCO_GL=egl` for headless GPU
rendering and pass `--workers` to match the pod's CPU quota.
**Primitive.** One episode moves one piece: rest, above source, descend, close, lift,
carry, above destination, descend, open, retreat, rest. A capture is two episodes,
the first into the tray. Joint targets at 30 Hz with minimum-jerk timing.
**Grasp.** Gripper straight down. The fingers form a V opening upward, so with the
tips just below a piece's head the jaws close on the head, as a person pinches it:
pawn head, rook turret, bishop mitre, queen and king upper-body collar, knight head
from the sides. If the squeeze slips, the head rests on the tips. Heights are
fractions of piece height (`[grasp] tip_fraction`), so they follow every piece set.
**Jaw direction.** Along a board diagonal where the fingers have most room, else
along a rank or file (needed on rank 8 beside the deck); knights across the head.
**Planning.** Every trajectory is checked frame by frame in a copy of the model with
clearances: 2 mm arm to pieces and 4 mm carried piece to pieces while moving
sideways, 1-1.5 mm during slow vertical moves, 1.5 mm to fixed obstacles, 0.5 mm arm
to arm. The carry follows the height each point of the path needs. Over the far
ranks, where straight-down reach runs out, the fingertips lean outward by the least
tilt that clears (up to 20 degrees); grasps and releases stay straight down (except the
near-base fallbacks below). After the
grasp and again after the lift, the expert reads where the piece actually sits in the
hand and plans from that.
**Near the arm base.** Ranks 7-8 are 8.5-14 cm from the pan axis, where the folded arm
can bring the wrist camera or the jaw into the shoulder for real, not only through
bulky hulls. When every normal option fails, the expert tries, in order: jaw yaws
22.5 degrees off the diagonals and axes; a carry that leans the fingertips 10 or 20
degrees inward (toward the base) where it passes within 13-17 cm of the pan axis; and
a grasp leaning 10 or 20 degrees inward. A piece grasped at a lean hangs at that lean,
so it is set down with the wrist roll and lean that stand it upright again (only two
yaws per destination can do that). Moves that succeed without these are unchanged.
**Episodes.** Random legal positions (0-70 random plies), a legal move of the side to
move or (15%) any piece to any empty square, captures as tray moves half the time,
captured pieces lying in the tray. Pieces up to 3 mm off-centre, randomly turned,
knights facing the opponent within 25 degrees. Everything else in `phase2_config.toml`.
**Variety (phase 2b).** Every 25 episodes a new board and tray (22-25 mm squares, 6-22 mm
border, 3-20 mm thick, tray size and rim) with pieces scaled to the squares; boards the
arm cannot serve even square and flush against the deck are redrawn. Every episode:
the robot plays white half the time (board turned round); board angle and position and
the tray's side, angle and position are redrawn until every square and the tray's drop
area are in reach (big boards end up nearly square, small ones turn up to about 10
degrees); the table slides so edges and corners, with the floor in view, come up often;
one to four of six lamps (window, ceiling, desk lamp, sun; 2700-6500 K, dim to bright,
shadows); table (matte to glossy), floor, wall, board, piece, arm (white most often),
deck and tray colours; a laptop, phone, mug, notebook, pen and up to two cables around
the board; the overhead camera anywhere a person would mount it (35-80 cm above the
board, up to 45 degrees from vertical, any side but behind the robot, 38-62 degree
lenses), checked so the whole board and tray are in frame and the resting arm hides no
square; and a webcam look on every image (`camera_effects.py`). The rover and wrist
cameras only get remounting errors.
**Recording.** Each episode is simulated without cameras first; only successes are
replayed from the same seed with rendering, which MuJoCo reproduces exactly. Frames:
`observation.images.{overhead,rover,wrist}` 640x480 with the red and blue squares,
`observation.state` and `action` in LeRobot SO-101 units (arm joints in degrees as with
`use_degrees=True`, gripper 0-100 over its range), and the instruction
"move the piece on the red square to the blue square". `phase2_episodes.jsonl` next to
the dataset records each episode's move, piece set and randomisation.