文件 IndexIVF.h

namespace faiss

实现 k-means 聚类,具有许多变体。

版权所有 (c) Facebook, Inc. 及其附属公司。

此源代码根据 MIT 许可证获得许可,该许可证位于此源树的根目录中的 LICENSE 文件中。

IDSelector 旨在定义要处理的向量子集(用于删除或作为搜索的子集)

PQ4 SIMD 打包和累加函数

基本内核使用 bbs = nb * 2 * 16 个向量累加 nq 查询向量,并为此生成一个输出矩阵。 对于 nq * nb <= 4 很有用,否则寄存器溢出变得太大。

这些函数的实现分布在 3 个 cpp 文件中,以减少并行编译时间。 模板被显式实例化。

此文件包含用于计算距离的内核的回调。

在整个库中,向量以 float * 指针的形式提供。 当批量处理(添加/搜索)多个向量时,大多数算法都可以得到优化。 在这种情况下,它们作为矩阵传入。 当大小为 d 的 n 个向量作为 float * x 提供时,向量 i 的分量 j 是

x[ i * d + j ]

其中 0 <= i < n 且 0 <= j < d。 换句话说,矩阵始终是紧凑的。 指定矩阵的大小时,我们将其称为 n*d 矩阵,这意味着行优先存储。

I/O 函数可以读取/写入到文件名、文件句柄或抽象介质的对象。

读取函数返回的对象应使用 delete 取消分配。 这些对象中的所有引用都归对象所有。

反向列表的定义 + 一些实现该接口的常见类。

由于 IVF(反向文件)索引对于大规模用例非常有用,因此我们将与它们相关的一些函数分组到这个小库中。 大多数函数都适用于 IndexIVF 和嵌入在 IndexPreTransform 中的 IndexIVF。

此文件实现了 L2 和内积之外的额外度量标准

实现了一些神经网络层,主要用于支持 QINCo

定义一些将转换应用于一组向量的对象 通常这些是预处理步骤。

类型定义

using IVFSearchParameters = SearchParametersIVF

变量

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

封装了 IndexIVF 的量化器对象

此类隔离了独立于列表存储的字段(尤其是训练)

faiss::IndexIVFInterface, faiss::IndexShardsIVF 子类化

公共函数

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

训练量化器并调用 train_residual 来训练子量化器。

size_t coarse_code_size() const

计算存储列表 ID 所需的字节数

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()

公共成员

Index *quantizer = nullptr

将向量映射到倒排列表的量化器

size_t nlist = 0

倒排列表的数量

char quantizer_trains_alone = 0

>= 0: 在 k 均值训练中使用量化器作为索引 = 1: 只需将训练集传递给量化器的 train() = 2: 在平面索引上进行 k 均值训练 + 将质心添加到量化器

bool own_fields = false

对象是否拥有量化器

ClusteringParameters cp

用于覆盖默认的聚类参数

Index *clustering_index = nullptr

用于覆盖聚类期间使用的索引

struct SearchParametersIVF : public faiss::SearchParameters

faiss::IVFPQSearchParameters 继承

公共函数

inline virtual ~SearchParametersIVF()

公共成员

size_t nprobe = 1

查询时的探测数量

size_t max_codes = 0

访问以进行查询的最大代码数

SearchParameters *quantizer_params = nullptr
void *inverted_list_context = nullptr

传递给 InvertedLists 的上下文对象

struct IndexIVFInterface : public faiss::Level1Quantizer

faiss::IndexIVF, faiss::gpu::GpuIndexIVF 继承

公共函数

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

搜索一组向量,这些向量已通过IVF量化器预量化。 将相应的堆填充查询结果。 默认实现使用 InvertedListScanners 进行搜索。

参数:
  • n – 要查询的向量数

  • x – 查询向量,大小为 nx * d

  • assign – 粗量化索引,大小为 nx * nprobe

  • centroid_dis – 到粗糙质心的距离,大小为 nx * nprobe

  • distance – 输出距离,大小为 n * k

  • labels – 输出标签,大小为 n * k

  • store_pairs – 在结果的上/下 32 位中存储 inv list index + inv list offset,而不是 id(用于重新排序)。

  • params – 用于覆盖对象的搜索参数

  • stats – 要更新的搜索统计信息(可以为空)

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

范围搜索一组向量,这些向量已通过IVF量化器预量化。 填写 RangeSearchResults 结果。 默认实现使用 InvertedListScanners 进行搜索。

参数:
  • n – 要查询的向量数

  • x – 查询向量,大小为 nx * d

  • assign – 粗量化索引,大小为 nx * nprobe

  • centroid_dis – 到粗糙质心的距离,大小为 nx * nprobe

  • result – 输出结果

  • store_pairs – 在结果的上/下 32 位中存储 inv list index + inv list offset,而不是 id(用于重新排序)。

  • params – 用于覆盖对象的搜索参数

  • stats – 要更新的搜索统计信息(可以为空)

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

训练量化器并调用 train_residual 来训练子量化器。

size_t coarse_code_size() const

计算存储列表 ID 所需的字节数

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

公共成员

size_t nprobe = 1

查询时的探测数量

size_t max_codes = 0

访问以进行查询的最大代码数

Index *quantizer = nullptr

将向量映射到倒排列表的量化器

size_t nlist = 0

倒排列表的数量

char quantizer_trains_alone = 0

>= 0: 在 k 均值训练中使用量化器作为索引 = 1: 只需将训练集传递给量化器的 train() = 2: 在平面索引上进行 k 均值训练 + 将质心添加到量化器

bool own_fields = false

对象是否拥有量化器

ClusteringParameters cp

用于覆盖默认的聚类参数

Index *clustering_index = nullptr

用于覆盖聚类期间使用的索引

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

基于倒排文件 (IVF) 的 Index

在倒排文件中,量化器(一个 Index 实例)为要添加的每个向量提供一个量化索引。量化索引映射到一个列表(也称为倒排列表或posting list),其中存储了向量的id。

仅在训练后才需要倒排列表对象。如果未从外部设置,则会自动使用 ArrayInvertedLists

在搜索时,要搜索的向量也被量化,并且仅搜索与量化索引相对应的列表。这通过使其非穷举来加速搜索。可以使用多探针搜索来放宽此限制:选择几个(nprobe)量化索引,并访问多个倒排列表。

子类实现索引的后过滤,从而优化从查询到数据库向量的距离估计。

faiss::IndexIVFAdditiveQuantizerfaiss::IndexIVFFastScanfaiss::IndexIVFFlatfaiss::IndexIVFPQfaiss::IndexIVFScalarQuantizerfaiss::IndexIVFSpectralHash 继承

公共函数

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

倒排文件在输入端获取一个量化器(Index),它实现了将向量映射到列表标识符的函数。

virtual void reset() override

从数据库中删除所有元素。

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

训练量化器并调用 train_encoder 以训练子量化器。

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

使用 NULL id 调用 add_with_ids。

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

调用 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)

在向量分配已预定义的情况下,向量加法的实现。默认实现将代码提取传递给 encode_vectors。

参数:

precomputed_idx – 输入向量的量化索引(大小为 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

将一组向量编码为它们在倒排列表中出现的形式

参数:
  • list_nos – 量化器返回的倒排列表 ID(大小为 n)。 -1s 将被忽略。

  • codes – 输出代码,大小为 n * code_size

  • include_listno – 在代码中包含列表 ID(在这种情况下,将 ceil(log8(nlist)) 添加到代码大小)

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

添加使用独立编解码器计算的向量

参数:
  • codes – 要添加的代码,大小为 n * sa_code_size()

  • xids – 相应的 ID,大小为 n

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

训练向量的编码器。

如果 by_residual 为 true,则使用残差和相应的 assign 数组调用它,否则 x 是原始训练向量,assign=nullptr

virtual idx_t train_encoder_num_vectors() const

可以被子类重新定义以指示它们需要多少训练向量

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

搜索一组向量,这些向量已通过IVF量化器预量化。 将相应的堆填充查询结果。 默认实现使用 InvertedListScanners 进行搜索。

参数:
  • n – 要查询的向量数

  • x – 查询向量,大小为 nx * d

  • assign – 粗量化索引,大小为 nx * nprobe

  • centroid_dis – 到粗糙质心的距离,大小为 nx * nprobe

  • distance – 输出距离,大小为 n * k

  • labels – 输出标签,大小为 n * k

  • store_pairs – 在结果的上/下 32 位中存储 inv list index + inv list offset,而不是 id(用于重新排序)。

  • params – 用于覆盖对象的搜索参数

  • stats – 要更新的搜索统计信息(可以为空)

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

范围搜索一组向量,这些向量已通过IVF量化器预量化。 填写 RangeSearchResults 结果。 默认实现使用 InvertedListScanners 进行搜索。

参数:
  • n – 要查询的向量数

  • x – 查询向量,大小为 nx * d

  • assign – 粗量化索引,大小为 nx * nprobe

  • centroid_dis – 到粗糙质心的距离,大小为 nx * nprobe

  • result – 输出结果

  • store_pairs – 在结果的上/下 32 位中存储 inv list index + inv list offset,而不是 id(用于重新排序)。

  • params – 用于覆盖对象的搜索参数

  • stats – 要更新的搜索统计信息(可以为空)

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

分配向量,然后调用 search_preassign

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

查询索引中维度为 d 的 n 个向量。

返回所有距离 < radius 的向量。请注意,许多索引不实现 range_search(只有 k-NN 搜索是强制性的)。

参数:
  • n – 向量的数量

  • x – 要搜索的输入向量,大小为 n * d

  • radius – 搜索半径

  • result – 结果表

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

获取此索引的扫描器(store_pairs 表示忽略标签)

默认搜索实现使用它来计算距离

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

重建一个向量。仅当 maintain_direct_map 设置为 1 或 2 时才有效

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

更新向量的子集。

索引必须具有 direct_map

参数:
  • nv – 要更新的向量数

  • idx – 要更新的向量索引,大小为 nv

  • v – 新值的向量,大小为 nv*d

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

重建索引向量的子集。

覆盖默认实现以绕过 reconstruct(),这要求维护 direct_map。

参数:
  • i0 – 要重建的第一个向量

  • ni – 要重建的向量数

  • recons – 重建向量的输出数组,大小为 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

与搜索类似,但也会为搜索结果重建存储的向量(或有损编码情况下的近似值)。

覆盖默认实现,以避免维护 direct_map,而是通过 store_pairs 标志在 search_preassigned() 中获取代码偏移量。

参数:

recons – 重建的向量大小 (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

与搜索类似,但也会返回与搜索结果的存储向量相对应的代码。

参数:
  • codes – 代码 (n, k, code_size)

  • include_listno – 在代码中包含列表 ID(在这种情况下,将 ceil(log8(nlist)) 添加到代码大小)

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

根据(倒排列表索引 + 倒排列表偏移量)而不是 ID 来重建向量。

当不维护 direct_map 并且 inv list 偏移量由 search_preassigned() 计算且设置了 store_pairs 时,这对于重建非常有用。

virtual size_t remove_ids(const IDSelector &sel) override

数据集操作函数。

virtual void check_compatible_for_merge(const Index &otherIndex) const override

检查两个索引是否兼容(即,它们以相同的方式训练并且具有相同的参数)。否则抛出异常。

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

将条目从另一个数据集移动到 self。在输出时,other 为空。add_id 将添加到所有移动的 ID(对于顺序 ID,这将是 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

将条目索引的子集复制到另一个索引,请参阅 Invlists::copy_subset_to 了解 subset_type 的含义

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

id 是否已排序?

void make_direct_map(bool new_maintain_direct_map = true)

初始化一个直接映射

参数:

new_maintain_direct_map – 如果为 true,则创建一个直接映射,否则清除它

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

替换倒排列表,如果 own_invlists 为 true,则旧的倒排列表会被释放

virtual size_t sa_code_size() const override

生成的代码的大小(以字节为单位)

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

编码一组向量 sa_encode 将调用 encode_vector,并且 include_listno=true

参数:
  • n – 要编码的向量数量

  • x – 要编码的向量

  • bytes – 代码的输出数组

返回值:

写入代码的字节数

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

训练量化器并调用 train_residual 来训练子量化器。

size_t coarse_code_size() const

计算存储列表 ID 所需的字节数

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

公共成员

InvertedLists *invlists = nullptr

访问实际数据。

bool own_invlists = false
size_t code_size = 0

每个向量的代码大小(以字节为单位)

int parallel_mode = 0

并行模式确定如何使用 OpenMP 并行化查询

0 (默认): 在查询上拆分 1: 在倒排列表上并行化 2: 在两者上并行化 3: 以更精细的粒度在查询上拆分

PARALLEL_MODE_NO_HEAP_INIT: 二进制或与先前结合以防止堆被初始化和最终化

const int PARALLEL_MODE_NO_HEAP_INIT = 1024
DirectMap direct_map

可选的映射,将 id 映射回 invlist 条目。这启用了 reconstruct()

bool by_residual = true

invlist 中的代码是否编码了相对于质心的向量?

size_t nprobe = 1

查询时的探测数量

size_t max_codes = 0

访问以进行查询的最大代码数

Index *quantizer = nullptr

将向量映射到倒排列表的量化器

size_t nlist = 0

倒排列表的数量

char quantizer_trains_alone = 0

>= 0: 在 k 均值训练中使用量化器作为索引 = 1: 只需将训练集传递给量化器的 train() = 2: 在平面索引上进行 k 均值训练 + 将质心添加到量化器

bool own_fields = false

对象是否拥有量化器

ClusteringParameters cp

用于覆盖默认的聚类参数

Index *clustering_index = nullptr

用于覆盖聚类期间使用的索引

struct InvertedListScanner
#include <IndexIVF.h>

处理查询的对象。要扫描的倒排列表在外部提供。该对象有很多状态,但 distance_to_code 和 scan_codes 可以在多个线程中调用

公共函数

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

从现在开始,我们处理这个查询。

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

以下代码来自这个倒排列表

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

计算单个查询到代码的距离

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

扫描一组代码,计算与当前查询的距离,并在必要时更新结果堆。默认实现调用 distance_to_code。

参数:
  • n – 要扫描的代码数量

  • codes – 要扫描的代码(n * code_size)

  • ids – 相应的 ID(如果 store_pairs 则忽略)

  • distances – 堆距离(大小为 k)

  • labels – 堆标签(大小为 k)

  • k – 堆大小

返回值:

执行的堆更新次数

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

扫描一组代码,计算与当前查询的距离,如果距离小于半径,则更新结果

(默认实现会失败)

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

公共成员

idx_t list_no = -1

记住当前列表

bool keep_max = false

保留最大值而不是最小值

bool store_pairs

存储倒排列表中的位置,而不是标签

const IDSelector *sel

在此 ID 子集中搜索

size_t code_size = 0

在 scan_codes 的默认实现中使用

struct IndexIVFStats

公共函数

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

公共成员

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