Skip to main content

emeans-langchain

LangChain document transformers and a document compressor built on e-means, the mini-batch k-means from faiss contrib/e_means. It runs on the CPU out of the box; an AMD (ROCm) or NVIDIA GPU can be used for large ingestion batches.

Component LangChain base class What it does
EMeansClusteringFilter BaseDocumentTransformer Drop-in replacement for langchain_community's EmbeddingsClusteringFilter
EMeansDiversityCompressor BaseDocumentCompressor Diversity reranker for ContextualCompressionRetriever: best documents from different clusters
EMeansDedupTransformer BaseDocumentTransformer Ingest-time near-duplicate chunk removal, with an audit report and incremental ingestion

Status: alpha (0.1.3). The package name follows my other e-means integrations (emeans-haystack, emeans-dify) rather than langchain-<provider>.

Install

pip install emeans-langchain            # CPU: langchain-core, emeans-core (numpy, faiss-cpu)

The CPU backend is e-means itself (NumpyEmeans, which ships with faiss-cpu), not a different k-means. The clustering backend and the duplicate check come from emeans-core, shared with the other emeans integrations. A GPU is optional, and needs a GPU build of torch that you install first:

# AMD GPU (ROCm): install a ROCm build of torch first, then the emeans-rocm port.
# Example for an RX 9060-series card (gfx1200) on ROCm 10.1; see the emeans-rocm README for other targets.
pip install --extra-index-url https://stable.repo.amd.com/rocm/whl-next/ "torch[device-gfx1200]==2.14.0+rocm10.1.0"
pip install "emeans-langchain[rocm]"

# NVIDIA GPU: install a CUDA build of torch, then the package; the stock faiss e-means GPU code is used.
pip install emeans-langchain

[rocm] adds emeans-rocm (AMD kernels through Triton, through emeans-core[rocm]) and does not install torch. There is no extra that installs torch: pip install torch without an index URL takes the PyPI wheel (a CUDA build on Linux x86-64, never ROCm), so pick the torch build for your GPU yourself. torch and emeans-rocm are detected when the backend first runs.

Supported GPUs: AMD through ROCm, as covered by emeans-rocm (RX 9000 / gfx120x tested by emeans-rocm; other targets compile-checked there). NVIDIA through CUDA uses upstream faiss e-means, which supports it, but this package has not been tested on an NVIDIA GPU. The GPU tests (in emeans-core, which holds the GPU code) and the GPU columns in BENCHMARKS.md were run on an AMD Radeon RX 9060 XT (gfx1200) with torch 2.14 for ROCm 10.1 and emeans-rocm 0.2.11.

Examples

1. Drop-in swap for EmbeddingsClusteringFilter

-from langchain_community.document_transformers import EmbeddingsClusteringFilter
+from emeans_langchain import EMeansClusteringFilter as EmbeddingsClusteringFilter

 filter = EmbeddingsClusteringFilter(embeddings=embeddings, num_clusters=5, num_closest=1)
 docs = filter.transform_documents(docs)

Same parameters, defaults and output rules (num_clusters=5, num_closest=1, random_state=42, sorted=False, remove_duplicates=False), and the same ValueError when there are fewer documents than clusters. Documented differences:

  • an empty input returns [] (the original raises inside scikit-learn);
  • embeddings are L2-normalised before clustering (normalize=True); pass normalize=False to cluster raw vectors by Euclidean distance like the original;
  • returned documents get metadata["emeans_cluster_id"] (opt out with add_metadata=False);
  • the original returns stateful documents that carry their embedding for the next filter in a DocumentCompressorPipeline; this one returns plain Document copies when it adds metadata (stateful inputs stay stateful);
  • e-means and scikit-learn's KMeans are different algorithms. On well-separated clusters the tests get the same documents as the original. On overlapping clusters the partitions differ legitimately. On the noisy clusters of BENCHMARKS.md the two agree fully at 100 and 1,000 points (ARI 1.0); at 10,000 points in 50 clusters the ARI between them is 0.91, and against the true clusters 0.97 for e-means and 0.93 for scikit-learn.

It also reads vectors that are already known (from a vector store's metadata["embedding"], from the stateful documents of EmbeddingsRedundantFilter, or from an EmbeddingCache) instead of embedding again.

2. Diversity reranking in a compression retriever

from langchain_classic.retrievers import ContextualCompressionRetriever   # pip install langchain-classic
from emeans_langchain import EmbeddingCache, EMeansDiversityCompressor

compressor = EMeansDiversityCompressor(
    embeddings=embeddings,
    top_n=4,                         # documents returned
    embedding_cache=EmbeddingCache(),  # documents seen in earlier queries are not embedded again
)
retriever = ContextualCompressionRetriever(
    base_compressor=compressor,
    base_retriever=vector_store.as_retriever(search_kwargs={"k": 20}),
)
docs = retriever.invoke("how do I rotate the API keys?")

The retrieved documents are split into top_n clusters (num_clusters), each cluster contributes its document most similar to the query (docs_per_cluster=1), and the result is ordered by cosine similarity to the query. Each document gets emeans_cluster_id and emeans_query_similarity metadata. Retrieval sizes are small, so this runs on the CPU (about 5.5 to 19 ms per query for 20 to 100 documents on a 10-core desktop CPU; see BENCHMARKS.md).

ContextualCompressionRetriever now lives in langchain-classic; this package only depends on langchain-core.

3. Ingest-time deduplication

from emeans_langchain import EMeansDedupTransformer, ReferenceVectors

dedup = EMeansDedupTransformer(embeddings=embeddings, threshold=0.92, keep="first")
unique_chunks = dedup.transform_documents(chunks)

# Audit before dropping anything:
report = dedup.find_duplicates(chunks)
for drop in report.drops:
    leader = drop.kept_index if drop.kept_index is not None else drop.reference_id
    print(drop.index, "duplicates", leader, round(drop.score, 3))

# Incremental ingestion: also compare with what is already indexed.
dedup = EMeansDedupTransformer(embeddings=embeddings, reference=vector_store)  # any LangChain VectorStore
dedup = EMeansDedupTransformer(
    embeddings=embeddings, reference=ReferenceVectors(vectors=indexed_matrix, ids=indexed_ids)
)

How it works: e-means splits the batch into round(sqrt(n)) clusters (blocking). Each chunk is compared, in FP32 cosine similarity, with the chunks already kept in its own cluster and in the neighbor_clusters=2 nearest other clusters; at or above threshold it is dropped and the kept chunk records it in metadata["emeans_duplicates"] (index, id, source, score). Every drop is a verified pair above the threshold; a duplicate whose partner falls in a cluster that is not searched is kept, never the other way round. With num_clusters=None (default), batches of at most max_cluster_size (4,096) chunks are compared exactly, without clustering.

  • keep="first" | "longest" chooses the survivor of a duplicate group.

  • mode="report" drops nothing: proposed drops get emeans_duplicate_of metadata, their keepers emeans_duplicates (and every chunk emeans_cluster_id when clustering ran); find_duplicates() returns a DedupReport with scores.

  • Clusters larger than max_cluster_size are split again with e-means; all similarities are computed in bounded blocks, never as an N×N matrix.

  • find_duplicates_vectors(matrix) deduplicates a precomputed matrix without Document objects.

  • reference=: a VectorStore is queried with similarity_search_by_vector (reference_k=4 neighbours per chunk); the neighbours are re-embedded (or read from metadata["embedding"]) so that the same FP32 cosine threshold applies. With a large batch this makes one store query per chunk. ReferenceVectors is checked in memory with the same blocking.

  • The threshold depends on the embedding model: 0.92 is a starting point, check it with mode="report" on your data. On overlapping book chunks embedded with bge-small (BENCHMARKS.md), 0.92 found 66% of the chunks sharing at least 80% of their text with an earlier one, with 98% of drops sharing at least half their text; 0.95 found 32%.

  • Blocking is for large batches. On that 20k-chunk corpus, exact comparison (num_clusters=1, max_cluster_size=10**9) took 0.6 s against 1.4 s for blocking on the CPU, and recalled more (66% against 62% with 1 neighbour and 64% with 2). With e-means on an 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 about the same recall. On 100k synthetic vectors, blocking took 2.3 to 5.6 s on a 10-core CPU 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, 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 fp32, 0.14 to 0.5 s in bf16/fp16, same recall). With a GPU, the duplicate check's similarity products run there too; the leader rule itself and input normalisation stay on the CPU. These timings use neighbor_clusters=1; the default of 2 costs 3 to 11% more on the synthetic data (CPU and GPU) and is within noise on the real corpus.

  • Recall against the exact comparison (every chunk against every earlier kept chunk), share of its drops that blocking also makes (real chunks: CPU and GPU FP32; synthetic rows: GPU FP32):

    data 0 neighbours 1 neighbour 2 neighbours (default)
    real chunks, threshold 0.92 80% 91% 95%
    real chunks, threshold 0.95 88% to 88.5% 96% 98% to 98.5%
    1M synthetic, d=384 89% 96% 98%
    1M synthetic, d=1024 96% 99% 99.4%

    Missed duplicates are kept, never wrongly dropped. On 1M rows with a GPU, the exact comparison took 1.8 to 3.1 minutes against 4.6 to 9.5 s for 2 neighbours.

Backends, precision and determinism

CPU (default) AMD GPU, [rocm] NVIDIA GPU (your CUDA torch)
Engine faiss-cpu NumpyEmeans emeans_rocm (Triton) faiss contrib.e_means (torch)
precision="fp32" yes yes yes (untested here)
precision="bf16" falls back to fp32 (one warning) yes yes (untested here)
precision="fp16" falls back to fp32 (one warning) yes yes (untested here)
Bit-identical repeats (same seed) yes, tested not guaranteed by default; see below not guaranteed
  • device="auto" (default) uses a GPU only when one is visible to torch and n × k >= gpu_threshold (default 1e6: about 10k documents in sqrt(n) clusters), so retrieval-sized inputs stay on the CPU. On an RX 9060 XT, in a warm process, the GPU's speed-up over the CPU fits of the same run was 0.31 to 0.51× at n × k = 1e3 (the GPU slower), 1.44 to 4.92× at 1.1e4, 7.09 to 7.85× at 1e6 and 22.99 to 27.96× at 1.1e7 to 3.2e7 (the largest measured). That run had imported torch first, which slowed its CPU fits of 500 to 5,000 documents: in the CPU-only run (started 2026-12-04 15:32 UTC), the CPU was also faster at 1.1e4 for d=384 (30.0 ms against the GPU's 35.0 ms). The first GPU fit in a process takes about 1.6 s (torch import, HIP start-up; 75 ms on the CPU in the same run): raise gpu_threshold for one-off scripts on mid-sized batches, or pass device="cpu". device="cpu" or device="cuda" forces a backend; "cuda" also means AMD GPUs under ROCm, as in torch. The active backend is logged once (logger emeans_core). If a GPU fit fails under "auto", the CPU runs it instead with a warning.
  • precision only affects GPU training. Cluster labels always come from an FP32 assignment, and every duplicate decision is an FP32 cosine similarity.
  • normalize=True (default) L2-normalises vectors and runs e-means in spherical mode, so Euclidean k-means distances rank documents the same way as cosine similarity. With normalize=False, clustering uses raw Euclidean distances (vector length matters; the clustering filter then allows all-zero vectors). Dedup scores are cosine similarities in both cases.
  • init="auto" seeds with k-means++ when n × k <= 1e7 and uses e-means' seeded sample otherwise; nepochs=None means 20 epochs for those small problems and 5 otherwise. e-means' batch laws pick very small batches on tiny inputs. On noisy synthetic clusters of 20 to 1,024 rows (d=384, 30 seeds per case), plain e-means (sampled seeds, 5 epochs) left an inertia 2 to 33% higher than these defaults (mean per-seed change), and agreed less with the true clusters (mean ARI 0.87 to 0.99 against 0.97 to 1.00). The k-means++ seeding gives most of the gain (BENCHMARKS.md, small-input defaults section).
  • Small CPU fits (n × k × d <= 2e8) run faiss single-threaded, scoped to the calling thread: OpenMP start-up cost dominates them (for 50 documents, 7 to 8 ms single-threaded against 75 to 82 ms with OpenMP). Up to that limit, single-threaded fits were faster in the run that had not imported torch; with torch imported first, OpenMP was up to 11% faster from 2,000 documents (backend section of BENCHMARKS.md).
  • Import faiss before torch if your application loads torch (local Hugging Face embeddings, for instance) before the first fit: with torch imported first, CPU fits of 500 to 5,000 documents ran 1.07 to 2.95× slower in the BENCHMARKS.md backend table (torch and faiss each load their own OpenMP runtime); import faiss before import torch avoided it, in a check not recorded in BENCHMARKS.md. emeans-core also imports torch itself, when it is installed, with device="cuda" or with device="auto" once n × k >= gpu_threshold; device="cpu" does not.
  • Determinism: on the CPU, the same seed and input give bit-identical output (tested). On a GPU, emeans-rocm reports bit-identical repeats on an RX 9060 XT for the default Triton paths with revival on, but not on every path (PyTorch fallback, some dimensions). Pass deterministic=True (clustering filter and dedup) to request PyTorch deterministic algorithms while training (process-wide while it runs). GPU tests compare with tolerances (ARI), not exact equality. GPU results are not expected to match CPU results bit for bit.

Edge cases

Input Behaviour
Empty list Empty list, no embedding call
One document Dedup: returned as is. Filter (needs num_clusters=1, like the original) and compressor: returned with their emeans_ metadata
Fewer documents than num_clusters Filter: ValueError like EmbeddingsClusteringFilter. Compressor and dedup: k clamped (with a warning when num_clusters was set)
All-zero vector ValueError naming the document index (it has no direction); allowed by the clustering filter with normalize=False
NaN / infinite values ValueError naming the document index
Mixed embedding dimensions ValueError
Exact duplicates Filter / compressor: clustered together; dedup: dropped with a score of 1.0 (up to FP32 rounding)

Metadata keys written by this package all start with emeans_. Existing keys are never overwritten (a warning is logged once), input metadata is never mutated (stateful documents get their computed embedding in state, as with langchain-community), and add_metadata=False turns it off.

Async

atransform_documents and acompress_documents call the embeddings' async methods (aembed_documents, aembed_query) and, for a VectorStore reference, asimilarity_search_by_vector; clustering and the duplicate check run in a worker thread (asyncio.to_thread). The embedding lists are converted to a float32 matrix and checked on the event loop, and with a VectorStore reference so is the per-chunk comparison with its hits (reference_k vectors per chunk).

import emeans_langchain does not import faiss, torch or emeans-rocm; the backend loads on first use, once per process, under a lock.

Benchmarks

See BENCHMARKS.md: dedup on synthetic (100k / 1M vectors, d = 384 / 768 / 1024) and real data (overlapping chunks of public-domain books), reranker latency, and a comparison with EmbeddingsClusteringFilter, each with its platform manifest. GPU columns are filled from runs on a real GPU only.

Bug reports

Please include the sanitised platform manifest:

python -m emeans_langchain.env --alias my-machine

It contains no hostname, username, home directory or environment variable outside a short allowlist (thread counts, visible devices, HIP/ROCm settings).

License

MIT. select_closest in clustering_filter.py is adapted from langchain-community (MIT); see THIRD_PARTY_NOTICES.md. e-means comes from faiss (MIT, Meta Platforms) and emeans-rocm (MIT).

Metadata

Release files for emeans-langchain 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for emeans-langchain 0.1.3
File Size Uploaded Provenance Actions
emeans_langchain-0.1.3.tar.gz 29.9 kB Without provenance Details for emeans_langchain-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for emeans-langchain 0.1.3
File Interpreter ABI Platform Actions
emeans_langchain-0.1.3-py3-none-any.whl Python 3 none any Details for emeans_langchain-0.1.3-py3-none-any.whl

Total release size: 54.2 kB

Release files / emeans_langchain-0.1.3.tar.gz

Download URL emeans_langchain-0.1.3.tar.gz
Size 29.9 kB
Tags Source
SHA-256 checksum
How to use checksums
ee800ec570511e239ea52cc64c6653064109f704918730536c99e2942f692ed5
BLAKE2b-256 checksum
How to use checksums
2d093cf267ca6f321a7408da5ff7fb4e1a7e9568037005a5566cda2e61c15791
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.1

Release files / emeans_langchain-0.1.3-py3-none-any.whl

Download URL emeans_langchain-0.1.3-py3-none-any.whl
Size 24.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b1bbee143653e3fe3775c2137a43248835ea6a974b89020611dd8c88079794ac
BLAKE2b-256 checksum
How to use checksums
3f3be019e8c8fb02685bb4fb1905ff0a8d23cd28602f41467cb59bf024bca596
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.1

Security for emeans-langchain 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page