All posts

Composable Vector Search in Python with kANNolo

by tusKANNy team
Vector SearchPythonReleasekANNolo

kANNolo 0.18 changes how indexes are built from Python. Before, each index was a class with a fixed combination of representation, quantizer and index structure. Now these are independent choices: you pick the representation, the similarity function, the encoder, the index structure and any number of rescoring stages, and kannolo.build assembles the index. Changing a quantizer, an index structure or a whole stage of a pipeline is a one-line change.

From classes to building blocks

Until version 0.17, the Python package exposed one class per combination: DensePlainHNSW, DensePQHNSW, DenseRerankHNSW, SparseRerankHNSW, and so on. Each class had its own constructor and its own arguments. Any combination outside this list, such as an IVF index rescored on float16 vectors or a sparse first stage rescored with a dense model, required writing Rust.

The Rust side of kANNolo never had this limitation. As we describe in our paper on Vectorium and kANNolo1, the libraries split approximate nearest neighbors search into independent parts: a vector representation, a distance function, an encoder that compresses the vectors, and an index structure. Any index can serve as the first stage of a two-stage RerankIndex, and any dataset can rescore its candidates. The new Python API exposes the same parts:

import numpy as np
import kannolo
 
data = np.load("embeddings.npy")   # shape (n, d), float32
queries = np.load("queries.npy")   # shape (n_queries, d)
 
index = kannolo.build(
    data,
    metric="ip",
    encoder=kannolo.RaBitQ(bits=1),               # 1-bit codes in the graph
    index=kannolo.HNSW(m=32, ef_construction=200),
    rerank=kannolo.Rerank(kannolo.Plain("f16")),  # candidates rescored on float16
)
 
dists, ids = index.search(queries, k=10, ef_search=100, k_candidates=100)
index.save("dense.kannolo")
index = kannolo.load("dense.kannolo")  # the file records how the index was built

Each argument is one independent choice:

  • Representation: dense vectors, sparse vectors, or multi-vector documents (one vector per token, as in ColBERT2). It is inferred from the data: a 2-D array is dense, a scipy.sparse matrix is sparse, a list of token matrices is multi-vector.
  • Metric: inner product, Euclidean distance, or MaxSim for multi-vector data.
  • Encoder: how the vectors are stored. Plain float32, float16 or bfloat16, fixed point, Product Quantization (PQ)3, RaBitQ4 and RaBitQ-ext5 from 1 to 8 bits per component, and the sparse and multi-vector encoders of Vectorium.
  • Index: an exhaustive scan (Flat), an HNSW graph6, or an IVF index with flat or HNSW centroids.
  • Rescoring stages: zero, one or more. Each stage has its own encoder, metric and representation, and rescores the candidates of the stage before it.

The search parameters follow the same logic. index.search is the same method for every index, and each parameter applies to one part of it: ef_search to an HNSW first stage (or to the HNSW centroids of an IVF), nprobe to an IVF first stage, k_candidates to each rescoring stage. Every parameter has a default. An argument that does not apply to the index raises an error instead of being silently ignored.

Comparing methods by changing one argument

Since every choice is independent, comparing quantizers or index structures is a loop. The example below builds six indexes on SIFT1M3, with three encoders and two index structures, and measures their recall. The collection, the queries and the ground truth are available on Hugging Face as .npy files:

import itertools
import numpy as np
import kannolo
 
data = np.load("dataset.npy")
queries = np.load("queries.npy")
truth = np.load("groundtruth.npy")[:, :10]
 
encoders = {
    "f16": kannolo.Plain("f16"),
    "PQ(32)": kannolo.PQ(subspaces=32),
    "RaBitQ(4)": kannolo.RaBitQ(bits=4),
}
indexes = {
    "HNSW": (kannolo.HNSW(), dict(ef_search=100)),
    "IVF": (kannolo.IVF(n_lists=4096), dict(nprobe=32)),
}
 
for (e, encoder), (i, (structure, params)) in itertools.product(encoders.items(), indexes.items()):
    index = kannolo.build(data, metric="l2", encoder=encoder, index=structure)
    _, ids = index.search(queries, k=10, **params)
    recall = np.mean([len(set(a) & set(b)) / 10 for a, b in zip(ids, truth)])
    print(f"{i:<5} {e:<10} recall@10 {recall:.3f}  {index.nbytes / 2**20:.0f} MiB")

kannolo.check validates a combination without building anything. A combination that does not exist raises an error that says why, for example DotPacking8 scores with inner product only; use metric="ip".

Hybrid pipelines

A rescoring stage can hold a different representation of the same items. A learned sparse first stage, such as SPLADE7, can retrieve candidates that a multi-vector model then rescores. In our ECIR 2026 paper8 this pipeline was up to 24× faster than state-of-the-art multi-vector retrieval systems. It now takes a single call:

index = kannolo.build(
    splade_docs,                         # scipy.sparse matrix, one row per document
    encoder=kannolo.DotPacking8(),
    index=kannolo.HNSW(),
    rerank=kannolo.Rerank(
        kannolo.TwoLevelPQ(subspaces=16),  # compressed token vectors
        data=(tokens, doc_lengths),        # the multi-vector documents, same order
    ),
)
 
dists, ids = index.search(
    splade_queries, k=10,
    rerank_queries=colbert_queries,      # each stage receives queries in its representation
    k_candidates=100,
)

Replacing the multi-vector stage with a dense one gives a sparse-to-dense pipeline, and a dense first stage can be rescored with sparse or multi-vector vectors in the same way.

Residuals and cascades

A rescoring stage does not have to store the full vectors. With residual rescoring, the first stage indexes only part of each vector, and the rescoring stage stores the rest. The score of a candidate is the sum of the two. For learned sparse vectors, the graph can be built on the components that hold 60% of each vector's L1 mass. In our RerankIndex post this index was up to 4.3× faster than a plain HNSW graph on MS MARCO:

index = kannolo.build(
    splade_docs,
    encoder=kannolo.Blocked(),
    index=kannolo.HNSW(),
    transform=kannolo.L1Prune(60),                               # the graph keeps 60% of the L1 mass
    rerank=kannolo.Rerank(kannolo.Plain("f16"), residual=True),  # the rest rescores the candidates
)

A list of rescoring stages gives a cascade, where each stage rescores the candidates of the stage before it. Here 1-bit codes in the graph return 400 candidates, 8-bit codes keep the best 50, and float32 vectors give the final top 10:

index = kannolo.build(
    data,
    encoder=kannolo.RaBitQ(bits=1),
    index=kannolo.HNSW(),
    rerank=[kannolo.Rerank(kannolo.RaBitQ(bits=8)), kannolo.Rerank(kannolo.Plain("f32"))],
)
dists, ids = index.search(queries, k=10, k_candidates=[400, 50])

Composing indexes from stored parts

Building a graph takes minutes to hours, while a rescoring stage is only an encoded copy of the collection. kannolo.compose adds rescoring stages to an index that is already built or loaded. The first stage is shared, not copied, so one stored first stage can be combined with several rescoring encoders in memory:

first = kannolo.load("hnsw_pq32.kannolo")   # built once, with metric="l2": the file records it
 
rescorings = {
    "f32": kannolo.Plain("f32"),
    "f16": kannolo.Plain("f16"),
    "RaBitQ(8)": kannolo.RaBitQ(bits=8),
}
for name, encoder in rescorings.items():
    # the rescoring stage uses the first stage's metric, unless given its own (metric=...)
    index = kannolo.compose(first, kannolo.Rerank(encoder, data=data))
    _, ids = index.search(queries, k=10, ef_search=100, k_candidates=100)
    recall = np.mean([len(set(a) & set(b)) / 10 for a, b in zip(ids, truth)])
    print(f"{name:<10} recall@10 {recall:.3f}  {index.nbytes / 2**20:.0f} MiB")

We ran this on SIFT1M with three first stages and three rescoring encoders, which gives nine two-stage indexes from three stored files. The first stages are an HNSW graph over 1-bit RaBitQ codes, an HNSW graph over PQ codes with 32 subspaces, and an IVF index with 4,096 lists over 4-bit RaBitQ codes. Each first stage returns 100 candidates (ef_search=100 for HNSW, nprobe=32 for IVF). Recall is the fraction of the true 10 nearest neighbors that an index returns, measured on 1,000 queries, and throughput is measured on one thread. Memory is the size of the whole two-stage index:

First stageRescoringMemory (MiB)Recall@10, first stageRecall@10, two-stageQueries/s
HNSW, RaBitQ (1 bit)float326380.2610.7253,749
float163940.7253,652
RaBitQ (8 bits)2800.7223,679
HNSW, PQ (32 subspaces)float325780.7090.9884,253
float163340.9884,167
RaBitQ (8 bits)2200.9663,936
IVF, RaBitQ (4 bits)float325660.8640.9172,315
float163210.9172,328
RaBitQ (8 bits)2070.9022,590

Building the first stages took between 13 and 137 seconds, while each compose call took less than half a second. Rescoring on float32 or float16 gives the same recall, because both find every true neighbor among the 100 candidates, and float16 takes about 240 MiB less. The recall of a two-stage index is therefore limited by its first stage: on the 128 dimensions of SIFT1M, the 1-bit RaBitQ graph puts only 72.5% of the true neighbors among its candidates, while the PQ graph puts 98.9%. A table like this one takes a few minutes to produce, and it shows where to spend memory for a given collection.

Every composition, from Python

The table below is Table 7 of our paper. It lists the compositions that are meaningful for each representation, with the name of the published method that has the same structure, where one exists. Scalar stands for float32, float16, bfloat16 and 16- or 8-bit fixed point, and RaBitQ for both the 1-bit RaBitQ and RaBitQ-ext.

First-stage indexFirst-stage encoderRescoringKnown as
Dense
Flatscalar——
FlatPQ—PQ3
FlatRaBitQ——
FlatPQ, RaBitQscalar, PQ, RaBitQ—
HNSWscalar—HNSW6
HNSWPQ—HNSWPQ
HNSWRaBitQ——
HNSWPQscalar, PQ, RaBitQHNSWPQ + refine
HNSWRaBitQscalar, PQ, RaBitQHNSW-RaBitQ
IVF, flat centroidsscalar, PQ—IVFFlat, IVFPQ3
IVF, HNSW centroidsscalar, PQ—IVF-HNSW
IVF, flat or HNSW centroidsRaBitQ—IVF-RaBitQ4
IVF, IVF centroidsscalar, PQ——
IVF, any centroidsscalar, PQ, RaBitQscalar, PQ, RaBitQ—
Sparse
Flatscalar, blocked, DotPacking8——
HNSWscalar, blocked, DotPacking8——
IVF, any centroidsscalar, DotPacking8——
Flat, HNSW, IVFscalar, DotPacking8scalar—
Flat, HNSW, IVFtop-a% of L1 mass, scalar or blockedscalar or blocked residuals—
Multi-vector
Flat, HNSWscalar, PQ, two-level PQ——
Flat, HNSWscalar, PQ, two-level PQscalar, PQ, two-level PQ—
Hybrid
Flat, HNSW, IVFany sparseany dense—
Flat, HNSW, IVFany sparseany multi-vectorMultivector reranking8
Flat, HNSW, IVFany denseany sparse, any multi-vector—
Cascade
two-stage indexany two-stage indexany—

Every row except two can be built from Python: an IVF whose centroids are themselves indexed with an IVF, and a sparse IVF whose clusters are stored with DotPacking8. The Rust types allow both, but kANNolo does not build them yet, neither from Python nor from its command-line tools. The paper measures many of these compositions against FAISS, the RaBitQ library and other systems.

No cost at search time

The Rust library builds one specialized type for each combination. The Python API cannot know in advance which combination a user will choose, so each index is wrapped behind one common interface, called once per batch of queries. The search inside each call runs the same specialized code as a Rust program that names the types directly.

The library contains every combination compiled ahead of time. A build from source can leave out the representations it does not need (dense, sparse, multi-vector or IVF) for a smaller library and a faster build.

HNSW indexes built with the new API also support filtered search with ACORN9. A filter, given as a mask, a list of ids or a function, restricts the results to the vectors that satisfy it, and it is applied during the graph traversal.

Try it

Install kANNolo with pip install kannolo. The Python guide lists every option, and the notebooks cover dense and sparse benchmarks, hybrid pipelines, composition from stored parts and filtered search. If you build a combination we have not tried, tell us how it performs on GitHub.

References

  1. Silvio Martinico, Franco Maria Nardini, Cosimo Rulli, Rossano Venturini. Modular and Efficient Approximate Nearest Neighbors Search with Vectorium and kANNolo. arXiv, 2026. arXiv:2611.03927 ↩

  2. Omar Khattab, Matei Zaharia. ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT. SIGIR, 2020. doi:10.1145/3397271.3401075 ↩

  3. Hervé Jégou, Matthijs Douze, Cordelia Schmid. Product Quantization for Nearest Neighbor Search. IEEE Transactions on Pattern Analysis and Machine Intelligence, 2011. doi:10.1109/TPAMI.2010.57 ↩ ↩2 ↩3 ↩4

  4. Jianyang Gao, Cheng Long. RaBitQ: Quantizing High-Dimensional Vectors with a Theoretical Error Bound for Approximate Nearest Neighbor Search. SIGMOD, 2024. doi:10.1145/3654970 ↩ ↩2

  5. Jianyang Gao, Yutong Gou, Yuexuan Xu, Yongyi Yang, Cheng Long, Raymond Chi-Wing Wong. Practical and Asymptotically Optimal Quantization of High-Dimensional Vectors in Euclidean Space for Approximate Nearest Neighbor Search. SIGMOD, 2025. doi:10.1145/3725413 ↩

  6. Yu A. Malkov, D. A. Yashunin. Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs. IEEE Transactions on Pattern Analysis and Machine Intelligence, 2020. doi:10.1109/TPAMI.2018.2889473 ↩ ↩2

  7. Thibault Formal, Benjamin Piwowarski, Stéphane Clinchant. SPLADE: Sparse Lexical and Expansion Model for First Stage Ranking. SIGIR, 2021. doi:10.1145/3404835.3463098 ↩

  8. Silvio Martinico, Franco Maria Nardini, Cosimo Rulli, Rossano Venturini. Multivector Reranking in the Era of Strong First-Stage Retrievers. ECIR, 2026. doi:10.1007/978-3-032-21324-2_4 ↩ ↩2

  9. Liana Patel, Peter Kraft, Carlos Guestrin, Matei Zaharia. ACORN: Performant and Predicate-Agnostic Search Over Vector Embeddings and Structured Data. SIGMOD, 2024. doi:10.1145/3654923 ↩