ggigelmo1's picture
Accept Anaconda ToS for defaults channel before conda create
dc155da verified
Raw History Blame Contribute Delete
11.5 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 # Step 2 (after OK)
modal run modal_app.py --stage full --method spot --fraction 0.25 --seed 0 # rerun
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>
GPU is set at the function definitions (T4 function + CPU function). Modal bills
per second of running time only; image builds are not billed.
"""
import modal
APP_NAME = "stbr-repro"
VOL_NAME = "stbr-repro-out"
STBR_COMMIT = "c47ebe2bf1c4bc801a225c8b86ae00917e7e706a"
SPOT_COMMIT = "4be91cce407e93a8631043328f868b1b7abb86ba"
D4RL_COMMIT = "4aff6f8c46f62f9a57f79caa9287efefa45b6688"
CODE_URL = "https://huggingface.co/datasets/ggigelmo1/hopper-medium-v2-subsets/resolve/main/code"
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")
.apt_install("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",
"/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",
"/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.31.1 h5py==3.8.0 click cloudpickle==1.6.0 pyglet==1.5.0 "
"scipy matplotlib==3.7.5 gymnasium==0.29.1 mujoco==2.3.7 imageio-ffmpeg huggingface_hub",
f"/opt/conda/envs/stbr/bin/pip install --no-deps "
f"git+https://github.com/rail-berkeley/d4rl.git@{D4RL_COMMIT}",
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) -> dict:
"""Shared body, called by the two thin @app.function wrappers below."""
import glob
import json
import os
import re
import shutil
import subprocess
import time
t0 = time.time()
run_id = f"{method}_f{fraction}_s{seed}"
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
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)
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 /root/repos/StBR --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":
# 1) VAE on the SAME subset (idempotent across runs via the volume)
out_volume.reload()
vi = f" --num_iters {int(vae_iters)}" if int(vae_iters) != 100_000 else ""
cands = glob.glob(f"{vae_dir}/runs/train_vae/hopper_medium/*/model/"
f"vae_model_hopper_medium_b0.5_*.pt")
if not cands:
cmd = (f"{PY} /root/code/launch.py --repo /root/repos/SPOT --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:
cands = sorted(glob.glob(f"{vae_dir}/runs/train_vae/hopper_medium/*/model/"
f"vae_model_hopper_medium_b0.5_*.pt"),
key=lambda p: int(p.rsplit("_", 1)[1].split(".")[0]))
os.makedirs("/root/repos/SPOT/models/vae_trained_models", exist_ok=True)
shutil.copy(cands[-1],
"/root/repos/SPOT/models/vae_trained_models/vae_model_hopper_medium.pt")
# 2) policy training with the authors' main.py + their config
cmd = (f"{PY} /root/code/launch.py --repo /root/repos/SPOT --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)
# collect the authors' own run dirs (args.json, tensorboard, checkpoints)
repo_name = "StBR" if method == "stbr" else "SPOT"
if os.path.isdir(f"/root/repos/{repo_name}/runs"):
shutil.copytree(f"/root/repos/{repo_name}/runs", 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,
"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,
"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
@app.function(image=APP_IMAGE, gpu="T4", cpu=4, timeout=10 * 3600,
volumes={"/out": out_volume}, max_containers=10, name="run-training-t4")
def run_training_t4(method: str, fraction: float, seed: int,
max_timesteps: int = 0, vae_iters: int = 100_000) -> dict:
return do_run_training(method, fraction, seed, max_timesteps, vae_iters)
@app.function(image=APP_IMAGE, gpu=None, cpu=4, timeout=10 * 3600,
volumes={"/out": out_volume}, max_containers=10, name="run-training-cpu")
def run_training_cpu(method: str, fraction: float, seed: int,
max_timesteps: int = 0, vae_iters: int = 100_000) -> dict:
return do_run_training(method, fraction, seed, max_timesteps, vae_iters)
@app.local_entrypoint()
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):
if stage == "smoke":
# Step 1 gate: 1 seed, 10% subset, short training (20k steps), full D4RL eval.
# GPU (T4) sequential StBR->SPOT; CPU variant spawned alongside for the
# CPU-vs-GPU cost/speed estimate in the report.
h3 = run_training_cpu.spawn("stbr", 0.10, 0, 20000, 100_000)
h4 = run_training_cpu.spawn("spot", 0.10, 0, 20000, 100_000)
r1 = run_training_t4.remote("stbr", 0.10, 0, 20000, 100_000)
r2 = run_training_t4.remote("spot", 0.10, 0, 20000, 100_000)
r3 = h3.get()
r4 = h4.get()
print("=== SMOKE RESULTS ===")
for r in (r1, r2, r3, r4):
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 a single failed run
jobs = [(method, float(fraction), int(seed), max_timesteps, vae_iters)]
results = run_training_t4.starmap(jobs, return_exceptions=True)
print([str(r) for r in results])
return
jobs = [(m, f, s, max_timesteps, vae_iters)
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}")