"""Run Phase 2 launcher jobs (experiments/lerobot/run.py) on Modal GPUs. Used for the GeCO reproduction (G0, G1). The image pins the laptop environment's exact packages (requirements.txt). Two volumes persist across runs: behavior-hf-cache /cache: HF_HOME (LIBERO dataset, SmolVLA/SmolVLM2 weights) and LIBERO assets behavior-results experiments/results (run folders, same layout as on the laptop) envs/modal/bin/modal run experiments/lerobot/modal/app.py::probe # GPU + MuJoCo rendering check envs/modal/bin/modal run experiments/lerobot/modal/app.py::smoke --run G1 # 20 steps + 1 episode envs/modal/bin/modal run --detach experiments/lerobot/modal/app.py::full --runs G0,G1 # survives the laptop sleeping envs/modal/bin/modal volume get behavior-results phase2/ experiments/results/phase2/ `full` trains each run in its own container, then evaluates each suite in its own container, all in parallel. """ from __future__ import annotations import os import subprocess from pathlib import Path import modal HERE = Path(__file__).resolve().parent REPO = "/repo" PY = "/usr/local/bin/python" image = ( modal.Image.debian_slim(python_version="3.12") .apt_install("git", "ffmpeg", "libegl1", "libgl1", "libgles2", "libglib2.0-0", "libosmesa6", "build-essential", "cmake") .uv_pip_install(requirements=[str(HERE / "requirements.txt")], extra_options="--index-strategy unsafe-best-match") .env({"MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl", "NVIDIA_DRIVER_CAPABILITIES": "all", "COURSE_PY": PY, "HF_HOME": "/cache/huggingface", "HF_HUB_ENABLE_HF_TRANSFER": "0", "TOKENIZERS_PARALLELISM": "false"}) .add_local_dir(str(HERE.parent), f"{REPO}/experiments/lerobot", ignore=["modal/__pycache__", "**/*.pyc"]) ) hf_cache = modal.Volume.from_name("behavior-hf-cache", create_if_missing=True) results = modal.Volume.from_name("behavior-results", create_if_missing=True) VOLS = {"/cache": hf_cache, f"{REPO}/experiments/results": results} app = modal.App("behavior-geco-repro", image=image) def _launch(args: list[str]) -> str: """Run run.py with args; stream its output; return the run folder name from its 'done:' line.""" os.makedirs(f"{REPO}/experiments/results/phase2", exist_ok=True) os.makedirs("/cache/libero", exist_ok=True) # LIBERO's asset download goes to ~/.cache/libero if not os.path.exists("/root/.cache/libero"): os.makedirs("/root/.cache", exist_ok=True) os.symlink("/cache/libero", "/root/.cache/libero") p = subprocess.Popen([PY, f"{REPO}/experiments/lerobot/run.py", *args], cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) folder = "" for line in p.stdout: print(line, end="", flush=True) if line.startswith("done:"): folder = Path(line.split(":", 1)[1].strip()).name rc = p.wait() hf_cache.commit() results.commit() if rc: raise RuntimeError(f"run.py {' '.join(args)} exited {rc}") return folder @app.function(cpu=8, memory=16384, volumes=VOLS, timeout=4 * 3600) def prefetch(): """Download the FULL LIBERO dataset (~33 GB), and the SmolVLA/SmolVLM2 weights into the cache volume once. With only an episode subset requested, LeRobot downloads part of the data files and then finds no rows for the selected episodes ("Instruction 'train' corresponds to no data"), so the full copy is required.""" code = ("from lerobot.datasets.lerobot_dataset import LeRobotDataset; d = LeRobotDataset('HuggingFaceVLA/libero');" "print('dataset', d.num_episodes, 'episodes', d.num_frames, 'frames', d.root);" "from huggingface_hub import snapshot_download as s;" "[print(r, s(r)) for r in ('lerobot/smolvla_base', 'HuggingFaceTB/SmolVLM2-500M-Video-Instruct')])") # LIBERO's simulator assets download on first use in run.py (importing libero here would prompt for a config) os.makedirs("/cache/libero", exist_ok=True) if not os.path.exists("/root/.cache/libero"): os.makedirs("/root/.cache", exist_ok=True) os.symlink("/cache/libero", "/root/.cache/libero") subprocess.run([PY, "-c", code], check=True) hf_cache.commit() print(subprocess.run(["du", "-sh", "/cache/huggingface", "/cache/libero"], capture_output=True, text=True).stdout) @app.function(gpu="L4", volumes=VOLS, timeout=1800) def probe(): """GPU, CUDA and headless MuJoCo rendering (EGL, then OSMesa) inside the image.""" print(subprocess.run(["nvidia-smi", "--query-gpu=name,memory.total,driver_version", "--format=csv"], capture_output=True, text=True).stdout) import torch print("torch", torch.__version__, "cuda", torch.cuda.is_available()) for gl in ("egl", "osmesa"): code = ("import mujoco;m=mujoco.MjModel.from_xml_string('" "');r=mujoco.Renderer(m,64,64);" "d=mujoco.MjData(m);mujoco.mj_forward(m,d);r.update_scene(d);print('render ok',r.render().mean())") out = subprocess.run([PY, "-c", code], capture_output=True, text=True, env=dict(os.environ, MUJOCO_GL=gl, PYOPENGL_PLATFORM=gl)) print(gl, "->", out.stdout.strip()[:200], "| stderr tail:", out.stderr.strip()[-120:]) @app.function(gpu="L40S", cpu=8, memory=32768, volumes=VOLS, timeout=6 * 3600) def train(run: str, extra: list[str] | None = None) -> str: return _launch([run, "--only", "train", *(extra or [])]) @app.function(gpu="L4", cpu=8, memory=32768, volumes=VOLS, timeout=6 * 3600) def evaluate(folder: str, phase: str, extra: list[str] | None = None) -> str: results.reload() _launch(["--resume-run", f"{REPO}/experiments/results/phase2/{folder}", "--only", phase, *(extra or [])]) return phase @app.function(gpu="L40S", cpu=8, memory=32768, volumes=VOLS, timeout=3600) def smoke_job(run: str) -> str: return _launch([run, "--smoke", "--max-retries", "1"]) @app.local_entrypoint() def smoke(run: str = "G1"): print("smoke folder:", smoke_job.remote(run)) @app.function(cpu=1, memory=1024, timeout=12 * 3600) def pipeline(runs: list[str], trials: int, steps: int) -> list[str]: """Runs on Modal, so the job survives the laptop sleeping: train all runs in parallel, then every (run, suite) evaluation in parallel. Each suite writes run.json's returncodes, so the last writer wins there; the results themselves (eval_/eval_info.json, ood_scores.json) are separate files and are what counts.""" extra = ["--trials", str(trials), "--steps", str(steps)] folders = list(train.map(runs, kwargs={"extra": extra})) print("trained:", folders, flush=True) jobs = [(f, f"eval_{s}") for f in folders for s in ("libero_goal", "libero_spatial")] # run.py SUITES (G runs) for phase in evaluate.starmap(jobs, return_exceptions=True): print("finished", phase, flush=True) return folders @app.function(cpu=1, memory=1024, timeout=12 * 3600) def eval_pipeline(folders: list[str]) -> list[str]: jobs = [(f, f"eval_{s}") for f in folders for s in ("libero_goal", "libero_spatial")] return [str(r) for r in evaluate.starmap(jobs, return_exceptions=True)] @app.local_entrypoint() def evals(folders: str): """Re-run only the evaluations of already-trained run folders (comma-separated names), e.g. after a crash.""" print("done:", eval_pipeline.remote(folders.split(","))) @app.local_entrypoint() def full(runs: str = "G0,G1", trials: int = 10, steps: int = 10_000): # Launch with `modal run --detach`: the pipeline runs remotely and keeps going if this client disconnects. print("all done:", pipeline.remote(runs.split(","), trials, steps)) @app.function(gpu="L4", cpu=8, memory=32768, volumes=VOLS, timeout=3 * 3600) def diagnose_job(g0: str, g1: str, frames: int, k_max: int, schedule: str = "a3", zero_pad: bool = False, sweep: str = "") -> str: """Offline GeCO diagnostics (experiments/lerobot/geco_diagnose.py) on dataset frames; no simulator.""" results.reload() r = f"{REPO}/experiments/results/phase2" tag = ("_smoke" if frames < 50 else "") + ("" if schedule == "a3" else f"_sched{schedule}") + ("_sweep" if sweep else "") out = f"{r}/{g1}/geco_diagnose{tag}.json" subprocess.run([PY, f"{REPO}/experiments/lerobot/geco_diagnose.py", "--g0", f"{r}/{g0}", "--g1", f"{r}/{g1}", "--frames", str(frames), "--k-max", str(k_max), "--schedule", schedule, *(["--zero-pad"] if zero_pad else []), *(["--sweep", sweep] if sweep else []), "--out", out], cwd=REPO, check=True) results.commit() return out @app.local_entrypoint() def diagnose(g0: str = "G0_20261130T222645Z", g1: str = "G1_20261130T222906Z", frames: int = 400, k_max: int = 100, schedule: str = "a3", zero_pad: bool = False, sweep: str = ""): print("wrote", diagnose_job.remote(g0, g1, frames, k_max, schedule, zero_pad, sweep)) @app.function(cpu=1, memory=1024, timeout=12 * 3600) def kmax_pipeline(folder: str, kmaxes: list[int], schedule: str = "a3") -> list[str]: tag = "" if schedule == "a3" else f"_{schedule}" jobs = [(folder, f"eval_{s}_k{k}{tag}", ["--geco-kmax", str(k), "--geco-schedule", schedule]) for k in kmaxes for s in ("libero_goal", "libero_spatial")] return [str(r) for r in evaluate.starmap(jobs, return_exceptions=True)] @app.local_entrypoint() def geco_kmax(folder: str = "G1_20261130T222906Z", kmaxes: str = "30,100", schedule: str = "a3"): """Closed-loop LIBERO evaluations of a trained GeCO run with other sampler settings (one container each).""" print("done:", kmax_pipeline.remote(folder, [int(k) for k in kmaxes.split(",")], schedule)) @app.function(cpu=1, memory=1024, timeout=12 * 3600) def resume_pipeline(folder: str, phases: list[str], extra: list[str] | None = None) -> list[str]: """Continue a run folder on Modal: training resumes from its last checkpoint (L40S), then the given eval phases run in parallel (L4). Finished phases are skipped by run.py. (No volume here: the worker functions reload it.)""" if "train" in phases: train_resume.remote(folder) jobs = [(folder, p, extra or []) for p in phases if p != "train"] return [str(r) for r in evaluate.starmap(jobs, return_exceptions=True)] @app.function(gpu="L40S", cpu=8, memory=32768, volumes=VOLS, timeout=6 * 3600) def train_resume(folder: str) -> str: results.reload() return _launch(["--resume-run", f"{REPO}/experiments/results/phase2/{folder}", "--only", "train"]) @app.local_entrypoint() def resume(folder: str, phases: str, extra: str = ""): """Fire-and-forget: `modal run --detach app.py::resume --folder G2_... --phases train,eval_libero_goal,...`. The job is spawned on Modal and this client returns at once, so a dropped laptop connection cannot stop it (on 2026-12-02 a "Deadline exceeded" in a waiting client stopped two detached apps).""" call = resume_pipeline.spawn(folder, phases.split(","), extra.split() if extra else []) print("spawned", call.object_id)