Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Store only the quantized index in the RaBitQ backend (#1297)

Pablo Miguel Argudof8689ed90372
diff --git a/docs/embeddings/configuration/ann.md b/docs/embeddings/configuration/ann.md
index 02748f2d..e604500b 100644
--- a/docs/embeddings/configuration/ann.md
+++ b/docs/embeddings/configuration/ann.md
@@ -109,7 +109,7 @@ rabitq:
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.
+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. The index is stored as a single file. Note that rabitq indexes can not be modified after creation, upserts/deletes and other modifications are not supported.
### torch
diff --git a/src/python/txtai/ann/dense/rabitq.py b/src/python/txtai/ann/dense/rabitq.py
index 51a348bd..0fd72dc0 100644
--- a/src/python/txtai/ann/dense/rabitq.py
+++ b/src/python/txtai/ann/dense/rabitq.py
@@ -3,8 +3,6 @@ RabitQ module
"""
import math
-import os
-import tempfile
# Conditional import
try:
@@ -15,7 +13,6 @@ try:
except ImportError:
RABITQ = False
-from ...archive import ArchiveFactory
from ..base import ANN
# Core library imports
@@ -23,18 +20,18 @@ 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
-
+# pylint: disable=W0223
class RabitQ(ANN):
"""
Builds an ANN index using the rabitqlib library (RaBitQ quantization).
+
+ Only the quantized index is stored, as a single file. Native indexes can't be extended or have rows removed,
+ so this backend doesn't support append and delete.
"""
def __init__(self, config):
@@ -43,41 +40,11 @@ class RabitQ(ANN):
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
+ # Invalid modes raise ValueError before native code runs
+ self.backend = IvfIndex.load(path) if self.mode() == "ivf" else HnswIndex.load(path)
def index(self, embeddings):
self.close()
@@ -85,179 +52,97 @@ class RabitQ(ANN):
# 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)
+ vectors = np.ascontiguousarray(embeddings, dtype=np.float32)
+ rows = vectors.shape[0]
- 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)))
+ # Quantization bits per dimension, validated by rabitqlib
+ nbits = self.setting("nbits", 1)
- self.build()
+ # Default clusters to 4 * sqrt(N), bounded to [1, N] so KMeans always fits
+ clusters = self.setting("clusters", None)
+ clusters = max(1, min(clusters if clusters else round(4 * math.sqrt(rows)), rows))
- # Update id offset and index metadata
- self.config["offset"] += new
- self.metadata()
+ cluster = KMeans(n_clusters=clusters, random_state=0, n_init=1).fit(vectors)
+ centroids = np.ascontiguousarray(cluster.cluster_centers_, dtype=np.float32)
+ clusterids = np.ascontiguousarray(cluster.labels_, dtype=np.uint32)
- def delete(self, ids):
- if not ids or not self.count():
- return
+ dim = self.config["dimensions"]
+ if mode == "ivf":
+ backend = IvfIndex(dim=dim, max_elements=rows, num_clusters=clusters, nbits=nbits, metric="ip")
+ settings = {"mode": mode, "nbits": nbits, "clusters": clusters, "nprobe": self.setting("nprobe", self.nprobe(clusters))}
+ else:
+ 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),
+ )
+ settings = {
+ "mode": mode,
+ "nbits": nbits,
+ "m": self.setting("m", 16),
+ "efconstruction": self.setting("efconstruction", 200),
+ "efsearch": self.setting("efsearch", None),
+ "randomseed": self.setting("randomseed", 100),
+ }
- # 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
+ backend.build(vectors, centroids, clusterids)
+ self.backend = backend
- # Rebuild once deleted rows outnumber live rows, this bounds search overfetch
- if self.count() < len(self.ids) - self.count():
- self.build()
+ # Add id offset and index build metadata
+ self.config["offset"] = rows
+ self.metadata(settings)
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))
+ # The native index errors when k exceeds its row count
+ k = min(limit, self.count())
- mode = self.mode()
- if mode == "ivf":
- nprobe = self.setting("nprobe", max(1, round(self.numclusters / 16)))
+ if self.mode() == "ivf":
+ nprobe = self.setting("nprobe", self.nprobe(self.backend.num_clusters))
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])
+ ids, distances = self.backend.search(queries, k, self.setting("efsearch", None) or 0)
- return results
+ # Map results to [(id, score)], dropping unfilled sentinel slots
+ return [
+ [(int(uid), float(1.0 - dist)) for uid, dist in zip(uids, dists) if uid != SENTINEL]
+ for uids, dists in zip(ids.tolist(), distances.tolist())
+ ]
def count(self):
- return int(np.count_nonzero(self.ids != DELETED)) if self.ids is not None else 0
+ return self.backend.max_elements if self.backend 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")
+ self.backend.save(path)
- def close(self):
- # Parent logic releases the backend
- super().close()
-
- self.vectors = None
- self.ids = None
- self.numclusters = 0
-
- def mode(self, default="ivf"):
+ def mode(self):
"""
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)
+ mode = self.setting("mode", "ivf")
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):
+ def nprobe(self, clusters):
"""
- Returns index build settings for metadata.
+ Returns the default number of clusters to probe at search time.
Args:
- mode: index mode
+ clusters: number of IVF clusters
Returns:
- dict of build settings
+ default nprobe
"""
- 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)
+ return max(1, round(clusters / 16))
diff --git a/test/python/testann/testdense.py b/test/python/testann/testdense.py
index 32741a26..d8851e7f 100644
--- a/test/python/testann/testdense.py
+++ b/test/python/testann/testdense.py
@@ -14,6 +14,7 @@ from unittest.mock import patch
import ggml
import numpy as np
+from rabitqlib import HnswIndex, IvfIndex
from sqlalchemy.dialects.postgresql import BIT
from sqlalchemy.ext.compiler import compiles
@@ -539,7 +540,7 @@ class TestDense(unittest.TestCase):
Test RabitQ backend
"""
- self.runTests("rabitq")
+ self.runTests("rabitq", None, False)
def testRabitQCustom(self):
"""
@@ -573,9 +574,9 @@ class TestDense(unittest.TestCase):
ann.load(index)
self.assertEqual(ann.count(), 0)
- def testRabitQDelete(self):
+ def testRabitQUpdate(self):
"""
- Test RabitQ deletes mark rows without rebuilding the index
+ Test RabitQ stores a single file and does not support append and delete
"""
# Generate dummy data
@@ -583,46 +584,35 @@ class TestDense(unittest.TestCase):
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)
+ # Offset marks the index as existing, see Embeddings.exists
+ self.assertEqual(ann.config["offset"], 100)
+
+ with self.assertRaises(NotImplementedError):
+ ann.append(data[:1])
+
+ with self.assertRaises(NotImplementedError):
+ ann.delete([0])
- # 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})
+ # Limit above the row count returns every row
+ for result in ann.search(data[:2], 200):
+ self.assertEqual(len(result), 100)
- # Deletes are kept after a save and reload
+ # Index is a single file that reloads with the same count and results
index = os.path.join(tempfile.gettempdir(), f"rabitq.{mode}.{round(time.time() * 1000)}")
ann.save(index)
+ self.assertTrue(os.path.isfile(index))
+
+ # File is the native index, readable without the wrapper
+ native = IvfIndex.load(index) if mode == "ivf" else HnswIndex.load(index)
+ self.assertEqual(native.max_elements, 100)
+
+ expected = ann.search(data[:2], 10)
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), [[]])
+ self.assertEqual(ann.count(), 100)
+ self.assertEqual(ann.search(data[:2], 10), expected)
@unittest.skipIf(platform.system() == "Darwin", "SQLite extensions not supported on macOS")
def testSQLite(self):