💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Add RaBitQ as an ANN backend (#1251)
Pablo Miguel Argudo6737ee4e01ec
diff --git a/docs/embeddings/configuration/ann.md b/docs/embeddings/configuration/ann.mdindex ceb52374..02748f2d 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|milvus|numpy|torch|turbovec|zvec|pgvector|sqlite|custom+backend: faiss|hnsw|annoy|ggml|milvus|numpy|rabitq|torch|turbovec|zvec|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.@@ -91,6 +91,26 @@ numpy:The NumPy backend is a k-nearest neighbors backend. It's designed for simplicity and works well with smaller datasets that fit into memory.+### rabitq++```yaml+rabitq:+ mode: index mode (ivf or hnsw) - defaults to "ivf"+ nbits: number of quantization bits per dimension (int) - defaults to 1,+ supports 1 to 9 in both modes, ivf mode also supports 32 which+ keeps raw vectors for reranking+ clusters: number of IVF clusters (int) - defaults to+ max(1, min(round(4 * sqrt(embeddings count)), embeddings count))+ nprobe: search probe setting for ivf mode (int) - defaults to+ max(1, round(num_clusters/16))+ m: M param for hnsw mode (int) - defaults to 16+ efconstruction: ef_construction param for hnsw mode (int) - defaults to 200+ efsearch: ef search param for hnsw mode (int) - defaults to None and not set+ randomseed: random-seed param for hnsw mode (int) - defaults to 100+```++The [rabitq](https://github.com/VectorDB-NTU/RaBitQ-Library) backend is a quantized index powered by the [RaBitQ algorithm](https://doi.org/10.1145/3725413). It supports ivf and hnsw search modes. Vectors are stored with 1-bit quantization by default. More bits increase accuracy at the cost of memory.+### torch```yamldiff --git a/setup.py b/setup.pyindex 7682e139..f99e8369 100644--- a/setup.py+++ b/setup.py@@ -62,6 +62,7 @@ extras["ann"] = ["hnswlib>=0.5.0","milvus-lite>=3.1.1","pgvector>=0.4.1",+ "rabitqlib>=0.3.9","scikit-learn>=0.23.1","scipy>=1.4.1","sqlalchemy>=2.0.20",diff --git a/src/python/txtai/ann/dense/__init__.py b/src/python/txtai/ann/dense/__init__.pyindex 81f5afc6..76b14326 100644--- a/src/python/txtai/ann/dense/__init__.py+++ b/src/python/txtai/ann/dense/__init__.py@@ -9,6 +9,7 @@ from .hnsw import HNSWfrom .milvus import Milvusfrom .numpy import NumPyfrom .pgvector import PGVector+from .rabitq import RabitQfrom .torch import Torchfrom .turbovec import TurboVecfrom .zvec import Zvecdiff --git a/src/python/txtai/ann/dense/factory.py b/src/python/txtai/ann/dense/factory.pyindex fb0e396a..bd66d0e7 100644--- a/src/python/txtai/ann/dense/factory.py+++ b/src/python/txtai/ann/dense/factory.py@@ -12,6 +12,7 @@ from .hnsw import HNSWfrom .milvus import Milvusfrom .numpy import NumPyfrom .pgvector import PGVector+from .rabitq import RabitQfrom .sqlite import SQLitefrom .torch import Torchfrom .turbovec import TurboVec@@ -35,6 +36,7 @@ class ANNFactory:ANN"""+ # pylint: disable=R0912# ANN instanceann = Nonebackend = config.get("backend", "faiss" if FAISS else "numpy")@@ -44,16 +46,18 @@ class ANNFactory:ann = Annoy(config)elif backend == "faiss":ann = Faiss(config)+ elif backend == "ggml":+ ann = GGML(config)elif backend == "hnsw":ann = HNSW(config)elif backend == "milvus":ann = Milvus(config)- elif backend == "ggml":- ann = GGML(config)elif backend == "numpy":ann = NumPy(config)elif backend == "pgvector":ann = PGVector(config)+ elif backend == "rabitq":+ ann = RabitQ(config)elif backend == "sqlite":ann = SQLite(config)elif backend == "torch":diff --git a/src/python/txtai/ann/dense/rabitq.py b/src/python/txtai/ann/dense/rabitq.pynew file mode 100644index 00000000..51a348bd--- /dev/null+++ b/src/python/txtai/ann/dense/rabitq.py@@ -0,0 +1,263 @@+"""+RabitQ module+"""++import math+import os+import tempfile++# Conditional import+try:+ from rabitqlib import HnswIndex, IvfIndex+ from sklearn.cluster import KMeans++ RABITQ = True+except ImportError:+ RABITQ = False++from ...archive import ArchiveFactory+from ..base import ANN++# Core library imports+from ...util import Library++library = Library()+np = library.numpy()+safetensors = library.safetensors()++# Sentinel for unfilled top-k slots in native search results+SENTINEL = 0xFFFFFFFF++# External id for rows marked as deleted+DELETED = -1+++class RabitQ(ANN):+ """+ Builds an ANN index using the rabitqlib library (RaBitQ quantization).+ """++ def __init__(self, config):+ super().__init__(config)++ if not RABITQ:+ raise ImportError('rabitqlib is not available - install "ann" extra to enable')++ # Retained corpus: native indexes have no append/delete, appends rebuild from these rows and deletes mark rows until the next rebuild+ self.vectors = None+ self.ids = None+ self.numclusters = 0++ def load(self, path):+ self.close()++ try:+ # rabitqlib reads the whole index into memory, so the extracted files are only needed while loading+ with tempfile.TemporaryDirectory() as directory:+ archive = ArchiveFactory.create(directory)+ archive.load(path, "tar")++ # Retained corpus tensors plus index metadata+ with safetensors.safe_open(os.path.join(directory, "vectors.safetensors"), framework="np") as f:+ metadata = f.metadata() if f.metadata() else {}+ self.vectors = np.ascontiguousarray(f.get_tensor("vectors"), dtype=np.float32)+ self.ids = np.array(f.get_tensor("ids"), dtype=np.int64)++ self.numclusters = int(metadata.get("clusters", 0))++ # Mode comes from the current config, falling back to the saved snapshot. Invalid modes raise ValueError before native code runs.+ mode = self.mode(metadata.get("mode", "ivf"))++ # Empty indexes are saved without a native index file+ native = os.path.join(directory, "index.bin")+ if os.path.exists(native):+ self.backend = IvfIndex.load(native) if mode == "ivf" else HnswIndex.load(native)++ # Default the offset for snapshots that don't have it+ self.config["offset"] = int(metadata.get("offset", len(self.ids)))+ except Exception:+ self.close()+ raise++ def index(self, embeddings):+ self.close()++ # Mode is validated before any state is stored+ mode = self.mode()++ self.vectors = np.ascontiguousarray(embeddings, dtype=np.float32)+ self.ids = np.arange(self.vectors.shape[0], dtype=np.int64)++ self.build()++ # Add id offset and index build metadata+ self.config["offset"] = self.vectors.shape[0]+ self.metadata(self.settings(mode))++ def append(self, embeddings):+ embeddings = np.ascontiguousarray(embeddings, dtype=np.float32)+ new = embeddings.shape[0]++ self.vectors = np.ascontiguousarray(np.concatenate((self.vectors, embeddings), axis=0), dtype=np.float32)+ self.ids = np.concatenate((self.ids, np.arange(self.config["offset"], self.config["offset"] + new, dtype=np.int64)))++ self.build()++ # Update id offset and index metadata+ self.config["offset"] += new+ self.metadata()++ def delete(self, ids):+ if not ids or not self.count():+ return++ # Mark rows as deleted, search skips them. Unknown ids match nothing and are silently ignored.+ self.ids[np.isin(self.ids, np.array(ids, dtype=np.int64))] = DELETED++ # Rebuild once deleted rows outnumber live rows, this bounds search overfetch+ if self.count() < len(self.ids) - self.count():+ self.build()++ def search(self, queries, limit):+ count = self.count()+ if not count:+ return [[] for _ in queries]++ queries = np.ascontiguousarray(queries, dtype=np.float32)++ # Overfetch by the number of deleted rows, clamped to the native row count as the native index errors when k exceeds it+ k = min(limit + len(self.ids) - count, len(self.ids))++ mode = self.mode()+ if mode == "ivf":+ nprobe = self.setting("nprobe", max(1, round(self.numclusters / 16)))+ ids, distances = self.backend.search(queries, k, nprobe)+ else:+ ef = self.setting("efsearch", None)+ ids, distances = self.backend.search(queries, k, ef or 0)++ # Map results to [(id, score)], dropping unfilled sentinel slots and deleted rows+ results = []+ for pids, dists in zip(ids.tolist(), distances.tolist()):+ result = [(int(self.ids[pid]), float(1.0 - dist)) for pid, dist in zip(pids, dists) if pid != SENTINEL and self.ids[pid] != DELETED]+ results.append(result[:limit])++ return results++ def count(self):+ return int(np.count_nonzero(self.ids != DELETED)) if self.ids is not None else 0++ def save(self, path):+ # Stage the native index and the retained corpus, then bundle both into a single tar file+ with tempfile.TemporaryDirectory() as directory:+ # Empty indexes have no native index to save+ if self.backend is not None:+ self.backend.save(os.path.join(directory, "index.bin"))++ # Save retained corpus tensors, safetensors metadata values must be strings+ safetensors.numpy.save_file(+ {"vectors": self.vectors, "ids": self.ids},+ os.path.join(directory, "vectors.safetensors"),+ {"mode": self.mode(), "clusters": str(self.numclusters), "offset": str(self.config.get("offset", len(self.ids)))},+ )++ archive = ArchiveFactory.create(directory)+ archive.save(path, "tar")++ def close(self):+ # Parent logic releases the backend+ super().close()++ self.vectors = None+ self.ids = None+ self.numclusters = 0++ def mode(self, default="ivf"):+ """+ Returns the configured index mode.++ Args:+ default: default value when the mode setting is not found++ Returns:+ index mode, only "ivf" or "hnsw" are accepted+ """++ mode = self.setting("mode", default)+ if mode not in ("ivf", "hnsw"):+ raise ValueError(f'Invalid RabitQ mode: {mode}. Supported modes are "ivf" and "hnsw".')++ return mode++ def settings(self, mode):+ """+ Returns index build settings for metadata.++ Args:+ mode: index mode++ Returns:+ dict of build settings+ """++ if mode == "ivf":+ return {+ "mode": mode,+ "nbits": self.setting("nbits", 1),+ "clusters": self.numclusters,+ "nprobe": self.setting("nprobe", max(1, round(self.numclusters / 16))),+ }++ return {+ "mode": mode,+ "nbits": self.setting("nbits", 1),+ "m": self.setting("m", 16),+ "efconstruction": self.setting("efconstruction", 200),+ "efsearch": self.setting("efsearch", None),+ "randomseed": self.setting("randomseed", 100),+ }++ def build(self):+ """+ Builds the native index from the retained corpus, dropping rows marked as deleted.+ """++ live = self.ids != DELETED+ if not live.all():+ self.vectors = np.ascontiguousarray(self.vectors[live], dtype=np.float32)+ self.ids = self.ids[live]++ rows = self.vectors.shape[0]+ if not rows:+ self.backend = None+ self.numclusters = 0+ return++ mode = self.mode()+ dim = self.config["dimensions"]++ # Quantization bits per dimension, validated by rabitqlib+ nbits = self.setting("nbits", 1)++ # Default clusters to 4 * sqrt(N), bounded to [1, N] so KMeans always fits+ clusters = self.setting("clusters", None)+ self.numclusters = max(1, min(clusters if clusters else round(4 * math.sqrt(rows)), rows))++ cluster = KMeans(n_clusters=self.numclusters, random_state=0, n_init=1).fit(self.vectors)+ centroids = np.ascontiguousarray(cluster.cluster_centers_, dtype=np.float32)+ clusterids = np.ascontiguousarray(cluster.labels_, dtype=np.uint32)++ if mode == "ivf":+ self.backend = IvfIndex(dim=dim, max_elements=rows, num_clusters=self.numclusters, nbits=nbits, metric="ip")+ else:+ self.backend = HnswIndex(+ dim=dim,+ max_elements=rows,+ M=self.setting("m", 16),+ ef_construction=self.setting("efconstruction", 200),+ nbits=nbits,+ metric="ip",+ random_seed=self.setting("randomseed", 100),+ )++ self.backend.build(self.vectors, centroids, clusterids)diff --git a/test/python/testann/testdense.py b/test/python/testann/testdense.pyindex b30f514a..f98384e5 100644--- a/test/python/testann/testdense.py+++ b/test/python/testann/testdense.py@@ -535,6 +535,96 @@ class TestDense(unittest.TestCase):# Close ANNann.close()+ def testRabitQ(self):+ """+ Test RabitQ backend+ """++ self.runTests("rabitq")++ def testRabitQCustom(self):+ """+ Test RabitQ backend with custom settings+ """++ # Test with custom settings+ self.runTests("rabitq", {"rabitq": {"mode": "hnsw"}}, False)+ self.runTests("rabitq", {"rabitq": {"clusters": 8, "nprobe": 2}}, False)+ self.runTests("rabitq", {"rabitq": {"nbits": 4}}, False)+ self.runTests("rabitq", {"rabitq": {"mode": "hnsw", "nbits": 4}}, False)+ self.runTests("rabitq", {"rabitq": {"nbits": 32}}, False)++ # Generate dummy data+ data = np.random.rand(100, 240).astype(np.float32)+ self.normalize(data)++ # Test invalid modes and quantization bits+ for mode, nbits in [("invalid", 1), ("ivf", 10), ("hnsw", 32)]:+ with self.assertRaises(ValueError):+ ann = ANNFactory.create({"backend": "rabitq", "dimensions": 240, "rabitq": {"mode": mode, "nbits": nbits}})+ ann.index(data)++ # Test a failed load leaves an empty index+ ann = ANNFactory.create({"backend": "rabitq", "dimensions": 240})+ ann.index(data)+ index = os.path.join(tempfile.gettempdir(), f"rabitq.invalid.{round(time.time() * 1000)}")+ ann.save(index)+ ann.config["rabitq"] = {"mode": "invalid"}+ with self.assertRaises(ValueError):+ ann.load(index)+ self.assertEqual(ann.count(), 0)++ def testRabitQDelete(self):+ """+ Test RabitQ deletes mark rows without rebuilding the index+ """++ # Generate dummy data+ data = np.random.rand(100, 240).astype(np.float32)+ self.normalize(data)++ for mode in ["ivf", "hnsw"]:+ # Probe all clusters so ivf searches can fill the limit+ ann = ANNFactory.create({"backend": "rabitq", "dimensions": 240, "rabitq": {"mode": mode, "nprobe": 100}})+ ann.index(data)+ backend = ann.backend++ # Empty deletes are ignored+ ann.delete([])+ self.assertEqual(ann.count(), 100)++ # Deleted rows are skipped by search and the limit is still filled+ ann.delete([0, 1])+ self.assertIs(ann.backend, backend)+ self.assertEqual(ann.count(), 98)+ for result in ann.search(data[:2], 10):+ self.assertEqual(len(result), 10)+ self.assertFalse({0, 1} & {uid for uid, _ in result})++ # Deletes are kept after a save and reload+ index = os.path.join(tempfile.gettempdir(), f"rabitq.{mode}.{round(time.time() * 1000)}")+ ann.save(index)+ ann.load(index)+ self.assertEqual(ann.count(), 98)+ ann.delete([2])+ self.assertEqual(ann.count(), 97)++ # Append rebuilds the index without the deleted rows+ ann.append(data[:1])+ self.assertEqual(ann.vectors.shape[0], 98)+ self.assertEqual(ann.count(), 98)++ # Rebuild once deleted rows outnumber live rows+ ann.delete(list(range(3, 60)))+ self.assertEqual(ann.vectors.shape[0], ann.count())+ self.assertEqual(ann.count(), 41)++ # Deleting all rows leaves an empty index, deletes on an empty index are ignored+ ann.delete(list(range(200)))+ ann.delete([0])+ self.assertEqual(ann.count(), 0)+ self.assertEqual(ann.search(data[:1], 10), [[]])+@unittest.skipIf(platform.system() == "Darwin", "SQLite extensions not supported on macOS")def testSQLite(self):"""diff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex 0a7d74df..116fda7f 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -56,6 +56,7 @@ class TestOptional(unittest.TestCase):"peft","pgvector","PIL",+ "rabitqlib","rich","scipy","scipy.sparse",@@ -139,6 +140,9 @@ class TestOptional(unittest.TestCase):with self.assertRaises(ImportError):ANNFactory.create({"backend": "pgvector"})+ with self.assertRaises(ImportError):+ ANNFactory.create({"backend": "rabitq"})+with self.assertRaises(ImportError):ANNFactory.create({"backend": "sqlite"})