File size: 6,616 Bytes
b26bdfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Run the PiBehavior-lite ablation one job at a time (the "staged" plan), stoppable between jobs.

  python3 experiments/lerobot/run_queue.py [--wait-pid PID] [--only-smoke]
  touch experiments/results/phase2/STOP     # finish the current job, then stop (delete the file to resume)

Order: plumbing smoke checks of every new patch (minutes each), then ORDER (full runs ≈3 h each on a 4090
laptop, eval-only runs ≈1.2 h). A finished run is skipped; an unfinished run folder is resumed (--resume-run), so
the queue can simply be restarted after a stop or crash. A failed job is logged and the queue moves on; a GPU that
fails a tiny CUDA test (after a driver reset) stops the queue. Log: experiments/results/phase2/queue.log
"""
import argparse
import json
import os
import subprocess
import sys
import time
from datetime import UTC, datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
RES = ROOT / "experiments/results/phase2"
RUN = [sys.executable, str(ROOT / "experiments/lerobot/run.py")]
STOP = RES / "STOP"
LOG = RES / "queue.log"

SMOKES = ["B3", "B4", "B6"]                       # training-side patches, 20 steps + 1 episode
EVAL_SMOKES = [("B7", "A3"), ("B9", "A3")]        # eval-side patches on an existing checkpoint (plumbing only)
# Overnight order: B1 then B7 (which needs B1's checkpoint), the training ablations, then cheap eval-only runs.
ORDER = [("B1", None), ("B7", "B1"), ("B6", None), ("B3", None), ("C3", None), ("B4", None),
         ("B9", "A3"), ("B8", "A3")]
SEEDS = [("A3", 2000)]                            # second baseline seed: run-to-run noise
PY = ROOT / "envs/lerobot/.venv/bin/python"


def log(msg):
    line = f"{datetime.now(UTC):%Y-%m-%dT%H:%M:%SZ} {msg}"
    print(line, flush=True)
    with open(LOG, "a") as f:
        f.write(line + "\n")


def finished(run_id, smoke=False, seed=1000):
    """Newest completed (all return codes 0) folder for this run, or None."""
    best = None
    for d in sorted(RES.glob(f"{run_id}_*")):
        try:
            m = json.loads((d / "run.json").read_text())
        except (OSError, ValueError):
            continue
        rc = m.get("returncodes", {})
        if (m.get("smoke") == smoke and m.get("seed", 1000) == seed and rc
                and len(rc) == len(m.get("commands", {})) and not any(rc.values())):
            best = d
    return best


def unfinished(run_id, seed=1000):
    """Newest non-smoke folder for this run that has not completed (to resume instead of restarting)."""
    best = None
    for d in sorted(RES.glob(f"{run_id}_*")):
        try:
            m = json.loads((d / "run.json").read_text())
        except (OSError, ValueError):
            continue
        rc = m.get("returncodes", {})
        if not m.get("smoke") and m.get("seed", 1000) == seed and not (
                rc and len(rc) == len(m.get("commands", {})) and not any(rc.values())):
            best = d
    return best


def gpu_ok(tries=4, wait=300):
    """A tiny CUDA op in a fresh process. After a driver reset the GPU can stay unusable in WSL: then stop."""
    for i in range(tries):
        try:
            r = subprocess.run([str(PY), "-c", "import torch; print(torch.ones(2, device='cuda').sum().item())"],
                               capture_output=True, text=True, timeout=180)
            if r.returncode == 0 and "2.0" in r.stdout:
                return True
            why = f"rc={r.returncode} {r.stderr.strip()[-200:]}"
        except subprocess.TimeoutExpired:
            why = "timed out (hung driver)"
        log(f"GPU check failed ({i + 1}/{tries}): {why}")
        time.sleep(wait)
    return False


FAILED = []


def job(args, label, resume_seed=None):
    """Run one job; on failure log it and move on (run.py already retries crashes from checkpoints).
    A job whose run folder exists unfinished is resumed with --resume-run."""
    if STOP.exists():
        log(f"STOP file present: stopping before {label}")
        sys.exit(0)
    if not gpu_ok():
        log(f"GPU unusable: stopping the queue before {label} (restart Windows/WSL, then rerun this script)")
        sys.exit(2)
    if resume_seed is not None and (u := unfinished(args[0], resume_seed)) is not None:
        args = ["--resume-run", str(u)]
        label += f" (resume {u.name})"
    log(f"start {label}: {' '.join(args)}")
    rc = subprocess.run(RUN + args, cwd=ROOT).returncode
    log(f"end {label}: rc={rc}")
    # keep the model and sample videos of every finished run (hard links; see keep_artifacts.py)
    subprocess.run([sys.executable, str(ROOT / "experiments/lerobot/keep_artifacts.py")], cwd=ROOT,
                   stdout=subprocess.DEVNULL)
    if rc:
        FAILED.append(label)
        log(f"{label} failed: continuing with the next job (rerun the queue later to resume it)")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--wait-pid", type=int, default=None, help="start after this process exits (e.g. running A3)")
    ap.add_argument("--only-smoke", action="store_true")
    a = ap.parse_args()
    if a.wait_pid:
        log(f"waiting for pid {a.wait_pid}")
        while os.path.exists(f"/proc/{a.wait_pid}"):
            time.sleep(60)
    a3 = finished("A3")
    if a3 is None:
        log("A3 (baseline) has no finished run: run it first")
        sys.exit(1)
    for r in SMOKES:
        if not finished(r, smoke=True):
            job([r, "--smoke"], f"{r} smoke")
    for r, src in EVAL_SMOKES:
        if not finished(r, smoke=True):
            job([r, "--smoke", "--from-run", str(finished(src))], f"{r} smoke on {src}")
    if a.only_smoke:
        return
    for r, src in ORDER:
        if finished(r):
            continue
        if src is None:
            job([r], r, resume_seed=1000)
        elif (s := finished(src)) is not None:
            job([r, "--from-run", str(s)], f"{r} on {src}", resume_seed=1000)
        else:
            log(f"skip {r}: its source run {src} has not finished")
    for r, seed in SEEDS:
        if not finished(r, seed=seed):
            job([r, "--seed", str(seed)], f"{r} seed {seed}", resume_seed=seed)
    # D1 (all composable additions together): plumbing smoke first, the full run only if the smoke passed.
    if not finished("D1"):
        if not finished("D1", smoke=True):
            job(["D1", "--smoke"], "D1 smoke")
        if finished("D1", smoke=True):
            job(["D1"], "D1", resume_seed=1000)
        else:
            log("skip D1: its smoke run did not pass")
    log(f"queue complete; failed: {FAILED or 'none'}")


if __name__ == "__main__":
    main()