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 turbovec an ANN backend, closes #1109

davidmezzettidf53803cf7f3
diff --git a/docs/embeddings/configuration/ann.md b/docs/embeddings/configuration/ann.md
index 65c87bb2..b39b8a3f 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|pgvector|sqlite|custom
+backend: faiss|hnsw|annoy|ggml|numpy|torch|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,14 @@ torch:
blocksize: quantization block size parameter
```
+### 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).
+
+```yaml
+turbovec:
+ bitwidth: number of bits to store each vector dimension as. Supports 2, 3 or 4.
+
### pgvector
```yaml
pgvector:
diff --git a/setup.py b/setup.py
index b2e2c497..8e4633fa 100644
--- a/setup.py
+++ b/setup.py
@@ -64,6 +64,7 @@ extras["ann"] = [
"scipy>=1.4.1",
"sqlalchemy>=2.0.20",
"sqlite-vec>=0.1.1",
+ "turbovec>=0.7.0",
]
extras["api"] = [
diff --git a/src/python/txtai/ann/dense/__init__.py b/src/python/txtai/ann/dense/__init__.py
index 804b2481..2526fd00 100644
--- a/src/python/txtai/ann/dense/__init__.py
+++ b/src/python/txtai/ann/dense/__init__.py
@@ -9,3 +9,4 @@ from .hnsw import HNSW
from .numpy import NumPy
from .pgvector import PGVector
from .torch import Torch
+from .turbovec import TurboVec
diff --git a/src/python/txtai/ann/dense/factory.py b/src/python/txtai/ann/dense/factory.py
index eaf61505..69d09a0e 100644
--- a/src/python/txtai/ann/dense/factory.py
+++ b/src/python/txtai/ann/dense/factory.py
@@ -12,6 +12,7 @@ from .numpy import NumPy
from .pgvector import PGVector
from .sqlite import SQLite
from .torch import Torch
+from .turbovec import TurboVec
class ANNFactory:
@@ -52,6 +53,8 @@ class ANNFactory:
ann = SQLite(config)
elif backend == "torch":
ann = Torch(config)
+ elif backend == "turbovec":
+ ann = TurboVec(config)
else:
ann = ANNFactory.resolve(backend, config)
diff --git a/src/python/txtai/ann/dense/turbovec.py b/src/python/txtai/ann/dense/turbovec.py
new file mode 100644
index 00000000..8a97261b
--- /dev/null
+++ b/src/python/txtai/ann/dense/turbovec.py
@@ -0,0 +1,82 @@
+"""
+TurboVec module
+"""
+
+# Conditional import
+try:
+ from turbovec import IdMapIndex
+
+ TURBOVEC = True
+except ImportError:
+ TURBOVEC = False
+
+from ..base import ANN
+
+# Core library imports
+from ...util import Library
+
+np = Library().numpy()
+
+
+class TurboVec(ANN):
+ """
+ Builds an ANN index using the turbovec library.
+ """
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not TURBOVEC:
+ raise ImportError('turbovec is not available - install "ann" extra to enable')
+
+ def load(self, path):
+ # Load index
+ self.backend = IdMapIndex.load(path)
+
+ def index(self, embeddings):
+ # Lookup index settings
+ bitwidth = self.setting("bitwidth", 4)
+
+ # Create index
+ self.backend = IdMapIndex(dim=self.config["dimensions"], bit_width=bitwidth)
+
+ # Add items - position in embeddings is used as the id
+ self.backend.add_with_ids(embeddings, np.arange(embeddings.shape[0], dtype=np.uint64))
+
+ # Add id offset, delete counter and index build metadata
+ self.config["offset"] = embeddings.shape[0]
+ self.metadata({"bitwidth": bitwidth})
+
+ def append(self, embeddings):
+ new = embeddings.shape[0]
+
+ self.backend.add_with_ids(embeddings, np.arange(self.config["offset"], self.config["offset"] + new, dtype=np.uint64))
+
+ # Update id offset and index metadata
+ self.config["offset"] += new
+ self.metadata()
+
+ def delete(self, ids):
+ # Mark elements as deleted to omit from search results
+ for uid in ids:
+ self.backend.remove(uid)
+
+ def search(self, queries, limit):
+ # Run the query
+ scores, ids = self.backend.search(queries=queries, k=limit)
+
+ # Map results to [(id, score)]
+ results = []
+ for x, score in enumerate(scores):
+
+ # Build (id, score) tuples, convert to ints and floats
+ results.append(list(zip(ids[x].tolist(), score.tolist())))
+
+ return results
+
+ def count(self):
+ return len(self.backend)
+
+ def save(self, path):
+ # Write index
+ self.backend.write(path)
diff --git a/test/python/testann/testdense.py b/test/python/testann/testdense.py
index cac36090..23ce586f 100644
--- a/test/python/testann/testdense.py
+++ b/test/python/testann/testdense.py
@@ -378,6 +378,13 @@ class TestDense(unittest.TestCase):
ann.delete([0])
self.assertEqual(ann.count(), 99)
+ def testTurboVec(self):
+ """
+ Test turbovec backend
+ """
+
+ self.runTests("turbovec")
+
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 846b9061..892970a6 100644
--- a/test/python/testoptional.py
+++ b/test/python/testoptional.py
@@ -67,6 +67,7 @@ class TestOptional(unittest.TestCase):
"staticvectors",
"tika",
"ttstokenizer",
+ "turbovec",
"xmltodict",
]
@@ -138,6 +139,9 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
ANNFactory.create({"backend": "torch", "torch": {"quantize": True}})
+ with self.assertRaises(ImportError):
+ ANNFactory.create({"backend": "turbovec"})
+
# Test sparse methods
with self.assertRaises(ImportError):
SparseANNFactory.create({"backend": "ivfsparse"})