playful / chess-sim /code /sim /push_dataset.py
Ali-Uraish's picture
chess-sim: perturbed-teacher (DART) results: paired test, grasp traces, summary; code
749b1c8 verified
Raw History Blame Contribute Delete
15.9 kB
"""Upload phase 2 outputs into one folder of a Hugging Face dataset repo.
Everything goes under `--path-in-repo` (default `chess-sim`) and nothing outside
that folder is touched:
chess-sim/README.md what is here and how to load it
chess-sim/datasets/<name>/ the LeRobot dataset with phase2_episodes.jsonl and
phase2_summary.json (LeRobot's temporary images left out)
chess-sim/review/<name>.mp4 the review video, if the dataset folder has one
chess-sim/reports/ sim/reports/ (grasp validation)
chess-sim/code/ the sim/ code and assets that made the data, and pyproject.toml
LeRobot's own push_to_hub writes to the repo root and replaces its README, so the
folder is staged locally and sent with upload_large_folder, which only adds or
replaces files. Log in once first with `.venv/bin/hf auth login` (a token that can
write to the repo).
Run: .venv/bin/python sim/push_dataset.py --repo-id Machanize/playful --name pilot_60
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(HERE))
SKIP_DIRS = {"__pycache__", "renders", "reports", ".cache"}
def _place(src: Path, dst: Path):
dst.parent.mkdir(parents=True, exist_ok=True)
try:
os.link(src, dst) # same disk: no copy of a large dataset
except OSError:
shutil.copy2(src, dst)
def _tree(src: Path, dst: Path, skip=frozenset()):
for dirpath, dirnames, filenames in os.walk(src):
dirnames[:] = [n for n in dirnames if n not in skip]
for f in filenames:
if f == ".DS_Store":
continue
p = Path(dirpath) / f
_place(p, dst / p.relative_to(src))
NOTES = {
"pilot_60": "The first pilot: nominal board and tray, narrower lighting and camera variety. Kept for reference.",
"varied_2000": "Heavy randomisation (see *What varies*). Trained the first model, 0% in the sim test "
"(since deleted; report in `reports/policy_eval/`).",
"baseline_v1": "The simple baseline (see *Baseline scene*): one fixed scene and ten fixed opening moves. "
"Trains `Machanize/chess_phase_smolvla_baseline`.",
"baseline_recovery_v1": "Correction demonstrations in the baseline scene (see *Corrections*), first "
"attempt: the teacher rises and pauses before regrasping, which made the fine-tuned "
"policy hover (20%). Kept for reference; not used for training.",
"baseline_recovery_v2": "Correction demonstrations, second attempt (`collect_recovery.py --style v2`): the "
"teacher lines up from where the arm is, rising only as far as needed, and goes "
"straight down, with no pause. Fine-tuning the baseline on these plus baseline_v1 "
"lowered success (30% vs 51.7% on the same episodes: more pieces knocked over). "
"Kept for reference; not used.",
"baseline_dart_v1": "baseline_v1's 300 scenes (same episode seeds) with a perturbed teacher (see *Perturbed "
"teacher*): in about half the 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. A model trained fresh on it with the baseline recipe corrects on the way down and "
"closes more precisely (5.4 vs 6.6 mm); success 28.5% vs 25.5% on 200 paired scenes "
"(not significant), 17/40 vs 7/40 on the trace scenes (`reports/dart_eval/`). Checkpoint in "
"`experiments/dart/`.",
}
def _info(repo_id: str, folder: str, name: str) -> dict:
"""LeRobot's meta/info.json of a dataset already in the repo."""
from huggingface_hub import hf_hub_download
try:
return json.loads(Path(hf_hub_download(repo_id, f"{folder}/datasets/{name}/meta/info.json",
repo_type="dataset")).read_text())
except Exception:
return {}
def readme(repo_id: str, folder: str, name: str, dataset: Path) -> str:
"""The folder README: every dataset in it (those already uploaded plus this one)."""
from huggingface_hub import HfApi
try:
names = {Path(e.path).name for e in HfApi().list_repo_tree(repo_id, path_in_repo=f"{folder}/datasets",
repo_type="dataset")}
except Exception:
names = set()
names.add(name)
val_path = HERE / "reports" / "grasp_validation.json"
val = json.loads(val_path.read_text())["summary"] if val_path.exists() else {}
lines = [
"# chess-sim: SO-101 chess pick-and-place in simulation", "",
"Scripted-expert demonstrations of an SO-101 arm moving one chess piece from a square "
"to another square or into a capture tray, recorded in MuJoCo. Made for training SmolVLA "
"(phase 2 of the play-machanize project).", "",
"Every dataset is LeRobot v3.0 at 30 fps, 640x480 images, with the source square highlighted "
"red and the destination (square or tray) blue. `observation.state` and `action`: 5 arm joints in "
"degrees and the gripper 0-100 (LeRobot's SO-101 follower with `use_degrees=True`). One instruction "
"for every frame: \"move the piece on the red square to the blue square\". `phase2_episodes.jsonl` "
"has per-episode notes (seed, piece, squares, board, piece set, lighting, cameras).", "",
"## Datasets", "",
"| folder | episodes | frames | cameras | video | notes |", "|---|---|---|---|---|---|",
]
for n in sorted(names):
info = json.loads((dataset / "meta" / "info.json").read_text()) if n == name else _info(repo_id, folder, n)
cams = [k.split(".")[-1] for k, f in info.get("features", {}).items() if f.get("dtype") == "video"]
vid = next((f.get("info", {}) for f in info.get("features", {}).values() if f.get("dtype") == "video"), {})
video = f"{vid.get('video.codec', '?')} {vid.get('video.pix_fmt', '')}".strip()
lines.append(f"| `datasets/{n}/` | {info.get('total_episodes', '?')} | {info.get('total_frames', '?')} | "
f"{', '.join(cams) or '?'} | {video} | {NOTES.get(n, '')} |")
lines += ["", "`review/<name>.mp4`: random episodes of a dataset, read back through LeRobot. "
"`reports/`: expert validation, policy tests and diagnostics. `code/`: the simulation, expert "
"and export code that produced the data.", ""]
lines += ["## What varies (varied_2000)", "",
"- **Board and tray:** 22-25 mm squares, 6-22 mm border, 3-20 mm thick, pieces scaled to the "
"squares. The robot plays white or black. The board's angle and position vary within reach; "
"the tray varies in side, angle, size and colour.",
"- **Table:** slides so its edges and corners, with the floor, come into view. Matte to glossy "
"tables, with varied floors and walls.",
"- **Lighting:** one to four lamps (window, ceiling, desk lamp, sun), 2700-6500 K, dim to "
"bright, with and without shadows.",
"- **Colours:** the arm (white most often), the pieces and the board.",
"- **Clutter:** a laptop, phone, mug, notebook, pen and cables around the board.",
"- **Overhead camera:** anywhere a person would mount it (35-80 cm up, up to 45 degrees from "
"vertical, any side but behind the robot, 38-62 degree lenses). The wrist and rover cameras "
"vary only by small mounting errors.",
"- **Webcam look:** auto-exposure, white balance, blur, noise, JPEG and vignetting.",
"- **Video:** LeRobot's default encoding (H.264, CRF 30, 4:2:0 chroma), which washes out the "
"small red and blue squares.", ""]
if "baseline_v1" in names:
lines += ["## Baseline scene (baseline_v1)", "",
"Everything fixed, to get reliable closed-loop success before adding variety back one change "
"at a time (settings: `code/sim/phase2_baseline.toml`).", "",
"- The nominal board (25 mm squares) square to the robot and flush against its deck; the "
"robot plays black. Reference piece set, black and white pieces, white arm.",
"- Tray on the right, fixed table, the scene's window and ceiling lamps, no clutter.",
"- An overhead camera like the owner's (65 cm up, straight down, 44 degree lens, the arm at the "
"top edge) and the wrist camera, no mounting error, a clean webcam (no noise, blur or colour "
"effects, light JPEG).",
"- Ten opening moves from the start position: e7e5, d7d5, g8f6, b8c6, c7c5 (the robot's "
"side) and e2e4, d2d4, g1f3, b1c3, c2c4 (the far side).",
"- Markers with an opaque 2 px outline; pieces centred in their squares.",
"- Sharper video: H.264 at CRF 18 with full 4:4:4 chroma.", ""]
if "baseline_recovery_v1" in names:
lines += ["## Corrections (baseline_recovery_v1)", "",
"DAgger-style data in the baseline scene. The baseline policy "
"(`Machanize/chess_phase_smolvla_baseline`) drives; the scripted teacher takes over from "
"exactly where the arm is, and only the teacher's part is recorded. A grasp inspection had "
"shown the policy's jaws close 4-6 mm off the piece when it fails, against about 1 mm when "
"it holds. Handovers (`recovery.trigger` in `phase2_episodes.jsonl`):", "",
"- `pre_grasp`: the jaws, still open, come within 15-45 mm above the piece. The teacher "
"lines up above it, holds still 0.5 s (the wrist camera sees the piece between the jaws), "
"descends, grasps and finishes the move.",
"- `misaligned_close`: the policy starts closing more than 2.5 mm off. The teacher reopens, "
"rises clear, holds still 0.5 s to look, lines up, grasps and finishes.",
"- `failed_lift`: the jaws closed but the piece did not rise within 1.2 s. Same recovery.", "",
"Episodes where the piece had toppled or a neighbour had moved before the handover are "
"dropped, as are failed recoveries.", "",
"Fine-tuning the baseline on these plus baseline_v1 gave 20% (from 36.7%): in `pre_grasp` "
"and after a misaligned close the teacher first rises to its approach height and pauses, "
"and the policy learned to hover over pawns. The next attempt (`--style v2`) lines up from "
"where the arm is and goes straight down.", ""]
if "baseline_dart_v1" in names:
lines += ["## Perturbed teacher (baseline_dart_v1)", "",
"DART-style demonstrations (`PHASE2_PROFILE=baseline,dart`, `Expert.perturb_pick`). The plain "
"teacher always starts its descent exactly centred and goes straight down, so near the piece "
"its next action can be predicted from the joint state alone; the baseline policy's roughly "
"7 mm aiming error is never corrected on the way down.", "",
"- In about half the episodes the executed hand drifts sideways by a random 2-10 mm (any "
"direction) during the approach, holds the offset into the descent and returns to the plan "
"over 0.3-0.8 s, ending 4 mm above the target's top. Each offset is collision-checked with "
"the target included.",
"- The recorded `action` is the clean plan throughout; `observation.state` and the images "
"show the perturbed hand. The episodes therefore show \"from off-centre, command the centred "
"path\", and never an off-centre aim.",
"- Same 300 episode seeds as baseline_v1 (`--seeds-from`), so each episode repeats the same "
"scene, move and timing. `dart_offset_mm` in `phase2_episodes.jsonl` is the executed offset "
"(null when unperturbed).", "",
"Teacher validation, 100 scenes: 100% success perturbed and plain, no touches on the target "
"or its neighbours before the grasp (`reports/dart_teacher/`).", ""]
if val:
lines += [f"Expert validation (random layouts): {val['success_percent']}% of {val['trials']} trials "
f"(target above {val['target_percent']}%).", ""]
lines += [
"## Load", "",
"LeRobot expects a dataset at the top of a folder, so download it first (replace `<name>`):", "",
"```bash",
f"hf download {repo_id} --repo-type dataset --include \"{folder}/datasets/<name>/*\" --local-dir playful",
"```", "", "```python",
"from lerobot.datasets.lerobot_dataset import LeRobotDataset",
f"ds = LeRobotDataset(\"local/so101_chess_sim\", root=\"playful/{folder}/datasets/<name>\")",
"```", "",
]
return "\n".join(lines)
def push(repo_id: str, dataset: Path, name: str, folder: str = "chess-sim", delete_local: bool = False,
dry_run: bool = False) -> str:
from huggingface_hub import HfApi
with tempfile.TemporaryDirectory(dir=dataset.parent) as tmp:
stage = Path(tmp) / folder
_tree(dataset, stage / "datasets" / name, skip={"images", ".cache"})
videos = list(dataset.glob("review_*.mp4"))
for v in videos:
(stage / "datasets" / name / v.name).unlink()
_place(v, stage / "review" / f"{name}.mp4")
_tree(HERE / "reports", stage / "reports")
_tree(HERE, stage / "code" / "sim", skip=SKIP_DIRS)
_place(ROOT / "pyproject.toml", stage / "code" / "pyproject.toml")
(stage / "README.md").write_text(readme(repo_id, folder, name, dataset))
if dry_run:
files = [p for p in Path(tmp).rglob("*") if p.is_file()]
print((stage / "README.md").read_text())
print(f"{len(files)} files, {sum(p.stat().st_size for p in files) / 1e6:.1f} MB, for example:")
for p in sorted(files)[:: max(1, len(files) // 25)]:
print(" ", p.relative_to(tmp))
return "(dry run, nothing uploaded)"
HfApi().upload_large_folder(repo_id=repo_id, folder_path=tmp, repo_type="dataset")
if delete_local:
shutil.rmtree(dataset)
return f"https://huggingface.co/datasets/{repo_id}/tree/main/{folder}"
def main():
from episode import load_config
cfg = load_config()
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--repo-id", required=True, help="e.g. Machanize/playful")
ap.add_argument("--name", required=True, help="dataset folder name, e.g. pilot_60")
ap.add_argument("--root", default=cfg["dataset"]["root"])
ap.add_argument("--path-in-repo", default="chess-sim")
ap.add_argument("--delete-local", action="store_true", help="remove the local dataset after a successful upload")
ap.add_argument("--dry-run", action="store_true", help="stage and list the files, upload nothing")
args = ap.parse_args()
url = push(args.repo_id, (ROOT / args.root).resolve(), args.name, args.path_in_repo, args.delete_local,
args.dry_run)
print(f"uploaded to {url}")
if __name__ == "__main__":
main()