pinka 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gao Chengzhi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
pinka-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: pinka
3
+ Version: 0.1.0
4
+ Summary: Pack GPU jobs onto shared cards by measured memory: a single-node job pool with VRAM/CPU/RAM booking, dependencies and retries
5
+ Author: Gao Chengzhi
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Gaochengzhi/pinka
8
+ Project-URL: Repository, https://github.com/Gaochengzhi/pinka
9
+ Project-URL: Issues, https://github.com/Gaochengzhi/pinka/issues
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Environment :: GPU :: NVIDIA CUDA
13
+ Classifier: Topic :: System :: Distributed Computing
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: nvml
18
+ Requires-Dist: nvidia-ml-py; extra == "nvml"
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ <p align="center">
24
+ <img src="https://raw.githubusercontent.com/Gaochengzhi/pinka/84808d9ff3edd2d93b01bb41352f6317eeca9b79/docs/logo.svg" alt="pinka 拼卡" width="340">
25
+ </p>
26
+
27
+ <p align="center"><b>Pack GPU jobs onto shared cards by the memory they actually use.</b></p>
28
+
29
+ <p align="center">
30
+ <a href="https://pypi.org/project/pinka/"><img src="https://img.shields.io/pypi/v/pinka" alt="PyPI"></a>
31
+ <a href="https://pypi.org/project/pinka/"><img src="https://img.shields.io/pypi/pyversions/pinka" alt="Python"></a>
32
+ <a href="https://github.com/Gaochengzhi/pinka/actions/workflows/ci.yml"><img src="https://github.com/Gaochengzhi/pinka/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
33
+ <a href="https://github.com/Gaochengzhi/pinka/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT"></a>
34
+ <a href="https://github.com/Gaochengzhi/pinka/blob/main/pyproject.toml"><img src="https://img.shields.io/badge/dependencies-none-brightgreen" alt="Dependencies: none"></a>
35
+ </p>
36
+
37
+ <p align="center">
38
+ <img src="https://raw.githubusercontent.com/Gaochengzhi/pinka/84808d9ff3edd2d93b01bb41352f6317eeca9b79/docs/pinka.svg" alt="Left: a whole-card queue gives each GPU one job and leaves most VRAM idle while jobs wait. Right: pinka takes jobs off a spool, books each at its measured peak instead of its declaration, and stacks several jobs per GPU until the queue is empty." width="100%">
39
+ </p>
40
+
41
+ Most single-machine schedulers hand out whole GPUs, so a job that needs 9 GB holds an 80 GB card while others wait.
42
+ pinka is a job pool for one machine that books each job at the VRAM it really uses and stacks as many as fit on each
43
+ card. The name is Mandarin *pīn kǎ* (拼卡): sharing a card, the way people share a taxi.
44
+
45
+ - **Measured booking.** A job starts at its declared VRAM; once it has run a while, or its name has a history, it is
46
+ booked at its measured peak, and the space it frees goes to the next job.
47
+ - **Chains and retries.** `--after` dependencies, `--tries`, requeue on CUDA out-of-memory. Every job ends with a
48
+ `DONE` or `ERROR` marker that any script can wait on.
49
+ - **Guards.** A job far above its declaration is stopped and requeued before it takes a neighbour down; host RAM is
50
+ admitted and guarded too.
51
+ - **Nothing to set up.** No root, no database (the state is a folder of JSON files), Python standard library only.
52
+
53
+ pinka is a slimmed port of a private pool that ran about 53,000 jobs a month on a shared multi-GPU box.
54
+
55
+ ## Install
56
+
57
+ ```bash
58
+ pip install pinka # or: uv tool install pinka
59
+ pip install 'pinka[nvml]' # optional: read the cards through NVML instead of nvidia-smi
60
+ ```
61
+
62
+ GPU jobs need Linux and NVIDIA drivers; elsewhere pinka runs CPU-only jobs.
63
+
64
+ ## Quickstart
65
+
66
+ ```bash
67
+ pinka daemon & # the dispatcher; keep it running (tmux, systemd user unit)
68
+ A=$(pinka submit --name eval-1 --vram 6 -- python eval.py --shard 1)
69
+ B=$(pinka submit --name eval-2 --vram 6 -- python eval.py --shard 2)
70
+ pinka submit --name report --vram 0 --after $A,$B -- python report.py
71
+ pinka status # per card: used, booked, free; which jobs run where
72
+ pinka wait $A $B # block until both end; exit 0 if all are done
73
+ ```
74
+
75
+ `--vram` is the peak VRAM in GB; `--vram 0` makes a CPU-only job.
76
+
77
+ ## Why not X
78
+
79
+ | Tool | Why it does not fit this case |
80
+ |:--|:--|
81
+ | task-spooler (`ts -G`), simple_gpu_scheduler | each job gets whole free cards |
82
+ | pueue | a fine queue, but it does not know about GPUs |
83
+ | Ray (`num_gpus=0.25`) | fractions are set by hand and never measured; a large dependency |
84
+ | Slurm GRES shards | needs root and cluster setup |
85
+
86
+ If each of your jobs needs a whole GPU, task-spooler or pueue is the simpler choice.
87
+
88
+ ## Learn more
89
+
90
+ Every command, the booking and guard rules, the state layout, hooks and configuration are in
91
+ [AGENTS.md](https://github.com/Gaochengzhi/pinka/blob/main/AGENTS.md). It is written for people and coding agents alike: point your AI at it.
92
+
93
+ ## Licence
94
+
95
+ MIT ([LICENSE](https://github.com/Gaochengzhi/pinka/blob/main/LICENSE)). Copyright (c) 2026 Gao Chengzhi.
pinka-0.1.0/README.md ADDED
@@ -0,0 +1,73 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/Gaochengzhi/pinka/84808d9ff3edd2d93b01bb41352f6317eeca9b79/docs/logo.svg" alt="pinka 拼卡" width="340">
3
+ </p>
4
+
5
+ <p align="center"><b>Pack GPU jobs onto shared cards by the memory they actually use.</b></p>
6
+
7
+ <p align="center">
8
+ <a href="https://pypi.org/project/pinka/"><img src="https://img.shields.io/pypi/v/pinka" alt="PyPI"></a>
9
+ <a href="https://pypi.org/project/pinka/"><img src="https://img.shields.io/pypi/pyversions/pinka" alt="Python"></a>
10
+ <a href="https://github.com/Gaochengzhi/pinka/actions/workflows/ci.yml"><img src="https://github.com/Gaochengzhi/pinka/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
11
+ <a href="https://github.com/Gaochengzhi/pinka/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT"></a>
12
+ <a href="https://github.com/Gaochengzhi/pinka/blob/main/pyproject.toml"><img src="https://img.shields.io/badge/dependencies-none-brightgreen" alt="Dependencies: none"></a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <img src="https://raw.githubusercontent.com/Gaochengzhi/pinka/84808d9ff3edd2d93b01bb41352f6317eeca9b79/docs/pinka.svg" alt="Left: a whole-card queue gives each GPU one job and leaves most VRAM idle while jobs wait. Right: pinka takes jobs off a spool, books each at its measured peak instead of its declaration, and stacks several jobs per GPU until the queue is empty." width="100%">
17
+ </p>
18
+
19
+ Most single-machine schedulers hand out whole GPUs, so a job that needs 9 GB holds an 80 GB card while others wait.
20
+ pinka is a job pool for one machine that books each job at the VRAM it really uses and stacks as many as fit on each
21
+ card. The name is Mandarin *pīn kǎ* (拼卡): sharing a card, the way people share a taxi.
22
+
23
+ - **Measured booking.** A job starts at its declared VRAM; once it has run a while, or its name has a history, it is
24
+ booked at its measured peak, and the space it frees goes to the next job.
25
+ - **Chains and retries.** `--after` dependencies, `--tries`, requeue on CUDA out-of-memory. Every job ends with a
26
+ `DONE` or `ERROR` marker that any script can wait on.
27
+ - **Guards.** A job far above its declaration is stopped and requeued before it takes a neighbour down; host RAM is
28
+ admitted and guarded too.
29
+ - **Nothing to set up.** No root, no database (the state is a folder of JSON files), Python standard library only.
30
+
31
+ pinka is a slimmed port of a private pool that ran about 53,000 jobs a month on a shared multi-GPU box.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install pinka # or: uv tool install pinka
37
+ pip install 'pinka[nvml]' # optional: read the cards through NVML instead of nvidia-smi
38
+ ```
39
+
40
+ GPU jobs need Linux and NVIDIA drivers; elsewhere pinka runs CPU-only jobs.
41
+
42
+ ## Quickstart
43
+
44
+ ```bash
45
+ pinka daemon & # the dispatcher; keep it running (tmux, systemd user unit)
46
+ A=$(pinka submit --name eval-1 --vram 6 -- python eval.py --shard 1)
47
+ B=$(pinka submit --name eval-2 --vram 6 -- python eval.py --shard 2)
48
+ pinka submit --name report --vram 0 --after $A,$B -- python report.py
49
+ pinka status # per card: used, booked, free; which jobs run where
50
+ pinka wait $A $B # block until both end; exit 0 if all are done
51
+ ```
52
+
53
+ `--vram` is the peak VRAM in GB; `--vram 0` makes a CPU-only job.
54
+
55
+ ## Why not X
56
+
57
+ | Tool | Why it does not fit this case |
58
+ |:--|:--|
59
+ | task-spooler (`ts -G`), simple_gpu_scheduler | each job gets whole free cards |
60
+ | pueue | a fine queue, but it does not know about GPUs |
61
+ | Ray (`num_gpus=0.25`) | fractions are set by hand and never measured; a large dependency |
62
+ | Slurm GRES shards | needs root and cluster setup |
63
+
64
+ If each of your jobs needs a whole GPU, task-spooler or pueue is the simpler choice.
65
+
66
+ ## Learn more
67
+
68
+ Every command, the booking and guard rules, the state layout, hooks and configuration are in
69
+ [AGENTS.md](https://github.com/Gaochengzhi/pinka/blob/main/AGENTS.md). It is written for people and coding agents alike: point your AI at it.
70
+
71
+ ## Licence
72
+
73
+ MIT ([LICENSE](https://github.com/Gaochengzhi/pinka/blob/main/LICENSE)). Copyright (c) 2026 Gao Chengzhi.
@@ -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"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -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)
@@ -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))