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 +31 -0
- modelpolis/builder/__init__.py +1 -0
- modelpolis/builder/image.def.tmpl +25 -0
- modelpolis/builder/image.py +221 -0
- modelpolis/builder/model_toml.py +100 -0
- modelpolis/builder/publish.py +303 -0
- modelpolis/builder/verify.py +226 -0
- modelpolis/builder/weights.py +212 -0
- modelpolis/cli.py +679 -0
- modelpolis/paths.py +39 -0
- modelpolis/runner/__init__.py +1 -0
- modelpolis/runner/api.py +525 -0
- modelpolis/runner/conformance.py +375 -0
- modelpolis/runner/launch.py +165 -0
- modelpolis/runner/model.py +382 -0
- modelpolis/runner/store.py +297 -0
- modelpolis/worker/__init__.py +5 -0
- modelpolis/worker/adapter.py +45 -0
- modelpolis/worker/main.py +85 -0
- modelpolis/worker/serve.py +332 -0
- modelpolis/worker/torch_gpu.py +128 -0
- modelpolis-0.1.0.dist-info/METADATA +223 -0
- modelpolis-0.1.0.dist-info/RECORD +27 -0
- modelpolis-0.1.0.dist-info/WHEEL +5 -0
- modelpolis-0.1.0.dist-info/entry_points.txt +2 -0
- modelpolis-0.1.0.dist-info/licenses/LICENSE +21 -0
- modelpolis-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Place a verified SIF in the store and write its entry in ``catalog.toml`` (plan/DESIGN.md 6).
|
|
2
|
+
|
|
3
|
+
Publish accepts a SIF only if ``modelpolis verify`` passed on that exact file: its verify
|
|
4
|
+
record (``<sif>.verify.json``) must hold the SIF's sha256. The SIF is copied to
|
|
5
|
+
``$MODELPOLIS_HOME/images/<name>/<version>-<sha12>.sif`` through a temporary file, whose sha256
|
|
6
|
+
is checked before it is renamed into place.
|
|
7
|
+
|
|
8
|
+
Only an explicit push uploads the unchanged SIF and sets its repository overview before
|
|
9
|
+
depositing it and writing the registry reference to the catalogue.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import shlex
|
|
16
|
+
import shutil
|
|
17
|
+
import subprocess
|
|
18
|
+
import sys
|
|
19
|
+
import tomllib
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from urllib.error import HTTPError
|
|
22
|
+
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
|
23
|
+
|
|
24
|
+
from modelpolis.runner.model import describe
|
|
25
|
+
from modelpolis.runner.store import (
|
|
26
|
+
DOCKER_HUB_NAMESPACE,
|
|
27
|
+
DOCKER_HUB_PREFIX,
|
|
28
|
+
docker_hub_tags,
|
|
29
|
+
images_dir,
|
|
30
|
+
sha256_of,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
from .image import REPO_ROOT, model_dir_for
|
|
34
|
+
from .model_toml import ModelDefinition, read_model_toml
|
|
35
|
+
from .verify import newest_build, record_path
|
|
36
|
+
|
|
37
|
+
CATALOG = REPO_ROOT / "catalog.toml"
|
|
38
|
+
LOCAL = "local"
|
|
39
|
+
CATALOG_HEADER = (
|
|
40
|
+
"# Written by `modelpolis publish`; do not edit by hand.\n"
|
|
41
|
+
"# One table per model: the registry reference or local, the SIF sha256, the API version\n"
|
|
42
|
+
"# and the model version, with the licence when pushed.\n"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def registry_of(definition: ModelDefinition) -> str:
|
|
47
|
+
"""The ``[publish] registry`` of a model definition; ``local`` if it names none."""
|
|
48
|
+
return definition.publish.get("registry", LOCAL)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def push(sif: Path, registry: str, *, dry_run: bool = False) -> None:
|
|
52
|
+
"""Push the verified file itself, using the user's own Apptainer login."""
|
|
53
|
+
if registry == LOCAL:
|
|
54
|
+
raise ValueError("a local image is never pushed")
|
|
55
|
+
command = ["apptainer", "push", str(sif), registry]
|
|
56
|
+
if dry_run:
|
|
57
|
+
print(shlex.join(command))
|
|
58
|
+
else:
|
|
59
|
+
subprocess.run(command, check=True, stdout=sys.stderr)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def check_publish_metadata(definition: ModelDefinition) -> str:
|
|
63
|
+
"""Refuse local models and incomplete metadata before inspecting or uploading a SIF."""
|
|
64
|
+
registry = registry_of(definition)
|
|
65
|
+
if registry == LOCAL:
|
|
66
|
+
raise ValueError(f"{definition.spec.name} is marked local; a local image is never pushed")
|
|
67
|
+
component = r"[a-z0-9]+(?:[._-]+[a-z0-9]+)*"
|
|
68
|
+
if not isinstance(registry, str) or not re.fullmatch(
|
|
69
|
+
rf"oras://[A-Za-z0-9.-]+(?::[0-9]+)?/{component}(?:/{component})*", registry
|
|
70
|
+
):
|
|
71
|
+
raise ValueError("[publish] registry must name an oras:// repository without a tag")
|
|
72
|
+
if registry.startswith("oras://docker.io/") and len(registry.split("/")) != 5:
|
|
73
|
+
raise ValueError("[publish] registry must be oras://docker.io/<namespace>/<repository>")
|
|
74
|
+
for key in ("license", "citation"):
|
|
75
|
+
value = definition.publish.get(key)
|
|
76
|
+
if not isinstance(value, str) or not value.strip():
|
|
77
|
+
raise ValueError(f"[publish] {key} is required and must not be empty for --push")
|
|
78
|
+
for key in ("license_url", "restrictions"):
|
|
79
|
+
if not isinstance(definition.publish.get(key, ""), str):
|
|
80
|
+
raise ValueError(f"[publish] {key} must be text") # noqa: TRY004 - invalid config
|
|
81
|
+
return registry
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def overview_text(definition: ModelDefinition, entry: dict) -> str:
|
|
85
|
+
"""The same repository overview for uploads, other registries and dry runs."""
|
|
86
|
+
metadata = definition.publish
|
|
87
|
+
license_text = metadata["license"]
|
|
88
|
+
if metadata.get("license_url"):
|
|
89
|
+
license_text = f"[{license_text}]({metadata['license_url']})"
|
|
90
|
+
restrictions = metadata.get("restrictions", "").strip() or "Attribution only."
|
|
91
|
+
return (
|
|
92
|
+
f"# {entry['name']} {entry['version']}\n\n"
|
|
93
|
+
f"Reference: `{entry['registry']}`\n\n"
|
|
94
|
+
f"Tag: `{entry['registry'].rsplit(':', 1)[1]}`\n\n"
|
|
95
|
+
f"SHA256: `{entry['sha256']}`\n\n"
|
|
96
|
+
f"API version: {entry['api']}\n\n"
|
|
97
|
+
f"Licence: {license_text}\n\n"
|
|
98
|
+
f"Restrictions: {restrictions}\n\n"
|
|
99
|
+
f"Citation: {metadata['citation']}\n\n"
|
|
100
|
+
f"Get the image: `modelpolis fetch {entry['name']}` or, in Python, "
|
|
101
|
+
f'`import modelpolis as mp; mp.load("{entry["name"]}")`.\n\n'
|
|
102
|
+
"This image is an Apptainer SIF: pull it with Apptainer, not with Docker.\n\n"
|
|
103
|
+
"A `latest` tag in this repository, if present, is the legacy Docker image.\n"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _NoRedirect(HTTPRedirectHandler):
|
|
108
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
109
|
+
# Credentials belong only to the requested Docker Hub endpoint.
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def docker_hub_token() -> str:
|
|
114
|
+
"""Validate environment credentials and return a fresh in-memory access token."""
|
|
115
|
+
username = os.environ.get("DOCKERHUB_USERNAME")
|
|
116
|
+
password = os.environ.get("DOCKERHUB_TOKEN")
|
|
117
|
+
if not username or not password:
|
|
118
|
+
raise ValueError("Docker Hub overview needs DOCKERHUB_USERNAME and DOCKERHUB_TOKEN")
|
|
119
|
+
# Login documentation (checked 2026-11-28):
|
|
120
|
+
# https://docs.docker.com/reference/api/hub/latest/operations/AuthCreateAccessToken/
|
|
121
|
+
opener = build_opener(_NoRedirect())
|
|
122
|
+
login = Request(
|
|
123
|
+
"https://hub.docker.com/v2/auth/token",
|
|
124
|
+
data=json.dumps({"identifier": username, "secret": password}).encode(),
|
|
125
|
+
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
|
126
|
+
method="POST",
|
|
127
|
+
)
|
|
128
|
+
try:
|
|
129
|
+
with opener.open(login, timeout=30) as response:
|
|
130
|
+
token = json.load(response)["access_token"]
|
|
131
|
+
if not isinstance(token, str) or not token.strip():
|
|
132
|
+
raise ValueError("invalid access token")
|
|
133
|
+
return token
|
|
134
|
+
except HTTPError as e:
|
|
135
|
+
raise ValueError(f"Docker Hub login failed (HTTP {e.code})") from None
|
|
136
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
137
|
+
# Never include a response body, request, token or transport error text.
|
|
138
|
+
raise ValueError("Docker Hub login failed (connection or invalid response)") from None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def set_docker_hub_overview(registry: str, overview: str) -> None:
|
|
142
|
+
"""Get a fresh token after the upload, then update only the repository overview."""
|
|
143
|
+
token = docker_hub_token()
|
|
144
|
+
# Overview PATCH is in Docker's client linked from its documentation:
|
|
145
|
+
# https://docs.docker.com/docker-hub/mcp-server/
|
|
146
|
+
# https://github.com/docker/hub-mcp/blob/68f4c79223f3ac2a5b6732de58ce7ba22aa8f1a8/src/repos.ts
|
|
147
|
+
opener = build_opener(_NoRedirect())
|
|
148
|
+
try:
|
|
149
|
+
namespace, repository = registry.removeprefix("oras://docker.io/").split("/")
|
|
150
|
+
request = Request(
|
|
151
|
+
f"https://hub.docker.com/v2/namespaces/{namespace}/repositories/{repository}",
|
|
152
|
+
data=json.dumps({"full_description": overview}).encode(),
|
|
153
|
+
headers={
|
|
154
|
+
"Content-Type": "application/json",
|
|
155
|
+
"Accept": "application/json",
|
|
156
|
+
"Authorization": f"Bearer {token}",
|
|
157
|
+
},
|
|
158
|
+
method="PATCH",
|
|
159
|
+
)
|
|
160
|
+
with opener.open(request, timeout=30):
|
|
161
|
+
pass
|
|
162
|
+
except HTTPError as e:
|
|
163
|
+
raise ValueError(f"Docker Hub overview update failed (HTTP {e.code})") from None
|
|
164
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
165
|
+
# Never include a response body, request, token or transport error text.
|
|
166
|
+
raise ValueError(
|
|
167
|
+
"Docker Hub overview update failed (connection or invalid response)"
|
|
168
|
+
) from None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def check_verified(sif: Path, sha256: str) -> dict:
|
|
172
|
+
"""The SIF's verify record, if it passed for a file with this sha256; else ``ValueError``."""
|
|
173
|
+
path = record_path(sif)
|
|
174
|
+
if not path.is_file():
|
|
175
|
+
raise ValueError(f"{sif} has no verify record ({path.name}); run modelpolis verify first")
|
|
176
|
+
record = json.loads(path.read_text())
|
|
177
|
+
if record.get("result") != "passed":
|
|
178
|
+
raise ValueError(f"{path} does not record a passing verify")
|
|
179
|
+
if record.get("sha256") != sha256:
|
|
180
|
+
raise ValueError(
|
|
181
|
+
f"{sif} changed since it was verified: sha256 {sha256}, verified "
|
|
182
|
+
f"{record.get('sha256')}; run modelpolis verify again"
|
|
183
|
+
)
|
|
184
|
+
return record
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def deposit(sif: Path, dest: Path, sha256: str) -> None:
|
|
188
|
+
"""Copy ``sif`` to ``dest`` via a temporary file and a rename; skip if already there."""
|
|
189
|
+
if dest.is_file() and sha256_of(dest) == sha256:
|
|
190
|
+
return
|
|
191
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
192
|
+
partial = dest.with_name(f".{dest.name}.partial")
|
|
193
|
+
try:
|
|
194
|
+
shutil.copyfile(sif, partial)
|
|
195
|
+
actual = sha256_of(partial)
|
|
196
|
+
if actual != sha256:
|
|
197
|
+
raise ValueError(f"copy of {sif} has sha256 {actual}, expected {sha256}")
|
|
198
|
+
partial.replace(dest)
|
|
199
|
+
finally:
|
|
200
|
+
partial.unlink(missing_ok=True)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def read_catalog(path: Path) -> dict[str, dict]:
|
|
204
|
+
if not path.is_file():
|
|
205
|
+
return {}
|
|
206
|
+
with path.open("rb") as f:
|
|
207
|
+
return tomllib.load(f)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def write_catalog(path: Path, entries: dict[str, dict]) -> None:
|
|
211
|
+
"""Write the catalogue, one table per model in name order, through a temporary file."""
|
|
212
|
+
text = CATALOG_HEADER
|
|
213
|
+
for name in sorted(entries):
|
|
214
|
+
key = name if re.fullmatch(r"[A-Za-z0-9_-]+", name) else json.dumps(name)
|
|
215
|
+
text += f"\n[{key}]\n"
|
|
216
|
+
for key, value in entries[name].items():
|
|
217
|
+
text += f"{key} = {json.dumps(value)}\n"
|
|
218
|
+
partial = path.with_name(f".{path.name}.partial")
|
|
219
|
+
partial.write_text(text)
|
|
220
|
+
partial.replace(path)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def publish(
|
|
224
|
+
name_or_path: str,
|
|
225
|
+
sif: str | os.PathLike | None = None,
|
|
226
|
+
catalog: str | os.PathLike | None = None,
|
|
227
|
+
*,
|
|
228
|
+
push_to_registry: bool = False,
|
|
229
|
+
dry_run: bool = False,
|
|
230
|
+
) -> tuple[dict, Path]:
|
|
231
|
+
"""Deposit a verified SIF in the store and update the catalogue; return the entry and path."""
|
|
232
|
+
definition = read_model_toml(model_dir_for(name_or_path) / "model.toml")
|
|
233
|
+
registry = check_publish_metadata(definition) if push_to_registry else LOCAL
|
|
234
|
+
name = definition.spec.name
|
|
235
|
+
sif = Path(sif) if sif is not None else newest_build(name)
|
|
236
|
+
if not sif.is_file():
|
|
237
|
+
raise FileNotFoundError(f"no SIF at {sif}")
|
|
238
|
+
sha256 = sha256_of(sif)
|
|
239
|
+
check_verified(sif, sha256)
|
|
240
|
+
spec = describe(sif)
|
|
241
|
+
if spec.name != name:
|
|
242
|
+
raise ValueError(f"{sif} is the image of {spec.name!r}, not {name!r}")
|
|
243
|
+
|
|
244
|
+
dest = images_dir(name) / f"{spec.version}-{sha256[:12]}.sif"
|
|
245
|
+
entry = {"registry": LOCAL, "sha256": sha256, "api": spec.api, "version": spec.version}
|
|
246
|
+
if push_to_registry:
|
|
247
|
+
if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)*", spec.version):
|
|
248
|
+
raise ValueError(
|
|
249
|
+
f"SIF version {spec.version!r} must be ASCII numbers joined by dots "
|
|
250
|
+
"(for example, 1.2.0) for --push"
|
|
251
|
+
)
|
|
252
|
+
tag = f"{spec.version}-api{spec.api}-{sha256[:12]}"
|
|
253
|
+
if not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}", tag):
|
|
254
|
+
raise ValueError(f"SIF version and API produce an invalid registry tag: {tag!r}")
|
|
255
|
+
restrictions = definition.publish.get("restrictions", "").strip()
|
|
256
|
+
entry["registry"] = f"{registry}:{tag}"
|
|
257
|
+
entry["license"] = definition.publish["license"] + (
|
|
258
|
+
f"; {restrictions}" if restrictions else ""
|
|
259
|
+
)
|
|
260
|
+
overview = overview_text(definition, {"name": name} | entry)
|
|
261
|
+
rule_registry = f"oras://docker.io/{DOCKER_HUB_NAMESPACE}/{DOCKER_HUB_PREFIX}{name}"
|
|
262
|
+
if registry != rule_registry:
|
|
263
|
+
print(f"Image version check was not made: only {rule_registry} is supported.")
|
|
264
|
+
elif dry_run:
|
|
265
|
+
print("Repository tags will be read at the real push to check the image version.")
|
|
266
|
+
else:
|
|
267
|
+
version = tuple(int(part) for part in spec.version.split("."))
|
|
268
|
+
for existing in docker_hub_tags(name):
|
|
269
|
+
if (
|
|
270
|
+
tuple(int(part) for part in existing.version.split(".")) == version
|
|
271
|
+
and existing.api == spec.api
|
|
272
|
+
and existing.sha12 != sha256[:12]
|
|
273
|
+
):
|
|
274
|
+
raise ValueError(
|
|
275
|
+
f"{registry} already has tag {existing.tag} with another image; "
|
|
276
|
+
"raise the model's version before pushing"
|
|
277
|
+
)
|
|
278
|
+
if not dry_run and registry.startswith("oras://docker.io/"):
|
|
279
|
+
docker_hub_token() # Reject unusable overview credentials before uploading.
|
|
280
|
+
push(sif, entry["registry"], dry_run=dry_run)
|
|
281
|
+
if dry_run:
|
|
282
|
+
print(overview)
|
|
283
|
+
elif registry.startswith("oras://docker.io/"):
|
|
284
|
+
try:
|
|
285
|
+
set_docker_hub_overview(registry, overview)
|
|
286
|
+
except ValueError as e:
|
|
287
|
+
raise ValueError(
|
|
288
|
+
f"{e}; the image is pushed to {entry['registry']}, but the overview "
|
|
289
|
+
"was not set. The catalogue is unchanged; fix the overview error and "
|
|
290
|
+
"run the same command again to complete publication."
|
|
291
|
+
) from None
|
|
292
|
+
else:
|
|
293
|
+
print(overview)
|
|
294
|
+
print("Repository overview was not set: automatic updates support Docker Hub only.")
|
|
295
|
+
if dry_run:
|
|
296
|
+
print(f"Would deposit {sif} at {dest} and update the catalogue; no changes made.")
|
|
297
|
+
return {"name": name} | entry, dest
|
|
298
|
+
deposit(sif, dest, sha256)
|
|
299
|
+
path = Path(catalog) if catalog is not None else CATALOG
|
|
300
|
+
entries = read_catalog(path)
|
|
301
|
+
entries[name] = entry
|
|
302
|
+
write_catalog(path, entries)
|
|
303
|
+
return {"name": name} | entry, dest
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Verify a SIF against its model directory (plan/DESIGN.md section 6).
|
|
2
|
+
|
|
3
|
+
First the runner's conformance checklist, then the reference input: ``reference/input.txt`` is
|
|
4
|
+
predicted with all outputs, and each output is compared with its reference. Shape and dtype must
|
|
5
|
+
match exactly; values must meet the model definition's ``[build] tolerance`` (P1 unless a
|
|
6
|
+
maintainer approved another). The options are the defaults, or those of
|
|
7
|
+
``reference/options.json`` if it is there. Each subfolder of ``reference/`` with an
|
|
8
|
+
``input.txt`` is one more reference, laid out the same way and checked the same way; its results
|
|
9
|
+
are labelled ``<subfolder>/<output>`` (AlphaGenome: ``window_2048/``).
|
|
10
|
+
|
|
11
|
+
Without ``reference/slice.json`` (the fake model), each output is compared with
|
|
12
|
+
``reference/<output>.npy``, which has a leading batch axis of 1. With it (a real model,
|
|
13
|
+
docs/decisions/2026-11-24-reference-outputs.md), ``slice.json`` maps each checked output to
|
|
14
|
+
``{"axis", "indices", "full", "full_sha256"}``, or, to slice several axes, ``{"axes": {<axis>:
|
|
15
|
+
<indices>, ...}, "full", "full_sha256"}`` (Borzoi: every 4th bin and every 32nd track):
|
|
16
|
+
|
|
17
|
+
- the slice: the prediction for the one input, without its batch axis, at ``indices`` along
|
|
18
|
+
``axis`` (along each axis of ``axes``, in turn), against ``reference/<output>.npy``. Always
|
|
19
|
+
run.
|
|
20
|
+
- the full reference: the whole prediction against ``<data root>/<full>``, after checking its
|
|
21
|
+
sha256. With ``"full_batch_axis": true`` the full file keeps the batch axis of 1 of its
|
|
22
|
+
capture (Borzoi), and the prediction is compared with its batch axis. Skipped, and reported as
|
|
23
|
+
skipped, if the data root or the file is not there.
|
|
24
|
+
- an output not in ``slice.json`` has no reference and is reported as unchecked; it does not fail.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
import hashlib
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
from dataclasses import dataclass
|
|
31
|
+
from datetime import UTC, datetime
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
|
|
36
|
+
from modelpolis.paths import load_paths
|
|
37
|
+
from modelpolis.runner import conformance
|
|
38
|
+
from modelpolis.runner.model import load
|
|
39
|
+
|
|
40
|
+
from .image import model_dir_for, sha256_of, store_root
|
|
41
|
+
from .model_toml import FP32, MIXED, P1, read_model_toml
|
|
42
|
+
|
|
43
|
+
RTOL, ATOL = P1["rtol"], P1["atol"]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Comparison:
|
|
48
|
+
output: str
|
|
49
|
+
passed: bool | None # None: not compared (skipped or unchecked); never a failure
|
|
50
|
+
max_abs: float | None = None
|
|
51
|
+
max_rel: float | None = None
|
|
52
|
+
detail: str = ""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def newest_build(name: str) -> Path:
|
|
56
|
+
"""The newest ``*.sif`` in ``$MODELPOLIS_HOME/builds/<name>/``."""
|
|
57
|
+
folder = store_root() / "builds" / name
|
|
58
|
+
candidates = sorted(folder.glob("*.sif")) if folder.is_dir() else []
|
|
59
|
+
if not candidates:
|
|
60
|
+
raise FileNotFoundError(f"no SIF for {name!r} in {folder}; run modelpolis build {name}")
|
|
61
|
+
return max(candidates, key=lambda p: (p.stat().st_mtime, p.name))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def compare(
|
|
65
|
+
output: str, got: np.ndarray, reference_file: Path, rtol: float = RTOL, atol: float = ATOL
|
|
66
|
+
) -> Comparison:
|
|
67
|
+
"""One output against its reference file: exact shape and dtype, values within tolerance."""
|
|
68
|
+
if not reference_file.is_file():
|
|
69
|
+
return Comparison(output, False, detail=f"missing reference file {reference_file}")
|
|
70
|
+
ref = np.load(reference_file)
|
|
71
|
+
if got.shape != ref.shape or got.dtype != ref.dtype:
|
|
72
|
+
return Comparison(
|
|
73
|
+
output, False, detail=f"got {got.dtype} {got.shape}, reference {ref.dtype} {ref.shape}"
|
|
74
|
+
)
|
|
75
|
+
if got.size == 0:
|
|
76
|
+
return Comparison(output, True, 0.0, 0.0)
|
|
77
|
+
a, b = got.astype(np.float64), ref.astype(np.float64)
|
|
78
|
+
diff = np.abs(a - b)
|
|
79
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
80
|
+
rel = np.where(diff == 0, 0.0, diff / np.abs(b))
|
|
81
|
+
passed = bool(np.allclose(got, ref, rtol=rtol, atol=atol))
|
|
82
|
+
return Comparison(output, passed, float(np.nanmax(diff)), float(np.nanmax(rel)))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def compare_full(output: str, got: np.ndarray, entry: dict, rtol=RTOL, atol=ATOL) -> Comparison:
|
|
86
|
+
"""``got`` against the full reference under the data root, or a skip saying why."""
|
|
87
|
+
label = f"{output} (full)"
|
|
88
|
+
try:
|
|
89
|
+
path = load_paths().root / entry["full"]
|
|
90
|
+
except RuntimeError as e:
|
|
91
|
+
return Comparison(label, None, detail=f"skipped: no data root ({e})")
|
|
92
|
+
if not path.is_file():
|
|
93
|
+
return Comparison(label, None, detail=f"skipped: {path} not found")
|
|
94
|
+
h = hashlib.sha256()
|
|
95
|
+
with path.open("rb") as f:
|
|
96
|
+
for block in iter(lambda: f.read(1 << 20), b""):
|
|
97
|
+
h.update(block)
|
|
98
|
+
if "full_sha256" in entry and h.hexdigest() != entry["full_sha256"]:
|
|
99
|
+
return Comparison(label, False, detail=f"{path}: sha256 differs from slice.json")
|
|
100
|
+
result = compare(label, got[None] if entry.get("full_batch_axis") else got, path, rtol, atol)
|
|
101
|
+
result.detail = "; ".join(x for x in (result.detail, str(path)) if x)
|
|
102
|
+
return result
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def compare_sliced(
|
|
106
|
+
spec, out: dict[str, np.ndarray], reference: Path, rtol=RTOL, atol=ATOL
|
|
107
|
+
) -> list[Comparison]:
|
|
108
|
+
"""The slice and full comparisons of ``reference/slice.json`` (see the module docstring)."""
|
|
109
|
+
slices = json.loads((reference / "slice.json").read_text())
|
|
110
|
+
unknown = sorted(set(slices) - set(spec.outputs))
|
|
111
|
+
if unknown:
|
|
112
|
+
raise ValueError(f"slice.json names outputs not in the spec: {', '.join(unknown)}")
|
|
113
|
+
results = []
|
|
114
|
+
for name in spec.outputs:
|
|
115
|
+
if name not in slices:
|
|
116
|
+
results.append(Comparison(name, None, detail="unchecked: no reference for this output"))
|
|
117
|
+
continue
|
|
118
|
+
entry = slices[name]
|
|
119
|
+
got = out[name][0] # the one reference input, without the batch axis
|
|
120
|
+
picks = entry["axes"] if "axes" in entry else {entry["axis"]: entry["indices"]}
|
|
121
|
+
part = got
|
|
122
|
+
for axis, indices in picks.items():
|
|
123
|
+
index = np.asarray(indices, dtype=np.int64)
|
|
124
|
+
part = np.take(part, index, axis=spec.outputs[name].axes.index(axis))
|
|
125
|
+
results.append(compare(f"{name} (slice)", part, reference / f"{name}.npy", rtol, atol))
|
|
126
|
+
results.append(compare_full(name, got, entry, rtol, atol))
|
|
127
|
+
return results
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def reference_folders(reference: Path) -> list[Path]:
|
|
131
|
+
"""``reference/``, then each subfolder of it with an ``input.txt``, in name order."""
|
|
132
|
+
return [reference] + sorted(
|
|
133
|
+
p for p in reference.iterdir() if p.is_dir() and (p / "input.txt").is_file()
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def compare_reference(
|
|
138
|
+
sif: str | os.PathLike, model_dir: Path, device: str | None = None, rtol=RTOL, atol=ATOL
|
|
139
|
+
):
|
|
140
|
+
"""Predict each reference input and compare the outputs with their references."""
|
|
141
|
+
reference = Path(model_dir) / "reference"
|
|
142
|
+
folders = reference_folders(reference)
|
|
143
|
+
with load(sif, device) as model:
|
|
144
|
+
(input_name,) = model.spec.inputs
|
|
145
|
+
spec = model.spec
|
|
146
|
+
outs = []
|
|
147
|
+
for folder in folders:
|
|
148
|
+
sequence = (folder / "input.txt").read_text().strip()
|
|
149
|
+
given = folder / "options.json"
|
|
150
|
+
options = json.loads(given.read_text()) if given.is_file() else None
|
|
151
|
+
outs.append(model.predict({input_name: [sequence]}, options=options))
|
|
152
|
+
results = []
|
|
153
|
+
for folder, out in zip(folders, outs, strict=True):
|
|
154
|
+
if (folder / "slice.json").is_file():
|
|
155
|
+
found = compare_sliced(spec, out, folder, rtol, atol)
|
|
156
|
+
else:
|
|
157
|
+
found = [
|
|
158
|
+
compare(name, out[name], folder / f"{name}.npy", rtol, atol)
|
|
159
|
+
for name in spec.outputs
|
|
160
|
+
]
|
|
161
|
+
if folder != reference:
|
|
162
|
+
for c in found:
|
|
163
|
+
c.output = f"{folder.name}/{c.output}"
|
|
164
|
+
results += found
|
|
165
|
+
return results
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def choose_precision(comparisons: list[Comparison]) -> str:
|
|
169
|
+
"""Rule 6: mixed precision if every checked output met the tolerance, else fp32.
|
|
170
|
+
|
|
171
|
+
``comparisons`` are those of a mixed-precision image. At least one must have been compared;
|
|
172
|
+
skipped and unchecked outputs (``passed is None``) neither pass nor fail it.
|
|
173
|
+
"""
|
|
174
|
+
checked = [c.passed for c in comparisons if c.passed is not None]
|
|
175
|
+
return MIXED if checked and all(checked) else FP32
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def write_precision_record(sif: Path, chosen: str, tolerance: dict, comparisons) -> Path:
|
|
179
|
+
"""Record the build's precision check next to the SIF: ``<sif>.precision.json``."""
|
|
180
|
+
record = {
|
|
181
|
+
"sif": sif.name,
|
|
182
|
+
"chosen": chosen,
|
|
183
|
+
"tried": MIXED,
|
|
184
|
+
"tolerance": tolerance,
|
|
185
|
+
"date": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
186
|
+
"comparisons": [vars(c) for c in comparisons],
|
|
187
|
+
}
|
|
188
|
+
path = sif.with_name(sif.name + ".precision.json")
|
|
189
|
+
path.write_text(json.dumps(record, indent=2) + "\n")
|
|
190
|
+
return path
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def record_path(sif: str | os.PathLike) -> Path:
|
|
194
|
+
"""The verify record of a SIF: ``<sif>.verify.json`` next to it."""
|
|
195
|
+
sif = Path(sif)
|
|
196
|
+
return sif.with_name(sif.name + ".verify.json")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def write_record(sif: str | os.PathLike, name: str, summary: list[str]) -> Path:
|
|
200
|
+
"""After a passing verify, record the SIF's sha256, the date and the result lines.
|
|
201
|
+
|
|
202
|
+
``modelpolis publish`` accepts a SIF only if this record's sha256 equals the SIF's.
|
|
203
|
+
"""
|
|
204
|
+
record = {
|
|
205
|
+
"name": name,
|
|
206
|
+
"sif": Path(sif).name,
|
|
207
|
+
"sha256": sha256_of(Path(sif)),
|
|
208
|
+
"date": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
209
|
+
"result": "passed",
|
|
210
|
+
"summary": summary,
|
|
211
|
+
}
|
|
212
|
+
path = record_path(sif)
|
|
213
|
+
path.write_text(json.dumps(record, indent=2) + "\n")
|
|
214
|
+
return path
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def verify(name_or_path: str, sif: str | os.PathLike | None = None, device: str | None = None):
|
|
218
|
+
"""Run conformance and the reference comparison; return the SIF, both result lists."""
|
|
219
|
+
model_dir = model_dir_for(name_or_path)
|
|
220
|
+
definition = read_model_toml(model_dir / "model.toml")
|
|
221
|
+
if sif is None:
|
|
222
|
+
sif = newest_build(definition.spec.name)
|
|
223
|
+
results = conformance.run(sif, device)
|
|
224
|
+
if any(r.passed is False for r in results):
|
|
225
|
+
return Path(sif), results, []
|
|
226
|
+
return Path(sif), results, compare_reference(sif, model_dir, device, **definition.tolerance)
|