File size: 12,381 Bytes
189f97d
 
 
 
 
 
 
 
 
 
 
6c53210
 
189f97d
6c53210
189f97d
 
6c53210
 
8718ac4
6e335fd
 
 
 
cdd2807
 
189f97d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc155da
 
 
189f97d
cdd2807
 
189f97d
 
cdd2807
 
 
189f97d
 
6e335fd
cdd2807
 
 
189f97d
 
cdd2807
 
 
 
189f97d
 
 
 
 
 
 
 
 
 
 
 
 
6c53210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189f97d
 
6c53210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189f97d
 
 
 
 
 
6c53210
189f97d
 
 
 
6c53210
 
 
 
189f97d
 
 
 
6c53210
189f97d
 
 
 
 
 
6c53210
189f97d
 
 
 
1490101
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
"""
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.

Env-pin notes (see README "Deviations" in the dataset repo):
- gym 0.18.3 (authors' pin) caps Pillow<=8.2.0; imageio>=2.10.5 floors
  pillow>=8.3.2. Fix: imageio==2.9.0 — the last release without a pillow pin,
  and the version the authors' `anaconda` metapackage (py3.8.5, 2021) shipped.
- .env() variables are NOT visible inside Modal build steps, so the mujoco-py
  precompile sets LD_LIBRARY_PATH inline.
"""
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",
    )
    .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) -> 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}")