emeans-haystack 0.1.2__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.
- emeans_haystack-0.1.2.dist-info/METADATA +162 -0
- emeans_haystack-0.1.2.dist-info/RECORD +14 -0
- emeans_haystack-0.1.2.dist-info/WHEEL +4 -0
- emeans_haystack-0.1.2.dist-info/licenses/LICENSE.txt +202 -0
- haystack_integrations/components/preprocessors/emeans/__init__.py +8 -0
- haystack_integrations/components/preprocessors/emeans/_backend.py +1183 -0
- haystack_integrations/components/preprocessors/emeans/_model.py +337 -0
- haystack_integrations/components/preprocessors/emeans/_utils.py +181 -0
- haystack_integrations/components/preprocessors/emeans/clusterer.py +223 -0
- haystack_integrations/components/preprocessors/emeans/fitter.py +298 -0
- haystack_integrations/components/preprocessors/py.typed +0 -0
- haystack_integrations/components/rankers/emeans/__init__.py +7 -0
- haystack_integrations/components/rankers/emeans/ranker.py +166 -0
- haystack_integrations/components/rankers/py.typed +0 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ogaude <ogaude.code@proton.me>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import secrets
|
|
10
|
+
import zipfile
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
FORMAT_VERSION = 1
|
|
20
|
+
|
|
21
|
+
METADATA_KEYS: tuple[str, ...] = (
|
|
22
|
+
"format_version",
|
|
23
|
+
"k",
|
|
24
|
+
"d",
|
|
25
|
+
"spherical",
|
|
26
|
+
"centroids_sha256",
|
|
27
|
+
"created_at",
|
|
28
|
+
"n_train",
|
|
29
|
+
"seed",
|
|
30
|
+
"nepochs",
|
|
31
|
+
"backend",
|
|
32
|
+
"assignment_backend",
|
|
33
|
+
"precision_used",
|
|
34
|
+
"emeans_source",
|
|
35
|
+
"faiss_version",
|
|
36
|
+
"emeans_haystack_version",
|
|
37
|
+
"recipe",
|
|
38
|
+
)
|
|
39
|
+
_COMPUTED_KEYS = ("format_version", "k", "d", "centroids_sha256", "created_at", "emeans_haystack_version")
|
|
40
|
+
_REQUIRED_KEYS = ("format_version", "k", "d", "spherical", "centroids_sha256")
|
|
41
|
+
UNIT_NORM_TOLERANCE = 1e-3
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class EmeansModel:
|
|
46
|
+
"""A loaded model file: centroids plus the metadata stored with them."""
|
|
47
|
+
|
|
48
|
+
path: str
|
|
49
|
+
centroids: np.ndarray
|
|
50
|
+
metadata: dict[str, Any]
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def k(self) -> int:
|
|
54
|
+
"""Number of clusters."""
|
|
55
|
+
return int(self.centroids.shape[0])
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def d(self) -> int:
|
|
59
|
+
"""Embedding dimension."""
|
|
60
|
+
return int(self.centroids.shape[1])
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def spherical(self) -> bool:
|
|
64
|
+
"""Whether the model clusters by cosine similarity."""
|
|
65
|
+
return self.metadata["spherical"] is True
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ModelCache:
|
|
69
|
+
"""
|
|
70
|
+
Remembers the last model loaded and reloads it only when the path or the file changes.
|
|
71
|
+
|
|
72
|
+
A file counts as changed when its device, inode, size or modification time differ. `save_model` always writes
|
|
73
|
+
a new inode, so every rewrite by this package is detected even when the modification time is unchanged
|
|
74
|
+
(coarse filesystem timestamps, `cp -p`, restored backups).
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self) -> None:
|
|
78
|
+
"""Create an empty cache."""
|
|
79
|
+
self._key: tuple[str, int, int, int, int] | None = None
|
|
80
|
+
self._model: EmeansModel | None = None
|
|
81
|
+
|
|
82
|
+
def get(self, path: str, loader: Callable[[str], EmeansModel]) -> EmeansModel:
|
|
83
|
+
"""
|
|
84
|
+
Return the model at `path`, calling `loader(path)` unless the cached model comes from the same file.
|
|
85
|
+
|
|
86
|
+
:param path: Path of the model file.
|
|
87
|
+
:param loader: Function that loads a model file, normally `load_model`.
|
|
88
|
+
"""
|
|
89
|
+
try:
|
|
90
|
+
st = os.stat(path)
|
|
91
|
+
key: tuple[str, int, int, int, int] | None = (
|
|
92
|
+
os.path.abspath(path),
|
|
93
|
+
st.st_dev,
|
|
94
|
+
st.st_ino,
|
|
95
|
+
st.st_size,
|
|
96
|
+
st.st_mtime_ns,
|
|
97
|
+
)
|
|
98
|
+
except OSError:
|
|
99
|
+
key = None # the loader reports the missing or unreadable file
|
|
100
|
+
if self._model is None or key is None or key != self._key:
|
|
101
|
+
self._model = loader(path)
|
|
102
|
+
self._key = key
|
|
103
|
+
return self._model
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def model_checksum(centroids: np.ndarray, *, spherical: bool) -> str:
|
|
107
|
+
"""
|
|
108
|
+
Return the checksum stored as `centroids_sha256`.
|
|
109
|
+
|
|
110
|
+
Definition (model format version 1): the lowercase hex SHA-256 of the ASCII header
|
|
111
|
+
`spherical=<1|0>;k=<k>;d=<d>;` immediately followed by the centroid values as float32 in C (row-major)
|
|
112
|
+
order. The header binds the clustering mode and the shape to the centroid bytes, so editing `spherical`,
|
|
113
|
+
`k` or `d` in the metadata is detected like editing a centroid value.
|
|
114
|
+
|
|
115
|
+
:param centroids: float32 centroids of shape `(k, d)`.
|
|
116
|
+
:param spherical: Whether the model clusters by cosine similarity.
|
|
117
|
+
"""
|
|
118
|
+
k, d = centroids.shape
|
|
119
|
+
header = f"spherical={int(spherical)};k={int(k)};d={int(d)};".encode("ascii")
|
|
120
|
+
body = np.ascontiguousarray(centroids, dtype=np.float32).tobytes(order="C")
|
|
121
|
+
return hashlib.sha256(header + body).hexdigest()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def save_model(path: str, centroids: np.ndarray, metadata: dict[str, Any], *, overwrite: bool) -> None:
|
|
125
|
+
"""
|
|
126
|
+
Write a model file atomically.
|
|
127
|
+
|
|
128
|
+
The data goes to a temporary file in the target directory first, so a crash never leaves a partial model.
|
|
129
|
+
|
|
130
|
+
:param path: Target `.npz` path.
|
|
131
|
+
:param centroids: Centroids of shape `(k, d)`; stored as float32.
|
|
132
|
+
:param metadata: The caller-supplied metadata keys; format version, `k`, `d`, checksum, creation time and package
|
|
133
|
+
version are added here.
|
|
134
|
+
:param overwrite: If `False`, an existing file at `path` raises `FileExistsError`.
|
|
135
|
+
:raises ValueError: If `metadata` does not have exactly the expected keys, or `spherical` is not a bool.
|
|
136
|
+
"""
|
|
137
|
+
expected_keys = set(METADATA_KEYS) - set(_COMPUTED_KEYS)
|
|
138
|
+
if set(metadata) != expected_keys:
|
|
139
|
+
msg = (
|
|
140
|
+
f"metadata keys must be exactly {sorted(expected_keys)}; "
|
|
141
|
+
f"missing {sorted(expected_keys - set(metadata))}, unexpected {sorted(set(metadata) - expected_keys)}"
|
|
142
|
+
)
|
|
143
|
+
raise ValueError(msg)
|
|
144
|
+
if not isinstance(metadata["spherical"], bool):
|
|
145
|
+
msg = f"metadata spherical must be True or False, got {metadata['spherical']!r}"
|
|
146
|
+
raise ValueError(msg)
|
|
147
|
+
c = np.ascontiguousarray(centroids, dtype=np.float32)
|
|
148
|
+
meta: dict[str, Any] = {
|
|
149
|
+
**metadata,
|
|
150
|
+
"format_version": FORMAT_VERSION,
|
|
151
|
+
"k": int(c.shape[0]),
|
|
152
|
+
"d": int(c.shape[1]),
|
|
153
|
+
"centroids_sha256": model_checksum(c, spherical=metadata["spherical"]),
|
|
154
|
+
"created_at": datetime.now(UTC).isoformat(),
|
|
155
|
+
"emeans_haystack_version": _package_version(),
|
|
156
|
+
}
|
|
157
|
+
parent = os.path.dirname(os.path.abspath(path))
|
|
158
|
+
tmp_path = ""
|
|
159
|
+
try:
|
|
160
|
+
fd, tmp_path = _create_temp(parent, os.path.basename(path))
|
|
161
|
+
with os.fdopen(fd, "wb") as tmp:
|
|
162
|
+
np.savez(tmp, centroids=c, metadata=np.array(json.dumps(meta, sort_keys=True, default=_json_default)))
|
|
163
|
+
tmp.flush()
|
|
164
|
+
os.fsync(tmp.fileno())
|
|
165
|
+
if overwrite:
|
|
166
|
+
os.replace(tmp_path, path)
|
|
167
|
+
else:
|
|
168
|
+
_create_exclusive(tmp_path, path)
|
|
169
|
+
finally:
|
|
170
|
+
if tmp_path:
|
|
171
|
+
with contextlib.suppress(FileNotFoundError):
|
|
172
|
+
os.unlink(tmp_path)
|
|
173
|
+
_fsync_directory(parent)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _fsync_directory(directory: str) -> None:
|
|
177
|
+
"""Make the new directory entry durable, so a power loss after return cannot lose the model (POSIX only)."""
|
|
178
|
+
if os.name != "posix":
|
|
179
|
+
return
|
|
180
|
+
try:
|
|
181
|
+
fd = os.open(directory, os.O_RDONLY)
|
|
182
|
+
except OSError:
|
|
183
|
+
return
|
|
184
|
+
try:
|
|
185
|
+
os.fsync(fd)
|
|
186
|
+
except OSError:
|
|
187
|
+
pass # some filesystems do not support fsync on a directory; the rename is still atomic
|
|
188
|
+
finally:
|
|
189
|
+
os.close(fd)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _package_version() -> str:
|
|
193
|
+
try:
|
|
194
|
+
return version("emeans-haystack")
|
|
195
|
+
except PackageNotFoundError:
|
|
196
|
+
return "unknown"
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _create_temp(parent: str, name: str) -> tuple[int, str]:
|
|
200
|
+
"""
|
|
201
|
+
Create a new temporary file next to the target and return its descriptor and path.
|
|
202
|
+
|
|
203
|
+
The file is opened with mode `0o666` so that the kernel applies the process umask, as for any normal file.
|
|
204
|
+
Reading the umask with `os.umask` would change it for every thread of the process for a moment.
|
|
205
|
+
"""
|
|
206
|
+
for _ in range(100):
|
|
207
|
+
tmp_path = os.path.join(parent, f".{name}.{secrets.token_hex(8)}.tmp")
|
|
208
|
+
try:
|
|
209
|
+
return os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666), tmp_path
|
|
210
|
+
except FileExistsError:
|
|
211
|
+
continue
|
|
212
|
+
msg = f"could not create a temporary file in {parent}"
|
|
213
|
+
raise FileExistsError(msg)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _create_exclusive(tmp_path: str, path: str) -> None:
|
|
217
|
+
try:
|
|
218
|
+
os.link(tmp_path, path)
|
|
219
|
+
except FileExistsError:
|
|
220
|
+
raise
|
|
221
|
+
except OSError:
|
|
222
|
+
# Hard links are not supported on this filesystem: fall back to a plain existence check.
|
|
223
|
+
if os.path.exists(path):
|
|
224
|
+
raise FileExistsError(path) from None
|
|
225
|
+
os.replace(tmp_path, path)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _json_default(value: object) -> Any:
|
|
229
|
+
if isinstance(value, np.integer):
|
|
230
|
+
return int(value)
|
|
231
|
+
if isinstance(value, np.floating):
|
|
232
|
+
return float(value)
|
|
233
|
+
if isinstance(value, np.ndarray):
|
|
234
|
+
return value.tolist()
|
|
235
|
+
msg = f"Object of type {type(value).__name__} is not JSON serializable"
|
|
236
|
+
raise TypeError(msg)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def load_model(path: str) -> EmeansModel:
|
|
240
|
+
"""
|
|
241
|
+
Read a model file written by `save_model` and validate it.
|
|
242
|
+
|
|
243
|
+
Loading never unpickles anything, so a model file cannot run code. The checks run in this order: `file`,
|
|
244
|
+
`arrays`, `format_version`, `metadata`, `shape`, `finite`, `unit_norm`, `checksum`.
|
|
245
|
+
|
|
246
|
+
:param path: Path of the `.npz` model file.
|
|
247
|
+
:raises FileNotFoundError: If the file does not exist.
|
|
248
|
+
:raises ValueError: If the file is not a valid, supported model; the message names the file and the failed check.
|
|
249
|
+
"""
|
|
250
|
+
if not os.path.exists(path):
|
|
251
|
+
msg = f"Model file not found: {path}"
|
|
252
|
+
raise FileNotFoundError(msg)
|
|
253
|
+
if not os.path.isfile(path):
|
|
254
|
+
raise _invalid(path, "file", "not a regular file")
|
|
255
|
+
centroids, metadata = _read_arrays(path)
|
|
256
|
+
_check_format_version(path, metadata)
|
|
257
|
+
_check_metadata_types(path, metadata)
|
|
258
|
+
_check_shape(path, centroids, metadata)
|
|
259
|
+
if not np.isfinite(centroids).all():
|
|
260
|
+
raise _invalid(path, "finite", "centroids contain NaN or infinite values")
|
|
261
|
+
if metadata["spherical"]:
|
|
262
|
+
norms = np.linalg.norm(centroids.astype(np.float64), axis=1)
|
|
263
|
+
bad = int(np.count_nonzero(np.abs(norms - 1.0) > UNIT_NORM_TOLERANCE))
|
|
264
|
+
if bad:
|
|
265
|
+
raise _invalid(path, "unit_norm", f"{bad} centroid rows of a spherical model do not have unit norm")
|
|
266
|
+
if model_checksum(centroids, spherical=metadata["spherical"]) != metadata["centroids_sha256"]:
|
|
267
|
+
detail = "centroids, spherical, k or d do not match centroids_sha256; the file is corrupt or modified"
|
|
268
|
+
raise _invalid(path, "checksum", detail)
|
|
269
|
+
return EmeansModel(path=str(path), centroids=centroids, metadata=metadata)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _invalid(path: str, check: str, detail: str) -> ValueError:
|
|
273
|
+
return ValueError(f"{path}: {check} check failed: {detail}")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _read_arrays(path: str) -> tuple[np.ndarray, dict[str, Any]]:
|
|
277
|
+
try:
|
|
278
|
+
loaded = np.load(path, allow_pickle=False)
|
|
279
|
+
except (ValueError, EOFError, zipfile.BadZipFile, KeyError, OSError) as e:
|
|
280
|
+
raise _invalid(path, "arrays", f"cannot read as an .npz archive ({e})") from e
|
|
281
|
+
if not isinstance(loaded, np.lib.npyio.NpzFile):
|
|
282
|
+
raise _invalid(path, "arrays", "not an .npz archive")
|
|
283
|
+
with loaded as z:
|
|
284
|
+
if set(z.files) != {"centroids", "metadata"}:
|
|
285
|
+
raise _invalid(path, "arrays", f"expected arrays centroids and metadata, found {sorted(z.files)}")
|
|
286
|
+
try:
|
|
287
|
+
centroids = np.array(z["centroids"])
|
|
288
|
+
raw = z["metadata"]
|
|
289
|
+
except (ValueError, EOFError, zipfile.BadZipFile, KeyError, OSError) as e:
|
|
290
|
+
raise _invalid(path, "arrays", f"cannot read arrays ({e})") from e
|
|
291
|
+
if raw.ndim != 0 or raw.dtype.kind != "U":
|
|
292
|
+
raise _invalid(path, "arrays", "metadata is not a 0-d string array")
|
|
293
|
+
try:
|
|
294
|
+
metadata = json.loads(str(raw))
|
|
295
|
+
except ValueError as e:
|
|
296
|
+
raise _invalid(path, "arrays", f"metadata is not valid JSON ({e})") from e
|
|
297
|
+
if not isinstance(metadata, dict):
|
|
298
|
+
raise _invalid(path, "arrays", "metadata is not a JSON object")
|
|
299
|
+
missing = [key for key in _REQUIRED_KEYS if key not in metadata]
|
|
300
|
+
if missing:
|
|
301
|
+
raise _invalid(path, "arrays", f"metadata lacks keys {missing}")
|
|
302
|
+
return centroids, metadata
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _check_format_version(path: str, metadata: dict[str, Any]) -> None:
|
|
306
|
+
version = metadata["format_version"]
|
|
307
|
+
if isinstance(version, bool) or not isinstance(version, int):
|
|
308
|
+
raise _invalid(path, "format_version", f"format_version must be an integer, got {version!r}")
|
|
309
|
+
if version > FORMAT_VERSION:
|
|
310
|
+
raise _invalid(
|
|
311
|
+
path,
|
|
312
|
+
"format_version",
|
|
313
|
+
f"model format_version {version} is newer than supported version {FORMAT_VERSION}; upgrade emeans-haystack",
|
|
314
|
+
)
|
|
315
|
+
if version < 1:
|
|
316
|
+
raise _invalid(path, "format_version", f"unsupported format_version {version}")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _check_metadata_types(path: str, metadata: dict[str, Any]) -> None:
|
|
320
|
+
# A truthy string such as "false" must never select the spherical geometry, nor a falsy one the Euclidean.
|
|
321
|
+
spherical = metadata["spherical"]
|
|
322
|
+
if not isinstance(spherical, bool):
|
|
323
|
+
raise _invalid(path, "metadata", f"metadata spherical must be true or false, got {spherical!r}")
|
|
324
|
+
checksum = metadata["centroids_sha256"]
|
|
325
|
+
if not isinstance(checksum, str):
|
|
326
|
+
raise _invalid(path, "metadata", f"metadata centroids_sha256 must be a string, got {checksum!r}")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _check_shape(path: str, centroids: np.ndarray, metadata: dict[str, Any]) -> None:
|
|
330
|
+
k, d = metadata["k"], metadata["d"]
|
|
331
|
+
for name, value in (("k", k), ("d", d)):
|
|
332
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
|
333
|
+
raise _invalid(path, "shape", f"metadata {name} must be a positive integer, got {value!r}")
|
|
334
|
+
if centroids.dtype != np.float32:
|
|
335
|
+
raise _invalid(path, "shape", f"centroids must be float32, got {centroids.dtype}")
|
|
336
|
+
if centroids.ndim != 2 or centroids.shape != (k, d): # noqa: PLR2004
|
|
337
|
+
raise _invalid(path, "shape", f"centroids have shape {centroids.shape}, metadata says ({k}, {d})")
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ogaude <ogaude.code@proton.me>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import numbers
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from haystack import Document
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def check_positive_int(name: str, value: object, *, allow_none: bool = False) -> None:
|
|
14
|
+
"""
|
|
15
|
+
Raise `ValueError` unless `value` is an integer of at least 1 (or `None` when allowed).
|
|
16
|
+
|
|
17
|
+
Python and NumPy integers are accepted; booleans are rejected even though they are integers in Python. Callers
|
|
18
|
+
store `int(value)` so that NumPy integers never reach serialisation.
|
|
19
|
+
|
|
20
|
+
:param name: Parameter name used in the error message.
|
|
21
|
+
:param value: Value to check.
|
|
22
|
+
:param allow_none: Whether `None` is an accepted value.
|
|
23
|
+
"""
|
|
24
|
+
if value is None and allow_none:
|
|
25
|
+
return
|
|
26
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Integral) or int(value) < 1:
|
|
27
|
+
msg = f"{name} must be a positive integer{' or None' if allow_none else ''}, got {value!r}"
|
|
28
|
+
raise ValueError(msg)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def optional_int(value: int | None) -> int | None:
|
|
32
|
+
"""Return `value` as a plain Python `int` (NumPy integers included), or `None` unchanged."""
|
|
33
|
+
return None if value is None else int(value)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def check_bool(name: str, value: object) -> None:
|
|
37
|
+
"""
|
|
38
|
+
Raise `ValueError` unless `value` is `True` or `False`.
|
|
39
|
+
|
|
40
|
+
Truthy strings such as `"no"` are rejected rather than silently read as `True`.
|
|
41
|
+
|
|
42
|
+
:param name: Parameter name used in the error message.
|
|
43
|
+
:param value: Value to check.
|
|
44
|
+
"""
|
|
45
|
+
if not isinstance(value, bool):
|
|
46
|
+
msg = f"{name} must be True or False, got {value!r}"
|
|
47
|
+
raise ValueError(msg)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def check_integer(name: str, value: object) -> None:
|
|
51
|
+
"""
|
|
52
|
+
Raise `ValueError` unless `value` is an integer (booleans are rejected).
|
|
53
|
+
|
|
54
|
+
:param name: Parameter name used in the error message.
|
|
55
|
+
:param value: Value to check.
|
|
56
|
+
"""
|
|
57
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Integral):
|
|
58
|
+
msg = f"{name} must be an integer, got {value!r}"
|
|
59
|
+
raise ValueError(msg)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def check_threshold(name: str, value: object) -> None:
|
|
63
|
+
"""
|
|
64
|
+
Raise `ValueError` unless `value` is a real number that is not NaN; infinity is allowed.
|
|
65
|
+
|
|
66
|
+
:param name: Parameter name used in the error message.
|
|
67
|
+
:param value: Value to check.
|
|
68
|
+
"""
|
|
69
|
+
if isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Real) or math.isnan(value):
|
|
70
|
+
msg = f"{name} must be a number, got {value!r}"
|
|
71
|
+
raise ValueError(msg)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def check_nepochs(value: object) -> None:
|
|
75
|
+
"""
|
|
76
|
+
Raise `ValueError` unless `value` is a finite real number greater than 0.
|
|
77
|
+
|
|
78
|
+
:param value: Value to check.
|
|
79
|
+
"""
|
|
80
|
+
if (
|
|
81
|
+
isinstance(value, (bool, np.bool_))
|
|
82
|
+
or not isinstance(value, numbers.Real)
|
|
83
|
+
or not math.isfinite(value)
|
|
84
|
+
or not float(value) > 0
|
|
85
|
+
):
|
|
86
|
+
msg = f"nepochs must be a finite number greater than 0, got {value!r}"
|
|
87
|
+
raise ValueError(msg)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def resolve_k(n_usable: int, k: int | None, target_cluster_size: int | None) -> int:
|
|
91
|
+
"""
|
|
92
|
+
Return the number of clusters to fit.
|
|
93
|
+
|
|
94
|
+
An explicit `k` is returned as is. Otherwise `k = max(1, min(round(n / target_cluster_size), n))`.
|
|
95
|
+
|
|
96
|
+
:param n_usable: Number of documents with an embedding.
|
|
97
|
+
:param k: Explicit number of clusters, or `None`.
|
|
98
|
+
:param target_cluster_size: Average number of documents per cluster, used when `k` is `None`.
|
|
99
|
+
"""
|
|
100
|
+
if k is not None:
|
|
101
|
+
return k
|
|
102
|
+
if target_cluster_size is None:
|
|
103
|
+
msg = "Either k or target_cluster_size must be set"
|
|
104
|
+
raise ValueError(msg)
|
|
105
|
+
return max(1, min(round(n_usable / target_cluster_size), n_usable))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def extract_embeddings(
|
|
109
|
+
documents: Sequence[Document], *, expected_dim: int | None = None
|
|
110
|
+
) -> tuple[list[int], np.ndarray]:
|
|
111
|
+
"""
|
|
112
|
+
Collect the embeddings of the documents that have one into a new float32 matrix.
|
|
113
|
+
|
|
114
|
+
:param documents: Input documents.
|
|
115
|
+
:param expected_dim: If given, every embedding must have this dimension.
|
|
116
|
+
:returns: The positions of the documents that have an embedding, and a C-contiguous float32 array of
|
|
117
|
+
shape `(m, d)` holding their embeddings.
|
|
118
|
+
:raises ValueError: On mixed or unexpected dimensions, or on NaN or infinite values.
|
|
119
|
+
"""
|
|
120
|
+
positions: list[int] = []
|
|
121
|
+
rows: list[Sequence[float]] = []
|
|
122
|
+
dim: int | None = expected_dim
|
|
123
|
+
first_dim: int | None = None
|
|
124
|
+
for pos, doc in enumerate(documents):
|
|
125
|
+
embedding = doc.embedding
|
|
126
|
+
if embedding is None:
|
|
127
|
+
continue
|
|
128
|
+
length = len(embedding)
|
|
129
|
+
if first_dim is None:
|
|
130
|
+
first_dim = length
|
|
131
|
+
elif length != first_dim:
|
|
132
|
+
msg = (
|
|
133
|
+
f"Embedding dimension mismatch: document {doc.id} has dimension {length}, "
|
|
134
|
+
f"but other documents have dimension {first_dim}"
|
|
135
|
+
)
|
|
136
|
+
raise ValueError(msg)
|
|
137
|
+
if expected_dim is not None and length != expected_dim:
|
|
138
|
+
msg = f"Embedding dimension mismatch: document {doc.id} has dimension {length}, expected {expected_dim}"
|
|
139
|
+
raise ValueError(msg)
|
|
140
|
+
positions.append(pos)
|
|
141
|
+
rows.append(embedding)
|
|
142
|
+
|
|
143
|
+
if not rows:
|
|
144
|
+
return positions, np.zeros((0, dim or 0), dtype=np.float32)
|
|
145
|
+
|
|
146
|
+
x64 = np.asarray(rows, dtype=np.float64)
|
|
147
|
+
_check_finite(x64, documents, positions, "contains NaN or infinite values")
|
|
148
|
+
with np.errstate(over="ignore"): # overflow is reported below with its own message
|
|
149
|
+
x32 = np.ascontiguousarray(x64.astype(np.float32))
|
|
150
|
+
_check_finite(x32, documents, positions, "has values outside the float32 range")
|
|
151
|
+
return positions, x32
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _check_finite(x: np.ndarray, documents: Sequence[Document], positions: list[int], problem: str) -> None:
|
|
155
|
+
bad_rows = np.flatnonzero(~np.isfinite(x).all(axis=1))
|
|
156
|
+
if bad_rows.size:
|
|
157
|
+
doc_id = documents[positions[int(bad_rows[0])]].id
|
|
158
|
+
msg = f"Embedding of document {doc_id} {problem}"
|
|
159
|
+
raise ValueError(msg)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def normalize_rows(x: np.ndarray, doc_ids: Sequence[str]) -> np.ndarray:
|
|
163
|
+
"""
|
|
164
|
+
Return a new float32 array whose rows have unit L2 norm.
|
|
165
|
+
|
|
166
|
+
Each row is first divided by its largest absolute value so that very large or very small values do not
|
|
167
|
+
overflow or underflow in the norm.
|
|
168
|
+
|
|
169
|
+
:param x: Matrix of shape `(m, d)`. It is not modified.
|
|
170
|
+
:param doc_ids: Document id of every row, used in error messages.
|
|
171
|
+
:raises ValueError: If a row is all zeros.
|
|
172
|
+
"""
|
|
173
|
+
x64 = np.asarray(x, dtype=np.float64)
|
|
174
|
+
scale = np.abs(x64).max(axis=1) if x64.shape[1] else np.zeros(x64.shape[0])
|
|
175
|
+
zero_rows = np.flatnonzero(scale == 0)
|
|
176
|
+
if zero_rows.size:
|
|
177
|
+
msg = f"Document {doc_ids[int(zero_rows[0])]} has a zero embedding, which cannot be used with spherical=True"
|
|
178
|
+
raise ValueError(msg)
|
|
179
|
+
scaled = x64 / scale[:, None]
|
|
180
|
+
scaled /= np.linalg.norm(scaled, axis=1, keepdims=True)
|
|
181
|
+
return np.ascontiguousarray(scaled.astype(np.float32))
|