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
modelpolis/cli.py
ADDED
|
@@ -0,0 +1,679 @@
|
|
|
1
|
+
"""The ``modelpolis`` command: one function per subcommand, filled in by later tasks."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
# (subcommand, help, takes a model name)
|
|
8
|
+
SUBCOMMANDS = [
|
|
9
|
+
("list", "list the models in the store, the catalogue and Docker Hub", False),
|
|
10
|
+
("describe", "print a model's spec", True),
|
|
11
|
+
("fetch", "pull a model's image into the store ahead of time", True),
|
|
12
|
+
("predict", "run a model on input sequences", True),
|
|
13
|
+
("bench", "measure a model's throughput", True),
|
|
14
|
+
("new", "start a model directory from the fake model", True),
|
|
15
|
+
("build", "build a model's image with Apptainer", True),
|
|
16
|
+
("verify", "check an image with conformance and its reference output", True),
|
|
17
|
+
("publish", "place a verified image in the store and the catalogue", True),
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _not_implemented(args: argparse.Namespace) -> int:
|
|
22
|
+
print(f"modelpolis {args.command}: not implemented yet", file=sys.stderr)
|
|
23
|
+
return 2
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cmd_list(args: argparse.Namespace) -> int:
|
|
27
|
+
import re
|
|
28
|
+
|
|
29
|
+
from modelpolis.runner import store
|
|
30
|
+
|
|
31
|
+
try:
|
|
32
|
+
entries = store.read_catalog(args.catalog)
|
|
33
|
+
rows = {}
|
|
34
|
+
for folder in (store.store_root() / "images").glob("*"):
|
|
35
|
+
if not folder.is_dir() or folder.name in entries:
|
|
36
|
+
continue
|
|
37
|
+
candidates = [path for path in folder.glob("*.sif") if path.is_file()]
|
|
38
|
+
if candidates:
|
|
39
|
+
newest = max(candidates, key=lambda p: (p.stat().st_mtime, p.name))
|
|
40
|
+
match = re.fullmatch(r"(.+)-[0-9a-f]{12}", newest.stem)
|
|
41
|
+
version = match[1] if match else newest.stem
|
|
42
|
+
rows[folder.name] = (version, "local", "present")
|
|
43
|
+
except (OSError, ValueError) as e:
|
|
44
|
+
print(f"modelpolis list: {e}", file=sys.stderr)
|
|
45
|
+
return 1
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
names = store.docker_hub_names()
|
|
49
|
+
except RuntimeError as e:
|
|
50
|
+
print(f"modelpolis list: {e}", file=sys.stderr)
|
|
51
|
+
names = []
|
|
52
|
+
for name in names:
|
|
53
|
+
if name in entries:
|
|
54
|
+
continue
|
|
55
|
+
try:
|
|
56
|
+
entry = store._docker_hub_entry(name)
|
|
57
|
+
except RuntimeError as e:
|
|
58
|
+
print(f"modelpolis list: {e}", file=sys.stderr)
|
|
59
|
+
continue
|
|
60
|
+
if entry is not None:
|
|
61
|
+
entries[name] = entry
|
|
62
|
+
|
|
63
|
+
for name, entry in entries.items():
|
|
64
|
+
present = "present" if store.catalog_image(name, entry).is_file() else "missing"
|
|
65
|
+
rows[name] = (entry["version"], entry["registry"], present)
|
|
66
|
+
for name in sorted(rows):
|
|
67
|
+
print(name, *rows[name], sep="\t")
|
|
68
|
+
return 0
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def cmd_describe(args: argparse.Namespace) -> int:
|
|
72
|
+
import json
|
|
73
|
+
|
|
74
|
+
from modelpolis.runner.model import describe
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
spec = describe(args.name)
|
|
78
|
+
except (FileNotFoundError, RuntimeError, ValueError) as e:
|
|
79
|
+
print(f"modelpolis describe: {e}", file=sys.stderr)
|
|
80
|
+
return 1
|
|
81
|
+
print(json.dumps(spec.to_json(), indent=2))
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def cmd_fetch(args: argparse.Namespace) -> int:
|
|
86
|
+
from modelpolis.runner.store import fetch
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
sif = fetch(args.name, args.catalog)
|
|
90
|
+
except (OSError, RuntimeError, ValueError) as e:
|
|
91
|
+
print(f"modelpolis fetch: {e}", file=sys.stderr)
|
|
92
|
+
return 1
|
|
93
|
+
print(sif)
|
|
94
|
+
return 0
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_predict(args: argparse.Namespace) -> int:
|
|
98
|
+
from pathlib import Path
|
|
99
|
+
|
|
100
|
+
import numpy as np
|
|
101
|
+
|
|
102
|
+
from modelpolis.runner.model import load
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
with open(args.input) as f:
|
|
106
|
+
sequences = [line.strip() for line in f if line.strip()]
|
|
107
|
+
out_dir = Path(args.output)
|
|
108
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
with load(args.name, device=args.device) as model:
|
|
110
|
+
outputs = model.predict(sequences)
|
|
111
|
+
except (OSError, RuntimeError, ValueError) as e:
|
|
112
|
+
print(f"modelpolis predict: {e}", file=sys.stderr)
|
|
113
|
+
return 1
|
|
114
|
+
for name, value in outputs.items():
|
|
115
|
+
if isinstance(value, list): # items of different sizes: one file per item
|
|
116
|
+
paths = [out_dir / f"{name}.{i}.npy" for i in range(len(value))]
|
|
117
|
+
for path, item in zip(paths, value, strict=True):
|
|
118
|
+
np.save(path, item)
|
|
119
|
+
else:
|
|
120
|
+
paths = [out_dir / f"{name}.npy"]
|
|
121
|
+
np.save(paths[0], value)
|
|
122
|
+
for path in paths:
|
|
123
|
+
print(path)
|
|
124
|
+
return 0
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
BENCH_HEADER = (
|
|
128
|
+
"| date | model | image | GPU model | load time | sequences per second "
|
|
129
|
+
"| peak GPU memory | transfer time | note |"
|
|
130
|
+
)
|
|
131
|
+
BENCH_SEPARATOR = "|---|---|---|---|---:|---:|---|---|---|"
|
|
132
|
+
BENCH_HELP = """\
|
|
133
|
+
Load the model, run warm-up then timed predictions on fixed random ACGT sequences (seed 0, the
|
|
134
|
+
spec's input length), print the results and add one row to the results table.
|
|
135
|
+
|
|
136
|
+
load time seconds for load(): container start-up plus model loading
|
|
137
|
+
sequences per second timed sequences / sum of the timed predict() seconds (as M0.T6)
|
|
138
|
+
peak GPU memory largest GPU memory nvidia-smi reports for the processes bench started
|
|
139
|
+
(the worker and its container), sampled every 0.2 s from before load
|
|
140
|
+
to the last request; includes the CUDA context and allocator cache and
|
|
141
|
+
can miss peaks shorter than a sample; n/a on the CPU or with no sample
|
|
142
|
+
transfer time seconds per timed sequence spent outside the worker's infer_s: input
|
|
143
|
+
writing and reading, text preparation, the pipe and the runner reading
|
|
144
|
+
outputs; the device-to-host copy and the worker's np.save of outputs
|
|
145
|
+
fall inside infer_s, so this is a lower bound on the transfer
|
|
146
|
+
|
|
147
|
+
With --stream, each request consumes model.stream() chunk by chunk and drops each chunk's
|
|
148
|
+
outputs, instead of calling predict(), which joins them.
|
|
149
|
+
|
|
150
|
+
The note gives the runner's peak memory (ru_maxrss of the bench process, which holds the runner:
|
|
151
|
+
its whole life, not the worker or the container) and ends with the seconds of the first request
|
|
152
|
+
(a warm-up one, if any) and of the last.
|
|
153
|
+
|
|
154
|
+
The row goes after the last row of the table with the bench header, or, if the file has none,
|
|
155
|
+
at its end under a new header."""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _gpu_model(device: str) -> str:
|
|
159
|
+
"""The name nvidia-smi gives GPU ``n`` of ``cuda:n``; ``n/a`` on the CPU."""
|
|
160
|
+
import subprocess
|
|
161
|
+
|
|
162
|
+
if device == "cpu":
|
|
163
|
+
return "n/a"
|
|
164
|
+
index = device.partition(":")[2]
|
|
165
|
+
try:
|
|
166
|
+
out = subprocess.run(
|
|
167
|
+
["nvidia-smi", "-i", index, "--query-gpu=name", "--format=csv,noheader"],
|
|
168
|
+
check=True,
|
|
169
|
+
capture_output=True,
|
|
170
|
+
text=True,
|
|
171
|
+
).stdout.strip()
|
|
172
|
+
except (OSError, subprocess.CalledProcessError):
|
|
173
|
+
return "n/a"
|
|
174
|
+
return out or "n/a"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _descendants(root: int) -> set[int]:
|
|
178
|
+
"""PIDs of every process below ``root``, read from ``/proc``."""
|
|
179
|
+
import os
|
|
180
|
+
|
|
181
|
+
parents = {}
|
|
182
|
+
for entry in os.listdir("/proc"):
|
|
183
|
+
if entry.isdigit():
|
|
184
|
+
try:
|
|
185
|
+
with open(f"/proc/{entry}/stat") as f:
|
|
186
|
+
stat = f.read()
|
|
187
|
+
except OSError:
|
|
188
|
+
continue
|
|
189
|
+
parents[int(entry)] = int(stat.rpartition(")")[2].split()[1])
|
|
190
|
+
found, frontier = set(), {root}
|
|
191
|
+
while frontier:
|
|
192
|
+
frontier = {pid for pid, ppid in parents.items() if ppid in frontier} - found
|
|
193
|
+
found |= frontier
|
|
194
|
+
return found
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class _GpuMemory:
|
|
198
|
+
"""Samples, in a thread, the GPU memory nvidia-smi reports for processes below this one."""
|
|
199
|
+
|
|
200
|
+
def __init__(self, interval_s: float = 0.2):
|
|
201
|
+
import threading
|
|
202
|
+
|
|
203
|
+
self.peak_mib: int | None = None
|
|
204
|
+
self._interval_s = interval_s
|
|
205
|
+
self._stop = threading.Event()
|
|
206
|
+
self._thread = threading.Thread(target=self._run, daemon=True)
|
|
207
|
+
|
|
208
|
+
def _sample(self) -> None:
|
|
209
|
+
import os
|
|
210
|
+
import subprocess
|
|
211
|
+
|
|
212
|
+
try:
|
|
213
|
+
out = subprocess.run(
|
|
214
|
+
[
|
|
215
|
+
"nvidia-smi",
|
|
216
|
+
"--query-compute-apps=pid,used_memory",
|
|
217
|
+
"--format=csv,noheader,nounits",
|
|
218
|
+
],
|
|
219
|
+
check=True,
|
|
220
|
+
capture_output=True,
|
|
221
|
+
text=True,
|
|
222
|
+
).stdout
|
|
223
|
+
except (OSError, subprocess.CalledProcessError):
|
|
224
|
+
return
|
|
225
|
+
mine = _descendants(os.getpid())
|
|
226
|
+
used = 0
|
|
227
|
+
for line in out.splitlines():
|
|
228
|
+
pid, _, mib = line.partition(",")
|
|
229
|
+
if pid.strip().isdigit() and int(pid) in mine and mib.strip().isdigit():
|
|
230
|
+
used += int(mib)
|
|
231
|
+
if used:
|
|
232
|
+
self.peak_mib = max(self.peak_mib or 0, used)
|
|
233
|
+
|
|
234
|
+
def _run(self) -> None:
|
|
235
|
+
while not self._stop.is_set():
|
|
236
|
+
self._sample()
|
|
237
|
+
self._stop.wait(self._interval_s)
|
|
238
|
+
|
|
239
|
+
def __enter__(self):
|
|
240
|
+
self._thread.start()
|
|
241
|
+
return self
|
|
242
|
+
|
|
243
|
+
def __exit__(self, *exc) -> None:
|
|
244
|
+
self._stop.set()
|
|
245
|
+
self._thread.join()
|
|
246
|
+
self._sample()
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _commit() -> str:
|
|
250
|
+
"""The short commit of this checkout, ``-dirty`` if it has changes; ``n/a`` outside git."""
|
|
251
|
+
import subprocess
|
|
252
|
+
|
|
253
|
+
here = Path(__file__).parent
|
|
254
|
+
try:
|
|
255
|
+
sha = subprocess.run(
|
|
256
|
+
["git", "-C", str(here), "rev-parse", "--short", "HEAD"],
|
|
257
|
+
check=True,
|
|
258
|
+
capture_output=True,
|
|
259
|
+
text=True,
|
|
260
|
+
).stdout.strip()
|
|
261
|
+
dirty = subprocess.run(
|
|
262
|
+
["git", "-C", str(here), "status", "--porcelain"],
|
|
263
|
+
check=True,
|
|
264
|
+
capture_output=True,
|
|
265
|
+
text=True,
|
|
266
|
+
).stdout.strip()
|
|
267
|
+
except (OSError, subprocess.CalledProcessError):
|
|
268
|
+
return "n/a"
|
|
269
|
+
return sha + ("-dirty" if dirty else "")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _parse_subset(items: list[str]) -> dict:
|
|
273
|
+
"""``axis=start:stop`` or ``axis=i,j,k`` to the ``subset`` argument of ``predict``."""
|
|
274
|
+
subset = {}
|
|
275
|
+
for item in items:
|
|
276
|
+
axis, eq, sel = item.partition("=")
|
|
277
|
+
if not eq or not axis:
|
|
278
|
+
raise ValueError(f"--subset must be axis=start:stop or axis=i,j,..., got {item!r}")
|
|
279
|
+
if ":" in sel:
|
|
280
|
+
start, _, stop = sel.partition(":")
|
|
281
|
+
subset[axis] = slice(int(start) if start else None, int(stop) if stop else None)
|
|
282
|
+
else:
|
|
283
|
+
subset[axis] = [int(i) for i in sel.split(",")]
|
|
284
|
+
return subset
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _add_row(path, row: str) -> None:
|
|
288
|
+
"""Insert ``row`` after the last row of the bench table, or add the table at the end."""
|
|
289
|
+
path = Path(path)
|
|
290
|
+
lines = path.read_text().splitlines() if path.is_file() else []
|
|
291
|
+
if BENCH_HEADER in lines:
|
|
292
|
+
end = lines.index(BENCH_HEADER) + 1
|
|
293
|
+
while end < len(lines) and lines[end].startswith("|"):
|
|
294
|
+
end += 1
|
|
295
|
+
lines.insert(end, row)
|
|
296
|
+
else:
|
|
297
|
+
if lines and lines[-1].strip():
|
|
298
|
+
lines.append("")
|
|
299
|
+
lines += [BENCH_HEADER, BENCH_SEPARATOR, row]
|
|
300
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
301
|
+
path.write_text("\n".join(lines) + "\n")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _parse_options(spec, items: list[str]) -> dict:
|
|
305
|
+
"""Read ``name=value`` by the spec's option type, then validate and fill defaults."""
|
|
306
|
+
import json
|
|
307
|
+
|
|
308
|
+
from modelpolis.runner.model import check_options
|
|
309
|
+
|
|
310
|
+
options = {}
|
|
311
|
+
for item in items:
|
|
312
|
+
name, eq, value = item.partition("=")
|
|
313
|
+
if not eq or name not in spec.options:
|
|
314
|
+
raise ValueError(f"--option needs a known name=value, got {item!r}")
|
|
315
|
+
option = spec.options[name]
|
|
316
|
+
try:
|
|
317
|
+
if option.type == "int":
|
|
318
|
+
value = int(value)
|
|
319
|
+
elif option.type == "float":
|
|
320
|
+
value = float(value)
|
|
321
|
+
elif option.type == "bool":
|
|
322
|
+
value = {"true": True, "false": False}[value.lower()]
|
|
323
|
+
elif option.type == "choice" and value not in (option.choices or []):
|
|
324
|
+
value = json.loads(value)
|
|
325
|
+
except (ValueError, KeyError):
|
|
326
|
+
raise ValueError(
|
|
327
|
+
f"--option {name!r}: invalid {option.type} value in {item!r}"
|
|
328
|
+
) from None
|
|
329
|
+
options[name] = value
|
|
330
|
+
return check_options(spec, options)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def cmd_bench(args: argparse.Namespace) -> int:
|
|
334
|
+
from modelpolis.builder.image import REPO_ROOT, has_checkout
|
|
335
|
+
|
|
336
|
+
if args.results is None:
|
|
337
|
+
if not has_checkout():
|
|
338
|
+
print("modelpolis bench: without a checkout, pass --results <file>", file=sys.stderr)
|
|
339
|
+
return 1
|
|
340
|
+
args.results = str(REPO_ROOT / "bench" / "results.md")
|
|
341
|
+
|
|
342
|
+
import contextlib
|
|
343
|
+
import datetime
|
|
344
|
+
import json
|
|
345
|
+
import resource
|
|
346
|
+
import time
|
|
347
|
+
|
|
348
|
+
import numpy as np
|
|
349
|
+
|
|
350
|
+
from modelpolis.runner.api import OneOf, chosen_window
|
|
351
|
+
from modelpolis.runner.model import default_device, describe, load
|
|
352
|
+
from modelpolis.runner.store import find_image
|
|
353
|
+
|
|
354
|
+
try:
|
|
355
|
+
sif = find_image(args.name)
|
|
356
|
+
spec = describe(sif)
|
|
357
|
+
device = args.device or default_device(spec)
|
|
358
|
+
if len(spec.inputs) != 1 or next(iter(spec.inputs.values())).kind != "text":
|
|
359
|
+
raise ValueError("bench needs a model with exactly one text input")
|
|
360
|
+
options = _parse_options(spec, args.option)
|
|
361
|
+
input_name = next(iter(spec.inputs))
|
|
362
|
+
length = chosen_window(spec, input_name, options) or spec.inputs[input_name].length
|
|
363
|
+
length = max(length.values) if isinstance(length, OneOf) else length
|
|
364
|
+
if length is None:
|
|
365
|
+
raise ValueError("bench needs a fixed input length in the spec")
|
|
366
|
+
batch = spec.resources.batch if args.batch is None else args.batch
|
|
367
|
+
n_inputs = batch if args.inputs is None else args.inputs
|
|
368
|
+
if n_inputs < 1 or batch < 1 or args.repeats < 1 or args.warmup < 0:
|
|
369
|
+
raise ValueError("--inputs, --batch, --repeats must be at least 1, --warmup at least 0")
|
|
370
|
+
rng = np.random.default_rng(0)
|
|
371
|
+
sequences = ["".join(rng.choice(list("ACGT"), length)) for _ in range(n_inputs)]
|
|
372
|
+
outputs = args.outputs.split(",") if args.outputs else None
|
|
373
|
+
subset = _parse_subset(args.subset)
|
|
374
|
+
if args.stream:
|
|
375
|
+
|
|
376
|
+
def run(*a, **k):
|
|
377
|
+
for _ in model.stream(*a, **k):
|
|
378
|
+
pass # each chunk's outputs are dropped here
|
|
379
|
+
|
|
380
|
+
else:
|
|
381
|
+
|
|
382
|
+
def run(*a, **k):
|
|
383
|
+
model.predict(*a, **k)
|
|
384
|
+
|
|
385
|
+
memory = _GpuMemory() if device != "cpu" else contextlib.nullcontext()
|
|
386
|
+
with memory:
|
|
387
|
+
start = time.perf_counter()
|
|
388
|
+
model = load(sif, device=device)
|
|
389
|
+
load_s = time.perf_counter() - start
|
|
390
|
+
with model:
|
|
391
|
+
request_s = [] # every request, warm-up and timed, in order
|
|
392
|
+
for _ in range(args.warmup):
|
|
393
|
+
start = time.perf_counter()
|
|
394
|
+
run(sequences, outputs, subset, options=options, batch=batch)
|
|
395
|
+
request_s.append(time.perf_counter() - start)
|
|
396
|
+
timed_s = infer_s = 0.0
|
|
397
|
+
for _ in range(args.repeats):
|
|
398
|
+
model.infer_s = 0.0
|
|
399
|
+
start = time.perf_counter()
|
|
400
|
+
run(sequences, outputs, subset, options=options, batch=batch)
|
|
401
|
+
request_s.append(time.perf_counter() - start)
|
|
402
|
+
timed_s += request_s[-1]
|
|
403
|
+
infer_s += model.infer_s
|
|
404
|
+
except (OSError, RuntimeError, TypeError, ValueError) as e:
|
|
405
|
+
print(f"modelpolis bench: {e}", file=sys.stderr)
|
|
406
|
+
return 1
|
|
407
|
+
n = n_inputs * args.repeats
|
|
408
|
+
rss_mib = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024 # KiB on Linux
|
|
409
|
+
peak = getattr(memory, "peak_mib", None)
|
|
410
|
+
cells = {
|
|
411
|
+
"date": datetime.datetime.now(datetime.UTC).date().isoformat(),
|
|
412
|
+
"model": spec.name,
|
|
413
|
+
"image": sif.name,
|
|
414
|
+
"GPU model": _gpu_model(device),
|
|
415
|
+
"load time": f"{load_s:.6f}",
|
|
416
|
+
"sequences per second": f"{n / timed_s:.6f}",
|
|
417
|
+
"peak GPU memory": "n/a" if peak is None else f"{peak} MiB",
|
|
418
|
+
"transfer time": f"{max(timed_s - infer_s, 0.0) / n:.6f} s/seq",
|
|
419
|
+
}
|
|
420
|
+
details = (
|
|
421
|
+
f"commit {_commit()}; device {device}; batch {batch}; {n_inputs} inputs of {length}; "
|
|
422
|
+
f"{args.warmup} warm-up + {args.repeats} timed; "
|
|
423
|
+
f"outputs {args.outputs or 'all'}; subset {' '.join(args.subset) or 'none'}; "
|
|
424
|
+
f"options {json.dumps(options, sort_keys=True)}; "
|
|
425
|
+
f"{'stream' if args.stream else 'predict'}; runner peak RSS {rss_mib:.0f} MiB; "
|
|
426
|
+
f"first request {request_s[0]:.3f} s, last {request_s[-1]:.3f} s"
|
|
427
|
+
)
|
|
428
|
+
cells["note"] = f"{args.note}; {details}" if args.note else details
|
|
429
|
+
for key, value in cells.items():
|
|
430
|
+
print(f"{key}: {value}")
|
|
431
|
+
row = "| " + " | ".join(v.replace("|", "\\|") for v in cells.values()) + " |"
|
|
432
|
+
try:
|
|
433
|
+
_add_row(args.results, row)
|
|
434
|
+
except OSError as e:
|
|
435
|
+
print(f"modelpolis bench: {e}", file=sys.stderr)
|
|
436
|
+
return 1
|
|
437
|
+
print(f"row added to {args.results}")
|
|
438
|
+
return 0
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def cmd_new(args: argparse.Namespace) -> int:
|
|
442
|
+
import re
|
|
443
|
+
import shlex
|
|
444
|
+
import shutil
|
|
445
|
+
|
|
446
|
+
from modelpolis.builder.image import REPO_ROOT, require_checkout
|
|
447
|
+
|
|
448
|
+
try:
|
|
449
|
+
require_checkout()
|
|
450
|
+
if re.fullmatch(r"[a-z][a-z0-9_]*", args.name) is None:
|
|
451
|
+
raise ValueError(
|
|
452
|
+
f"invalid model name {args.name!r}: use lower-case letters, digits and "
|
|
453
|
+
"underscores, starting with a letter"
|
|
454
|
+
)
|
|
455
|
+
models = Path(args.models).expanduser() if args.models else REPO_ROOT / "models"
|
|
456
|
+
model_dir = models.resolve() / args.name
|
|
457
|
+
model_dir.mkdir(parents=True) # Refuse existing paths before copying anything.
|
|
458
|
+
try:
|
|
459
|
+
shutil.copytree(
|
|
460
|
+
REPO_ROOT / "models" / "_fake",
|
|
461
|
+
model_dir,
|
|
462
|
+
dirs_exist_ok=True,
|
|
463
|
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"),
|
|
464
|
+
)
|
|
465
|
+
definition = model_dir / "model.toml"
|
|
466
|
+
definition.write_text(
|
|
467
|
+
definition.read_text().replace('name = "_fake"', f'name = "{args.name}"', 1)
|
|
468
|
+
)
|
|
469
|
+
except BaseException:
|
|
470
|
+
shutil.rmtree(model_dir)
|
|
471
|
+
raise
|
|
472
|
+
except (OSError, ValueError) as e:
|
|
473
|
+
print(f"modelpolis new: {e}", file=sys.stderr)
|
|
474
|
+
return 1
|
|
475
|
+
print(model_dir)
|
|
476
|
+
path = shlex.quote(str(model_dir))
|
|
477
|
+
print(f"modelpolis build {path}")
|
|
478
|
+
print(f"modelpolis verify {path} --sif <sif>")
|
|
479
|
+
return 0
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def cmd_build(args: argparse.Namespace) -> int:
|
|
483
|
+
import json
|
|
484
|
+
import subprocess
|
|
485
|
+
|
|
486
|
+
from modelpolis.builder.image import build
|
|
487
|
+
|
|
488
|
+
try:
|
|
489
|
+
sif, sha256 = build(args.name, args.output, args.weights, args.device)
|
|
490
|
+
except subprocess.CalledProcessError as e:
|
|
491
|
+
print(f"modelpolis build: {e.cmd[0]} failed (exit {e.returncode})", file=sys.stderr)
|
|
492
|
+
return e.returncode or 1
|
|
493
|
+
except (OSError, ValueError) as e:
|
|
494
|
+
print(f"modelpolis build: {e}", file=sys.stderr)
|
|
495
|
+
return 1
|
|
496
|
+
print(sif)
|
|
497
|
+
print(f"sha256 {sha256}")
|
|
498
|
+
precision = sif.with_name(sif.name + ".precision.json")
|
|
499
|
+
if precision.is_file():
|
|
500
|
+
record = json.loads(precision.read_text())
|
|
501
|
+
print(f"precision {record['chosen']} (tried {record['tried']}; record {precision})")
|
|
502
|
+
for c in record["comparisons"]:
|
|
503
|
+
mark = {True: "pass", False: "FAIL", None: "skip"}[c["passed"]]
|
|
504
|
+
diffs = "" if c["max_abs"] is None else f"max abs {c['max_abs']:.3g}, "
|
|
505
|
+
diffs += "" if c["max_rel"] is None else f"max rel {c['max_rel']:.3g}"
|
|
506
|
+
print(f" {mark} {c['output']}: {'; '.join(x for x in (diffs, c['detail']) if x)}")
|
|
507
|
+
if not deposits_on_build(args.name):
|
|
508
|
+
return 0
|
|
509
|
+
# A model with protected weights cannot be pulled: one build also verifies the SIF and, if
|
|
510
|
+
# verify passes, places it in the store (plan/DESIGN.md section 5). Same checks as running
|
|
511
|
+
# modelpolis verify, then modelpolis publish.
|
|
512
|
+
verified = cmd_verify(argparse.Namespace(name=args.name, sif=str(sif), device=args.device))
|
|
513
|
+
if verified != 0:
|
|
514
|
+
return verified
|
|
515
|
+
return cmd_publish(argparse.Namespace(name=args.name, sif=str(sif), catalog=None))
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def deposits_on_build(name: str) -> bool:
|
|
519
|
+
"""True for a model whose weights are protected: ``build`` then verifies and publishes it."""
|
|
520
|
+
from modelpolis.builder.image import model_dir_for
|
|
521
|
+
from modelpolis.builder.model_toml import read_model_toml
|
|
522
|
+
|
|
523
|
+
definition = read_model_toml(model_dir_for(name) / "model.toml")
|
|
524
|
+
return definition.weights.get("source") == "protected"
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def cmd_verify(args: argparse.Namespace) -> int:
|
|
528
|
+
from modelpolis.builder.image import model_dir_for
|
|
529
|
+
from modelpolis.builder.model_toml import P1, read_model_toml
|
|
530
|
+
from modelpolis.builder.verify import verify, write_record
|
|
531
|
+
|
|
532
|
+
try:
|
|
533
|
+
sif, results, comparisons = verify(args.name, args.sif, args.device)
|
|
534
|
+
except (FileNotFoundError, ValueError) as e:
|
|
535
|
+
print(f"modelpolis verify: {e}", file=sys.stderr)
|
|
536
|
+
return 1
|
|
537
|
+
lines = [] # also kept in the verify record
|
|
538
|
+
|
|
539
|
+
def out(line: str) -> None:
|
|
540
|
+
print(line)
|
|
541
|
+
lines.append(line)
|
|
542
|
+
|
|
543
|
+
out(f"verify {sif}")
|
|
544
|
+
out("conformance:")
|
|
545
|
+
for r in results:
|
|
546
|
+
mark = {True: "pass", False: "FAIL", None: "skip"}[r.passed]
|
|
547
|
+
out(f" {mark} {r.item}: {r.detail}")
|
|
548
|
+
passed = all(r.passed is not False for r in results)
|
|
549
|
+
if not passed:
|
|
550
|
+
out("reference: not run, conformance failed")
|
|
551
|
+
else:
|
|
552
|
+
tolerance = read_model_toml(model_dir_for(args.name) / "model.toml").tolerance
|
|
553
|
+
label = ", P1" if tolerance == P1 else ", not P1"
|
|
554
|
+
out(f"reference (rtol={tolerance['rtol']}, atol={tolerance['atol']}{label}):")
|
|
555
|
+
for c in comparisons:
|
|
556
|
+
mark = {True: "pass", False: "FAIL", None: "skip"}[c.passed]
|
|
557
|
+
diffs = "" if c.max_abs is None else f"max abs {c.max_abs:.3g}, max rel {c.max_rel:.3g}"
|
|
558
|
+
if c.max_abs == 0:
|
|
559
|
+
diffs += " (exact match)"
|
|
560
|
+
out(f" {mark} {c.output}: {'; '.join(x for x in (diffs, c.detail) if x)}")
|
|
561
|
+
passed = all(c.passed is not False for c in comparisons)
|
|
562
|
+
failed = [r.item for r in results if r.passed is False] + [
|
|
563
|
+
c.output for c in comparisons if c.passed is False
|
|
564
|
+
]
|
|
565
|
+
out("verify: passed" if passed else f"verify: FAILED ({', '.join(failed)})")
|
|
566
|
+
if passed:
|
|
567
|
+
name = read_model_toml(model_dir_for(args.name) / "model.toml").spec.name
|
|
568
|
+
print(f"record {write_record(sif, name, lines)}")
|
|
569
|
+
return 0 if passed else 1
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def cmd_publish(args: argparse.Namespace) -> int:
|
|
573
|
+
import subprocess
|
|
574
|
+
|
|
575
|
+
from modelpolis.builder.publish import publish
|
|
576
|
+
|
|
577
|
+
try:
|
|
578
|
+
entry, dest = publish(
|
|
579
|
+
args.name,
|
|
580
|
+
args.sif,
|
|
581
|
+
args.catalog,
|
|
582
|
+
push_to_registry=getattr(args, "push", False),
|
|
583
|
+
dry_run=getattr(args, "dry_run", False),
|
|
584
|
+
)
|
|
585
|
+
except subprocess.CalledProcessError as e:
|
|
586
|
+
print(f"modelpolis publish: apptainer push failed (exit {e.returncode})", file=sys.stderr)
|
|
587
|
+
return e.returncode or 1
|
|
588
|
+
except (OSError, ValueError, RuntimeError) as e:
|
|
589
|
+
print(f"modelpolis publish: {e}", file=sys.stderr)
|
|
590
|
+
return 1
|
|
591
|
+
if getattr(args, "dry_run", False):
|
|
592
|
+
return 0
|
|
593
|
+
print(dest)
|
|
594
|
+
print(f"sha256 {entry['sha256']}")
|
|
595
|
+
print(f"catalogue: {entry['name']} = {entry['registry']}, version {entry['version']}")
|
|
596
|
+
return 0
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
600
|
+
parser = argparse.ArgumentParser(prog="modelpolis", description=__doc__)
|
|
601
|
+
sub = parser.add_subparsers(dest="command", metavar="command", required=True)
|
|
602
|
+
for name, help_text, takes_name in SUBCOMMANDS:
|
|
603
|
+
p = sub.add_parser(name, help=help_text, description=help_text)
|
|
604
|
+
if takes_name:
|
|
605
|
+
p.add_argument(
|
|
606
|
+
"name",
|
|
607
|
+
help="new model name: [a-z][a-z0-9_]*"
|
|
608
|
+
if name == "new"
|
|
609
|
+
else "model name or path to a SIF",
|
|
610
|
+
)
|
|
611
|
+
if name == "new":
|
|
612
|
+
p.add_argument("--models", help="parent folder (default: models/ in the repo)")
|
|
613
|
+
if name in ("list", "fetch"):
|
|
614
|
+
p.add_argument("--catalog", help="catalogue file (default: catalog.toml in the repo)")
|
|
615
|
+
if name == "predict":
|
|
616
|
+
p.add_argument("input", help="text file with one sequence per line")
|
|
617
|
+
p.add_argument("--output", required=True, help="folder for one <output>.npy per output")
|
|
618
|
+
p.add_argument("--device", help="device such as cpu or cuda:0 (default: from the spec)")
|
|
619
|
+
if name == "bench":
|
|
620
|
+
p.description = BENCH_HELP
|
|
621
|
+
p.formatter_class = argparse.RawDescriptionHelpFormatter
|
|
622
|
+
p.add_argument("--device", help="device such as cpu or cuda:0 (default: from the spec)")
|
|
623
|
+
p.add_argument("--batch", type=int, help="items per request (default: from the spec)")
|
|
624
|
+
p.add_argument("--inputs", type=int, help="sequences per prediction (default: batch)")
|
|
625
|
+
p.add_argument("--warmup", type=int, default=2, help="untimed predictions (default 2)")
|
|
626
|
+
p.add_argument("--repeats", type=int, default=5, help="timed predictions (default 5)")
|
|
627
|
+
p.add_argument("--outputs", help="comma-separated outputs to request (default: all)")
|
|
628
|
+
p.add_argument(
|
|
629
|
+
"--option",
|
|
630
|
+
action="append",
|
|
631
|
+
default=[],
|
|
632
|
+
help="name=value by the spec's type (bool: true/false); repeat for several options; "
|
|
633
|
+
"window options also choose the synthetic input length",
|
|
634
|
+
)
|
|
635
|
+
p.add_argument(
|
|
636
|
+
"--subset",
|
|
637
|
+
action="append",
|
|
638
|
+
default=[],
|
|
639
|
+
help="axis=start:stop or axis=i,j,...; repeat for several axes",
|
|
640
|
+
)
|
|
641
|
+
p.add_argument(
|
|
642
|
+
"--stream",
|
|
643
|
+
action="store_true",
|
|
644
|
+
help="consume model.stream() chunk by chunk instead of predict()",
|
|
645
|
+
)
|
|
646
|
+
p.add_argument("--note", default="", help="text for the note column, e.g. the rule")
|
|
647
|
+
p.add_argument(
|
|
648
|
+
"--results",
|
|
649
|
+
help="results file (default: bench/results.md in a checkout; required otherwise)",
|
|
650
|
+
)
|
|
651
|
+
if name == "build":
|
|
652
|
+
p.add_argument("--output", help="folder for the SIF (default: store builds/<name>/)")
|
|
653
|
+
p.add_argument("--weights", help="folder holding a protected model's weight files")
|
|
654
|
+
p.add_argument(
|
|
655
|
+
"--device",
|
|
656
|
+
help="device for the precision check, and for the verify that follows the "
|
|
657
|
+
"build of a model with protected weights (default: from the spec)",
|
|
658
|
+
)
|
|
659
|
+
if name == "verify":
|
|
660
|
+
p.add_argument("--sif", help="SIF to verify (default: newest in store builds/<name>/)")
|
|
661
|
+
p.add_argument("--device", help="device such as cpu or cuda:0 (default: from the spec)")
|
|
662
|
+
if name == "publish":
|
|
663
|
+
p.add_argument("--sif", help="SIF to publish (default: newest in store builds/<name>/)")
|
|
664
|
+
p.add_argument("--catalog", help="catalogue file (default: catalog.toml in the repo)")
|
|
665
|
+
p.add_argument("--push", action="store_true", help="push to the model's registry")
|
|
666
|
+
p.add_argument(
|
|
667
|
+
"--dry-run", action="store_true", help="show publication without changes"
|
|
668
|
+
)
|
|
669
|
+
p.set_defaults(func=globals()[f"cmd_{name}"])
|
|
670
|
+
return parser
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def main(argv: list[str] | None = None) -> int:
|
|
674
|
+
args = build_parser().parse_args(argv)
|
|
675
|
+
return args.func(args)
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
if __name__ == "__main__":
|
|
679
|
+
sys.exit(main())
|