Download code/experiments/lerobot/run.py from herooooooooo/repro-generative-control-as-optimization: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/spaces/herooooooooo/repro-generative-control-as-optimization/resolve/main/code/experiments/lerobot/run.py
- Command line
-
hf download hf://spaces/herooooooooo/repro-generative-control-as-optimization/code/experiments/lerobot/run.py
-
curl -L -o run.py https://huggingface.co/spaces/herooooooooo/repro-generative-control-as-optimization/resolve/main/code/experiments/lerobot/run.py
18.5 kB
| #!/usr/bin/env python3 | |
| """Phase 2 launcher: one registry entry per run (Parts A–C), exact commands, one folder per run. | |
| python3 experiments/lerobot/run.py --list | |
| python3 experiments/lerobot/run.py A3 --dry-run # print the exact commands | |
| python3 experiments/lerobot/run.py A3 [--steps 10000] [--trials 10] [--suites libero_spatial,libero_object] | |
| python3 experiments/lerobot/run.py A3 --smoke # 20 train steps + 1 episode: plumbing check only | |
| Results: experiments/results/phase2/<RUN>_<UTC>/{run.json, train.log, train/, eval_<suite>/eval_info.json} | |
| Reduced protocol (default, chosen 2026-11-25): train on all 40 LIBERO tasks, 10k steps, evaluate libero_spatial + | |
| libero_object with 10 trials per task. Scale --steps/--trials/--suites up for the full protocol. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import shutil | |
| import subprocess | |
| import sys | |
| import time | |
| from datetime import UTC, datetime | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[2] | |
| HERE = Path(__file__).resolve().parent | |
| PY = Path(os.environ.get("COURSE_PY", ROOT / "envs/lerobot/.venv/bin/python")) # Modal: the image's python | |
| A = HERE / "assets" | |
| # smolvla_base was pre-trained with cameras camera1..3; LIBERO provides image (agentview) + image2 (wrist). | |
| # Same map at train and eval time; SmolVLA skips the absent camera3. (C5 trains from scratch: no rename needed.) | |
| RENAME = '--rename_map={"observation.images.image": "observation.images.camera1", "observation.images.image2": "observation.images.camera2"}' | |
| SMOL_BATCH = 16 # largest that fits full fine-tuning (C4) on 16 GB; kept equal for every SmolVLA run | |
| SMOL = ["--policy.type=smolvla", "--policy.pretrained_path=lerobot/smolvla_base", f"--batch_size={SMOL_BATCH}", RENAME] | |
| GOAL_EPISODES = "--dataset.episodes=" + json.dumps(json.loads((A / "libero_goal_episodes.json").read_text())).replace(" ", "") | |
| SUITES = {"G0": "libero_goal,libero_spatial", "G1": "libero_goal,libero_spatial"} # default otherwise: --suites | |
| # Actions executed per prediction at eval time, fixed for every run (B8 uses its own 26->20 rule). LeRobot's default | |
| # executes the whole 50-action chunk open-loop; HuggingFaceVLA/smolvla_libero used 1 (re-plan every step). Published | |
| # SmolVLA LIBERO numbers are sensitive to this, so it is recorded in run.json and kept equal across runs. | |
| EXEC_STEPS = 10 | |
| # id: (title, part, wrapper args, extra lerobot-train args, eval wrapper args, what it teaches) | |
| RUNS = { | |
| "A1": ("ACT (no language)", "A", [], ["--policy.type=act", "--batch_size=32"], [], | |
| "Action chunking + CVAE from scratch. No language input, so with 40 tasks it cannot know WHICH task."), | |
| "A2": ("Diffusion Policy (no language)", "A", [], ["--policy.type=diffusion", "--batch_size=32"], [], | |
| "DDPM denoising of action sequences from scratch; contrast with flow matching."), | |
| "A3": ("SmolVLA fine-tune (= B0 = C1)", "A", [], SMOL, [], | |
| "Small VLA: frozen SmolVLM2 + trained flow-matching expert; language-conditioned."), | |
| "B1": ("+ correlated noise", "B", ["--corr-noise", str(A / "libero_chunk_L.pt")], SMOL, | |
| ["--corr-noise", str(A / "libero_chunk_L.pt")], "Noise shaped like real action chunks (β=0.5)."), | |
| "B2": ("task ids instead of language", "B", ["--task-ids", str(A / "libero_task_ids.json")], SMOL, | |
| ["--task-ids", str(A / "libero_task_ids.json")], "Does the language path matter, or only task identity?"), | |
| "B3": ("+ stage token, stage head, voting tracker", "B", ["--stage", str(A / "libero_task_ids.json")], SMOL, | |
| ["--stage", str(A / "libero_task_ids.json")], | |
| "System 2: 5 equal-time stages per demo, a stage head on the VLM, 2-of-3 voting at run time."), | |
| "B4": ("+ FAST auxiliary loss (on C3: LM trainable)", "B", ["--fast-aux", str(A / "fast_tokenizer")], | |
| SMOL + ["--policy.freeze_vision_encoder=true", "--policy.train_expert_only=false"], [], | |
| "Teach the VLM to predict tokenised action chunks (weight 0.1). Compare with C3, not A3."), | |
| "B5": ("+ multi-sample flow matching K=8", "B", ["--multisample", "8"], SMOL, [], | |
| "8 noise/time draws per VLM pass: lower-variance gradients at small extra cost."), | |
| "B6": ("+ mixed-layer KV", "B", ["--kv-mix"], SMOL, ["--kv-mix"], | |
| "Expert attends to learned mixes of all VLM layers, not one layer each (identity init)."), | |
| "B7": ("+ correlated inpainting (eval only, reuses B1)", "B", None, None, | |
| ["--corr-noise", str(A / "libero_chunk_L.pt"), "--inpaint", str(A / "libero_chunk_L.pt")], | |
| "Pin the 4 actions the previous chunk planned next; correct the rest through Σ. Compare with B1."), | |
| "B8": ("+ action compression 26->20 (eval only, reuses A3)", "B", None, None, ["--compress", "26", "20"], | |
| "Execute 26 predicted actions in 20 steps: faster episodes; does success drop?"), | |
| "B9": ("+ gripper retry rule (eval only, reuses A3)", "B", None, None, ["--gripper-retry"], | |
| "LIBERO analogue of the correction rules: reopen after a grasp closed on nothing, then retry."), | |
| # Everything that composes on a frozen-VLM SmolVLA, the closest this course gets to the full PiBehavior recipe | |
| # (which replaced language with task embeddings, hence B2). Left out: B4 (needs the LM trainable and its own | |
| # forward; not yet merged with B3's) and B8 (a speed trick, not accuracy). | |
| "D1": ("PiBehavior-lite combined: B1+B2+B3+B5+B6 (train), B7+B9 (eval)", "D", | |
| ["--corr-noise", str(A / "libero_chunk_L.pt"), "--task-ids", str(A / "libero_task_ids.json"), | |
| "--multisample", "8", "--kv-mix", "--stage", str(A / "libero_task_ids.json")], SMOL, | |
| ["--corr-noise", str(A / "libero_chunk_L.pt"), "--task-ids", str(A / "libero_task_ids.json"), | |
| "--kv-mix", "--inpaint", str(A / "libero_chunk_L.pt"), | |
| "--stage", str(A / "libero_task_ids.json"), "--gripper-retry"], | |
| "All composable additions at once, as the winning entry used them. Compare with A3."), | |
| # Part G: GeCO reproduction (NeurIPS 2026, arXiv 2603.17834, Table 5). Both trained on LIBERO-Goal only (dataset | |
| # tasks 10-19); evaluated on libero_goal (in distribution) and libero_spatial (out of distribution). | |
| "G0": ("Goal-only SmolVLA, flow-matching-loss OOD score (GeCO baseline)", "G", [], SMOL + [GOAL_EPISODES], | |
| ["--fm-score"], "Baseline detector: one-sample flow-matching loss of the policy's own chunk."), | |
| "G1": ("Goal-only SmolVLA trained with GeCO, residual-norm OOD score", "G", ["--geco"], SMOL + [GOAL_EPISODES], | |
| ["--geco"], "Time-unconditional flow matching: expert actions are zeros of the field; ‖f‖ flags OOD."), | |
| "C2": ("train vision encoder, freeze LM", "C", ["--variant", "vision_only"], SMOL, [], | |
| "Do the robot's 'eyes' need adapting?"), | |
| "C3": ("train LM, freeze vision", "C", [], SMOL + ["--policy.freeze_vision_encoder=true", | |
| "--policy.train_expert_only=false"], [], | |
| "Does the 'reasoning' part need adapting?"), | |
| "C4": ("train everything", "C", [], SMOL + ["--policy.freeze_vision_encoder=false", | |
| "--policy.train_expert_only=false"], [], | |
| "Full fine-tune: most capacity, most risk of forgetting/overfitting."), | |
| "C5": ("no internet pre-training (VLM random init)", "C", [], | |
| # batch 8: from-scratch C5 at batch 16 exhausted 16 GB and spilled to shared memory (~94 s/step) in the | |
| # 2026-11-26 smoke check. Compare with C1-C4 per sample seen, not per step. | |
| ["--policy.type=smolvla", "--policy.load_vlm_weights=false", "--batch_size=8", | |
| "--policy.freeze_vision_encoder=false", "--policy.train_expert_only=false"], [], | |
| "What does web-scale pre-training buy? Same architecture from scratch."), | |
| } | |
| def ensure_libero_config(): | |
| """LeRobot's LIBERO package prompts interactively on first import unless config.yaml exists. Write the defaults.""" | |
| cfg_dir = ROOT / "envs/lerobot/libero_config" | |
| if (cfg_dir / "config.yaml").exists(): | |
| return | |
| pkg = subprocess.run([str(PY), "-c", "import importlib.util,os;print(os.path.dirname(importlib.util.find_spec('libero').origin))"], | |
| capture_output=True, text=True).stdout.strip().splitlines()[-1] + "/libero" | |
| cfg_dir.mkdir(parents=True, exist_ok=True) | |
| (cfg_dir / "config.yaml").write_text("\n".join(f"{k}: {pkg}/{v}" for k, v in [ | |
| ("assets", "assets"), ("bddl_files", "bddl_files"), ("benchmark_root", ""), ("datasets", "../datasets"), | |
| ("init_states", "init_files")]) + "\n") | |
| def prune_checkpoints(ckdir: Path): | |
| """Delete checkpoints older than the one `last` points to (each SmolVLA checkpoint is ~1.6 GB). | |
| Only older ones: a newer directory is a checkpoint LeRobot is still writing (it moves `last` after the save), | |
| and deleting it mid-save crashed training with a safetensors "No such file or directory" error.""" | |
| last = ckdir / "last" | |
| if not last.is_symlink(): | |
| return | |
| keep = int(last.resolve().name) | |
| for d in ckdir.iterdir(): | |
| if d.is_dir() and not d.is_symlink() and d.name.isdigit() and int(d.name) < keep: | |
| shutil.rmtree(d, ignore_errors=True) | |
| def execute(run, meta, cmds, wargs, max_retries, resume_train=False, only=None): | |
| # LIBERO asks an interactive question on first import unless a config exists; assets download on first use. | |
| gl = os.environ.get("MUJOCO_GL") | |
| env = dict(os.environ, MUJOCO_GL=gl if gl in ("egl", "osmesa") else "glx", | |
| DISPLAY=os.environ.get("DISPLAY", ":0"), LIBERO_CONFIG_PATH=str(ROOT / "envs/lerobot/libero_config")) | |
| for name, c in cmds: | |
| if only and name not in only: | |
| continue # Modal: training and each suite's eval run in separate containers | |
| if meta.get("returncodes", {}).get(name) == 0: | |
| continue # finished in an earlier launch | |
| attempt, rc = 0, None | |
| last = run / "train/checkpoints/last/pretrained_model/train_config.json" | |
| if name == "train" and resume_train and last.exists(): | |
| attempt, c = meta.get("attempts", {}).get(name, 1), [str(PY), str(HERE / "train_variant.py"), *wargs, | |
| "--", f"--config_path={last}", "--resume=true"] | |
| max_retries += attempt | |
| elif name != "train": | |
| shutil.rmtree(run / name, ignore_errors=True) # a partial eval from an earlier launch | |
| while True: | |
| with open(run / f"{name}.log", "a") as log: | |
| if attempt: | |
| log.write(f"\n===== retry {attempt} at {datetime.now(UTC):%Y-%m-%dT%H:%M:%SZ}: {' '.join(c)}\n") | |
| log.flush() | |
| proc = subprocess.Popen(c, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, env=env) | |
| while (rc := proc.poll()) is None: | |
| time.sleep(60) | |
| if name == "train": | |
| prune_checkpoints(run / "train/checkpoints") | |
| meta.setdefault("attempts", {})[name] = attempt + 1 | |
| if not rc or attempt >= max_retries: | |
| break | |
| attempt += 1 | |
| time.sleep(90) # let the GPU recover after a device fault | |
| if name == "train": | |
| last = run / "train/checkpoints/last/pretrained_model/train_config.json" | |
| if last.exists(): # resume from the newest checkpoint (LeRobot restores optimiser + step) | |
| c = [str(PY), str(HERE / "train_variant.py"), *wargs, "--", f"--config_path={last}", | |
| "--resume=true"] | |
| else: # crashed before the first checkpoint: start over in a clean directory | |
| shutil.rmtree(run / "train", ignore_errors=True) | |
| else: | |
| shutil.rmtree(run / name, ignore_errors=True) | |
| if name == "train": | |
| prune_checkpoints(run / "train/checkpoints") | |
| meta.setdefault("returncodes", {})[name] = rc | |
| (run / "run.json").write_text(json.dumps(meta, indent=2)) | |
| if rc: | |
| sys.exit(f"{name} failed (rc={rc}) after {attempt + 1} attempts; see {run / f'{name}.log'}") | |
| def geco_kmax_phases(cmds, kmaxes): | |
| """Extra GeCO evaluations of a trained G1 folder with K_max = k iterations (the paper's App. D uses 10): | |
| phase eval_<suite>_k<k>, the same command with --geco-kmax k and its own output folder.""" | |
| extra = [] | |
| for k in kmaxes: | |
| for name, c in cmds: | |
| if name.startswith("eval_") and "--geco" in c and "_k" not in name: | |
| i = c.index("--geco") | |
| c2 = c[:i + 1] + ["--geco-kmax", str(k)] + c[i + 1:] | |
| c2 = [f"{x}_k{k}" if x.startswith("--output_dir=") else x for x in c2] | |
| extra.append((f"{name}_k{k}", c2)) | |
| return extra | |
| def resume_run(run, max_retries, only=None, geco_kmax=()): | |
| meta = json.loads((run / "run.json").read_text()) | |
| wargs = RUNS[meta["run"]][2] | |
| cmds = list(meta["commands"].items()) | |
| known = {n for n, _ in cmds} | |
| cmds += [(n, c) for n, c in geco_kmax_phases(cmds, geco_kmax) if n not in known] | |
| meta["commands"] = dict(cmds) | |
| meta.setdefault("relaunches", []).append(f"{datetime.now(UTC):%Y-%m-%dT%H:%M:%SZ}") | |
| ensure_libero_config() # a fresh machine (a Modal eval container) has none: LIBERO would prompt and crash | |
| execute(run, meta, cmds, wargs, max_retries, resume_train=True, only=only) | |
| print("done:", run) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("run", nargs="?") | |
| ap.add_argument("--list", action="store_true") | |
| ap.add_argument("--steps", type=int, default=10_000) | |
| ap.add_argument("--trials", type=int, default=10, help="episodes per task") | |
| ap.add_argument("--suites", default=None, help="default libero_spatial,libero_object (G runs: goal,spatial)") | |
| ap.add_argument("--from-run", default=None, help="eval-only runs: folder of the finished run whose checkpoint " | |
| "is reused (B7: a B1 run, B8: an A3 run)") | |
| ap.add_argument("--seed", type=int, default=1000, help="training + eval seed (LeRobot default 1000)") | |
| ap.add_argument("--resume-run", default=None, help="continue an existing run folder: resume training from its " | |
| "last checkpoint, skip finished phases") | |
| ap.add_argument("--max-retries", type=int, default=8, help="resume training after a crash (WSL GPU faults)") | |
| ap.add_argument("--only", default=None, help="comma-separated phases to run (train, eval_<suite>); others skipped") | |
| ap.add_argument("--geco-kmax", default="", help="with --resume-run on a G1 folder: comma-separated K_max values; " | |
| "adds phases eval_<suite>_k<K> (GeCO sampler run for K iterations instead of 10)") | |
| ap.add_argument("--smoke", action="store_true") | |
| ap.add_argument("--dry-run", action="store_true") | |
| a = ap.parse_args() | |
| if a.resume_run: | |
| return resume_run(Path(a.resume_run).resolve(), a.max_retries, a.only and a.only.split(","), | |
| [int(k) for k in a.geco_kmax.split(",") if k]) | |
| if a.list or not a.run: | |
| for k, v in RUNS.items(): | |
| print(f"{k:3} [{v[1]}] {v[0]:48} {v[5]}") | |
| return | |
| title, part, wargs, targs, eargs, why = RUNS[a.run] | |
| steps, trials = (20, 1) if a.smoke else (a.steps, a.trials) | |
| suites = (a.suites or SUITES.get(a.run, "libero_spatial,libero_object")).split(",") | |
| suites = suites[:1] if a.smoke else suites | |
| tag = ("_smoke" if a.smoke else "") + (f"_s{a.seed}" if a.seed != 1000 else "") | |
| run = ROOT / "experiments/results/phase2" / f"{a.run}{tag}_{datetime.now(UTC):%Y%m%dT%H%M%SZ}" | |
| cmds = [] | |
| if targs is not None: | |
| cmds.append(("train", [str(PY), str(HERE / "train_variant.py"), *wargs, "--", | |
| "--dataset.repo_id=HuggingFaceVLA/libero", *targs, f"--steps={steps}", | |
| f"--save_freq={min(1000, steps)}", "--log_freq=50", f"--seed={a.seed}", | |
| f"--output_dir={run / 'train'}", | |
| "--policy.push_to_hub=false", f"--job_name={a.run}"])) | |
| ckpt = run / "train/checkpoints/last/pretrained_model" | |
| else: | |
| if not a.from_run and not a.dry_run: | |
| sys.exit(f"{a.run} is eval-only and needs --from-run <run folder> (B7: B1, B8/B9: A3)") | |
| ckpt = Path(a.from_run or "<source run>") / "train/checkpoints/last/pretrained_model" | |
| uses_rename = (targs is None) or (RENAME in targs) # B7/B8 reuse a SmolVLA checkpoint | |
| for s in suites: | |
| cmds.append((f"eval_{s}", [str(PY), str(HERE / "eval_variant.py"), *eargs, "--", f"--policy.path={ckpt}", | |
| *([RENAME] if uses_rename else []), | |
| *([] if a.run == "B8" else [f"--policy.n_action_steps={EXEC_STEPS}"]), | |
| # render at the dataset's 256x256 (LiberoEnv default is 360x360): Diffusion's | |
| # spatial-softmax encoder is size-fixed, and every policy then sees training-size images | |
| "--env.type=libero", "--env.observation_height=256", "--env.observation_width=256", | |
| f"--env.task={s}", f"--eval.n_episodes={trials}", f"--seed={a.seed}", | |
| "--eval.batch_size=1", *(["--env.task_ids=[0]"] if a.smoke else []), | |
| f"--output_dir={run / f'eval_{s}'}"])) | |
| if a.dry_run: | |
| for name, c in cmds: | |
| print(f"# {name}\n{' '.join(c)}\n") | |
| return | |
| run.mkdir(parents=True) | |
| ensure_libero_config() | |
| meta = {"run": a.run, "title": title, "part": part, "teaches": why, "steps": steps, "trials_per_task": trials, | |
| "suites": suites, "smoke": a.smoke, "seed": a.seed, "from_run": a.from_run, "eval_n_action_steps": None if a.run == "B8" else EXEC_STEPS, "commands": {n: c for n, c in cmds}, | |
| "label": {"A": "BASELINE_MODEL", "B": "PIBEHAVIOR_LITE_ABLATION", "C": "VLA_ANATOMY", | |
| "D": "PIBEHAVIOR_LITE_COMBINED", "G": "GECO_REPRO"}[part]} | |
| (run / "run.json").write_text(json.dumps(meta, indent=2)) | |
| execute(run, meta, cmds, wargs, a.max_retries, only=a.only and a.only.split(",")) | |
| print("done:", run) | |
| if __name__ == "__main__": | |
| main() | |