File size: 9,358 Bytes
b16b327 | 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 | """What a job handler gets: its config, a lease-fenced writer to its repo, a work dir and a deadline."""
from __future__ import annotations
import json
import os
import shutil
import signal
import subprocess
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from .hub import JobHandle, LeaseLost
from .io import append_jsonl
SECRET_MARKERS = ("TOKEN", "KEY", "SECRET", "PASSWORD")
NOT_SECRET = {"TOKENIZERS_PARALLELISM"}
def is_secret_name(name: str) -> bool:
return name.upper() not in NOT_SECRET and any(m in name.upper() for m in SECRET_MARKERS)
class PhaseFailed(Exception):
"""A phase subprocess exited non-zero."""
class OutOfTime(Exception):
"""Not enough session time left to start the next unit of work. The job pauses."""
class PhaseTimeout(OutOfTime):
"""A phase ran past its time limit. The job pauses, and its time estimate should grow."""
def __init__(self, msg: str, elapsed: float):
super().__init__(msg)
self.elapsed = elapsed
@dataclass
class Session:
id: str
user: str
start: float
deadline: float
hub: str
ops_repo: str
work: Path
gen_python: str
n_gpus: int
code_sha: str
env_dir: Path | None = None
def time_left(self) -> float:
return self.deadline - time.time()
def secret_values() -> list[str]:
return [v for k, v in os.environ.items() if is_secret_name(k) and len(v) >= 8]
def scrub_env(env: dict[str, str]) -> dict[str, str]:
return {k: v for k, v in env.items() if not is_secret_name(k)}
@dataclass
class JobContext:
job_id: str
config: dict[str, Any]
handle: JobHandle
session: Session
state: dict[str, Any] = field(default_factory=dict)
def __post_init__(self) -> None:
self.work = self.session.work / self.job_id
self.repo_dir = self.work / "repo"
self.logs = self.work / "logs"
for d in (self.work, self.repo_dir, self.logs):
d.mkdir(parents=True, exist_ok=True)
self._env_committed = False
def log(self, msg: str) -> None:
stamp = time.strftime("%H:%M:%S")
line = f"[{stamp} {self.job_id}] {msg}"
print(line, flush=True)
with open(self.logs / "job.log", "a", encoding="utf-8") as f:
f.write(line + "\n")
def time_left(self) -> float:
return self.session.time_left()
def require_time(self, seconds: float, what: str) -> None:
if self.time_left() < seconds:
raise OutOfTime(f"{what} needs ~{seconds / 60:.0f} min, {self.time_left() / 60:.0f} min left")
def check_lease(self) -> None:
if self.handle.lost.is_set():
raise LeaseLost(self.job_id)
def fetch(self, patterns: list[str]) -> Path:
return self.handle.store.download(patterns, self.repo_dir, revision=self.handle.head)
def read_json(self, path: str, default: Any = None) -> Any:
return self.handle.read_json(path, default)
def commit(self, files: dict[str, Any], message: str, state: dict[str, Any] | None = None,
deletes: list[str] | None = None) -> None:
"""Write files and an updated state.json in one atomic, lease-fenced commit."""
adds: dict[str, Path | bytes] = {}
for path, value in files.items():
if isinstance(value, (dict, list)):
adds[path] = json.dumps(value, indent=2).encode()
elif isinstance(value, str):
adds[path] = value.encode()
else:
adds[path] = value
new_state = None
if state is not None:
new_state = {**self.state, **state, "updated": time.time(), "code_sha": self.session.code_sha}
adds["state.json"] = json.dumps(new_state, indent=2).encode()
env_files = not self._env_committed and self.session.env_dir and self.session.env_dir.exists()
if env_files:
for p in sorted(self.session.env_dir.iterdir()):
if p.is_file():
adds[f"env/{self.session.id}/{p.name}"] = p
self.handle.commit(adds, f"{self.job_id}: {message}", deletes=deletes)
if new_state is not None:
self.state = new_state
if env_files:
self._env_committed = True
def metric(self, row: dict[str, Any]) -> Path:
path = self.repo_dir / "metrics.jsonl"
append_jsonl(path, {"time": time.time(), "session": self.session.id, "user": self.session.user,
"code_sha": self.session.code_sha, **row})
return path
def run(self, cmd: list[str], name: str, timeout: float, env: dict[str, str] | None = None,
secret_free: bool = False) -> None:
self.run_many([(cmd, env or {})], name, timeout, secret_free)
def run_many(self, procs: list[tuple[list[str], dict[str, str]]], name: str, timeout: float,
secret_free: bool = False) -> None:
"""Run phase subprocesses side by side (one per GPU). Kill them all if the lease is lost,
the time limit passes or any of them fails."""
timeout = min(timeout, self.time_left())
if timeout <= 60:
raise OutOfTime(f"no time left to run {name}")
base_env = {**os.environ}
if secret_free:
base_env = scrub_env(base_env)
base_env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(Path(__file__).resolve().parent.parent),
base_env.get("PYTHONPATH", "")]))
free_leftover_gpu_memory(self.log)
self.log(f"start {name} x{len(procs)}: {' '.join(procs[0][0][:5])} ... (limit {timeout / 60:.0f} min)")
t0 = time.time()
logs = [self.logs / (f"{name}.log" if len(procs) == 1 else f"{name}.{i}.log") for i in range(len(procs))]
handles = [open(p, "ab") for p in logs]
group = {"start_new_session": True} if os.name == "posix" else {}
running = [subprocess.Popen(cmd, env={**base_env, **env}, stdout=h, stderr=subprocess.STDOUT, **group)
for (cmd, env), h in zip(procs, handles, strict=True)]
last_echo = t0
try:
while True:
codes = [p.poll() for p in running]
failed = [i for i, c in enumerate(codes) if c not in (None, 0)]
if failed:
i = failed[0]
raise PhaseFailed(f"{name} (process {i}) exited {codes[i]}; last lines:\n{tail(logs[i], 25)}")
if all(c == 0 for c in codes):
break
now = time.time()
if self.handle.lost.is_set():
raise LeaseLost(self.job_id)
if now - t0 > timeout:
raise PhaseTimeout(f"{name} hit its time limit after {(now - t0) / 60:.0f} min", now - t0)
if now - last_echo > 300:
self.log(f"{name} running {(now - t0) / 60:.0f} min: {tail(logs[0])}")
last_echo = now
time.sleep(5)
finally:
for p in running:
kill_group(p)
for h in handles:
h.close()
self.log(f"done {name} in {(time.time() - t0) / 60:.1f} min")
def free_leftover_gpu_memory(log) -> None:
"""The runner itself never touches CUDA, so any process holding GPU memory before a phase starts
is a leftover from an earlier phase. Kill it, so the next phase gets the whole GPU."""
if os.name != "posix" or not shutil.which("nvidia-smi"):
return
out = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"],
capture_output=True, text=True, timeout=60).stdout
for line in out.strip().splitlines():
pid_s, _, mem = line.partition(",")
pid = int(pid_s.strip()) if pid_s.strip().isdigit() else None
if pid and pid != os.getpid():
log(f"leftover process {pid} holds {mem.strip()} MiB of GPU memory; killing it")
try:
os.kill(pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
def kill_group(p: subprocess.Popen) -> None:
"""Kill a phase and everything it started (torchrun ranks, vLLM's engine process), even after
the leader exited, so no orphan keeps holding GPU memory."""
if os.name == "posix":
try:
os.killpg(p.pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
elif p.poll() is None:
p.kill()
p.wait()
def tail(path: Path, n: int = 1) -> str:
try:
with open(path, "rb") as f:
f.seek(0, 2)
f.seek(max(0, f.tell() - 8000))
lines = [x for x in f.read().decode(errors="replace").splitlines() if x.strip()]
return "\n".join(lines[-n:])[-4000:]
except OSError:
return ""
def python_module(module: str, *args: str, python: str | None = None) -> list[str]:
return [python or sys.executable, "-m", module, *args]
|