Search

Search papers and lessons

Billion-scale similarity search with GPUs

Jeff Johnson, Matthijs Douze, Hervé Jégou · 2017

FAISS made nearest-neighbour search over a billion vectors practical on GPUs by fusing a one-pass top-k selection with product-quantized search.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Probability
  • Algorithms
  • Linear algebra
  • Systems
  • ReadReady to readNot yet

TL;DR

Finding the closest vectors to a query, out of a billion stored vectors, is too slow to do by brute force on one processor. This paper makes it fast on GPUs in two ways: a new method for picking the k smallest values from a huge array, which keeps its working set in the chip's fastest memory and reads the data only once, and a search layout built on product quantization that compresses each vector to a few bytes. The authors report a k-NN graph over 1 billion vectors built in under 12 hours on four GPUs, and a search 8.5 times faster than the previous best GPU method at billion scale.

Builds on: K-Nearest Neighbors, Product Quantization, Inverted Index, GPU Architecture · Leads to: Approximate Nearest Neighbor Search

Why it mattered

Embedding models turn images, videos, and text into lists of numbers, and "find the most similar item" becomes "find the nearest vector". Systems that retrieve passages for language models, match product photos, or cluster huge image collections all run this search at scale. The paper's library, FAISS, is open-source, and the authors released their approach so others could compare against it.

The paper changed what was practical in two ways. First, it showed that a GPU can build a k-NN graph of a 95-million-image collection (the YFCC100M dataset) in 35 minutes, at an accuracy above 0.8. Second, it made billion-vector indexes fit on a handful of GPUs with a usable speed-accuracy trade-off, where earlier GPU work covered only small or exhaustive search. For the neighbouring ideas, read Approximate Nearest Neighbor Search for the wider family of methods and Vector Quantization for the compression idea underneath.

The problem

A typical embedding has 50 to 1000 dimensions. The database is large enough that it stops fitting in memory in its raw form. Each query must be compared with every vector, and the work grows with the database size times the dimension. For the SIFT1M benchmark (one million 128-dimensional vectors, 10,000 queries) the full distance computation is about 1.28 trillion floating-point operations, which a GPU does in under a second. The harder part is what comes after the distances: picking the k smallest of them for every query.

Three obstacles appear when the job moves to a GPU.

  • Selection is the bottleneck. Standard k-selection methods make several passes over the data in slow global memory. Heaps, the usual choice on a CPU for small k, expose little parallelism because each insert changes the tree in a data-dependent way. GPU heaps and priority queues added warp divergence, extra kernel launches, and synchronisation.
  • Compressed search needs a GPU layout. Product quantization with an inverted file (IVFADC) is the standard way to shrink billion-vector indexes. Its list scans and table lookups have to be arranged for the GPU's memory system, which the paper's Section 5 does.
  • Prior GPU work did not reach billion scale. Most GPU similarity-search code used binary codes, small datasets, or exhaustive search. The one GPU method that handled billion-vector quantized search was the state of the art the authors had to beat.

GPUs have very high arithmetic and memory throughput, but they penalise irregular control flow. The standard selection algorithms assume the opposite, so the fix had to be a selection structure that a GPU can run without branching.

How it works

The search runs in five stages. Each query is compared against a set of compressed vectors grouped into lists, and only the closest few lists are scanned.

flowchart LR
  A[Batch of queries] --> B[Coarse quantizer picks tau nearest lists]
  B --> C[Scan those inverted lists of PQ codes]
  C --> D[Sum one table lookup per code byte]
  D --> E[WarpSelect keeps the k smallest]
  E --> F[k nearest vector IDs]

Here is one tiny instance, with a toy codebook of two entries per sub-quantizer instead of the paper's 256, so every number can be checked by hand. The query is a four-dimensional vector that has already had its coarse centroid subtracted. The stored vectors are coded in two bytes each.

  1. Split the query residual into two halves. The query residual is (1,0,0,2)(1, 0, 0, 2). The first half is (1,0)(1, 0) and the second is (0,2)(0, 2). Check: the halves together have four numbers.
  2. Build a lookup table for each half. The first sub-quantizer has codewords (0,0)(0, 0) and (2,0)(2, 0). The squared distance from (1,0)(1, 0) to each is 11 and 11, so the table is T1=[1,1]T_1 = [1, 1]. The second sub-quantizer has codewords (0,0)(0, 0) and (0,3)(0, 3). The squared distances from (0,2)(0, 2) are 44 and 11, so T2=[4,1]T_2 = [4, 1]. Check: each table has one entry per codeword.
  3. Read a stored code as two indices. Suppose the list holds three codes, (0,1)(0, 1), (1,0)(1, 0) and (0,0)(0, 0). The code (0,1)(0, 1) means codeword 0 of the first sub-quantizer and codeword 1 of the second. No vector is decoded.
  4. Add two table lookups. For (0,1)(0, 1) the approximate squared distance is T1[0]+T2[1]=1+1=2T_1[0] + T_2[1] = 1 + 1 = 2. Check: the code has two bytes, so there are exactly two lookups.
  5. Repeat for the other codes. For (1,0)(1, 0) the sum is T1[1]+T2[0]=1+4=5T_1[1] + T_2[0] = 1 + 4 = 5. For (0,0)(0, 0) it is T1[0]+T2[0]=1+4=5T_1[0] + T_2[0] = 1 + 4 = 5. Check: three codes, three sums, and the work per code is still two lookups.
  6. Keep the smallest. With k=1k = 1, the selection keeps the code (0,1)(0, 1) with distance 22, which is the nearest neighbour under the approximation. In the paper, the same selection runs in registers across all 32 lanes of a warp, in one pass over the data.

The point of the walkthrough is step 4. Each stored vector costs two table reads and two additions, and the expensive multiplications were done once per query in the tables. The paper's graph experiments on YFCC100M use 16, 32 or 64 bytes per vector, so each vector costs that many lookups instead of a full sum over all dimensions.

The math

Definition: k-selection
Given an array of ℓ\ell numbers a0,…,aℓ−1a_0, \dots, a_{\ell-1} and an integer kk, k-selection returns the kk smallest values together with their positions in the array. The paper's comparisons use squared distances, so "smallest" means nearest.

The symbols used below: xx is a query vector in Rd\mathbb{R}^d, yiy_i is the ii-th database vector, ℓ\ell is the number of database vectors in a list, nqn_q is the number of queries in a batch, and ⟨⋅,⋅⟩\langle \cdot, \cdot \rangle is the dot product.

Step 1 in symbols: distances as a matrix product

The exact search computes all squared distances between a batch of queries and the database. It uses the identity behind Euclidean Distance:

∥xj−yi∥22=∥xj∥2+∥yi∥2−2⟨xj,yi⟩.\|x_j - y_i\|_2^2 = \|x_j\|^2 + \|y_i\|^2 - 2\langle x_j, y_i \rangle.

The first two terms are precomputed once per vector. The third term for a whole batch is the matrix product XY⊤XY^\top, so the expensive part is a Matrix Multiplication that GPUs run very efficiently. The authors call it through cuBLAS, the GPU matrix library. The ∥xj∥2\|x_j\|^2 term is the same for every candidate of one query, so it can be dropped before selection without changing the ranking.

Step 2 in symbols: coarse lists

IVFADC splits the database into ∣C1∣|\mathcal{C}_1| inverted lists using a first quantizer q1q_1, trained with K-Means Clustering; the paper uses 2162^{16} coarse centroids on YFCC100M and 2182^{18} on Deep1B. Each vector yy is stored with its residual after q1q_1, and the search only looks inside the τ\tau lists whose centroids are closest to the query:

LIVFADC=k-argmini s.t. q1(yi)∈LIVF  ∥x−q(yi)∥2,L_{\mathrm{IVFADC}} = \underset{i \text{ s.t. } q_1(y_i) \in L_{\mathrm{IVF}}}{k\text{-}\mathrm{argmin}} \; \|x - q(y_i)\|_2,

where LIVFL_{\mathrm{IVF}} is the set of the τ\tau nearest coarse centroids. The number τ\tau is the multi-probe parameter: larger τ\tau means more accuracy and more scanning.

Step 3 in symbols: product quantization and table lookups

The fine quantizer q2q_2 is a product quantizer. A vector is cut into bb sub-vectors, and each sub-vector is replaced by the index of its nearest codeword out of 256, so the code is bb bytes and ∣C2∣=256b|\mathcal{C}_2| = 256^b reproduction values exist. Once xx and the coarse centroid are known, the squared distance to any stored code is a sum of bb table entries:

∥x−q(y)∥22=∑j=1b∥x~j−qj ⁣(y~j)∥22,\|x - q(y)\|_2^2 = \sum_{j=1}^{b} \left\|\tilde{x}^{j} - q^{j}\!\left(\tilde{y}^{j}\right)\right\|_2^2 ,

where x~j\tilde{x}^{j} and y~j\tilde{y}^{j} are the jj-th sub-vectors of the query and stored residuals. Each table TjT_j has 256 entries, one for each codeword of sub-quantizer jj.

The cost comparison is what makes the method fast. Computing nn distances directly takes n×dn \times d multiply-adds. With tables it takes 256×d256 \times d multiply-adds once, then n×bn \times b lookup-adds. For d=128d = 128 and b=8b = 8 this is 128128 multiply-adds per vector against 88 lookup-adds per vector, about sixteen times less work per stored vector. For one query against a list of 10610^6 vectors, that is 1.28×1081.28 \times 10^8 multiply-adds against 8×1068 \times 10^6 lookup-adds, plus one table build of 256×128=32,768256 \times 128 = 32{,}768 multiply-adds. Counted directly from the formulas, these totals are an illustration; the paper does not report them.

Step 4 in symbols: the cost of WarpSelect

WarpSelect processes the ℓ\ell candidate values in groups of 32, one per lane. Write tt for the length of each lane's thread queue. Three kinds of work happen, with costs C1C_1 (compare 32 values with the queue heads), C2=O(t)C_2 = O(t) (insert into a thread queue), and C3=O(tlog⁡(32t)2+klog⁡(max⁡(k,32t)))C_3 = O\big(t \log(32t)^2 + k \log(\max(k, 32t))\big) (sort and merge the queues). They happen N1=ℓ/32N_1 = \ell / 32, N2=O(klog⁡ℓ)N_2 = O(k \log \ell) and N3=O(klog⁡(ℓ)/t)N_3 = O(k \log(\ell)/t) times on random data. The total is N1C1+N2C2+N3C3N_1 C_1 + N_2 C_2 + N_3 C_3. A larger tt makes the merges rarer but each insertion more expensive, so the paper picks tt by experiment: t=2t = 2 for k≤32k \le 32, t=3t = 3 for k≤128k \le 128, t=4t = 4 for k≤256k \le 256, and t=8t = 8 for k≤1024k \le 1024.

Step 5 in symbols: the memory bound

A memory-bound kernel cannot run faster than its input can be read. If the input is BB bytes and the device delivers bandwidth WW bytes per second, the time is at least B/WB / W. The authors use this roofline bound to judge how close their selection comes to the limit. For a single pass over global memory, that limit is the reference point for "percent of peak".

Results

The numbers below are the paper's own results. Times are on NVIDIA Titan X GPUs unless stated.

ExperimentThis paperComparisonSource of comparison
k-selection, ℓ=128000\ell = 128000, k=100k = 1001.62 times faster than fgknnfgknn merge queueSection 6.1
k-selection, ℓ=128000\ell = 128000, k=1000k = 10002.01 times faster than fgknnfgknn merge queueSection 6.1
Peak fraction of WarpSelect55 percent at k=100k = 100; 16 percent at k=1000k = 1000Memory-bandwidth limitSection 6.1
Exact search, SIFT1M85 percent of peakcuBLAS GEMM and selectionSection 6.3
k-means, MNIST8m, 256 centroids140 s on 1 GPU; 84 s on 4 GPUsBIDMach, 320 sSection 6.2
k-means, MNIST8m, 4096 centroids316 s on 1 GPU; 100 s on 4 GPUsBIDMach, 735 sSection 6.2
SIFT1M, same time budget, 0.02 ms per queryR@1 = 0.80, R@100 = 0.95R@1 = 0.51, R@100 = 0.86Section 6.4
SIFT1B, one GPU, 8 bytes per vectorR@10 = 0.376 in 17.7 µs per queryR@10 = 0.35 in 150 µsSection 6.4
Deep1B, 4 GPUsR@1 = 0.4517 in 0.0133 ms per vectorCPU paper: R@1 = 0.45 in 20 ms, one threadSection 6.4
k-NN graph, 95 million imagesAccuracy above 0.8 in 35 minutesnoneSection 6.5

What they mean. The selection gains matter most at large kk and large arrays, and the memory-bound peak tells you how much headroom is left. The billion-scale search results show that a quantized index with careful GPU layout beats the previous GPU method on accuracy and speed at a similar memory budget. The k-NN graph results show that a graph over 95 million or 1 billion vectors, which earlier GPU work had not reached, can be built in hours on a few GPUs.

When to use this design. The design suits large databases of dense vectors of moderate dimension, where k is small and the index must fit in GPU memory. For exact search over a small collection, a plain GPU search is simpler and exact. The authors' own results show the tradeoffs: WarpSelect drops to 16 percent of peak at k=1000k = 1000, and compression trades accuracy for memory, with τ\tau and bb setting the balance between recall and speed.

Limits. The 8.5 times figure compares against one GPU baseline on SIFT1B, and it is a per-query time at a specified accuracy, not a whole-system benchmark. The Deep1B comparison with a CPU uses different hardware, and the paper says so. The k-NN graph comparison with NN-Descent is across different machines and dataset sizes. Multi-GPU scaling is near linear for replication on k-means, but for the k-NN graph, going from four to eight GPUs gave about 1.6 times speedup for 20-byte codes and about 1.7 times for 40-byte codes. Finally, the selection kernel's efficiency drops sharply for large kk, so the best settings depend on the workload.

Reading guide

The paper has seven sections and an appendix. Read them in this order, with the lessons each one needs.

  • Section 1, Introduction. Motivation and the list of contributions. Needs Approximate Nearest Neighbor Search and Product Quantization.
  • Section 2, Problem statement. Defines the search, k-selection, batching, exact search, and IVFADC. Needs K-Nearest Neighbors, Euclidean Distance, Inverted Index and Product Quantization.
  • Section 3, GPU overview. Explains lanes, warps, blocks, registers, and shared memory, then the problems with heaps and priority queues on a GPU. Needs GPU Architecture, GPU Memory Hierarchy and Priority Queue.
  • Section 4, Fast k-selection. The in-register sorting networks (Algorithms 1 and 2) and WarpSelect (Algorithm 3). Needs Sorting Network and Sorting Algorithm. Read Section 4.1 slowly; it is the most technical part.
  • Section 5, Computation layout. Exact search through GEMM, the lookup-table decomposition, the GPU implementation, and multi-GPU replication and sharding. Needs Matrix Multiplication, K-Means Clustering and the material above.
  • Section 6, Experiments. Each subsection answers one question: selection speed, clustering, exact search, billion-scale search, the k-NN graph, and using that graph to find smooth paths between images. Read the tables and the discussion paragraphs; skip the figure captions until you have the context.
  • Section 7 and the appendix. The conclusion is short. The appendix derives the WarpSelect cost, which uses the reasoning in Section 4.3.

Check yourself

QuestionWhat does k-selection return, and why is it harder on a GPU than on a CPU?Show answer
It returns the kk smallest values in an array together with their positions. On a CPU, a small max-heap is a natural choice, but a heap updates in a serial, data-dependent way and does not use SIMD parallelism well. On a GPU, the standard methods make several passes over data in global memory, and heaps cause warp divergence, so the algorithm must be restructured to fit registers and a single pass.
QuestionA product quantizer uses b=16b = 16 bytes per code, and each stored vector costs one table lookup per byte. How many lookup-adds does a list of 10510^5 codes need for one query?Show answer
Each code needs 1616 lookup-adds, so the list needs 105×16=1.6×10610^5 \times 16 = 1.6 \times 10^6 lookup-adds. The tables are built once per query and are not counted per code.
QuestionWhy does the paper fuse the k-selection into the distance kernel instead of writing the full distance matrix to global memory?Show answer
The full matrix is large, and writing it and reading it back costs two extra passes over global memory. Fusing selection into the kernel that produces the distances removes one pass, so the kernel moves less data. The paper reports that the unfused version is at least 25 percent slower on SIFT1M.
QuestionYou have a database of 50 million 256-dimensional vectors and a GPU with 16 GB of memory. Would you store the raw vectors, and what does the paper suggest instead?Show answer
Raw float32 vectors would need about 50 million times 256 times 4 bytes, roughly 51 GB, which does not fit on one 16 GB GPU. The paper suggests compressing each vector with product quantization, so the codes take a few bytes per vector, and using an inverted file so that each query scans only a few lists. The compressed index is then small enough to hold on one GPU, at a cost in accuracy that the parameters τ\tau and bb control.

Sources

Read the full paper

Jeff Johnson, Matthijs Douze, Hervé Jégou, 2017. arXiv:1702.08734