modelpolis 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.
@@ -0,0 +1,382 @@
1
+ """A loaded model: chunk the caller's inputs and exchange messages with the worker.
2
+
3
+ See plan/DESIGN.md sections 3.3, 3.4 and 4. ``Model`` starts one worker, waits for ``Ready``,
4
+ then sends one request per chunk of ``batch`` items: the chunk's inputs are written as ``.npy``
5
+ files in the session directory, and each reply's outputs are read back from there. ``predict``
6
+ stacks the chunks; ``stream`` yields them one at a time, deleting each chunk's files first, so
7
+ memory stays flat however long the input is. An output whose items were cropped to different
8
+ sizes (short inputs, see ``runner.api.InputMap``) comes back as a list of per-item arrays.
9
+ """
10
+
11
+ import itertools
12
+ import json
13
+ import os
14
+ import queue
15
+ import sys
16
+ import threading
17
+ from collections.abc import Callable, Iterable, Iterator
18
+ from pathlib import Path
19
+ from typing import Any, Self
20
+
21
+ import numpy as np
22
+
23
+ from . import launch
24
+ from .api import (
25
+ API_VERSION,
26
+ ArrayFile,
27
+ ErrorReply,
28
+ Indices,
29
+ OkReply,
30
+ Range,
31
+ Ready,
32
+ Request,
33
+ Spec,
34
+ Subset,
35
+ output_shape,
36
+ pack_text,
37
+ split_items,
38
+ worker_message_from_json,
39
+ )
40
+ from .store import find_image
41
+
42
+ LOG_TAIL_CHARS = 4000
43
+
44
+
45
+ class WorkerError(RuntimeError):
46
+ """The session failed (no ``Ready``, a timeout, a closed pipe); the model is closed."""
47
+
48
+
49
+ class RequestError(RuntimeError):
50
+ """The worker answered a request with an error; the model stays usable."""
51
+
52
+ def __init__(self, message: str, traceback: str | None = None):
53
+ super().__init__(message)
54
+ self.traceback = traceback
55
+
56
+
57
+ def read_spec(text: str) -> Spec:
58
+ """Read the spec printed by ``worker describe``; a different API version is an error."""
59
+ d = json.loads(text)
60
+ api = d.get("api") if isinstance(d, dict) else None
61
+ if api != API_VERSION:
62
+ raise RuntimeError(
63
+ f"API version mismatch: the image reports api {api!r}, "
64
+ f"this runner speaks api {API_VERSION}"
65
+ )
66
+ return Spec.from_json(d)
67
+
68
+
69
+ def default_device(spec: Spec) -> str:
70
+ """``cuda:0`` if the spec's first device is ``cuda``, else ``cpu``."""
71
+ return "cuda:0" if spec.resources.devices[:1] == ["cuda"] else "cpu"
72
+
73
+
74
+ def check_options(spec: Spec, options: dict[str, Any] | None) -> dict[str, Any]:
75
+ """Type-check the caller's options against the spec and fill every default."""
76
+ options = dict(options or {})
77
+ unknown = sorted(set(options) - set(spec.options))
78
+ if unknown:
79
+ raise ValueError(f"unknown option(s) {unknown}; the spec has {sorted(spec.options)}")
80
+ filled = {}
81
+ for name, o in spec.options.items():
82
+ value = options.get(name, o.default)
83
+ if o.type == "bool":
84
+ ok = isinstance(value, bool)
85
+ elif o.type == "int":
86
+ ok = isinstance(value, int) and not isinstance(value, bool)
87
+ elif o.type == "float":
88
+ ok = isinstance(value, int | float) and not isinstance(value, bool)
89
+ value = float(value) if ok else value
90
+ elif o.type == "str":
91
+ ok = isinstance(value, str)
92
+ elif o.type == "choice":
93
+ ok = value in (o.choices or [])
94
+ else:
95
+ raise ValueError(f"option {name!r} has unknown type {o.type!r} in the spec")
96
+ if not ok:
97
+ expected = f"one of {o.choices}" if o.type == "choice" else f"a {o.type}"
98
+ raise TypeError(f"option {name!r} must be {expected}, got {value!r}")
99
+ filled[name] = value
100
+ return filled
101
+
102
+
103
+ def check_outputs(spec: Spec, outputs: str | list[str] | None) -> list[str]:
104
+ """The requested output names; ``None`` means all of them."""
105
+ if outputs is None:
106
+ return list(spec.outputs)
107
+ if isinstance(outputs, str):
108
+ outputs = [outputs]
109
+ unknown = [o for o in outputs if o not in spec.outputs]
110
+ if unknown:
111
+ raise ValueError(f"unknown output(s) {unknown}; the spec has {sorted(spec.outputs)}")
112
+ return list(outputs)
113
+
114
+
115
+ def convert_subset(
116
+ spec: Spec, outputs: list[str], subset: dict | None, options: dict[str, Any] | None = None
117
+ ) -> dict[str, Subset]:
118
+ """Turn ``{axis: list | slice}`` into the explicit forms, checking each axis may be subset.
119
+
120
+ An open slice ends at the output's size under ``options`` (its window, if an option picks it).
121
+ """
122
+ converted = {}
123
+ for axis, sel in (subset or {}).items():
124
+ having = [o for o in outputs if axis in spec.outputs[o].axes]
125
+ if not having:
126
+ raise ValueError(f"subset axis {axis!r} is not an axis of the outputs {outputs}")
127
+ for o in having:
128
+ if axis not in spec.outputs[o].subset_axes:
129
+ raise ValueError(f"output {o!r} cannot be subset on axis {axis!r}")
130
+ if isinstance(sel, list):
131
+ converted[axis] = Indices([int(i) for i in sel])
132
+ elif isinstance(sel, slice):
133
+ if sel.step not in (None, 1):
134
+ raise ValueError(f"subset on {axis!r}: a slice step must be 1, got {sel.step}")
135
+ sizes = {
136
+ output_shape(spec, o, options or {})[spec.outputs[o].axes.index(axis)]
137
+ for o in having
138
+ }
139
+ if (sel.start is None or sel.stop is None) and len(sizes) > 1:
140
+ raise ValueError(f"subset on {axis!r}: the outputs differ in size {sorted(sizes)}")
141
+ size = sizes.pop()
142
+ start = 0 if sel.start is None else int(sel.start)
143
+ stop = size if sel.stop is None else int(sel.stop)
144
+ converted[axis] = Range(start, stop)
145
+ else:
146
+ raise TypeError(f"subset on {axis!r} must be a list or a slice, got {sel!r}")
147
+ return converted
148
+
149
+
150
+ def _rows(spec: Spec, inputs: Any) -> Iterator[tuple]:
151
+ """One tuple per item, in the order of ``spec.inputs``."""
152
+ names = list(spec.inputs)
153
+ if isinstance(inputs, dict):
154
+ if set(inputs) != set(names):
155
+ raise ValueError(f"inputs must have the keys {names}, got {sorted(inputs)}")
156
+ columns = [inputs[n] for n in names]
157
+ else:
158
+ if len(names) != 1:
159
+ raise ValueError(f"this model has several inputs {names}: pass a dict of lists")
160
+ columns = [inputs]
161
+ for name, column in zip(names, columns, strict=True):
162
+ if isinstance(column, str | bytes):
163
+ raise TypeError(f"input {name!r} must be a list or iterable of items, not a string")
164
+ return zip(*columns, strict=True)
165
+
166
+
167
+ def _join_chunks(chunks: list) -> np.ndarray | list[np.ndarray]:
168
+ """Stack the chunks of one output if every item has one shape, else a list of items."""
169
+ if all(isinstance(c, np.ndarray) for c in chunks) and len({c.shape[1:] for c in chunks}) == 1:
170
+ return np.concatenate(chunks)
171
+ return [item for c in chunks for item in c]
172
+
173
+
174
+ class Model:
175
+ """One running model. Use as a context manager, or call ``close()``.
176
+
177
+ ``start(sif, device)`` starts the worker and returns an object like ``launch.Worker``
178
+ (``process``, ``session``, ``close(failed)``); tests pass one that runs without Apptainer.
179
+ """
180
+
181
+ def __init__(
182
+ self,
183
+ sif: str | os.PathLike,
184
+ spec: Spec,
185
+ device: str,
186
+ start: Callable[[str | os.PathLike, str], Any] = launch.Worker,
187
+ ):
188
+ self.spec = spec
189
+ self.device = device
190
+ self.ready: Ready | None = None
191
+ self.infer_s = 0.0 # sum of the worker's infer_s over every answered request
192
+ self._next_id = 0
193
+ self._closed = False
194
+ self._worker = start(sif, device)
195
+ self._lines: queue.Queue[str | None] = queue.Queue()
196
+ threading.Thread(
197
+ target=self._read, args=(self._worker.process.stdout,), daemon=True
198
+ ).start()
199
+ message = self._receive(spec.resources.load_timeout_s, "the ready message")
200
+ if not isinstance(message, Ready):
201
+ self._fail(f"expected the ready message, got {message!r}")
202
+ if message.api != API_VERSION:
203
+ self._fail(
204
+ f"API version mismatch: the worker reports api {message.api}, "
205
+ f"this runner speaks api {API_VERSION}"
206
+ )
207
+ self.ready = message
208
+
209
+ # -- the pipe ----------------------------------------------------------
210
+
211
+ def _read(self, stdout) -> None:
212
+ try:
213
+ for line in stdout:
214
+ self._lines.put(line)
215
+ except (OSError, ValueError):
216
+ pass # the pipe was closed under us
217
+ self._lines.put(None)
218
+
219
+ def _fail(self, reason: str):
220
+ """Close the session as failed and raise with the tail of the worker log."""
221
+ self._closed = True
222
+ self._worker.close(failed=True)
223
+ saved = getattr(self._worker, "saved_log", None)
224
+ tail = Path(saved).read_text(errors="replace")[-LOG_TAIL_CHARS:] if saved else ""
225
+ where = f" (log: {saved})" if saved else ""
226
+ raise WorkerError(f"{reason}{where}\n--- worker log tail ---\n{tail}")
227
+
228
+ def _receive(self, timeout: float, what: str):
229
+ try:
230
+ line = self._lines.get(timeout=timeout)
231
+ except queue.Empty:
232
+ self._fail(f"timed out after {timeout} s waiting for {what}")
233
+ if line is None:
234
+ code = self._worker.process.poll()
235
+ self._fail(f"the worker closed its output while we waited for {what} (exit {code})")
236
+ try:
237
+ return worker_message_from_json(json.loads(line))
238
+ except (ValueError, KeyError, TypeError) as e:
239
+ self._fail(f"unreadable message from the worker: {line.strip()!r} ({e})")
240
+
241
+ def _send(self, request: Request) -> None:
242
+ try:
243
+ self._worker.process.stdin.write(json.dumps(request.to_json()) + "\n")
244
+ self._worker.process.stdin.flush()
245
+ except (BrokenPipeError, OSError, ValueError):
246
+ self._fail("the worker closed its input")
247
+
248
+ # -- one chunk ---------------------------------------------------------
249
+
250
+ def _run_chunk(self, rows, outputs, subset, options) -> dict[str, np.ndarray | list]:
251
+ request_id = self._next_id
252
+ self._next_id += 1
253
+ session = Path(self._worker.session)
254
+ files = []
255
+ try:
256
+ inputs = {}
257
+ for name, column in zip(self.spec.inputs, zip(*rows, strict=True), strict=True):
258
+ file = f"req-{request_id}-{name}.npy"
259
+ if self.spec.inputs[name].kind == "text":
260
+ for i, s in enumerate(column):
261
+ if not isinstance(s, str):
262
+ raise TypeError(f"input {name!r}: item {i} is not a string: {s!r}")
263
+ data, lengths = pack_text(list(column))
264
+ else:
265
+ data, lengths = np.stack([np.asarray(a) for a in column]), None
266
+ np.save(session / file, data)
267
+ files.append(session / file)
268
+ inputs[name] = ArrayFile(file, lengths)
269
+ self._send(Request(request_id, inputs, outputs, subset, options))
270
+ while True:
271
+ reply = self._receive(self.spec.resources.infer_timeout_s, f"reply {request_id}")
272
+ if isinstance(reply, ErrorReply):
273
+ raise RequestError(f"request {request_id}: {reply.error}", reply.traceback)
274
+ if not isinstance(reply, OkReply):
275
+ self._fail(f"expected a reply to request {request_id}, got {reply!r}")
276
+ for f in reply.outputs.values():
277
+ files.append(session / f.file)
278
+ if reply.id == request_id:
279
+ self.infer_s += reply.infer_s
280
+ break
281
+ if reply.id > request_id:
282
+ self._fail(f"reply {reply.id} arrived while waiting for {request_id}")
283
+ # a late reply to an interrupted earlier request: its files are dropped below
284
+ missing = [o for o in outputs if o not in reply.outputs]
285
+ if missing:
286
+ self._fail(f"reply {request_id} lacks the outputs {missing}")
287
+ result = {}
288
+ for o in outputs:
289
+ f = reply.outputs[o]
290
+ array = np.load(session / f.file)
291
+ if f.lengths is None:
292
+ result[o] = array
293
+ continue
294
+ input_map = self.spec.outputs[o].input_map
295
+ if input_map is None:
296
+ self._fail(f"reply {request_id}: {o} has lengths but no input_map in the spec")
297
+ axis = self.spec.outputs[o].axes.index(input_map.axis)
298
+ result[o] = split_items(array, f.lengths, axis)
299
+ return result
300
+ finally:
301
+ for path in files:
302
+ path.unlink(missing_ok=True)
303
+
304
+ # -- the public API ----------------------------------------------------
305
+
306
+ def stream(
307
+ self,
308
+ inputs: Any,
309
+ outputs: str | list[str] | None = None,
310
+ subset: dict | None = None,
311
+ options: dict[str, Any] | None = None,
312
+ batch: int | None = None,
313
+ ) -> Iterator[tuple[np.ndarray, dict[str, np.ndarray | list[np.ndarray]]]]:
314
+ """Yield ``(positions, outputs)`` per chunk; ``positions`` index the caller's input.
315
+
316
+ Each output is one stacked array, or a list of per-item arrays if their shapes differ.
317
+ """
318
+ if self._closed:
319
+ raise RuntimeError("the model is closed")
320
+ outputs = check_outputs(self.spec, outputs)
321
+ options = check_options(self.spec, options)
322
+ subset = convert_subset(self.spec, outputs, subset, options)
323
+ batch = self.spec.resources.batch if batch is None else batch
324
+ if isinstance(batch, bool) or not isinstance(batch, int) or batch < 1:
325
+ raise ValueError(f"batch must be a positive int, got {batch!r}")
326
+ rows = _rows(self.spec, inputs)
327
+ return self._stream(rows, outputs, subset, options, batch)
328
+
329
+ def _stream(self, rows, outputs, subset, options, batch):
330
+ start = 0
331
+ while chunk := list(itertools.islice(rows, batch)):
332
+ if self._closed:
333
+ raise RuntimeError("the model is closed")
334
+ result = self._run_chunk(chunk, outputs, subset, options)
335
+ yield np.arange(start, start + len(chunk)), result
336
+ start += len(chunk)
337
+
338
+ def predict(
339
+ self,
340
+ inputs: Iterable | dict[str, Iterable],
341
+ outputs: str | list[str] | None = None,
342
+ subset: dict | None = None,
343
+ options: dict[str, Any] | None = None,
344
+ batch: int | None = None,
345
+ ) -> dict[str, np.ndarray | list[np.ndarray]]:
346
+ """Run every chunk; per output, one stacked array, or a list if item shapes differ."""
347
+ parts = [out for _, out in self.stream(inputs, outputs, subset, options, batch)]
348
+ if not parts:
349
+ raise ValueError("no inputs given")
350
+ return {name: _join_chunks([p[name] for p in parts]) for name in parts[0]}
351
+
352
+ def close(self) -> None:
353
+ """End the worker and remove the session folder."""
354
+ if not self._closed:
355
+ self._closed = True
356
+ self._worker.close()
357
+
358
+ def __enter__(self) -> Self:
359
+ return self
360
+
361
+ def __exit__(self, exc_type, exc, tb) -> None:
362
+ self.close()
363
+
364
+
365
+ def describe(name_or_path: str | os.PathLike, sha256: str | None = None) -> Spec:
366
+ """The spec of a name or SIF path; fetch if absent from the store, then check the API."""
367
+ return read_spec(launch.describe(find_image(name_or_path, sha256)))
368
+
369
+
370
+ def load(
371
+ name_or_path: str | os.PathLike,
372
+ device: str | None = None,
373
+ sha256: str | None = None,
374
+ start: Callable[[str | os.PathLike, str], Any] = launch.Worker,
375
+ ) -> Model:
376
+ """Find or fetch the image, check its spec, and start its worker."""
377
+ sif = find_image(name_or_path, sha256)
378
+ spec = read_spec(launch.describe(sif))
379
+ device = device or default_device(spec)
380
+ message = f"Loading {spec.name} {spec.version} from {sif} on {device}"
381
+ print(" ".join(message.split()), file=sys.stderr, flush=True)
382
+ return Model(sif, spec, device, start)
@@ -0,0 +1,297 @@
1
+ """The model store: find or pull a SIF by name, or check a SIF path's checksum.
2
+
3
+ The store root is ``$MODELPOLIS_HOME``, default ``~/.cache/modelpolis``. Images live at
4
+ ``images/<name>/<version>-<sha12>.sif``; worker logs go to ``logs/``.
5
+ The catalogue is ``catalog.toml`` at the repository root, written by ``modelpolis publish``.
6
+ """
7
+
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import re
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ import tomllib
16
+ from dataclasses import dataclass
17
+ from http.client import HTTPException
18
+ from pathlib import Path
19
+ from urllib.error import HTTPError
20
+ from urllib.request import urlopen
21
+
22
+ from .api import API_VERSION
23
+
24
+ ENV_VAR = "MODELPOLIS_HOME"
25
+ DEFAULT_HOME = "~/.cache/modelpolis"
26
+ CATALOG = Path(__file__).resolve().parents[3] / "catalog.toml"
27
+ DOCKER_HUB_NAMESPACE = "tanlab"
28
+ DOCKER_HUB_PREFIX = "modelpolis-"
29
+ DOCKER_HUB_TIMEOUT = 30
30
+ MODEL_NAME = re.compile(r"[a-z][a-z0-9_]*")
31
+ IMAGE_TAG = re.compile(r"([0-9]+(?:\.[0-9]+)*)-api([0-9]+)-([0-9a-f]{12})")
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class DockerHubTag:
36
+ """A published tag, retaining the version spelling used in its reference and filename."""
37
+
38
+ tag: str
39
+ version: str
40
+ api: int
41
+ sha12: str
42
+
43
+
44
+ def docker_hub_tags(name: str) -> list[DockerHubTag]:
45
+ """Read every page of rule-shaped tags, including other API versions, without a login.
46
+
47
+ Return an empty list for an invalid model name or an absent/private repository (404).
48
+ Connection and response errors raise RuntimeError without response bodies.
49
+ """
50
+ if MODEL_NAME.fullmatch(name) is None:
51
+ return []
52
+ repository = f"{DOCKER_HUB_NAMESPACE}/{DOCKER_HUB_PREFIX}{name}"
53
+ endpoint = (
54
+ f"https://hub.docker.com/v2/namespaces/{DOCKER_HUB_NAMESPACE}"
55
+ f"/repositories/{DOCKER_HUB_PREFIX}{name}/tags"
56
+ )
57
+ url = f"{endpoint}?page_size=100"
58
+ tags = []
59
+ visited = set()
60
+ while url is not None:
61
+ try:
62
+ # Pagination stays on this repository and cannot loop indefinitely.
63
+ if not isinstance(url, str) or not url.startswith(endpoint + "?") or url in visited:
64
+ raise ValueError("invalid next page")
65
+ visited.add(url)
66
+ with urlopen(url, timeout=DOCKER_HUB_TIMEOUT) as response:
67
+ page = json.load(response)
68
+ if not isinstance(page, dict) or not isinstance(page["results"], list):
69
+ raise TypeError("invalid tag list")
70
+ for result in page["results"]:
71
+ if not isinstance(result, dict) or not isinstance(result["name"], str):
72
+ raise TypeError("invalid tag name")
73
+ match = IMAGE_TAG.fullmatch(result["name"])
74
+ if match:
75
+ version, api, sha12 = match.groups()
76
+ tags.append(DockerHubTag(result["name"], version, int(api), sha12))
77
+ url = page["next"]
78
+ except HTTPError as e:
79
+ if e.code == 404 and len(visited) == 1:
80
+ return []
81
+ raise RuntimeError(f"Docker Hub tags for {repository} failed (HTTP {e.code})") from None
82
+ except (OSError, HTTPException, ValueError, KeyError, TypeError):
83
+ raise RuntimeError(
84
+ f"Docker Hub tags for {repository} failed (connection or invalid response)"
85
+ ) from None
86
+ return tags
87
+
88
+
89
+ def _docker_hub_entry(name: str) -> dict | None:
90
+ tags = docker_hub_tags(name)
91
+ if not tags:
92
+ return None
93
+ repository = f"{DOCKER_HUB_NAMESPACE}/{DOCKER_HUB_PREFIX}{name}"
94
+ compatible = [tag for tag in tags if tag.api == API_VERSION]
95
+ if not compatible:
96
+ versions = ", ".join(str(api) for api in sorted({tag.api for tag in tags}))
97
+ raise RuntimeError(
98
+ f"Docker Hub repository {repository} has API versions {versions}; "
99
+ f"this runner speaks API version {API_VERSION}"
100
+ )
101
+
102
+ def version_key(tag: DockerHubTag) -> tuple[int, ...]:
103
+ return tuple(int(part) for part in tag.version.split("."))
104
+
105
+ highest = max(map(version_key, compatible))
106
+ latest = sorted((tag for tag in compatible if version_key(tag) == highest), key=lambda t: t.tag)
107
+ if len({tag.sha12 for tag in latest}) > 1:
108
+ raise RuntimeError(
109
+ f"ambiguous highest version in Docker Hub repository {repository}: "
110
+ + ", ".join(tag.tag for tag in latest)
111
+ )
112
+ chosen = latest[-1]
113
+ return {
114
+ "version": chosen.version,
115
+ "api": chosen.api,
116
+ "sha256": chosen.sha12,
117
+ "registry": f"oras://docker.io/{repository}:{chosen.tag}",
118
+ }
119
+
120
+
121
+ def docker_hub_names() -> list[str]:
122
+ """List model names in the namespace; tags still need resolving by the lookup rule.
123
+
124
+ Read every repository page without a login. Connection and response errors raise
125
+ RuntimeError without response bodies, as in docker_hub_tags.
126
+ """
127
+ endpoint = f"https://hub.docker.com/v2/namespaces/{DOCKER_HUB_NAMESPACE}/repositories"
128
+ url = f"{endpoint}?page_size=100"
129
+ names = set()
130
+ visited = set()
131
+ while url is not None:
132
+ try:
133
+ if not isinstance(url, str) or not url.startswith(endpoint + "?") or url in visited:
134
+ raise ValueError("invalid next page")
135
+ visited.add(url)
136
+ with urlopen(url, timeout=DOCKER_HUB_TIMEOUT) as response:
137
+ page = json.load(response)
138
+ if not isinstance(page, dict) or not isinstance(page["results"], list):
139
+ raise TypeError("invalid repository list")
140
+ for result in page["results"]:
141
+ if not isinstance(result, dict) or not isinstance(result["name"], str):
142
+ raise TypeError("invalid repository name")
143
+ repository = result["name"]
144
+ if repository.startswith(DOCKER_HUB_PREFIX):
145
+ name = repository.removeprefix(DOCKER_HUB_PREFIX)
146
+ if MODEL_NAME.fullmatch(name):
147
+ names.add(name)
148
+ url = page["next"]
149
+ except HTTPError as e:
150
+ raise RuntimeError(
151
+ f"Docker Hub repositories for {DOCKER_HUB_NAMESPACE} failed (HTTP {e.code})"
152
+ ) from None
153
+ except (OSError, HTTPException, ValueError, KeyError, TypeError):
154
+ raise RuntimeError(
155
+ f"Docker Hub repositories for {DOCKER_HUB_NAMESPACE} failed "
156
+ "(connection or invalid response)"
157
+ ) from None
158
+ return sorted(names)
159
+
160
+
161
+ def store_root() -> Path:
162
+ """The store root: ``$MODELPOLIS_HOME`` if set, else ``~/.cache/modelpolis``."""
163
+ return Path(os.environ.get(ENV_VAR) or DEFAULT_HOME).expanduser()
164
+
165
+
166
+ def images_dir(name: str) -> Path:
167
+ return store_root() / "images" / name
168
+
169
+
170
+ def logs_dir() -> Path:
171
+ """The folder for worker logs, created if missing."""
172
+ path = store_root() / "logs"
173
+ path.mkdir(parents=True, exist_ok=True)
174
+ return path
175
+
176
+
177
+ def read_catalog(path: str | os.PathLike | None = None) -> dict[str, dict]:
178
+ """The catalogue's entries by model name; empty if the file does not exist."""
179
+ path = Path(path) if path is not None else CATALOG
180
+ if not path.is_file():
181
+ return {}
182
+ with path.open("rb") as f:
183
+ return tomllib.load(f)
184
+
185
+
186
+ def catalog_image(name: str, entry: dict) -> Path:
187
+ """Where the store keeps the SIF of a catalogue entry: ``images/<name>/<version>-<sha12>.sif``."""
188
+ return images_dir(name) / f"{entry['version']}-{entry['sha256'][:12]}.sif"
189
+
190
+
191
+ def sha256_of(path: Path) -> str:
192
+ h = hashlib.sha256()
193
+ with path.open("rb") as f:
194
+ for block in iter(lambda: f.read(1 << 20), b""):
195
+ h.update(block)
196
+ return h.hexdigest()
197
+
198
+
199
+ def fetch(name: str, catalog: str | os.PathLike | None = None) -> Path:
200
+ """Return the published SIF from the catalogue or Docker Hub by rule, pulling if missing.
201
+
202
+ Progress and the optional licence notice go to stderr. The reference is passed to
203
+ Apptainer unchanged; the temporary file is never visible to name lookups.
204
+ """
205
+ catalog = Path(catalog) if catalog is not None else CATALOG
206
+ entry = read_catalog(catalog).get(name)
207
+ by_rule = entry is None
208
+ if by_rule:
209
+ entry = _docker_hub_entry(name)
210
+ if entry is None:
211
+ repository = f"{DOCKER_HUB_NAMESPACE}/{DOCKER_HUB_PREFIX}{name}"
212
+ registry = (
213
+ f"Docker Hub repository {repository}"
214
+ if MODEL_NAME.fullmatch(name)
215
+ else "Docker Hub not searched (model names must match [a-z][a-z0-9_]*)"
216
+ )
217
+ catalogue = (
218
+ "; no catalogue without a checkout"
219
+ if catalog == CATALOG and not CATALOG.is_file()
220
+ else f" and catalogue {catalog}"
221
+ )
222
+ raise FileNotFoundError(
223
+ f"no image for {name!r}: searched {images_dir(name)}{catalogue}; "
224
+ f"{registry}; a model that is not distributed must be built from a checkout"
225
+ )
226
+ dest = catalog_image(name, entry)
227
+ if dest.is_file():
228
+ return dest
229
+ reference = entry["registry"]
230
+ if reference == "local":
231
+ raise FileNotFoundError(
232
+ f"no image for {name!r} in {images_dir(name)}: the model is local and is never "
233
+ f"in a registry; run modelpolis build {name} --weights <path> "
234
+ f"(--weights is needed only where models/{name}/WEIGHTS.md asks for it)"
235
+ )
236
+ dest.parent.mkdir(parents=True, exist_ok=True)
237
+ with tempfile.TemporaryDirectory(prefix=".pull-", dir=dest.parent) as folder:
238
+ partial = Path(folder) / dest.name
239
+ try:
240
+ message = f"Pulling {name} {entry['version']} from {reference}"
241
+ print(" ".join(message.split()), file=sys.stderr, flush=True)
242
+ subprocess.run(
243
+ # The store keeps the image, so Apptainer's own cache would be a second copy.
244
+ ["apptainer", "pull", "--disable-cache", str(partial), reference],
245
+ check=True,
246
+ stdout=sys.stderr,
247
+ )
248
+ actual = sha256_of(partial)
249
+ expected = entry["sha256"].lower()
250
+ matches = actual.startswith(expected) if by_rule else actual == expected
251
+ if not matches:
252
+ raise ValueError(
253
+ f"checksum mismatch for {reference}: expected {entry['sha256']}, got {actual}"
254
+ )
255
+ partial.replace(dest)
256
+ except subprocess.CalledProcessError as e:
257
+ raise RuntimeError(f"apptainer pull {reference} failed (exit {e.returncode})") from e
258
+ except OSError as e:
259
+ raise RuntimeError(f"apptainer pull {reference} failed: {e}") from e
260
+ if by_rule:
261
+ page = f"https://hub.docker.com/r/{DOCKER_HUB_NAMESPACE}/{DOCKER_HUB_PREFIX}{name}"
262
+ print(f"Licence and citation: {page}", file=sys.stderr)
263
+ elif "license" in entry:
264
+ license_line = " ".join(entry["license"].split()).rstrip(".")
265
+ print(
266
+ f'Licence: {license_line}; see README.md, "Licences and downloading".',
267
+ file=sys.stderr,
268
+ )
269
+ return dest
270
+
271
+
272
+ def find_image(name_or_path: str | os.PathLike, sha256: str | None = None) -> Path:
273
+ """Return the SIF for a path to an existing file, or for a model name in the store.
274
+
275
+ For a name, the SIF is looked up under ``$MODELPOLIS_HOME/images/<name>/``; if several
276
+ ``*.sif`` files are there, the newest by modification time is returned (ties broken by
277
+ file name). If none are there, fetch the catalogue entry or look up Docker Hub by rule.
278
+ If ``sha256`` is given, the file's checksum must match it.
279
+ """
280
+ path = Path(name_or_path).expanduser()
281
+ if path.is_file():
282
+ sif = path
283
+ elif os.sep in str(name_or_path) or path.suffix == ".sif":
284
+ raise FileNotFoundError(f"no image at {path}")
285
+ else:
286
+ folder = images_dir(str(name_or_path))
287
+ candidates = sorted(folder.glob("*.sif")) if folder.is_dir() else []
288
+ sif = (
289
+ max(candidates, key=lambda p: (p.stat().st_mtime, p.name))
290
+ if candidates
291
+ else fetch(str(name_or_path))
292
+ )
293
+ if sha256 is not None:
294
+ actual = sha256_of(sif)
295
+ if actual != sha256.lower():
296
+ raise ValueError(f"checksum mismatch for {sif}: expected {sha256}, got {actual}")
297
+ return sif
@@ -0,0 +1,5 @@
1
+ """Runs inside every image. Imports only runner.api from the runner."""
2
+
3
+ from .adapter import Adapter
4
+
5
+ __all__ = ["Adapter"]