Hot AI News

Approximate nearest neighbor search: How AI finds the closest match among millions of vectors

Embeddings turn text into points. Approximate nearest neighbor search finds the closest points fast by giving up a little exactness. How HNSW graphs and FAISS made it practical.

Approximate nearest neighbor search: How AI finds the closest match among millions of vectors
Photo illustration: Aiholics

Approximate nearest neighbor (ANN) search is a way to find the items most similar to a query without comparing the query to every item. It trades a small chance of missing the very best match for a large gain in speed. It is the machinery behind most search over embeddings, the lists of numbers that stand for meaning.

Our explainer on text embeddings shows how a sentence becomes a point. This guide covers the next problem: finding the closest points when there are millions of them.

Why checking every point stops working

Imagine a phone with 10 million saved notes, each stored as an embedding. You type a question and want the five most related notes. The simplest method is to compare your question’s vector with every stored vector and sort the scores.

That is how OpenAI’s embeddings guide demonstrates text search. It computes the cosine similarity between the query and each document, then returns the highest scores. The sample code scans every stored vector and does not use an index.

This exact approach is called brute force. It always finds the true closest items, and for thousands of documents it is fine. For millions or billions, each query must touch every vector, and the cost grows in step with the collection.

Advertisements

Giving up a little exactness to skip most of the work

A robotic gripper lifts a gray component from a tray of similar parts beside a display showing a large candidate grid and a shortlist of three matches.
Photo illustration: Aiholics

The key idea is to accept an answer that is almost always right. An ANN index organizes vectors ahead of time, so a query only visits a small fraction of them. Think of asking a librarian who walks you straight to the right aisle, instead of reading every spine in the building.

Quality is usually measured as recall: of the true top results, how many did the fast method return? A recall of 0.95 means it found 95 of the real 100 nearest items. Builders tune the index until speed and recall are acceptable for their product.

The stored vectors are the same ones the embedding model produced. Only the lookup changes. This is why a dedicated vector database exists: OpenAI’s guide says you can extract the embedding vector, save it in a vector database, and use it for many different use cases.

A road map with highways and side streets

The most widely used design is the Hierarchical Navigable Small World graph, or HNSW. It was published by Yu. A. Malkov and D. A. Yashunin, first submitted to arXiv in March 2016 and last revised in August 2018.

The paper describes a multi-layer structure of proximity graphs. In each graph, every stored vector is linked to some of its neighbors. Each vector is assigned a top layer at random, with an exponentially decaying probability. Few vectors reach the upper layers, so those layers are sparse and their links span long distances.

Search starts at the top layer. Think of taking a highway to the right region, then switching to main roads, then to side streets. At each layer the search hops to whichever linked neighbor is closer to the query, and the result seeds the next layer down.

The authors compare the structure to a skip list, a classic data structure that uses sparse upper levels to jump ahead. According to the abstract, the layering allows logarithmic complexity scaling, meaning cost grows slowly as the collection grows. The paper also describes a heuristic for choosing which neighbors to link, which it says helps at high recall and with highly clustered data.

Advertisements

Making it fast with GPUs and compression

Graphs are one family of methods. Another line of work focuses on raw hardware speed and memory. In 2017, Jeff Johnson, Matthijs Douze and Hervé Jégou published “Billion-scale similarity search with GPUs”, the paper behind the open-source library often called FAISS.

The authors report a design for selecting the k smallest distances that runs at up to 55% of theoretical peak performance on a GPU. They say it gave a nearest-neighbor implementation 8.5 times faster than the prior GPU state of the art.

The paper covers brute-force, approximate and compressed-domain search. The compressed variant is based on product quantization, which stores each vector in a compact code so far more of them fit in memory. As scale examples, the authors report building a high-accuracy k-nearest-neighbor graph on 95 million images in 35 minutes, and a graph over 1 billion vectors in under 12 hours on four GPUs. They open-sourced the implementation.

Where it runs today

ANN indexes sit under semantic search, recommendations, and retrieval for chatbots, where an app fetches relevant passages before an AI model writes an answer. Any product that stores embeddings in a vector store relies on some form of this lookup, whether built on HNSW, compressed indexes, or a mix.

Size matters here too. OpenAI’s guide notes that larger embeddings in a vector store generally cost more compute, memory and storage than smaller ones. It adds that a dimensions parameter can shorten embeddings, for example to fit a store that supports vectors only up to 1024 dimensions. Shorter vectors make the index smaller and queries cheaper, at some cost in detail.

Trade-offs and what to watch

ANN has real limits. A fast index can silently miss the best match, and the miss rate depends on settings and data. Teams should measure recall on their own queries instead of trusting a default.

  • Memory: graph indexes keep links in addition to vectors, so they can use more RAM than the raw data.
  • Updates: adding and deleting vectors is easy in some designs and awkward in others.
  • Filters: combining similarity with rules such as “only documents from this year” can reduce both speed and recall.
  • Embedding quality: the index only finds close points. If the embedding model places the wrong things near each other, a perfect index returns wrong answers faster.

Watch for work on keeping indexes small through compression and shorter vectors, and on hardware-aware designs that mix GPUs, memory and disk. As collections grow into the billions, the cleverness of the lookup matters as much as the model that made the vectors.

Sign Up for the Daily AI Pulse

One email a day. All the stories that matter.

Daniel ReedAI Research, Safety & Ethics Analyst

Daniel Reed currently works as an AI Research, Safety & Ethics Analyst at Aiholics, writing about how changes in artificial intelligence are affecting and will affect scholarship,…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may also like