Datasets:
ArXiv:
License:
Download code/modal_app.py from ggigelmo1/hopper-medium-v2-subsets: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/datasets/ggigelmo1/hopper-medium-v2-subsets/resolve/main/code/modal_app.py
- Command line
-
hf download hf://datasets/ggigelmo1/hopper-medium-v2-subsets/code/modal_app.py
-
curl -L -o modal_app.py https://huggingface.co/datasets/ggigelmo1/hopper-medium-v2-subsets/resolve/main/code/modal_app.py
18 kB
| """ | |
| modal_app.py — Modal orchestration for the StBR reproduction (arXiv:2610.38238). | |
| Reproduces StBR vs SPOT on D4RL hopper-medium-v2 trajectory-level subsets | |
| (25% / 10%, 5 seeds), running the AUTHORS' training scripts UNMODIFIED | |
| (StBR main.py, SPOT train_vae.py + main.py) via launch.py, whose only | |
| intervention is monkey-patching d4rl.qlearning_dataset to serve the subset. | |
| Usage (from any machine with the Modal token as env vars | |
| MODAL_TOKEN_ID / MODAL_TOKEN_SECRET, or `modal token set`): | |
| modal run modal_app.py --stage smoke # Step 1 gate | |
| modal run modal_app.py --stage full --seeds 0 # seed-0 wave (4 runs) | |
| modal run modal_app.py --stage full --seeds 1,2,3,4 # remaining seeds (16 runs) | |
| modal run modal_app.py --stage full --method spot --fraction 0.25 --seed 0 # rerun | |
| modal run modal_app.py --stage full --method spot --fraction 0.1 --seed 1 \ | |
| --vae_source official # labelled ablation | |
| Artifacts are written to a Modal Volume (stbr-repro-out) as | |
| /out/<run_id>/{train.log,results.json,subset_recipe/,runs/} | |
| and fetched with: modal volume get stbr-repro-out <remote> <local> | |
| Durability: the authors' `runs/` workdir is a symlink into the volume-mounted | |
| /out/<run_id>/runs, and a background thread commits the volume every 90 s — | |
| checkpoints, tensorboard eval logs and stdout logs survive crashes mid-training. | |
| Design notes: | |
| - The Modal function shim runs on the image's Python 3.11 (from_registry | |
| add_python; Modal 1.7 requires >=3.11). ALL training (StBR/SPOT/d4rl/mujoco-py) | |
| runs via subprocess with the absolute path /opt/conda/envs/stbr/bin/python | |
| (3.8.5, the authors' conda_env.yml pin). | |
| - PRIMARY PROTOCOL: SPOT's VAE is trained on the SAME trajectory subset | |
| (no data leak). ABLATION (labelled, vae_source='official'): SPOT uses the | |
| authors' official full-data pretrained VAE (rehosted from their Google Drive | |
| release into the dataset repo) — run_ids carry an _officialvae suffix. | |
| - SPOT has NO CPU variant: the authors' train_vae.py hardcodes device='cuda' | |
| (disclosed). StBR main.py is device-flexible, so StBR CPU runs are possible. | |
| - SPOT's authors' code contains a divergence kill switch (SPOT.py train(): | |
| `if Q.mean().item() > 1e4: exit(0)`); runs that hit it are reported as | |
| failed seeds, never silently replaced. | |
| - gym 0.18.3 caps Pillow<=8.2.0; imageio pinned to 2.9.0 (no pillow pin; the | |
| version the authors' `anaconda` metapackage shipped). Failed builds archived | |
| in the dataset repo logs/failed/. | |
| """ | |
| import modal | |
| APP_NAME = "stbr-repro" | |
| VOL_NAME = "stbr-repro-out" | |
| STBR_COMMIT = "c47ebe2bf1c4bc801a225c8b86ae00917e7e706a" | |
| SPOT_COMMIT = "4be91cce407e93a8631043328f868b1b7abb86ba" | |
| D4RL_COMMIT = "4aff6f8c46f62f9a57f79caa9287efefa45b6688" | |
| REPO_BASE = "https://huggingface.co/datasets/ggigelmo1/hopper-medium-v2-subsets/resolve/main" | |
| CODE_URL = REPO_BASE + "/code" | |
| OFFICIAL_VAE_URL = REPO_BASE + "/official_vae/vae_model_hopper_medium.pt" | |
| PY = "/opt/conda/envs/stbr/bin/python" | |
| # Same stack as code/Dockerfile (kept in lockstep deliberately). | |
| APP_IMAGE = ( | |
| modal.Image.from_registry("ubuntu:22.04", add_python="3.11") | |
| .apt_install("python3", "git", "curl", "wget", "bzip2", "ca-certificates", "build-essential", | |
| "pkg-config", "libgl1-mesa-dev", "libosmesa6-dev", "libglew-dev", | |
| "libglfw3", "libglfw3-dev", "patchelf", "libegl1") | |
| .run_commands( | |
| "mkdir -p /root/.mujoco && wget -q https://mujoco.org/download/mujoco210-linux-x86_64.tar.gz " | |
| "-O /tmp/mujoco210.tar.gz && tar -zxf /tmp/mujoco210.tar.gz -C /root/.mujoco/", | |
| "wget -q https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh " | |
| "-O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda", | |
| ) | |
| .run_commands( | |
| # newer conda requires accepting Anaconda's ToS for the `defaults` channel | |
| "/opt/conda/bin/conda tos accept --override-channels " | |
| "--channel https://repo.anaconda.com/pkgs/main --channel https://repo.anaconda.com/pkgs/r || true", | |
| "/opt/conda/bin/conda create -y -n stbr python=3.8.5", | |
| ) | |
| .run_commands( | |
| "/opt/conda/envs/stbr/bin/pip install --upgrade pip==24.0 setuptools==59.5.0 wheel==0.37.1", | |
| "/opt/conda/envs/stbr/bin/pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121", | |
| ) | |
| .run_commands( | |
| # core deps from the authors' conda_env.yml (+ imageio 2.9.0, see notes) | |
| "/opt/conda/envs/stbr/bin/pip install numpy==1.23.5 gym==0.18.3 'cython<3' mujoco-py==2.1.2.14 " | |
| "pyyaml==5.4.1 coolname==1.1.0 termcolor==1.1.0 tensorboard==2.7.0 protobuf==3.17.3 " | |
| "tqdm==4.61.2 imageio==2.9.0 h5py==3.8.0 click cloudpickle==1.6.0 pyglet==1.5.0 " | |
| "scipy matplotlib==3.7.5", | |
| # modern gymnasium + mujoco: Step-3 MP4 rendering ONLY, never used by training | |
| "/opt/conda/envs/stbr/bin/pip install gymnasium==0.29.1 mujoco==2.3.7 imageio-ffmpeg", | |
| f"/opt/conda/envs/stbr/bin/pip install --no-deps " | |
| f"git+https://github.com/rail-berkeley/d4rl.git@{D4RL_COMMIT}", | |
| ) | |
| .run_commands( | |
| # precompile mujoco-py (LD_LIBRARY_PATH inline: .env() is not visible at build time) | |
| "LD_LIBRARY_PATH=/root/.mujoco/mujoco210/bin:/usr/lib/x86_64-linux-gnu " | |
| f"{PY} -c \"import mujoco_py; print('mujoco-py OK', mujoco_py.__version__)\"", | |
| ) | |
| .env({ | |
| "LD_LIBRARY_PATH": "/root/.mujoco/mujoco210/bin:/usr/lib/nvidia:/usr/lib/x86_64-linux-gnu", | |
| "MUJOCO_PY_MUJOCO_PATH": "/root/.mujoco/mujoco210", | |
| "D4RL_SUPPRESS_IMPORT_ERROR": "1", | |
| }) | |
| ) | |
| out_volume = modal.Volume.from_name(VOL_NAME, create_if_missing=True) | |
| app = modal.App(APP_NAME) | |
| def do_run_training(method: str, fraction: float, seed: int, | |
| max_timesteps: int = 0, vae_iters: int = 100_000, | |
| hw_tag: str = "", vae_source: str = "subset") -> dict: | |
| """Shared body, called by the thin @app.function wrappers below.""" | |
| import glob | |
| import json | |
| import os | |
| import re | |
| import shutil | |
| import subprocess | |
| import threading | |
| import time | |
| def _vae_key(p): | |
| return int(p.rsplit("_", 1)[1].split(".")[0]) | |
| t0 = time.time() | |
| vae_tag = "_officialvae" if vae_source == "official" else "" | |
| run_id = f"{method}_f{fraction}_s{seed}" + (f"_{hw_tag}" if hw_tag else "") + vae_tag | |
| out_dir = f"/out/{run_id}" | |
| vae_dir = f"/out/vae_f{fraction}_s{seed}" | |
| os.makedirs(out_dir, exist_ok=True) | |
| os.makedirs("/root/code", exist_ok=True) | |
| os.makedirs("/root/repos", exist_ok=True) | |
| # pipeline code (launch.py / subset_loader.py) from the public dataset repo | |
| for f in ("launch.py", "subset_loader.py"): | |
| subprocess.run(["curl", "-fsSL", f"{CODE_URL}/{f}", "-o", f"/root/code/{f}"], check=True) | |
| # authors' repos at pinned commits | |
| repo_name = "StBR" if method == "stbr" else "SPOT" | |
| repo_dir = f"/root/repos/{repo_name}" | |
| if not os.path.isdir(repo_dir): | |
| subprocess.run(["git", "clone", "-q", | |
| "https://github.com/DarrenJum/StBR" if method == "stbr" | |
| else "https://github.com/thuml/SPOT", repo_dir], check=True) | |
| subprocess.run(["git", "-C", repo_dir, "checkout", "-q", | |
| STBR_COMMIT if method == "stbr" else SPOT_COMMIT], check=True) | |
| # Durability: point the authors' workdir (repo runs/) into the volume and | |
| # commit periodically, so checkpoints + eval logs survive a crash. | |
| runs_dir = os.path.join(repo_dir, "runs") | |
| vol_runs = os.path.join(out_dir, "runs") | |
| os.makedirs(vol_runs, exist_ok=True) | |
| if not os.path.exists(runs_dir): | |
| os.symlink(vol_runs, runs_dir) | |
| runs_is_linked = os.path.islink(runs_dir) | |
| stop_commit = threading.Event() | |
| def _commit_loop(): | |
| while not stop_commit.wait(90): | |
| try: | |
| out_volume.commit() | |
| except Exception as e: # keep training even if a commit hiccups | |
| print(f"[volume-commit] {type(e).__name__}: {e}", flush=True) | |
| committer = threading.Thread(target=_commit_loop, daemon=True) | |
| committer.start() | |
| def sh(cmd, log_name): | |
| with open(os.path.join(out_dir, log_name), "w") as fh: | |
| p = subprocess.run(cmd, shell=True, executable="/bin/bash", | |
| stdout=fh, stderr=subprocess.STDOUT) | |
| return p.returncode | |
| maxts = f" --max_timesteps {int(max_timesteps)}" if max_timesteps else "" | |
| rc, log_name = 0, "train.log" | |
| if method == "stbr": | |
| cmd = (f"{PY} /root/code/launch.py --repo {repo_dir} --entry main.py " | |
| f"--config configs/offline/hopper-medium.yml --method stbr " | |
| f"--fraction {fraction} --seed {seed}{maxts} --out {out_dir}") | |
| rc = sh(cmd, log_name) | |
| elif method == "spot": | |
| # SPOT needs a VAE. PRIMARY (subset): train train_vae.py on the SAME | |
| # subset; persist the checkpoint to the volume for rerun reuse. | |
| # ABLATION (official): use the authors' pretrained full-data VAE. | |
| os.makedirs("/root/repos/SPOT/models/vae_trained_models", exist_ok=True) | |
| official_path = "/root/repos/SPOT/models/vae_trained_models/vae_model_hopper_medium.pt" | |
| if vae_source == "official": | |
| subprocess.run(["curl", "-fsSL", OFFICIAL_VAE_URL, "-o", official_path], check=True) | |
| else: | |
| out_volume.reload() | |
| vi = f" --num_iters {int(vae_iters)}" if int(vae_iters) != 100_000 else "" | |
| vol_vae = sorted(glob.glob(f"{vae_dir}/vae_model_hopper_medium_b0.5_*.pt"), | |
| key=_vae_key) | |
| if not vol_vae: | |
| cmd = (f"{PY} /root/code/launch.py --repo {repo_dir} --entry train_vae.py " | |
| f"--method spot --fraction {fraction} --seed {seed} --out {vae_dir} " | |
| f"--extra_args --env hopper --dataset medium{vi}") | |
| rc = sh(cmd, "vae.log") | |
| if rc != 0: | |
| log_name = "vae.log" | |
| if rc == 0: | |
| if not vol_vae: | |
| repo_vae = sorted( | |
| glob.glob("/root/repos/SPOT/runs/train_vae/hopper_medium/*/model/" | |
| "vae_model_hopper_medium_b0.5_*.pt"), key=_vae_key) | |
| if not repo_vae: | |
| stop_commit.set() | |
| raise FileNotFoundError( | |
| "VAE training returned rc=0 but no checkpoint was found in " | |
| "/root/repos/SPOT/runs/train_vae/") | |
| os.makedirs(vae_dir, exist_ok=True) | |
| shutil.copy(repo_vae[-1], | |
| os.path.join(vae_dir, os.path.basename(repo_vae[-1]))) | |
| out_volume.commit() | |
| vol_vae = [os.path.join(vae_dir, os.path.basename(repo_vae[-1]))] | |
| shutil.copy(vol_vae[-1], official_path) | |
| if rc == 0: | |
| # policy training with the authors' main.py + their config | |
| cmd = (f"{PY} /root/code/launch.py --repo {repo_dir} --entry main.py " | |
| f"--config configs/offline/hopper-medium.yml --method spot " | |
| f"--fraction {fraction} --seed {seed}{maxts} --out {out_dir}") | |
| rc = sh(cmd, log_name) | |
| stop_commit.set() | |
| try: | |
| committer.join(timeout=10) | |
| except Exception: | |
| pass | |
| # (only needed if runs/ was NOT volume-linked, e.g. legacy layout) | |
| if not runs_is_linked and os.path.isdir(runs_dir): | |
| shutil.copytree(runs_dir, os.path.join(out_dir, "runs"), dirs_exist_ok=True) | |
| log_text = "" | |
| lp = os.path.join(out_dir, log_name) | |
| if os.path.exists(lp): | |
| log_text = open(lp, errors="replace").read() | |
| scores = re.findall(r"Evaluation over (\d+) episodes: ([0-9.]+)", log_text) | |
| sizes = re.findall(r"Dataset size: (\d+)", log_text) | |
| try: | |
| gpu_name = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], | |
| capture_output=True, text=True).stdout.strip() | |
| except Exception: | |
| gpu_name = "" | |
| result = { | |
| "run_id": run_id, "method": method, "fraction": fraction, "seed": seed, | |
| "vae_source": vae_source, | |
| "n_transitions": int(sizes[-1]) if sizes else None, | |
| "eval_history": [(int(a), float(b)) for a, b in scores], | |
| "final_score": float(scores[-1][1]) if scores else None, | |
| "best_score": max((float(b) for _, b in scores), default=None), | |
| "wall_sec": round(time.time() - t0, 1), | |
| "hardware": gpu_name or "cpu", | |
| "status": "completed" if rc == 0 else f"failed rc={rc}", | |
| "stbr_commit": STBR_COMMIT, "spot_commit": SPOT_COMMIT, | |
| "d4rl_commit": D4RL_COMMIT, | |
| "max_timesteps": int(max_timesteps) if max_timesteps else 1_000_000, | |
| "vae_iters": int(vae_iters), | |
| } | |
| with open(os.path.join(out_dir, "results.json"), "w") as fh: | |
| json.dump(result, fh, indent=2) | |
| out_volume.commit() | |
| print(json.dumps(result)) | |
| return result | |
| def run_training_t4(method: str, fraction: float, seed: int, | |
| max_timesteps: int = 0, vae_iters: int = 100_000, | |
| hw_tag: str = "t4", vae_source: str = "subset") -> dict: | |
| return do_run_training(method, fraction, seed, max_timesteps, vae_iters, hw_tag, vae_source) | |
| def run_training_cpu(method: str, fraction: float, seed: int, | |
| max_timesteps: int = 0, vae_iters: int = 100_000, | |
| hw_tag: str = "cpu", vae_source: str = "subset") -> dict: | |
| return do_run_training(method, fraction, seed, max_timesteps, vae_iters, hw_tag, vae_source) | |
| def render_videos(policy_repo: str, specs_json: str, gl: str = "egl") -> dict: | |
| """Record hopper rollout MP4s (10 s simulated time, offscreen MuJoCo gl=egl|osmesa) | |
| from the published checkpoints. Heavy lifting runs in the conda env via the | |
| subprocess render_rollout.py; this shim only orchestrates and returns the manifest.""" | |
| import subprocess | |
| import os | |
| import json | |
| import time | |
| t0 = time.time() | |
| os.makedirs("/root/code", exist_ok=True) | |
| os.makedirs("/root/repos", exist_ok=True) | |
| os.makedirs("/out/videos", exist_ok=True) | |
| for f in ("launch.py", "subset_loader.py", "render_rollout.py"): | |
| subprocess.run(["curl", "-fsSL", f"{CODE_URL}/{f}", "-o", f"/root/code/{f}"], check=True) | |
| for name, url, commit in ( | |
| ("StBR", "https://github.com/DarrenJum/StBR", STBR_COMMIT), | |
| ("SPOT", "https://github.com/thuml/SPOT", SPOT_COMMIT), | |
| ): | |
| repo_dir = f"/root/repos/{name}" | |
| if not os.path.isdir(repo_dir): | |
| subprocess.run(["git", "clone", "-q", url, repo_dir], check=True) | |
| subprocess.run(["git", "-C", repo_dir, "checkout", "-q", commit], check=True) | |
| log_path = f"/out/videos/render_log_{gl}.txt" | |
| with open(log_path, "w") as fh: | |
| p = subprocess.run( | |
| [PY, "/root/code/render_rollout.py", "--policy-repo", policy_repo, | |
| "--specs-json", specs_json, "--gl", gl], | |
| stdout=fh, stderr=subprocess.STDOUT) | |
| manifest = None | |
| mp = f"/out/videos/render_manifest_{gl}.json" | |
| if os.path.exists(mp): | |
| manifest = json.load(open(mp)) | |
| result = {"gl": gl, "rc": p.returncode, "wall_sec": round(time.time() - t0, 1), | |
| "manifest": manifest} | |
| print(json.dumps(result)) | |
| return result | |
| def main(stage: str = "smoke", | |
| method: str = "", fraction: str = "", seed: str = "", | |
| fractions: str = "0.25,0.1", seeds: str = "0,1,2,3,4", | |
| max_timesteps: int = 0, vae_iters: int = 100_000, | |
| vae_source: str = "subset"): | |
| if stage == "smoke": | |
| # Step 1 gate: 1 seed, 10% subset, short training (20k steps), full D4RL eval. | |
| # T4: StBR + SPOT (sequential); CPU: StBR only — SPOT's train_vae.py | |
| # hardcodes device='cuda' and cannot run CPU-only unmodified (disclosed). | |
| h3 = run_training_cpu.spawn("stbr", 0.10, 0, 20000, 100_000, "cpu") | |
| r1 = run_training_t4.remote("stbr", 0.10, 0, 20000, 100_000, "t4") | |
| r2 = run_training_t4.remote("spot", 0.10, 0, 20000, 100_000, "t4") | |
| r3 = h3.get() | |
| print("=== SMOKE RESULTS ===") | |
| for r in (r1, r2, r3): | |
| print(r) | |
| elif stage == "full": | |
| f_list = [float(x) for x in fractions.split(",")] | |
| s_list = [int(x) for x in seeds.split(",")] | |
| if method and fraction: | |
| # rerun / ablation: single or few (method, fraction, seed) combos | |
| s_ids = [int(x) for x in seed.split(",")] if seed else s_list | |
| jobs = [(method, float(fraction), s, max_timesteps, vae_iters, "t4", vae_source) | |
| for s in s_ids] | |
| results = run_training_t4.starmap(jobs, return_exceptions=True) | |
| for r in results: | |
| print("RUN_RESULT", r) | |
| return | |
| jobs = [(m, f, s, max_timesteps, vae_iters, "t4", "subset") | |
| for m in ("stbr", "spot") for f in f_list for s in s_list] | |
| print(f"Launching {len(jobs)} runs (max_containers=10 on the function)") | |
| results = list(run_training_t4.starmap(jobs, return_exceptions=True)) | |
| for r in results: | |
| print("RUN_RESULT", r) | |
| elif stage == "check": | |
| import subprocess | |
| print(subprocess.run(["modal", "volume", "ls", VOL_NAME], capture_output=True, text=True).stdout) | |
| else: | |
| raise SystemExit(f"unknown stage {stage}") | |