File size: 15,515 Bytes
575b0ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
360
361
362
363
364
365
366
367
368
369
370
371
372
"""Dependency/priority GPU job queue for a single 8-GPU node.

  python -m tdprm.queue.gpuq run      --plan plan.json [--gpus 0,1,2,3,4,5,6,7]
  python -m tdprm.queue.gpuq status   --plan plan.json
  python -m tdprm.queue.gpuq simulate --plan plan.json         # predicted timeline from est_hours
  python -m tdprm.queue.gpuq retry    --plan plan.json JOB_ID
  python -m tdprm.queue.gpuq kill     --plan plan.json JOB_ID
  python -m tdprm.queue.gpuq hold     --plan plan.json JOB_ID [JOB_ID ...]   # `retry` releases

A job is {"id", "script", "gpus", "priority", "deps", "est_hours"}; deps are job ids or "file:<path>"
(waits until the file exists, e.g. a checkpoint's READY marker). The scheduler repeatedly starts the
highest-priority ready job that fits on free GPUs (lower priority value first; backfilling allowed),
so GPUs never idle while runnable work exists. State survives restarts of the queue process.
"""

import argparse
import fcntl
import heapq
import json
import os
import signal
import subprocess
import time
from pathlib import Path

PAIRS = [(0, 1), (2, 3), (4, 5), (6, 7)]


def load_plan(path):
    """Plan file: a list of jobs, or {"jobs": [...], "reservations": [{"gpus": [...], "jobs": [...]}]}."""
    data = json.loads(Path(path).read_text())
    return (data, []) if isinstance(data, list) else (data["jobs"], data.get("reservations", []))


def reserved_gpus(job_id, reservations, finished):
    """GPUs this job may not use: GPUs held by reservations whose job group is still unfinished and
    which do not list this job."""
    blocked = set()
    for r in reservations:
        if any(j not in finished for j in r["jobs"]) and job_id not in r["jobs"]:
            blocked |= set(r["gpus"])
    return blocked


def state_path(plan_path):
    return Path(plan_path).with_suffix(".state.json")


def load_state(plan_path):
    p = state_path(plan_path)
    return json.loads(p.read_text()) if p.exists() else {}


def save_state(plan_path, state):
    p = state_path(plan_path)
    tmp = p.with_suffix(".tmp")
    tmp.write_text(json.dumps(state, indent=1))
    tmp.replace(p)


def expand(s):
    return os.path.expandvars(os.path.expanduser(s))


def finished(s, max_retries):
    """No further attempt will be made: done, blocked, killed, or failed with the automatic retries used up."""
    st = s.get("status")
    return st in ("done", "blocked") or (st == "failed" and (s.get("exit") == -15 or s.get("attempts", 0) >= max_retries))


def deps_met(job, state, max_retries=0):
    """deps: job ids (must be done), "file:<path>" (must exist), "after:<job id>" (must be finished, any outcome)."""
    for d in job.get("deps", []):
        if d.startswith("file:"):
            if not Path(expand(d[5:])).exists():
                return False
        elif d.startswith("after:"):
            if not finished(state.get(d[6:], {}), max_retries):
                return False
        elif state.get(d, {}).get("status") != "done":
            return False
    return True


def deps_failed(job, state):
    return any(not d.startswith(("file:", "after:")) and state.get(d, {}).get("status") in ("failed", "blocked")
               for d in job.get("deps", []))


def pick_gpus(n, free):
    if n == 0:
        return []
    if n == 2:
        for a, b in PAIRS:
            if a in free and b in free:
                return [a, b]
    if len(free) >= n:
        return sorted(free)[:n]
    return None


def alive(pid):
    try:
        os.kill(pid, 0)
        return True
    except OSError:
        return False


def launch(job, gpus, logdir):
    logdir.mkdir(parents=True, exist_ok=True)
    log = logdir / f"{job['id']}.log"
    exitf = logdir / f"{job['id']}.exit"
    exitf.unlink(missing_ok=True)
    env = dict(os.environ)
    env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, gpus)) if gpus else ""
    env["TDPRM_GPU0"] = str(gpus[0]) if gpus else "9"
    cmd = f"bash {expand(job['script'])}; echo $? > {exitf}"
    proc = subprocess.Popen(["bash", "-c", cmd], env=env, stdout=open(log, "ab"), stderr=subprocess.STDOUT,
                            start_new_session=True)
    return proc.pid


def refresh(state, logdir):
    for jid, s in state.items():
        if s.get("status") != "running":
            continue
        exitf = logdir / f"{jid}.exit"
        if exitf.exists():
            code = int(exitf.read_text().strip() or 1)
            s.update(status="done" if code == 0 else "failed", exit=code, end=time.time())
        elif not alive(s["pid"]):
            s.update(status="failed", exit=-1, end=time.time())
        else:
            continue
        reap(s["pid"])


def reap(pgid):
    """Kill what a finished job left behind in its process group (vLLM's EngineCore can outlive its trainer and
    keep ~18 GB of GPU memory)."""
    try:
        os.killpg(pgid, signal.SIGKILL)
    except OSError:
        pass


def gpu_memory_used():
    """MiB in use per GPU index; {} when nvidia-smi is unavailable."""
    try:
        out = subprocess.run(["nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader,nounits"],
                             capture_output=True, text=True, timeout=30).stdout
        return {int(i): int(m) for i, m in (line.split(",") for line in out.strip().splitlines())}
    except (OSError, ValueError, subprocess.SubprocessError):
        return {}


def retryable(s, args, now):
    return (s.get("status") == "failed" and s.get("exit") != -15 and s.get("attempts", 0) < args.max_retries
            and now - s.get("end", now) >= args.retry_after)


def lock(plan_path):
    """Exclusive lock for a state read-modify-write (scheduler loop vs retry/hold/kill); released on close."""
    f = open(Path(plan_path).with_suffix(".lock"), "w")
    fcntl.flock(f, fcntl.LOCK_EX)
    return f


def run(args):
    plan, reservations = load_plan(args.plan)
    gpus_all = [int(g) for g in args.gpus.split(",")]
    logdir = Path(args.plan).with_suffix("").parent / "logs"
    state = load_state(args.plan)
    order = {j["id"]: i for i, j in enumerate(plan)}
    while True:
        held = lock(args.plan)
        state = load_state(args.plan)          # picks up retry/hold/kill issued while the queue runs
        refresh(state, logdir)
        now = time.time()
        for j in plan:
            s = state.get(j["id"], {})
            if retryable(s, args, now):
                state[j["id"]] = {"status": "pending", "attempts": s.get("attempts", 0) + 1}
                for other in state.values():
                    if other.get("status") == "blocked":
                        other["status"] = "pending"
                print(f"[{time.strftime('%H:%M:%S')}] auto-retry {j['id']} (retry {s.get('attempts', 0) + 1})", flush=True)
        busy = {g for s in state.values() if s.get("status") == "running" for g in s.get("gpus", [])}
        # memory still held (a finished job's processes exiting, or a foreign process) also makes a GPU busy
        busy |= {g for g, mib in gpu_memory_used().items() if mib > args.max_used_mib}
        free = set(gpus_all) - busy
        pending = [j for j in plan if state.get(j["id"], {}).get("status", "pending") == "pending"]
        for j in pending:
            if deps_failed(j, state):
                state[j["id"]] = {"status": "blocked"}
        ready = sorted((j for j in pending if state.get(j["id"], {}).get("status") != "blocked"
                        and deps_met(j, state, args.max_retries)),
                       key=lambda j: (j.get("priority", 50), order[j["id"]]))
        finished = {jid for jid, s in state.items() if s.get("status") in ("done", "failed", "blocked")}
        waiting_head = False
        for j in ready:
            if waiting_head and j.get("est_hours", 1.0) > args.backfill_max_hours:
                continue
            gpus = pick_gpus(j.get("gpus", 1), free - reserved_gpus(j["id"], reservations, finished))
            if gpus is None:
                if j.get("gpus", 1) > 0 and not any(j["id"] in r["jobs"] for r in reservations):
                    waiting_head = True       # a higher-priority job is waiting: only short jobs may backfill
                continue
            pid = launch(j, gpus, logdir)
            free -= set(gpus)
            state[j["id"]] = {"status": "running", "gpus": gpus, "pid": pid, "start": time.time(),
                              "attempts": state.get(j["id"], {}).get("attempts", 0)}
            print(f"[{time.strftime('%H:%M:%S')}] start {j['id']} on GPUs {gpus} (pid {pid})", flush=True)
        save_state(args.plan, state)
        held.close()
        remaining = [j for j in plan if state.get(j["id"], {}).get("status", "pending") in ("pending", "running", "held")
                     or retryable(state.get(j["id"], {}), args, float("inf"))]
        if not remaining:
            print("all jobs finished", flush=True)
            return
        time.sleep(args.poll)


def status(args):
    plan, _ = load_plan(args.plan)
    state = load_state(args.plan)
    logdir = Path(args.plan).with_suffix("").parent / "logs"
    refresh(state, logdir)
    now = time.time()
    counts = {}
    for j in plan:
        s = state.get(j["id"], {"status": "pending"})
        counts[s["status"]] = counts.get(s["status"], 0) + 1
        if s["status"] in ("running", "failed", "blocked", "held") or args.all:
            el = ((s.get("end") or now) - s["start"]) / 3600 if "start" in s else 0
            print(f"{s['status']:8s} {j['id']:45s} gpus={s.get('gpus', '-')!s:8s} {el:5.2f}h  est={j.get('est_hours', 0):.1f}h")
    print(counts)


def simulate(args):
    """List-scheduling simulation with the same policy as `run`, using est_hours."""
    plan, reservations = load_plan(args.plan)
    n_gpu = len(args.gpus.split(","))
    order = {j["id"]: i for i, j in enumerate(plan)}
    finish, start, gpu_of = {}, {}, {}
    free_at = {g: 0.0 for g in range(n_gpu)}
    t, running, done = 0.0, [], set()
    pending = list(plan)
    while pending or running:
        free = {g for g, ft in free_at.items() if ft <= t + 1e-9}
        progressed = True
        while progressed:
            progressed = False
            ready = []
            for j in pending:
                ok = True
                for d in j.get("deps", []):
                    if d.startswith("file:"):
                        src = j.get("produced_by")
                        frac = j.get("produced_at_frac", 1.0)
                        if src is None:
                            continue                  # an existing input, not produced by a job of this plan
                        if src not in start or start[src] + frac * plan_est(plan, src) > t + 1e-9:
                            ok = False
                    elif d.removeprefix("after:") not in done:
                        ok = False
                if ok:
                    ready.append(j)
            ready.sort(key=lambda j: (j.get("priority", 50), order[j["id"]]))
            waiting_head = False
            for j in ready:
                if waiting_head and j.get("est_hours", 1.0) > args.backfill_max_hours:
                    continue
                gpus = pick_gpus(j.get("gpus", 1), free - reserved_gpus(j["id"], reservations, done))
                if gpus is None:
                    if j.get("gpus", 1) > 0 and not any(j["id"] in r["jobs"] for r in reservations):
                        waiting_head = True
                    continue
                start[j["id"]] = t
                end = t + j.get("est_hours", 1.0)
                finish[j["id"]] = end
                gpu_of[j["id"]] = gpus
                for g in gpus:
                    free_at[g] = end
                free -= set(gpus)
                heapq.heappush(running, (end, j["id"]))
                pending.remove(j)
                progressed = True
        if not running:
            if pending:
                raise RuntimeError(f"unschedulable: {[j['id'] for j in pending][:5]}")
            break
        candidates = [running[0][0]] + [start[j["produced_by"]] + j.get("produced_at_frac", 1.0) *
                                        plan_est(plan, j["produced_by"]) for j in pending
                                        if j.get("produced_by") in start]
        nxt = min(c for c in candidates if c > t + 1e-9) if any(c > t + 1e-9 for c in candidates) else running[0][0]
        t = nxt
        while running and running[0][0] <= t + 1e-9:
            _, jid = heapq.heappop(running)
            done.add(jid)
    rows = sorted(start, key=lambda k: (start[k], k))
    for jid in rows:
        if args.all or not jid.startswith("eval_"):
            print(f"{start[jid]:6.2f}h -> {finish[jid]:6.2f}h  gpus={gpu_of[jid]!s:8s} {jid}")
    makespan = max(finish.values()) if finish else 0
    busy = sum(len(gpu_of[j]) * (finish[j] - start[j]) for j in finish)
    print(f"makespan {makespan:.1f}h, GPU utilization {busy / (n_gpu * makespan):.1%}" if makespan else "empty plan")
    marks = [start[j["id"]] + j["first_look_frac"] * j.get("est_hours", 1.0) for j in plan
             if j.get("first_look_frac") is not None and j["id"] in start]
    if marks:
        print(f"round-100 in-loop eval of the first-wave arms: earliest ~{min(marks):.1f}h, all ~{max(marks):.1f}h")


def plan_est(plan, jid):
    plan = plan[0] if isinstance(plan, tuple) else plan
    for j in plan:
        if j["id"] == jid:
            return j.get("est_hours", 1.0)
    return 1.0


def control(args, action):
    with lock(args.plan):
        _control(args, action)


def _control(args, action):
    state = load_state(args.plan)
    if action == "hold":
        for jid in args.job:
            if state.get(jid, {}).get("status", "pending") in ("pending", "failed", "blocked"):
                state[jid] = {"status": "held"}
        save_state(args.plan, state)
        return
    args.job = args.job[0]
    s = state.get(args.job, {})
    if action == "kill" and s.get("status") == "running":
        try:
            os.killpg(os.getpgid(s["pid"]), signal.SIGTERM)
        except OSError:
            pass
        s.update(status="failed", exit=-15, end=time.time())
    elif action == "retry":
        state[args.job] = {"status": "pending"}
        for jid, st in state.items():
            if st.get("status") == "blocked":
                st["status"] = "pending"
    save_state(args.plan, state)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("cmd", choices=["run", "status", "simulate", "retry", "kill", "hold"])
    parser.add_argument("job", nargs="*")
    parser.add_argument("--plan", required=True)
    parser.add_argument("--gpus", default="0,1,2,3,4,5,6,7")
    parser.add_argument("--poll", type=float, default=20)
    parser.add_argument("--all", action="store_true")
    parser.add_argument("--backfill-max-hours", type=float, default=0.5,
                        help="while a higher-priority job waits for GPUs, only jobs this short may start")
    parser.add_argument("--max-retries", type=int, default=2, help="automatic retries of a failed job")
    parser.add_argument("--retry-after", type=float, default=300, help="seconds between a failure and its retry")
    parser.add_argument("--max-used-mib", type=int, default=1024,
                        help="a GPU with more memory in use than this is not given to a new job")
    args = parser.parse_args()
    {"run": run, "status": status, "simulate": simulate}.get(args.cmd, lambda a: control(a, args.cmd))(args)


if __name__ == "__main__":
    main()