emeans-core 0.1.0__tar.gz

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,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+ .coverage
11
+ benchmarks/data/
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html); while in 0.x, a breaking change bumps
6
+ the minor version.
7
+
8
+ ## [Unreleased]
9
+
10
+ Planned as 0.1.0, the first release.
11
+
12
+ ### Added
13
+
14
+ - The e-means clustering backend and the near-duplicate check of emeans-langchain 0.1.1, moved
15
+ here with unchanged results so that every emeans integration shares one copy: CPU (faiss-cpu `NumpyEmeans`)
16
+ and GPU (emeans-rocm or stock faiss e-means through torch) backends with the same defaults
17
+ (`init="auto"`, `nepochs=None`, `device="auto"` threshold, single-threaded small CPU fits), the
18
+ two-pass leader-rule duplicate check with e-means blocking and neighbouring-cluster probes, the
19
+ reduced-precision guard for GPU products, and row-chunked normalisation.
20
+ - Public API: `dedup`, `DedupReport`, `DuplicateDrop`, `ReferenceVectors`, `match_external`,
21
+ `ExternalMatches`, `fit`, `FitOutput`, `prepare`, `nearest_centroids`, `l2_normalize`,
22
+ `as_matrix`, `clamp_k`, `EmbeddingCache`, `backend_info`, `collect_env`, `warn_once`,
23
+ `reset_backend_cache`, `DEFAULT_GPU_THRESHOLD`, `__version__`. Backend messages go to the
24
+ `emeans_core` logger.
25
+ - `python -m emeans_core.env`: sanitised platform manifest; integrations add their own version and
26
+ source commit through `collect_env(project=..., project_file=...)`.
27
+ - `[rocm]` extra (emeans-rocm, no torch).
28
+ - Tests moved with the code (fuzzing against the reference loop, exact ties, reduced-precision
29
+ emulation, piles with a memory bound, GPU tests), a parity test against outputs of emeans-langchain
30
+ 0.1.1 (a stored baseline, and in CI a baseline recorded on the runner), and a check of every
31
+ Python example of the README.
32
+ - Benchmarks (dedup on synthetic vectors, backend, seeding defaults) with the results
33
+ emeans-langchain recorded on the same code, plus two CPU-only runs of the backend workload made
34
+ with emeans-core. The backend table shows CPU fits from a CPU-only process and from the GPU run
35
+ (torch imported first, which slowed its CPU fits of 500 to 5,000 rows) in separate columns.
36
+
37
+ [Unreleased]: https://github.com/ogaude/emeans-core/commits/main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Olivier Gaude
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,281 @@
1
+ Metadata-Version: 2.5
2
+ Name: emeans-core
3
+ Version: 0.1.0
4
+ Summary: Framework-free e-means clustering backend and near-duplicate removal shared by the emeans-* integrations (CPU, optional ROCm/CUDA GPU)
5
+ Project-URL: Source, https://github.com/ogaude/emeans-core
6
+ Project-URL: Issues, https://github.com/ogaude/emeans-core/issues
7
+ Project-URL: Changelog, https://github.com/ogaude/emeans-core/blob/main/CHANGELOG.md
8
+ Project-URL: Benchmarks, https://github.com/ogaude/emeans-core/blob/main/BENCHMARKS.md
9
+ Author-email: Olivier Gaude <ogaude.code@proton.me>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ License-File: THIRD_PARTY_NOTICES.md
13
+ Keywords: clustering,deduplication,e-means,embeddings,faiss,k-means,near-duplicates,rag,rocm
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: faiss-cpu<2,>=1.16.0
25
+ Requires-Dist: numpy<3,>=2.0
26
+ Provides-Extra: rocm
27
+ Requires-Dist: emeans-rocm<0.3,>=0.2.5; extra == 'rocm'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # emeans-core
31
+
32
+ The framework-free engine behind the emeans integrations: an
33
+ [e-means](https://github.com/ogaude/e-means-rocm) clustering backend (the mini-batch k-means from
34
+ faiss `contrib/e_means`) and a near-duplicate check built on it. It works on plain numpy
35
+ matrices. It runs on the CPU out of the box; an AMD (ROCm) or NVIDIA GPU can be used for large
36
+ inputs.
37
+
38
+ [emeans-langchain](https://github.com/ogaude/emeans-langchain) is built on it. The
39
+ integrations add the framework layer: documents, embedding models, vector stores, metadata.
40
+ Use emeans-core directly when you already have embedding matrices, or to build another
41
+ integration.
42
+
43
+ Status: alpha (0.1.0). The code is emeans-langchain 0.1.1's engine, moved here with unchanged
44
+ results (only the logger name, some messages and the argument interface differ) and exposed as a
45
+ small public API with emeans-langchain's parameter names; emeans-langchain 0.1.2
46
+ gives bit-identical results through it on the CPU.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install emeans-core # CPU: numpy, faiss-cpu
52
+ ```
53
+
54
+ The CPU backend is e-means itself (`NumpyEmeans`, which ships with `faiss-cpu`), not a different
55
+ k-means. A GPU is optional, and needs a GPU build of torch that you install first:
56
+
57
+ ```bash
58
+ # AMD GPU (ROCm): install a ROCm build of torch, then the emeans-rocm port.
59
+ # Example for an RX 9060-series card (gfx1200) on ROCm 10.1; see the emeans-rocm README for other targets.
60
+ pip install --extra-index-url https://stable.repo.amd.com/rocm/whl-next/ "torch[device-gfx1200]==2.14.0+rocm10.1.0"
61
+ pip install "emeans-core[rocm]"
62
+
63
+ # NVIDIA GPU: install a CUDA build of torch; emeans-core then uses the stock faiss e-means GPU code.
64
+ ```
65
+
66
+ `[rocm]` adds `emeans-rocm` (AMD kernels through Triton) and does not install torch. There is no
67
+ extra that installs torch: `pip install torch` without an index URL takes the PyPI wheel (a CUDA
68
+ build on Linux x86-64, never ROCm), so pick the torch build for your GPU yourself. torch and
69
+ emeans-rocm are detected when the backend first runs; `import emeans_core` imports neither, nor
70
+ faiss.
71
+
72
+ **Supported GPUs**: AMD through ROCm, as covered by emeans-rocm. NVIDIA through CUDA uses upstream
73
+ faiss e-means, which supports it, but **this package has not been tested on an NVIDIA GPU**. GPU
74
+ tests skip themselves when torch sees no GPU.
75
+
76
+ ## Examples
77
+
78
+ ### Near-duplicate rows of a matrix
79
+
80
+ ```python
81
+ import numpy as np
82
+ from emeans_core import dedup
83
+
84
+ rng = np.random.default_rng(0)
85
+ x = rng.standard_normal((20_000, 64)).astype(np.float32)
86
+ x[10_000:10_050] = x[:50] + 0.05 * rng.standard_normal((50, 64)).astype(np.float32) # near-copies
87
+
88
+ report = dedup(x, threshold=0.95)
89
+ print(len(report.kept), "kept,", len(report.drops), "dropped,", report.num_clusters, "clusters")
90
+ drop = report.drops[0]
91
+ print(drop.index, "duplicates", drop.kept_index, f"(cosine {drop.score:.3f})")
92
+ ```
93
+
94
+ ```text
95
+ 19950 kept, 50 dropped, 141 clusters
96
+ 10000 duplicates 0 (cosine 0.999)
97
+ ```
98
+
99
+ `report.kept` lists the rows to keep, in input order; each `DuplicateDrop` names the kept row (or
100
+ the reference entry) that absorbs it, with the FP32 cosine similarity. `report.cluster_ids` gives
101
+ each row's blocking cluster.
102
+
103
+ ### Against vectors already indexed
104
+
105
+ ```python
106
+ from emeans_core import ReferenceVectors
107
+
108
+ indexed = ReferenceVectors(vectors=x[:100], ids=[f"doc-{i}" for i in range(100)])
109
+ report = dedup(x[10_000:10_100], reference=indexed)
110
+ print(len(report.drops), "of 100 new rows are already indexed; first:", report.drops[0].reference_id)
111
+ ```
112
+
113
+ ```text
114
+ 50 of 100 new rows are already indexed; first: doc-0
115
+ ```
116
+
117
+ When the indexed vectors live in a vector store that can only return each row's nearest
118
+ neighbours, compare each row with its own neighbours with `match_external`, then pass the result
119
+ to `dedup(..., external=...)`: those rows are dropped first, with the same threshold rule.
120
+
121
+ ```python
122
+ from emeans_core import match_external
123
+
124
+ batch = x[10_000:10_003]
125
+ neighbours = [x[:2], x[5:7], np.empty((0, 64))] # what the store returned for each row
126
+ ids = [["doc-0", "doc-1"], ["doc-5", "doc-6"], []]
127
+ matches = match_external(batch, neighbours, ids, threshold=0.95)
128
+ print(matches.matched.tolist(), list(matches.ids))
129
+ report = dedup(batch, external=matches)
130
+ print(report.kept, [(d.index, d.reference_id) for d in report.drops])
131
+ ```
132
+
133
+ ```text
134
+ [True, False, False] ['doc-0', None, None]
135
+ [1, 2] [(0, 'doc-0')]
136
+ ```
137
+
138
+ ### Clustering
139
+
140
+ ```python
141
+ from emeans_core import fit, nearest_centroids, prepare
142
+
143
+ unit = prepare(x[:2_000], normalize=True) # unit rows; normalize=False: float32, values unchanged
144
+ out = fit(unit, 8, spherical=True)
145
+ print(out.centroids.shape, out.labels.shape, out.backend, out.precision, out.info["init"])
146
+ print(nearest_centroids(unit[:3], out.centroids, 2).shape)
147
+ ```
148
+
149
+ ```text
150
+ (8, 64) (2000,) cpu fp32 k-means++
151
+ (3, 2)
152
+ ```
153
+
154
+ `fit` takes data already prepared: pass `spherical=True` for unit rows (cosine geometry),
155
+ `False` for raw Euclidean k-means. Labels always come from an FP32 assignment.
156
+
157
+ ## API
158
+
159
+ The public API is `emeans_core.__all__` (the names below and `__version__`), plus the
160
+ `emeans_core.env` module (`import emeans_core.env`; `main`, `sanitize`, `git_sha`, used by integrations for their own
161
+ manifest command) and `emeans_core.cache`. Modules whose name starts with an underscore are
162
+ private.
163
+
164
+ | Name | What it is |
165
+ |---|---|
166
+ | `dedup(x, *, threshold=0.92, keep="first", lengths=None, num_clusters=None, max_cluster_size=4096, neighbor_clusters=2, reference=None, external=None, normalize=True, device="auto", precision="fp32", nepochs=None, init="auto", seed=1234, deterministic=False, gpu_threshold=1e6, block_size=1024)` | Near-duplicate rows of an `(n, d)` matrix; returns a `DedupReport` |
167
+ | `DedupReport`, `DuplicateDrop` | Kept rows, drops with scores and absorbers, cluster ids, backend, info |
168
+ | `ReferenceVectors(vectors, ids)` | Already-indexed vectors to check new rows against |
169
+ | `match_external(x, candidates, candidate_ids, threshold)`, `ExternalMatches` | Each row against its own external candidates (e.g. vector-store hits), same threshold rule; rows must be finite |
170
+ | `fit(x, k, *, spherical, seed=1234, device="auto", precision="fp32", nepochs=None, deterministic=False, gpu_threshold=1e6, init="auto")`, `FitOutput` | e-means on prepared data: centroids, labels, backend, precision, info |
171
+ | `prepare(x, normalize)`, `l2_normalize(x)`, `as_matrix(vectors)` | FP32 conversion (`as_matrix` rejects mixed dimensions and NaN/inf with clear errors; `prepare` does not check), row-chunked L2 normalisation (all-zero rows raise) |
172
+ | `nearest_centroids(x, centroids, m=1, *, metric="ip", device="cpu")` | The `m` nearest centroids of each row (`device="cuda"`: `metric="ip"` on the GPU; `"l2"` always on the CPU) |
173
+ | `clamp_k(k, n, *, what)` | Clamp a cluster count to `n`, with a warning |
174
+ | `EmbeddingCache(maxsize=10_000, namespace="")` | Thread-safe LRU cache of embeddings keyed by text |
175
+ | `backend_info(*, include_gpu=True)` | CPU and GPU engines available, the emeans-rocm range, the GPU threshold |
176
+ | `collect_env(alias=None, *, include_gpu=True, project=None, project_file=None, extra_packages=())` | Sanitised platform manifest (also `python -m emeans_core.env`) |
177
+ | `warn_once`, `reset_backend_cache`, `DEFAULT_GPU_THRESHOLD` | For integrations: one-time warnings on the `emeans_core` logger, test isolation, the default threshold |
178
+
179
+ Versioning: semantic versioning, and while in 0.x a breaking change bumps the minor version.
180
+ Integrations pin `emeans-core>=0.1,<0.2`.
181
+
182
+ ## How the duplicate check works
183
+
184
+ - **Leader rule.** Rows are visited in keep order: input order with `keep="first"`, longest text
185
+ first with `keep="longest"` (pass `lengths`; ties keep input order). A row is dropped when its
186
+ FP32 cosine similarity to an earlier *kept* row, or to a reference vector, is at least
187
+ `threshold` (with a 1e-6 margin for FP32 rounding). Only kept rows absorb others, so there are
188
+ no chains, and every drop is a real pair above the threshold.
189
+ - **Blocking.** With `num_clusters=None`, inputs of at most `max_cluster_size` rows are compared
190
+ exactly. Larger inputs are split into `round(sqrt(n))` e-means clusters (clusters larger than
191
+ `max_cluster_size` are split again, up to 4 rounds), and each row is compared with the rows of
192
+ its own cluster and of the `neighbor_clusters` clusters whose centroids are nearest. Blocking
193
+ never produces a drop without a real pair above the threshold, but it can miss drops, and a
194
+ missed duplicate that is kept can then absorb rows that the exact rule would have kept.
195
+ The share of the exact rule's drops that blocking finds, for 0, 1 and 2 neighbours, is measured
196
+ in [BENCHMARKS.md](https://github.com/ogaude/emeans-core/blob/main/BENCHMARKS.md).
197
+ - **Ties** between equal similarities go to the earlier probed cluster, then to the row filed
198
+ earlier in keep order, references first, so the fast path gives the result of a row-by-row
199
+ reference loop, up to float rounding of the similarities (fuzz-tested for exact equality on
200
+ vectors whose similarities are exact, ties included).
201
+ - **Memory.** Similarities are computed in blocks of `block_size` rows (at least 4096 on a GPU)
202
+ against tiles of earlier rows, never as an `n × n` matrix. Piles of identical or near-identical
203
+ rows are resolved against kept rows only, which keeps their memory bounded (tested; their run
204
+ time is not benchmarked).
205
+ - **GPU.** When e-means trains on a GPU, the candidate similarity products run there too (the
206
+ exact path, without clustering, stays on the CPU); the leader rule and input normalisation
207
+ always run on the CPU. If the host process has enabled reduced-precision matrix
208
+ products (TF32 or bf16 through `torch.backends.cuda.matmul.allow_tf32` or
209
+ `torch.set_float32_matmul_precision`), GPU candidates are kept down to `threshold - 0.02` and all
210
+ recomputed in FP32 on the CPU, so decisions stay exact as long as the reduced-precision error
211
+ stays below 0.02 (the code's estimate: about 1e-3 for TF32, 8e-3 for bf16).
212
+ - **Inputs.** NaN or infinite values raise `ValueError` naming the rows (the first 10). Scores
213
+ always use L2-normalised FP32 copies, so all-zero rows raise `ValueError` ("no direction to
214
+ compare"). `normalize=False` only changes the clustering, which then uses raw Euclidean
215
+ distances.
216
+
217
+ ## Backends, precision and determinism
218
+
219
+ | | CPU (default) | AMD GPU, `[rocm]` | NVIDIA GPU |
220
+ |---|---|---|---|
221
+ | Engine | faiss-cpu `NumpyEmeans` | `emeans_rocm` (Triton) | faiss `contrib.e_means` (torch) |
222
+ | `precision="fp32"` | yes | yes | yes (untested here) |
223
+ | `precision="bf16"` / `"fp16"` | falls back to fp32 (one warning) | yes | yes (untested here) |
224
+ | Bit-identical repeats (same seed) | yes, tested | not guaranteed | not guaranteed |
225
+
226
+ - `device="auto"` uses a GPU only when torch sees one **and** `n × k >= gpu_threshold` (default
227
+ 1e6). In a warm process, the recorded GPU fits were slower than the CPU fits of the same run
228
+ only at `n × k = 1e3`; against a process that had not imported torch the CPU was also faster at 1.1e4 for
229
+ d=384, and the GPU led from about 3e4 up. The first GPU fit in a process also pays a start-up
230
+ cost (torch import, GPU initialisation, about 1.6 s here) that the threshold is meant to pay
231
+ back, so retrieval-sized inputs stay on the CPU (backend section of
232
+ [BENCHMARKS.md](https://github.com/ogaude/emeans-core/blob/main/BENCHMARKS.md)).
233
+ `device="cuda"` forces the GPU (AMD GPUs too, as in torch) and raises if none is visible when
234
+ e-means runs; `dedup`'s exact path (no clustering) runs on the CPU whatever `device` is. If a
235
+ GPU fit fails under `"auto"`, the CPU runs it instead, with a warning. The active backend is
236
+ logged once on the `emeans_core` logger.
237
+ - `precision` only affects GPU training. Labels come from an FP32 assignment and every duplicate
238
+ decision is an FP32 cosine similarity.
239
+ - `init="auto"` seeds with k-means++ when `n × k <= 1e7`, and with e-means' seeded sample of rows
240
+ otherwise; `nepochs=None` means 20 epochs for those small problems and 5 otherwise (e-means'
241
+ batch laws pick very small batches on tiny inputs). The small-input section of BENCHMARKS.md
242
+ compares these defaults with plain e-means.
243
+ - CPU fits with `n × k × d <= 2e8` run faiss single-threaded, scoped to the calling thread: OpenMP
244
+ start-up dominates fits of up to about a thousand rows; for larger fits up to that limit, see the
245
+ threads table of BENCHMARKS.md.
246
+ - **Import faiss before torch** if your application uses both: when torch was imported first, CPU
247
+ fits of 500 to 5,000 rows ran 1.11 to 2.82x slower in the BENCHMARKS.md backend table (torch and
248
+ faiss each load their own OpenMP runtime); `import faiss` before `import torch` avoided it, in a
249
+ check not recorded in BENCHMARKS.md. emeans-core imports torch itself only to use or look for a
250
+ GPU: with `device="cuda"`, with `device="auto"` once `n × k >= gpu_threshold` (when torch is
251
+ installed), and in `backend_info()` and `collect_env()` unless `include_gpu=False`. With
252
+ `device="cpu"` it does not.
253
+ - `deterministic=True` requests PyTorch deterministic algorithms while training on a GPU
254
+ (process-wide while it runs). GPU fits are not expected to match CPU fits bit for bit: tests
255
+ compare them by partition agreement (ARI). GPU duplicate decisions are tested for exact
256
+ equality with the reference loop.
257
+
258
+ ## Benchmarks
259
+
260
+ [BENCHMARKS.md](https://github.com/ogaude/emeans-core/blob/main/BENCHMARKS.md): dedup on 100k and
261
+ 1M synthetic vectors (CPU, GPU, three precisions), recall against the exact rule for 0 to 2
262
+ neighbouring clusters, CPU against GPU fit times, first-call cost, threads, and the small-input
263
+ seeding defaults, each with its platform manifest. Those results were recorded by
264
+ emeans-langchain on the code that moved here; the file says which runs.
265
+
266
+ ## Bug reports
267
+
268
+ Please include the sanitised platform manifest:
269
+
270
+ ```bash
271
+ python -m emeans_core.env --alias my-machine
272
+ ```
273
+
274
+ It replaces the hostname, username and home directory in every field, identifies the host only by
275
+ the alias you give (`--alias` or `EMEANS_HOST_ALIAS`), and reads environment variables from a short
276
+ allowlist only (thread counts, visible devices, the ROCm GFX override, PyTorch allocator settings).
277
+
278
+ ## License
279
+
280
+ MIT. e-means comes from faiss (MIT, Meta Platforms) and, optionally, emeans-rocm (MIT); see
281
+ [THIRD_PARTY_NOTICES.md](https://github.com/ogaude/emeans-core/blob/main/THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,252 @@
1
+ # emeans-core
2
+
3
+ The framework-free engine behind the emeans integrations: an
4
+ [e-means](https://github.com/ogaude/e-means-rocm) clustering backend (the mini-batch k-means from
5
+ faiss `contrib/e_means`) and a near-duplicate check built on it. It works on plain numpy
6
+ matrices. It runs on the CPU out of the box; an AMD (ROCm) or NVIDIA GPU can be used for large
7
+ inputs.
8
+
9
+ [emeans-langchain](https://github.com/ogaude/emeans-langchain) is built on it. The
10
+ integrations add the framework layer: documents, embedding models, vector stores, metadata.
11
+ Use emeans-core directly when you already have embedding matrices, or to build another
12
+ integration.
13
+
14
+ Status: alpha (0.1.0). The code is emeans-langchain 0.1.1's engine, moved here with unchanged
15
+ results (only the logger name, some messages and the argument interface differ) and exposed as a
16
+ small public API with emeans-langchain's parameter names; emeans-langchain 0.1.2
17
+ gives bit-identical results through it on the CPU.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install emeans-core # CPU: numpy, faiss-cpu
23
+ ```
24
+
25
+ The CPU backend is e-means itself (`NumpyEmeans`, which ships with `faiss-cpu`), not a different
26
+ k-means. A GPU is optional, and needs a GPU build of torch that you install first:
27
+
28
+ ```bash
29
+ # AMD GPU (ROCm): install a ROCm build of torch, then the emeans-rocm port.
30
+ # Example for an RX 9060-series card (gfx1200) on ROCm 10.1; see the emeans-rocm README for other targets.
31
+ pip install --extra-index-url https://stable.repo.amd.com/rocm/whl-next/ "torch[device-gfx1200]==2.14.0+rocm10.1.0"
32
+ pip install "emeans-core[rocm]"
33
+
34
+ # NVIDIA GPU: install a CUDA build of torch; emeans-core then uses the stock faiss e-means GPU code.
35
+ ```
36
+
37
+ `[rocm]` adds `emeans-rocm` (AMD kernels through Triton) and does not install torch. There is no
38
+ extra that installs torch: `pip install torch` without an index URL takes the PyPI wheel (a CUDA
39
+ build on Linux x86-64, never ROCm), so pick the torch build for your GPU yourself. torch and
40
+ emeans-rocm are detected when the backend first runs; `import emeans_core` imports neither, nor
41
+ faiss.
42
+
43
+ **Supported GPUs**: AMD through ROCm, as covered by emeans-rocm. NVIDIA through CUDA uses upstream
44
+ faiss e-means, which supports it, but **this package has not been tested on an NVIDIA GPU**. GPU
45
+ tests skip themselves when torch sees no GPU.
46
+
47
+ ## Examples
48
+
49
+ ### Near-duplicate rows of a matrix
50
+
51
+ ```python
52
+ import numpy as np
53
+ from emeans_core import dedup
54
+
55
+ rng = np.random.default_rng(0)
56
+ x = rng.standard_normal((20_000, 64)).astype(np.float32)
57
+ x[10_000:10_050] = x[:50] + 0.05 * rng.standard_normal((50, 64)).astype(np.float32) # near-copies
58
+
59
+ report = dedup(x, threshold=0.95)
60
+ print(len(report.kept), "kept,", len(report.drops), "dropped,", report.num_clusters, "clusters")
61
+ drop = report.drops[0]
62
+ print(drop.index, "duplicates", drop.kept_index, f"(cosine {drop.score:.3f})")
63
+ ```
64
+
65
+ ```text
66
+ 19950 kept, 50 dropped, 141 clusters
67
+ 10000 duplicates 0 (cosine 0.999)
68
+ ```
69
+
70
+ `report.kept` lists the rows to keep, in input order; each `DuplicateDrop` names the kept row (or
71
+ the reference entry) that absorbs it, with the FP32 cosine similarity. `report.cluster_ids` gives
72
+ each row's blocking cluster.
73
+
74
+ ### Against vectors already indexed
75
+
76
+ ```python
77
+ from emeans_core import ReferenceVectors
78
+
79
+ indexed = ReferenceVectors(vectors=x[:100], ids=[f"doc-{i}" for i in range(100)])
80
+ report = dedup(x[10_000:10_100], reference=indexed)
81
+ print(len(report.drops), "of 100 new rows are already indexed; first:", report.drops[0].reference_id)
82
+ ```
83
+
84
+ ```text
85
+ 50 of 100 new rows are already indexed; first: doc-0
86
+ ```
87
+
88
+ When the indexed vectors live in a vector store that can only return each row's nearest
89
+ neighbours, compare each row with its own neighbours with `match_external`, then pass the result
90
+ to `dedup(..., external=...)`: those rows are dropped first, with the same threshold rule.
91
+
92
+ ```python
93
+ from emeans_core import match_external
94
+
95
+ batch = x[10_000:10_003]
96
+ neighbours = [x[:2], x[5:7], np.empty((0, 64))] # what the store returned for each row
97
+ ids = [["doc-0", "doc-1"], ["doc-5", "doc-6"], []]
98
+ matches = match_external(batch, neighbours, ids, threshold=0.95)
99
+ print(matches.matched.tolist(), list(matches.ids))
100
+ report = dedup(batch, external=matches)
101
+ print(report.kept, [(d.index, d.reference_id) for d in report.drops])
102
+ ```
103
+
104
+ ```text
105
+ [True, False, False] ['doc-0', None, None]
106
+ [1, 2] [(0, 'doc-0')]
107
+ ```
108
+
109
+ ### Clustering
110
+
111
+ ```python
112
+ from emeans_core import fit, nearest_centroids, prepare
113
+
114
+ unit = prepare(x[:2_000], normalize=True) # unit rows; normalize=False: float32, values unchanged
115
+ out = fit(unit, 8, spherical=True)
116
+ print(out.centroids.shape, out.labels.shape, out.backend, out.precision, out.info["init"])
117
+ print(nearest_centroids(unit[:3], out.centroids, 2).shape)
118
+ ```
119
+
120
+ ```text
121
+ (8, 64) (2000,) cpu fp32 k-means++
122
+ (3, 2)
123
+ ```
124
+
125
+ `fit` takes data already prepared: pass `spherical=True` for unit rows (cosine geometry),
126
+ `False` for raw Euclidean k-means. Labels always come from an FP32 assignment.
127
+
128
+ ## API
129
+
130
+ The public API is `emeans_core.__all__` (the names below and `__version__`), plus the
131
+ `emeans_core.env` module (`import emeans_core.env`; `main`, `sanitize`, `git_sha`, used by integrations for their own
132
+ manifest command) and `emeans_core.cache`. Modules whose name starts with an underscore are
133
+ private.
134
+
135
+ | Name | What it is |
136
+ |---|---|
137
+ | `dedup(x, *, threshold=0.92, keep="first", lengths=None, num_clusters=None, max_cluster_size=4096, neighbor_clusters=2, reference=None, external=None, normalize=True, device="auto", precision="fp32", nepochs=None, init="auto", seed=1234, deterministic=False, gpu_threshold=1e6, block_size=1024)` | Near-duplicate rows of an `(n, d)` matrix; returns a `DedupReport` |
138
+ | `DedupReport`, `DuplicateDrop` | Kept rows, drops with scores and absorbers, cluster ids, backend, info |
139
+ | `ReferenceVectors(vectors, ids)` | Already-indexed vectors to check new rows against |
140
+ | `match_external(x, candidates, candidate_ids, threshold)`, `ExternalMatches` | Each row against its own external candidates (e.g. vector-store hits), same threshold rule; rows must be finite |
141
+ | `fit(x, k, *, spherical, seed=1234, device="auto", precision="fp32", nepochs=None, deterministic=False, gpu_threshold=1e6, init="auto")`, `FitOutput` | e-means on prepared data: centroids, labels, backend, precision, info |
142
+ | `prepare(x, normalize)`, `l2_normalize(x)`, `as_matrix(vectors)` | FP32 conversion (`as_matrix` rejects mixed dimensions and NaN/inf with clear errors; `prepare` does not check), row-chunked L2 normalisation (all-zero rows raise) |
143
+ | `nearest_centroids(x, centroids, m=1, *, metric="ip", device="cpu")` | The `m` nearest centroids of each row (`device="cuda"`: `metric="ip"` on the GPU; `"l2"` always on the CPU) |
144
+ | `clamp_k(k, n, *, what)` | Clamp a cluster count to `n`, with a warning |
145
+ | `EmbeddingCache(maxsize=10_000, namespace="")` | Thread-safe LRU cache of embeddings keyed by text |
146
+ | `backend_info(*, include_gpu=True)` | CPU and GPU engines available, the emeans-rocm range, the GPU threshold |
147
+ | `collect_env(alias=None, *, include_gpu=True, project=None, project_file=None, extra_packages=())` | Sanitised platform manifest (also `python -m emeans_core.env`) |
148
+ | `warn_once`, `reset_backend_cache`, `DEFAULT_GPU_THRESHOLD` | For integrations: one-time warnings on the `emeans_core` logger, test isolation, the default threshold |
149
+
150
+ Versioning: semantic versioning, and while in 0.x a breaking change bumps the minor version.
151
+ Integrations pin `emeans-core>=0.1,<0.2`.
152
+
153
+ ## How the duplicate check works
154
+
155
+ - **Leader rule.** Rows are visited in keep order: input order with `keep="first"`, longest text
156
+ first with `keep="longest"` (pass `lengths`; ties keep input order). A row is dropped when its
157
+ FP32 cosine similarity to an earlier *kept* row, or to a reference vector, is at least
158
+ `threshold` (with a 1e-6 margin for FP32 rounding). Only kept rows absorb others, so there are
159
+ no chains, and every drop is a real pair above the threshold.
160
+ - **Blocking.** With `num_clusters=None`, inputs of at most `max_cluster_size` rows are compared
161
+ exactly. Larger inputs are split into `round(sqrt(n))` e-means clusters (clusters larger than
162
+ `max_cluster_size` are split again, up to 4 rounds), and each row is compared with the rows of
163
+ its own cluster and of the `neighbor_clusters` clusters whose centroids are nearest. Blocking
164
+ never produces a drop without a real pair above the threshold, but it can miss drops, and a
165
+ missed duplicate that is kept can then absorb rows that the exact rule would have kept.
166
+ The share of the exact rule's drops that blocking finds, for 0, 1 and 2 neighbours, is measured
167
+ in [BENCHMARKS.md](https://github.com/ogaude/emeans-core/blob/main/BENCHMARKS.md).
168
+ - **Ties** between equal similarities go to the earlier probed cluster, then to the row filed
169
+ earlier in keep order, references first, so the fast path gives the result of a row-by-row
170
+ reference loop, up to float rounding of the similarities (fuzz-tested for exact equality on
171
+ vectors whose similarities are exact, ties included).
172
+ - **Memory.** Similarities are computed in blocks of `block_size` rows (at least 4096 on a GPU)
173
+ against tiles of earlier rows, never as an `n × n` matrix. Piles of identical or near-identical
174
+ rows are resolved against kept rows only, which keeps their memory bounded (tested; their run
175
+ time is not benchmarked).
176
+ - **GPU.** When e-means trains on a GPU, the candidate similarity products run there too (the
177
+ exact path, without clustering, stays on the CPU); the leader rule and input normalisation
178
+ always run on the CPU. If the host process has enabled reduced-precision matrix
179
+ products (TF32 or bf16 through `torch.backends.cuda.matmul.allow_tf32` or
180
+ `torch.set_float32_matmul_precision`), GPU candidates are kept down to `threshold - 0.02` and all
181
+ recomputed in FP32 on the CPU, so decisions stay exact as long as the reduced-precision error
182
+ stays below 0.02 (the code's estimate: about 1e-3 for TF32, 8e-3 for bf16).
183
+ - **Inputs.** NaN or infinite values raise `ValueError` naming the rows (the first 10). Scores
184
+ always use L2-normalised FP32 copies, so all-zero rows raise `ValueError` ("no direction to
185
+ compare"). `normalize=False` only changes the clustering, which then uses raw Euclidean
186
+ distances.
187
+
188
+ ## Backends, precision and determinism
189
+
190
+ | | CPU (default) | AMD GPU, `[rocm]` | NVIDIA GPU |
191
+ |---|---|---|---|
192
+ | Engine | faiss-cpu `NumpyEmeans` | `emeans_rocm` (Triton) | faiss `contrib.e_means` (torch) |
193
+ | `precision="fp32"` | yes | yes | yes (untested here) |
194
+ | `precision="bf16"` / `"fp16"` | falls back to fp32 (one warning) | yes | yes (untested here) |
195
+ | Bit-identical repeats (same seed) | yes, tested | not guaranteed | not guaranteed |
196
+
197
+ - `device="auto"` uses a GPU only when torch sees one **and** `n × k >= gpu_threshold` (default
198
+ 1e6). In a warm process, the recorded GPU fits were slower than the CPU fits of the same run
199
+ only at `n × k = 1e3`; against a process that had not imported torch the CPU was also faster at 1.1e4 for
200
+ d=384, and the GPU led from about 3e4 up. The first GPU fit in a process also pays a start-up
201
+ cost (torch import, GPU initialisation, about 1.6 s here) that the threshold is meant to pay
202
+ back, so retrieval-sized inputs stay on the CPU (backend section of
203
+ [BENCHMARKS.md](https://github.com/ogaude/emeans-core/blob/main/BENCHMARKS.md)).
204
+ `device="cuda"` forces the GPU (AMD GPUs too, as in torch) and raises if none is visible when
205
+ e-means runs; `dedup`'s exact path (no clustering) runs on the CPU whatever `device` is. If a
206
+ GPU fit fails under `"auto"`, the CPU runs it instead, with a warning. The active backend is
207
+ logged once on the `emeans_core` logger.
208
+ - `precision` only affects GPU training. Labels come from an FP32 assignment and every duplicate
209
+ decision is an FP32 cosine similarity.
210
+ - `init="auto"` seeds with k-means++ when `n × k <= 1e7`, and with e-means' seeded sample of rows
211
+ otherwise; `nepochs=None` means 20 epochs for those small problems and 5 otherwise (e-means'
212
+ batch laws pick very small batches on tiny inputs). The small-input section of BENCHMARKS.md
213
+ compares these defaults with plain e-means.
214
+ - CPU fits with `n × k × d <= 2e8` run faiss single-threaded, scoped to the calling thread: OpenMP
215
+ start-up dominates fits of up to about a thousand rows; for larger fits up to that limit, see the
216
+ threads table of BENCHMARKS.md.
217
+ - **Import faiss before torch** if your application uses both: when torch was imported first, CPU
218
+ fits of 500 to 5,000 rows ran 1.11 to 2.82x slower in the BENCHMARKS.md backend table (torch and
219
+ faiss each load their own OpenMP runtime); `import faiss` before `import torch` avoided it, in a
220
+ check not recorded in BENCHMARKS.md. emeans-core imports torch itself only to use or look for a
221
+ GPU: with `device="cuda"`, with `device="auto"` once `n × k >= gpu_threshold` (when torch is
222
+ installed), and in `backend_info()` and `collect_env()` unless `include_gpu=False`. With
223
+ `device="cpu"` it does not.
224
+ - `deterministic=True` requests PyTorch deterministic algorithms while training on a GPU
225
+ (process-wide while it runs). GPU fits are not expected to match CPU fits bit for bit: tests
226
+ compare them by partition agreement (ARI). GPU duplicate decisions are tested for exact
227
+ equality with the reference loop.
228
+
229
+ ## Benchmarks
230
+
231
+ [BENCHMARKS.md](https://github.com/ogaude/emeans-core/blob/main/BENCHMARKS.md): dedup on 100k and
232
+ 1M synthetic vectors (CPU, GPU, three precisions), recall against the exact rule for 0 to 2
233
+ neighbouring clusters, CPU against GPU fit times, first-call cost, threads, and the small-input
234
+ seeding defaults, each with its platform manifest. Those results were recorded by
235
+ emeans-langchain on the code that moved here; the file says which runs.
236
+
237
+ ## Bug reports
238
+
239
+ Please include the sanitised platform manifest:
240
+
241
+ ```bash
242
+ python -m emeans_core.env --alias my-machine
243
+ ```
244
+
245
+ It replaces the hostname, username and home directory in every field, identifies the host only by
246
+ the alias you give (`--alias` or `EMEANS_HOST_ALIAS`), and reads environment variables from a short
247
+ allowlist only (thread counts, visible devices, the ROCm GFX override, PyTorch allocator settings).
248
+
249
+ ## License
250
+
251
+ MIT. e-means comes from faiss (MIT, Meta Platforms) and, optionally, emeans-rocm (MIT); see
252
+ [THIRD_PARTY_NOTICES.md](https://github.com/ogaude/emeans-core/blob/main/THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,6 @@
1
+ # Third-party notices
2
+
3
+ ## e-means
4
+
5
+ e-means is not vendored. It is used through `faiss-cpu` (`faiss.contrib.e_means`, MIT License,
6
+ Copyright (c) Meta Platforms, Inc. and affiliates) and, optionally, `emeans-rocm` (MIT License).