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.
@@ -0,0 +1,1183 @@
1
+ # SPDX-FileCopyrightText: 2026-present ogaude <ogaude.code@proton.me>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """The only module that touches the e-means engine; PyTorch is imported only inside functions, when a GPU is used."""
6
+
7
+ import contextlib
8
+ import gc
9
+ import importlib
10
+ import importlib.metadata
11
+ import importlib.util
12
+ import os
13
+ import sys
14
+ import threading
15
+ import time
16
+ from collections.abc import Callable, Iterator, Mapping, Sequence
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any, Protocol
20
+
21
+ import numpy as np
22
+ from haystack import logging
23
+ from haystack.lazy_imports import LazyImport
24
+ from packaging.specifiers import SpecifierSet
25
+ from packaging.version import InvalidVersion, Version
26
+
27
+ with LazyImport("Run 'pip install \"faiss-cpu>=1.16.0\"'") as faiss_import:
28
+ import faiss
29
+ from faiss.contrib.e_means import NumpyEmeans
30
+
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ DEVICES: tuple[str, ...] = ("auto", "cpu", "cuda")
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class EnvInfo:
39
+ """What the current environment offers, detected without importing PyTorch."""
40
+
41
+ torch_importable: bool
42
+ gpu_available: bool
43
+ is_rocm: bool
44
+ emeans_rocm: bool # installed and inside the supported version range, so used as the GPU engine
45
+ device_name: str | None
46
+ torch_version: str | None
47
+ hip_version: str | None
48
+ cuda_version: str | None = None
49
+ arch: str | None = None
50
+ mismatch_reason: str | None = None
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class BackendChoice:
55
+ """The backend picked for one fit or assignment."""
56
+
57
+ name: str
58
+ device_name: str
59
+ fallback_reason: str | None # for a GPU choice: why a preferred GPU engine or rung was not used, else None
60
+ requested: str | None = None # the e-means `assignment_backend` of the chosen GPU rung; None means CPU
61
+ engine: str | None = None # GPU engine: None for `gpu_engine()`'s default, STOCK_ENGINE for the stock one
62
+
63
+
64
+ class GpuRung(Protocol):
65
+ """
66
+ One GPU backend option that `select_backend` can consider.
67
+
68
+ A rung may also carry two optional attributes, read with `getattr`: `applies`, a callable taking the `EnvInfo`
69
+ that returns `False` to skip the rung silently, and `engine`, the GPU engine it runs on (`STOCK_ENGINE` or
70
+ `None` for the default).
71
+ """
72
+
73
+ @property
74
+ def name(self) -> str:
75
+ """Short name of the rung, used in reports."""
76
+
77
+ @property
78
+ def requested(self) -> str:
79
+ """The e-means `assignment_backend` this rung asks for."""
80
+
81
+ def usable(self, env: EnvInfo) -> str | None:
82
+ """Return `None` when this backend can run in `env`, otherwise the reason it cannot."""
83
+
84
+
85
+ class Assigner(Protocol):
86
+ """Assigns embeddings to the nearest centroid of a saved model."""
87
+
88
+ def assign(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
89
+ """Return `(score, labels)`: float32 scores and int64 cluster indices for each row of `x`."""
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class FitResult:
94
+ """Centroids from a fit, plus the training report."""
95
+
96
+ centroids: np.ndarray
97
+ info: dict[str, Any]
98
+
99
+
100
+ def emeans_rocm_importable() -> bool:
101
+ """Return whether the `emeans_rocm` package is installed, without importing it (so without importing torch)."""
102
+ try:
103
+ return importlib.util.find_spec("emeans_rocm") is not None
104
+ except (ImportError, ValueError):
105
+ return False
106
+
107
+
108
+ # The emeans-rocm releases this integration is tested against. The README install line stays unpinned (D-03); a
109
+ # release outside this range is not used: the stock faiss engine runs instead and a warning names the version.
110
+ _EMEANS_ROCM_SUPPORTED = ">=0.2.5,<0.3"
111
+ _UNSUPPORTED_WARNED: set[str] = set() # reasons already logged in this process
112
+ _NATIVE_NOTES_WARNED: set[str] = set() # "Triton rung failed, using native FP32" notes already logged
113
+
114
+
115
+ def emeans_rocm_unsupported_reason() -> str | None:
116
+ """
117
+ Return why the installed `emeans_rocm` is not used, or `None` when it is usable or not installed.
118
+
119
+ A module that is not the installed distribution's copy (for example a source checkout on the path, with or
120
+ without a wheel installed) has no checkable version and is used as is.
121
+ """
122
+ if not emeans_rocm_importable():
123
+ return None
124
+ version = _dist_version("emeans-rocm")
125
+ if version is None or not _emeans_rocm_is_packaged():
126
+ return None
127
+ try:
128
+ supported = SpecifierSet(_EMEANS_ROCM_SUPPORTED).contains(Version(version), prereleases=True)
129
+ except InvalidVersion:
130
+ supported = False
131
+ if supported:
132
+ return None
133
+ return (
134
+ f"emeans-rocm {version} is outside the supported range {_EMEANS_ROCM_SUPPORTED}; "
135
+ "using the stock faiss e-means engine"
136
+ )
137
+
138
+
139
+ def emeans_rocm_enabled() -> bool:
140
+ """Return whether `emeans_rocm` is the GPU engine: installed and in the supported range. Warns once if not."""
141
+ if not emeans_rocm_importable():
142
+ return False
143
+ reason = emeans_rocm_unsupported_reason()
144
+ if reason is None:
145
+ return True
146
+ if reason not in _UNSUPPORTED_WARNED:
147
+ _UNSUPPORTED_WARNED.add(reason)
148
+ logger.warning("{reason}", reason=reason)
149
+ return False
150
+
151
+
152
+ STOCK_ENGINE = "faiss" # names the stock `faiss.contrib.e_means` engine in `BackendChoice.engine`
153
+
154
+
155
+ def gpu_engine(engine: str | None = None) -> Any:
156
+ """
157
+ Return the module that provides the GPU `Emeans` and `QuantizedEmeans` classes.
158
+
159
+ By default `emeans_rocm` is used on any GPU when it is importable and inside `_EMEANS_ROCM_SUPPORTED`, otherwise
160
+ `faiss.contrib.e_means`. With `engine=STOCK_ENGINE`, `faiss.contrib.e_means` is always used: that is the GPU
161
+ fallback when every emeans-rocm rung fails its probe. CPU paths must not call this: they use the stock
162
+ `NumpyEmeans`.
163
+
164
+ :param engine: `None` for the default choice, or `STOCK_ENGINE`.
165
+ """
166
+ if engine == STOCK_ENGINE:
167
+ return importlib.import_module("faiss.contrib.e_means")
168
+ if emeans_rocm_enabled():
169
+ return importlib.import_module("emeans_rocm")
170
+ return importlib.import_module("faiss.contrib.e_means")
171
+
172
+
173
+ def _dist_version(dist: str) -> str | None:
174
+ """Return the installed version of distribution `dist`, or `None` when it is not installed."""
175
+ try:
176
+ return importlib.metadata.version(dist)
177
+ except importlib.metadata.PackageNotFoundError:
178
+ return None
179
+
180
+
181
+ def _cpu_source() -> str:
182
+ """Return the engine label for CPU fits, e.g. `"faiss-cpu 1.16.0"`."""
183
+ return f"faiss-cpu {faiss.__version__}"
184
+
185
+
186
+ def _emeans_rocm_is_packaged() -> bool:
187
+ """
188
+ Return whether the `emeans_rocm` module found on the path is the copy installed by the `emeans-rocm` distribution.
189
+
190
+ `sys.path` (the working directory, `PYTHONPATH`) can put a source checkout ahead of the installed wheel, and an
191
+ editable install runs its checkout; then the distribution's version does not describe the code that runs.
192
+ """
193
+ try:
194
+ spec = importlib.util.find_spec("emeans_rocm")
195
+ dist = importlib.metadata.distribution("emeans-rocm")
196
+ except (ImportError, ValueError, importlib.metadata.PackageNotFoundError):
197
+ return False
198
+ origin = spec.origin if spec is not None else None
199
+ if not origin:
200
+ return False
201
+ try:
202
+ module_file = Path(origin).resolve()
203
+ return any(Path(str(dist.locate_file(entry))).resolve() == module_file for entry in dist.files or ())
204
+ except (OSError, ValueError):
205
+ return False
206
+
207
+
208
+ def detect_emeans_source() -> str:
209
+ """
210
+ Return the GPU engine label: `"emeans-rocm <version>"` when it is the GPU engine, else the faiss-cpu label.
211
+
212
+ When the imported `emeans_rocm` is not the installed distribution's copy, the label says so instead of
213
+ claiming the installed version: `"emeans-rocm <version> (source checkout)"` when a distribution is installed
214
+ but a checkout runs, `"emeans-rocm (unversioned source checkout)"` when none is installed. Paths are never
215
+ included.
216
+ """
217
+ if emeans_rocm_enabled():
218
+ version = _dist_version("emeans-rocm")
219
+ if version is None:
220
+ return "emeans-rocm (unversioned source checkout)"
221
+ if not _emeans_rocm_is_packaged():
222
+ return f"emeans-rocm {version} (source checkout)"
223
+ return f"emeans-rocm {version}"
224
+ return _cpu_source()
225
+
226
+
227
+ def _engine_source(engine: str | None) -> str:
228
+ """Return the label of the GPU engine `engine` (see `gpu_engine`)."""
229
+ return _cpu_source() if engine == STOCK_ENGINE else detect_emeans_source()
230
+
231
+
232
+ @dataclass(frozen=True)
233
+ class ProbeResult:
234
+ """Outcome of the tiny training run that checks a GPU rung works."""
235
+
236
+ ok: bool
237
+ assignment_backend: str | None
238
+ reason: str | None
239
+
240
+
241
+ ProbeFn = Callable[[str, str, str], ProbeResult] # (rung name, requested assignment backend, precision)
242
+
243
+ _PROBE_CACHE: dict[tuple[str, str, str], ProbeResult] = {} # (rung name, requested, precision) -> outcome
244
+ _PROBE_LOCK = threading.Lock() # guards the two dicts only; never held while a probe runs
245
+ _PROBE_KEY_LOCKS: dict[tuple[str, str, str], threading.Lock] = {} # serialises probes of one key
246
+ _TRANSIENT_MARKERS = ("out of memory", "busy")
247
+
248
+
249
+ def _is_transient_failure(reason: str | None) -> bool:
250
+ """Return whether a probe failure looks transient (memory pressure, busy device), so it must not be memoised."""
251
+ text = (reason or "").lower()
252
+ return any(marker in text for marker in _TRANSIENT_MARKERS)
253
+
254
+
255
+ _PROBE_ROWS = 1024
256
+ _PROBE_DIM = 64
257
+ _PROBE_K = 16
258
+
259
+ # Mirror faiss.contrib.e_means.base: stock faiss 1.16 and emeans-rocm 0.2.5 resolve `unused_threshold=None` to
260
+ # these values (mass-based revival); emeans-rocm 0.2.6 resolves `None` to cost-based revival instead, so the value
261
+ # is always passed explicitly.
262
+ _UNUSED_THRESHOLD = 0.1
263
+ _NO_REVIVAL_MAX_D = 2
264
+
265
+
266
+ def _unused_threshold(d: int) -> float:
267
+ """
268
+ Return the revival threshold passed to every e-means engine constructor.
269
+
270
+ :param d: Embedding dimension.
271
+ :returns: `0.0` (no revival) for `d <= 2`, otherwise `0.1` (mass-based revival).
272
+ """
273
+ return 0.0 if d <= _NO_REVIVAL_MAX_D else _UNUSED_THRESHOLD
274
+
275
+
276
+ def _run_probe(requested: str, precision: str, engine: str | None = None) -> ProbeResult:
277
+ # Both spherical modes are probed: e-means takes mode-dependent code paths, and the verdict is reused for
278
+ # every later fit and assignment on this rung, whatever its mode.
279
+ torch = importlib.import_module("torch")
280
+ x = None
281
+ em = None
282
+ centroids = None
283
+ failed = True
284
+ try:
285
+ # Inside the try: a broken engine install (e.g. a failing `import emeans_rocm`) is a recorded probe
286
+ # failure, so `device="auto"` falls back to the next rung or the CPU instead of crashing.
287
+ e_means = gpu_engine(engine)
288
+ label = ""
289
+ for spherical in (True, False):
290
+ generator = torch.Generator(device="cuda")
291
+ generator.manual_seed(0)
292
+ x = torch.randn(_PROBE_ROWS, _PROBE_DIM, device="cuda", generator=generator)
293
+ if spherical:
294
+ x = x / x.norm(dim=1, keepdim=True)
295
+ kwargs: dict[str, Any] = {
296
+ "nepochs": 1,
297
+ "seed": 0,
298
+ "spherical": spherical,
299
+ "capture_assignments": False,
300
+ "assignment_backend": requested,
301
+ "unused_threshold": _unused_threshold(_PROBE_DIM),
302
+ }
303
+ if precision == "fp32":
304
+ em = e_means.QuantizedEmeans(_PROBE_DIM, _PROBE_K, quantizer=None, **kwargs)
305
+ else:
306
+ em = e_means.Emeans(_PROBE_DIM, _PROBE_K, **kwargs)
307
+ if precision == "fp16":
308
+ x = x.half()
309
+ centroids, _ = em.train(x)
310
+ if tuple(centroids.shape) != (_PROBE_K, _PROBE_DIM) or not bool(torch.isfinite(centroids).all()):
311
+ mode = "spherical" if spherical else "non-spherical"
312
+ return ProbeResult(False, None, f"the {mode} probe produced non-finite or misshapen centroids")
313
+ if spherical:
314
+ label = str(em.recipe["assignment_backend"])
315
+ failed = False
316
+ return ProbeResult(True, label, None)
317
+ except torch.OutOfMemoryError:
318
+ raise
319
+ except Exception as error:
320
+ return ProbeResult(False, None, f"{type(error).__name__}: {error}")
321
+ finally:
322
+ del x, em, centroids
323
+ if failed:
324
+ # A failed engine's traceback frames can keep its GPU tensors alive in reference cycles; collect them so
325
+ # the next rung (possibly another engine) starts with that memory released.
326
+ gc.collect()
327
+ torch.cuda.empty_cache()
328
+
329
+
330
+ def probe(rung_name: str, requested: str, precision: str, engine: str | None = None) -> ProbeResult:
331
+ """
332
+ Run the tiny training probe once per process for each rung, assignment backend and precision; remember it.
333
+
334
+ :param rung_name: Name of the rung being probed.
335
+ :param requested: The e-means `assignment_backend` to probe.
336
+ :param precision: `"fp32"`, `"bf16"` or `"fp16"`.
337
+ :param engine: GPU engine to probe (see `gpu_engine`); rungs on different engines have different names, so the
338
+ memo key stays `(rung_name, requested, precision)`.
339
+ :raises torch.OutOfMemoryError: If the GPU is out of memory; this is never remembered.
340
+
341
+ Probes for the same key run once at a time; probes for different keys do not wait for each other. A failure
342
+ whose reason mentions running out of memory or a busy device is treated as transient and is not remembered.
343
+ """
344
+ key = (rung_name, requested, precision)
345
+ with _PROBE_LOCK:
346
+ cached = _PROBE_CACHE.get(key)
347
+ if cached is not None:
348
+ return cached
349
+ key_lock = _PROBE_KEY_LOCKS.setdefault(key, threading.Lock())
350
+ with key_lock:
351
+ with _PROBE_LOCK:
352
+ cached = _PROBE_CACHE.get(key)
353
+ if cached is not None:
354
+ return cached # another thread probed this key while we waited
355
+ result = _run_probe(requested, precision) if engine is None else _run_probe(requested, precision, engine)
356
+ if result.ok or not _is_transient_failure(result.reason):
357
+ with _PROBE_LOCK:
358
+ _PROBE_CACHE[key] = result
359
+ logger.debug(
360
+ "GPU probe for rung {rung} at {precision}: ok={ok} ({reason})",
361
+ rung=rung_name,
362
+ precision=precision,
363
+ ok=result.ok,
364
+ reason=result.reason,
365
+ )
366
+ return result
367
+
368
+
369
+ def clear_probe_cache() -> None:
370
+ """Forget every remembered probe outcome."""
371
+ with _PROBE_LOCK:
372
+ _PROBE_CACHE.clear()
373
+ _UNSUPPORTED_WARNED.clear()
374
+ _NATIVE_NOTES_WARNED.clear()
375
+
376
+
377
+ def _applies_always(_env: EnvInfo) -> bool:
378
+ return True
379
+
380
+
381
+ @dataclass(frozen=True)
382
+ class _Attempt:
383
+ name: str
384
+ requested: str
385
+ gate: Callable[[EnvInfo], str | None]
386
+ probe_fn: ProbeFn
387
+ engine: str | None = None
388
+ applies: Callable[[EnvInfo], bool] = _applies_always # False: skipped without a reason (nothing to report)
389
+
390
+ def usable(self, env: EnvInfo) -> str | None:
391
+ reason = self.gate(env)
392
+ if reason is not None:
393
+ return reason
394
+ result = self.probe_fn(self.name, self.requested, "fp32")
395
+ return None if result.ok else result.reason
396
+
397
+
398
+ def _needs_emeans_rocm(env: EnvInfo) -> str | None:
399
+ if env.is_rocm and env.emeans_rocm:
400
+ return None
401
+ unsupported = emeans_rocm_unsupported_reason()
402
+ if unsupported is not None:
403
+ return unsupported
404
+ return "needs the emeans-rocm package (pip install emeans-rocm) on a ROCm build of PyTorch"
405
+
406
+
407
+ def _needs_nvidia(env: EnvInfo) -> str | None:
408
+ return "needs an NVIDIA GPU" if env.is_rocm else None
409
+
410
+
411
+ def _always(_env: EnvInfo) -> str | None:
412
+ return None
413
+
414
+
415
+ def _emeans_rocm_is_engine(env: EnvInfo) -> bool:
416
+ return env.emeans_rocm
417
+
418
+
419
+ def _stock_probe(rung_name: str, requested: str, precision: str) -> ProbeResult:
420
+ return probe(rung_name, requested, precision, engine=STOCK_ENGINE)
421
+
422
+
423
+ STOCK_RUNG = "native-stock"
424
+ ROCM_TRITON_RUNG = "rocm-triton"
425
+
426
+
427
+ def default_rungs(probe_fn: ProbeFn | None = None) -> tuple[GpuRung, ...]:
428
+ """
429
+ Return the GPU ladder in the order it is tried.
430
+
431
+ The first four rungs use `gpu_engine()`'s default engine (emeans-rocm when it is enabled). The last one,
432
+ `native-stock`, runs the stock `faiss.contrib.e_means` native path on the GPU and is tried only when
433
+ emeans-rocm is the GPU engine, so a GPU on which every emeans-rocm rung fails still runs before the CPU.
434
+
435
+ :param probe_fn: Probe to use for every rung; the memoised `probe` (on the rung's engine) when omitted.
436
+ """
437
+ fn = probe_fn if probe_fn is not None else probe
438
+ stock_fn = probe_fn if probe_fn is not None else _stock_probe
439
+ return (
440
+ _Attempt(ROCM_TRITON_RUNG, "auto", _needs_emeans_rocm, fn),
441
+ _Attempt("nvidia-auto", "auto", _needs_nvidia, fn),
442
+ _Attempt("nvidia-triton", "triton", _needs_nvidia, fn),
443
+ _Attempt("native", "native", _always, fn),
444
+ _Attempt(STOCK_RUNG, "native", _always, stock_fn, engine=STOCK_ENGINE, applies=_emeans_rocm_is_engine),
445
+ )
446
+
447
+
448
+ def _device_nodes() -> tuple[bool, bool]:
449
+ """Return `(amd_node, nvidia_node)`: whether a GPU device node exists, checked without importing PyTorch."""
450
+ return (
451
+ os.path.exists("/dev/kfd"),
452
+ os.path.exists("/dev/nvidia0") or os.path.exists("/dev/nvidiactl"),
453
+ )
454
+
455
+
456
+ def mismatch_reason(
457
+ *,
458
+ amd_node: bool,
459
+ nvidia_node: bool,
460
+ torch_version: str | None,
461
+ hip_version: str | None,
462
+ cuda_version: str | None,
463
+ gpu_available: bool,
464
+ ) -> str | None:
465
+ """
466
+ Explain why a GPU is present but PyTorch cannot use it because the installed build is the wrong one.
467
+
468
+ :param amd_node: Whether `/dev/kfd` exists.
469
+ :param nvidia_node: Whether an NVIDIA device node exists.
470
+ :param torch_version: Installed PyTorch version.
471
+ :param hip_version: `torch.version.hip` (`None` for builds without ROCm).
472
+ :param cuda_version: `torch.version.cuda` (`None` for builds without CUDA).
473
+ :param gpu_available: `torch.cuda.is_available()`.
474
+ :returns: The explanation, or `None` when there is no mismatch.
475
+ """
476
+ if gpu_available:
477
+ return None
478
+ if nvidia_node and not amd_node and hip_version is not None:
479
+ return (
480
+ f"NVIDIA GPU found but PyTorch {torch_version} is a ROCm build; "
481
+ "install a CUDA build of PyTorch, for example with the [gpu] extra"
482
+ )
483
+ # NVIDIA first: an AMD APU or iGPU exposes /dev/kfd next to an NVIDIA dGPU even when ROCm does not support it.
484
+ if nvidia_node and cuda_version is None and hip_version is None:
485
+ return (
486
+ f"NVIDIA GPU found but PyTorch {torch_version} is a CPU-only build; "
487
+ "install a CUDA build of PyTorch, for example with the [gpu] extra"
488
+ )
489
+ if amd_node and hip_version is None and not (nvidia_node and cuda_version is not None):
490
+ return (
491
+ f"AMD GPU found (/dev/kfd) but PyTorch {torch_version} is not a ROCm build; "
492
+ "if this GPU is supported by ROCm, install the ROCm build of PyTorch and do not use the [gpu] extra"
493
+ )
494
+ return None
495
+
496
+
497
+ def _visible_devices_clause(name: str, value: str) -> str:
498
+ return f"{name}={value!r} is set and may hide it; unset it, or use device='cpu' to run on CPU"
499
+
500
+
501
+ def hidden_gpu_reason(
502
+ *,
503
+ amd_node: bool,
504
+ nvidia_node: bool,
505
+ torch_version: str | None,
506
+ hip_version: str | None,
507
+ cuda_version: str | None,
508
+ gpu_available: bool,
509
+ environ: Mapping[str, str],
510
+ ) -> str | None:
511
+ """
512
+ Explain why a GPU is present and PyTorch has the matching build but still sees no GPU.
513
+
514
+ :param amd_node: Whether `/dev/kfd` exists.
515
+ :param nvidia_node: Whether an NVIDIA device node exists.
516
+ :param torch_version: Installed PyTorch version.
517
+ :param hip_version: `torch.version.hip` (`None` for builds without ROCm).
518
+ :param cuda_version: `torch.version.cuda` (`None` for builds without CUDA).
519
+ :param gpu_available: `torch.cuda.is_available()`.
520
+ :param environ: Process environment, scanned for `*_VISIBLE_DEVICES` variables relevant to the vendor.
521
+ :returns: The explanation, or `None` when PyTorch sees a GPU or the build does not match the device.
522
+ """
523
+ if gpu_available:
524
+ return None
525
+ if amd_node and hip_version is not None:
526
+ text = f"AMD GPU found (/dev/kfd) and PyTorch {torch_version} is a ROCm build, but PyTorch sees no GPU; "
527
+ for name in ("ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES"):
528
+ if name in environ:
529
+ return text + _visible_devices_clause(name, environ[name])
530
+ return text + (
531
+ "check that the amdgpu driver is loaded and that this user can open /dev/kfd and /dev/dri "
532
+ "(render and video groups)"
533
+ )
534
+ if nvidia_node and cuda_version is not None:
535
+ text = f"NVIDIA GPU found and PyTorch {torch_version} is a CUDA {cuda_version} build, but PyTorch sees no GPU; "
536
+ if "CUDA_VISIBLE_DEVICES" in environ:
537
+ return text + _visible_devices_clause("CUDA_VISIBLE_DEVICES", environ["CUDA_VISIBLE_DEVICES"])
538
+ return text + (
539
+ f"check that the NVIDIA driver is loaded and supports CUDA {cuda_version}, "
540
+ "and that this user can open /dev/nvidia*"
541
+ )
542
+ return None
543
+
544
+
545
+ def detect_environment() -> EnvInfo:
546
+ """Inspect the environment; PyTorch is imported only when it is installed."""
547
+ emeans_rocm = emeans_rocm_enabled()
548
+ try:
549
+ torch_findable = importlib.util.find_spec("torch") is not None
550
+ except (ImportError, ValueError):
551
+ torch_findable = False
552
+ unavailable = EnvInfo(False, False, False, emeans_rocm, None, None, None)
553
+ if not torch_findable:
554
+ return unavailable
555
+ try:
556
+ torch = importlib.import_module("torch")
557
+ except Exception as error:
558
+ # find_spec found torch, so it is installed and any import failure means a broken install. A ROCm/CUDA build
559
+ # whose shared libraries cannot be loaded usually raises ImportError, sometimes OSError or RuntimeError.
560
+ reason = f"PyTorch is installed but could not be imported: {type(error).__name__}: {error}"
561
+ return EnvInfo(False, False, False, emeans_rocm, None, None, None, mismatch_reason=reason)
562
+ hip_version = torch.version.hip
563
+ device_name: str | None = None
564
+ arch: str | None = None
565
+ init_error: str | None = None
566
+ try:
567
+ gpu_available = bool(torch.cuda.is_available())
568
+ if gpu_available:
569
+ device_name = str(torch.cuda.get_device_name(0))
570
+ if hip_version is not None:
571
+ arch = getattr(torch.cuda.get_device_properties(0), "gcnArchName", None)
572
+ else:
573
+ major, minor = torch.cuda.get_device_capability(0)
574
+ arch = f"sm_{major}{minor}"
575
+ except (OSError, RuntimeError) as error:
576
+ gpu_available, device_name, arch = False, None, None
577
+ init_error = f"PyTorch could not initialise the GPU: {type(error).__name__}: {error}"
578
+ amd_node, nvidia_node = _device_nodes()
579
+ probe_args = {
580
+ "amd_node": amd_node,
581
+ "nvidia_node": nvidia_node,
582
+ "torch_version": str(torch.__version__),
583
+ "hip_version": hip_version,
584
+ "cuda_version": torch.version.cuda,
585
+ "gpu_available": gpu_available,
586
+ }
587
+ mismatch = init_error or mismatch_reason(**probe_args) or hidden_gpu_reason(**probe_args, environ=os.environ)
588
+ return EnvInfo(
589
+ torch_importable=True,
590
+ gpu_available=gpu_available,
591
+ is_rocm=hip_version is not None,
592
+ emeans_rocm=emeans_rocm,
593
+ device_name=device_name,
594
+ torch_version=str(torch.__version__),
595
+ hip_version=hip_version,
596
+ cuda_version=torch.version.cuda,
597
+ arch=arch,
598
+ mismatch_reason=mismatch,
599
+ )
600
+
601
+
602
+ def _is_out_of_memory(error: BaseException) -> bool:
603
+ """Return whether `error` is a PyTorch out-of-memory error, without importing PyTorch (it may be absent)."""
604
+ torch_module = sys.modules.get("torch")
605
+ oom_type = getattr(torch_module, "OutOfMemoryError", None)
606
+ return isinstance(oom_type, type) and isinstance(error, oom_type)
607
+
608
+
609
+ def select_backend(
610
+ *,
611
+ device: str,
612
+ n: int,
613
+ k: int,
614
+ gpu_threshold: float,
615
+ env: EnvInfo | None = None,
616
+ gpu_rungs: Sequence[GpuRung] | None = None,
617
+ warn: bool = True,
618
+ ) -> BackendChoice:
619
+ """
620
+ Pick the backend for a run.
621
+
622
+ A GPU rung is accepted when a tiny training probe (both spherical modes, fixed small `d` and `k`, without
623
+ deterministic mode) succeeds on it, once per process. The probe does not cover every shape or mode, so a rung
624
+ that passes it can still fail on the real data; such an error propagates and the next rung is not tried.
625
+ With `device="auto"`, a GPU out-of-memory error during a rung's probe counts as that rung failing (it is not
626
+ remembered, so later runs probe again); with `device="cuda"` it propagates. Errors from the real fit propagate.
627
+
628
+ When emeans-rocm is the GPU engine and every one of its rungs fails, the stock `faiss.contrib.e_means` native
629
+ rung is tried on the GPU before the CPU (both for `"auto"` and `"cuda"`); the choice then carries
630
+ `engine=STOCK_ENGINE` and a `fallback_reason` naming the failed rungs, and a warning is logged. On ROCm with
631
+ emeans-rocm enabled, a `native` choice made because the `rocm-triton` probe failed carries that probe failure
632
+ in `fallback_reason`, and a warning naming it is logged once per process.
633
+
634
+ :param device: `"cpu"`, `"cuda"` or `"auto"`.
635
+ :param n: Number of embeddings.
636
+ :param k: Number of clusters.
637
+ :param gpu_threshold: With `device="auto"`, a GPU is considered only when `n * k` reaches this value.
638
+ :param env: Detected environment; detected here when omitted and a GPU is considered.
639
+ :param gpu_rungs: GPU backends to try in order; `None` means the default ladder.
640
+ :param warn: Log fallback warnings. Pass `False` when the same run has already logged them, for example
641
+ after an auto-fit, so each run warns once.
642
+ :raises RuntimeError: If `device="cuda"` and no GPU backend is usable.
643
+ :raises ValueError: If `device` is not a known value.
644
+ :raises torch.OutOfMemoryError: If `device="cuda"` and a rung's probe runs out of GPU memory.
645
+ """
646
+ if device not in DEVICES:
647
+ msg = f"device must be 'auto', 'cpu' or 'cuda', got {device!r}"
648
+ raise ValueError(msg)
649
+ if device == "cpu":
650
+ return BackendChoice("cpu", "cpu", None)
651
+ if device == "auto" and n * k < gpu_threshold:
652
+ return BackendChoice("cpu", "cpu", None)
653
+ environment = env if env is not None else detect_environment()
654
+ should_warn = environment.mismatch_reason is not None
655
+ if environment.mismatch_reason is not None:
656
+ detail = environment.mismatch_reason
657
+ elif not environment.torch_importable:
658
+ detail = "PyTorch is not installed"
659
+ elif not environment.gpu_available:
660
+ detail = "no GPU visible to PyTorch"
661
+ else:
662
+ rungs = gpu_rungs if gpu_rungs is not None else default_rungs()
663
+ reasons: list[str] = []
664
+ failed: dict[str, str] = {} # rung name -> why it was not usable
665
+ oom_rungs: list[str] = []
666
+ for rung in rungs:
667
+ applies = getattr(rung, "applies", None)
668
+ if applies is not None and not applies(environment):
669
+ continue
670
+ try:
671
+ reason = rung.usable(environment)
672
+ except Exception as error:
673
+ if device != "auto" or not _is_out_of_memory(error):
674
+ raise
675
+ reason = f"probe ran out of GPU memory ({type(error).__name__}: {error})"
676
+ oom_rungs.append(rung.name)
677
+ if reason is None:
678
+ if oom_rungs and warn:
679
+ logger.warning(
680
+ "GPU probe ran out of memory on {oom}; using {rung}", oom=", ".join(oom_rungs), rung=rung.name
681
+ )
682
+ engine = getattr(rung, "engine", None)
683
+ note = None
684
+ if engine == STOCK_ENGINE and reasons:
685
+ note = (
686
+ f"no emeans-rocm GPU backend usable: {'; '.join(reasons)}; "
687
+ f"using the stock faiss e-means engine on the GPU ({rung.name})"
688
+ )
689
+ if warn:
690
+ logger.warning("{reason}", reason=note)
691
+ elif _triton_rejected_for_native(environment, rung.requested, failed):
692
+ note = (
693
+ f"emeans-rocm is installed but its Triton rung failed the GPU probe "
694
+ f"({failed[ROCM_TRITON_RUNG]}); using native FP32 ({rung.name})"
695
+ )
696
+ if warn and note not in _NATIVE_NOTES_WARNED:
697
+ _NATIVE_NOTES_WARNED.add(note)
698
+ logger.warning("{reason}", reason=note)
699
+ return BackendChoice(
700
+ rung.name, environment.device_name or "cuda", note, requested=rung.requested, engine=engine
701
+ )
702
+ reasons.append(f"{rung.name}: {reason}")
703
+ failed[rung.name] = reason
704
+ detail = "; ".join(reasons) or "no GPU backend registered"
705
+ should_warn = True
706
+ if device == "cuda":
707
+ msg = f"device='cuda' requested but no GPU backend usable: {detail}"
708
+ raise RuntimeError(msg)
709
+ fallback_reason = f"no GPU backend usable: {detail}"
710
+ if should_warn and warn:
711
+ logger.warning("{reason}", reason=fallback_reason)
712
+ return BackendChoice("cpu", "cpu", fallback_reason)
713
+
714
+
715
+ def _triton_rejected_for_native(env: EnvInfo, requested: str, failed: Mapping[str, str]) -> bool:
716
+ """Return whether a `native` choice on ROCm is only made because emeans-rocm's Triton rung failed its probe."""
717
+ # With is_rocm and emeans_rocm the rocm-triton gate passes, so a recorded failure is a probe failure.
718
+ return requested == "native" and env.is_rocm and env.emeans_rocm and ROCM_TRITON_RUNG in failed
719
+
720
+
721
+ _EMEANS_ROCM_HINT = "(pip install emeans-rocm for Triton kernels and BF16/FP16 on RX 9000 GPUs)"
722
+
723
+
724
+ def _backend_hint(*, is_rocm: bool, assignment_backend: str, emeans_rocm: bool) -> str | None:
725
+ """Return a one-line hint for AMD users running the native rung without emeans-rocm, otherwise `None`."""
726
+ if is_rocm and assignment_backend == "native" and not emeans_rocm:
727
+ return _EMEANS_ROCM_HINT
728
+ return None
729
+
730
+
731
+ _BACKEND_NAMES = {"native": "gpu-pytorch", "triton": "gpu-triton", "cute": "gpu-cute"}
732
+ _PRECISION_NAMES = {"float32": "fp32", "bfloat16": "bf16", "float16": "fp16"}
733
+
734
+
735
+ _DETERMINISTIC_LOCK = threading.Lock()
736
+
737
+
738
+ @contextlib.contextmanager
739
+ def _deterministic(torch: Any, enabled: bool) -> Iterator[None]:
740
+ """
741
+ Run the body with PyTorch's deterministic algorithms on, then restore the previous setting.
742
+
743
+ The setting is process-global, so deterministic bodies are serialised with a lock. On CUDA builds,
744
+ `CUBLAS_WORKSPACE_CONFIG` is set for the body only when unset and removed afterwards; PyTorch may already have
745
+ chosen its cuBLAS workspace by then, so users who need guaranteed reproducibility on NVIDIA should export it
746
+ before starting the process.
747
+
748
+ Known limitation: the lock serialises deterministic bodies against each other only. While one holds it, the
749
+ process-global setting and the temporary `CUBLAS_WORKSPACE_CONFIG` also apply to GPU work in other threads
750
+ (a non-deterministic fit, `_GpuAssigner.assign`, `_run_probe`). Taking the lock around that work as well would
751
+ serialise all GPU work in the process, so it is documented instead.
752
+ """
753
+ if not enabled:
754
+ yield
755
+ return
756
+ with _DETERMINISTIC_LOCK:
757
+ previous = torch.are_deterministic_algorithms_enabled()
758
+ warn_only = torch.is_deterministic_algorithms_warn_only_enabled()
759
+ set_env = torch.version.hip is None and "CUBLAS_WORKSPACE_CONFIG" not in os.environ
760
+ if set_env:
761
+ os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
762
+ try:
763
+ torch.use_deterministic_algorithms(True)
764
+ yield
765
+ finally:
766
+ torch.use_deterministic_algorithms(previous, warn_only=warn_only)
767
+ if set_env:
768
+ os.environ.pop("CUBLAS_WORKSPACE_CONFIG", None)
769
+
770
+
771
+ def fit_model(
772
+ x: np.ndarray,
773
+ *,
774
+ k: int,
775
+ spherical: bool,
776
+ nepochs: float,
777
+ seed: int,
778
+ max_points_per_centroid: int | None,
779
+ backend: BackendChoice,
780
+ precision: str = "fp32",
781
+ deterministic: bool = False,
782
+ allow_cpu_fallback: bool = False,
783
+ init_centroids: np.ndarray | None = None,
784
+ ) -> FitResult:
785
+ """
786
+ Train e-means on `x` and return the centroids with a report of what ran.
787
+
788
+ :param x: float32 matrix of shape `(n, d)`; already normalised when `spherical` is true.
789
+ :param k: Number of clusters.
790
+ :param spherical: Cluster by cosine similarity.
791
+ :param nepochs: Passes over the data.
792
+ :param seed: Random seed.
793
+ :param max_points_per_centroid: Train on a random subset when `n` exceeds this many points per centroid.
794
+ :param backend: The backend chosen by `select_backend`.
795
+ :param precision: Requested precision. The CPU backend always runs FP32 and warns once for `bf16` or `fp16`.
796
+ :param deterministic: Request deterministic algorithms on the GPU; CPU training is deterministic already.
797
+ The setting is process-wide while the fit trains, so GPU work in other threads runs with it too.
798
+ :param allow_cpu_fallback: With True, a GPU fit whose memory estimate exceeds free GPU memory runs on the CPU
799
+ backend instead; the fitter passes True for `device="auto"`.
800
+ :param init_centroids: Optional starting centroids of shape `(k, d)`, float32 (private; used by the benchmarks).
801
+ Default None keeps e-means' own seeded init.
802
+ """
803
+ faiss_import.check()
804
+ if backend.requested is not None:
805
+ return _fit_gpu(
806
+ x,
807
+ k=k,
808
+ spherical=spherical,
809
+ nepochs=nepochs,
810
+ seed=seed,
811
+ max_points_per_centroid=max_points_per_centroid,
812
+ backend=backend,
813
+ precision=precision,
814
+ deterministic=deterministic,
815
+ allow_cpu_fallback=allow_cpu_fallback,
816
+ init_centroids=init_centroids,
817
+ )
818
+ return _fit_cpu(
819
+ x,
820
+ k=k,
821
+ spherical=spherical,
822
+ nepochs=nepochs,
823
+ seed=seed,
824
+ max_points_per_centroid=max_points_per_centroid,
825
+ backend=backend,
826
+ precision=precision,
827
+ init_centroids=init_centroids,
828
+ )
829
+
830
+
831
+ def _fit_cpu(
832
+ x: np.ndarray,
833
+ *,
834
+ k: int,
835
+ spherical: bool,
836
+ nepochs: float,
837
+ seed: int,
838
+ max_points_per_centroid: int | None,
839
+ backend: BackendChoice,
840
+ precision: str,
841
+ init_centroids: np.ndarray | None = None,
842
+ ) -> FitResult:
843
+ if precision in ("bf16", "fp16"):
844
+ logger.warning("precision '{precision}' is not supported on the CPU backend; using fp32", precision=precision)
845
+ n, d = x.shape
846
+ em = NumpyEmeans(
847
+ d,
848
+ k,
849
+ nepochs=nepochs,
850
+ seed=seed,
851
+ spherical=spherical,
852
+ max_points_per_centroid=max_points_per_centroid,
853
+ capture_assignments=False,
854
+ unused_threshold=_unused_threshold(d),
855
+ )
856
+ start = time.perf_counter()
857
+ centroids, _ = em.train(x, init_centroids=init_centroids)
858
+ train_seconds = time.perf_counter() - start
859
+ recipe = em.recipe
860
+ iteration_stats = em.iteration_stats
861
+ imbalance = float(iteration_stats[-1].get("imbalance_factor", float("nan"))) if iteration_stats else float("nan")
862
+ info: dict[str, Any] = {
863
+ "backend": backend.name, # the backend that ran, not e-means' own "faiss" label
864
+ "device_name": backend.device_name,
865
+ "precision_used": "fp32",
866
+ "assignment_backend": str(recipe.get("assignment_backend", recipe["backend"])),
867
+ "recipe": recipe,
868
+ "n_train": _n_train(n, k, max_points_per_centroid),
869
+ "train_seconds": float(train_seconds),
870
+ "emeans_source": _cpu_source(),
871
+ "faiss_version": str(faiss.__version__),
872
+ "nepochs": float(recipe["nepochs"]),
873
+ "batch_size": int(recipe["batch_size"]),
874
+ "alpha0": float(recipe["alpha0"]),
875
+ "n_splits": int(em.n_splits),
876
+ "imbalance": imbalance,
877
+ "unused_threshold": _unused_threshold(d),
878
+ "backend_hint": None,
879
+ "memory_estimate_bytes": None,
880
+ "fallback_reason": backend.fallback_reason,
881
+ }
882
+ return FitResult(centroids=np.ascontiguousarray(centroids, dtype=np.float32), info=info)
883
+
884
+
885
+ def resolve_precision(choice: BackendChoice, precision: str, probe_fn: ProbeFn | None = None) -> tuple[str, str | None]:
886
+ """
887
+ Decide the precision a GPU fit trains in, using a memoised probe at that precision on the chosen rung.
888
+
889
+ :param choice: The chosen GPU backend; its `requested` assignment backend is what gets probed.
890
+ :param precision: `"auto"`, `"fp32"`, `"bf16"` or `"fp16"` as requested by the user.
891
+ :param probe_fn: Probe to run; defaults to the memoised `probe`.
892
+ :returns: The precision to train with (`"fp32"`, `"bf16"` or `"fp16"`) and a warning text, or None when
893
+ nothing needs reporting. `"auto"` falls back to FP32 silently; an explicit `"bf16"`/`"fp16"` that the rung
894
+ cannot run falls back to FP32 with a warning.
895
+ :raises ValueError: If `choice` is a CPU choice.
896
+ """
897
+ if choice.requested is None:
898
+ msg = "resolve_precision applies to GPU backends only"
899
+ raise ValueError(msg)
900
+ if precision == "fp32":
901
+ return "fp32", None
902
+ if choice.requested == "native":
903
+ # The native rung is the FP32 fallback by definition; explicit native assignment would accept BF16/FP16
904
+ # tensors, but its reduced-precision behaviour is not part of the contract.
905
+ return "fp32", None if precision == "auto" else _unsupported(precision, choice)
906
+ run_probe = probe_fn or probe
907
+ wanted = "bf16" if precision == "auto" else precision
908
+ if run_probe(choice.name, choice.requested, wanted).ok:
909
+ return wanted, None
910
+ if precision == "auto":
911
+ return "fp32", None
912
+ return "fp32", _unsupported(precision, choice)
913
+
914
+
915
+ def _unsupported(precision: str, choice: BackendChoice) -> str:
916
+ return f"precision '{precision}' is not supported on the {choice.name} GPU backend; using fp32"
917
+
918
+
919
+ def _n_train(n: int, k: int, max_points_per_centroid: int | None) -> int:
920
+ return int(max_points_per_centroid * k if max_points_per_centroid and n > max_points_per_centroid * k else n)
921
+
922
+
923
+ class _FallbackToCpu(Exception): # noqa: N818
924
+ """Raised inside `_fit_gpu` to leave the GPU block, release its memory, and fit on the CPU instead."""
925
+
926
+
927
+ def _gib(size: int) -> str:
928
+ return f"{size / 2**30:.2f} GiB"
929
+
930
+
931
+ def _memory_preflight(
932
+ e_means: Any, torch: Any, em: Any, *, n: int, dtype: Any, subsampled: bool
933
+ ) -> tuple[int | None, int | None]:
934
+ """
935
+ Ask e-means how much GPU memory training needs and how much is free.
936
+
937
+ :returns: `(estimate, free)` in bytes, or `(None, None)` when e-means has no `memory_estimate` (upstream
938
+ faiss), when training runs on a subset the estimate does not cover, or when the estimate fails: the
939
+ pre-flight never breaks a fit that would have run.
940
+ """
941
+ estimate_fn = getattr(e_means, "memory_estimate", None)
942
+ if estimate_fn is None:
943
+ return None, None
944
+ if subsampled:
945
+ logger.debug("GPU memory estimate skipped: it does not cover the max_points_per_centroid subset copy")
946
+ return None, None
947
+ try:
948
+ # include_input stays at its default (True): the host-to-GPU copy of the rows has not happened yet.
949
+ # The fp16 path briefly holds the float32 copy plus the half copy, which the estimate does not count.
950
+ estimate = int(estimate_fn(em, n, dtype, "cuda"))
951
+ free = int(torch.cuda.mem_get_info()[0])
952
+ except Exception as error:
953
+ logger.debug("GPU memory estimate unavailable: {error}", error=error)
954
+ return None, None
955
+ return estimate, free
956
+
957
+
958
+ def _number(value: Any, cast: Callable[[Any], Any], default: Any) -> Any:
959
+ """Return `cast(value)`, or `default` when the value is missing or cannot be converted."""
960
+ if value is None:
961
+ return default
962
+ try:
963
+ return cast(value)
964
+ except (TypeError, ValueError):
965
+ return default
966
+
967
+
968
+ def _fit_gpu(
969
+ x: np.ndarray,
970
+ *,
971
+ k: int,
972
+ spherical: bool,
973
+ nepochs: float,
974
+ seed: int,
975
+ max_points_per_centroid: int | None,
976
+ backend: BackendChoice,
977
+ precision: str,
978
+ deterministic: bool,
979
+ allow_cpu_fallback: bool = False,
980
+ init_centroids: np.ndarray | None = None,
981
+ ) -> FitResult:
982
+ torch = importlib.import_module("torch")
983
+ e_means = gpu_engine(backend.engine)
984
+ train_precision, warning = resolve_precision(backend, precision)
985
+ if warning is not None:
986
+ logger.warning("{warning}", warning=warning)
987
+ if train_precision == "fp16" and x.size and float(np.abs(x).max()) > float(np.finfo(np.float16).max):
988
+ # e-means does not check GPU data for infinity, so a value outside the FP16 range would train silently.
989
+ logger.warning("embeddings exceed the fp16 range; using fp32")
990
+ train_precision = "fp32"
991
+ n, d = x.shape
992
+ x_gpu = None
993
+ init_gpu = None
994
+ em = None
995
+ centroids = None
996
+ fallback_reason: str | None = None
997
+ estimate: int | None = None
998
+ try:
999
+ engine = e_means.QuantizedEmeans if train_precision == "fp32" else e_means.Emeans
1000
+ extra: dict[str, Any] = {"quantizer": None} if train_precision == "fp32" else {}
1001
+ em = engine(
1002
+ d,
1003
+ k,
1004
+ nepochs=nepochs,
1005
+ seed=seed,
1006
+ spherical=spherical,
1007
+ max_points_per_centroid=max_points_per_centroid,
1008
+ capture_assignments=False,
1009
+ assignment_backend=backend.requested,
1010
+ unused_threshold=_unused_threshold(d),
1011
+ **extra,
1012
+ )
1013
+ # bf16 runs pass float32 rows to an automatic Emeans, which memory_estimate costs as the BF16 cast.
1014
+ estimate, free = _memory_preflight(
1015
+ e_means,
1016
+ torch,
1017
+ em,
1018
+ n=n,
1019
+ dtype=torch.float16 if train_precision == "fp16" else torch.float32,
1020
+ subsampled=_n_train(n, k, max_points_per_centroid) < n,
1021
+ )
1022
+ if estimate is not None and free is not None and estimate > free:
1023
+ if allow_cpu_fallback:
1024
+ fallback_reason = (
1025
+ f"GPU memory estimate for training ({_gib(estimate)}) exceeds free GPU memory "
1026
+ f"({_gib(free)}); using the CPU backend"
1027
+ )
1028
+ logger.warning("{reason}", reason=fallback_reason)
1029
+ else:
1030
+ logger.info(
1031
+ "GPU memory estimate for training ({estimate}) exceeds free GPU memory ({free}); "
1032
+ "training on the GPU anyway because device='cuda'",
1033
+ estimate=_gib(estimate),
1034
+ free=_gib(free),
1035
+ )
1036
+ elif estimate is not None and free is not None:
1037
+ logger.debug(
1038
+ "GPU memory estimate for training {estimate}, free {free}", estimate=_gib(estimate), free=_gib(free)
1039
+ )
1040
+ if fallback_reason is not None:
1041
+ raise _FallbackToCpu
1042
+ x_gpu = torch.from_numpy(np.ascontiguousarray(x, dtype=np.float32)).to("cuda")
1043
+ if train_precision == "fp16":
1044
+ x_gpu = x_gpu.half()
1045
+ if init_centroids is not None:
1046
+ # Starting centroids stay FP32 even when the data trains in FP16.
1047
+ init_gpu = torch.from_numpy(np.ascontiguousarray(init_centroids, dtype=np.float32)).to("cuda")
1048
+ with _deterministic(torch, deterministic):
1049
+ start = time.perf_counter()
1050
+ centroids, _ = em.train(x_gpu, init_centroids=init_gpu)
1051
+ torch.cuda.synchronize()
1052
+ train_seconds = time.perf_counter() - start
1053
+ result = np.ascontiguousarray(centroids.detach().float().cpu().numpy(), dtype=np.float32)
1054
+ # Reporting fields are read with defaults: a renamed field in a newer engine must never discard a finished
1055
+ # training run.
1056
+ raw_recipe = getattr(em, "recipe", None)
1057
+ recipe: dict[str, Any] = dict(raw_recipe) if isinstance(raw_recipe, Mapping) else {}
1058
+ # read after training: e-means resolves "auto" itself
1059
+ label = str(recipe.get("assignment_backend", backend.requested or "unknown"))
1060
+ representation = recipe.get("representation")
1061
+ precision_used = train_precision
1062
+ if representation is not None:
1063
+ precision_label = str(representation).removeprefix("torch.")
1064
+ precision_used = _PRECISION_NAMES.get(precision_label, precision_label)
1065
+ iteration_stats = getattr(em, "iteration_stats", None)
1066
+ imbalance = float("nan")
1067
+ if iteration_stats:
1068
+ last = iteration_stats[-1]
1069
+ imbalance = _number(
1070
+ last.get("imbalance_factor") if isinstance(last, Mapping) else None, float, float("nan")
1071
+ )
1072
+ info: dict[str, Any] = {
1073
+ "backend": _BACKEND_NAMES.get(label, f"gpu-{label}"),
1074
+ "device_name": backend.device_name,
1075
+ "precision_used": precision_used,
1076
+ "assignment_backend": label,
1077
+ "recipe": recipe,
1078
+ "n_train": _n_train(n, k, max_points_per_centroid),
1079
+ "train_seconds": float(train_seconds),
1080
+ "emeans_source": _engine_source(backend.engine),
1081
+ "faiss_version": str(faiss.__version__),
1082
+ "nepochs": _number(recipe.get("nepochs"), float, float(nepochs)),
1083
+ "batch_size": _number(recipe.get("batch_size"), int, None),
1084
+ "alpha0": _number(recipe.get("alpha0"), float, None),
1085
+ "n_splits": _number(getattr(em, "n_splits", None), int, None),
1086
+ "imbalance": imbalance,
1087
+ "unused_threshold": _unused_threshold(d),
1088
+ "backend_hint": _backend_hint(
1089
+ is_rocm=torch.version.hip is not None,
1090
+ assignment_backend=label,
1091
+ emeans_rocm=emeans_rocm_enabled(),
1092
+ ),
1093
+ "memory_estimate_bytes": estimate,
1094
+ "fallback_reason": backend.fallback_reason,
1095
+ }
1096
+ return FitResult(centroids=result, info=info)
1097
+ except _FallbackToCpu:
1098
+ pass
1099
+ finally:
1100
+ # Drop every GPU tensor before empty_cache(), or the centroids' memory stays allocated.
1101
+ del x_gpu, em, centroids, init_gpu
1102
+ torch.cuda.empty_cache()
1103
+ # The GPU memory is released by now, so the CPU fit does not compete with the dropped engine for it.
1104
+ fit = _fit_cpu(
1105
+ x,
1106
+ k=k,
1107
+ spherical=spherical,
1108
+ nepochs=nepochs,
1109
+ seed=seed,
1110
+ max_points_per_centroid=max_points_per_centroid,
1111
+ backend=BackendChoice("cpu", "cpu", fallback_reason),
1112
+ precision="fp32",
1113
+ init_centroids=init_centroids,
1114
+ )
1115
+ fit.info["memory_estimate_bytes"] = estimate
1116
+ return fit
1117
+
1118
+
1119
+ class _CpuAssigner:
1120
+ def __init__(self, centroids: np.ndarray, *, spherical: bool) -> None:
1121
+ faiss_import.check()
1122
+ k, d = centroids.shape
1123
+ self._em = NumpyEmeans(d, k, spherical=spherical, unused_threshold=_unused_threshold(d))
1124
+ self._em.centroids = centroids
1125
+
1126
+ def assign(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
1127
+ score, labels = self._em.assign(x)
1128
+ return np.asarray(score, dtype=np.float32), np.asarray(labels, dtype=np.int64)
1129
+
1130
+
1131
+ def cpu_assigner(centroids: np.ndarray, *, spherical: bool) -> Assigner:
1132
+ """
1133
+ Build an assigner for saved centroids on CPU.
1134
+
1135
+ :param centroids: float32 centroids of shape `(k, d)`.
1136
+ :param spherical: Whether the model clusters by cosine similarity (scores are then cosine similarities;
1137
+ otherwise squared L2 distances).
1138
+ """
1139
+ return _CpuAssigner(centroids, spherical=spherical)
1140
+
1141
+
1142
+ class _GpuAssigner:
1143
+ """FP32 assignment on the GPU; reduced precision is never used for cluster ids."""
1144
+
1145
+ def __init__(self, centroids: np.ndarray, *, spherical: bool, requested: str, engine: str | None = None) -> None:
1146
+ faiss_import.check()
1147
+ self._torch = importlib.import_module("torch")
1148
+ e_means = gpu_engine(engine)
1149
+ k, d = centroids.shape
1150
+ self._em = e_means.QuantizedEmeans(
1151
+ d,
1152
+ k,
1153
+ spherical=spherical,
1154
+ quantizer=None,
1155
+ assignment_backend=requested,
1156
+ unused_threshold=_unused_threshold(d),
1157
+ )
1158
+ self._em.centroids = self._torch.from_numpy(np.ascontiguousarray(centroids, dtype=np.float32)).to("cuda")
1159
+
1160
+ def assign(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
1161
+ chunk = self._torch.from_numpy(np.ascontiguousarray(x, dtype=np.float32)).to("cuda")
1162
+ try:
1163
+ score, labels = self._em.assign(chunk)
1164
+ return (
1165
+ score.float().cpu().numpy().astype(np.float32),
1166
+ labels.cpu().numpy().astype(np.int64),
1167
+ )
1168
+ finally:
1169
+ del chunk
1170
+
1171
+
1172
+ def assigner_for(backend: BackendChoice, centroids: np.ndarray, *, spherical: bool) -> Assigner:
1173
+ """
1174
+ Build an assigner for saved centroids on the chosen backend.
1175
+
1176
+ :param backend: Backend chosen by `select_backend`; a CPU choice (`requested` is None) gives the CPU assigner.
1177
+ :param centroids: float32 centroids of shape `(k, d)`.
1178
+ :param spherical: Whether the model clusters by cosine similarity (otherwise squared L2 distances).
1179
+ :returns: An assigner whose `assign` returns `(score, labels)`; GPU assignment is always FP32.
1180
+ """
1181
+ if backend.requested is None:
1182
+ return cpu_assigner(centroids, spherical=spherical)
1183
+ return _GpuAssigner(centroids, spherical=spherical, requested=backend.requested, engine=backend.engine)