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.
modelpolis/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """modelpolis: one model-agnostic API for sequence-to-function models."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("modelpolis")
6
+
7
+
8
+ # The runner is imported on first use, so that ``import modelpolis.runner.api`` inside an image
9
+ # does not pull in the launcher.
10
+ def fetch(name, catalog=None):
11
+ """Return the catalogued SIF path, pulling and checking it if it is missing."""
12
+ from .runner.store import fetch
13
+
14
+ return fetch(name, catalog)
15
+
16
+
17
+ def load(name_or_path, device=None, sha256=None):
18
+ """Start a model by name or SIF path and return a ``Model``.
19
+
20
+ ``device=None`` means ``cuda:0`` if the spec's first device is ``cuda``, else ``cpu``.
21
+ """
22
+ from .runner.model import load
23
+
24
+ return load(name_or_path, device, sha256)
25
+
26
+
27
+ def describe(name_or_path):
28
+ """Return a model's ``Spec`` without loading it."""
29
+ from .runner.model import describe
30
+
31
+ return describe(name_or_path)
@@ -0,0 +1 @@
1
+ """Build machine only: turns a model directory into a verified SIF."""
@@ -0,0 +1,25 @@
1
+ Bootstrap: docker
2
+ From: {{base}}
3
+
4
+ # The one definition template for every model (plan/DESIGN.md section 6), filled by
5
+ # builder/image.py. {{stage}} holds the model directory (model/), the spec JSON (spec.json),
6
+ # requirements.lock and a wheel of modelpolis built at the current commit (build/).
7
+ # The weights line becomes one "<verified file> <dest>/<path>" line per weight file of [weights]
8
+ # (builder/weights.py), or nothing for source = "none".
9
+
10
+ %files
11
+ {{stage}} /opt/modelpolis
12
+ {{weights}}
13
+
14
+ %post
15
+ set -eu
16
+ export PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
17
+ # The model's own post.sh, if any, runs first (section 6), e.g. to add Python to a CUDA base.
18
+ if [ -f /opt/modelpolis/model/post.sh ]; then sh -eu /opt/modelpolis/model/post.sh; fi
19
+ PY=$(command -v python{{python}})
20
+ # The lock first, then modelpolis without its dependencies, so the lock pins win.
21
+ "$PY" -m pip install --no-cache-dir -r /opt/modelpolis/build/requirements.lock
22
+ "$PY" -m pip install --no-cache-dir --no-deps /opt/modelpolis/build/*.whl
23
+ rm -rf /opt/modelpolis/build /root/.cache/pip
24
+ printf '#!/bin/sh\nexec %s -m modelpolis.worker.main "$@"\n' "$PY" > /opt/modelpolis/worker
25
+ chmod 755 /opt/modelpolis/worker
@@ -0,0 +1,221 @@
1
+ """Fill the one definition template and run ``apptainer build`` (plan/DESIGN.md section 6).
2
+
3
+ The build runs without root: ``apptainer build --fakeroot`` in an unprivileged user namespace
4
+ (mapped through ``/etc/subuid`` if the user has entries there, else root-mapped). No Docker is used; the base image is
5
+ pulled by Apptainer from its pinned digest. The SIF is written to
6
+ ``$MODELPOLIS_HOME/builds/<name>/<version>-<sha12>.sif`` unless another folder is given; it is
7
+ placed in ``images/`` only by publish, after verify.
8
+
9
+ With ``[resources] precision = "auto"`` the build chooses the precision (rule 6 of
10
+ plan/DESIGN.md section 8): it builds a ``bf16-mixed`` image and compares its reference output
11
+ with the reference at the model's tolerance (``builder/verify.py``). It keeps that image if every
12
+ checked output meets the tolerance; else it removes it and builds an ``fp32`` image. Either way
13
+ ``<sif>.precision.json`` records the comparisons and the choice.
14
+ """
15
+
16
+ import hashlib
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ from dataclasses import replace
23
+ from pathlib import Path
24
+
25
+ from .model_toml import AUTO, FP32, MIXED, read_model_toml, write_spec_json
26
+
27
+ TEMPLATE = Path(__file__).with_name("image.def.tmpl")
28
+ REPO_ROOT = Path(__file__).resolve().parents[3]
29
+ BUILD_FLAGS = ("--fakeroot",)
30
+
31
+
32
+ def has_checkout() -> bool:
33
+ """Whether this package is running from a repository with the model directories."""
34
+ return (REPO_ROOT / "models" / "_fake" / "model.toml").is_file()
35
+
36
+
37
+ def require_checkout() -> None:
38
+ if not has_checkout():
39
+ raise FileNotFoundError(
40
+ "needs a checkout of the repository installed with pip install -e ., "
41
+ "because the model directories are not in the package: "
42
+ "https://github.com/tanjiminlab/modelpolis-sequence"
43
+ )
44
+
45
+
46
+ # These two duplicate runner/store.py, from when the builder could import only runner.api.
47
+ def store_root() -> Path:
48
+ return Path(os.environ.get("MODELPOLIS_HOME") or "~/.cache/modelpolis").expanduser()
49
+
50
+
51
+ def sha256_of(path: Path) -> str:
52
+ h = hashlib.sha256()
53
+ with path.open("rb") as f:
54
+ for block in iter(lambda: f.read(1 << 20), b""):
55
+ h.update(block)
56
+ return h.hexdigest()
57
+
58
+
59
+ def model_dir_for(name_or_path: str) -> Path:
60
+ """``models/<name>/`` in the repo, or a path to a model directory."""
61
+ require_checkout()
62
+ path = Path(name_or_path).expanduser()
63
+ if not path.is_dir():
64
+ path = REPO_ROOT / "models" / name_or_path
65
+ if not (path / "model.toml").is_file():
66
+ raise FileNotFoundError(f"no model directory with a model.toml for {name_or_path!r}")
67
+ return path.resolve()
68
+
69
+
70
+ def base_reference(base: str) -> str:
71
+ """The ``From:`` line: ``docker://`` removed, and the tag dropped if a digest pins the image.
72
+
73
+ Apptainer 1.5 refuses a reference with both a tag and a digest; the digest alone decides.
74
+ """
75
+ name, at, digest = base.removeprefix("docker://").partition("@")
76
+ if at:
77
+ folder, slash, last = name.rpartition("/")
78
+ name = folder + slash + last.partition(":")[0]
79
+ return name + at + digest
80
+
81
+
82
+ def fill_template(base: str, python: str, stage: Path, weights: list[tuple[Path, str]] = ()) -> str:
83
+ """The definition text; ``weights`` holds ``(host path, path in the image)`` pairs."""
84
+ text = TEMPLATE.read_text()
85
+ for key, value in (("base", base_reference(base)), ("python", python)):
86
+ text = text.replace("{{" + key + "}}", value)
87
+ for host, dest in weights:
88
+ if any(c.isspace() for c in f"{host}{dest}"):
89
+ raise ValueError(f"weights: paths with spaces cannot go into %files: {host} {dest}")
90
+ files = "".join(f" {host} {dest}\n" for host, dest in weights)
91
+ return text.replace("{{stage}}", str(stage)).replace(" {{weights}}\n", files)
92
+
93
+
94
+ def resolve_data_files(entries: list[dict]) -> list[tuple[Path, str]]:
95
+ """``[build] data_files`` as ``(verified host path, path in the image)`` pairs.
96
+
97
+ Each entry is ``{path, sha256, dest}``: ``path`` relative to the data root
98
+ (``modelpolis.paths``), ``dest`` absolute in the image. Each file is checked against its
99
+ sha256 before the build; nothing under the data root is written.
100
+ """
101
+ if not entries:
102
+ return []
103
+ from modelpolis.paths import load_paths
104
+
105
+ try:
106
+ root = load_paths().root
107
+ except RuntimeError as e:
108
+ raise FileNotFoundError(f"[build] data_files need the data root: {e}") from None
109
+ pairs = []
110
+ for entry in entries:
111
+ path, sha256, dest = entry.get("path"), entry.get("sha256", ""), entry.get("dest")
112
+ if set(entry) != {"path", "sha256", "dest"}:
113
+ raise ValueError(f"[build] data_files: entries need path, sha256 and dest: {entry}")
114
+ if not path or path.startswith("/") or ".." in Path(path).parts:
115
+ raise ValueError(f"[build] data_files: path must be relative without '..': {path!r}")
116
+ if not isinstance(dest, str) or not dest.startswith("/"):
117
+ raise ValueError(f"[build] data_files: dest must be absolute in the image: {dest!r}")
118
+ host = root / path
119
+ if not host.is_file():
120
+ raise FileNotFoundError(f"[build] data_files: {host} not found")
121
+ actual = sha256_of(host)
122
+ if actual != sha256:
123
+ raise ValueError(f"[build] data_files: {host}: sha256 {actual}, expected {sha256}")
124
+ pairs.append((host.resolve(), dest))
125
+ return pairs
126
+
127
+
128
+ def build_wheel(dest: Path) -> Path:
129
+ """A wheel of modelpolis from the repo at its current state, without dependencies."""
130
+ require_checkout()
131
+ if not (REPO_ROOT / "pyproject.toml").is_file():
132
+ raise FileNotFoundError(f"modelpolis repo not found at {REPO_ROOT}")
133
+ subprocess.run(
134
+ [sys.executable, "-m", "pip", "wheel", "--no-deps", "--no-build-isolation", "-q"]
135
+ + ["-w", str(dest), str(REPO_ROOT)],
136
+ check=True,
137
+ )
138
+ (wheel,) = dest.glob("modelpolis-*.whl")
139
+ return wheel
140
+
141
+
142
+ def build(
143
+ name_or_path: str,
144
+ output: str | Path | None = None,
145
+ weights_dir: str | Path | None = None,
146
+ device: str | None = None,
147
+ ) -> tuple[Path, str]:
148
+ """Build a model's SIF; return its path and sha256.
149
+
150
+ Weight files are fetched or located and verified first (``builder/weights.py``);
151
+ ``weights_dir`` is the folder of a protected model's files (``--weights``). ``device`` is
152
+ where the precision check runs, for ``precision = "auto"`` (default: from the spec).
153
+
154
+ Raises ``subprocess.CalledProcessError`` if ``apptainer build`` fails; its output has
155
+ already gone to the terminal.
156
+ """
157
+ model_dir = model_dir_for(name_or_path)
158
+ definition = read_model_toml(model_dir / "model.toml")
159
+ spec = definition.spec
160
+ apptainer = shutil.which("apptainer")
161
+ if apptainer is None:
162
+ raise FileNotFoundError("apptainer was not found on PATH; see docs/setup.md")
163
+ from .weights import resolve_weights # imports this module
164
+
165
+ weights = resolve_weights(definition.weights, model_dir, weights_dir)
166
+ weights += resolve_data_files(definition.build.get("data_files", []))
167
+ out_dir = Path(output) if output else store_root() / "builds" / spec.name
168
+ out_dir.mkdir(parents=True, exist_ok=True)
169
+ if spec.resources.precision != AUTO:
170
+ return build_sif(apptainer, definition, spec, model_dir, weights, out_dir)
171
+
172
+ from .verify import choose_precision, compare_reference, write_precision_record
173
+
174
+ def with_precision(precision):
175
+ return replace(spec, resources=replace(spec.resources, precision=precision))
176
+
177
+ sif, sha256 = build_sif(
178
+ apptainer, definition, with_precision(MIXED), model_dir, weights, out_dir
179
+ )
180
+ try:
181
+ comparisons = compare_reference(sif, model_dir, device, **definition.tolerance)
182
+ except BaseException:
183
+ sif.unlink(missing_ok=True)
184
+ raise
185
+ chosen = choose_precision(comparisons)
186
+ if chosen == FP32:
187
+ sif.unlink()
188
+ sif, sha256 = build_sif(
189
+ apptainer, definition, with_precision(FP32), model_dir, weights, out_dir
190
+ )
191
+ write_precision_record(sif, chosen, definition.tolerance, comparisons)
192
+ return sif, sha256
193
+
194
+
195
+ def build_sif(apptainer, definition, spec, model_dir, weights, out_dir) -> tuple[Path, str]:
196
+ """One ``apptainer build`` of the model with ``spec`` as the image's spec JSON."""
197
+ base, python = definition.build["base"], definition.build["python"]
198
+ with tempfile.TemporaryDirectory(prefix="modelpolis-build-") as tmp:
199
+ tmp = Path(tmp)
200
+ stage = tmp / "stage"
201
+ shutil.copytree(
202
+ model_dir, stage / "model", ignore=shutil.ignore_patterns("__pycache__", "*.pyc")
203
+ )
204
+ write_spec_json(spec, stage / "spec.json")
205
+ (stage / "build").mkdir()
206
+ shutil.copy(model_dir / "requirements.lock", stage / "build" / "requirements.lock")
207
+ build_wheel(stage / "build")
208
+ def_file = tmp / "image.def"
209
+ def_file.write_text(fill_template(base, python, stage, weights))
210
+ partial = out_dir / f".{spec.version}.partial.sif"
211
+ try:
212
+ subprocess.run(
213
+ [apptainer, "build", *BUILD_FLAGS, "--force", str(partial), str(def_file)],
214
+ check=True,
215
+ )
216
+ sha256 = sha256_of(partial)
217
+ sif = out_dir / f"{spec.version}-{sha256[:12]}.sif"
218
+ partial.replace(sif)
219
+ finally:
220
+ partial.unlink(missing_ok=True)
221
+ return sif, sha256
@@ -0,0 +1,100 @@
1
+ """Read a model definition (``model.toml``) and write the spec JSON that goes into the image.
2
+
3
+ See plan/DESIGN.md section 6. The spec fields become a ``runner.api.Spec``; the ``adapter``
4
+ string and the build-only tables ``[build]``, ``[weights]`` and ``[publish]`` are kept
5
+ separately and never go into the spec JSON.
6
+
7
+ Precision (rule 6 of plan/DESIGN.md section 8): ``[resources] precision`` is ``"fp32"``,
8
+ ``"bf16-mixed"`` (the forward pass under bf16 autocast) or ``"auto"``. ``"auto"`` is for the
9
+ model definition only: the build tries ``"bf16-mixed"``, keeps it if the reference comparison
10
+ meets ``[build] tolerance``, else builds ``"fp32"``, and the image's spec holds the choice. The
11
+ tolerance (default P1) is also what verify uses.
12
+ """
13
+
14
+ import json
15
+ import tomllib
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from modelpolis.runner.api import API_VERSION, Spec
21
+
22
+ REQUIRED_FIELDS = ("name", "version", "adapter")
23
+ SPEC_TABLES = ("inputs", "outputs", "options", "resources")
24
+ BUILD_TABLES = ("build", "weights", "publish")
25
+ TOP_LEVEL = REQUIRED_FIELDS + SPEC_TABLES + BUILD_TABLES
26
+
27
+ # Used for any [resources] field left out (plan/DESIGN.md section 6).
28
+ RESOURCE_DEFAULTS = {
29
+ "devices": ["cuda"],
30
+ "batch": 1,
31
+ "precision": "fp32",
32
+ "load_timeout_s": 300,
33
+ "infer_timeout_s": 120,
34
+ }
35
+
36
+
37
+ FP32, MIXED, AUTO = "fp32", "bf16-mixed", "auto"
38
+
39
+ # P1 of plan/ROADMAP.md, approved by a maintainer on 2026-11-24. Any other [build] tolerance
40
+ # needs a maintainer's approval (AGENTS.md).
41
+ P1 = {"rtol": 1e-3, "atol": 1e-4}
42
+
43
+
44
+ @dataclass
45
+ class ModelDefinition:
46
+ spec: Spec
47
+ adapter: str
48
+ build: dict[str, Any] = field(default_factory=dict)
49
+ weights: dict[str, Any] = field(default_factory=dict)
50
+ publish: dict[str, Any] = field(default_factory=dict)
51
+
52
+ @property
53
+ def tolerance(self) -> dict[str, float]:
54
+ """``{"rtol", "atol"}`` from ``[build] tolerance``; P1 if it is left out."""
55
+ tolerance = self.build.get("tolerance", P1)
56
+ if set(tolerance) != {"rtol", "atol"}:
57
+ raise ValueError("model.toml: [build] tolerance needs exactly rtol and atol")
58
+ return {k: float(v) for k, v in tolerance.items()}
59
+
60
+
61
+ def parse_model_toml(text: str) -> ModelDefinition:
62
+ """Read the text of a ``model.toml``."""
63
+ d = tomllib.loads(text)
64
+ unknown = sorted(set(d) - set(TOP_LEVEL))
65
+ if unknown:
66
+ raise ValueError(f"model.toml: unknown top-level keys or tables: {', '.join(unknown)}")
67
+ for name in REQUIRED_FIELDS:
68
+ if name not in d:
69
+ raise ValueError(f"model.toml: missing required field {name!r}")
70
+ spec_json = {
71
+ "api": API_VERSION,
72
+ "name": d["name"],
73
+ "version": d["version"],
74
+ "inputs": d.get("inputs", {}),
75
+ "outputs": d.get("outputs", {}),
76
+ "options": d.get("options", {}),
77
+ "resources": RESOURCE_DEFAULTS | d.get("resources", {}),
78
+ }
79
+ try:
80
+ spec = Spec.from_json(spec_json)
81
+ except KeyError as e:
82
+ raise ValueError(f"model.toml: missing field {e.args[0]!r} in a spec table") from None
83
+ return ModelDefinition(
84
+ spec, d["adapter"], d.get("build", {}), d.get("weights", {}), d.get("publish", {})
85
+ )
86
+
87
+
88
+ def read_model_toml(path: str | Path) -> ModelDefinition:
89
+ """Read a ``model.toml`` file."""
90
+ return parse_model_toml(Path(path).read_text())
91
+
92
+
93
+ def spec_json(spec: Spec) -> str:
94
+ """The spec JSON that goes into the image, as ``worker describe`` prints it."""
95
+ return json.dumps(spec.to_json(), indent=2) + "\n"
96
+
97
+
98
+ def write_spec_json(spec: Spec, path: str | Path) -> None:
99
+ """Write the spec JSON to ``path``."""
100
+ Path(path).write_text(spec_json(spec))