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,212 @@
1
+ """Fetch or locate a model's weight files and verify their sha256 (plan/DESIGN.md section 6).
2
+
3
+ The ``[weights]`` table of ``model.toml``::
4
+
5
+ [weights]
6
+ source = "huggingface" # "none", "url", "huggingface" or "protected"
7
+ repo = "EleutherAI/enformer-official-rough" # huggingface only
8
+ revision = "<40-hex commit>" # huggingface only: a commit, not a branch
9
+ dest = "/opt/modelpolis/weights" # optional; the default shown
10
+ files = [
11
+ { path = "pytorch_model.bin", sha256 = "<64 hex>" },
12
+ { path = "config.json", sha256 = "<64 hex>" },
13
+ ]
14
+
15
+ - ``none``: nothing is fetched or copied; ``files`` must be empty or absent.
16
+ - ``url``: each file has its own ``url`` (``https://``, ``http://`` or ``file://``).
17
+ - ``huggingface``: each file is downloaded from
18
+ ``https://huggingface.co/<repo>/resolve/<revision>/<path>``. A model whose files come from
19
+ several repositories (Borzoi's four replicates) gives a file its own ``repo`` and
20
+ ``revision``, which override the table's, and ``repo_path``, its path in that repository
21
+ (default: ``path``), so files of the same name land in different places::
22
+
23
+ files = [
24
+ { repo = "johahi/borzoi-replicate-0", revision = "<40-hex commit>",
25
+ path = "replicate-0/model.safetensors", repo_path = "model.safetensors", sha256 = "…" },
26
+ ]
27
+ - ``protected``: the files are read from the directory given with ``modelpolis build --weights``,
28
+ at ``<dir>/<path>``. If it is not given or a file is missing, the build stops with the text of
29
+ the model's ``WEIGHTS.md``.
30
+
31
+ Each file ends up in the image at ``<dest>/<path>``; ``path`` is relative and may not contain
32
+ ``..``. Downloaded files are kept in the build cache ``$MODELPOLIS_HOME/cache/weights/<sha256>``,
33
+ named by their expected sha256, and a cached file is reused only if its sha256 still matches.
34
+ A download goes to a temporary file in the same folder and is renamed only after its sha256
35
+ matches, so a mismatch leaves nothing in the cache. Every file is verified before
36
+ :func:`resolve_weights` returns.
37
+ """
38
+
39
+ import hashlib
40
+ import os
41
+ import re
42
+ import tempfile
43
+ import urllib.request
44
+ from dataclasses import dataclass
45
+ from pathlib import Path, PurePosixPath
46
+ from typing import Any
47
+
48
+ from .image import sha256_of as file_sha256
49
+ from .image import store_root
50
+
51
+ SOURCES = ("none", "url", "huggingface", "protected")
52
+ DEFAULT_DEST = "/opt/modelpolis/weights"
53
+ HF_URL = "https://huggingface.co/{repo}/resolve/{revision}/{path}"
54
+ SHA256 = re.compile(r"^[0-9a-f]{64}$")
55
+ COMMIT = re.compile(r"^[0-9a-f]{40}$")
56
+
57
+
58
+ class ChecksumError(ValueError):
59
+ """A weight file's sha256 differs from the one in ``model.toml``."""
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class WeightFile:
64
+ path: str # relative to dest in the image
65
+ sha256: str
66
+ url: str | None = None # None for a protected file
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class Weights:
71
+ source: str
72
+ dest: str
73
+ files: tuple[WeightFile, ...]
74
+
75
+
76
+ def cache_dir() -> Path:
77
+ """``$MODELPOLIS_HOME/cache/weights/``."""
78
+ return store_root() / "cache" / "weights"
79
+
80
+
81
+ def parse_weights(table: dict[str, Any]) -> Weights:
82
+ """Check a ``[weights]`` table and return it as :class:`Weights`."""
83
+ source = table.get("source", "none")
84
+ if source not in SOURCES:
85
+ raise ValueError(f"[weights]: source must be one of {', '.join(SOURCES)}, got {source!r}")
86
+ known = {"source", "dest", "files"} | (
87
+ {"repo", "revision"} if source == "huggingface" else set()
88
+ )
89
+ unknown = sorted(set(table) - known)
90
+ if unknown:
91
+ raise ValueError(f"[weights]: unknown keys for source {source!r}: {', '.join(unknown)}")
92
+ dest = table.get("dest", DEFAULT_DEST)
93
+ if not isinstance(dest, str) or not dest.startswith("/"):
94
+ raise ValueError(f"[weights]: dest must be an absolute path in the image, got {dest!r}")
95
+ entries = table.get("files", [])
96
+ if source == "none":
97
+ if entries:
98
+ raise ValueError('[weights]: source = "none" must not list files')
99
+ return Weights(source, dest, ())
100
+ if not entries:
101
+ raise ValueError(f"[weights]: source {source!r} needs at least one entry in files")
102
+ files, seen = [], set()
103
+ for entry in entries:
104
+ allowed = {"path", "sha256"} | {
105
+ "url": {"url"},
106
+ "huggingface": {"repo", "revision", "repo_path"},
107
+ }.get(source, set())
108
+ extra = sorted(set(entry) - allowed)
109
+ if extra:
110
+ raise ValueError(f"[weights]: unknown keys in a files entry: {', '.join(extra)}")
111
+ path, sha256 = entry.get("path"), str(entry.get("sha256", "")).lower()
112
+ parts = PurePosixPath(path or "").parts
113
+ if not path or path.startswith("/") or ".." in parts or "\\" in path:
114
+ raise ValueError(f"[weights]: path must be relative without '..', got {path!r}")
115
+ if path in seen:
116
+ raise ValueError(f"[weights]: {path!r} is listed twice")
117
+ seen.add(path)
118
+ if not SHA256.match(sha256):
119
+ raise ValueError(f"[weights]: {path}: sha256 must be 64 hex digits")
120
+ url = None
121
+ if source == "url":
122
+ url = entry.get("url")
123
+ if not url:
124
+ raise ValueError(f"[weights]: {path}: source = 'url' needs a url per file")
125
+ elif source == "huggingface":
126
+ url = _hf_url(table, entry, path)
127
+ files.append(WeightFile(path, sha256, url))
128
+ return Weights(source, dest, tuple(files))
129
+
130
+
131
+ def _hf_url(table: dict[str, Any], entry: dict[str, Any], path: str) -> str:
132
+ """The pinned download URL of one huggingface file; its own repo and revision win."""
133
+ repo = entry.get("repo", table.get("repo"))
134
+ revision = entry.get("revision", table.get("revision"))
135
+ if not repo:
136
+ raise ValueError(f'[weights]: {path}: source = "huggingface" needs repo')
137
+ if not isinstance(revision, str) or not COMMIT.match(revision):
138
+ raise ValueError(f"[weights]: {path}: revision must be a 40-hex commit, got {revision!r}")
139
+ repo_path = entry.get("repo_path", path)
140
+ if (
141
+ not isinstance(repo_path, str)
142
+ or repo_path.startswith("/")
143
+ or ".." in PurePosixPath(repo_path).parts
144
+ ):
145
+ raise ValueError(f"[weights]: {path}: repo_path must be relative without '..'")
146
+ return HF_URL.format(repo=repo, revision=revision, path=repo_path)
147
+
148
+
149
+ def _mismatch(name: str, expected: str, actual: str) -> ChecksumError:
150
+ return ChecksumError(f"weights: {name}: sha256 mismatch: expected {expected}, got {actual}")
151
+
152
+
153
+ def fetch(file: WeightFile) -> Path:
154
+ """The cached copy of a public file, downloaded first unless a matching copy is cached."""
155
+ folder = cache_dir()
156
+ target = folder / file.sha256
157
+ if target.is_file():
158
+ if file_sha256(target) == file.sha256:
159
+ return target
160
+ target.unlink() # a corrupted cache entry: download again
161
+ folder.mkdir(parents=True, exist_ok=True)
162
+ fd, tmp_name = tempfile.mkstemp(dir=folder, prefix=f".{file.sha256[:12]}.", suffix=".partial")
163
+ tmp = Path(tmp_name)
164
+ try:
165
+ h = hashlib.sha256()
166
+ with os.fdopen(fd, "wb") as out, urllib.request.urlopen(file.url) as response:
167
+ for block in iter(lambda: response.read(1 << 20), b""):
168
+ h.update(block)
169
+ out.write(block)
170
+ if h.hexdigest() != file.sha256:
171
+ raise _mismatch(f"{file.path} (from {file.url})", file.sha256, h.hexdigest())
172
+ tmp.replace(target)
173
+ finally:
174
+ tmp.unlink(missing_ok=True)
175
+ return target
176
+
177
+
178
+ def _weights_md(model_dir: Path) -> str:
179
+ md = model_dir / "WEIGHTS.md"
180
+ return md.read_text() if md.is_file() else f"(no WEIGHTS.md in {model_dir})"
181
+
182
+
183
+ def locate(file: WeightFile, weights_dir: Path | None, model_dir: Path) -> Path:
184
+ """A protected file at ``<weights_dir>/<path>``, verified."""
185
+ if weights_dir is None:
186
+ raise FileNotFoundError(
187
+ "weights: this model's weights are protected; pass --weights <dir>.\n\n"
188
+ + _weights_md(model_dir)
189
+ )
190
+ path = Path(weights_dir).expanduser() / file.path
191
+ if not path.is_file():
192
+ raise FileNotFoundError(f"weights: {path} not found.\n\n" + _weights_md(model_dir))
193
+ actual = file_sha256(path)
194
+ if actual != file.sha256:
195
+ raise _mismatch(str(path), file.sha256, actual)
196
+ return path.resolve()
197
+
198
+
199
+ def resolve_weights(
200
+ table: dict[str, Any], model_dir: Path, weights_dir: str | Path | None = None
201
+ ) -> list[tuple[Path, str]]:
202
+ """Every weight file as ``(verified host path, path in the image)``; empty for ``none``."""
203
+ weights = parse_weights(table)
204
+ pairs = []
205
+ for f in weights.files:
206
+ host = (
207
+ locate(f, Path(weights_dir) if weights_dir else None, Path(model_dir))
208
+ if weights.source == "protected"
209
+ else fetch(f)
210
+ )
211
+ pairs.append((host, str(PurePosixPath(weights.dest) / f.path)))
212
+ return pairs