emeans-core 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.
- emeans_core/__init__.py +61 -0
- emeans_core/_backend.py +518 -0
- emeans_core/_dedup.py +443 -0
- emeans_core/_dedup_core.py +713 -0
- emeans_core/_info.py +54 -0
- emeans_core/_vectors.py +76 -0
- emeans_core/cache.py +71 -0
- emeans_core/env.py +308 -0
- emeans_core/py.typed +0 -0
- emeans_core-0.1.0.dist-info/METADATA +281 -0
- emeans_core-0.1.0.dist-info/RECORD +14 -0
- emeans_core-0.1.0.dist-info/WHEEL +4 -0
- emeans_core-0.1.0.dist-info/licenses/LICENSE +21 -0
- emeans_core-0.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +6 -0
emeans_core/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Framework-free e-means clustering backend and near-duplicate removal for the emeans-* integrations.
|
|
2
|
+
|
|
3
|
+
Importing this package never imports faiss, torch or emeans-rocm: the clustering backend
|
|
4
|
+
loads on first use. Everything public is listed in ``__all__``, plus the ``emeans_core.env``
|
|
5
|
+
and ``emeans_core.cache`` modules; modules whose name starts with an underscore are private and
|
|
6
|
+
may change in any release.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from emeans_core._backend import DEFAULT_GPU_THRESHOLD, FitOutput, fit, reset_backend_cache, warn_once
|
|
12
|
+
from emeans_core._dedup import (
|
|
13
|
+
DedupReport,
|
|
14
|
+
DuplicateDrop,
|
|
15
|
+
ExternalMatches,
|
|
16
|
+
ReferenceVectors,
|
|
17
|
+
dedup,
|
|
18
|
+
match_external,
|
|
19
|
+
)
|
|
20
|
+
from emeans_core._info import backend_info, nearest_centroids
|
|
21
|
+
from emeans_core._vectors import as_matrix, clamp_k, l2_normalize, prepare
|
|
22
|
+
from emeans_core.cache import EmbeddingCache
|
|
23
|
+
|
|
24
|
+
__version__ = "0.1.0"
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"DEFAULT_GPU_THRESHOLD",
|
|
28
|
+
"DedupReport",
|
|
29
|
+
"DuplicateDrop",
|
|
30
|
+
"EmbeddingCache",
|
|
31
|
+
"ExternalMatches",
|
|
32
|
+
"FitOutput",
|
|
33
|
+
"ReferenceVectors",
|
|
34
|
+
"__version__",
|
|
35
|
+
"as_matrix",
|
|
36
|
+
"backend_info",
|
|
37
|
+
"clamp_k",
|
|
38
|
+
"collect_env",
|
|
39
|
+
"dedup",
|
|
40
|
+
"fit",
|
|
41
|
+
"l2_normalize",
|
|
42
|
+
"match_external",
|
|
43
|
+
"nearest_centroids",
|
|
44
|
+
"prepare",
|
|
45
|
+
"reset_backend_cache",
|
|
46
|
+
"warn_once",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def __getattr__(name: str) -> Any:
|
|
51
|
+
# Imported on first use, so that ``python -m emeans_core.env`` does not find the module loaded.
|
|
52
|
+
if name == "collect_env":
|
|
53
|
+
from emeans_core.env import collect_env
|
|
54
|
+
|
|
55
|
+
return collect_env
|
|
56
|
+
msg = f"module 'emeans_core' has no attribute {name!r}"
|
|
57
|
+
raise AttributeError(msg)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def __dir__() -> list[str]:
|
|
61
|
+
return sorted(set(globals()) | set(__all__))
|
emeans_core/_backend.py
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
"""Clustering backends: e-means on CPU (faiss-cpu's NumpyEmeans) or on a GPU (torch).
|
|
2
|
+
|
|
3
|
+
Nothing here imports faiss, torch or emeans-rocm at module import time. Engines load on
|
|
4
|
+
first use, once per process, under a lock.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import importlib
|
|
11
|
+
import importlib.metadata
|
|
12
|
+
import importlib.util
|
|
13
|
+
import logging
|
|
14
|
+
import os
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Literal
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("emeans_core")
|
|
24
|
+
|
|
25
|
+
Device = Literal["auto", "cpu", "cuda"]
|
|
26
|
+
Precision = Literal["fp32", "bf16", "fp16"]
|
|
27
|
+
DEVICES: tuple[str, ...] = ("auto", "cpu", "cuda")
|
|
28
|
+
PRECISIONS: tuple[str, ...] = ("fp32", "bf16", "fp16")
|
|
29
|
+
INITS: tuple[str, ...] = ("auto", "k-means++", "sample")
|
|
30
|
+
|
|
31
|
+
# Same revival setting as emeans-haystack: mass-based revival at 0.1, none for d <= 2.
|
|
32
|
+
# emeans-rocm >= 0.2.6 resolves None to cost-based revival, so the value is always passed.
|
|
33
|
+
_UNUSED_THRESHOLD = 0.1
|
|
34
|
+
_NO_REVIVAL_MAX_D = 2
|
|
35
|
+
|
|
36
|
+
# emeans-rocm releases this package is tested against; others fall back to stock faiss.
|
|
37
|
+
EMEANS_ROCM_SUPPORTED = (0, 2, 5), (0, 3, 0)
|
|
38
|
+
|
|
39
|
+
KMEANS_PP_MAX_WORK = 1e7
|
|
40
|
+
"""With ``init="auto"``, k-means++ seeding is used when ``n * k`` is at most this value."""
|
|
41
|
+
|
|
42
|
+
SINGLE_THREAD_MAX_WORK = 2e8
|
|
43
|
+
"""CPU fits with ``n * k * d`` up to this run faiss single-threaded: OpenMP start-up costs several
|
|
44
|
+
milliseconds per call, which dominates small (retrieval-sized) problems. On a 10-core CPU, in the
|
|
45
|
+
two runs of the BENCHMARKS.md backend section, 50 to 200 rows took 7.2 to 13.8 ms single-threaded
|
|
46
|
+
against 22.6 to 75.3 ms with OpenMP. Up to this limit, single-threaded fits were faster in the
|
|
47
|
+
CPU-only run shown there and in the two earlier CPU-only runs kept in ``benchmarks/results``; in
|
|
48
|
+
the GPU run, whose process had imported torch first, OpenMP was up to 11% faster from 2,000 rows."""
|
|
49
|
+
|
|
50
|
+
SMALL_NEPOCHS = 20.0
|
|
51
|
+
"""Epochs used by ``nepochs=None`` when ``n * k <= KMEANS_PP_MAX_WORK``."""
|
|
52
|
+
|
|
53
|
+
DEFAULT_GPU_THRESHOLD = 1e6
|
|
54
|
+
"""With ``device="auto"``, a GPU is used only when ``n * k`` reaches this value. Measured on an RX
|
|
55
|
+
9060 XT against a 10-core CPU (BENCHMARKS.md, backend section), warm process, CPU and GPU fits of
|
|
56
|
+
the GPU run: the GPU's speed-up over the CPU was 0.31 to 0.51x at ``n * k = 1e3`` (the GPU slower),
|
|
57
|
+
1.44 to 4.92x at 1.1e4, 7.09 to 7.85x at 1e6 and 22.99 to 27.96x at 1.1e7 to 3.2e7 (the largest
|
|
58
|
+
measured), as in the table. That run's process had imported torch first, which slowed its CPU fits
|
|
59
|
+
of 500 to 5,000 rows; in the CPU-only run shown in BENCHMARKS.md (started 2026-12-04 19:27 UTC),
|
|
60
|
+
those fits were up to 2.82x faster, and at 1.1e4 (d=384) the CPU took 29.5 ms against the GPU's
|
|
61
|
+
35.0 ms. The first GPU fit in a process takes about 1.6 s (torch import, HIP start-up);
|
|
62
|
+
retrieval-sized inputs stay on the CPU."""
|
|
63
|
+
|
|
64
|
+
_lock = threading.RLock()
|
|
65
|
+
_deterministic_lock = threading.Lock()
|
|
66
|
+
_cache: dict[str, Any] = {}
|
|
67
|
+
_logged: set[str] = set()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def unused_threshold(d: int) -> float:
|
|
71
|
+
"""Revival threshold passed to every e-means constructor (0 disables revival)."""
|
|
72
|
+
return 0.0 if d <= _NO_REVIVAL_MAX_D else _UNUSED_THRESHOLD
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _log_once(key: str, level: int, msg: str, *args: Any) -> None:
|
|
76
|
+
with _lock:
|
|
77
|
+
if key in _logged:
|
|
78
|
+
return
|
|
79
|
+
_logged.add(key)
|
|
80
|
+
logger.log(level, msg, *args)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def warn_once(key: str, msg: str, *args: Any) -> None:
|
|
84
|
+
"""Log a warning once per process for ``key``."""
|
|
85
|
+
_log_once("warn:" + key, logging.WARNING, msg, *args)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _dist_version(name: str) -> str | None:
|
|
89
|
+
try:
|
|
90
|
+
return importlib.metadata.version(name)
|
|
91
|
+
except importlib.metadata.PackageNotFoundError:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _version_tuple(version: str) -> tuple[int, ...]:
|
|
96
|
+
parts: list[int] = []
|
|
97
|
+
for piece in version.split("+")[0].split("."):
|
|
98
|
+
digits = "".join(ch for ch in piece if ch.isdigit())
|
|
99
|
+
if not digits:
|
|
100
|
+
break
|
|
101
|
+
parts.append(int(digits))
|
|
102
|
+
return tuple(parts)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _find_spec(name: str) -> bool:
|
|
106
|
+
try:
|
|
107
|
+
return importlib.util.find_spec(name) is not None
|
|
108
|
+
except (ImportError, ValueError):
|
|
109
|
+
return False
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def faiss_module() -> Any:
|
|
113
|
+
"""Import faiss once (thread-safe)."""
|
|
114
|
+
with _lock:
|
|
115
|
+
if "faiss" not in _cache:
|
|
116
|
+
try:
|
|
117
|
+
_cache["faiss"] = importlib.import_module("faiss")
|
|
118
|
+
except ImportError as error: # pragma: no cover - faiss-cpu is a dependency
|
|
119
|
+
msg = "faiss is required for the CPU e-means backend: pip install faiss-cpu"
|
|
120
|
+
raise ImportError(msg) from error
|
|
121
|
+
return _cache["faiss"]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cpu_engine() -> Any:
|
|
125
|
+
"""Return ``NumpyEmeans`` from faiss-cpu's ``faiss.contrib.e_means`` (no torch import)."""
|
|
126
|
+
with _lock:
|
|
127
|
+
if "cpu_engine" not in _cache:
|
|
128
|
+
faiss_module()
|
|
129
|
+
module = importlib.import_module("faiss.contrib.e_means.e_means")
|
|
130
|
+
_cache["cpu_engine"] = module.NumpyEmeans
|
|
131
|
+
return _cache["cpu_engine"]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def emeans_rocm_usable() -> bool:
|
|
135
|
+
"""Whether ``emeans_rocm`` is installed in the supported version range (checked without importing it)."""
|
|
136
|
+
if not _find_spec("emeans_rocm"):
|
|
137
|
+
return False
|
|
138
|
+
version = _dist_version("emeans-rocm")
|
|
139
|
+
if version is None: # a source checkout on the path: used as is
|
|
140
|
+
return True
|
|
141
|
+
low, high = EMEANS_ROCM_SUPPORTED
|
|
142
|
+
ok = low <= _version_tuple(version) < high
|
|
143
|
+
if not ok:
|
|
144
|
+
warn_once(
|
|
145
|
+
"rocm-range",
|
|
146
|
+
"emeans-rocm %s is outside the supported range [%s, %s); using stock faiss e-means",
|
|
147
|
+
version,
|
|
148
|
+
".".join(map(str, low)),
|
|
149
|
+
".".join(map(str, high)),
|
|
150
|
+
)
|
|
151
|
+
return ok
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def gpu_engine_source() -> str:
|
|
155
|
+
"""Label of the GPU e-means engine that would run (no import)."""
|
|
156
|
+
if emeans_rocm_usable():
|
|
157
|
+
return f"emeans-rocm {_dist_version('emeans-rocm') or '(source checkout)'}"
|
|
158
|
+
return f"faiss.contrib.e_means (faiss {_dist_version('faiss-cpu') or _dist_version('faiss-gpu') or '?'})"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _torch() -> Any:
|
|
162
|
+
with _lock:
|
|
163
|
+
if "torch" not in _cache:
|
|
164
|
+
_cache["torch"] = importlib.import_module("torch")
|
|
165
|
+
return _cache["torch"]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def gpu_available() -> bool:
|
|
169
|
+
"""Whether torch is installed and sees a GPU (CUDA or ROCm). Imports torch only when installed."""
|
|
170
|
+
with _lock:
|
|
171
|
+
if "gpu_available" in _cache:
|
|
172
|
+
return bool(_cache["gpu_available"])
|
|
173
|
+
available = False
|
|
174
|
+
if _find_spec("torch"):
|
|
175
|
+
try:
|
|
176
|
+
available = bool(_torch().cuda.is_available())
|
|
177
|
+
except Exception as error: # a broken torch install must not break CPU users
|
|
178
|
+
warn_once("torch-broken", "torch is installed but failed to load (%s); using the CPU backend", error)
|
|
179
|
+
_cache["gpu_available"] = available
|
|
180
|
+
return available
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def gpu_engine() -> Any:
|
|
184
|
+
"""Return the module providing GPU ``Emeans``/``QuantizedEmeans`` (emeans_rocm or stock faiss)."""
|
|
185
|
+
with _lock:
|
|
186
|
+
if "gpu_engine" not in _cache:
|
|
187
|
+
name = "emeans_rocm" if emeans_rocm_usable() else "faiss.contrib.e_means"
|
|
188
|
+
_cache["gpu_engine"] = importlib.import_module(name)
|
|
189
|
+
return _cache["gpu_engine"]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def reset_backend_cache() -> None:
|
|
193
|
+
"""Forget loaded engines and one-time log keys (for tests)."""
|
|
194
|
+
with _lock:
|
|
195
|
+
_cache.clear()
|
|
196
|
+
_logged.clear()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@dataclass(frozen=True)
|
|
200
|
+
class FitOutput:
|
|
201
|
+
"""Result of one clustering run."""
|
|
202
|
+
|
|
203
|
+
centroids: np.ndarray
|
|
204
|
+
"""FP32 centroids, shape ``(k, d)``."""
|
|
205
|
+
labels: np.ndarray
|
|
206
|
+
"""Nearest-centroid ids from an FP32 assignment, shape ``(n,)``."""
|
|
207
|
+
backend: str
|
|
208
|
+
"""``"cpu"`` or ``"gpu"``: the backend that ran."""
|
|
209
|
+
precision: str
|
|
210
|
+
"""Precision clustering ran in (always ``"fp32"`` on CPU)."""
|
|
211
|
+
info: dict[str, Any] = field(default_factory=dict)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def kmeans_plusplus(x: np.ndarray, k: int, seed: int) -> np.ndarray:
|
|
215
|
+
"""Greedy k-means++ seeding (as scikit-learn: ``2 + log(k)`` candidates per step), FP32, deterministic."""
|
|
216
|
+
rng = np.random.default_rng(seed)
|
|
217
|
+
n = len(x)
|
|
218
|
+
trials = 2 + int(np.log(k))
|
|
219
|
+
sq = np.einsum("ij,ij->i", x, x, dtype=np.float64)
|
|
220
|
+
centers = np.empty((k, x.shape[1]), dtype=np.float32)
|
|
221
|
+
first = int(rng.integers(n))
|
|
222
|
+
centers[0] = x[first]
|
|
223
|
+
closest = np.maximum(sq + sq[first] - 2.0 * (x @ x[first]), 0.0)
|
|
224
|
+
potential = float(closest.sum())
|
|
225
|
+
for c in range(1, k):
|
|
226
|
+
if potential <= 0.0: # every row coincides with a centre already: any row will do
|
|
227
|
+
candidates = rng.integers(n, size=trials)
|
|
228
|
+
else:
|
|
229
|
+
cumulative = np.cumsum(closest)
|
|
230
|
+
candidates = np.minimum(np.searchsorted(cumulative, rng.random(trials) * cumulative[-1]), n - 1)
|
|
231
|
+
dist = np.maximum(sq[None, :] + sq[candidates][:, None] - 2.0 * (x[candidates] @ x.T), 0.0)
|
|
232
|
+
merged = np.minimum(closest[None, :], dist)
|
|
233
|
+
potentials = merged.sum(axis=1)
|
|
234
|
+
best = int(np.argmin(potentials))
|
|
235
|
+
centers[c] = x[candidates[best]]
|
|
236
|
+
closest, potential = merged[best], float(potentials[best])
|
|
237
|
+
return centers
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def resolve_init(init: str, n: int, k: int) -> str:
|
|
241
|
+
if init not in INITS:
|
|
242
|
+
msg = f"init must be one of {INITS}, got {init!r}"
|
|
243
|
+
raise ValueError(msg)
|
|
244
|
+
if init == "auto":
|
|
245
|
+
return "k-means++" if float(n) * float(k) <= KMEANS_PP_MAX_WORK else "sample"
|
|
246
|
+
return init
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def check_device(device: str) -> None:
|
|
250
|
+
if device not in DEVICES:
|
|
251
|
+
msg = f"device must be one of {DEVICES}, got {device!r}"
|
|
252
|
+
raise ValueError(msg)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def check_precision(precision: str) -> None:
|
|
256
|
+
if precision not in PRECISIONS:
|
|
257
|
+
msg = f"precision must be one of {PRECISIONS}, got {precision!r}"
|
|
258
|
+
raise ValueError(msg)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def resolve_device(device: str, n: int, k: int, gpu_threshold: float) -> str:
|
|
262
|
+
"""Return ``"cpu"`` or ``"gpu"`` for a run of ``n`` rows and ``k`` clusters."""
|
|
263
|
+
check_device(device)
|
|
264
|
+
if device == "cpu":
|
|
265
|
+
chosen = "cpu"
|
|
266
|
+
elif device == "cuda":
|
|
267
|
+
if not gpu_available():
|
|
268
|
+
msg = "device='cuda' was requested but no GPU is visible to torch (install a CUDA or ROCm build of torch)"
|
|
269
|
+
raise RuntimeError(msg)
|
|
270
|
+
chosen = "gpu"
|
|
271
|
+
else:
|
|
272
|
+
chosen = "gpu" if float(n) * float(k) >= gpu_threshold and gpu_available() else "cpu"
|
|
273
|
+
if chosen == "cpu":
|
|
274
|
+
_log_once("active:cpu", logging.INFO, "emeans-core backend: CPU e-means (faiss-cpu NumpyEmeans)")
|
|
275
|
+
else:
|
|
276
|
+
_log_once("active:gpu", logging.INFO, "emeans-core backend: GPU e-means (%s)", gpu_engine_source())
|
|
277
|
+
return chosen
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def fit(
|
|
281
|
+
x: np.ndarray,
|
|
282
|
+
k: int,
|
|
283
|
+
*,
|
|
284
|
+
spherical: bool,
|
|
285
|
+
seed: int = 1234,
|
|
286
|
+
device: str = "auto",
|
|
287
|
+
precision: str = "fp32",
|
|
288
|
+
nepochs: float | None = None,
|
|
289
|
+
deterministic: bool = False,
|
|
290
|
+
gpu_threshold: float = DEFAULT_GPU_THRESHOLD,
|
|
291
|
+
init: str = "auto",
|
|
292
|
+
) -> FitOutput:
|
|
293
|
+
"""Train e-means on ``x`` (float32, already normalised when ``spherical``) and label every row.
|
|
294
|
+
|
|
295
|
+
Labels always come from an FP32 assignment, whatever ``precision`` training used.
|
|
296
|
+
``init="auto"`` seeds with k-means++ for small problems (``n * k <= KMEANS_PP_MAX_WORK``) and
|
|
297
|
+
otherwise with e-means' own seeded sample of ``k`` rows. ``nepochs=None`` means 20 epochs for
|
|
298
|
+
those small problems (e-means' batch laws pick very small batches there) and e-means' 5 otherwise.
|
|
299
|
+
"""
|
|
300
|
+
check_precision(precision)
|
|
301
|
+
n, _d = x.shape
|
|
302
|
+
if not 1 <= k <= n:
|
|
303
|
+
msg = f"k must be in [1, n]: got k={k} for n={n}"
|
|
304
|
+
raise ValueError(msg)
|
|
305
|
+
chosen = resolve_device(device, n, k, gpu_threshold)
|
|
306
|
+
init_used = resolve_init(init, n, k)
|
|
307
|
+
small = float(n) * float(k) <= KMEANS_PP_MAX_WORK
|
|
308
|
+
if nepochs is None:
|
|
309
|
+
nepochs = SMALL_NEPOCHS if small else 5.0
|
|
310
|
+
x = np.ascontiguousarray(x, dtype=np.float32)
|
|
311
|
+
init_centroids = kmeans_plusplus(x, k, seed) if init_used == "k-means++" else None
|
|
312
|
+
if chosen == "gpu":
|
|
313
|
+
try:
|
|
314
|
+
return _fit_gpu(
|
|
315
|
+
x,
|
|
316
|
+
k,
|
|
317
|
+
spherical=spherical,
|
|
318
|
+
seed=seed,
|
|
319
|
+
precision=precision,
|
|
320
|
+
nepochs=nepochs,
|
|
321
|
+
deterministic=deterministic,
|
|
322
|
+
init_centroids=init_centroids,
|
|
323
|
+
)
|
|
324
|
+
except Exception as error:
|
|
325
|
+
if device == "cuda":
|
|
326
|
+
raise
|
|
327
|
+
warn_once("gpu-fallback", "GPU e-means failed (%s); falling back to the CPU backend", error)
|
|
328
|
+
if precision != "fp32":
|
|
329
|
+
warn_once(
|
|
330
|
+
f"cpu-precision:{precision}", "precision %r is not available on the CPU backend; using fp32", precision
|
|
331
|
+
)
|
|
332
|
+
return _fit_cpu(x, k, spherical=spherical, seed=seed, nepochs=nepochs, init_centroids=init_centroids)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
@contextlib.contextmanager
|
|
336
|
+
def cpu_threads_for(work: float) -> Iterator[None]:
|
|
337
|
+
"""Run faiss single-threaded for small problems. OpenMP thread counts are per calling thread,
|
|
338
|
+
so this does not affect fits running concurrently in other threads."""
|
|
339
|
+
if work > SINGLE_THREAD_MAX_WORK:
|
|
340
|
+
yield
|
|
341
|
+
return
|
|
342
|
+
faiss = faiss_module()
|
|
343
|
+
previous = faiss.omp_get_max_threads()
|
|
344
|
+
faiss.omp_set_num_threads(1)
|
|
345
|
+
try:
|
|
346
|
+
yield
|
|
347
|
+
finally:
|
|
348
|
+
faiss.omp_set_num_threads(previous)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _fit_cpu(
|
|
352
|
+
x: np.ndarray, k: int, *, spherical: bool, seed: int, nepochs: float, init_centroids: np.ndarray | None
|
|
353
|
+
) -> FitOutput:
|
|
354
|
+
engine = cpu_engine()
|
|
355
|
+
d = x.shape[1]
|
|
356
|
+
x = np.ascontiguousarray(x, dtype=np.float32)
|
|
357
|
+
start = time.perf_counter_ns()
|
|
358
|
+
em = engine(
|
|
359
|
+
d,
|
|
360
|
+
k,
|
|
361
|
+
nepochs=nepochs,
|
|
362
|
+
seed=int(seed),
|
|
363
|
+
spherical=spherical,
|
|
364
|
+
capture_assignments=False,
|
|
365
|
+
unused_threshold=unused_threshold(d),
|
|
366
|
+
)
|
|
367
|
+
with cpu_threads_for(float(len(x)) * k * d):
|
|
368
|
+
centroids, _ = em.train(x, init_centroids=init_centroids)
|
|
369
|
+
train_ns = time.perf_counter_ns() - start
|
|
370
|
+
centroids = np.ascontiguousarray(centroids, dtype=np.float32)
|
|
371
|
+
_, labels = em.assign(x)
|
|
372
|
+
recipe = getattr(em, "recipe", None) or {}
|
|
373
|
+
info = {
|
|
374
|
+
"train_ns": train_ns,
|
|
375
|
+
"batch_size": recipe.get("batch_size"),
|
|
376
|
+
"nepochs": recipe.get("nepochs", nepochs),
|
|
377
|
+
"init": "k-means++" if init_centroids is not None else "sample",
|
|
378
|
+
"engine": f"faiss-cpu {_dist_version('faiss-cpu') or '?'} NumpyEmeans",
|
|
379
|
+
}
|
|
380
|
+
return FitOutput(centroids, np.asarray(labels, dtype=np.int64), "cpu", "fp32", info)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
@contextlib.contextmanager
|
|
384
|
+
def _deterministic(torch: Any, enabled: bool) -> Iterator[None]:
|
|
385
|
+
"""Request PyTorch deterministic algorithms while training (process-wide setting).
|
|
386
|
+
|
|
387
|
+
On CUDA builds cuBLAS also needs ``CUBLAS_WORKSPACE_CONFIG``; it is set for the duration when
|
|
388
|
+
unset (as emeans-haystack does), and not on ROCm builds. A dedicated lock serialises
|
|
389
|
+
deterministic fits without blocking the engine-loading lock that other fits use.
|
|
390
|
+
"""
|
|
391
|
+
if not enabled:
|
|
392
|
+
yield
|
|
393
|
+
return
|
|
394
|
+
with _deterministic_lock:
|
|
395
|
+
previous = torch.are_deterministic_algorithms_enabled()
|
|
396
|
+
previous_warn_only = torch.is_deterministic_algorithms_warn_only_enabled()
|
|
397
|
+
set_cublas = getattr(torch.version, "hip", None) is None and "CUBLAS_WORKSPACE_CONFIG" not in os.environ
|
|
398
|
+
if set_cublas:
|
|
399
|
+
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
|
|
400
|
+
torch.use_deterministic_algorithms(True)
|
|
401
|
+
try:
|
|
402
|
+
yield
|
|
403
|
+
finally:
|
|
404
|
+
torch.use_deterministic_algorithms(previous, warn_only=previous_warn_only)
|
|
405
|
+
if set_cublas:
|
|
406
|
+
os.environ.pop("CUBLAS_WORKSPACE_CONFIG", None)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _fit_gpu(
|
|
410
|
+
x: np.ndarray,
|
|
411
|
+
k: int,
|
|
412
|
+
*,
|
|
413
|
+
spherical: bool,
|
|
414
|
+
seed: int,
|
|
415
|
+
precision: str,
|
|
416
|
+
nepochs: float,
|
|
417
|
+
deterministic: bool,
|
|
418
|
+
init_centroids: np.ndarray | None = None,
|
|
419
|
+
) -> FitOutput:
|
|
420
|
+
"""GPU training, following emeans-haystack: FP32 through ``QuantizedEmeans(quantizer=None)``
|
|
421
|
+
(a plain ``Emeans`` casts FP32 input to BF16 by default), BF16/FP16 through ``Emeans``."""
|
|
422
|
+
torch = _torch()
|
|
423
|
+
engine = gpu_engine()
|
|
424
|
+
d = x.shape[1]
|
|
425
|
+
if precision == "fp16" and x.size and float(np.abs(x).max()) > float(np.finfo(np.float16).max):
|
|
426
|
+
warn_once("fp16-range", "embeddings exceed the fp16 range; training in fp32")
|
|
427
|
+
precision = "fp32"
|
|
428
|
+
common: dict[str, Any] = {
|
|
429
|
+
"nepochs": nepochs,
|
|
430
|
+
"seed": int(seed),
|
|
431
|
+
"spherical": spherical,
|
|
432
|
+
"capture_assignments": False,
|
|
433
|
+
"unused_threshold": unused_threshold(d),
|
|
434
|
+
}
|
|
435
|
+
if precision == "fp32":
|
|
436
|
+
em = engine.QuantizedEmeans(d, k, quantizer=None, **common)
|
|
437
|
+
else:
|
|
438
|
+
em = engine.Emeans(d, k, **common)
|
|
439
|
+
x_gpu = init_gpu = None
|
|
440
|
+
try:
|
|
441
|
+
start = time.perf_counter_ns()
|
|
442
|
+
x_gpu = torch.from_numpy(np.ascontiguousarray(x, dtype=np.float32)).to("cuda")
|
|
443
|
+
if precision == "fp16":
|
|
444
|
+
x_gpu = x_gpu.half()
|
|
445
|
+
if init_centroids is not None: # starting centroids stay FP32 whatever the data precision
|
|
446
|
+
init_gpu = torch.from_numpy(np.ascontiguousarray(init_centroids, dtype=np.float32)).to("cuda")
|
|
447
|
+
torch.cuda.synchronize()
|
|
448
|
+
transfer_ns = time.perf_counter_ns() - start
|
|
449
|
+
with _deterministic(torch, deterministic):
|
|
450
|
+
start = time.perf_counter_ns()
|
|
451
|
+
centroids, _ = em.train(x_gpu, init_centroids=init_gpu)
|
|
452
|
+
torch.cuda.synchronize()
|
|
453
|
+
train_ns = time.perf_counter_ns() - start
|
|
454
|
+
centroids_np = np.ascontiguousarray(centroids.detach().float().cpu().numpy(), dtype=np.float32)
|
|
455
|
+
recipe = dict(getattr(em, "recipe", None) or {})
|
|
456
|
+
labels = gpu_assign(centroids_np, x, spherical=spherical)
|
|
457
|
+
used = str(recipe.get("representation", precision)).removeprefix("torch.")
|
|
458
|
+
used = {"float32": "fp32", "bfloat16": "bf16", "float16": "fp16"}.get(used, used)
|
|
459
|
+
info = {
|
|
460
|
+
"train_ns": train_ns,
|
|
461
|
+
"transfer_ns": transfer_ns,
|
|
462
|
+
"assignment_backend": recipe.get("assignment_backend"),
|
|
463
|
+
"batch_size": recipe.get("batch_size"),
|
|
464
|
+
"nepochs": recipe.get("nepochs", nepochs),
|
|
465
|
+
"init": "k-means++" if init_centroids is not None else "sample",
|
|
466
|
+
"engine": gpu_engine_source(),
|
|
467
|
+
}
|
|
468
|
+
return FitOutput(centroids_np, labels, "gpu", used, info)
|
|
469
|
+
finally:
|
|
470
|
+
del x_gpu, init_gpu, em
|
|
471
|
+
with contextlib.suppress(Exception):
|
|
472
|
+
torch.cuda.empty_cache()
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def gpu_assign(centroids: np.ndarray, x: np.ndarray, *, spherical: bool, chunk: int = 65536) -> np.ndarray:
|
|
476
|
+
"""FP32 nearest-centroid labels on the GPU (reduced precision is never used for labels)."""
|
|
477
|
+
torch = _torch()
|
|
478
|
+
engine = gpu_engine()
|
|
479
|
+
k, d = centroids.shape
|
|
480
|
+
em = engine.QuantizedEmeans(d, k, spherical=spherical, quantizer=None, unused_threshold=unused_threshold(d))
|
|
481
|
+
em.centroids = torch.from_numpy(np.ascontiguousarray(centroids, dtype=np.float32)).to("cuda")
|
|
482
|
+
out = np.empty(len(x), dtype=np.int64)
|
|
483
|
+
for begin in range(0, len(x), chunk):
|
|
484
|
+
rows = torch.from_numpy(np.ascontiguousarray(x[begin : begin + chunk], dtype=np.float32)).to("cuda")
|
|
485
|
+
_, labels = em.assign(rows)
|
|
486
|
+
out[begin : begin + chunk] = labels.cpu().numpy().astype(np.int64)
|
|
487
|
+
del rows
|
|
488
|
+
return out
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def nearest_centroids(
|
|
492
|
+
x: np.ndarray,
|
|
493
|
+
centroids: np.ndarray,
|
|
494
|
+
m: int,
|
|
495
|
+
*,
|
|
496
|
+
backend: str = "cpu",
|
|
497
|
+
chunk: int = 16384,
|
|
498
|
+
metric: Literal["ip", "l2"] = "ip",
|
|
499
|
+
) -> np.ndarray:
|
|
500
|
+
"""Return the ``m`` nearest centroids of every row, FP32: largest inner product (unit-norm rows)
|
|
501
|
+
or, with ``metric="l2"``, smallest Euclidean distance."""
|
|
502
|
+
m = max(1, min(m, len(centroids)))
|
|
503
|
+
if backend == "gpu" and metric == "ip":
|
|
504
|
+
torch = _torch()
|
|
505
|
+
c = torch.from_numpy(np.ascontiguousarray(centroids, dtype=np.float32)).to("cuda")
|
|
506
|
+
out = np.empty((len(x), m), dtype=np.int64)
|
|
507
|
+
for begin in range(0, len(x), chunk):
|
|
508
|
+
rows = torch.from_numpy(np.ascontiguousarray(x[begin : begin + chunk], dtype=np.float32)).to("cuda")
|
|
509
|
+
out[begin : begin + chunk] = torch.topk(rows @ c.T, m, dim=1).indices.cpu().numpy()
|
|
510
|
+
return out
|
|
511
|
+
faiss = faiss_module()
|
|
512
|
+
_, idx = faiss.knn(
|
|
513
|
+
np.ascontiguousarray(x, dtype=np.float32),
|
|
514
|
+
np.ascontiguousarray(centroids, dtype=np.float32),
|
|
515
|
+
m,
|
|
516
|
+
metric=faiss.METRIC_INNER_PRODUCT if metric == "ip" else faiss.METRIC_L2,
|
|
517
|
+
)
|
|
518
|
+
return np.asarray(idx, dtype=np.int64)
|