Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions include/svs/concurrent/dynamic_index.h
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,10 @@
[&](const auto is, uint64_t /*tid*/) {
for (auto i : is) {
for (size_t j = 0, jmax = getsize<1>(ids); j < jmax; ++j) {
// Skip the invalid-neighbor marker written by a cancelled search.
if (ids.at(i, j) == no_external_id) {
continue;
}
auto internal = lib::narrow_cast<Idx>(ids.at(i, j));
ids.at(i, j) = unsafe_translate_internal_id(internal);
}
Expand Down Expand Up @@ -948,10 +952,13 @@
scratch.scratch,
query,
greedy_search_closure(scratch.prefetch_parameters, cancel),
*this
*this,
cancel
);
}

// On cancel, see ``VamanaIndex::search``. Here a marker can also appear mid-row (an
// ID consolidated concurrently translates to the marker ID).
template <typename I, data::ImmutableMemoryDataset Queries>
void search(
QueryResultView<I> results,
Expand Down Expand Up @@ -997,13 +1004,10 @@
);
}

// Check if request to cancel the search
if (cancel()) {
return;
}

// After the search procedure, the indices in `results` are internal.
// Perform one more pass to convert these to external ids.
// This also runs when the search was cancelled so that the partial results are
// external; slots holding the invalid-neighbor marker are left untouched.
translate_to_external(results.indices());
}

Expand Down Expand Up @@ -1092,7 +1096,7 @@
/// find and fill these empty entries when adding new points.
///
template <data::ImmutableMemoryDataset Points, class ExternalIds>
std::vector<size_t> add_points(

Check notice on line 1099 in include/svs/concurrent/dynamic_index.h

View check run for this annotation

codefactor.io / CodeFactor

Complex Method

Complexity is 25 (lines 1099-1297).
const Points& points, const ExternalIds& external_ids, bool reuse_empty = false
) {
const size_t num_points = points.size();
Expand Down
18 changes: 12 additions & 6 deletions include/svs/index/vamana/dynamic_index.h
Original file line number Diff line number Diff line change
Expand Up @@ -630,12 +630,18 @@ class MutableVamanaIndex {
requires(std::tuple_size_v<Dims> == 2)
void translate_to_external(DenseArray<size_t, Dims, Base>& ids) {
// N.B.: lib::narrow_cast should be valid because the origin of the IDs is internal.
constexpr size_t invalid_id =
type_traits::sentinel_v<Neighbor<size_t>, std::less<>>.id();
threads::parallel_for(
threadpool_,
threads::StaticPartition{getsize<0>(ids)},
[&](const auto is, uint64_t /*tid*/) {
for (auto i : is) {
for (size_t j = 0, jmax = getsize<1>(ids); j < jmax; ++j) {
// Skip the invalid-neighbor marker written by a cancelled search.
if (ids.at(i, j) == invalid_id) {
continue;
}
auto internal = lib::narrow_cast<Idx>(ids.at(i, j));
ids.at(i, j) = translate_internal_id(internal);
}
Expand Down Expand Up @@ -718,10 +724,13 @@ class MutableVamanaIndex {
scratch.scratch,
query,
greedy_search_closure(scratch.prefetch_parameters, cancel),
*this
*this,
cancel
);
}

// If ``cancel`` returns ``true``, ``results`` holds the (external) neighbors found so
// far, followed by the invalid-neighbor marker. See ``VamanaIndex::search``.
template <typename I, data::ImmutableMemoryDataset Queries>
void search(
QueryResultView<I> results,
Expand Down Expand Up @@ -761,13 +770,10 @@ class MutableVamanaIndex {
}
);

// Check if request to cancel the search
if (cancel()) {
return;
}

// After the search procedure, the indices in `results` are internal.
// Perform one more pass to convert these to external ids.
// This also runs when the search was cancelled so that the partial results are
// external; slots holding the invalid-neighbor marker are left untouched.
translate_to_external(results.indices());
}

Expand Down
69 changes: 50 additions & 19 deletions include/svs/index/vamana/extensions.h
Original file line number Diff line number Diff line change
Expand Up @@ -430,12 +430,18 @@ struct VamanaSingleSearchType {
/// and the graph becomes sparsely connected. It's a corner case and should
/// not happen frequently, but when it does, we may need to supplement the buffer
/// with additional results.
///
/// The top-up is skipped if ``cancel`` returns ``true``, so that a cancelled search keeps
/// exactly the candidates it found before being interrupted.
template <typename Index, typename SearchBuffer, typename Query>
void check_and_supplement_search_buffer(
const Index& index, SearchBuffer& search_buffer, const Query& query
const Index& index,
SearchBuffer& search_buffer,
const Query& query,
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>())
) {
if (search_buffer.valid() < search_buffer.target_window() &&
search_buffer.valid() < index.size()) {
search_buffer.valid() < index.size() && !cancel()) {
search_buffer.sort();
for (auto external_id : index.external_ids()) {
auto internal_id = index.translate_external_id(external_id);
Expand All @@ -452,9 +458,9 @@ void check_and_supplement_search_buffer(
/// Customization point object for processing single queries.
inline constexpr VamanaSingleSearchType single_search{};

/// In this function, cancel does not need to be called since search will call cancel
/// However, lvq requires cancel to be called to skip reranking
/// Here we have cancel to make the interface consistent with lvq
/// ``search`` polls ``cancel`` itself; after a cancel the buffer holds the candidates found
/// so far (a query that never started holds only its entry points). Compressed datasets
/// (LVQ, LeanVec) take the same argument and rerank those candidates.
template <
typename Data,
typename SearchBuffer,
Expand All @@ -472,16 +478,46 @@ SVS_FORCE_INLINE void svs_invoke(
const Index& index,
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>())
) {
// Check if request to cancel the search
if (cancel()) {
return;
}
// Perform graph search.
auto accessor = data::GetDatumAccessor();
search(query, accessor, distance, search_buffer);

if constexpr (Index::needs_id_translation) {
check_and_supplement_search_buffer(index, search_buffer, query);
check_and_supplement_search_buffer(index, search_buffer, query, cancel);
}
}

///
/// @brief Copy the results of ``search_buffer`` into row ``query`` of ``result``.
///
/// Normally all ``result.n_neighbors()`` entries are copied. If the buffer holds fewer
/// entries than that and ``cancel`` returns ``true``, only the entries found so far are
/// copied and the rest of the row is padded with the invalid-neighbor marker
/// (``type_traits::sentinel_v<Neighbor<I>, Cmp>``: the largest ``I`` as the id and the
/// worst distance).
///
template <typename SearchBuffer, std::integral I>
void copy_results(
const SearchBuffer& search_buffer,
QueryResultView<I>& result,
size_t query,
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>())
) {
size_t num_neighbors = result.n_neighbors();
size_t found = search_buffer.size();
if (found < num_neighbors && cancel()) {
for (size_t j = 0; j < found; ++j) {
result.set(search_buffer[j], query, j);
}
constexpr auto marker =
type_traits::sentinel_v<Neighbor<I>, typename SearchBuffer::compare_type>;
for (size_t j = found; j < num_neighbors; ++j) {
result.set(marker, query, j);
}
return;
}
for (size_t j = 0; j < num_neighbors; ++j) {
result.set(search_buffer[j], query, j);
}
}

Expand Down Expand Up @@ -573,21 +609,16 @@ void svs_invoke(
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>())
) {
// Fallback implementation
size_t num_neighbors = result.n_neighbors();
for (auto i : thread_indices) {
// Check if request to cancel the search
if (cancel()) {
return;
}
// Perform search - results will be queued in the search buffer.
// Perform search - results will be queued in the search buffer. If ``cancel``
// fires, the buffer holds what was found so far (only the entry points if the
// query never started) and ``copy_results`` pads the rest of the row.
single_search(
dataset, search_buffer, distance, queries.get_datum(i), search, index, cancel
);

// Copy back results.
for (size_t j = 0; j < num_neighbors; ++j) {
result.set(search_buffer[j], i, j);
}
copy_results(search_buffer, result, i, cancel);
}
}

Expand Down
16 changes: 12 additions & 4 deletions include/svs/index/vamana/index.h
Original file line number Diff line number Diff line change
Expand Up @@ -533,7 +533,8 @@ class VamanaIndex {
scratch.scratch,
query,
greedy_search_closure(scratch.prefetch_parameters, cancel),
*this
*this,
cancel
);
}

Expand All @@ -552,9 +553,16 @@ class VamanaIndex {
/// @param search_parameters search parameters to use for the search.
/// @param cancel A predicate called during the search to determine if the search should
/// be cancelled.
// Return ``true`` if the search should be cancelled. This functor must implement
// ``bool operator()()``. Note: This predicate should be thread-safe as it can be
// called concurrently by different threads during the search.
/// Return ``true`` if the search should be cancelled. This functor must implement
/// ``bool operator()()``. Note: This predicate should be thread-safe as it can be
/// called concurrently by different threads during the search. Once it returns
/// ``true`` it must keep returning ``true`` for the rest of the call.
/// After a cancel, each row holds the neighbors found so far (nearest first,
/// final distances, external IDs), followed by the invalid-neighbor marker
/// ``type_traits::sentinel_v<Neighbor<I>, Cmp>`` (max ID, worst distance).
/// Queries that had not started may hold only their entry points. Treat every
/// slot whose ID is the marker as empty: in the concurrent index a marker can
/// also appear mid-row.
///
/// Perform a multi-threaded graph search over the index, overwriting the contents
/// of ``result`` with the results of search.
Expand Down
3 changes: 2 additions & 1 deletion include/svs/index/vamana/iterator.h
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,8 @@ class BatchIteratorBase {
scratchspace_.scratch,
lib::as_const_span(query_),
search_closure,
*parent_
*parent_,
cancel
);
});

Expand Down
6 changes: 4 additions & 2 deletions include/svs/orchestrators/manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ template <typename IFace> class ManagerInterface : public IFace {
virtual search_parameters_type get_search_parameters() const = 0;
virtual void set_search_parameters(const search_parameters_type&) = 0;

// Cancel callback is not thread safe and can be called multiple times
// Cancel does not return the partial results
// Cancel callback must be thread-safe and can be called multiple times
// Vamana: after a cancel, `results` holds the neighbors found so far, padded with the
// invalid-neighbor marker (see VamanaIndex::search). Other index types: contents of
// `results` are unspecified after a cancel.
// Cancel is not templated as this is a pure virtual function
virtual void search(
svs::QueryResultView<size_t> results,
Expand Down
109 changes: 109 additions & 0 deletions tests/svs/index/vamana/dynamic_index.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@
// header under test.
#include "svs/index/vamana/dynamic_index.h"
#include "svs/index/vamana/consolidate.h"
#include "svs/index/vamana/index.h"

// stl
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <filesystem>
#include <iostream>
#include <limits>
#include <memory>
#include <numeric>
#include <sstream>
Expand Down Expand Up @@ -464,3 +467,109 @@ CATCH_TEST_CASE("MutableVamana Index Memory Usage", "[graph_index][dynamic_index
const size_t usage = index.get_memory_breakdown().total();
CATCH_REQUIRE(usage == expected_total_bytes);
}

CATCH_TEST_CASE("Vamana Cancelled Search", "[graph_index][dynamic_index][cancel]") {
using Distance = svs::distance::DistanceL2;
const size_t num_neighbors = 10;
auto data = test_dataset::data_f32();
auto queries = test_dataset::queries();
auto sp = svs::index::vamana::VamanaSearchParameters{};
sp.buffer_config_ = svs::index::vamana::SearchBufferConfig{20};
svs::index::vamana::VamanaBuildParameters parameters{1.2, 64, 10, 20, 10, true};

// ``to_row`` maps a returned ID to the row of ``data`` holding its vector; ``live``
// says whether that row is still in the index.
auto check = [&](auto& index, auto to_row, auto live) {
auto exact = [&](size_t id, size_t q) {
float sum = 0;
for (size_t d = 0; d < queries.dimensions(); ++d) {
float diff = data.get_datum(to_row(id))[d] - queries.get_datum(q)[d];
sum += diff * diff;
}
return sum;
};
const size_t marker = std::numeric_limits<size_t>::max();
auto search = [&](auto cancel) {
svs::QueryResult<size_t> results{queries.size(), num_neighbors};
index.search(results.view(), queries.cview(), sp, cancel);
return results;
};

// A predicate that never fires gives the same results as no predicate.
svs::QueryResult<size_t> reference{queries.size(), num_neighbors};
index.search(reference.view(), queries.cview(), sp);
auto never = search(svs::lib::Returns(svs::lib::Const<false>()));
for (size_t q = 0; q < queries.size(); ++q) {
for (size_t j = 0; j < num_neighbors; ++j) {
CATCH_REQUIRE(reference.index(q, j) != marker);
CATCH_REQUIRE(live(to_row(reference.index(q, j))));
CATCH_REQUIRE(never.index(q, j) == reference.index(q, j));
CATCH_REQUIRE(never.distance(q, j) == reference.distance(q, j));
}
}

// Fire after a number of polls: each row is a prefix of live neighbors (nearest
// first, exact distances), followed only by markers.
std::atomic<size_t> polls{0};
auto results = search([&]() { return polls.fetch_add(1) >= 500; });
size_t partial = 0;
for (size_t q = 0; q < queries.size(); ++q) {
size_t valid = 0;
while (valid < num_neighbors && results.index(q, valid) != marker) {
size_t id = results.index(q, valid);
CATCH_REQUIRE(live(to_row(id)));
CATCH_REQUIRE(results.distance(q, valid) == Catch::Approx(exact(id, q)));
CATCH_REQUIRE(
(valid == 0 ||
results.distance(q, valid - 1) <= results.distance(q, valid))
);
++valid;
}
for (size_t j = valid; j < num_neighbors; ++j) {
CATCH_REQUIRE(results.index(q, j) == marker);
}
partial += valid < num_neighbors;
}
CATCH_REQUIRE(partial > 0);
};

CATCH_SECTION("Static index") {
auto index = svs::index::vamana::auto_build(parameters, data, Distance(), 2);
check(
index, [](size_t id) { return id; }, [](size_t) { return true; }
);
}

CATCH_SECTION("Dynamic index with deletions and external IDs") {
std::vector<size_t> ids(data.size());
for (size_t i = 0; i < ids.size(); ++i) {
ids[i] = 1000 + 3 * i;
}
auto index = svs::index::vamana::MutableVamanaIndex(
parameters, test_dataset::data_blocked_f32(), ids, Distance(), 2
);
std::vector<size_t> deleted;
for (size_t i = 0; i < ids.size(); i += 7) {
deleted.push_back(ids[i]);
}
// Row `i` has external ID `1000 + 3 * i`; delete every 7th row.
index.delete_entries(deleted);
check(
index,
[](size_t id) { return (id - 1000) / 3; },
[](size_t row) { return row % 7 != 0; }
);

// The batch iterator forwards ``cancel`` too: a search cancelled before it starts
// is not topped up from the live IDs, while an uncancelled one fills the batch.
const size_t batch = 50;
auto query_datum = queries.get_datum(0);
auto query = std::span<const float>(query_datum.data(), query_datum.size());
auto full = index.make_batch_iterator(query);
full.next(batch);
CATCH_REQUIRE(full.size() == batch);
auto cancelled = index.make_batch_iterator(query);
cancelled.next(batch, []() { return true; });
CATCH_REQUIRE(cancelled.size() < batch);
}
}
Loading