Paper commentary
The Faiss library
Faiss trades speed, memory and accuracy for vector search
- Problem Brute force search over large embedding sets gets too slow, because its cost grows with database size. No single index fits every memory and speed budget.
- Method Faiss is a toolkit of indexes that chains parts such as quantizers and inverted lists. Its IVF index clusters vectors and searches only a few clusters per query.
- Results In benchmarks, Faiss ran faster than SCANN on Deep10M batch search.
Why exact search stops scaling
Embedding search asks which stored vectors lie closest to a query vector. Given a set of database vectors and a query vector, the minimum can be found by iterating over all database vectors, which is brute force search. Faiss's IndexFlat implements this brute force search, and its cost grows with the database size. In low dimensions, branch-and-bound methods yield exact results, but in large dimensions they give no speedup over brute force search.
Brute force is not trivial to implement well, since it needs fast distance computation and a fast way to keep the k smallest distances. Faiss computes distances either directly or with a matrix multiplication decomposition when query vectors come in large batches. Some distance differences are too small to separate positive from negative items in an application, so exact ordering is not always needed.
In these cases, approximate nearest neighbor search (ANNS) becomes the interesting option.
With ANNS, the user accepts imperfect results, and that opens a new design space. The database can be preprocessed into an indexing structure, which the paper simply calls an index. Accuracy is measured as a discrepancy with the exact search results, which is an intermediate goal. The end-to-end accuracy also depends on how well the distance metric matches the item matching objective.
Recall at k is the fraction of the n ground-truth nearest neighbors found in the first k results.
Faiss is a library for ANNS, and it doesn't extract features or run as a service. Faiss is a toolbox of indexing methods, so the best index depends on the problem's constraints rather than on one fixed method. The paper shows a choice between a dozen index types for this reason. Its scope stays limited to algorithmic ANNS implementation, so Faiss isn't a database with write concurrency or sharding.
Three constraints and how they are measured
The evaluation treats speed, memory usage and accuracy as the active constraints. Accuracy always stays active, because returning random results would otherwise be sufficient. For ANNS, accuracy is measured as a discrepancy with the exact search results. The measure n-recall@k is the fraction of the n ground-truth nearest neighbors that appear in the first k search results.
When n equals k equals 1, the recall and the intersection measure coincide, and the recall is called accuracy.
For range search, the authors compare a result list from a threshold ε′ against the exact list from the threshold ε. They sweep ε′ from small to large, which traces a precision-recall curve whose area gives the mean average precision. For vector encoder-decoder pairs, the standard metric is the mean squared error between each vector and its reconstruction.
Here C is the encoder, D is the decoder, and the expectation runs over the vectors x. This measures how much a code distorts each vector, which is a different question from whether the right neighbours are returned.
Speed and accuracy trade against each other, so the evaluation keeps only the Pareto-optimal settings. Each hyperparameter moves speed and accuracy monotonically, so an earlier evaluation can rule out a new setting without running it. In the Deep100M example, the grid of 5808 configurations shrank to 398 experiments. Of those, 87 settings were Pareto-optimal.
This pruning keeps the search over settings affordable when the parameter grid is large.
How the components chain together
A fast index and a precise step combine as a two-stage search, where the fast index first returns a shortlist of results. The more accurate search then computes exact-quality results only for that shortlist, so the accurate index must allow efficient random access to database vectors. Some implementations keep the accurate vectors on a slower storage such as flash, for example in the DiskANN-based designs.
The polysemous codes method is implemented in IndexIVFPQ.
Before encoding, a vector can be transformed, and the transforms are chosen so that the distances stay meaningful. A random rotation spreads the variance over all the dimensions without changing the measured distances, and Faiss applies it with a RandomRotationMatrix. PCA helps because k-means quantizers are more likely to fall into local minima in high-dimensional spaces.
OPQ rotates the space so that each sub-vector of a product quantizer decorrelates, which makes PQ more accurate when variance sits on a few components.
Table 2 shows how L2, inner product and cosine can be converted into one another by preprocessing the query and database vectors. These conversions add one or two extra dimensions to the vectors, so the transformed vectors have a very anisotropic distribution. That anisotropy makes indexing harder, in particular with product or scalar quantization methods.
Section 4.2 describes the mitigations for this effect.
Compression codecs from k-means to additive quantizers
Compression turns each vector into a short integer code, and the codec sets the trade-off between code size and reconstruction error. A quantizer converts a continuous vector to an integer whose bit string has size ⌈log 2 K⌉, and the decoder can only rebuild K distinct vectors. Most Faiss indexes use asymmetric distance computation because they keep the query uncompressed, so no accuracy is lost on the query side.
The distance to a stored code C_i is then ∥q−D(C_i)∥, so only the database side gets decoded. Symmetric distance computation compresses the query too, which helps when queries also face a storage limit.
The k-means quantizer is the most accurate in principle, because its K centroids enumerate every vector it can reconstruct. Its memory and encoding cost grow exponentially with the code size, so it's impractical beyond roughly 3-byte codes, or 16M centroids. Scalar quantizers encode each dimension on its own, so they trade accuracy for speed.
The ScalarQuantizer supports SQ8, SQ6 and SQ4, and SQfp16 and SQbf16 use 16-bit floats.
A product quantizer splits the vector into M sub-vectors and quantizes each with its own k-means codebook. The code size is M times the bits needed for K codewords, so PQ6x10 means six sub-vectors of 10 bits each. Additive quantizers sum codewords from M codebooks, which reaches more reconstructions but makes optimal encoding NP-hard. The residual quantizer encodes stage by stage, picking the codeword that best reconstructs what is left.
It keeps a beam of candidate codes, which trades encoding time against accuracy. The local search quantizer starts from a rough encoding and refines it with random flips and iterated conditional modes under simulated annealing.
The authors order the quantizers by flexibility, so each level can represent everything the level before it can, and more. The extra flexibility costs training time and storage, which is why the product quantizer is the usual compromise. Compressed-domain search avoids decompressing stored codes, and additive quantizers need the norm term to compute L2 distances.
Which codec wins at which code size
The codec benchmark plots MSE against encoding time on Deep1M at 8 bytes per vector and on Contriever1M at 64 bytes per vector. Each plot compares the (P)RQ, (P)RQ with LUT, (P)LSQ and (P)LSQ on GPU variants, and lower values are better on both axes. The two regimes differ: Deep1M is low-dimensional, while Contriever1M is high-dimensional.
For short codes, the additive quantizers are the best options, so the additive family wins when the code budget is tight. LSQ is more accurate than RQ for small codes, but it doesn't scale well to longer codes.
For larger code sizes, the authors encode several sub-vectors independently with product-additive quantizers. That design splits the vector and encodes each part with an additive quantizer, so the codes are concatenated. The hierarchy places the product quantizer below the additive quantizer, so the additive one has more degrees of freedom and more training and storage cost.
Figure 3 covers Deep1M and Contriever1M across code sizes from 8 to 256 bytes and from 8 to 512 bytes, respectively. Encoding residuals is beneficial for shorter codes, while the contribution changes for larger codes. Residual encoding, controlled by the IndexIVF.by residual flag, is set to true by default.
Inverted files and graph indexes
IVF clusters the database with a coarse quantizer into K_IVF inverted lists, and a query visits only P_IVF of them. The coarse quantizer's K_IVF reproduction values are called centroids, and the vectors of each cluster are stored contiguously in the inverted lists. When P_IVF is fixed and the lists are balanced, the number of distance computations is K_IVF + P_IVF × N / K_IVF.
That count reaches a minimum when K_IVF = √(P_IVF N), which yields the usual recommendation to set P_IVF proportional to √N. The authors call this only a rough approximation, because P_IVF must grow with the number of lists to keep accuracy fixed. Unbalanced list sizes multiply the expected number of distance computations by the imbalance factor, and the coarse quantizer is often non-exhaustive, for example HNSW.
Figure 4 shows the optimal K_IVF for each database size on BigANN1B, with P_IVF set so that 1-recall@1 is 90%. On BigANN1B the optimal settings had K_IVF/√N roughly between 15 and 20. When K_IVF exceeds the optimal setting, the P_IVF needed to reach the target accuracy decreases as the dataset grows, because the nearest neighbour is more likely to fall in a nearby cluster.
Fitting t = t_0 N^α to the fastest index gives α between 0.29 and 0.45 for target recall@1 from 0.5 to 0.99. Because α stays below 0.5, search time grows more slowly than √N, though the exponent rises for higher accuracy targets.
Graph indexes navigate a neighbour graph instead of visiting clusters, and HNSW can add vectors on the fly. HNSW promotes some randomly selected vertices to hubs that are explored first. NSG is built from an input k-nearest-neighbour graph, replaces some short-range edges with longer-range edges, and starts searching from a fixed centre point.
Increasing the number of edges per node improves results until 64 edges, and performance deteriorates beyond that. NSG obtains better trade-offs in general, but building the k-NN graph with NN-descent takes 37 s for 1M vectors.
Graph-based indices suit indexes where memory usage isn't constrained, typically below 1M vectors. Beyond 10M vectors, construction time typically becomes the limiting factor for graph indexes.
Filtered search with bit signatures
Faiss offers a basic predicate for filtering, but metadata checks inside it are slow. Each check fetches a row of the sparse matrix Mmeta, which causes cache misses and an iterative binary search. Faiss can instead exploit the unused bits of the identifier to carry metadata. With N documents indexed by sequential ids, 63 minus ceil(log2(N)) bits stay unused.
Those bits suit enumerated types such as country codes, dates, and version numbers, but not more complex metadata.
The BigANN 2023 filtered track gives each query one or two terms from a fixed vocabulary. A database vector passes the filter only if it contains all the query terms. Each word j gets a 39-bit signature S[j], and a set of words gets the bitwise OR of its signatures. The query signature is sq = S[w1] OR S[w2], and each database signature si is the OR over its words.
If both query words are in a vector, every 1 bit of sq is also set in si, so not-si AND sq equals 0. A nonzero result therefore proves that the vector lacks at least one query word, which makes it a safe pre-filter. The test takes only a few machine instructions on data already in registers, so it runs before the full predicate.
The filter quality depends on the signatures, so the authors tried i.i.d. Bernoulli bits with varying p. At p of 0.1 the filter hit rate was 82.1%, the highest of the four settings tested. At p of 0.05 the hit rate was 75.4%, and at p of 0.5 it fell to 42.0%. The paper also contrasts vector-first search, which this filter serves, with metadata-first search.
Metadata-first search brute-forces a subset of vectors, which is slow but acceptable only if the subset is small.
Comparison with SCANN and Vamana
The Faiss authors compare their library with SCANN and Vamana using the ANN-benchmarks codebase. The training is performed on the database vectors, which differs slightly from the evaluation protocol originally used for this dataset. Throughput is measured in queries per second with 48 threads in batch mode. The figure plots 10-recall@10 on the horizontal axis against QPS on a logarithmic scale.
For Faiss, the authors use IVF with a Product Residual Quantizer optimized for SIMD. The index then re-ranks its results, as described in the refining section. Faiss runs faster than SCANN across the operating points. Faiss is about on par with Vamana, depending on the operating point. Choosing an index for a given setting still calls for benchmarking on the target data.
Limitations of the design and the reported results
The HNSW graph index doesn't support suppression or mutation, so deleting or changing its vectors is not handled. NSG goes further: it doesn't even support adding vectors incrementally. Supporting these operations would require heuristics that rebuild the graph when it is mutated. Those heuristics exist in HNSWlib and FreshDiskANN but are suboptimal for indexing.
NSG's graph is frozen after the first batch of vectors is added, so adding more vectors afterwards is hard.
Updates can hurt fitted structures when the data distribution shifts. If additions, removals or updates change the distribution significantly, the efficiency of techniques that fit the data degrades. This degradation affects IVF and PQ compression, and the authors suggest explicit updates of the index structure to address it. The IVF direct map, which supports id-based lookup, removal and update, is disabled by default.
It incurs a memory overhead and an add-time computation overhead.
The experiments use database and query vectors sampled from the same distribution. The authors don't address out-of-distribution data in this work. Vector search is an operation the authors treat as well-defined, so the limits above concern the index design rather than the query definition. Filtering by metadata with IDSelector callbacks is inefficient, because each check needs an indirection to the metadata table.
The ratio K_IVF over the square root of N depends on the data distribution, so the value of roughly 15 to 20 doesn't transfer directly. The scaling fit uses only the fastest index in Figure 4 on BigANN1B. Since the fit comes from a single dataset, it is an empirical rule rather than a general complexity guarantee.
Paper info
- Authors
- Matthijs Douze, Alexandr Guzhva, Chengqi Deng, Jeff Johnson, Gergely Szilvasy, Pierre-Emmanuel Mazaré, Maria Lomeli, Lucas Hosseini, Hervé Jégou
- Venue
- arXiv · Preprint
- First published
- 2024-1-16
- Added
- 2026-11-12
- Updated
- 2025-10-23
- Version
- v4
- arXiv
- 2401.08281
- Category
- cs.LG · cs.CV · cs.SE
- Original paper terms
- CC BY 4.0
- What we show
- Paper info and commentary
AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.
Quote from the paper
Matthijs Douze, Alexandr Guzhva, Chengqi Deng, Jeff Johnson, Gergely Szilvasy, Pierre-Emmanuel Mazaré, Maria Lomeli, Lucas Hosseini, Hervé Jégou (2024). The Faiss library. arXiv:2401.08281v4. https://arxiv.org/abs/2401.08281v4
BibTeX
@misc{douze2024faiss,
title = {{The Faiss library}},
author = {Matthijs Douze and Alexandr Guzhva and Chengqi Deng and Jeff Johnson and Gergely Szilvasy and Pierre-Emmanuel Mazaré and Maria Lomeli and Lucas Hosseini and Hervé Jégou},
year = {2024},
eprint = {2401.08281},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2401.08281v4}
}