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,223 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ogaude <ogaude.code@proton.me>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from typing import Any, Literal
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from haystack import Document, component, default_from_dict, default_to_dict, logging
|
|
11
|
+
|
|
12
|
+
from haystack_integrations.components.preprocessors.emeans._backend import DEVICES, assigner_for, select_backend
|
|
13
|
+
from haystack_integrations.components.preprocessors.emeans._model import EmeansModel, ModelCache, load_model
|
|
14
|
+
from haystack_integrations.components.preprocessors.emeans._utils import (
|
|
15
|
+
check_bool,
|
|
16
|
+
check_positive_int,
|
|
17
|
+
check_threshold,
|
|
18
|
+
extract_embeddings,
|
|
19
|
+
normalize_rows,
|
|
20
|
+
)
|
|
21
|
+
from haystack_integrations.components.preprocessors.emeans.fitter import EmeansFitter
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@component
|
|
27
|
+
class EmeansDocumentClusterer:
|
|
28
|
+
"""
|
|
29
|
+
Assigns each document to the nearest centroid of a saved e-means model.
|
|
30
|
+
|
|
31
|
+
Every output document with an embedding gets `meta["cluster_id"]`, an `int` in `[0, k)`.
|
|
32
|
+
|
|
33
|
+
### Usage example
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from haystack_integrations.components.preprocessors.emeans import EmeansDocumentClusterer
|
|
37
|
+
|
|
38
|
+
clusterer = EmeansDocumentClusterer(model_path="clusters.npz")
|
|
39
|
+
clustered = clusterer.run(documents=documents_with_embeddings)["documents"]
|
|
40
|
+
print(clustered[0].meta["cluster_id"])
|
|
41
|
+
```
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
model_path: str | None = None,
|
|
47
|
+
return_distance: bool = False,
|
|
48
|
+
batch_size: int = 65536,
|
|
49
|
+
device: Literal["auto", "cpu", "cuda"] = "auto",
|
|
50
|
+
gpu_threshold: float = 1e10,
|
|
51
|
+
fit_if_missing: bool = False,
|
|
52
|
+
fit_params: dict[str, Any] | None = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
"""
|
|
55
|
+
Create an EmeansDocumentClusterer.
|
|
56
|
+
|
|
57
|
+
:param model_path: Model to load. May instead (or also) come from the `model_path` run input, which wins.
|
|
58
|
+
:param return_distance: Also write the distance (Euclidean model) or cosine similarity (spherical model)
|
|
59
|
+
to the assigned centroid.
|
|
60
|
+
:param batch_size: Documents assigned per chunk. Affects memory only, not results.
|
|
61
|
+
:param device: `"cpu"`, `"cuda"` or `"auto"`.
|
|
62
|
+
:param gpu_threshold: With `device="auto"`, a GPU is used only when `n * k` is at least this value.
|
|
63
|
+
:param fit_if_missing: Fit a model on this run's documents when no file exists at the model path.
|
|
64
|
+
:param fit_params: Fitter parameters used when `fit_if_missing` is set, except `model_path`.
|
|
65
|
+
"""
|
|
66
|
+
check_positive_int("batch_size", batch_size)
|
|
67
|
+
check_bool("return_distance", return_distance)
|
|
68
|
+
check_bool("fit_if_missing", fit_if_missing)
|
|
69
|
+
check_threshold("gpu_threshold", gpu_threshold)
|
|
70
|
+
if device not in DEVICES:
|
|
71
|
+
msg = f"device must be 'auto', 'cpu' or 'cuda', got {device!r}"
|
|
72
|
+
raise ValueError(msg)
|
|
73
|
+
if fit_if_missing:
|
|
74
|
+
self._validate_fit_params(fit_params)
|
|
75
|
+
self.model_path = model_path
|
|
76
|
+
self.return_distance = return_distance
|
|
77
|
+
self.batch_size = int(batch_size)
|
|
78
|
+
self.device = device
|
|
79
|
+
self.gpu_threshold = gpu_threshold
|
|
80
|
+
self.fit_if_missing = fit_if_missing
|
|
81
|
+
self.fit_params = fit_params
|
|
82
|
+
self._models = ModelCache()
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def _validate_fit_params(fit_params: dict[str, Any] | None) -> None:
|
|
86
|
+
if not isinstance(fit_params, dict) or not fit_params:
|
|
87
|
+
msg = f"fit_params must be a non-empty dict when fit_if_missing=True, got {fit_params!r}"
|
|
88
|
+
raise ValueError(msg)
|
|
89
|
+
params = fit_params
|
|
90
|
+
forbidden = sorted({"model_path", "overwrite"} & params.keys())
|
|
91
|
+
if forbidden:
|
|
92
|
+
msg = f"fit_params must not contain {forbidden}: the model path is the clusterer's and it never overwrites"
|
|
93
|
+
raise ValueError(msg)
|
|
94
|
+
try:
|
|
95
|
+
# The fitter constructor only validates; it does no file access.
|
|
96
|
+
EmeansFitter(model_path="<fit_if_missing>", **params)
|
|
97
|
+
except TypeError as e:
|
|
98
|
+
msg = f"fit_params is not a valid fitter configuration: {e}"
|
|
99
|
+
raise ValueError(msg) from e
|
|
100
|
+
|
|
101
|
+
def to_dict(self) -> dict[str, Any]:
|
|
102
|
+
"""
|
|
103
|
+
Serialize the component to a dictionary.
|
|
104
|
+
|
|
105
|
+
:returns: Dictionary with all init parameters.
|
|
106
|
+
"""
|
|
107
|
+
return default_to_dict(
|
|
108
|
+
self,
|
|
109
|
+
model_path=self.model_path,
|
|
110
|
+
return_distance=self.return_distance,
|
|
111
|
+
batch_size=self.batch_size,
|
|
112
|
+
device=self.device,
|
|
113
|
+
gpu_threshold=self.gpu_threshold,
|
|
114
|
+
fit_if_missing=self.fit_if_missing,
|
|
115
|
+
fit_params=self.fit_params,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def from_dict(cls, data: dict[str, Any]) -> "EmeansDocumentClusterer":
|
|
120
|
+
"""
|
|
121
|
+
Deserialize the component from a dictionary.
|
|
122
|
+
|
|
123
|
+
:param data: Dictionary produced by `to_dict`.
|
|
124
|
+
:returns: The deserialized component.
|
|
125
|
+
"""
|
|
126
|
+
return default_from_dict(cls, data)
|
|
127
|
+
|
|
128
|
+
def warm_up(self) -> None:
|
|
129
|
+
"""Load the model for the init `model_path`, if one is set and available."""
|
|
130
|
+
if self.model_path is None:
|
|
131
|
+
return
|
|
132
|
+
if os.path.exists(self.model_path) or not self.fit_if_missing:
|
|
133
|
+
self._ensure_model(self.model_path)
|
|
134
|
+
|
|
135
|
+
def _ensure_model(self, path: str, documents: list[Document] | None = None) -> tuple[EmeansModel, bool]:
|
|
136
|
+
"""Load the model, auto-fitting it first when allowed; also return whether the fit chose the backend."""
|
|
137
|
+
warned = False
|
|
138
|
+
if documents is not None and self.fit_if_missing and not os.path.exists(path):
|
|
139
|
+
warned = self._auto_fit(path, documents)
|
|
140
|
+
return self._models.get(path, load_model), warned
|
|
141
|
+
|
|
142
|
+
def _auto_fit(self, path: str, documents: list[Document]) -> bool:
|
|
143
|
+
"""
|
|
144
|
+
Fit and save a model on `documents`.
|
|
145
|
+
|
|
146
|
+
:returns: True when the fit ran with this component's device settings, so any backend fallback warning
|
|
147
|
+
for this run has already been logged.
|
|
148
|
+
"""
|
|
149
|
+
logger.info(
|
|
150
|
+
"No model at {path}: fitting one on this run's documents; the clusters depend on the first batch seen",
|
|
151
|
+
path=path,
|
|
152
|
+
)
|
|
153
|
+
params = {"device": self.device, "gpu_threshold": self.gpu_threshold, **(self.fit_params or {})}
|
|
154
|
+
fitter = EmeansFitter(model_path=path, overwrite=False, **params)
|
|
155
|
+
try:
|
|
156
|
+
fitter.run(documents=documents)
|
|
157
|
+
return params["device"] == self.device and params["gpu_threshold"] == self.gpu_threshold
|
|
158
|
+
except FileExistsError:
|
|
159
|
+
# Another writer created the file first; use theirs.
|
|
160
|
+
logger.info("Model {path} was created concurrently; using it", path=path)
|
|
161
|
+
return False
|
|
162
|
+
|
|
163
|
+
@component.output_types(documents=list[Document])
|
|
164
|
+
def run(self, documents: list[Document], model_path: str | None = None) -> dict[str, Any]:
|
|
165
|
+
"""
|
|
166
|
+
Write `meta["cluster_id"]` on every document that has an embedding.
|
|
167
|
+
|
|
168
|
+
:param documents: Documents to cluster. They are not modified; copies are returned in the same order.
|
|
169
|
+
Documents without embedding are returned unchanged.
|
|
170
|
+
:param model_path: Model to load; replaces the init value.
|
|
171
|
+
:returns: A dictionary with the `documents`, in input order.
|
|
172
|
+
:raises ValueError: If no model path is available, or on invalid embeddings.
|
|
173
|
+
:raises FileNotFoundError: If the model file does not exist and `fit_if_missing` is not set.
|
|
174
|
+
:raises RuntimeError: If `device="cuda"` and no GPU backend is usable.
|
|
175
|
+
"""
|
|
176
|
+
path = model_path if model_path is not None else self.model_path
|
|
177
|
+
if path is None:
|
|
178
|
+
msg = "No model path: set model_path at init or pass it to run()"
|
|
179
|
+
raise ValueError(msg)
|
|
180
|
+
if not documents:
|
|
181
|
+
return {"documents": []}
|
|
182
|
+
|
|
183
|
+
positions, x = extract_embeddings(documents)
|
|
184
|
+
n_skipped = len(documents) - len(positions)
|
|
185
|
+
if n_skipped:
|
|
186
|
+
logger.warning("{n} documents without embedding were returned unchanged", n=n_skipped)
|
|
187
|
+
if not positions:
|
|
188
|
+
return {"documents": list(documents)}
|
|
189
|
+
|
|
190
|
+
if self.device == "cuda":
|
|
191
|
+
# Fail before _ensure_model, which may auto-fit and write a model file; k does not matter for "cuda".
|
|
192
|
+
select_backend(device=self.device, n=len(positions), k=1, gpu_threshold=self.gpu_threshold)
|
|
193
|
+
model, fit_warned = self._ensure_model(path, documents)
|
|
194
|
+
if x.shape[1] != model.d:
|
|
195
|
+
msg = f"Embedding dimension mismatch: documents have dimension {x.shape[1]}, but the model has {model.d}"
|
|
196
|
+
raise ValueError(msg)
|
|
197
|
+
# An auto-fit in this run already logged any fallback warning; log it once per run (D-03).
|
|
198
|
+
backend = select_backend(
|
|
199
|
+
device=self.device,
|
|
200
|
+
n=len(positions),
|
|
201
|
+
k=model.k,
|
|
202
|
+
gpu_threshold=self.gpu_threshold,
|
|
203
|
+
warn=not fit_warned,
|
|
204
|
+
)
|
|
205
|
+
if model.spherical:
|
|
206
|
+
x = normalize_rows(x, [documents[p].id for p in positions])
|
|
207
|
+
|
|
208
|
+
assigner = assigner_for(backend, model.centroids, spherical=model.spherical)
|
|
209
|
+
metas: dict[int, dict[str, Any]] = {}
|
|
210
|
+
for lo in range(0, len(positions), self.batch_size):
|
|
211
|
+
scores, labels = assigner.assign(x[lo : lo + self.batch_size])
|
|
212
|
+
for offset, (score, label) in enumerate(zip(scores, labels, strict=True)):
|
|
213
|
+
doc = documents[positions[lo + offset]]
|
|
214
|
+
meta = {**doc.meta, "cluster_id": int(label)}
|
|
215
|
+
if self.return_distance:
|
|
216
|
+
if model.spherical:
|
|
217
|
+
meta["cluster_similarity"] = float(np.clip(score, -1.0, 1.0))
|
|
218
|
+
else:
|
|
219
|
+
meta["cluster_distance"] = float(max(score, 0.0))
|
|
220
|
+
metas[positions[lo + offset]] = meta
|
|
221
|
+
|
|
222
|
+
out = [replace(doc, meta=metas[i]) if i in metas else doc for i, doc in enumerate(documents)]
|
|
223
|
+
return {"documents": out}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026-present ogaude <ogaude.code@proton.me>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from haystack import Document, component, default_from_dict, default_to_dict, logging
|
|
10
|
+
|
|
11
|
+
from haystack_integrations.components.preprocessors.emeans._backend import DEVICES, fit_model, select_backend
|
|
12
|
+
from haystack_integrations.components.preprocessors.emeans._model import UNIT_NORM_TOLERANCE, save_model
|
|
13
|
+
from haystack_integrations.components.preprocessors.emeans._utils import (
|
|
14
|
+
check_bool,
|
|
15
|
+
check_integer,
|
|
16
|
+
check_nepochs,
|
|
17
|
+
check_positive_int,
|
|
18
|
+
check_threshold,
|
|
19
|
+
extract_embeddings,
|
|
20
|
+
normalize_rows,
|
|
21
|
+
optional_int,
|
|
22
|
+
resolve_k,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
_PRECISIONS = ("auto", "fp32", "bf16", "fp16")
|
|
28
|
+
_MIN_USABLE_DOCUMENTS = 2
|
|
29
|
+
_EMPTY_CENTROID_NORM = 0.5
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@component
|
|
33
|
+
class EmeansFitter:
|
|
34
|
+
"""
|
|
35
|
+
Trains e-means on the embeddings of the input documents and writes a model file.
|
|
36
|
+
|
|
37
|
+
The model file is the only link between fitting and assignment: connect `model_path` to an
|
|
38
|
+
`EmeansDocumentClusterer` to give documents stable `cluster_id`s.
|
|
39
|
+
|
|
40
|
+
### Usage example
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from haystack_integrations.components.preprocessors.emeans import EmeansFitter
|
|
44
|
+
|
|
45
|
+
fitter = EmeansFitter(model_path="clusters.npz", target_cluster_size=50)
|
|
46
|
+
result = fitter.run(documents=documents_with_embeddings)
|
|
47
|
+
print(result["stats"]["k"])
|
|
48
|
+
```
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
model_path: str,
|
|
54
|
+
k: int | None = None,
|
|
55
|
+
target_cluster_size: int | None = None,
|
|
56
|
+
spherical: bool = True,
|
|
57
|
+
nepochs: float = 5.0,
|
|
58
|
+
precision: Literal["auto", "fp32", "bf16", "fp16"] = "auto",
|
|
59
|
+
device: Literal["auto", "cpu", "cuda"] = "auto",
|
|
60
|
+
gpu_threshold: float = 1e10,
|
|
61
|
+
seed: int = 1234,
|
|
62
|
+
deterministic: bool = False,
|
|
63
|
+
max_points_per_centroid: int | None = None,
|
|
64
|
+
overwrite: bool = False,
|
|
65
|
+
) -> None:
|
|
66
|
+
"""
|
|
67
|
+
Create an EmeansFitter.
|
|
68
|
+
|
|
69
|
+
:param model_path: Where the `.npz` model file is written. Parent directories must exist.
|
|
70
|
+
:param k: Number of clusters. Exactly one of `k` and `target_cluster_size` must be set.
|
|
71
|
+
:param target_cluster_size: Average documents per cluster;
|
|
72
|
+
`k = max(1, min(round(n / target_cluster_size), n))` with `n` the number of usable documents.
|
|
73
|
+
:param spherical: If `True`, cluster by cosine similarity: embeddings are L2-normalised (on a copy).
|
|
74
|
+
If `False`, cluster by Euclidean distance.
|
|
75
|
+
:param nepochs: Passes over the data; fractional values are allowed.
|
|
76
|
+
:param precision: Number format of the nearest-centroid search on GPU. On CPU everything is FP32.
|
|
77
|
+
:param device: `"cpu"`, `"cuda"` or `"auto"`.
|
|
78
|
+
:param gpu_threshold: With `device="auto"`, a GPU is used only when `n * k` is at least this value.
|
|
79
|
+
:param seed: Seeds starting centroids, shuffling and cluster revival.
|
|
80
|
+
:param deterministic: On GPU, request deterministic algorithms during training. No effect on CPU. On
|
|
81
|
+
NVIDIA, export `CUBLAS_WORKSPACE_CONFIG=:4096:8` before starting the process for guaranteed repeats.
|
|
82
|
+
PyTorch's setting is process-wide: while the fit trains, GPU work in other threads (other fits,
|
|
83
|
+
cluster assignment, backend probes) also runs with deterministic algorithms on.
|
|
84
|
+
:param max_points_per_centroid: If set and `n > max_points_per_centroid * k`, train on a random subset.
|
|
85
|
+
:param overwrite: If `False`, an existing file at `model_path` raises `FileExistsError`.
|
|
86
|
+
"""
|
|
87
|
+
check_positive_int("k", k, allow_none=True)
|
|
88
|
+
check_positive_int("target_cluster_size", target_cluster_size, allow_none=True)
|
|
89
|
+
check_positive_int("max_points_per_centroid", max_points_per_centroid, allow_none=True)
|
|
90
|
+
self._check_exactly_one(k, target_cluster_size)
|
|
91
|
+
check_nepochs(nepochs)
|
|
92
|
+
check_bool("spherical", spherical)
|
|
93
|
+
check_bool("deterministic", deterministic)
|
|
94
|
+
check_bool("overwrite", overwrite)
|
|
95
|
+
check_integer("seed", seed)
|
|
96
|
+
check_threshold("gpu_threshold", gpu_threshold)
|
|
97
|
+
if device not in DEVICES:
|
|
98
|
+
msg = f"device must be one of {DEVICES}, got {device!r}"
|
|
99
|
+
raise ValueError(msg)
|
|
100
|
+
if precision not in _PRECISIONS:
|
|
101
|
+
msg = f"precision must be one of {_PRECISIONS}, got {precision!r}"
|
|
102
|
+
raise ValueError(msg)
|
|
103
|
+
self.model_path = model_path
|
|
104
|
+
self.k = optional_int(k)
|
|
105
|
+
self.target_cluster_size = optional_int(target_cluster_size)
|
|
106
|
+
self.spherical = spherical
|
|
107
|
+
self.nepochs = nepochs
|
|
108
|
+
self.precision = precision
|
|
109
|
+
self.device = device
|
|
110
|
+
self.gpu_threshold = gpu_threshold
|
|
111
|
+
self.seed = int(seed)
|
|
112
|
+
self.deterministic = deterministic
|
|
113
|
+
self.max_points_per_centroid = optional_int(max_points_per_centroid)
|
|
114
|
+
self.overwrite = overwrite
|
|
115
|
+
|
|
116
|
+
@staticmethod
|
|
117
|
+
def _check_exactly_one(k: int | None, target_cluster_size: int | None) -> None:
|
|
118
|
+
if (k is None) == (target_cluster_size is None):
|
|
119
|
+
msg = "Exactly one of k and target_cluster_size must be set"
|
|
120
|
+
raise ValueError(msg)
|
|
121
|
+
|
|
122
|
+
def to_dict(self) -> dict[str, Any]:
|
|
123
|
+
"""
|
|
124
|
+
Serialize the component to a dictionary.
|
|
125
|
+
|
|
126
|
+
:returns: Dictionary with all init parameters.
|
|
127
|
+
"""
|
|
128
|
+
return default_to_dict(
|
|
129
|
+
self,
|
|
130
|
+
model_path=self.model_path,
|
|
131
|
+
k=self.k,
|
|
132
|
+
target_cluster_size=self.target_cluster_size,
|
|
133
|
+
spherical=self.spherical,
|
|
134
|
+
nepochs=self.nepochs,
|
|
135
|
+
precision=self.precision,
|
|
136
|
+
device=self.device,
|
|
137
|
+
gpu_threshold=self.gpu_threshold,
|
|
138
|
+
seed=self.seed,
|
|
139
|
+
deterministic=self.deterministic,
|
|
140
|
+
max_points_per_centroid=self.max_points_per_centroid,
|
|
141
|
+
overwrite=self.overwrite,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def from_dict(cls, data: dict[str, Any]) -> "EmeansFitter":
|
|
146
|
+
"""
|
|
147
|
+
Deserialize the component from a dictionary.
|
|
148
|
+
|
|
149
|
+
:param data: Dictionary produced by `to_dict`.
|
|
150
|
+
:returns: The deserialized component.
|
|
151
|
+
"""
|
|
152
|
+
return default_from_dict(cls, data)
|
|
153
|
+
|
|
154
|
+
@component.output_types(model_path=str, stats=dict)
|
|
155
|
+
def run(
|
|
156
|
+
self,
|
|
157
|
+
documents: list[Document],
|
|
158
|
+
k: int | None = None,
|
|
159
|
+
target_cluster_size: int | None = None,
|
|
160
|
+
model_path: str | None = None,
|
|
161
|
+
) -> dict[str, Any]:
|
|
162
|
+
"""
|
|
163
|
+
Fit e-means on the embeddings of `documents` and write the model file.
|
|
164
|
+
|
|
165
|
+
:param documents: Documents with embeddings. Documents without an embedding are skipped.
|
|
166
|
+
:param k: Number of clusters. Passing `k` or `target_cluster_size` replaces both init values.
|
|
167
|
+
:param target_cluster_size: Average documents per cluster.
|
|
168
|
+
:param model_path: Where to write the model; replaces the init value.
|
|
169
|
+
:returns: A dictionary with `model_path` (the file written) and `stats` (a report of the fit).
|
|
170
|
+
:raises FileExistsError: If the file exists and `overwrite` is `False`.
|
|
171
|
+
:raises FileNotFoundError: If the parent directory of the model path does not exist.
|
|
172
|
+
:raises IsADirectoryError: If the model path is a directory and `overwrite` is `True`.
|
|
173
|
+
:raises RuntimeError: If `device="cuda"` and no GPU backend is usable.
|
|
174
|
+
:raises ValueError: On invalid parameters or embeddings, or if the fit produced a non-finite centroid or an
|
|
175
|
+
empty spherical centroid.
|
|
176
|
+
"""
|
|
177
|
+
if k is not None or target_cluster_size is not None:
|
|
178
|
+
check_positive_int("k", k, allow_none=True)
|
|
179
|
+
check_positive_int("target_cluster_size", target_cluster_size, allow_none=True)
|
|
180
|
+
use_k, use_tcs = optional_int(k), optional_int(target_cluster_size)
|
|
181
|
+
else:
|
|
182
|
+
use_k, use_tcs = self.k, self.target_cluster_size
|
|
183
|
+
self._check_exactly_one(use_k, use_tcs)
|
|
184
|
+
path = model_path if model_path is not None else self.model_path
|
|
185
|
+
|
|
186
|
+
parent = os.path.dirname(os.path.abspath(path))
|
|
187
|
+
if not os.path.isdir(parent):
|
|
188
|
+
msg = f"parent directory of model_path does not exist: {parent}"
|
|
189
|
+
raise FileNotFoundError(msg)
|
|
190
|
+
if os.path.exists(path) and not self.overwrite:
|
|
191
|
+
msg = f"Model file already exists: {path}. Pass overwrite=True to replace it."
|
|
192
|
+
raise FileExistsError(msg)
|
|
193
|
+
if os.path.isdir(path):
|
|
194
|
+
msg = f"model_path is a directory, not a file: {path}"
|
|
195
|
+
raise IsADirectoryError(msg)
|
|
196
|
+
|
|
197
|
+
positions, x = extract_embeddings(documents)
|
|
198
|
+
n_usable = len(positions)
|
|
199
|
+
n_skipped = len(documents) - n_usable
|
|
200
|
+
if n_skipped:
|
|
201
|
+
logger.warning("Skipped {n} documents without embedding", n=n_skipped)
|
|
202
|
+
if n_usable < _MIN_USABLE_DOCUMENTS:
|
|
203
|
+
msg = f"At least 2 documents with an embedding are required, got {n_usable}"
|
|
204
|
+
raise ValueError(msg)
|
|
205
|
+
if use_k is not None and use_k > n_usable:
|
|
206
|
+
msg = f"k={use_k} is larger than the number of usable documents ({n_usable})"
|
|
207
|
+
raise ValueError(msg)
|
|
208
|
+
|
|
209
|
+
if self.spherical:
|
|
210
|
+
x = normalize_rows(x, [documents[p].id for p in positions])
|
|
211
|
+
n_clusters = resolve_k(n_usable, use_k, use_tcs)
|
|
212
|
+
backend = select_backend(device=self.device, n=n_usable, k=n_clusters, gpu_threshold=self.gpu_threshold)
|
|
213
|
+
fit = fit_model(
|
|
214
|
+
x,
|
|
215
|
+
k=n_clusters,
|
|
216
|
+
spherical=self.spherical,
|
|
217
|
+
nepochs=self.nepochs,
|
|
218
|
+
seed=self.seed,
|
|
219
|
+
max_points_per_centroid=self.max_points_per_centroid,
|
|
220
|
+
backend=backend,
|
|
221
|
+
precision=self.precision,
|
|
222
|
+
deterministic=self.deterministic,
|
|
223
|
+
allow_cpu_fallback=self.device == "auto",
|
|
224
|
+
)
|
|
225
|
+
info = fit.info
|
|
226
|
+
# The GPU engine does not check its data for NaN or infinity, and NaN passes every norm comparison below.
|
|
227
|
+
# Check finiteness first, on every backend, so the fitter never writes a model its own loader refuses.
|
|
228
|
+
finite_rows = np.isfinite(fit.centroids).all(axis=1)
|
|
229
|
+
if not finite_rows.all():
|
|
230
|
+
n_bad = int(np.count_nonzero(~finite_rows))
|
|
231
|
+
msg = (
|
|
232
|
+
f"The fit produced {n_bad} non-finite centroids out of {n_clusters}; "
|
|
233
|
+
"use precision='fp32' or check the embeddings"
|
|
234
|
+
)
|
|
235
|
+
raise ValueError(msg)
|
|
236
|
+
if self.spherical:
|
|
237
|
+
norms = np.linalg.norm(fit.centroids.astype(np.float64), axis=1)
|
|
238
|
+
n_empty = int(np.count_nonzero(norms < _EMPTY_CENTROID_NORM))
|
|
239
|
+
if n_empty:
|
|
240
|
+
msg = (
|
|
241
|
+
f"The fit produced {n_empty} empty centroids out of {n_clusters}; "
|
|
242
|
+
"use a smaller k or a larger nepochs"
|
|
243
|
+
)
|
|
244
|
+
raise ValueError(msg)
|
|
245
|
+
# Same tolerance as load_model, so the fitter never writes a model its own loader refuses.
|
|
246
|
+
n_off = int(np.count_nonzero(np.abs(norms - 1.0) > UNIT_NORM_TOLERANCE))
|
|
247
|
+
if n_off:
|
|
248
|
+
msg = f"The fit produced {n_off} spherical centroids out of {n_clusters} that do not have unit norm"
|
|
249
|
+
raise ValueError(msg)
|
|
250
|
+
metadata = {
|
|
251
|
+
"spherical": self.spherical,
|
|
252
|
+
"n_train": info["n_train"],
|
|
253
|
+
"seed": self.seed,
|
|
254
|
+
"nepochs": float(self.nepochs),
|
|
255
|
+
"backend": info["backend"],
|
|
256
|
+
"assignment_backend": info["assignment_backend"],
|
|
257
|
+
"precision_used": info["precision_used"],
|
|
258
|
+
"emeans_source": info["emeans_source"],
|
|
259
|
+
"faiss_version": info["faiss_version"],
|
|
260
|
+
"recipe": info["recipe"],
|
|
261
|
+
}
|
|
262
|
+
save_model(path, fit.centroids, metadata, overwrite=self.overwrite)
|
|
263
|
+
|
|
264
|
+
stats: dict[str, Any] = {
|
|
265
|
+
"k": n_clusters,
|
|
266
|
+
"d": int(x.shape[1]),
|
|
267
|
+
"n_documents": len(documents),
|
|
268
|
+
"n_skipped": n_skipped,
|
|
269
|
+
"n_train": info["n_train"],
|
|
270
|
+
"spherical": self.spherical,
|
|
271
|
+
"backend": info["backend"],
|
|
272
|
+
"assignment_backend": info["assignment_backend"],
|
|
273
|
+
"device_name": info["device_name"],
|
|
274
|
+
"precision_used": info["precision_used"],
|
|
275
|
+
"fallback_reason": info["fallback_reason"],
|
|
276
|
+
"memory_estimate_bytes": info["memory_estimate_bytes"],
|
|
277
|
+
"emeans_source": info["emeans_source"],
|
|
278
|
+
"faiss_version": info["faiss_version"],
|
|
279
|
+
"nepochs": info["nepochs"],
|
|
280
|
+
"batch_size": info["batch_size"],
|
|
281
|
+
"alpha0": info["alpha0"],
|
|
282
|
+
"n_splits": info["n_splits"],
|
|
283
|
+
"imbalance": info["imbalance"],
|
|
284
|
+
"unused_threshold": info["unused_threshold"],
|
|
285
|
+
"train_seconds": info["train_seconds"],
|
|
286
|
+
}
|
|
287
|
+
logger.info(
|
|
288
|
+
"Fitted e-means on the {backend} backend (device {device_name}, precision {precision}): k={k} on {n} "
|
|
289
|
+
"documents in {seconds:.2f}s{hint}",
|
|
290
|
+
backend=info["backend"],
|
|
291
|
+
device_name=info["device_name"],
|
|
292
|
+
precision=info["precision_used"],
|
|
293
|
+
k=n_clusters,
|
|
294
|
+
n=n_usable,
|
|
295
|
+
seconds=info["train_seconds"],
|
|
296
|
+
hint=f" {info['backend_hint']}" if info.get("backend_hint") else "",
|
|
297
|
+
)
|
|
298
|
+
return {"model_path": path, "stats": stats}
|
|
File without changes
|