Faster Searching with Quantization and Query Adaptation

How can we make queries faster without giving up much accuracy? And what can we do when the queries we need to answer don’t look much like the data we indexed? PyNNDescent 0.8 adds a number of new options aimed at exactly these questions. In this guide we’ll walk through each of them: quantized search, which answers queries using compact codes in place of the full data; maximum inner product search, for when the size of a vector matters as well as its direction; adapting an index to the queries it will actually see; and a faster way of building indexes for high dimensional data. For each we’ll look at what it does, why it helps, and how to use it.

All of these options work with dense data. Sparse data is indexed and searched just as before.

To have something to work with, let’s make some random data to index, and some queries to search it with.

import numpy as np
from pynndescent import NNDescent

rng = np.random.default_rng(42)
data = rng.normal(size=(20000, 256)).astype(np.float32)
queries = rng.normal(size=(1000, 256)).astype(np.float32)

Adapting the index to the queries

Approximate nearest neighbor search works best when the queries come from the same distribution as the indexed data. This isn’t always the case. Multimodal models, for instance, embed text and images in a shared space, but text queries searching a collection of image embeddings tend to land in quite different parts of that space from the images themselves. The search graph and search tree are built to navigate the data, so such searches have to work considerably harder to find the true nearest neighbors.

If you have a sample of the kinds of queries you expect, you can prepare the index for them.

sample_queries = ...  # e.g. a few tens of thousands of example queries
index = NNDescent(data)
index.prepare(query_sample=sample_queries)
indices, distances = index.query(queries, k=10)

This does two things. First, the search graph gains extra edges among each sample query’s nearest data points, so that searches can move around more easily in the regions where queries tend to arrive. Second, searches start from a random projection tree built over the sample queries, rather than over the data, so they begin close to where the query’s neighbors actually are. If you are also using quantization_dims, the projection is fitted to the sample queries as well as the data. The result is that queries like the sample reach a given accuracy with less work. A few tens of thousands of sample queries or more tends to work best.

Preparing the index this way needs to know the nearest neighbors of each sample query in the data. If you already have them (ideally 64 or more for each query) you can pass their indices with query_neighbors; otherwise they are found by searching the index, which adds to the time prepare() takes.

The sample has to be given before the search index is built, so you need to call prepare(query_sample=...) before you first query the index. This is supported for dense data with either no quantization or "sq8" or "sq4" quantization. To keep the index small the sample isn’t kept once it has been used (it isn’t pickled with the index, for example). That means if you update() the index you should pass the sample to update() as well; otherwise the updated index is prepared without it, and you’ll get a warning letting you know.

Building indexes progressively

So far we’ve looked at making queries faster, but the same ideas can speed up building an index too. For dense data with many features most of the cost of building the nearest neighbor graph comes from computing distances in the early rounds of nearest neighbor descent, and those rounds only need to find roughly the right neighbors. With a progressive build those early rounds use 8-bit codes and integer dot products, while keeping somewhat longer lists of candidate neighbors so that the true neighbors aren’t lost along the way. The build then switches to exact distances to refine the graph. The final graph has exact distances, and typically recall that is as good or better.

You don’t need to do anything to make use of this. With the default progressive_build="auto" it is used for Euclidean, cosine and dot distances on data with 512 or more features, which is where it pays off. It makes building an index about 25% faster for 784 dimensional data, and about 45% faster at 4096 dimensions. From 1024 features up the random projection forest used to initialise the graph is also built on a lower dimensional random projection of the data, which is several times faster with no loss of graph quality. The progressive build does need about half as much memory again as the data itself while the index is being built, so if memory is tight, or you’d simply like the original build, pass progressive_build=False.

Using these options in pipelines

PyNNDescentTransformer accepts quantization, rerank_precision, quantization_dims and progressive_build as well, and passes them on to the index it builds. Bear in mind that quantization only speeds up the searches made when you transform new data. The nearest neighbor graph of the training data that fit_transform returns comes straight from building the index, so it is unaffected (although the progressive build can make it faster to compute).

That covers the new options in PyNNDescent 0.8. How much each of them helps depends a great deal on your data, so it’s worth trying a few settings and measuring the speed and accuracy you get. If you find cases where these options don’t behave as you’d expect, please open an issue and let us know.