Files
ML-Porosity/operations/p6_supervisor.py
lamlvh f3c30517fa Add P6 benchmark code, locked protocol_bench, T2 study and lock inputs
- ml_porosity/benchmark/ runner, scripts 32-35, scripts/run_bench.sh;
  misspec= option in synth_d2 (default path reproduces P2r bit for bit).
- configs/protocol_bench.{yaml,sha256,lock.json} locked 29/10 14:39 UTC
  (sha256 aa763f0a...), configs/d2_synth_bench.yaml.
- The eight protocol_bench inputs force-added from outputs/ (warp prior,
  wavelets, horizon cache, budgets) so load_protocol() and summarize work
  after a fresh clone. The 102 P2r reference artifacts (1.4 GB of particle
  npz) are not in git; they are only checked by posterior/train stages.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.

Main S1 runs are still training at this commit; results follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 01:06:59 +00:00

177 lines
7.7 KiB
Python

#!/usr/bin/env python3
"""P6 run supervisor (outside the protocol_bench lock; launches only scripts/run_bench.sh).
Every CYCLE seconds it logs a GPU snapshot and, for each driver spec:
* a dead, unfinished driver is relaunched in the user's tmux server on the card with the most free
memory, workers = min(target, (free - RESERVE) / PER_WORKER); it waits if neither card has room;
* when a driver finishes, its workers go to the unfinished driver with the most remaining jobs
(restart with more workers, at most CAP_DRIVER; in-flight jobs of that driver are lost and redone).
Drivers resume by fingerprint, so restarts never change results. Other users' processes are never touched.
"""
import json, os, re, signal, subprocess, time
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
STATE = REPO / "logs" / "p6_supervisor_state.json"
CYCLE, RESERVE, PER_WORKER = 300, 2500, 1700 # s, MiB kept free for others, MiB per SMC worker (measured 1556)
W_TOTAL, CAP_DRIVER, CAP_CARD, MAX_RESTARTS, MIN_BOOST_JOBS = 36, 16, 24, 5, 10
SPECS = { # adopted drivers launched at 16:07 UTC 29/10
"p6_s2": dict(studies="S2", regimes="", stages="posterior train", device="cuda:1", workers=6, log="logs/bench_s2_cuda1.out"),
"p6_s1a": dict(studies="S1", regimes="R10 Rm5 R0", stages="posterior train", device="cuda:0", workers=5, log="logs/bench_s1a_cuda0.out"),
"p6_s1b": dict(studies="S1", regimes="R0h R10tb", stages="posterior train", device="cuda:1", workers=2, log="logs/bench_s1b_cuda1.out"),
"p6_s348": dict(studies="S3 S4 S8", regimes="", stages="train", device="cuda:0", workers=4, log="logs/bench_s348_cuda0.out"),
# 30/10 01:05 UTC: p6_s1b split into two disjoint regime drivers to use the freed CPUs/GPUs
"p6_s1b_r0h": dict(studies="S1", regimes="R0h", stages="posterior train", device="cuda:0", workers=14, log="logs/bench_s1b_r0h_cuda0.out"),
"p6_s1b_r10tb": dict(studies="S1", regimes="R10tb", stages="posterior train", device="cuda:1", workers=14, log="logs/bench_s1b_r10tb_cuda1.out"),
}
def log(msg):
print(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), msg, flush=True)
def sh(cmd):
return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout.strip()
def gpus():
out = sh("nvidia-smi --query-gpu=index,memory.free,memory.used,utilization.gpu --format=csv,noheader,nounits")
return {f"cuda:{r[0]}": dict(free=int(r[1]), used=int(r[2]), util=int(r[3]))
for r in (list(map(str.strip, l.split(","))) for l in out.splitlines())}
def alive(name):
return subprocess.run(["tmux", "has-session", "-t", name], capture_output=True).returncode == 0
def tail_info(path):
"""(last runlog line, last progress (stage, k, n)) of a driver log."""
try:
lines = (REPO / path).read_text(errors="replace").splitlines()[-4000:]
except FileNotFoundError:
return None, None
rl = next((l for l in reversed(lines) if l.startswith("[runlog]")), None)
pr = None
for l in reversed(lines):
m = re.match(r"\[(posterior|train):[^ ]+ (\d+)/(\d+)\]", l)
if m:
pr = (m.group(1), int(m.group(2)), int(m.group(3)))
break
return rl, pr
def finished(name, s):
if (REPO / "logs" / f"p6_done_{name}").exists():
return True
rl, _ = tail_info(s["log"])
return bool(rl and " ok exit 0 " in rl and "_bench_train_" in rl)
def remaining(s):
_, pr = tail_info(s["log"])
if pr is None:
return 10 ** 6
stage, k, n = pr
return (n - k) + (n if stage == "posterior" and "train" in s["stages"] else 0)
def descendants(pid):
kids = sh(f"pgrep -P {pid}").split()
return [int(k) for k in kids] + [d for k in kids for d in descendants(int(k))]
def stop(name):
pane = sh(f"tmux list-panes -t {name} -F '#{{pane_pid}}'")
pids = descendants(int(pane)) if pane.isdigit() else []
for p in pids:
try:
os.kill(p, signal.SIGTERM)
except ProcessLookupError:
pass
time.sleep(20)
for p in pids:
try:
os.kill(p, signal.SIGKILL)
except ProcessLookupError:
pass
subprocess.run(["tmux", "kill-session", "-t", name], capture_output=True)
def card_load(state, exclude=None):
load = {"cuda:0": 0, "cuda:1": 0}
for n, s in state.items():
if n != exclude and s.get("status") == "running":
load[s["device"]] += s["workers"]
return load
def launch(name, s, state, target):
g, load = gpus(), card_load(state, exclude=name)
best = None
for dev in sorted(g, key=lambda d: (load[d], -g[d]["free"])):
w = min(target, (g[dev]["free"] - RESERVE) // PER_WORKER, CAP_CARD - load[dev])
if w >= 1:
best = (dev, int(w))
break
if best is None:
log(f"{name}: no room (free {[g[d]['free'] for d in sorted(g)]} MiB); waiting")
s["status"] = "waiting"
return
dev, w = best
s["log"] = f"logs/bench_{name.replace('p6_', '')}_{dev.replace(':', '')}.out"
env = f"STUDIES='{s['studies']}' DEVICE={dev} WORKERS={w} MEM_GB=2" + (f" REGIMES='{s['regimes']}'" if s["regimes"] else "")
cmd = f"env {env} scripts/run_bench.sh {s['stages']} >> {s['log']} 2>&1 && touch logs/p6_done_{name}"
subprocess.run(["tmux", "new-session", "-d", "-s", name, "-c", str(REPO), cmd], check=True)
s.update(device=dev, workers=w, status="running")
log(f"{name}: launched on {dev} with {w} workers ({s['studies']} {s['regimes']}; log {s['log']})")
def main():
state = json.loads(STATE.read_text()) if STATE.exists() else {n: dict(s, status="running", restarts=0) for n, s in SPECS.items()}
log(f"supervisor start; specs {list(state)}")
while True:
g = gpus()
log("gpu " + " ".join(f"{d}: free {v['free']} used {v['used']} util {v['util']}%" for d, v in sorted(g.items()))
+ " | " + " ".join(f"{n}={s['status']}/{s['device']}x{s['workers']}/rem {remaining(s) if s['status'] != 'done' else 0}"
for n, s in state.items()))
newly_done = False
for n, s in state.items():
if s["status"] in ("done", "failed", "replaced"):
continue
if alive(n):
continue
if finished(n, s):
s["status"] = "done"
newly_done = True
log(f"{n}: finished")
elif s["restarts"] >= MAX_RESTARTS:
s["status"] = "failed"
log(f"{n}: dead after {MAX_RESTARTS} restarts; giving up (see {s['log']})")
else:
if s["status"] == "running":
s["restarts"] += 1
log(f"{n}: driver dead and unfinished (last runlog: {tail_info(s['log'])[0]}); restart {s['restarts']}")
launch(n, s, state, s["workers"] if s["status"] != "waiting" else SPECS[n]["workers"])
if newly_done:
running = {n: s for n, s in state.items() if s["status"] == "running" and alive(n)}
free = W_TOTAL - sum(s["workers"] for s in running.values())
cand = sorted(running, key=lambda n: -remaining(running[n]))
if free >= 2 and cand and remaining(running[cand[0]]) >= MIN_BOOST_JOBS:
n = cand[0]
s = running[n]
target = min(CAP_DRIVER, s["workers"] + free)
log(f"{n}: boosting {s['workers']} -> {target} workers ({remaining(s)} jobs remaining)")
stop(n)
s["status"] = "restarting"
launch(n, s, state, target)
STATE.write_text(json.dumps(state, indent=1))
if all(s["status"] in ("done", "failed", "replaced") for s in state.values()):
log("all drivers finished or failed; supervisor exits")
return
time.sleep(CYCLE)
if __name__ == "__main__":
main()