mirror of
https://github.com/facebookresearch/faiss.git
synced 2026-10-12 02:13:36 +00:00
Summary: # Introduce early-stop controls for IVF search This PR adds optional early-stop controls to IVF search through `SearchParametersIVF`. IVF search looks in a sequence of buckets. Normally it keeps looking until it has checked all requested buckets. This PR adds a few ways to stop earlier: - stop after enough candidate vectors have been checked, - stop FastScan after enough buckets have been checked, - stop range search after several nearby buckets produce no results. All new fields default to disabled, so existing searches keep their current behavior unless callers opt in. ## New SearchParametersIVF fields Default values: | Field | Default | Effect | |---|---:|---| | `ensure_topk_full` | `false` | disabled; keep the existing hard `max_codes` behavior | | `max_lists_num` | `0` | disabled; FastScan is bounded only by `nprobe` | | `max_empty_result_buckets` | `0` | disabled; range search scans all requested probes | `ensure_topk_full` For k-NN search, `max_codes` limits how many candidate vectors are scanned. With `ensure_topk_full=false`, the search stops when the budget is reached. With `ensure_topk_full=true`, very small budgets become less aggressive: `max_codes` is treated as at least `k` post-filter scans. This helps when `max_codes < k`, or when an `IDSelector` filters out many candidates before a distance is computed. In the generic IVF path this is supported for `parallel_mode` 0 and 3. In FastScan k-NN it is supported by the per-query implementations 10 and 11. `max_lists_num` FastScan k-NN can also stop after visiting a limited number of inverted lists. `0` means disabled. With `ensure_topk_full`, this list budget is treated as at least `k` lists. This is only used by the FastScan per-query path (`search_implem_10`, also used for implementation 11). When FastScan is left on `implem = 0`, setting an early-stop k-NN option makes the dispatcher choose the per-query implementation automatically. If an incompatible FastScan implementation is selected explicitly, Faiss throws instead of ignoring the option. `max_empty_result_buckets` This is for range search. It stops probing a query after that many consecutive probed lists add no in-radius results. The counter resets as soon as a list adds at least one result. `0` means disabled. Setting this trades recall for less work: once nearby buckets repeatedly produce no hits, farther buckets are less likely to help. The generic IVF range path supports this in `parallel_mode == 0`. FastScan range search also supports it through implementation 10. With `implem = 0`, FastScan selects implementation 10 automatically when this option is set; explicit incompatible implementations throw. ## Selector-aware scan accounting This PR adds `InvertedListScannerStats`, returned by inverted-list scanner methods. It currently reports: - `scan_cnt`: number of distances actually computed, - `nheap_updates`: number of result updates. The important behavior change is that `IndexIVFStats::ndis` now uses `scan_cnt`. With an `IDSelector`, candidates rejected by the selector are not counted as computed distances. Without a selector, this matches the previous count because every scanned code reaches distance computation. This same post-filter count is used by `ensure_topk_full`, so a restrictive selector no longer consumes the search budget with candidates that were never eligible for the result heap. ## FastScan behavior FastScan k-NN now applies `max_codes`, `max_lists_num`, and `ensure_topk_full` in the per-query implementation. The code keeps separate counters per query, so multi-query batches have independent budgets. For `max_codes`, FastScan uses the result handler's scanned-row count. This means filtered-out rows do not consume the code budget. FastScan range search rejects k-NN-only options (`max_codes`, `max_lists_num`, and `ensure_topk_full`). It accepts `max_empty_result_buckets` when the selected implementation can preserve per-query probe order. ## API exposure The new fields are exposed through: - C++ `SearchParametersIVF`, - Python bindings, - the C API. The statistics is tracked via `InvertedListScanner::scan_codes(..., ResultHandler& handler)` call. In order to make it work inside `IndexIVF::search()`, it has been decided to transition it into this particular override of `InvertedListScanner::scan_codes()`. As a result, non-`ResultHandler` version of `scan_codes()` has been marked as non-virtual, so the custom `InvertedListScanner` implementations should override `ResultHandler`-based versions only. Another consequence is that `IndexIVFPQFastScanScanner` and `IndexIVFRaBitQFastScanScanner` accept only `HeapResultHandler` types of `ResultHandler`. These are the compromises that had to be made. ## Tests The tests cover: - default parameters preserving baseline k-NN and range-search results, - `ensure_topk_full` filling more result slots under tight budgets, - selector-aware `IndexIVFStats::ndis`, - range-search early exit and counter reset behavior, - unsupported parallel modes and FastScan implementations, - FastScan k-NN and range-search early-stop behavior, - Python and C API field exposure. Pull Request resolved: https://github.com/facebookresearch/faiss/pull/5160 Reviewed By: limqiying Differential Revision: D103044128 Pulled By: mnorris11 fbshipit-source-id: 80f1241c13ffc8173a3da0f2974fa9b6dd318890
386 lines
11 KiB
C++
386 lines
11 KiB
C++
/*
|
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*/
|
|
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
|
|
#include <memory>
|
|
#include <random>
|
|
#include <vector>
|
|
|
|
#include <gtest/gtest.h>
|
|
|
|
#include <faiss/AutoTune.h>
|
|
#include <faiss/IVFlib.h>
|
|
#include <faiss/IndexBinaryIVF.h>
|
|
#include <faiss/IndexIVF.h>
|
|
#include <faiss/clone_index.h>
|
|
#include <faiss/impl/AuxIndexStructures.h>
|
|
#include <faiss/impl/IDSelector.h>
|
|
#include <faiss/index_factory.h>
|
|
|
|
using namespace faiss;
|
|
|
|
namespace {
|
|
|
|
// dimension of the vectors to index
|
|
int d = 32;
|
|
|
|
// size of the database we plan to index
|
|
size_t nb = 1000;
|
|
|
|
// nb of queries
|
|
size_t nq = 200;
|
|
|
|
std::mt19937 rng;
|
|
|
|
std::vector<float> make_data(size_t n) {
|
|
std::vector<float> database(n * d);
|
|
std::uniform_real_distribution<> distrib;
|
|
for (size_t i = 0; i < n * d; i++) {
|
|
database[i] = distrib(rng);
|
|
}
|
|
return database;
|
|
}
|
|
|
|
std::unique_ptr<Index> make_index(
|
|
const char* index_type,
|
|
MetricType metric,
|
|
const std::vector<float>& x) {
|
|
assert(x.size() % d == 0);
|
|
idx_t local_nb = x.size() / d;
|
|
std::unique_ptr<Index> index(index_factory(d, index_type, metric));
|
|
index->train(local_nb, x.data());
|
|
index->add(local_nb, x.data());
|
|
return index;
|
|
}
|
|
|
|
std::vector<idx_t> search_index(Index* index, const float* xq) {
|
|
int k = 10;
|
|
std::vector<idx_t> I(k * nq);
|
|
std::vector<float> D(k * nq);
|
|
index->search(nq, xq, k, D.data(), I.data());
|
|
return I;
|
|
}
|
|
|
|
std::vector<idx_t> search_index_with_params(
|
|
Index* index,
|
|
const float* xq,
|
|
IVFSearchParameters* params) {
|
|
int k = 10;
|
|
std::vector<idx_t> I(k * nq);
|
|
std::vector<float> D(k * nq);
|
|
ivflib::search_with_parameters(
|
|
index, nq, xq, k, D.data(), I.data(), params);
|
|
return I;
|
|
}
|
|
|
|
/*************************************************************
|
|
* Test functions for a given index type
|
|
*************************************************************/
|
|
|
|
int test_params_override(const char* index_key, MetricType metric) {
|
|
std::vector<float> xb = make_data(nb); // database vectors
|
|
auto index = make_index(index_key, metric, xb);
|
|
// index->train(nb, xb.data());
|
|
// index->add(nb, xb.data());
|
|
std::vector<float> xq = make_data(nq);
|
|
ParameterSpace ps;
|
|
ps.set_index_parameter(index.get(), "nprobe", 2);
|
|
auto res2ref = search_index(index.get(), xq.data());
|
|
ps.set_index_parameter(index.get(), "nprobe", 9);
|
|
auto res9ref = search_index(index.get(), xq.data());
|
|
ps.set_index_parameter(index.get(), "nprobe", 1);
|
|
|
|
IVFSearchParameters params;
|
|
params.max_codes = 0;
|
|
params.nprobe = 2;
|
|
auto res2new = search_index_with_params(index.get(), xq.data(), ¶ms);
|
|
params.nprobe = 9;
|
|
auto res9new = search_index_with_params(index.get(), xq.data(), ¶ms);
|
|
|
|
if (res2ref != res2new) {
|
|
return 2;
|
|
}
|
|
|
|
if (res9ref != res9new) {
|
|
return 9;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
/*************************************************************
|
|
* Test subsets
|
|
*************************************************************/
|
|
|
|
/*************************************************************
|
|
* Test ensure_topk_full behavior
|
|
*************************************************************/
|
|
|
|
// With a tight max_codes budget the default search (ensure_topk_full=false)
|
|
// should truncate results, yielding -1 placeholders. With ensure_topk_full=true
|
|
// the same budget becomes soft: the probe loop keeps running until k raw
|
|
// candidates have been scanned, so placeholders disappear (data permitting).
|
|
int test_ensure_topk_full(const char* index_key, MetricType metric) {
|
|
std::vector<float> xb = make_data(nb);
|
|
auto index = make_index(index_key, metric, xb);
|
|
std::vector<float> xq = make_data(nq);
|
|
|
|
constexpr int k = 10;
|
|
// Budget: smaller than k codes per query. Guaranteed truncation when
|
|
// ensure_topk_full is false.
|
|
const size_t tight_budget = k / 2;
|
|
|
|
IVFSearchParameters p;
|
|
p.nprobe = 32;
|
|
p.max_codes = tight_budget;
|
|
p.ensure_topk_full = false;
|
|
auto res_tight = search_index_with_params(index.get(), xq.data(), &p);
|
|
|
|
p.ensure_topk_full = true;
|
|
auto res_full = search_index_with_params(index.get(), xq.data(), &p);
|
|
|
|
size_t miss_tight =
|
|
std::count(res_tight.begin(), res_tight.end(), (idx_t)-1);
|
|
size_t miss_full = std::count(res_full.begin(), res_full.end(), (idx_t)-1);
|
|
|
|
// ensure_topk_full=true must produce at least as many valid slots as
|
|
// ensure_topk_full=false; in practice it must strictly reduce -1 count
|
|
// given our tight budget.
|
|
if (miss_full > miss_tight) {
|
|
return 1;
|
|
}
|
|
if (miss_tight == 0) {
|
|
// Test assumption violated: budget should have caused truncation.
|
|
return 2;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// Regression test: when all three new fields are left at defaults the
|
|
// search behaves identically to a search with no params at all. This is the
|
|
// backward-compatibility guarantee for pre-existing baseline callers.
|
|
int test_defaults_preserve_baseline(const char* index_key, MetricType metric) {
|
|
std::vector<float> xb = make_data(nb);
|
|
auto index = make_index(index_key, metric, xb);
|
|
std::vector<float> xq = make_data(nq);
|
|
|
|
ParameterSpace ps;
|
|
ps.set_index_parameter(index.get(), "nprobe", 4);
|
|
auto res_no_params = search_index(index.get(), xq.data());
|
|
|
|
IVFSearchParameters p; // default-constructed: all new fields at 0/false
|
|
p.nprobe = 4;
|
|
auto res_default_params =
|
|
search_index_with_params(index.get(), xq.data(), &p);
|
|
|
|
if (res_no_params != res_default_params) {
|
|
return 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int test_selector(const char* index_key) {
|
|
std::vector<float> xb = make_data(nb); // database vectors
|
|
std::vector<float> xq = make_data(nq);
|
|
ParameterSpace ps;
|
|
|
|
std::vector<float> sub_xb;
|
|
std::vector<idx_t> kept;
|
|
for (size_t i = 0; i < nb; i++) {
|
|
if (i % 10 == 2) {
|
|
kept.push_back(i);
|
|
sub_xb.insert(
|
|
sub_xb.end(), xb.begin() + i * d, xb.begin() + (i + 1) * d);
|
|
}
|
|
}
|
|
|
|
// full index
|
|
auto index = make_index(index_key, METRIC_L2, xb);
|
|
ps.set_index_parameter(index.get(), "nprobe", 3);
|
|
|
|
// restricted index
|
|
std::unique_ptr<Index> sub_index(clone_index(index.get()));
|
|
sub_index->reset();
|
|
sub_index->add_with_ids(kept.size(), sub_xb.data(), kept.data());
|
|
|
|
auto ref_result = search_index(sub_index.get(), xq.data());
|
|
|
|
IVFSearchParameters params;
|
|
params.max_codes = 0;
|
|
params.nprobe = 3;
|
|
IDSelectorBatch sel(kept.size(), kept.data());
|
|
params.sel = &sel;
|
|
auto new_result = search_index_with_params(index.get(), xq.data(), ¶ms);
|
|
|
|
if (ref_result != new_result) {
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
/*************************************************************
|
|
* Test entry points
|
|
*************************************************************/
|
|
|
|
TEST(TPO, IVFFlat) {
|
|
int err1 = test_params_override("IVF32,Flat", METRIC_L2);
|
|
EXPECT_EQ(err1, 0);
|
|
int err2 = test_params_override("IVF32,Flat", METRIC_INNER_PRODUCT);
|
|
EXPECT_EQ(err2, 0);
|
|
}
|
|
|
|
TEST(TPO, IVFPQ) {
|
|
int err1 = test_params_override("IVF32,PQ8np", METRIC_L2);
|
|
EXPECT_EQ(err1, 0);
|
|
int err2 = test_params_override("IVF32,PQ8np", METRIC_INNER_PRODUCT);
|
|
EXPECT_EQ(err2, 0);
|
|
}
|
|
|
|
TEST(TPO, IVFSQ) {
|
|
int err1 = test_params_override("IVF32,SQ8", METRIC_L2);
|
|
EXPECT_EQ(err1, 0);
|
|
int err2 = test_params_override("IVF32,SQ8", METRIC_INNER_PRODUCT);
|
|
EXPECT_EQ(err2, 0);
|
|
}
|
|
|
|
TEST(TPO, IVFFlatPP) {
|
|
int err1 = test_params_override("PCA16,IVF32,SQ8", METRIC_L2);
|
|
EXPECT_EQ(err1, 0);
|
|
int err2 = test_params_override("PCA16,IVF32,SQ8", METRIC_INNER_PRODUCT);
|
|
EXPECT_EQ(err2, 0);
|
|
}
|
|
|
|
TEST(TPOEnsureTopK, IVFFlat) {
|
|
EXPECT_EQ(test_ensure_topk_full("IVF32,Flat", METRIC_L2), 0);
|
|
EXPECT_EQ(test_ensure_topk_full("IVF32,Flat", METRIC_INNER_PRODUCT), 0);
|
|
}
|
|
|
|
TEST(TPOEnsureTopK, IVFPQ) {
|
|
EXPECT_EQ(test_ensure_topk_full("IVF32,PQ8np", METRIC_L2), 0);
|
|
EXPECT_EQ(test_ensure_topk_full("IVF32,PQ8np", METRIC_INNER_PRODUCT), 0);
|
|
}
|
|
|
|
TEST(TPOEnsureTopK, IVFSQ) {
|
|
EXPECT_EQ(test_ensure_topk_full("IVF32,SQ8", METRIC_L2), 0);
|
|
EXPECT_EQ(test_ensure_topk_full("IVF32,SQ8", METRIC_INNER_PRODUCT), 0);
|
|
}
|
|
|
|
TEST(TPODefaults, IVFFlat) {
|
|
EXPECT_EQ(test_defaults_preserve_baseline("IVF32,Flat", METRIC_L2), 0);
|
|
}
|
|
|
|
TEST(TPODefaults, IVFPQ) {
|
|
EXPECT_EQ(test_defaults_preserve_baseline("IVF32,PQ8np", METRIC_L2), 0);
|
|
}
|
|
|
|
TEST(TPODefaults, IVFSQ) {
|
|
EXPECT_EQ(test_defaults_preserve_baseline("IVF32,SQ8", METRIC_L2), 0);
|
|
}
|
|
|
|
TEST(TSEL, IVFFlat) {
|
|
int err = test_selector("PCA16,IVF32,Flat");
|
|
EXPECT_EQ(err, 0);
|
|
}
|
|
|
|
TEST(TSEL, IVFFPQ) {
|
|
int err = test_selector("PCA16,IVF32,PQ4x8np");
|
|
EXPECT_EQ(err, 0);
|
|
}
|
|
|
|
TEST(TSEL, IVFFSQ) {
|
|
int err = test_selector("PCA16,IVF32,SQ8");
|
|
EXPECT_EQ(err, 0);
|
|
}
|
|
|
|
/*************************************************************
|
|
* Same for binary indexes
|
|
*************************************************************/
|
|
|
|
std::vector<uint8_t> make_data_binary(size_t n) {
|
|
std::vector<uint8_t> database(n * d / 8);
|
|
std::uniform_int_distribution<> distrib;
|
|
for (size_t i = 0; i < n * d / 8; i++) {
|
|
database[i] = distrib(rng);
|
|
}
|
|
return database;
|
|
}
|
|
|
|
std::unique_ptr<IndexBinaryIVF> make_index(
|
|
const char* index_type,
|
|
const std::vector<uint8_t>& x) {
|
|
auto index = std::unique_ptr<IndexBinaryIVF>(
|
|
dynamic_cast<IndexBinaryIVF*>(index_binary_factory(d, index_type)));
|
|
index->train(nb, x.data());
|
|
index->add(nb, x.data());
|
|
return index;
|
|
}
|
|
|
|
std::vector<idx_t> search_index(IndexBinaryIVF* index, const uint8_t* xq) {
|
|
int k = 10;
|
|
std::vector<idx_t> I(k * nq);
|
|
std::vector<int32_t> D(k * nq);
|
|
index->search(nq, xq, k, D.data(), I.data());
|
|
return I;
|
|
}
|
|
|
|
std::vector<idx_t> search_index_with_params(
|
|
IndexBinaryIVF* index,
|
|
const uint8_t* xq,
|
|
IVFSearchParameters* params) {
|
|
int k = 10;
|
|
std::vector<idx_t> I(k * nq);
|
|
std::vector<int32_t> D(k * nq);
|
|
|
|
std::vector<idx_t> Iq(params->nprobe * nq);
|
|
std::vector<int32_t> Dq(params->nprobe * nq);
|
|
|
|
index->quantizer->search(nq, xq, params->nprobe, Dq.data(), Iq.data());
|
|
index->search_preassigned(
|
|
nq, xq, k, Iq.data(), Dq.data(), D.data(), I.data(), false, params);
|
|
return I;
|
|
}
|
|
|
|
int test_params_override_binary(const char* index_key) {
|
|
std::vector<uint8_t> xb = make_data_binary(nb); // database vectors
|
|
auto index = make_index(index_key, xb);
|
|
index->train(nb, xb.data());
|
|
index->add(nb, xb.data());
|
|
std::vector<uint8_t> xq = make_data_binary(nq);
|
|
index->nprobe = 2;
|
|
auto res2ref = search_index(index.get(), xq.data());
|
|
index->nprobe = 9;
|
|
auto res9ref = search_index(index.get(), xq.data());
|
|
index->nprobe = 1;
|
|
|
|
IVFSearchParameters params;
|
|
params.max_codes = 0;
|
|
params.nprobe = 2;
|
|
auto res2new = search_index_with_params(index.get(), xq.data(), ¶ms);
|
|
params.nprobe = 9;
|
|
auto res9new = search_index_with_params(index.get(), xq.data(), ¶ms);
|
|
|
|
if (res2ref != res2new) {
|
|
return 2;
|
|
}
|
|
|
|
if (res9ref != res9new) {
|
|
return 9;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
TEST(TPOB, IVF) {
|
|
int err1 = test_params_override_binary("BIVF32");
|
|
EXPECT_EQ(err1, 0);
|
|
}
|