File size: 18,012 Bytes
189f97d
 
 
 
 
 
 
 
 
 
 
1e2b067
 
6c53210
264d929
 
189f97d
ab58fa5
189f97d
 
1e2b067
 
 
8718ac4
ab58fa5
 
 
 
 
264d929
 
 
 
ab58fa5
 
264d929
 
 
ab58fa5
 
 
189f97d
 
 
 
 
 
 
 
264d929
 
 
189f97d
 
 
 
587d29a
f7a4395
189f97d
 
 
 
 
 
 
 
 
dc155da
 
 
189f97d
cdd2807
 
189f97d
 
cdd2807
 
 
189f97d
 
6e335fd
cdd2807
 
 
189f97d
 
cdd2807
 
 
 
189f97d
 
 
 
 
 
 
 
 
 
 
 
 
6c53210
ab58fa5
264d929
ab58fa5
6c53210
 
 
 
 
 
1e2b067
6c53210
 
ab58fa5
 
 
6c53210
264d929
 
6c53210
 
 
 
 
 
 
 
 
 
1e2b067
 
 
 
264d929
1e2b067
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c53210
 
 
 
 
 
 
 
 
 
1e2b067
6c53210
 
 
 
264d929
 
 
 
 
 
 
 
 
 
 
 
ab58fa5
264d929
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e2b067
6c53210
189f97d
 
6c53210
1e2b067
 
 
 
 
 
 
 
 
6c53210
 
 
 
 
 
 
 
 
 
 
 
 
 
264d929
6c53210
 
 
264d929
6c53210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab58fa5
264d929
 
6c53210
 
 
 
 
ab58fa5
264d929
 
189f97d
 
5822cb5
 
 
e869711
 
 
 
5822cb5
e869711
5822cb5
 
e869711
5822cb5
 
e869711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5822cb5
 
7ee8a45
189f97d
 
 
264d929
 
189f97d
 
ab58fa5
 
 
 
 
189f97d
 
ab58fa5
6c53210
189f97d
 
 
 
264d929
 
 
 
6c53210
264d929
 
189f97d
264d929
189f97d
264d929
6c53210
189f97d
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
"""
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


@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,
                    hw_tag: str = "t4", vae_source: str = "subset") -> dict:
    return do_run_training(method, fraction, seed, max_timesteps, vae_iters, hw_tag, vae_source)


@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,
                     hw_tag: str = "cpu", vae_source: str = "subset") -> dict:
    return do_run_training(method, fraction, seed, max_timesteps, vae_iters, hw_tag, vae_source)


@app.function(image=APP_IMAGE, gpu="T4", cpu=4, timeout=3600,
              volumes={"/out": out_volume}, max_containers=10, name="render-video-t4")
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


@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,
         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}")