pinka 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pinka/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """pinka: pack GPU jobs onto shared cards by measured memory. A single-node job pool with VRAM, CPU and RAM booking,
2
+ dependencies and retries. See AGENTS.md."""
3
+ from .jobs import Spec, cancel, fanout, retarget, submit, wait # noqa: F401
4
+
5
+ __version__ = "0.1.0"
pinka/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
pinka/batch.py ADDED
@@ -0,0 +1,96 @@
1
+ """Foreground mode: `pinka run jobs.json` runs a list of jobs here and returns when they have all ended.
2
+
3
+ The list is JSON: [{"name": "a", "cmd": [...] or "shell string", "vram_gb": 6, "cpu": 2, "ram_gb": 4,
4
+ "after": ["other name"], "tries": 2, "timeout_h": 1, ...}, ...]; any submit field works, and `gpu_gb` / `cpus` are
5
+ accepted for vram_gb / cpu. Job ids are the names. The same dispatcher runs them, in a state dir of the list's own
6
+ (default: <list>.pinka/ next to it), so packing, booking, retries and markers are the daemon's.
7
+
8
+ Resume: a rerun of the list skips jobs already done with the same command, gives a job that failed one more try
9
+ (--retry-failed: all its tries) and first stops whatever a killed runner left running. SIGTERM / Ctrl-C stops every
10
+ job and exits.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import graphlib
15
+ import json
16
+ import sys
17
+ import time
18
+ from dataclasses import asdict, fields
19
+ from pathlib import Path
20
+
21
+ from . import host
22
+ from .config import atomic_json
23
+ from .dispatcher import Dispatcher
24
+ from .jobs import Spec
25
+
26
+ ALIASES = {"gpu_gb": "vram_gb", "cpus": "cpu"}
27
+ FIELDS = {f.name for f in fields(Spec)}
28
+
29
+
30
+ def load_list(path) -> list:
31
+ rows = json.loads(Path(path).read_text())
32
+ if not isinstance(rows, list):
33
+ raise ValueError("a job list is a JSON list of objects")
34
+ out, names = [], set()
35
+ for i, r in enumerate(rows):
36
+ r = {ALIASES.get(k, k): v for k, v in r.items()}
37
+ label = repr(r.get("name", "entry %d" % i))
38
+ bad = sorted(set(r) - FIELDS)
39
+ if bad:
40
+ raise ValueError("job %s: unknown field %s" % (label, ", ".join(bad)))
41
+ if "name" not in r or "cmd" not in r:
42
+ raise ValueError("job %s: needs name and cmd" % label)
43
+ if r["name"] in names or "/" in r["name"]:
44
+ raise ValueError("job %s: name repeated or contains '/'" % label)
45
+ names.add(r["name"])
46
+ out.append(Spec(**r).check())
47
+ for s in out:
48
+ missing = sorted(set(s.after) - names)
49
+ if missing:
50
+ raise ValueError("job %r: unknown after %s" % (s.name, missing))
51
+ try:
52
+ graphlib.TopologicalSorter({s.name: s.after for s in out}).prepare()
53
+ except graphlib.CycleError as e:
54
+ raise ValueError("dependency cycle: %s" % " -> ".join(e.args[1]))
55
+ return out
56
+
57
+
58
+ def run_batch(path, state=None, cfg: dict = None, retry_failed: bool = False, gpu=None, out=sys.stdout) -> int:
59
+ specs = load_list(path)
60
+ state = Path(state or Path(path).with_suffix(".pinka"))
61
+ d = Dispatcher(state, cfg=cfg, gpu=gpu, stop_on_exit=True)
62
+ names = [s.name for s in specs]
63
+
64
+ def prepare(d: Dispatcher) -> None:
65
+ jobs, now = d.st["jobs"], time.time()
66
+ for j in d.jobs("running"): # left by a runner that was killed: stop, then run again
67
+ try:
68
+ host.stop(d.jdir(j["id"]) / "owned.json", grace=5.0)
69
+ except (RuntimeError, OSError, ValueError) as e:
70
+ raise SystemExit("job %s of an earlier runner survives: %s" % (j["id"], e))
71
+ j["state"] = "cancelled"
72
+ for j in d.jobs("queued"):
73
+ if j["id"] not in names:
74
+ d.finish(j, "cancelled", None, "not in the list")
75
+ for i, s in enumerate(specs):
76
+ old = jobs.get(s.name)
77
+ if old and old["state"] == "done" and old["spec"]["cmd"] == s.cmd:
78
+ continue
79
+ spec = asdict(s)
80
+ if old and old["state"] == "failed" and not retry_failed:
81
+ spec["tries"] = 1
82
+ jobs[s.name] = dict(id=s.name, t_submit=now + i * 1e-6, spec=spec, state="queued", tries=0, why="new")
83
+ atomic_json(d.jdir(s.name) / "spec.json", jobs[s.name])
84
+ d.save()
85
+
86
+ rc = d.run(until_done=True, prepare=prepare)
87
+ jobs = [d.st["jobs"][n] for n in names if n in d.st["jobs"]]
88
+ w = max([len(n) for n in names] + [3])
89
+ print("\n%-*s %-9s %4s %5s %7s %s" % (w, "job", "state", "card", "tries", "hours", "why"), file=out)
90
+ for j in jobs:
91
+ h = (j.get("t1", time.time()) - j["t0"]) / 3600 if j.get("t0") else 0.0
92
+ print("%-*s %-9s %4s %5d %7.3f %s" % (w, j["id"], j["state"], "-" if j.get("gpu") is None else j["gpu"],
93
+ j.get("tries", 0), h, j.get("why") or ""), file=out)
94
+ ok = sum(j["state"] == "done" for j in jobs)
95
+ print("%d jobs, %d done; logs and markers under %s/jobs/<name>/" % (len(jobs), ok, state), file=out)
96
+ return rc or (0 if ok == len(names) else 1)
pinka/booking.py ADDED
@@ -0,0 +1,234 @@
1
+ """What a job is booked at: VRAM, cores and RAM from its declaration, its own measurements and the history of earlier
2
+ runs under the same history key. A declaration is an upper bound; what the same job measured is the estimate. A
3
+ declaration that proved too low stops being a cap. AGENTS.md, "How packing and booking work", has the rules in prose.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ import re
9
+ from pathlib import Path
10
+
11
+ from .config import atomic_json, read_json
12
+
13
+ VRAM_MARGIN, VRAM_PAD_GB = 1.2, 1.0 # own booking = margin x measured peak + pad
14
+ HIST_VRAM_MARGIN = 1.1 # history cap = margin x p95 of the key's peaks + pad
15
+ OVER_MARGIN, OVER_PAD_GB = 1.1, 1.0 # measured above margin x declared + pad: the declaration was too low
16
+ RAM_OVER_MARGIN, RAM_OVER_PAD_GB = 1.1, 2.0
17
+ CPU_MARGIN = 1.2
18
+ HIST_KEEP = 20
19
+ _SUFFIX = re.compile(r"(?:[-_.](?:[a-z]?\d+)|\d+)+$")
20
+
21
+
22
+ def hist_prefix(name: str) -> str:
23
+ """History key of a name: lower case, trailing -s3 / -k2 / _t0 / -007 / digits stripped, so `eval-s3` and
24
+ `eval-k12` share one history."""
25
+ n = name.lower()
26
+ return _SUFFIX.sub("", n) or n
27
+
28
+
29
+ def hist_key(spec) -> str:
30
+ """A spec dict (its `key`, else its name) or a plain name."""
31
+ if isinstance(spec, str):
32
+ return hist_prefix(spec)
33
+ return hist_prefix(spec.get("key") or spec["name"])
34
+
35
+
36
+ def _p95(xs: list) -> float:
37
+ xs = sorted(xs)
38
+ return xs[min(len(xs) - 1, math.ceil(0.95 * len(xs)) - 1)]
39
+
40
+
41
+ def known_caps(hist: dict, spec, min_n: int = 3) -> dict:
42
+ """{vram_gb, cpu, ram_gb} that finished runs under this key needed, with margin (VRAM: p95, so one spiky run does
43
+ not cost every later job a slot; cores and RAM: the max); only keys with >= min_n samples."""
44
+ e = (hist or {}).get(hist_key(spec)) or {}
45
+ out = {}
46
+ for key, src, scale, pad, agg in (("vram_gb", "vram", HIST_VRAM_MARGIN, VRAM_PAD_GB, _p95),
47
+ ("cpu", "cores", CPU_MARGIN, 0.0, max), ("ram_gb", "ram", 1.2, 1.0, max)):
48
+ xs = e.get(src) or []
49
+ if len(xs) >= min_n:
50
+ out[key] = round(agg(xs) * scale + pad, 1)
51
+ return out
52
+
53
+
54
+ def hist_max(hist: dict, spec, key: str = "vram") -> float:
55
+ """Largest recorded value under the key (one run is enough)."""
56
+ return max(((hist or {}).get(hist_key(spec)) or {}).get(key) or [0.0])
57
+
58
+
59
+ def hist_record(path: Path, spec, vram_gb: float = 0.0, cores: float = 0.0, ram_gb: float = 0.0) -> None:
60
+ h = read_json(path, {}) or {}
61
+ e = h.setdefault(hist_key(spec), {})
62
+ for k, v in (("vram", vram_gb), ("cores", cores), ("ram", ram_gb)):
63
+ if v > 0:
64
+ e[k] = (e.get(k, []) + [round(v, 2)])[-HIST_KEEP:]
65
+ atomic_json(path, h)
66
+
67
+
68
+ def history_defaults(hist: dict, name: str) -> dict:
69
+ """{vram_gb, cpu, ram_gb} = p95 x 1.2 of the runs under this name's key: what `submit` uses for an omitted flag."""
70
+ e = (hist or {}).get(hist_prefix(name)) or {}
71
+ out = {}
72
+ if e.get("vram"):
73
+ out["vram_gb"] = round(math.ceil(_p95(e["vram"]) * 1.2 * 10) / 10, 1)
74
+ if e.get("cores"):
75
+ out["cpu"] = max(1, math.ceil(_p95(e["cores"]) * 1.2))
76
+ if e.get("ram"):
77
+ out["ram_gb"] = round(math.ceil(_p95(e["ram"]) * 1.2 * 10) / 10, 1)
78
+ return out
79
+
80
+
81
+ def is_gpu(spec: dict) -> bool:
82
+ return float(spec.get("vram_gb") or 0) > 0 or bool(spec.get("exclusive"))
83
+
84
+
85
+ # ------------------------------------------------------------------------------------------------ VRAM
86
+ def over_declared(spec: dict, measured: float) -> bool:
87
+ return not spec.get("exclusive") and measured > OVER_MARGIN * float(spec.get("vram_gb") or 0) + OVER_PAD_GB
88
+
89
+
90
+ def vram_raised(spec: dict, peak: float = 0.0, seen: float = 0.0) -> float:
91
+ """GB to book for a job whose declaration proved too low (0 when it did not): 1.2 x its own peak + 1 (it may
92
+ still grow), or the key's recorded peak `seen` + 1."""
93
+ return round(max(VRAM_MARGIN * peak + VRAM_PAD_GB if over_declared(spec, peak) else 0.0,
94
+ seen + VRAM_PAD_GB if over_declared(spec, seen) else 0.0), 1)
95
+
96
+
97
+ def vram_need(spec: dict, known: dict, trust: bool = True, seen: float = 0.0) -> float:
98
+ """GB a queued job needs free on a card."""
99
+ up = vram_raised(spec, 0.0, seen)
100
+ if up:
101
+ return up
102
+ declared = float(spec.get("vram_gb") or 0)
103
+ if not trust or spec.get("exclusive") or "vram_gb" not in (known or {}):
104
+ return declared
105
+ return min(declared, known["vram_gb"])
106
+
107
+
108
+ def vram_charge(j: dict, now: float, known: dict = None, trust: bool = True, seen: float = 0.0,
109
+ settle_s: float = 600.0) -> float:
110
+ """GB a running job books besides what it uses now (the caller takes the max with the live measurement): the
111
+ declaration until its own peak can be believed (history, or settle_s of running), then
112
+ min(declared, max(history cap, 1.2 x own peak + 1))."""
113
+ s = j["spec"]
114
+ peak = float(j.get("vram_peak") or 0)
115
+ up = vram_raised(s, peak, seen)
116
+ if up:
117
+ return up
118
+ declared = float(s.get("vram_gb") or 0)
119
+ if not trust or s.get("exclusive"):
120
+ return declared
121
+ own = VRAM_MARGIN * peak + VRAM_PAD_GB
122
+ if "vram_gb" in (known or {}):
123
+ return min(declared, max(known["vram_gb"], own))
124
+ if peak <= 0 or now - j.get("t0", 0) < settle_s:
125
+ return declared
126
+ return min(declared, own)
127
+
128
+
129
+ # ------------------------------------------------------------------------------------------------ CPU, RAM
130
+ def cpu_charge(j: dict, now: float, known: float = None, young_s: float = 300.0) -> float:
131
+ """Cores a running job is charged: declared while young or unmeasured (at most the history cap), then 1.2 x its
132
+ measured peak over the last few minutes."""
133
+ declared = float(max(int(j["spec"].get("cpu") or 0), 1))
134
+ peak = j.get("cores_peak")
135
+ if peak is None or now - j.get("t0", 0) < young_s:
136
+ return declared if known is None else max(1.0, min(declared, max(known, CPU_MARGIN * float(peak or 0))))
137
+ return max(1.0, CPU_MARGIN * float(peak))
138
+
139
+
140
+ def ram_declared(spec: dict, default: float) -> float:
141
+ return float(spec.get("ram_gb") or 0) or float(default)
142
+
143
+
144
+ def ram_over(spec: dict, rss: float, default: float) -> bool:
145
+ return rss > RAM_OVER_MARGIN * ram_declared(spec, default) + RAM_OVER_PAD_GB
146
+
147
+
148
+ def ram_raised(spec: dict, seen: float, default: float) -> float:
149
+ """seen + 1 when the key's recorded RAM peak broke this declaration, else 0."""
150
+ return round(seen + 1.0, 1) if ram_over(spec, seen, default) else 0.0
151
+
152
+
153
+ def ram_need(spec: dict, known: dict, seen: float, default: float) -> float:
154
+ """GB of RAM a queued job is booked at: declared (else the default), at most history's cap, at least `ram_raised`."""
155
+ need = float(spec.get("ram_gb") or 0) or known.get("ram_gb", default)
156
+ if spec.get("ram_gb") and "ram_gb" in known:
157
+ need = min(need, known["ram_gb"])
158
+ return max(need, ram_raised(spec, seen, default))
159
+
160
+
161
+ def ram_reserve(j: dict, now: float, need: float, young_s: float = 300.0) -> float:
162
+ """RAM still to come from a young job: its booking minus what its tree already holds, tapering to 0 at young_s."""
163
+ age = now - j.get("t0", 0)
164
+ if age >= young_s:
165
+ return 0.0
166
+ return max(0.0, need - float(j.get("rss_now") or 0)) * (1.0 - max(age, 0.0) / young_s)
167
+
168
+
169
+ # ------------------------------------------------------------------------------------------------ same-key groups
170
+ # Jobs of one history key that share a card rarely peak at the same moment. From usage.jsonl the dispatcher learns,
171
+ # per key, the VRAM that n such jobs together used on a card (p99 over card-minutes, divided by n); m of them on a
172
+ # card then book together max(what they use now, min(the sum of their own bookings, max(m x margin x share, the
173
+ # largest own booking))), for m up to n_max + 1 (the largest count measured, plus one). Further jobs book their own.
174
+ def _quantile(xs: list, q: float) -> float:
175
+ xs = sorted(xs)
176
+ return xs[min(len(xs) - 1, max(0, math.ceil(q * len(xs)) - 1))]
177
+
178
+
179
+ def conc_shares(lines: list, jobs, now: float, min_n: int = 30, q: float = 0.99) -> dict:
180
+ """{key: {share, n_max, by_n: {n: [card-minutes, q-quantile of used / n]}}}. `lines`: usage.jsonl records (t,
181
+ cards {g: [util, GB used, GB booked, jobs]}); `jobs`: job records. A sample is a card-minute whose jobs were n >= 2
182
+ pool jobs of one key, all running from 30 s before to 30 s after it; its value is the card's VRAM used / n (used
183
+ includes processes outside the pool, so it errs high). Only counts n with >= min_n samples are trusted; share is
184
+ the largest of their quantiles (the conservative one)."""
185
+ if not lines:
186
+ return {}
187
+ t_lo, per = min(ln["t"] for ln in lines) - 60, {}
188
+ for j in jobs:
189
+ s, g, t0 = j["spec"], j.get("gpu"), j.get("t0")
190
+ if g is None or not t0 or not is_gpu(s) or s.get("exclusive"):
191
+ continue
192
+ t1 = now if j["state"] == "running" else j.get("t1") or t0
193
+ if t1 >= t_lo:
194
+ per.setdefault(str(g), []).append((t0, t1, hist_key(s)))
195
+ by = {}
196
+ for g, iv in per.items():
197
+ iv.sort()
198
+ i, on = 0, []
199
+ for ln in sorted((x for x in lines if g in (x.get("cards") or {})), key=lambda x: x["t"]):
200
+ t, c = ln["t"], ln["cards"][g]
201
+ while i < len(iv) and iv[i][0] <= t - 30:
202
+ on.append(iv[i])
203
+ i += 1
204
+ on = [x for x in on if x[1] >= t + 30]
205
+ if len(c) < 4 or c[3] < 2 or len(on) != c[3] or len({x[2] for x in on}) != 1:
206
+ continue
207
+ by.setdefault(on[0][2], {}).setdefault(len(on), []).append(float(c[1]) / len(on))
208
+ out = {}
209
+ for k, ns in by.items():
210
+ ok = {n: [len(xs), round(_quantile(xs, q), 2)] for n, xs in sorted(ns.items()) if len(xs) >= min_n}
211
+ if ok:
212
+ out[k] = dict(share=max(v[1] for v in ok.values()), n_max=max(ok), by_n=ok)
213
+ return out
214
+
215
+
216
+ def conc_eligible(spec: dict, conc: dict, seen: float = 0.0, peak: float = 0.0) -> bool:
217
+ """May this job be booked in its key's group? Not when exclusive or when it broke its declaration."""
218
+ return (hist_key(spec) in (conc or {}) and is_gpu(spec) and not spec.get("exclusive")
219
+ and not vram_raised(spec, peak, seen))
220
+
221
+
222
+ def conc_group(m: int, act: float, own_sum: float, own_max: float, share: float, margin: float) -> float:
223
+ """GB that m same-key jobs on one card book together."""
224
+ return round(max(act, min(own_sum, max(m * margin * share, own_max))), 1)
225
+
226
+
227
+ def conc_add(group: dict, info: dict, v: float, margin: float) -> float:
228
+ """GB one more job of the key (own booking `v`) adds to a card whose group is `group` ({m, act, own_sum, own_max,
229
+ booked}, or empty): the group's growth, or `v` once the card already holds n_max + 1 of them."""
230
+ g = group or dict(m=0, act=0.0, own_sum=0.0, own_max=0.0, booked=0.0)
231
+ if g["m"] >= info["n_max"] + 1:
232
+ return v
233
+ new = conc_group(g["m"] + 1, g["act"], g["own_sum"] + v, max(g["own_max"], v), info["share"], margin)
234
+ return max(0.0, round(new - g["booked"], 1))
pinka/cli.py ADDED
@@ -0,0 +1,301 @@
1
+ """pinka: pack GPU jobs onto shared cards by measured memory.
2
+
3
+ pinka daemon [--once] the dispatcher (keep it running, e.g. in tmux or a systemd user unit)
4
+ pinka submit --vram GB [flags] -- CMD ... queue a job; prints its id
5
+ pinka fanout --arms a,b,c [--collect CMD] [flags] -- CMD with {arm}
6
+ pinka run JOBS.json [--gpus 0,1] run a list of jobs here, in the foreground, and exit when all have ended
7
+ pinka list [--all] | show ID | cancel ID.. | retarget ID.. [--vram GB] [--ram GB] [--gpus 0,1] | wait ID..
8
+ pinka status | usage [--hours H] | history [--all] | config
9
+
10
+ The state dir is --state-dir, else $PINKA_HOME, else $XDG_STATE_HOME/pinka, else ~/.pinka.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ import sys
18
+ import time
19
+ from pathlib import Path
20
+
21
+ from . import booking as B
22
+ from . import jobs as J
23
+ from .config import FINAL, load_config, read_json, state_dir
24
+
25
+ STALE_S = 120.0
26
+
27
+
28
+ def _ids(s: str) -> list:
29
+ return [x for x in (s or "").split(",") if x]
30
+
31
+
32
+ def _warn(age: float) -> None:
33
+ if age > STALE_S:
34
+ print("note: no dispatcher is running for this state dir (start one: pinka daemon)", file=sys.stderr)
35
+
36
+
37
+ def _hist(a) -> dict:
38
+ return read_json(state_dir(a.state_dir) / "history.json", {}) or {}
39
+
40
+
41
+ def cmd_submit(a, arms=None):
42
+ cmd = a.argv[1:] if a.argv[:1] == ["--"] else a.argv
43
+ if not cmd:
44
+ sys.exit("no command (put it after --)")
45
+ cmd = cmd[0] if len(cmd) == 1 else cmd
46
+ name = a.name or Path(cmd.split()[0] if isinstance(cmd, str) else cmd[0]).name
47
+ defaults = B.history_defaults(_hist(a), name)
48
+ for flag, key in (("vram", "vram_gb"), ("cpu", "cpu"), ("ram", "ram_gb")):
49
+ if getattr(a, flag) is None and key in defaults:
50
+ setattr(a, flag, defaults[key])
51
+ print("%s %s from the history of '%s' (p95 x 1.2)" % (flag, defaults[key], B.hist_prefix(name)), file=sys.stderr)
52
+ if a.vram is None and not a.exclusive:
53
+ sys.exit("declare --vram GB (the job's peak VRAM; 0 for a CPU job) or --exclusive")
54
+ _, status, _, age = J.snapshot(a.state_dir)
55
+ sizes = [c["total_gb"] - (status.get("cfg") or {}).get("headroom_gb", 0) for c in (status.get("cards") or {}).values()]
56
+ if sizes and (a.vram or 0) > max(sizes) and not a.exclusive:
57
+ print("warning: --vram %g is more than any card offers (%.1f GB after headroom): it will never start; use "
58
+ "--exclusive for a whole card" % (a.vram, max(sizes)), file=sys.stderr)
59
+ env = dict(os.environ) if a.copy_env else {}
60
+ env.update(dict(kv.split("=", 1) for kv in a.env))
61
+ kw = dict(key=a.key, owner=a.owner or os.environ.get("USER", ""), cwd=a.cwd or os.getcwd(), log_dir=a.log_dir,
62
+ env=env, vram_gb=a.vram or 0.0, cpu=int(a.cpu or 0), ram_gb=a.ram or 0.0, exclusive=a.exclusive,
63
+ gpus=[int(g) for g in _ids(a.gpus)], tag=a.tag, priority=a.priority, after=_ids(a.after),
64
+ when_exists=a.when_exists, tries=a.tries, timeout_h=a.timeout_h)
65
+ if arms is None:
66
+ print(J.submit(cmd, name=name, state=a.state_dir, **kw))
67
+ else:
68
+ out = J.fanout(cmd, arms, name, collect=a.collect or None, state=a.state_dir, **kw)
69
+ for arm, jid in out["arms"].items():
70
+ print(jid, "%s-%s" % (name, arm))
71
+ if out["collect"]:
72
+ print(out["collect"], "%s-collect" % name)
73
+ _warn(age)
74
+ return 0
75
+
76
+
77
+ def cmd_fanout(a):
78
+ return cmd_submit(a, _ids(a.arms) or sys.exit("--arms a,b,c"))
79
+
80
+
81
+ def _age(t):
82
+ s = time.time() - t
83
+ return "%dm" % (s / 60) if s < 5400 else "%.1fh" % (s / 3600)
84
+
85
+
86
+ def cmd_list(a):
87
+ st, _, inbox, age = J.snapshot(a.state_dir)
88
+ jobs = list(st["jobs"].values()) + [dict(j, state="inbox", why="not yet read by the dispatcher") for j in inbox]
89
+ if not a.all:
90
+ cut = time.time() - 6 * 3600
91
+ jobs = [j for j in jobs if j["state"] not in FINAL or j.get("t1", 0) > cut]
92
+ order = {"running": 0, "queued": 1, "inbox": 2, "failed": 3, "cancelled": 4, "done": 5}
93
+ jobs.sort(key=lambda j: (order.get(j["state"], 9), -float(j["spec"].get("priority") or 0), j["t_submit"]))
94
+ print("%-16s %-9s %4s %-22s %11s %7s %5s %s" % ("id", "state", "card", "name", "vram b/d", "cpu", "age", "why"))
95
+ for j in jobs:
96
+ s = j["spec"]
97
+ vram = "card" if s.get("exclusive") else "%s/%g" % ("%.1f" % j["vram_booked"] if j.get("vram_booked") is not None
98
+ and j["state"] == "running" else "-", s.get("vram_gb") or 0)
99
+ cpu = "%.1f/%s" % (j["cores_peak"], s.get("cpu") or "-") if j["state"] == "running" and j.get("cores_peak") is not None else str(s.get("cpu") or "")
100
+ print("%-16s %-9s %4s %-22s %11s %7s %5s %s" % (j["id"][:16], j["state"], "" if j.get("gpu") is None else j["gpu"],
101
+ s["name"][:22], vram, cpu, _age(j.get("t0") or j["t_submit"]),
102
+ (j.get("why") or "")[:120]))
103
+ _warn(age)
104
+ return 0
105
+
106
+
107
+ def cmd_show(a):
108
+ j = J.find(a.id, a.state_dir)
109
+ if j is None:
110
+ sys.exit("no job %s" % a.id)
111
+ print(json.dumps(j, indent=1, default=str))
112
+ log = Path(j["spec"].get("log_dir") or state_dir(a.state_dir) / "jobs" / a.id) / "log.txt"
113
+ if log.exists():
114
+ print("\n--- tail of %s" % log)
115
+ print(log.read_bytes()[-3000:].decode(errors="replace"))
116
+ return 0
117
+
118
+
119
+ def cmd_cancel(a):
120
+ for jid in a.ids:
121
+ J.cancel(jid, a.state_dir)
122
+ print("cancel requested for %d job(s); the dispatcher acts within one round" % len(a.ids))
123
+ return 0
124
+
125
+
126
+ def cmd_retarget(a):
127
+ gpus = None if a.gpus is None else [int(g) for g in _ids(a.gpus)]
128
+ if gpus is None and a.vram is None and a.ram is None:
129
+ sys.exit("pass --gpus, --vram and / or --ram")
130
+ for jid in a.ids:
131
+ J.retarget(jid, a.state_dir, gpus=gpus, vram_gb=a.vram, ram_gb=a.ram)
132
+ return 0
133
+
134
+
135
+ def cmd_wait(a):
136
+ s = J.wait(a.ids, a.poll, a.state_dir)
137
+ for i, v in s.items():
138
+ print(i, v)
139
+ return 0 if all(v == "done" for v in s.values()) else 1
140
+
141
+
142
+ def cmd_status(a):
143
+ st, status, inbox, age = J.snapshot(a.state_dir)
144
+ if not status:
145
+ print("no status yet: no dispatcher has run on %s" % state_dir(a.state_dir))
146
+ return 1
147
+ run = [j for j in st["jobs"].values() if j["state"] == "running"]
148
+ c = status.get("counts", {})
149
+ m = status.get("mem") or {}
150
+ print("dispatcher pid %s, last round %.0f s ago; %d running, %d queued, %d in inbox" % (
151
+ status.get("pid"), age, c.get("running", 0), c.get("queued", 0), len(inbox)))
152
+ print("cpu charged %s / budget %s cores; RAM used %.1f GB, line %.1f GB (%s)" % (
153
+ (status.get("cpu") or {}).get("charged"), (status.get("cpu") or {}).get("budget"), m.get("used", 0), m.get("line", 0),
154
+ m.get("source", "none")))
155
+ hd = (status.get("cfg") or {}).get("headroom_gb", 0)
156
+ print("\n%4s %6s %15s %8s %9s %8s %s" % ("card", "util%", "used/total GB", "booked", "foreign", "free", "jobs (now/booked GB)"))
157
+ for g, x in sorted(status.get("cards", {}).items(), key=lambda kv: int(kv[0])):
158
+ free = x["total_gb"] - hd - x["foreign_gb"] - x["pool_gb"]
159
+ js = ", ".join("%s %s (%.1f/%.1f)" % (j["id"], j["spec"]["name"][:16], j.get("vram_now") or 0, j.get("vram_booked") or 0)
160
+ for j in run if str(j.get("gpu")) == str(g))
161
+ print("%4s %6d %15s %8.1f %9.1f %8.1f %s" % (g, x["util"], "%.1f/%.1f" % (x["used_gb"], x["total_gb"]), x["pool_gb"],
162
+ x["foreign_gb"], max(free, 0.0), js or "-"))
163
+ cpu_jobs = [j for j in run if j.get("gpu") is None]
164
+ if cpu_jobs:
165
+ print("CPU jobs: " + ", ".join("%s %s" % (j["id"], j["spec"]["name"]) for j in cpu_jobs))
166
+ idle = [g for g in (status.get("idle") or {}) if not any(str(j.get("gpu")) == g for j in run)]
167
+ ready = [j for j in st["jobs"].values() if j["state"] == "queued" and B.is_gpu(j["spec"]) and j.get("cause") not in
168
+ ("after", "gate", "new")]
169
+ if idle and ready:
170
+ print("\nidle card(s) %s while %d GPU job(s) wait; `pinka list` shows why" % (",".join(idle), len(ready)))
171
+ _warn(age)
172
+ return 0
173
+
174
+
175
+ def cmd_usage(a):
176
+ now, rows = time.time(), []
177
+ try:
178
+ for ln in (state_dir(a.state_dir) / "usage.jsonl").read_text().splitlines():
179
+ r = json.loads(ln)
180
+ if r.get("t", 0) >= now - a.hours * 3600:
181
+ rows.append(r)
182
+ except (OSError, ValueError):
183
+ pass
184
+ if not rows:
185
+ print("no usage samples in the last %g h" % a.hours)
186
+ return 0
187
+ split, card_h = {}, 0.0
188
+ for r, nxt in zip(rows, rows[1:] + [None]):
189
+ dt = min((nxt["t"] - r["t"]) if nxt else 60, 300) / 3600
190
+ for util, used, booked, jobs in r["cards"].values():
191
+ card_h += dt
192
+ k = ("computing" if util >= 10 else "job, GPU idle") if jobs else (
193
+ "queued: " + max(r["q_gpu"], key=r["q_gpu"].get) if r.get("q_gpu") else "no work queued")
194
+ split[k] = split.get(k, 0.0) + dt
195
+ print("last %g h: %.2f card-hours\n\n%-28s %10s %6s" % (a.hours, card_h, "card state", "card-hours", "share"))
196
+ for k, v in sorted(split.items(), key=lambda kv: -kv[1]):
197
+ print("%-28s %10.2f %5.0f%%" % (k, v, 100 * v / max(card_h, 1e-9)))
198
+ return 0
199
+
200
+
201
+ def cmd_history(a):
202
+ hist = _hist(a)
203
+ print("%-28s %5s %18s %12s %12s" % ("key", "runs", "VRAM p95/max GB", "cores max", "RAM max GB"))
204
+ for k, e in sorted(hist.items()):
205
+ v = e.get("vram") or []
206
+ if not a.all and len(v) < 1:
207
+ continue
208
+ print("%-28s %5d %18s %12s %12s" % (k[:28], len(v), "%.1f/%.1f" % (B._p95(v), max(v)) if v else "-",
209
+ "%.1f" % max(e["cores"]) if e.get("cores") else "-",
210
+ "%.1f" % max(e["ram"]) if e.get("ram") else "-"))
211
+ conc = (J.snapshot(a.state_dir)[1].get("conc") or {})
212
+ if conc:
213
+ print("\nsame-key groups (booked together on a card): key, share GB per job, largest measured count n_max")
214
+ for k, v in sorted(conc.items()):
215
+ print("%-28s %6.1f %4d" % (k[:28], v["share"], v["n_max"]))
216
+ return 0
217
+
218
+
219
+ def cmd_config(a):
220
+ print(json.dumps(load_config(state_dir(a.state_dir)), indent=1))
221
+ return 0
222
+
223
+
224
+ def cmd_daemon(a):
225
+ from .dispatcher import Dispatcher
226
+ return Dispatcher(a.state_dir).run(once=a.once)
227
+
228
+
229
+ def cmd_run(a):
230
+ from .batch import run_batch
231
+ cfg = {k: v for k, v in (("poll_s", a.poll), ("cpu_budget", a.cpus), ("ram_budget_gb", a.ram_gb)) if v}
232
+ cfg["idle_s"] = 0.0 # the runner owns its cards: an empty card is idle at once
233
+ if a.gpus is not None:
234
+ cfg["cards"] = [int(g) for g in _ids(a.gpus)]
235
+ try:
236
+ return run_batch(a.jobs, a.state_dir, cfg=cfg, retry_failed=a.retry_failed)
237
+ except ValueError as e:
238
+ sys.exit(str(e))
239
+
240
+
241
+ def _submit_flags(s):
242
+ s.add_argument("--name", default="", help="job name (default: the command's first word); also its history key")
243
+ s.add_argument("--key", default="", help="history key, when names differ but resource use does not")
244
+ s.add_argument("--vram", type=float, default=None, help="peak VRAM GB on its card; 0 = CPU job (default: history)")
245
+ s.add_argument("--cpu", type=int, default=None, help="cores; > 0 pins the job to that many free cores (Linux)")
246
+ s.add_argument("--ram", type=float, default=None, help="host RAM GB")
247
+ s.add_argument("--exclusive", action="store_true", help="alone on its card")
248
+ s.add_argument("--gpus", default="", help="allowed cards, e.g. 0,2 (default: any)")
249
+ s.add_argument("--tag", default="", help="per-card cap by tag (config tag_caps)")
250
+ s.add_argument("--priority", type=float, default=0.0, help="higher starts first")
251
+ s.add_argument("--after", default="", help="ids that must be done first (comma-separated)")
252
+ s.add_argument("--when-exists", default="", help="stay queued until this path exists")
253
+ s.add_argument("--tries", type=int, default=1)
254
+ s.add_argument("--timeout-h", type=float, default=0.0)
255
+ s.add_argument("--env", action="append", default=[], help="K=V (repeatable)")
256
+ s.add_argument("--no-copy-env", dest="copy_env", action="store_false",
257
+ help="run with the dispatcher's environment, not this shell's")
258
+ s.add_argument("--cwd", default="")
259
+ s.add_argument("--log-dir", default="", help="log.txt, STATUS, DONE / ERROR here (default <state>/jobs/<id>)")
260
+ s.add_argument("--owner", default="")
261
+ s.add_argument("argv", nargs=argparse.REMAINDER, metavar="CMD")
262
+
263
+
264
+ def main(argv=None):
265
+ ap = argparse.ArgumentParser(prog="pinka", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
266
+ ap.add_argument("--state-dir", default=None, help="default: $PINKA_HOME, $XDG_STATE_HOME/pinka, ~/.pinka")
267
+ sub = ap.add_subparsers(dest="cmd", required=True)
268
+ sub.add_parser("daemon").add_argument("--once", action="store_true")
269
+ _submit_flags(sub.add_parser("submit"))
270
+ s = sub.add_parser("fanout")
271
+ s.add_argument("--arms", required=True)
272
+ s.add_argument("--collect", default="", help="shell command run after every arm is done ({arms} = all arms)")
273
+ _submit_flags(s)
274
+ s = sub.add_parser("run")
275
+ s.add_argument("jobs")
276
+ s.add_argument("--gpus", default=None, help="cards to use (default: CUDA_VISIBLE_DEVICES, else all)")
277
+ s.add_argument("--cpus", type=float, default=None, help="CPU budget (default: the cores this process may use)")
278
+ s.add_argument("--ram-gb", type=float, default=None, help="RAM budget (default: measure the host)")
279
+ s.add_argument("--retry-failed", action="store_true")
280
+ s.add_argument("--poll", type=float, default=2.0)
281
+ sub.add_parser("list").add_argument("--all", action="store_true")
282
+ sub.add_parser("show").add_argument("id")
283
+ sub.add_parser("cancel").add_argument("ids", nargs="+")
284
+ s = sub.add_parser("retarget")
285
+ s.add_argument("ids", nargs="+")
286
+ s.add_argument("--gpus", default=None, help="allowed cards ('' = any)")
287
+ s.add_argument("--vram", type=float, default=None)
288
+ s.add_argument("--ram", type=float, default=None)
289
+ s = sub.add_parser("wait")
290
+ s.add_argument("ids", nargs="+")
291
+ s.add_argument("--poll", type=float, default=30.0)
292
+ sub.add_parser("status")
293
+ sub.add_parser("usage").add_argument("--hours", type=float, default=24.0)
294
+ sub.add_parser("history").add_argument("--all", action="store_true")
295
+ sub.add_parser("config")
296
+ a = ap.parse_args(argv)
297
+ return globals()["cmd_" + a.cmd](a)
298
+
299
+
300
+ if __name__ == "__main__":
301
+ sys.exit(main())