Quick start¶
Build, search, save and reload a small IVF-RaBitQ index with Python. This guide describes 0.9.0 and uses synthetic data, so no dataset download is required. Coming from 0.8 or 0.7? See the migration guide. For C++, go directly to C++ integration.
Install¶
Wheels support CPython 3.11–3.14 on Linux x86-64/ARM64, Windows x86-64 and macOS 14+ ARM64. x86-64 requires AVX2/FMA; ARM64 uses NEON. See installation for platform details and source builds.
Supply data and queries with shape (count, dim) in the original dimension.
Python indexes convert them to contiguous float32 and accept 64 <= dim <= 65536;
they rotate and pad internally. See input requirements.
Build and search an IVF-RaBitQ index¶
The following complete example uses deterministic synthetic data and does not require a dataset download:
import numpy as np
from rabitqlib import IvfIndex
rng = np.random.default_rng(42)
data = rng.standard_normal((500, 64)).astype(np.float32)
queries = rng.standard_normal((5, 64)).astype(np.float32)
index = IvfIndex(64, 5, metric="l2", seed=42) # 5 clusters, 7 bits by default
index.add(data) # learn 5 centroids, then quantize every vector into its cluster
ids, distances = index.search(queries, k=10, nprobe=5)
print(ids.shape, distances.shape) # (5, 10) (5, 10)
print(ids[0])
The first add on an untrained index trains it on the added vectors, as
index.train(data) would, then adds them. Training uses the settings in
index.cp: 10 k-means iterations on at most 256 sampled vectors per centroid,
spherical k-means for metric="ip" and "cosine", and the index seed. Change index.cp
before the first add to tune them, call index.train(sample) first to train on a
sample, or call index.set_centroids(centroids) to use centroids you computed
elsewhere. train and add use every available CPU by default, capped by
OMP_NUM_THREADS; pass num_threads= to limit them. Without seed, each index
draws a random rotation seed and reports it as index.seed.
nprobe sets how many clusters a query searches. Omitted, it is
num_clusters / 16, rounded and at least 1; this example probes all five.
Read the results¶
Both outputs have shape (number_of_queries, k). IDs are zero-based and follow
the order vectors were added: here they are row numbers of data, and later
add calls continue the numbering without renumbering existing vectors. Results are ordered by increasing distance: metric="l2" estimates
squared Euclidean distance, while metric="ip" estimates 1 - dot(data, query).
Smaller values are better for both metrics. Quantized distances are estimates,
not exact distances to the original vectors.
A search may return fewer than k valid neighbors, for example when k exceeds the
number of points, after removals, or when the probed IVF-RaBitQ clusters contain too
few points. IDs are int64; unfilled slots contain ID -1 and distance +inf. Filter them with
valid = np.isfinite(distances) before using IDs to index your data.
The metric argument accepts "l2", "ip" and "cosine".
metric="cosine" scales database and query vectors to unit length and returns
1 - cos; the saved file records it, so a loaded index keeps normalizing.
Measure recall¶
For this small L2 example, compute exact neighbors from the original vectors, then compare several probe counts on the same index. Recall@10 is the mean fraction of exact top-10 IDs returned for each query.
k = 10
# Float64 exhaustive distances are practical for this tiny dataset only.
delta = queries.astype(np.float64)[:, None, :] - data.astype(np.float64)[None, :, :]
exact_distances = np.sum(delta * delta, axis=2)
exact_ids = np.argsort(exact_distances, axis=1, kind="stable")[:, :k]
for nprobe in (1, 2, 5):
candidate_ids, _ = index.search(queries, k=k, nprobe=nprobe)
recall = np.mean([
np.intersect1d(found, expected).size / k
for found, expected in zip(candidate_ids, exact_ids)
])
print(f"nprobe={nprobe}: Recall@{k}={recall:.3f}")
Missing-result IDs cannot match any ground-truth ID and count as misses. Probing more clusters searches more candidates, but even probing all five does not guarantee recall of 1: quantized scoring and filtering remain approximate.
This small example demonstrates the calculation. For tuning, use representative
held-out queries and compare recall with latency; see the benchmark guide.
The exhaustive array above is only suitable for small datasets. IP ground truth
must rank 1 - dot instead of squared L2.
Save and load¶
Continue with the same index and queries. This example uses a temporary
directory that is removed when the block finishes; use your own persistent path
when keeping an index.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = str(Path(directory) / "ivf.index")
index.save(path)
loaded = IvfIndex.load(path)
loaded_ids, loaded_distances = loaded.search(queries, k=10, nprobe=5)
np.testing.assert_array_equal(loaded_ids, ids)
np.testing.assert_allclose(loaded_distances, distances)
The loaded index owns its data and restores the saved rotation. IVF-RaBitQ saves one
file, including its HNSW centroid routing; files from releases up to 0.8 with HNSW
routing also need the accompanying .hnsw file.
See file compatibility before downgrading.
Next steps¶
- IVF-RaBitQ: raw-vector reranking, precision, centroid routing and updates.
- HNSW-RaBitQ and SymphonyQG: graph-index workflows and parameters.
- Index usage contracts: counts, threading, input lifetimes and file paths.
- Clustering: choose flat RaBitQKMeans or graph-based QGKMeans.
- C++ integration: builds, installation and component selection.
- Stable core API: integrate quantization into your own storage.