emeans-langchain 0.1.1__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,47 @@
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).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.1] - 2026-12-04
10
+
11
+ First release on PyPI. 0.1.0 was only uploaded to TestPyPI as a release rehearsal; 0.1.1 adds a
12
+ recorded comparison behind the small-input `init` / `nepochs` defaults (`init` benchmark workload
13
+ and its section in `BENCHMARKS.md`) and is otherwise the same code.
14
+
15
+ ### Added
16
+
17
+ - `EMeansClusteringFilter`: drop-in replacement for langchain-community's
18
+ `EmbeddingsClusteringFilter` (same parameters, defaults and selection rules), clustering with
19
+ e-means; parity tests against the original.
20
+ - `EMeansDiversityCompressor`: diversity reranker for `ContextualCompressionRetriever`, reusing
21
+ vectors from document metadata and an optional `EmbeddingCache`.
22
+ - `EMeansDedupTransformer`: ingest-time near-duplicate removal (e-means blocking, FP32 cosine
23
+ check), `keep="first" | "longest"`, `mode="report"`, `find_duplicates()` /
24
+ `find_duplicates_vectors()`, incremental ingestion against `ReferenceVectors` or a LangChain
25
+ `VectorStore`, re-splitting of oversized clusters and memory-bounded similarity blocks.
26
+ - Backends: CPU e-means from faiss-cpu (default), GPU through `emeans-rocm` (`[rocm]`) or stock
27
+ faiss e-means with torch (`[gpu]`); `device`, `precision`, `init`, `nepochs`, and `deterministic` (clustering filter and dedup).
28
+ - `python -m emeans_langchain.env`: sanitised platform manifest for bug reports and benchmarks.
29
+ - `device="auto"` moves to the GPU at `n * k >= 1e6` (`gpu_threshold`), from GPU measurements
30
+ on an RX 9060 XT; retrieval-sized inputs stay on the CPU.
31
+ - The duplicate check compares candidates with matrix products and resolves the leader rule only
32
+ over rows that have candidates, with the same result as the row-by-row rule (1M rows, d=1024,
33
+ 1 neighbour: 91 s on a 10-core CPU, 244 s with a row-by-row check). When e-means runs on the
34
+ GPU, the candidate similarities are computed there too (same input: 9 s; 21 s with the products
35
+ on the CPU, 112 s row by row).
36
+ - The duplicate check stays fast and memory-bounded on piles of identical or near-identical
37
+ chunks, and stays exact when the host process enables reduced-precision GPU matrix products
38
+ (TF32, bf16): pairs near the threshold are confirmed in FP32 on the CPU. Input normalisation
39
+ works in row chunks, so it needs no whole-matrix temporaries.
40
+ - `neighbor_clusters` defaults to 2: it finds about half of the exact comparison's drops that 1
41
+ misses, for 3 to 11% more time on 1M synthetic rows (CPU and GPU) and no measurable difference
42
+ on real chunks.
43
+ - Benchmark scripts (`benchmarks/`) with JSONL results and a generated `BENCHMARKS.md`, including
44
+ the partition quality of the small-input `init` / `nepochs` defaults.
45
+
46
+ [Unreleased]: https://github.com/ogaude/emeans-langchain/compare/v0.1.1...HEAD
47
+ [0.1.1]: https://github.com/ogaude/emeans-langchain/releases/tag/v0.1.1
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ogaude
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,304 @@
1
+ Metadata-Version: 2.5
2
+ Name: emeans-langchain
3
+ Version: 0.1.1
4
+ Summary: LangChain document transformers and a diversity compressor built on e-means k-means (CPU, optional ROCm/CUDA GPU)
5
+ Project-URL: Source, https://github.com/ogaude/emeans-langchain
6
+ Project-URL: Issues, https://github.com/ogaude/emeans-langchain/issues
7
+ Project-URL: Changelog, https://github.com/ogaude/emeans-langchain/blob/main/CHANGELOG.md
8
+ Project-URL: Benchmarks, https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md
9
+ Author: ogaude
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ License-File: THIRD_PARTY_NOTICES.md
13
+ Keywords: clustering,deduplication,e-means,faiss,k-means,langchain,langchain-integration,rag,reranking,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>=1.16.0
25
+ Requires-Dist: langchain-core<2.0.0,>=1.0.0
26
+ Requires-Dist: numpy>=2.0
27
+ Provides-Extra: examples
28
+ Requires-Dist: langchain-classic>=1.0.0; extra == 'examples'
29
+ Provides-Extra: gpu
30
+ Requires-Dist: torch; extra == 'gpu'
31
+ Provides-Extra: rocm
32
+ Requires-Dist: emeans-rocm<0.3,>=0.2.5; extra == 'rocm'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # emeans-langchain
36
+
37
+ LangChain document transformers and a document compressor built on
38
+ [e-means](https://github.com/ogaude/e-means-rocm), the mini-batch k-means from faiss
39
+ `contrib/e_means`. It runs on the CPU out of the box; an AMD (ROCm) or NVIDIA GPU can be used
40
+ for large ingestion batches.
41
+
42
+ | Component | LangChain base class | What it does |
43
+ |---|---|---|
44
+ | `EMeansClusteringFilter` | `BaseDocumentTransformer` | Drop-in replacement for `langchain_community`'s `EmbeddingsClusteringFilter` |
45
+ | `EMeansDiversityCompressor` | `BaseDocumentCompressor` | Diversity reranker for `ContextualCompressionRetriever`: best documents from different clusters |
46
+ | `EMeansDedupTransformer` | `BaseDocumentTransformer` | Ingest-time near-duplicate chunk removal, with an audit report and incremental ingestion |
47
+
48
+ Status: alpha (0.1.1). The package name follows my other e-means integrations
49
+ ([emeans-haystack](https://github.com/ogaude/emeans-haystack),
50
+ [emeans-dify](https://github.com/ogaude/emeans-dify)) rather than `langchain-<provider>`.
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pip install emeans-langchain # CPU: langchain-core, numpy, faiss-cpu
56
+ ```
57
+
58
+ The CPU backend is e-means itself (`NumpyEmeans`, which ships with `faiss-cpu`), not a
59
+ different k-means. A GPU is optional:
60
+
61
+ ```bash
62
+ # AMD GPU (ROCm): install a ROCm build of torch first, then the emeans-rocm port.
63
+ # Example for an RX 9000 card (gfx1200) on ROCm 10.1; see the emeans-rocm README for other targets.
64
+ pip install --extra-index-url https://stable.repo.amd.com/rocm/whl-next/ "torch[device-gfx1200]==2.14.0+rocm10.1.0"
65
+ pip install "emeans-langchain[rocm]"
66
+
67
+ # NVIDIA GPU: install a CUDA build of torch, then
68
+ pip install "emeans-langchain[gpu]"
69
+ ```
70
+
71
+ `[rocm]` adds `emeans-rocm` (AMD kernels through Triton) and does not install torch. `[gpu]` only
72
+ requires `torch` and uses the stock faiss e-means GPU code: if no torch is installed, pip takes the
73
+ PyPI wheel (a CUDA build on Linux x86-64, never ROCm). Install the torch build for your GPU first.
74
+
75
+ **Supported GPUs**: AMD through ROCm, as covered by emeans-rocm (RX 9000 / gfx120x tested by
76
+ emeans-rocm; other targets compile-checked there). NVIDIA through CUDA uses upstream faiss
77
+ e-means, which supports it, but **this package has not been tested on an NVIDIA GPU**. The GPU
78
+ tests and the GPU columns in [BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md) were run on an AMD Radeon RX 9060 XT
79
+ (gfx1200) with torch 2.14 for ROCm 10.1 and emeans-rocm 0.2.11; GPU tests skip themselves when
80
+ torch sees no GPU.
81
+
82
+ ## Examples
83
+
84
+ ### 1. Drop-in swap for `EmbeddingsClusteringFilter`
85
+
86
+ ```diff
87
+ -from langchain_community.document_transformers import EmbeddingsClusteringFilter
88
+ +from emeans_langchain import EMeansClusteringFilter as EmbeddingsClusteringFilter
89
+
90
+ filter = EmbeddingsClusteringFilter(embeddings=embeddings, num_clusters=5, num_closest=1)
91
+ docs = filter.transform_documents(docs)
92
+ ```
93
+
94
+ Same parameters, defaults and output rules (`num_clusters=5`, `num_closest=1`,
95
+ `random_state=42`, `sorted=False`, `remove_duplicates=False`), and the same `ValueError` when
96
+ there are fewer documents than clusters. Documented differences:
97
+
98
+ - an empty input returns `[]` (the original raises inside scikit-learn);
99
+ - embeddings are L2-normalised before clustering (`normalize=True`); pass `normalize=False`
100
+ to cluster raw vectors by Euclidean distance like the original;
101
+ - returned documents get `metadata["emeans_cluster_id"]` (opt out with `add_metadata=False`);
102
+ - the original returns stateful documents that carry their embedding for the next filter in a
103
+ `DocumentCompressorPipeline`; this one returns plain `Document` copies when it adds metadata
104
+ (stateful inputs stay stateful);
105
+ - e-means and scikit-learn's `KMeans` are different algorithms. On well-separated clusters the
106
+ tests get the same documents as the original. On overlapping clusters the partitions differ
107
+ legitimately. On the noisy clusters of [BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md) the two agree fully
108
+ at 100 and 1,000 points (ARI 1.0); at 10,000 points in 50 clusters the ARI between them is
109
+ 0.91, and against the true clusters 0.97 for e-means and 0.93 for scikit-learn.
110
+
111
+ It also reads vectors that are already known (from a vector store's `metadata["embedding"]`,
112
+ from the stateful documents of `EmbeddingsRedundantFilter`, or from an `EmbeddingCache`)
113
+ instead of embedding again.
114
+
115
+ ### 2. Diversity reranking in a compression retriever
116
+
117
+ ```python
118
+ from langchain_classic.retrievers import ContextualCompressionRetriever # pip install langchain-classic
119
+ from emeans_langchain import EmbeddingCache, EMeansDiversityCompressor
120
+
121
+ compressor = EMeansDiversityCompressor(
122
+ embeddings=embeddings,
123
+ top_n=4, # documents returned
124
+ embedding_cache=EmbeddingCache(), # documents seen in earlier queries are not embedded again
125
+ )
126
+ retriever = ContextualCompressionRetriever(
127
+ base_compressor=compressor,
128
+ base_retriever=vector_store.as_retriever(search_kwargs={"k": 20}),
129
+ )
130
+ docs = retriever.invoke("how do I rotate the API keys?")
131
+ ```
132
+
133
+ The retrieved documents are split into `top_n` clusters (`num_clusters`), each cluster
134
+ contributes its document most similar to the query (`docs_per_cluster=1`), and the result is
135
+ ordered by cosine similarity to the query. Each document gets `emeans_cluster_id` and
136
+ `emeans_query_similarity` metadata. Retrieval sizes are small, so this runs on the CPU (about
137
+ 5.5 to 19 ms per query for 20 to 100 documents on a 10-core desktop CPU; see [BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md)).
138
+
139
+ `ContextualCompressionRetriever` now lives in `langchain-classic`; this package only depends
140
+ on `langchain-core`.
141
+
142
+ ### 3. Ingest-time deduplication
143
+
144
+ ```python
145
+ from emeans_langchain import EMeansDedupTransformer, ReferenceVectors
146
+
147
+ dedup = EMeansDedupTransformer(embeddings=embeddings, threshold=0.92, keep="first")
148
+ unique_chunks = dedup.transform_documents(chunks)
149
+
150
+ # Audit before dropping anything:
151
+ report = dedup.find_duplicates(chunks)
152
+ for drop in report.drops:
153
+ leader = drop.kept_index if drop.kept_index is not None else drop.reference_id
154
+ print(drop.index, "duplicates", leader, round(drop.score, 3))
155
+
156
+ # Incremental ingestion: also compare with what is already indexed.
157
+ dedup = EMeansDedupTransformer(embeddings=embeddings, reference=vector_store) # any LangChain VectorStore
158
+ dedup = EMeansDedupTransformer(
159
+ embeddings=embeddings, reference=ReferenceVectors(vectors=indexed_matrix, ids=indexed_ids)
160
+ )
161
+ ```
162
+
163
+ How it works: e-means splits the batch into `round(sqrt(n))` clusters (blocking). Each chunk is
164
+ compared, in FP32 cosine similarity, with the chunks already kept in its own cluster and in the
165
+ `neighbor_clusters=2` nearest other clusters; at or above `threshold` it is dropped and the kept
166
+ chunk records it in `metadata["emeans_duplicates"]` (index, id, source, score). Every drop is a
167
+ verified pair above the threshold; a duplicate whose partner falls in a cluster that is not
168
+ searched is kept, never the other way round. With `num_clusters=None` (default), batches of at
169
+ most `max_cluster_size` (4,096) chunks are compared exactly, without clustering.
170
+
171
+ - `keep="first" | "longest"` chooses the survivor of a duplicate group.
172
+ - `mode="report"` drops nothing: proposed drops get `emeans_duplicate_of` metadata, their
173
+ keepers `emeans_duplicates` (and every chunk `emeans_cluster_id` when clustering ran);
174
+ `find_duplicates()` returns a `DedupReport` with scores.
175
+ - Clusters larger than `max_cluster_size` are split again with e-means; all similarities are
176
+ computed in bounded blocks, never as an N×N matrix.
177
+ - `find_duplicates_vectors(matrix)` deduplicates a precomputed matrix without `Document` objects.
178
+ - `reference=`: a `VectorStore` is queried with `similarity_search_by_vector` (`reference_k=4`
179
+ neighbours per chunk); the neighbours are re-embedded (or read from
180
+ `metadata["embedding"]`) so that the same FP32 cosine threshold applies. With a large batch this
181
+ makes one store query per chunk. `ReferenceVectors` is checked in memory with the same blocking.
182
+ - The threshold depends on the embedding model: 0.92 is a starting point, check it with
183
+ `mode="report"` on your data. On overlapping book chunks embedded with bge-small
184
+ ([BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md)), 0.92 found 66% of the chunks sharing at least 80% of their text with an
185
+ earlier one, with 98% of drops sharing at least half their text; 0.95 found 32%.
186
+ - Blocking is for large batches. On that 20k-chunk corpus, exact comparison
187
+ (`num_clusters=1, max_cluster_size=10**9`) took 0.6 s against 1.4 s for blocking on the CPU,
188
+ and recalled more (66% against 62% with 1 neighbour and 64% with 2). With e-means on an
189
+ RX 9060 XT, blocking took 0.30 to 0.36 s (e-means 41 to 50 ms against 1.1 s on the CPU) with
190
+ about the same recall. On 100k synthetic vectors, blocking took 2.3 to 5.6 s on a 10-core CPU
191
+ and 0.42 to 0.83 s with the GPU, with 99% recall. On 1M vectors it took 38 to 91 s on the CPU,
192
+ of which e-means training was 25 to 62 s, and 3.6 to 9 s with the GPU (e-means 0.7 to 1.8 s in
193
+ fp32, 0.14 to 0.5 s in bf16/fp16, same recall). With a GPU, the duplicate check's similarity
194
+ products run there too; the leader rule itself and input normalisation stay on the CPU. These
195
+ timings use `neighbor_clusters=1`; the default of 2 costs 3 to 11% more on the synthetic data
196
+ (CPU and GPU) and is within noise on the real corpus.
197
+ - Recall against the exact comparison (every chunk against every earlier kept chunk), share of its
198
+ drops that blocking also makes (real chunks: CPU and GPU FP32; synthetic rows: GPU FP32):
199
+
200
+ | data | 0 neighbours | 1 neighbour | 2 neighbours (default) |
201
+ |---|---|---|---|
202
+ | real chunks, threshold 0.92 | 80% | 91% | 95% |
203
+ | real chunks, threshold 0.95 | 88% to 88.5% | 96% | 98% to 98.5% |
204
+ | 1M synthetic, d=384 | 89% | 96% | 98% |
205
+ | 1M synthetic, d=1024 | 96% | 99% | 99.4% |
206
+
207
+ Missed duplicates are kept, never wrongly dropped. On 1M rows with a GPU, the exact comparison
208
+ took 1.8 to 3.1 minutes against 4.6 to 9.5 s for 2 neighbours.
209
+
210
+ ## Backends, precision and determinism
211
+
212
+ | | CPU (default) | AMD GPU, `[rocm]` | NVIDIA GPU, `[gpu]` |
213
+ |---|---|---|---|
214
+ | Engine | faiss-cpu `NumpyEmeans` | `emeans_rocm` (Triton) | faiss `contrib.e_means` (torch) |
215
+ | `precision="fp32"` | yes | yes | yes (untested here) |
216
+ | `precision="bf16"` | falls back to fp32 (one warning) | yes | yes (untested here) |
217
+ | `precision="fp16"` | falls back to fp32 (one warning) | yes | yes (untested here) |
218
+ | Bit-identical repeats (same seed) | yes, tested | not guaranteed by default; see below | not guaranteed |
219
+
220
+ - `device="auto"` (default) uses a GPU only when one is visible to torch **and**
221
+ `n × k >= gpu_threshold` (default 1e6: about 10k documents in `sqrt(n)` clusters). Retrieval-
222
+ sized inputs stay on the CPU, where they are faster: on an RX 9060 XT, e-means training in a
223
+ warm process is 2 to 3× slower on the GPU at `n × k = 1e3`, 1.4 to 5× faster at 1e4, 7 to 8×
224
+ faster at 1e6 and 23 to 28× faster from 1e7 up. The first GPU fit in a process takes about
225
+ 1.6 s (torch import, HIP start-up; 75 ms on the CPU), which 1e6 pays back within a few calls;
226
+ raise `gpu_threshold` for one-off
227
+ scripts on mid-sized batches, or pass `device="cpu"`. `device="cpu"` or `device="cuda"` forces a backend; `"cuda"` also
228
+ means AMD GPUs under ROCm, as in torch. The active backend is logged once (logger
229
+ `emeans_langchain`). If a GPU fit fails under `"auto"`, the CPU runs it instead with a warning.
230
+ - `precision` only affects GPU training. Cluster labels always come from an FP32 assignment, and
231
+ every duplicate decision is an FP32 cosine similarity.
232
+ - `normalize=True` (default) L2-normalises vectors and runs e-means in spherical mode, so
233
+ Euclidean k-means distances rank documents the same way as cosine similarity. With
234
+ `normalize=False`, clustering uses raw Euclidean distances (vector length matters; the
235
+ clustering filter then allows all-zero vectors). Dedup scores are cosine similarities in both cases.
236
+ - `init="auto"` seeds with k-means++ when `n × k <= 1e7` and uses e-means' seeded sample
237
+ otherwise; `nepochs=None` means 20 epochs for those small problems and 5 otherwise. e-means'
238
+ batch laws pick very small batches on tiny inputs. On noisy synthetic clusters of 20 to 1,024
239
+ rows (d=384, 30 seeds per case), plain e-means (sampled seeds, 5 epochs) left an inertia 2 to
240
+ 33% higher than these defaults (mean per-seed change), and agreed less with the true clusters
241
+ (mean ARI 0.87 to 0.99 against 0.97 to 1.00). The k-means++ seeding gives most of the gain
242
+ (BENCHMARKS.md, small-input defaults section).
243
+ - Small CPU fits (`n × k × d <= 2e8`) run faiss single-threaded, scoped to the calling thread:
244
+ OpenMP start-up cost dominates them (75 ms against 7 ms for 50 documents), and larger fits up to
245
+ `1e9` were never more than about 10% slower single-threaded (backend section of BENCHMARKS.md).
246
+ - **Determinism**: on the CPU, the same seed and input give bit-identical output (tested).
247
+ On a GPU, emeans-rocm reports bit-identical repeats on an RX 9060 XT for the default Triton
248
+ paths with revival on, but not on every path (PyTorch fallback, some dimensions). Pass
249
+ `deterministic=True` (clustering filter and dedup) to request PyTorch deterministic algorithms while training (process-wide
250
+ while it runs). GPU tests compare with tolerances (ARI), not exact equality. GPU results are
251
+ not expected to match CPU results bit for bit.
252
+
253
+ ## Edge cases
254
+
255
+ | Input | Behaviour |
256
+ |---|---|
257
+ | Empty list | Empty list, no embedding call |
258
+ | One document | Dedup: returned as is. Filter (needs `num_clusters=1`, like the original) and compressor: returned with their `emeans_` metadata |
259
+ | Fewer documents than `num_clusters` | Filter: `ValueError` like `EmbeddingsClusteringFilter`. Compressor and dedup: `k` clamped (with a warning when `num_clusters` was set) |
260
+ | All-zero vector | `ValueError` naming the document index (it has no direction); allowed by the clustering filter with `normalize=False` |
261
+ | NaN / infinite values | `ValueError` naming the document index |
262
+ | Mixed embedding dimensions | `ValueError` |
263
+ | Exact duplicates | Filter / compressor: clustered together; dedup: dropped with a score of 1.0 (up to FP32 rounding) |
264
+
265
+ Metadata keys written by this package all start with `emeans_`. Existing keys are never
266
+ overwritten (a warning is logged once), input metadata is never mutated (stateful documents get
267
+ their computed embedding in `state`, as with langchain-community), and `add_metadata=False` turns
268
+ it off.
269
+
270
+ ## Async
271
+
272
+ `atransform_documents` and `acompress_documents` call the embeddings' async methods
273
+ (`aembed_documents`, `aembed_query`) and, for a `VectorStore` reference,
274
+ `asimilarity_search_by_vector`; clustering and the duplicate check run in a worker thread
275
+ (`asyncio.to_thread`). The embedding lists are converted to a float32 matrix and checked on the
276
+ event loop, and with a `VectorStore` reference so is the per-chunk comparison with its hits
277
+ (`reference_k` vectors per chunk).
278
+
279
+ `import emeans_langchain` does not import faiss, torch or emeans-rocm; the backend loads on first
280
+ use, once per process, under a lock.
281
+
282
+ ## Benchmarks
283
+
284
+ See [BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md): dedup on synthetic (100k / 1M vectors, d = 384 / 768 / 1024)
285
+ and real data (overlapping chunks of public-domain books), reranker latency, and a comparison
286
+ with `EmbeddingsClusteringFilter`, each with its platform manifest. GPU columns are filled from
287
+ runs on a real GPU only.
288
+
289
+ ## Bug reports
290
+
291
+ Please include the sanitised platform manifest:
292
+
293
+ ```bash
294
+ python -m emeans_langchain.env --alias my-machine
295
+ ```
296
+
297
+ It contains no hostname, username, home directory or environment variable outside a short
298
+ allowlist (thread counts, visible devices, HIP/ROCm settings).
299
+
300
+ ## License
301
+
302
+ MIT. `select_closest` in `clustering_filter.py` is adapted from langchain-community (MIT); see
303
+ [THIRD_PARTY_NOTICES.md](https://github.com/ogaude/emeans-langchain/blob/main/THIRD_PARTY_NOTICES.md). e-means comes from faiss (MIT, Meta Platforms)
304
+ and emeans-rocm (MIT).
@@ -0,0 +1,270 @@
1
+ # emeans-langchain
2
+
3
+ LangChain document transformers and a document compressor built on
4
+ [e-means](https://github.com/ogaude/e-means-rocm), the mini-batch k-means from faiss
5
+ `contrib/e_means`. It runs on the CPU out of the box; an AMD (ROCm) or NVIDIA GPU can be used
6
+ for large ingestion batches.
7
+
8
+ | Component | LangChain base class | What it does |
9
+ |---|---|---|
10
+ | `EMeansClusteringFilter` | `BaseDocumentTransformer` | Drop-in replacement for `langchain_community`'s `EmbeddingsClusteringFilter` |
11
+ | `EMeansDiversityCompressor` | `BaseDocumentCompressor` | Diversity reranker for `ContextualCompressionRetriever`: best documents from different clusters |
12
+ | `EMeansDedupTransformer` | `BaseDocumentTransformer` | Ingest-time near-duplicate chunk removal, with an audit report and incremental ingestion |
13
+
14
+ Status: alpha (0.1.1). The package name follows my other e-means integrations
15
+ ([emeans-haystack](https://github.com/ogaude/emeans-haystack),
16
+ [emeans-dify](https://github.com/ogaude/emeans-dify)) rather than `langchain-<provider>`.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install emeans-langchain # CPU: langchain-core, numpy, faiss-cpu
22
+ ```
23
+
24
+ The CPU backend is e-means itself (`NumpyEmeans`, which ships with `faiss-cpu`), not a
25
+ different k-means. A GPU is optional:
26
+
27
+ ```bash
28
+ # AMD GPU (ROCm): install a ROCm build of torch first, then the emeans-rocm port.
29
+ # Example for an RX 9000 card (gfx1200) on ROCm 10.1; see the emeans-rocm README for other targets.
30
+ pip install --extra-index-url https://stable.repo.amd.com/rocm/whl-next/ "torch[device-gfx1200]==2.14.0+rocm10.1.0"
31
+ pip install "emeans-langchain[rocm]"
32
+
33
+ # NVIDIA GPU: install a CUDA build of torch, then
34
+ pip install "emeans-langchain[gpu]"
35
+ ```
36
+
37
+ `[rocm]` adds `emeans-rocm` (AMD kernels through Triton) and does not install torch. `[gpu]` only
38
+ requires `torch` and uses the stock faiss e-means GPU code: if no torch is installed, pip takes the
39
+ PyPI wheel (a CUDA build on Linux x86-64, never ROCm). Install the torch build for your GPU first.
40
+
41
+ **Supported GPUs**: AMD through ROCm, as covered by emeans-rocm (RX 9000 / gfx120x tested by
42
+ emeans-rocm; other targets compile-checked there). NVIDIA through CUDA uses upstream faiss
43
+ e-means, which supports it, but **this package has not been tested on an NVIDIA GPU**. The GPU
44
+ tests and the GPU columns in [BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md) were run on an AMD Radeon RX 9060 XT
45
+ (gfx1200) with torch 2.14 for ROCm 10.1 and emeans-rocm 0.2.11; GPU tests skip themselves when
46
+ torch sees no GPU.
47
+
48
+ ## Examples
49
+
50
+ ### 1. Drop-in swap for `EmbeddingsClusteringFilter`
51
+
52
+ ```diff
53
+ -from langchain_community.document_transformers import EmbeddingsClusteringFilter
54
+ +from emeans_langchain import EMeansClusteringFilter as EmbeddingsClusteringFilter
55
+
56
+ filter = EmbeddingsClusteringFilter(embeddings=embeddings, num_clusters=5, num_closest=1)
57
+ docs = filter.transform_documents(docs)
58
+ ```
59
+
60
+ Same parameters, defaults and output rules (`num_clusters=5`, `num_closest=1`,
61
+ `random_state=42`, `sorted=False`, `remove_duplicates=False`), and the same `ValueError` when
62
+ there are fewer documents than clusters. Documented differences:
63
+
64
+ - an empty input returns `[]` (the original raises inside scikit-learn);
65
+ - embeddings are L2-normalised before clustering (`normalize=True`); pass `normalize=False`
66
+ to cluster raw vectors by Euclidean distance like the original;
67
+ - returned documents get `metadata["emeans_cluster_id"]` (opt out with `add_metadata=False`);
68
+ - the original returns stateful documents that carry their embedding for the next filter in a
69
+ `DocumentCompressorPipeline`; this one returns plain `Document` copies when it adds metadata
70
+ (stateful inputs stay stateful);
71
+ - e-means and scikit-learn's `KMeans` are different algorithms. On well-separated clusters the
72
+ tests get the same documents as the original. On overlapping clusters the partitions differ
73
+ legitimately. On the noisy clusters of [BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md) the two agree fully
74
+ at 100 and 1,000 points (ARI 1.0); at 10,000 points in 50 clusters the ARI between them is
75
+ 0.91, and against the true clusters 0.97 for e-means and 0.93 for scikit-learn.
76
+
77
+ It also reads vectors that are already known (from a vector store's `metadata["embedding"]`,
78
+ from the stateful documents of `EmbeddingsRedundantFilter`, or from an `EmbeddingCache`)
79
+ instead of embedding again.
80
+
81
+ ### 2. Diversity reranking in a compression retriever
82
+
83
+ ```python
84
+ from langchain_classic.retrievers import ContextualCompressionRetriever # pip install langchain-classic
85
+ from emeans_langchain import EmbeddingCache, EMeansDiversityCompressor
86
+
87
+ compressor = EMeansDiversityCompressor(
88
+ embeddings=embeddings,
89
+ top_n=4, # documents returned
90
+ embedding_cache=EmbeddingCache(), # documents seen in earlier queries are not embedded again
91
+ )
92
+ retriever = ContextualCompressionRetriever(
93
+ base_compressor=compressor,
94
+ base_retriever=vector_store.as_retriever(search_kwargs={"k": 20}),
95
+ )
96
+ docs = retriever.invoke("how do I rotate the API keys?")
97
+ ```
98
+
99
+ The retrieved documents are split into `top_n` clusters (`num_clusters`), each cluster
100
+ contributes its document most similar to the query (`docs_per_cluster=1`), and the result is
101
+ ordered by cosine similarity to the query. Each document gets `emeans_cluster_id` and
102
+ `emeans_query_similarity` metadata. Retrieval sizes are small, so this runs on the CPU (about
103
+ 5.5 to 19 ms per query for 20 to 100 documents on a 10-core desktop CPU; see [BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md)).
104
+
105
+ `ContextualCompressionRetriever` now lives in `langchain-classic`; this package only depends
106
+ on `langchain-core`.
107
+
108
+ ### 3. Ingest-time deduplication
109
+
110
+ ```python
111
+ from emeans_langchain import EMeansDedupTransformer, ReferenceVectors
112
+
113
+ dedup = EMeansDedupTransformer(embeddings=embeddings, threshold=0.92, keep="first")
114
+ unique_chunks = dedup.transform_documents(chunks)
115
+
116
+ # Audit before dropping anything:
117
+ report = dedup.find_duplicates(chunks)
118
+ for drop in report.drops:
119
+ leader = drop.kept_index if drop.kept_index is not None else drop.reference_id
120
+ print(drop.index, "duplicates", leader, round(drop.score, 3))
121
+
122
+ # Incremental ingestion: also compare with what is already indexed.
123
+ dedup = EMeansDedupTransformer(embeddings=embeddings, reference=vector_store) # any LangChain VectorStore
124
+ dedup = EMeansDedupTransformer(
125
+ embeddings=embeddings, reference=ReferenceVectors(vectors=indexed_matrix, ids=indexed_ids)
126
+ )
127
+ ```
128
+
129
+ How it works: e-means splits the batch into `round(sqrt(n))` clusters (blocking). Each chunk is
130
+ compared, in FP32 cosine similarity, with the chunks already kept in its own cluster and in the
131
+ `neighbor_clusters=2` nearest other clusters; at or above `threshold` it is dropped and the kept
132
+ chunk records it in `metadata["emeans_duplicates"]` (index, id, source, score). Every drop is a
133
+ verified pair above the threshold; a duplicate whose partner falls in a cluster that is not
134
+ searched is kept, never the other way round. With `num_clusters=None` (default), batches of at
135
+ most `max_cluster_size` (4,096) chunks are compared exactly, without clustering.
136
+
137
+ - `keep="first" | "longest"` chooses the survivor of a duplicate group.
138
+ - `mode="report"` drops nothing: proposed drops get `emeans_duplicate_of` metadata, their
139
+ keepers `emeans_duplicates` (and every chunk `emeans_cluster_id` when clustering ran);
140
+ `find_duplicates()` returns a `DedupReport` with scores.
141
+ - Clusters larger than `max_cluster_size` are split again with e-means; all similarities are
142
+ computed in bounded blocks, never as an N×N matrix.
143
+ - `find_duplicates_vectors(matrix)` deduplicates a precomputed matrix without `Document` objects.
144
+ - `reference=`: a `VectorStore` is queried with `similarity_search_by_vector` (`reference_k=4`
145
+ neighbours per chunk); the neighbours are re-embedded (or read from
146
+ `metadata["embedding"]`) so that the same FP32 cosine threshold applies. With a large batch this
147
+ makes one store query per chunk. `ReferenceVectors` is checked in memory with the same blocking.
148
+ - The threshold depends on the embedding model: 0.92 is a starting point, check it with
149
+ `mode="report"` on your data. On overlapping book chunks embedded with bge-small
150
+ ([BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md)), 0.92 found 66% of the chunks sharing at least 80% of their text with an
151
+ earlier one, with 98% of drops sharing at least half their text; 0.95 found 32%.
152
+ - Blocking is for large batches. On that 20k-chunk corpus, exact comparison
153
+ (`num_clusters=1, max_cluster_size=10**9`) took 0.6 s against 1.4 s for blocking on the CPU,
154
+ and recalled more (66% against 62% with 1 neighbour and 64% with 2). With e-means on an
155
+ RX 9060 XT, blocking took 0.30 to 0.36 s (e-means 41 to 50 ms against 1.1 s on the CPU) with
156
+ about the same recall. On 100k synthetic vectors, blocking took 2.3 to 5.6 s on a 10-core CPU
157
+ and 0.42 to 0.83 s with the GPU, with 99% recall. On 1M vectors it took 38 to 91 s on the CPU,
158
+ of which e-means training was 25 to 62 s, and 3.6 to 9 s with the GPU (e-means 0.7 to 1.8 s in
159
+ fp32, 0.14 to 0.5 s in bf16/fp16, same recall). With a GPU, the duplicate check's similarity
160
+ products run there too; the leader rule itself and input normalisation stay on the CPU. These
161
+ timings use `neighbor_clusters=1`; the default of 2 costs 3 to 11% more on the synthetic data
162
+ (CPU and GPU) and is within noise on the real corpus.
163
+ - Recall against the exact comparison (every chunk against every earlier kept chunk), share of its
164
+ drops that blocking also makes (real chunks: CPU and GPU FP32; synthetic rows: GPU FP32):
165
+
166
+ | data | 0 neighbours | 1 neighbour | 2 neighbours (default) |
167
+ |---|---|---|---|
168
+ | real chunks, threshold 0.92 | 80% | 91% | 95% |
169
+ | real chunks, threshold 0.95 | 88% to 88.5% | 96% | 98% to 98.5% |
170
+ | 1M synthetic, d=384 | 89% | 96% | 98% |
171
+ | 1M synthetic, d=1024 | 96% | 99% | 99.4% |
172
+
173
+ Missed duplicates are kept, never wrongly dropped. On 1M rows with a GPU, the exact comparison
174
+ took 1.8 to 3.1 minutes against 4.6 to 9.5 s for 2 neighbours.
175
+
176
+ ## Backends, precision and determinism
177
+
178
+ | | CPU (default) | AMD GPU, `[rocm]` | NVIDIA GPU, `[gpu]` |
179
+ |---|---|---|---|
180
+ | Engine | faiss-cpu `NumpyEmeans` | `emeans_rocm` (Triton) | faiss `contrib.e_means` (torch) |
181
+ | `precision="fp32"` | yes | yes | yes (untested here) |
182
+ | `precision="bf16"` | falls back to fp32 (one warning) | yes | yes (untested here) |
183
+ | `precision="fp16"` | falls back to fp32 (one warning) | yes | yes (untested here) |
184
+ | Bit-identical repeats (same seed) | yes, tested | not guaranteed by default; see below | not guaranteed |
185
+
186
+ - `device="auto"` (default) uses a GPU only when one is visible to torch **and**
187
+ `n × k >= gpu_threshold` (default 1e6: about 10k documents in `sqrt(n)` clusters). Retrieval-
188
+ sized inputs stay on the CPU, where they are faster: on an RX 9060 XT, e-means training in a
189
+ warm process is 2 to 3× slower on the GPU at `n × k = 1e3`, 1.4 to 5× faster at 1e4, 7 to 8×
190
+ faster at 1e6 and 23 to 28× faster from 1e7 up. The first GPU fit in a process takes about
191
+ 1.6 s (torch import, HIP start-up; 75 ms on the CPU), which 1e6 pays back within a few calls;
192
+ raise `gpu_threshold` for one-off
193
+ scripts on mid-sized batches, or pass `device="cpu"`. `device="cpu"` or `device="cuda"` forces a backend; `"cuda"` also
194
+ means AMD GPUs under ROCm, as in torch. The active backend is logged once (logger
195
+ `emeans_langchain`). If a GPU fit fails under `"auto"`, the CPU runs it instead with a warning.
196
+ - `precision` only affects GPU training. Cluster labels always come from an FP32 assignment, and
197
+ every duplicate decision is an FP32 cosine similarity.
198
+ - `normalize=True` (default) L2-normalises vectors and runs e-means in spherical mode, so
199
+ Euclidean k-means distances rank documents the same way as cosine similarity. With
200
+ `normalize=False`, clustering uses raw Euclidean distances (vector length matters; the
201
+ clustering filter then allows all-zero vectors). Dedup scores are cosine similarities in both cases.
202
+ - `init="auto"` seeds with k-means++ when `n × k <= 1e7` and uses e-means' seeded sample
203
+ otherwise; `nepochs=None` means 20 epochs for those small problems and 5 otherwise. e-means'
204
+ batch laws pick very small batches on tiny inputs. On noisy synthetic clusters of 20 to 1,024
205
+ rows (d=384, 30 seeds per case), plain e-means (sampled seeds, 5 epochs) left an inertia 2 to
206
+ 33% higher than these defaults (mean per-seed change), and agreed less with the true clusters
207
+ (mean ARI 0.87 to 0.99 against 0.97 to 1.00). The k-means++ seeding gives most of the gain
208
+ (BENCHMARKS.md, small-input defaults section).
209
+ - Small CPU fits (`n × k × d <= 2e8`) run faiss single-threaded, scoped to the calling thread:
210
+ OpenMP start-up cost dominates them (75 ms against 7 ms for 50 documents), and larger fits up to
211
+ `1e9` were never more than about 10% slower single-threaded (backend section of BENCHMARKS.md).
212
+ - **Determinism**: on the CPU, the same seed and input give bit-identical output (tested).
213
+ On a GPU, emeans-rocm reports bit-identical repeats on an RX 9060 XT for the default Triton
214
+ paths with revival on, but not on every path (PyTorch fallback, some dimensions). Pass
215
+ `deterministic=True` (clustering filter and dedup) to request PyTorch deterministic algorithms while training (process-wide
216
+ while it runs). GPU tests compare with tolerances (ARI), not exact equality. GPU results are
217
+ not expected to match CPU results bit for bit.
218
+
219
+ ## Edge cases
220
+
221
+ | Input | Behaviour |
222
+ |---|---|
223
+ | Empty list | Empty list, no embedding call |
224
+ | One document | Dedup: returned as is. Filter (needs `num_clusters=1`, like the original) and compressor: returned with their `emeans_` metadata |
225
+ | Fewer documents than `num_clusters` | Filter: `ValueError` like `EmbeddingsClusteringFilter`. Compressor and dedup: `k` clamped (with a warning when `num_clusters` was set) |
226
+ | All-zero vector | `ValueError` naming the document index (it has no direction); allowed by the clustering filter with `normalize=False` |
227
+ | NaN / infinite values | `ValueError` naming the document index |
228
+ | Mixed embedding dimensions | `ValueError` |
229
+ | Exact duplicates | Filter / compressor: clustered together; dedup: dropped with a score of 1.0 (up to FP32 rounding) |
230
+
231
+ Metadata keys written by this package all start with `emeans_`. Existing keys are never
232
+ overwritten (a warning is logged once), input metadata is never mutated (stateful documents get
233
+ their computed embedding in `state`, as with langchain-community), and `add_metadata=False` turns
234
+ it off.
235
+
236
+ ## Async
237
+
238
+ `atransform_documents` and `acompress_documents` call the embeddings' async methods
239
+ (`aembed_documents`, `aembed_query`) and, for a `VectorStore` reference,
240
+ `asimilarity_search_by_vector`; clustering and the duplicate check run in a worker thread
241
+ (`asyncio.to_thread`). The embedding lists are converted to a float32 matrix and checked on the
242
+ event loop, and with a `VectorStore` reference so is the per-chunk comparison with its hits
243
+ (`reference_k` vectors per chunk).
244
+
245
+ `import emeans_langchain` does not import faiss, torch or emeans-rocm; the backend loads on first
246
+ use, once per process, under a lock.
247
+
248
+ ## Benchmarks
249
+
250
+ See [BENCHMARKS.md](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md): dedup on synthetic (100k / 1M vectors, d = 384 / 768 / 1024)
251
+ and real data (overlapping chunks of public-domain books), reranker latency, and a comparison
252
+ with `EmbeddingsClusteringFilter`, each with its platform manifest. GPU columns are filled from
253
+ runs on a real GPU only.
254
+
255
+ ## Bug reports
256
+
257
+ Please include the sanitised platform manifest:
258
+
259
+ ```bash
260
+ python -m emeans_langchain.env --alias my-machine
261
+ ```
262
+
263
+ It contains no hostname, username, home directory or environment variable outside a short
264
+ allowlist (thread counts, visible devices, HIP/ROCm settings).
265
+
266
+ ## License
267
+
268
+ MIT. `select_closest` in `clustering_filter.py` is adapted from langchain-community (MIT); see
269
+ [THIRD_PARTY_NOTICES.md](https://github.com/ogaude/emeans-langchain/blob/main/THIRD_PARTY_NOTICES.md). e-means comes from faiss (MIT, Meta Platforms)
270
+ and emeans-rocm (MIT).