File IndexIVF.h

namespace faiss

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. Implementation of k-means clustering with many variants.

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. IDSelector is intended to define a subset of vectors to handle (for removal or as subset to search)

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. PQ4 SIMD packing and accumulation functions

The basic kernel accumulates nq query vectors with bbs = nb * 2 * 16 vectors and produces an output matrix for that. It is interesting for nq * nb <= 4, otherwise register spilling becomes too large.

The implementation of these functions is spread over 3 cpp files to reduce parallel compile times. Templates are instantiated explicitly.

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. This file contains callbacks for kernels that compute distances.

Throughout the library, vectors are provided as float * pointers. Most algorithms can be optimized when several vectors are processed (added/searched) together in a batch. In this case, they are passed in as a matrix. When n vectors of size d are provided as float * x, component j of vector i is

x[ i * d + j ]

where 0 <= i < n and 0 <= j < d. In other words, matrices are always compact. When specifying the size of the matrix, we call it an n*d matrix, which implies a row-major storage.

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. I/O functions can read/write to a filename, a file handle or to an object that abstracts the medium.

The read functions return objects that should be deallocated with delete. All references within these objectes are owned by the object.

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. Definition of inverted lists + a few common classes that implement the interface.

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. Since IVF (inverted file) indexes are of so much use for large-scale use cases, we group a few functions related to them in this small library. Most functions work both on IndexIVFs and IndexIVFs embedded within an IndexPreTransform.

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. In this file are the implementations of extra metrics beyond L2 and inner product

Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. Defines a few objects that apply transformations to a set of vectors Often these are pre-processing steps.

Typedefs

using IVFSearchParameters = SearchParametersIVF

Variables

FAISS_API bool check_compatible_for_merge_expensive_check
FAISS_API IndexIVFStats indexIVF_stats
struct Level1Quantizer
#include <IndexIVF.h>

Encapsulates a quantizer object for the IndexIVF

The class isolates the fields that are independent of the storage of the lists (especially training)

Subclassed by faiss::IndexIVFInterface, faiss::IndexShardsIVF

Public Functions

void train_q1(size_t n, const float *x, bool verbose, MetricType metric_type)

Trains the quantizer and calls train_residual to train sub-quantizers.

size_t coarse_code_size() const

compute the number of bytes required to store list ids

void encode_listno(idx_t list_no, uint8_t *code) const
idx_t decode_listno(const uint8_t *code) const
Level1Quantizer(Index *quantizer, size_t nlist)
Level1Quantizer()
~Level1Quantizer()

Public Members

Index *quantizer = nullptr

quantizer that maps vectors to inverted lists

size_t nlist = 0

number of inverted lists

char quantizer_trains_alone = 0

= 0: use the quantizer as index in a kmeans training = 1: just pass on the training set to the train() of the quantizer = 2: kmeans training on a flat index + add the centroids to the quantizer

bool own_fields = false

whether object owns the quantizer

ClusteringParameters cp

to override default clustering params

Index *clustering_index = nullptr

to override index used during clustering

struct SearchParametersIVF : public faiss::SearchParameters

Subclassed by faiss::IVFPQSearchParameters

Public Functions

inline virtual ~SearchParametersIVF()

Public Members

size_t nprobe = 1

number of probes at query time

size_t max_codes = 0

max nb of codes to visit to do a query

SearchParameters *quantizer_params = nullptr
void *inverted_list_context = nullptr

context object to pass to InvertedLists

struct IndexIVFInterface : public faiss::Level1Quantizer

Subclassed by faiss::IndexIVF, faiss::gpu::GpuIndexIVF

Public Functions

inline explicit IndexIVFInterface(Index *quantizer = nullptr, size_t nlist = 0)
virtual void search_preassigned(idx_t n, const float *x, idx_t k, const idx_t *assign, const float *centroid_dis, float *distances, idx_t *labels, bool store_pairs, const IVFSearchParameters *params = nullptr, IndexIVFStats *stats = nullptr) const = 0

search a set of vectors, that are pre-quantized by the IVF quantizer. Fill in the corresponding heaps with the query results. The default implementation uses InvertedListScanners to do the search.

Parameters:
  • n – nb of vectors to query

  • x – query vectors, size nx * d

  • assign – coarse quantization indices, size nx * nprobe

  • centroid_dis – distances to coarse centroids, size nx * nprobe

  • distance – output distances, size n * k

  • labels – output labels, size n * k

  • store_pairs – store inv list index + inv list offset instead in upper/lower 32 bit of result, instead of ids (used for reranking).

  • params – used to override the object’s search parameters

  • stats – search stats to be updated (can be null)

virtual void range_search_preassigned(idx_t nx, const float *x, float radius, const idx_t *keys, const float *coarse_dis, RangeSearchResult *result, bool store_pairs = false, const IVFSearchParameters *params = nullptr, IndexIVFStats *stats = nullptr) const = 0

Range search a set of vectors, that are pre-quantized by the IVF quantizer. Fill in the RangeSearchResults results. The default implementation uses InvertedListScanners to do the search.

Parameters:
  • n – nb of vectors to query

  • x – query vectors, size nx * d

  • assign – coarse quantization indices, size nx * nprobe

  • centroid_dis – distances to coarse centroids, size nx * nprobe

  • result – Output results

  • store_pairs – store inv list index + inv list offset instead in upper/lower 32 bit of result, instead of ids (used for reranking).

  • params – used to override the object’s search parameters

  • stats – search stats to be updated (can be null)

inline virtual ~IndexIVFInterface()
void train_q1(size_t n, const float *x, bool verbose, MetricType metric_type)

Trains the quantizer and calls train_residual to train sub-quantizers.

size_t coarse_code_size() const

compute the number of bytes required to store list ids

void encode_listno(idx_t list_no, uint8_t *code) const
idx_t decode_listno(const uint8_t *code) const

Public Members

size_t nprobe = 1

number of probes at query time

size_t max_codes = 0

max nb of codes to visit to do a query

Index *quantizer = nullptr

quantizer that maps vectors to inverted lists

size_t nlist = 0

number of inverted lists

char quantizer_trains_alone = 0

= 0: use the quantizer as index in a kmeans training = 1: just pass on the training set to the train() of the quantizer = 2: kmeans training on a flat index + add the centroids to the quantizer

bool own_fields = false

whether object owns the quantizer

ClusteringParameters cp

to override default clustering params

Index *clustering_index = nullptr

to override index used during clustering

struct IndexIVF : public faiss::Index, public faiss::IndexIVFInterface
#include <IndexIVF.h>

Index based on a inverted file (IVF)

In the inverted file, the quantizer (an Index instance) provides a quantization index for each vector to be added. The quantization index maps to a list (aka inverted list or posting list), where the id of the vector is stored.

The inverted list object is required only after trainng. If none is set externally, an ArrayInvertedLists is used automatically.

At search time, the vector to be searched is also quantized, and only the list corresponding to the quantization index is searched. This speeds up the search by making it non-exhaustive. This can be relaxed using multi-probe search: a few (nprobe) quantization indices are selected and several inverted lists are visited.

Sub-classes implement a post-filtering of the index that refines the distance estimation from the query to databse vectors.

Subclassed by faiss::IndexIVFAdditiveQuantizer, faiss::IndexIVFFastScan, faiss::IndexIVFFlat, faiss::IndexIVFPQ, faiss::IndexIVFScalarQuantizer, faiss::IndexIVFSpectralHash

Public Functions

IndexIVF(Index *quantizer, size_t d, size_t nlist, size_t code_size, MetricType metric = METRIC_L2)

The Inverted file takes a quantizer (an Index) on input, which implements the function mapping a vector to a list identifier.

virtual void reset() override

removes all elements from the database.

virtual void train(idx_t n, const float *x) override

Trains the quantizer and calls train_encoder to train sub-quantizers.

virtual void add(idx_t n, const float *x) override

Calls add_with_ids with NULL ids.

virtual void add_with_ids(idx_t n, const float *x, const idx_t *xids) override

default implementation that calls encode_vectors

virtual void add_core(idx_t n, const float *x, const idx_t *xids, const idx_t *precomputed_idx, void *inverted_list_context = nullptr)

Implementation of vector addition where the vector assignments are predefined. The default implementation hands over the code extraction to encode_vectors.

Parameters:

precomputed_idx – quantization indices for the input vectors (size n)

virtual void encode_vectors(idx_t n, const float *x, const idx_t *list_nos, uint8_t *codes, bool include_listno = false) const = 0

Encodes a set of vectors as they would appear in the inverted lists

Parameters:
  • list_nos – inverted list ids as returned by the quantizer (size n). -1s are ignored.

  • codes – output codes, size n * code_size

  • include_listno – include the list ids in the code (in this case add ceil(log8(nlist)) to the code size)

void add_sa_codes(idx_t n, const uint8_t *codes, const idx_t *xids)

Add vectors that are computed with the standalone codec

Parameters:
  • codes – codes to add size n * sa_code_size()

  • xids – corresponding ids, size n

virtual void train_encoder(idx_t n, const float *x, const idx_t *assign)

Train the encoder for the vectors.

If by_residual then it is called with residuals and corresponding assign array, otherwise x is the raw training vectors and assign=nullptr

virtual idx_t train_encoder_num_vectors() const

can be redefined by subclasses to indicate how many training vectors they need

virtual void search_preassigned(idx_t n, const float *x, idx_t k, const idx_t *assign, const float *centroid_dis, float *distances, idx_t *labels, bool store_pairs, const IVFSearchParameters *params = nullptr, IndexIVFStats *stats = nullptr) const override

search a set of vectors, that are pre-quantized by the IVF quantizer. Fill in the corresponding heaps with the query results. The default implementation uses InvertedListScanners to do the search.

Parameters:
  • n – nb of vectors to query

  • x – query vectors, size nx * d

  • assign – coarse quantization indices, size nx * nprobe

  • centroid_dis – distances to coarse centroids, size nx * nprobe

  • distance – output distances, size n * k

  • labels – output labels, size n * k

  • store_pairs – store inv list index + inv list offset instead in upper/lower 32 bit of result, instead of ids (used for reranking).

  • params – used to override the object’s search parameters

  • stats – search stats to be updated (can be null)

virtual void range_search_preassigned(idx_t nx, const float *x, float radius, const idx_t *keys, const float *coarse_dis, RangeSearchResult *result, bool store_pairs = false, const IVFSearchParameters *params = nullptr, IndexIVFStats *stats = nullptr) const override

Range search a set of vectors, that are pre-quantized by the IVF quantizer. Fill in the RangeSearchResults results. The default implementation uses InvertedListScanners to do the search.

Parameters:
  • n – nb of vectors to query

  • x – query vectors, size nx * d

  • assign – coarse quantization indices, size nx * nprobe

  • centroid_dis – distances to coarse centroids, size nx * nprobe

  • result – Output results

  • store_pairs – store inv list index + inv list offset instead in upper/lower 32 bit of result, instead of ids (used for reranking).

  • params – used to override the object’s search parameters

  • stats – search stats to be updated (can be null)

virtual void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels, const SearchParameters *params = nullptr) const override

assign the vectors, then call search_preassign

virtual void range_search(idx_t n, const float *x, float radius, RangeSearchResult *result, const SearchParameters *params = nullptr) const override

query n vectors of dimension d to the index.

return all vectors with distance < radius. Note that many indexes do not implement the range_search (only the k-NN search is mandatory).

Parameters:
  • n – number of vectors

  • x – input vectors to search, size n * d

  • radius – search radius

  • result – result table

virtual InvertedListScanner *get_InvertedListScanner(bool store_pairs = false, const IDSelector *sel = nullptr) const

Get a scanner for this index (store_pairs means ignore labels)

The default search implementation uses this to compute the distances

virtual void reconstruct(idx_t key, float *recons) const override

reconstruct a vector. Works only if maintain_direct_map is set to 1 or 2

virtual void update_vectors(int nv, const idx_t *idx, const float *v)

Update a subset of vectors.

The index must have a direct_map

Parameters:
  • nv – nb of vectors to update

  • idx – vector indices to update, size nv

  • v – vectors of new values, size nv*d

virtual void reconstruct_n(idx_t i0, idx_t ni, float *recons) const override

Reconstruct a subset of the indexed vectors.

Overrides default implementation to bypass reconstruct() which requires direct_map to be maintained.

Parameters:
  • i0 – first vector to reconstruct

  • ni – nb of vectors to reconstruct

  • recons – output array of reconstructed vectors, size ni * d

virtual void search_and_reconstruct(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels, float *recons, const SearchParameters *params = nullptr) const override

Similar to search, but also reconstructs the stored vectors (or an approximation in the case of lossy coding) for the search results.

Overrides default implementation to avoid having to maintain direct_map and instead fetch the code offsets through the store_pairs flag in search_preassigned().

Parameters:

recons – reconstructed vectors size (n, k, d)

void search_and_return_codes(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels, uint8_t *recons, bool include_listno = false, const SearchParameters *params = nullptr) const

Similar to search, but also returns the codes corresponding to the stored vectors for the search results.

Parameters:
  • codes – codes (n, k, code_size)

  • include_listno – include the list ids in the code (in this case add ceil(log8(nlist)) to the code size)

virtual void reconstruct_from_offset(int64_t list_no, int64_t offset, float *recons) const

Reconstruct a vector given the location in terms of (inv list index + inv list offset) instead of the id.

Useful for reconstructing when the direct_map is not maintained and the inv list offset is computed by search_preassigned() with store_pairs set.

virtual size_t remove_ids(const IDSelector &sel) override

Dataset manipulation functions.

virtual void check_compatible_for_merge(const Index &otherIndex) const override

check that the two indexes are compatible (ie, they are trained in the same way and have the same parameters). Otherwise throw.

virtual void merge_from(Index &otherIndex, idx_t add_id) override

moves the entries from another dataset to self. On output, other is empty. add_id is added to all moved ids (for sequential ids, this would be this->ntotal)

virtual CodePacker *get_CodePacker() const
virtual void copy_subset_to(IndexIVF &other, InvertedLists::subset_type_t subset_type, idx_t a1, idx_t a2) const

copy a subset of the entries index to the other index see Invlists::copy_subset_to for the meaning of subset_type

~IndexIVF() override
inline size_t get_list_size(size_t list_no) const
bool check_ids_sorted() const

are the ids sorted?

void make_direct_map(bool new_maintain_direct_map = true)

initialize a direct map

Parameters:

new_maintain_direct_map – if true, create a direct map, else clear it

void set_direct_map_type(DirectMap::Type type)
void replace_invlists(InvertedLists *il, bool own = false)

replace the inverted lists, old one is deallocated if own_invlists

virtual size_t sa_code_size() const override

size of the produced codes in bytes

virtual void sa_encode(idx_t n, const float *x, uint8_t *bytes) const override

encode a set of vectors sa_encode will call encode_vector with include_listno=true

Parameters:
  • n – nb of vectors to encode

  • x – the vectors to encode

  • bytes – output array for the codes

Returns:

nb of bytes written to codes

IndexIVF()
void train_q1(size_t n, const float *x, bool verbose, MetricType metric_type)

Trains the quantizer and calls train_residual to train sub-quantizers.

size_t coarse_code_size() const

compute the number of bytes required to store list ids

void encode_listno(idx_t list_no, uint8_t *code) const
idx_t decode_listno(const uint8_t *code) const

Public Members

InvertedLists *invlists = nullptr

Access to the actual data.

bool own_invlists = false
size_t code_size = 0

code size per vector in bytes

int parallel_mode = 0

Parallel mode determines how queries are parallelized with OpenMP

0 (default): split over queries 1: parallelize over inverted lists 2: parallelize over both 3: split over queries with a finer granularity

PARALLEL_MODE_NO_HEAP_INIT: binary or with the previous to prevent the heap to be initialized and finalized

const int PARALLEL_MODE_NO_HEAP_INIT = 1024
DirectMap direct_map

optional map that maps back ids to invlist entries. This enables reconstruct()

bool by_residual = true

do the codes in the invlists encode the vectors relative to the centroids?

size_t nprobe = 1

number of probes at query time

size_t max_codes = 0

max nb of codes to visit to do a query

Index *quantizer = nullptr

quantizer that maps vectors to inverted lists

size_t nlist = 0

number of inverted lists

char quantizer_trains_alone = 0

= 0: use the quantizer as index in a kmeans training = 1: just pass on the training set to the train() of the quantizer = 2: kmeans training on a flat index + add the centroids to the quantizer

bool own_fields = false

whether object owns the quantizer

ClusteringParameters cp

to override default clustering params

Index *clustering_index = nullptr

to override index used during clustering

struct InvertedListScanner
#include <IndexIVF.h>

Object that handles a query. The inverted lists to scan are provided externally. The object has a lot of state, but distance_to_code and scan_codes can be called in multiple threads

Public Functions

inline InvertedListScanner(bool store_pairs = false, const IDSelector *sel = nullptr)
virtual void set_query(const float *query_vector) = 0

from now on we handle this query.

virtual void set_list(idx_t list_no, float coarse_dis) = 0

following codes come from this inverted list

virtual float distance_to_code(const uint8_t *code) const = 0

compute a single query-to-code distance

virtual size_t scan_codes(size_t n, const uint8_t *codes, const idx_t *ids, float *distances, idx_t *labels, size_t k) const

scan a set of codes, compute distances to current query and update heap of results if necessary. Default implemetation calls distance_to_code.

Parameters:
  • n – number of codes to scan

  • codes – codes to scan (n * code_size)

  • ids – corresponding ids (ignored if store_pairs)

  • distances – heap distances (size k)

  • labels – heap labels (size k)

  • k – heap size

Returns:

number of heap updates performed

virtual size_t iterate_codes(InvertedListsIterator *iterator, float *distances, idx_t *labels, size_t k, size_t &list_size) const
virtual void scan_codes_range(size_t n, const uint8_t *codes, const idx_t *ids, float radius, RangeQueryResult &result) const

scan a set of codes, compute distances to current query and update results if distances are below radius

(default implementation fails)

virtual void iterate_codes_range(InvertedListsIterator *iterator, float radius, RangeQueryResult &result, size_t &list_size) const
inline virtual ~InvertedListScanner()

Public Members

idx_t list_no = -1

remember current list

bool keep_max = false

keep maximum instead of minimum

bool store_pairs

store positions in invlists rather than labels

const IDSelector *sel

search in this subset of ids

size_t code_size = 0

used in default implementation of scan_codes

struct IndexIVFStats

Public Functions

inline IndexIVFStats()
void reset()
void add(const IndexIVFStats &other)

Public Members

size_t nq
size_t nlist
size_t ndis
size_t nheap_updates
double quantization_time
double search_time