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 zvec as a dense ANN backend (#1130)

Morgan Carr14cbe51e0498
diff --git a/docs/embeddings/configuration/ann.md b/docs/embeddings/configuration/ann.md
index b39b8a3f..f679b90b 100644
--- a/docs/embeddings/configuration/ann.md
+++ b/docs/embeddings/configuration/ann.md
@@ -4,7 +4,7 @@ Approximate Nearest Neighbor (ANN) index configuration for storing vector embedd
## backend
```yaml
-backend: faiss|hnsw|annoy|ggml|numpy|torch|turbovec|pgvector|sqlite|custom
+backend: faiss|hnsw|annoy|ggml|numpy|torch|zvec|turbovec|pgvector|sqlite|custom
```
Sets the ANN backend. Defaults to `faiss`. Additional backends are available via the [ann](../../../install/#ann) extras package. Set custom backends via setting this parameter to the fully resolvable class string.
@@ -99,6 +99,15 @@ torch:
blocksize: quantization block size parameter
```
+### zvec
+
+The [zvec](https://github.com/alibaba/zvec) backend is an embedded, path-based vector index.
+
+```yaml
+zvec:
+ m: number of HNSW links per element (int) - defaults to 50
+```
+
### turbovec
The [turbovec](https://github.com/RyanCodrai/turbovec) backend is a k-nearest neighbors backend powered by the [TurboQuant algorithm](https://arxiv.org/abs/2504.19874).
diff --git a/setup.py b/setup.py
index c71b4d0d..8b0fd1a8 100644
--- a/setup.py
+++ b/setup.py
@@ -65,6 +65,7 @@ extras["ann"] = [
"sqlalchemy>=2.0.20",
"sqlite-vec>=0.1.1",
"turbovec>=0.7.0",
+ "zvec>=0.5.1",
]
extras["api"] = [
diff --git a/src/python/txtai/ann/dense/__init__.py b/src/python/txtai/ann/dense/__init__.py
index 2526fd00..2f9fc25b 100644
--- a/src/python/txtai/ann/dense/__init__.py
+++ b/src/python/txtai/ann/dense/__init__.py
@@ -10,3 +10,4 @@ from .numpy import NumPy
from .pgvector import PGVector
from .torch import Torch
from .turbovec import TurboVec
+from .zvec import Zvec
diff --git a/src/python/txtai/ann/dense/factory.py b/src/python/txtai/ann/dense/factory.py
index 69d09a0e..d58141e4 100644
--- a/src/python/txtai/ann/dense/factory.py
+++ b/src/python/txtai/ann/dense/factory.py
@@ -13,6 +13,7 @@ from .pgvector import PGVector
from .sqlite import SQLite
from .torch import Torch
from .turbovec import TurboVec
+from .zvec import Zvec
class ANNFactory:
@@ -55,6 +56,8 @@ class ANNFactory:
ann = Torch(config)
elif backend == "turbovec":
ann = TurboVec(config)
+ elif backend == "zvec":
+ ann = Zvec(config)
else:
ann = ANNFactory.resolve(backend, config)
diff --git a/src/python/txtai/ann/dense/zvec.py b/src/python/txtai/ann/dense/zvec.py
new file mode 100644
index 00000000..48d8b9aa
--- /dev/null
+++ b/src/python/txtai/ann/dense/zvec.py
@@ -0,0 +1,131 @@
+"""
+zvec module
+"""
+
+import os
+import shutil
+import tempfile
+
+# Conditional import
+try:
+ import zvec
+
+ ZVEC = True
+except ImportError:
+ ZVEC = False
+
+from ...archive import ArchiveFactory
+from ..base import ANN
+
+
+class Zvec(ANN):
+ """
+ Builds an ANN index using the zvec library.
+ """
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not ZVEC:
+ raise ImportError('zvec is not available - install "ann" extra to enable')
+
+ self.directory = None
+ self.path = None
+
+ def load(self, path):
+ self.close()
+ self.directory = tempfile.mkdtemp()
+ self.path = os.path.join(self.directory, "index")
+
+ try:
+ archive = ArchiveFactory.create(self.directory)
+ archive.load(path, "tar")
+ self.backend = zvec.open(self.path)
+ except Exception:
+ self.close()
+ raise
+
+ def index(self, embeddings):
+ self.close()
+
+ # Lookup index settings
+ m = self.setting("m", 50)
+
+ # Create collection
+ self.directory = tempfile.mkdtemp()
+ self.path = os.path.join(self.directory, "index")
+ schema = zvec.CollectionSchema(
+ name="txtai",
+ vectors=zvec.VectorSchema(
+ "embedding",
+ zvec.DataType.VECTOR_FP32,
+ self.config["dimensions"],
+ index_param=zvec.HnswIndexParam(metric_type=zvec.MetricType.IP, m=m),
+ ),
+ )
+ self.backend = zvec.create_and_open(path=self.path, schema=schema)
+
+ # Add items - position in embeddings is used as the id
+ self.insert(embeddings, 0)
+
+ # Add id offset and index build metadata
+ self.config["offset"] = embeddings.shape[0]
+ self.metadata({"m": m, "zvec": zvec.__version__})
+
+ def append(self, embeddings):
+ self.insert(embeddings, self.config["offset"])
+
+ # Update id offset and index metadata
+ self.config["offset"] += embeddings.shape[0]
+ self.metadata()
+
+ def delete(self, ids):
+ if ids:
+ self.backend.delete([str(uid) for uid in ids])
+
+ def search(self, queries, limit):
+ results = []
+ for query in queries:
+ matches = self.backend.query(
+ zvec.Query(field_name="embedding", vector=query.tolist()),
+ topk=limit,
+ )
+ results.append([(int(match.id), float(match.score)) for match in matches])
+
+ return results
+
+ def count(self):
+ return self.backend.stats.doc_count
+
+ def save(self, path):
+ self.backend.flush()
+ self.backend = None
+ archive = ArchiveFactory.create(self.directory)
+ archive.save(path, "tar")
+ self.backend = zvec.open(self.path)
+
+ def close(self):
+ # Parent logic releases the collection and its file locks
+ super().close()
+
+ if self.directory and os.path.exists(self.directory):
+ shutil.rmtree(self.directory)
+
+ self.directory = None
+ self.path = None
+
+ def insert(self, embeddings, offset):
+ """
+ Inserts embeddings starting at offset.
+
+ Args:
+ embeddings: embeddings array
+ offset: starting id
+ """
+
+ if embeddings.shape[0]:
+ for start in range(0, embeddings.shape[0], 1024):
+ batch = embeddings[start : start + 1024]
+ self.backend.insert(
+ [zvec.Doc(id=str(offset + start + uid), vectors={"embedding": embedding.tolist()}) for uid, embedding in enumerate(batch)]
+ )
diff --git a/test/python/testann/testdense.py b/test/python/testann/testdense.py
index 29c45a6c..59ff6ef0 100644
--- a/test/python/testann/testdense.py
+++ b/test/python/testann/testdense.py
@@ -393,6 +393,20 @@ class TestDense(unittest.TestCase):
self.runTests("turbovec")
+ def testZvec(self):
+ """
+ Test zvec backend
+ """
+
+ self.runTests("zvec")
+
+ def testZvecCustom(self):
+ """
+ Test zvec backend with custom settings
+ """
+
+ self.runTests("zvec", {"zvec": {"m": 16}})
+
def runTests(self, name, params=None, update=True):
"""
Runs a series of standard backend tests.
diff --git a/test/python/testoptional.py b/test/python/testoptional.py
index 560d6f25..b581aaf0 100644
--- a/test/python/testoptional.py
+++ b/test/python/testoptional.py
@@ -70,6 +70,7 @@ class TestOptional(unittest.TestCase):
"ttstokenizer",
"turbovec",
"xmltodict",
+ "zvec",
]
# Get handle to all currently loaded txtai modules
@@ -143,6 +144,9 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
ANNFactory.create({"backend": "turbovec"})
+ with self.assertRaises(ImportError):
+ ANNFactory.create({"backend": "zvec"})
+
# Test sparse methods
with self.assertRaises(ImportError):
SparseANNFactory.create({"backend": "ivfsparse"})