Metadata-Version: 2.5
Name: emeans-langchain
Version: 0.1.1
Summary: LangChain document transformers and a diversity compressor built on e-means k-means (CPU, optional ROCm/CUDA GPU)
Project-URL: Source, https://github.com/ogaude/emeans-langchain
Project-URL: Issues, https://github.com/ogaude/emeans-langchain/issues
Project-URL: Changelog, https://github.com/ogaude/emeans-langchain/blob/main/CHANGELOG.md
Project-URL: Benchmarks, https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md
Author: ogaude
License-Expression: MIT
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Keywords: clustering,deduplication,e-means,faiss,k-means,langchain,langchain-integration,rag,reranking,rocm
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: faiss-cpu>=1.16.0
Requires-Dist: langchain-core<2.0.0,>=1.0.0
Requires-Dist: numpy>=2.0
Provides-Extra: examples
Requires-Dist: langchain-classic>=1.0.0; extra == 'examples'
Provides-Extra: gpu
Requires-Dist: torch; extra == 'gpu'
Provides-Extra: rocm
Requires-Dist: emeans-rocm<0.3,>=0.2.5; extra == 'rocm'
Description-Content-Type: text/markdown

# emeans-langchain

LangChain document transformers and a document compressor built on
[e-means](https://github.com/ogaude/e-means-rocm), 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.1). The package name follows my other e-means integrations
([emeans-haystack](https://github.com/ogaude/emeans-haystack),
[emeans-dify](https://github.com/ogaude/emeans-dify)) rather than `langchain-<provider>`.

## Install

```bash
pip install emeans-langchain            # CPU: langchain-core, numpy, faiss-cpu
```

The CPU backend is e-means itself (`NumpyEmeans`, which ships with `faiss-cpu`), not a
different k-means. A GPU is optional:

```bash
# AMD GPU (ROCm): install a ROCm build of torch first, then the emeans-rocm port.
# Example for an RX 9000 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
pip install "emeans-langchain[gpu]"
```

`[rocm]` adds `emeans-rocm` (AMD kernels through Triton) and does not install torch. `[gpu]` only
requires `torch` and uses the stock faiss e-means GPU code: if no torch is installed, pip takes the
PyPI wheel (a CUDA build on Linux x86-64, never ROCm). Install the torch build for your GPU first.

**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 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
(gfx1200) with torch 2.14 for ROCm 10.1 and emeans-rocm 0.2.11; GPU tests skip themselves when
torch sees no GPU.

## Examples

### 1. Drop-in swap for `EmbeddingsClusteringFilter`

```diff
-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](https://github.com/ogaude/emeans-langchain/blob/main/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

```python
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](https://github.com/ogaude/emeans-langchain/blob/main/BENCHMARKS.md)).

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

### 3. Ingest-time deduplication

```python
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](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
  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, `[gpu]` |
|---|---|---|---|
| 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). Retrieval-
  sized inputs stay on the CPU, where they are faster: on an RX 9060 XT, e-means training in a
  warm process is 2 to 3× slower on the GPU at `n × k = 1e3`, 1.4 to 5× faster at 1e4, 7 to 8×
  faster at 1e6 and 23 to 28× faster from 1e7 up. The first GPU fit in a process takes about
  1.6 s (torch import, HIP start-up; 75 ms on the CPU), which 1e6 pays back within a few calls;
  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_langchain`). 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 (75 ms against 7 ms for 50 documents), and larger fits up to
  `1e9` were never more than about 10% slower single-threaded (backend section of BENCHMARKS.md).
- **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](https://github.com/ogaude/emeans-langchain/blob/main/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:

```bash
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](https://github.com/ogaude/emeans-langchain/blob/main/THIRD_PARTY_NOTICES.md). e-means comes from faiss (MIT, Meta Platforms)
and emeans-rocm (MIT).
