Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add Milvus Lite sparse ANN backend (#1420)

W1nnnd0c184b6447e0
diff --git a/docs/embeddings/configuration/scoring.md b/docs/embeddings/configuration/scoring.md
index 2767e344..5d48c679 100644
--- a/docs/embeddings/configuration/scoring.md
+++ b/docs/embeddings/configuration/scoring.md
@@ -36,7 +36,7 @@ batch: Sets the transform batch size
encodebatch: Sets the encode batch size
vectors: additional model init args
encodeargs: additional encode() args
-backend: ivfsparse|pgsparse|zvecsparse
+backend: ivfsparse|milvussparse|pgsparse|zvecsparse
```
Sparse vector scoring options. The sparse scoring instance combines a sparse vector model with a sparse approximate nearest neighbor index (ANN). This method supports both vector normalization and score normalization.
@@ -62,6 +62,10 @@ ivfsparse:
Inverted file (IVF) index with flat vector file storage and sparse array support.
+#### milvussparse
+
+Sparse ANN backed by [milvus-lite](https://github.com/milvus-io/milvus-lite). Stores sparse vectors in an embedded, path-based database with a sparse inverted index and exact inner product scoring. Only finite, non-negative weights are supported, which fits the output of SPLADE-style models. Vectors with negative or non-finite weights raise an error. Requires the [ann](../../../install/#ann) extras package.
+
#### pgsparse
Sparse ANN backed by Postgres. Supports same options as the [pgvector](../ann/#pgvector) ANN.
diff --git a/setup.py b/setup.py
index c219b79f..693f6ee1 100644
--- a/setup.py
+++ b/setup.py
@@ -60,7 +60,7 @@ extras["ann"] = [
"bitsandbytes>=0.42.0",
"ggml-python>=0.0.41",
"hnswlib>=0.5.0",
- "milvus-lite>=3.1.1",
+ "milvus-lite>=3.2.2",
"pgvector>=0.4.1",
"rabitqlib>=0.7.0",
"scikit-learn>=0.23.1",
diff --git a/src/python/txtai/ann/dense/milvus.py b/src/python/txtai/ann/dense/milvus.py
index dd2b2b7d..d9930f8a 100644
--- a/src/python/txtai/ann/dense/milvus.py
+++ b/src/python/txtai/ann/dense/milvus.py
@@ -61,11 +61,11 @@ class Milvus(ANN):
schema = milvus_lite.CollectionSchema(
fields=[
milvus_lite.FieldSchema("id", milvus_lite.DataType.INT64, is_primary=True),
- milvus_lite.FieldSchema("embedding", milvus_lite.DataType.FLOAT_VECTOR, dim=self.config["dimensions"]),
+ self.field(),
]
)
self.collection = self.backend.create_collection("txtai", schema)
- self.collection.create_index("embedding", {"index_type": "HNSW", "metric_type": "IP", "params": {"M": m}})
+ self.collection.create_index("embedding", self.indexparams(m))
self.collection.load()
# Add items - position in embeddings is used as the id
@@ -128,9 +128,47 @@ class Milvus(ANN):
"""
if embeddings.shape[0]:
- for start in range(0, embeddings.shape[0], 1024):
- batch = embeddings[start : start + 1024]
- self.collection.insert([{"id": offset + start + uid, "embedding": embedding.tolist()} for uid, embedding in enumerate(batch)])
+ # Prepare and validate all records before writing
+ records = [{"id": offset + uid, "embedding": self.prepare(embeddings[uid])} for uid in range(embeddings.shape[0])]
+
+ for start in range(0, len(records), 1024):
+ self.collection.insert(records[start : start + 1024])
+
+ def field(self):
+ """
+ Creates the vector field schema.
+
+ Returns:
+ milvus-lite FieldSchema
+ """
+
+ return milvus_lite.FieldSchema("embedding", milvus_lite.DataType.FLOAT_VECTOR, dim=self.config["dimensions"])
+
+ def indexparams(self, m):
+ """
+ Creates the vector index parameters.
+
+ Args:
+ m: number of HNSW links per element
+
+ Returns:
+ index parameters
+ """
+
+ return {"index_type": "HNSW", "metric_type": "IP", "params": {"M": m}}
+
+ def prepare(self, data):
+ """
+ Prepares a single vector for insertion.
+
+ Args:
+ data: input vector
+
+ Returns:
+ vector formatted for milvus-lite
+ """
+
+ return data.tolist()
def open(self):
"""
diff --git a/src/python/txtai/ann/sparse/__init__.py b/src/python/txtai/ann/sparse/__init__.py
index a52eddf5..dd6c908c 100644
--- a/src/python/txtai/ann/sparse/__init__.py
+++ b/src/python/txtai/ann/sparse/__init__.py
@@ -4,5 +4,6 @@ Sparse ANN imports
from .factory import SparseANNFactory
from .ivfsparse import IVFSparse
+from .milvussparse import MilvusSparse
from .pgsparse import PGSparse
from .zvecsparse import ZvecSparse
diff --git a/src/python/txtai/ann/sparse/factory.py b/src/python/txtai/ann/sparse/factory.py
index addcd0fe..0da5296c 100644
--- a/src/python/txtai/ann/sparse/factory.py
+++ b/src/python/txtai/ann/sparse/factory.py
@@ -6,6 +6,7 @@ from ...util import Resolver
from ..base import ANN
from .ivfsparse import IVFSparse
+from .milvussparse import MilvusSparse
from .pgsparse import PGSparse
from .zvecsparse import ZvecSparse
@@ -34,6 +35,8 @@ class SparseANNFactory:
# Create ANN instance
if backend == "ivfsparse":
ann = IVFSparse(config)
+ elif backend == "milvussparse":
+ ann = MilvusSparse(config)
elif backend == "pgsparse":
ann = PGSparse(config)
elif backend == "zvecsparse":
diff --git a/src/python/txtai/ann/sparse/milvussparse.py b/src/python/txtai/ann/sparse/milvussparse.py
new file mode 100644
index 00000000..7de499b0
--- /dev/null
+++ b/src/python/txtai/ann/sparse/milvussparse.py
@@ -0,0 +1,52 @@
+"""
+MilvusSparse module
+"""
+
+import math
+
+# Conditional import
+try:
+ import milvus_lite
+except ImportError:
+ pass
+
+from ..dense import Milvus
+
+
+class MilvusSparse(Milvus):
+ """
+ Builds a Sparse ANN index using the milvus-lite library. Requires milvus-lite >= 3.2.2 for inner product sparse search.
+
+ milvus-lite only stores finite, non-negative sparse weights. Invalid vectors raise a ValueError before any data is written.
+ """
+
+ def search(self, queries, limit):
+ results = []
+ for query in queries:
+ # Empty queries have no matches
+ query = self.prepare(query)
+ matches = self.collection.search([query], top_k=limit, metric_type="IP", anns_field="embedding", output_fields=["id"])[0] if query else []
+ results.append([(int(match["id"]), float(match["distance"])) for match in matches])
+
+ return results
+
+ def field(self):
+ # Empty rows are stored as null vectors to keep ids aligned
+ return milvus_lite.FieldSchema("embedding", milvus_lite.DataType.SPARSE_FLOAT_VECTOR, nullable=True)
+
+ def indexparams(self, m):
+ return {"index_type": "SPARSE_INVERTED_INDEX", "metric_type": "IP", "params": {}}
+
+ def prepare(self, data):
+ vector = {}
+ for index, value in zip(data.indices, data.data):
+ value = float(value)
+ if not math.isfinite(value) or value < 0:
+ raise ValueError(f"milvussparse only supports finite, non-negative weights, found {value} at index {index}")
+
+ # Skip explicit zeros
+ if value:
+ vector[int(index)] = value
+
+ # milvus-lite requires at least one non-zero weight, store empty rows as null
+ return vector if vector else None
diff --git a/test/python/testann/testsparse/testmilvussparse.py b/test/python/testann/testsparse/testmilvussparse.py
new file mode 100644
index 00000000..1ab3a3f5
--- /dev/null
+++ b/test/python/testann/testsparse/testmilvussparse.py
@@ -0,0 +1,113 @@
+"""
+MilvusSparse ANN module tests
+"""
+
+import os
+import tempfile
+
+
+from scipy.sparse import csr_matrix
+
+from txtai.ann import SparseANNFactory
+
+from .base import SparseTest
+
+
+class TestMilvusSparse(SparseTest):
+ """
+ MilvusSparse ANN tests.
+ """
+
+ def testMilvusSparse(self):
+ """
+ Test Sparse milvus-lite backend
+ """
+
+ # Generate test record
+ data = self.generate(1, 30522)
+
+ # Create ANN
+ path = os.path.join(tempfile.gettempdir(), "milvussparse")
+ ann = SparseANNFactory.create({"backend": "milvussparse", "dimensions": 30522})
+
+ # Test indexing
+ ann.index(data)
+ ann.append(data)
+
+ # Validate search results
+ self.assertEqual([[(uid, round(score, 5)) for uid, score in x] for x in ann.search(data, 1)], [[(0, 1.0)]])
+
+ # Validate save/load
+ ann.save(path)
+ ann.load(path)
+
+ # Validate count
+ self.assertEqual(ann.count(), 2)
+
+ # Test delete
+ ann.delete([0])
+ self.assertEqual(ann.count(), 1)
+ self.assertEqual(ann.search(data, 1)[0][0][0], 1)
+
+ # Close ANN
+ ann.close()
+
+ def testMilvusSparseEmpty(self):
+ """
+ Test MilvusSparse with an empty query
+ """
+
+ # Create ANN with an empty row
+ data = csr_matrix([[1.0, 0.0], [0.0, 0.0]])
+ ann = SparseANNFactory.create({"backend": "milvussparse", "dimensions": 2})
+ ann.index(data)
+
+ # Validate empty rows are indexed and searching with an empty query doesn't raise an error
+ self.assertEqual(ann.count(), 2)
+ self.assertEqual(len(ann.search(data, 1)), 2)
+
+ # Close ANN
+ ann.close()
+
+ def testMilvusSparseScores(self):
+ """
+ Test MilvusSparse scores are exact inner products
+ """
+
+ # Create ANN
+ data = self.generate(50, 30522)
+ ann = SparseANNFactory.create({"backend": "milvussparse", "dimensions": 30522})
+ ann.index(data)
+
+ # Validate scores against exact inner products
+ expected = (data[:5] @ data.T).toarray()
+ for x, results in enumerate(ann.search(data[:5], 10)):
+ for uid, score in results:
+ self.assertAlmostEqual(score, expected[x, uid], places=5)
+
+ # Close ANN
+ ann.close()
+
+ def testMilvusSparseInvalid(self):
+ """
+ Test MilvusSparse rejects invalid vectors without modifying the index
+ """
+
+ # Create ANN
+ ann = SparseANNFactory.create({"backend": "milvussparse", "dimensions": 2})
+ ann.index(csr_matrix([[1.0, 0.0]]))
+
+ # Validate negative and non-finite weights are rejected before any data is written
+ for value in [-1.0, float("nan"), float("inf")]:
+ with self.assertRaises(ValueError):
+ ann.append(csr_matrix([[0.0, 1.0], [0.0, value]]))
+
+ self.assertEqual(ann.count(), 1)
+ self.assertEqual(ann.config["offset"], 1)
+
+ # Validate a valid append after a rejected append uses the next id
+ ann.append(csr_matrix([[0.0, 1.0]]))
+ self.assertEqual(ann.search(csr_matrix([[0.0, 1.0]]), 1), [[(1, 1.0)]])
+
+ # Close ANN
+ ann.close()
diff --git a/test/python/testoptional.py b/test/python/testoptional.py
index c7956d94..67763fd7 100644
--- a/test/python/testoptional.py
+++ b/test/python/testoptional.py
@@ -159,6 +159,9 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
SparseANNFactory.create({"backend": "ivfsparse"})
+ with self.assertRaises(ImportError):
+ SparseANNFactory.create({"backend": "milvussparse"})
+
with self.assertRaises(ImportError):
SparseANNFactory.create({"backend": "pgsparse"})