Repository navigation
Expand file tree
/
Copy pathsat
More file actions
executable file
·497 lines (457 loc) · 18.1 KB
/
Copy pathsat
File metadata and controls
executable file
·497 lines (457 loc) · 18.1 KB
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
#!/usr/bin/env python3
# ──────────────────────────────────────────────────────────────
# sat — salloc TUI for UW Hyak (replaces the interactive `sa`/`sckpt`)
#
# One list of every place you can get a GPU:
# · owned partitions (ark/cse) with live free counts from hyakalloc
# · ckpt GPU types with exact free-GPU counts from per-node sinfo
# (counts free GPUs on partially-used nodes, not just idle ones)
#
# Pick a row, tweak if needed, hit Enter — it execs salloc. Memory
# and CPUs are auto-fitted to what's actually free so the job starts
# immediately; any manual tweak overrides the auto value.
#
# Keys:
# j/k or ↑/↓ select row +/- or ←/→ GPUs (= works too)
# t / T time down/up a toggle account ark/cse (ckpt rows)
# m / M memory down/up c / C CPUs down/up
# 0 reset to auto-fit r refresh availability
# Enter launch salloc p print command and exit
# q quit
# ──────────────────────────────────────────────────────────────
import curses
import locale
import os
import re
import subprocess
import sys
import threading
import time
REFRESH_SECS = 30.0
BAD_NODES = ("g3110",) # uncorrectable ECC errors; keep excluded
TIME_STEPS = ["1:00:00", "2:00:00", "4:00:00", "8:00:00", "9:05:00",
"12:00:00", "24:00:00"]
DEFAULT_TIME = "4:00:00"
CKPT_MAX_TIME = "9:05:00" # ckpt clamps longer requests to this anyway
CKPT_PART = {
"2080ti": "ckpt", "rtx6k": "ckpt", "a40": "ckpt", "a100": "ckpt",
"p100": "ckpt",
"l40": "ckpt-g2", "l40s": "ckpt-g2", "h200": "ckpt-g2",
}
def run_cmd(cmd, timeout=90):
try:
p = subprocess.run(cmd, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, timeout=timeout)
return p.stdout.decode("utf-8", "replace")
except Exception:
return ""
def parse_hyakalloc():
"""Owned-partition rows with account-aware free counts."""
out = run_cmd(["hyakalloc"])
out = re.sub("[╭╮╰╯├┤┼─│]", "", out)
rows, cur = [], {}
for line in out.splitlines():
t = line.split()
if not t:
continue
if t[-1] == "TOTAL":
if len(t) >= 6:
cur = {"acct": t[0], "part": t[1]}
vals = t[2:5]
else:
vals = t[0:3]
cur["t_cpu"], cur["t_mem"], cur["t_gpu"] = [
int(v.rstrip("G")) for v in vals]
elif t[-1] == "FREE" and cur:
vals = t[2:5] if len(t) >= 6 else t[0:3]
cur["f_cpu"], cur["f_mem"], cur["f_gpu"] = [
int(v.rstrip("G")) for v in vals]
if cur.get("t_gpu", 0) > 0:
gpu_type = cur["part"].replace("gpu-", "")
rows.append({
"kind": "owned", "acct": cur["acct"],
"part": cur["part"], "type": gpu_type,
"t_cpu": cur["t_cpu"], "t_mem": cur["t_mem"],
"t_gpu": cur["t_gpu"], "f_cpu": cur["f_cpu"],
"f_mem": cur["f_mem"], "f_gpu": cur["f_gpu"],
})
cur = {}
return rows
def parse_ckpt():
"""Per-GPU-type ckpt rows from per-node sinfo (exact free GPUs)."""
out = run_cmd(["sinfo", "-p", "ckpt-all", "-N", "-h", "-O",
"NodeHost:20,StateCompact:12,Gres:40,GresUsed:60,"
"CPUsState:20,Memory:12,AllocMem:12"])
agg = {}
for line in out.splitlines():
t = line.split()
if len(t) < 7:
continue
node, state, gres, used, cpus, mem_mb, alloc_mb = t[:7]
if node in BAD_NODES:
continue
if state.rstrip("*~#$@").lower() not in ("idle", "mix"):
continue
m = re.match(r"gpu:([\w.]+):(\d+)", gres)
if not m:
continue
typ, total = m.group(1), int(m.group(2))
mu = re.match(r"gpu:[\w.]+:(\d+)", used)
n_used = int(mu.group(1)) if mu else 0
free_gpu = total - n_used
if free_gpu <= 0:
continue
try:
idle_cpu = int(cpus.split("/")[1])
tot_cpu = int(cpus.split("/")[3])
free_mem = (int(mem_mb) - int(alloc_mb)) // 1024
tot_mem = int(mem_mb) // 1024
except (ValueError, IndexError):
continue
node_info = {
"node": node, "free_gpu": free_gpu,
"free_cpu": idle_cpu, "free_mem": free_mem,
"fair_mem": max(1, tot_mem // total),
"fair_cpu": max(1, tot_cpu // total),
}
a = agg.setdefault(typ, {"free_gpu": 0, "nodes": 0, "best": None})
a["free_gpu"] += free_gpu
a["nodes"] += 1
b = a["best"]
if b is None or (node_info["free_gpu"], node_info["free_mem"]) > \
(b["free_gpu"], b["free_mem"]):
a["best"] = node_info
rows = []
for typ in sorted(agg, key=lambda t: -agg[t]["free_gpu"]):
a = agg[typ]
rows.append({
"kind": "ckpt", "acct": "ark", "type": typ,
"part": CKPT_PART.get(typ, "ckpt-all"),
"f_gpu": a["free_gpu"], "nodes": a["nodes"], "best": a["best"],
})
return rows
def autofit(row, ngpus):
"""(mem_gb, cpus, starts_now) sized to what is actually free."""
n = max(1, ngpus)
if row["kind"] == "owned":
fair_mem = max(1, row["t_mem"] // row["t_gpu"])
fair_cpu = max(1, row["t_cpu"] // row["t_gpu"])
fits = row["f_gpu"] >= n
if fits:
mem = max(1, min(fair_mem, row["f_mem"] // n))
cpu = max(1, min(fair_cpu, row["f_cpu"] // n))
else:
mem, cpu = fair_mem, fair_cpu
return mem, cpu, fits # per-GPU values
b = row["best"]
fits = b is not None and b["free_gpu"] >= n
if fits:
mem = max(1, min(b["fair_mem"] * n, b["free_mem"]))
cpu = max(1, min(b["fair_cpu"] * n, b["free_cpu"]))
else:
mem, cpu = 128 * n, 10 * n
return mem, cpu, fits # totals
def build_cmd(row, ngpus, mem, cpu, tlimit, acct):
if row["kind"] == "owned":
return ["salloc", "-p", row["part"], "-A", row["acct"],
"--nodes=1", "--time=" + tlimit,
"--gres=gpu:{}".format(ngpus),
"--mem-per-gpu={}G".format(mem),
"--cpus-per-gpu={}".format(cpu)]
return ["salloc", "-p", row["part"], "-A", acct,
"--nodes=1", "--time=" + tlimit,
"--gres=gpu:{}:{}".format(row["type"], ngpus),
"--mem={}G".format(mem),
"--cpus-per-task={}".format(cpu),
"--exclude=" + ",".join(BAD_NODES)]
# ── UI ───────────────────────────────────────────────────────
C_RUN, C_PEND, C_BAD, C_INFO, C_HDR, C_DIM = 1, 2, 3, 4, 5, 6
def safe_add(scr, y, x, s, attr=0):
rows, cols = scr.getmaxyx()
if y < 0 or y >= rows or x >= cols:
return
try:
scr.addnstr(y, x, s, cols - x - 1, attr)
except curses.error:
pass
class App(object):
def __init__(self):
self.lock = threading.Lock()
self.wake = threading.Event()
self.stop_ev = threading.Event()
# worker-owned
self.owned = None # None = still loading
self.ckpt = None
# UI-owned
self.sel = 0
self.ngpus = 1
self.time_i = TIME_STEPS.index(DEFAULT_TIME)
self.acct = "ark"
self.mem_over = None # manual overrides; None = auto-fit
self.cpu_over = None
self.status = ""
self.result = None # cmd list to exec after wrapper exits
def rows(self):
rows = []
if self.owned:
rows.extend(self.owned)
if self.ckpt:
rows.extend(self.ckpt)
return rows
def selected(self):
rows = self.rows()
if rows and 0 <= self.sel < len(rows):
return rows[self.sel]
return None
def reset_row_params(self):
self.ngpus = 1
self.mem_over = None
self.cpu_over = None
def params(self):
row = self.selected()
if not row:
return None
mem, cpu, fits = autofit(row, self.ngpus)
if self.mem_over is not None:
mem = self.mem_over
if self.cpu_over is not None:
cpu = self.cpu_over
tlimit = TIME_STEPS[self.time_i]
if row["kind"] == "ckpt" and \
TIME_STEPS.index(CKPT_MAX_TIME) < self.time_i:
tlimit = CKPT_MAX_TIME
acct = row["acct"] if row["kind"] == "owned" else self.acct
return row, mem, cpu, fits, tlimit, acct
# ── background worker ──
def worker(self):
while not self.stop_ev.is_set():
ckpt = parse_ckpt() # fast — show it first
with self.lock:
self.ckpt = ckpt
owned = parse_hyakalloc() # slow (a few seconds)
with self.lock:
self.owned = owned
self.wake.wait(REFRESH_SECS)
self.wake.clear()
# ── drawing ──
def draw(self, scr):
scr.erase()
rows_n, cols = scr.getmaxyx()
left_w = max(30, min(44, cols // 3))
hdr = " sat — pick a GPU allocation"
safe_add(scr, 0, 0, hdr.ljust(cols - 1), curses.color_pair(C_HDR))
for y in range(1, rows_n - 1):
safe_add(scr, y, left_w, "│", curses.color_pair(C_DIM))
self.draw_rows(scr, 1, rows_n - 2, left_w)
self.draw_panel(scr, 1, left_w + 2, cols - left_w - 3)
keys = (" Enter launch +/- gpus t time m/c mem/cpu 0 auto "
"a acct p print r refresh q quit")
if self.status:
keys = " " + self.status
safe_add(scr, rows_n - 1, 0, keys.ljust(cols - 1),
curses.color_pair(C_HDR))
scr.refresh()
def draw_rows(self, scr, top, bottom, width):
rows = self.rows()
dim = curses.color_pair(C_DIM)
y = top
if self.owned is None:
safe_add(scr, y, 1, "hyakalloc loading…", dim)
y += 1
idx = 0
last_kind = None
for row in rows:
if row["kind"] != last_kind:
title = "OWNED (dedicated)" if row["kind"] == "owned" \
else "CKPT (preemptible ~8-9h)"
safe_add(scr, y, 1, title, dim | curses.A_BOLD)
y += 1
last_kind = row["kind"]
if row["kind"] == "owned":
free = row["f_gpu"]
line = " {:<4} {:<10} {:>3} free".format(
row["acct"], row["part"], free)
else:
free = row["f_gpu"]
line = " {:<8} {:<8} {:>4} free /{:>3}n".format(
row["type"], row["part"], free, row["nodes"])
attr = curses.color_pair(C_RUN if free > 0 else C_BAD)
if idx == self.sel:
attr |= curses.A_REVERSE
line = line.ljust(width)
safe_add(scr, y, 0, line[:width], attr)
y += 1
idx += 1
if self.ckpt is None:
safe_add(scr, y, 1, "sinfo loading…", dim)
def draw_panel(self, scr, top, x, width):
p = self.params()
dim = curses.color_pair(C_DIM)
if not p:
safe_add(scr, top + 1, x, "loading availability…", dim)
return
row, mem, cpu, fits, tlimit, acct = p
y = top
if row["kind"] == "owned":
info = [
("Target", "{} / {} ({})".format(
row["acct"], row["part"], row["type"]), 0),
("Free", "{} of {} GPUs {}G mem {} CPUs".format(
row["f_gpu"], row["t_gpu"], row["f_mem"],
row["f_cpu"]), 0),
]
else:
b = row["best"] or {}
info = [
("Target", "{} / {} (preemptible)".format(
row["part"], row["type"]), 0),
("Free", "{} GPUs across {} nodes".format(
row["f_gpu"], row["nodes"]), 0),
("Best", "{}: {} gpu, {}G mem, {} cpu free".format(
b.get("node", "?"), b.get("free_gpu", 0),
b.get("free_mem", 0), b.get("free_cpu", 0)), 0),
]
for label, val, attr in info:
safe_add(scr, y, x, "{:<9}".format(label + ":"), dim)
safe_add(scr, y, x + 9, val, attr)
y += 1
y += 1
unit = "/gpu" if row["kind"] == "owned" else "total"
mem_tag = "auto" if self.mem_over is None else "manual"
cpu_tag = "auto" if self.cpu_over is None else "manual"
req = [
("GPUs", "{} (+/- to change)".format(self.ngpus)),
("Time", "{} (t shorter / T longer)".format(tlimit)),
("Mem", "{}G {} [{}] (m/M)".format(mem, unit, mem_tag)),
("CPUs", "{} {} [{}] (c/C)".format(cpu, unit, cpu_tag)),
]
if row["kind"] == "ckpt":
req.append(("Account", "{} (a toggles ark/cse)".format(acct)))
safe_add(scr, y, x, "Request", dim | curses.A_BOLD)
y += 1
for label, val in req:
safe_add(scr, y, x, " {:<9}".format(label + ":"), dim)
safe_add(scr, y, x + 11, val)
y += 1
y += 1
if fits:
safe_add(scr, y, x, "✔ fits in free resources — should start "
"right away", curses.color_pair(C_RUN))
else:
safe_add(scr, y, x, "⚠ more than currently free — job will "
"pend", curses.color_pair(C_PEND))
y += 2
if row["kind"] == "ckpt":
safe_add(scr, y, x, "preemptible: stint ends by ~8-9h; the "
"shell dies on preemption", dim)
y += 1
y += 1
safe_add(scr, y, x, "Command", dim | curses.A_BOLD)
y += 1
cmd = " ".join(build_cmd(row, self.ngpus, mem, cpu, tlimit, acct))
for i in range(0, len(cmd), width - 2):
safe_add(scr, y, x + 1, cmd[i:i + width - 2],
curses.color_pair(C_INFO))
y += 1
# ── main loop ──
def loop(self, scr):
curses.use_default_colors()
for pair, fg in ((C_RUN, curses.COLOR_GREEN),
(C_PEND, curses.COLOR_YELLOW),
(C_BAD, curses.COLOR_RED),
(C_INFO, curses.COLOR_CYAN),
(C_DIM, curses.COLOR_BLUE)):
curses.init_pair(pair, fg, -1)
curses.init_pair(C_HDR, curses.COLOR_BLACK, curses.COLOR_CYAN)
try:
curses.curs_set(0)
except curses.error:
pass
scr.timeout(100)
threading.Thread(target=self.worker, daemon=True).start()
while True:
self.draw(scr)
ch = scr.getch()
if ch == -1:
continue
self.status = ""
n_rows = len(self.rows())
if ch in (ord("q"), 27):
self.stop_ev.set()
return
elif ch in (ord("j"), curses.KEY_DOWN):
if self.sel < n_rows - 1:
self.sel += 1
self.reset_row_params()
elif ch in (ord("k"), curses.KEY_UP):
if self.sel > 0:
self.sel -= 1
self.reset_row_params()
elif ch in (ord("+"), ord("="), curses.KEY_RIGHT):
self.ngpus += 1
elif ch in (ord("-"), ord("_"), curses.KEY_LEFT):
self.ngpus = max(1, self.ngpus - 1)
elif ch == ord("t"):
self.time_i = max(0, self.time_i - 1)
elif ch == ord("T"):
self.time_i = min(len(TIME_STEPS) - 1, self.time_i + 1)
elif ch == ord("m"):
p = self.params()
if p:
self.mem_over = max(1, p[1] - 8)
elif ch == ord("M"):
p = self.params()
if p:
self.mem_over = p[1] + 8
elif ch == ord("c"):
p = self.params()
if p:
self.cpu_over = max(1, p[2] - 2)
elif ch == ord("C"):
p = self.params()
if p:
self.cpu_over = p[2] + 2
elif ch == ord("0"):
self.mem_over = self.cpu_over = None
self.status = "reset to auto-fit"
elif ch == ord("a"):
self.acct = "cse" if self.acct == "ark" else "ark"
elif ch == ord("r"):
with self.lock:
self.owned = None
self.ckpt = None
self.wake.set()
elif ch in (ord("p"), ord("\n"), curses.KEY_ENTER, 10, 13):
p = self.params()
if not p:
self.status = "still loading…"
continue
row, mem, cpu, fits, tlimit, acct = p
self.result = (build_cmd(row, self.ngpus, mem, cpu,
tlimit, acct),
ch == ord("p"))
self.stop_ev.set()
return
def main():
if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help"):
print("sat: salloc TUI — pick a GPU allocation from live "
"availability (owned + ckpt),\nauto-fit mem/CPUs, "
"Enter to launch. `p` prints the command instead.")
return
if len(sys.argv) > 1 and sys.argv[1] == "--plain":
for r in parse_ckpt():
print(r)
for r in parse_hyakalloc():
print(r)
return
locale.setlocale(locale.LC_ALL, "")
app = App()
curses.wrapper(app.loop)
if app.result:
cmd, print_only = app.result
print(" ".join(cmd))
if not print_only:
sys.stdout.flush()
os.execvp("salloc", cmd)
if __name__ == "__main__":
main()