Skip to content
Draft
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
71 changes: 53 additions & 18 deletions include/svs/index/vamana/dynamic_index.h
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,32 @@ inline constexpr std::string_view name(SlotMetadata metadata) {

class ValidBuilder {
public:
ValidBuilder(const std::vector<SlotMetadata>& status)
: status_{status} {}
// Optional `pred` (with `translator`): an entry is also invalid if `pred(external_id)`
// is false. Invalid entries are navigated through but never returned.
ValidBuilder(
const std::vector<SlotMetadata>& status,
const IDTranslator* translator = nullptr,
const std::function<bool(size_t)>* pred = nullptr
)
: status_{status}
, translator_{translator}
, pred_{pred} {}

template <typename I>
constexpr PredicatedSearchNeighbor<I> operator()(I i, float distance) const {
bool invalid = getindex(status_, i) == SlotMetadata::Deleted;
// This neighbor should be skipped if the metadata corresponding to the given index
// marks this slot as deleted.
if (!invalid && pred_ != nullptr) {
invalid = !(*pred_)(translator_->get_external(i));
}
return PredicatedSearchNeighbor<I>(i, distance, !invalid);
}

private:
const std::vector<SlotMetadata>& status_;
const IDTranslator* translator_;
const std::function<bool(size_t)>* pred_;
};

template <graphs::MemoryGraph Graph, typename Data, typename Dist>
Expand Down Expand Up @@ -532,6 +545,9 @@ class MutableVamanaIndex {
[&](const auto is, uint64_t /*tid*/) {
for (auto i : is) {
for (size_t j = 0, jmax = getsize<1>(ids); j < jmax; ++j) {
if (ids.at(i, j) == static_cast<size_t>(-1)) {
continue; // Padding from a filtered search.
}
auto internal = lib::narrow_cast<Idx>(ids.at(i, j));
ids.at(i, j) = translate_internal_id(internal);
}
Expand Down Expand Up @@ -573,13 +589,17 @@ class MutableVamanaIndex {

// Return a `greedy_search` compatible builder for this index.
// This is an internal method, mostly used to help implement the batch iterator.
ValidBuilder internal_search_builder() const { return ValidBuilder{status_}; }
ValidBuilder internal_search_builder(const std::function<bool(size_t)>* pred = nullptr
) const {
return ValidBuilder{status_, &translator_, pred};
}

auto greedy_search_closure(
GreedySearchPrefetchParameters prefetch_parameters,
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>())
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>()),
const std::function<bool(size_t)>* pred = nullptr
) const {
return [&, prefetch_parameters](
return [&, prefetch_parameters, pred](
const auto& query, auto& accessor, auto& distance, auto& buffer
) {
// Perform the greedy search using the provided resources.
Expand All @@ -591,7 +611,7 @@ class MutableVamanaIndex {
distance,
buffer,
vamana::EntryPointInitializer<Idx>{lib::as_const_span(entry_point_)},
internal_search_builder(),
internal_search_builder(pred),
prefetch_parameters,
cancel
);
Expand Down Expand Up @@ -623,8 +643,12 @@ class MutableVamanaIndex {
QueryResultView<I> results,
const Queries& queries,
const search_parameters_type& sp,
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>())
const lib::DefaultPredicate& cancel = lib::Returns(lib::Const<false>()),
const std::function<bool(size_t)>* pred = nullptr
) {
// Optional `pred`: only entries whose external id passes are returned. It is called
// from all search threads. Rows with fewer passing entries than requested are
// padded with id `size_t(-1)` and the worst score.
threads::parallel_for(
threadpool_,
threads::StaticPartition{queries.size()},
Expand All @@ -637,23 +661,34 @@ class MutableVamanaIndex {
: sp.buffer_config_,
distance::comparator(distance_),
sp.search_buffer_visited_set_};
// Filtered: entries that fail go into the buffer's min-heap, not its
// sorted list.
buffer.enable_invalid_heap(pred != nullptr);

auto prefetch_parameters = GreedySearchPrefetchParameters{
sp.prefetch_lookahead_, sp.prefetch_step_};

auto scratch = extensions::per_thread_batch_search_setup(data_, distance_);

extensions::per_thread_batch_search(
data_,
buffer,
scratch,
queries,
results,
threads::UnitRange{is},
greedy_search_closure(prefetch_parameters, cancel),
*this,
cancel
);
auto run = [&](const auto& search) {
extensions::per_thread_batch_search(
data_,
buffer,
scratch,
queries,
results,
threads::UnitRange{is},
search,
*this,
cancel
);
};
auto search = greedy_search_closure(prefetch_parameters, cancel, pred);
if (pred == nullptr) {
run(search);
} else {
run(extensions::FilteredSearch<decltype(search)>{search, pred});
}
}
);

Expand Down
70 changes: 69 additions & 1 deletion include/svs/index/vamana/dynamic_search_buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {
vector_type candidates_{};
// An optional visited filter.
std::optional<set_type> visited_{std::nullopt};
// Optional (`enable_invalid_heap`): invalid entries go into this min-heap (best on
// top) instead of `candidates_`, so `candidates_` holds only valid entries and stays
// short. `invalid_seen_` replaces the duplicate check `candidates_` would have done.
bool use_invalid_heap_ = false;
vector_type invalid_heap_{};
std::unordered_set<Idx> invalid_seen_{};
value_type popped_{};

public:
MutableBuffer() = default;
Expand Down Expand Up @@ -197,6 +204,8 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {
/// @brief Prepare the buffer for a new search operation.
void clear() {
candidates_.clear();
invalid_heap_.clear();
invalid_seen_.clear();
best_unvisited_ = 0;
roi_end_ = 0;
valid_ = 0;
Expand All @@ -223,6 +232,9 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {

size_t capacity() const { return candidates_.capacity(); }

/// @brief Keep invalid entries in a separate min-heap instead of the sorted buffer.
void enable_invalid_heap(bool enable = true) { use_invalid_heap_ = enable; }

/// @brief Return the number of valid elements currently contained in the buffer.
size_t valid() const { return valid_; }

Expand Down Expand Up @@ -269,7 +281,8 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {
bool done() const {
// Until we've reached the target number of valid elements, we have to ignore
// the state of `roi_end_`.
return best_unvisited_ == ((valid() < target_valid_) ? size() : roi_end_);
return best_unvisited_ == ((valid() < target_valid_) ? size() : roi_end_) &&
!invalid_ready();
}

/// @brief Return the best unvisited neighbor in the buffer.
Expand All @@ -282,6 +295,21 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {
/// Post-conditions:
/// * The returned neighbor will be marked as visited.
const_reference next() {
// The best invalid entry goes first if it beats the best unvisited valid one.
if (invalid_ready()) {
size_t end = (valid() < target_valid_) ? size() : roi_end_;
if (best_unvisited_ == end || compare_(
invalid_heap_.front().distance(),
candidates_[best_unvisited_].distance()
)) {
std::pop_heap(invalid_heap_.begin(), invalid_heap_.end(), heap_compare());
popped_ = invalid_heap_.back();
invalid_heap_.pop_back();
popped_.set_visited();
return popped_;
}
}

// Get the best unvisited node
reference node = getindex(candidates_, best_unvisited_);
node.set_visited();
Expand All @@ -308,6 +336,10 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {
if (full() && valid) {
return;
}
if (use_invalid_heap_ && !valid) {
push_invalid(neighbor);
return;
}
candidates_.push_back(neighbor);
if (valid) {
++valid_;
Expand Down Expand Up @@ -460,6 +492,10 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {
}

size_t insert_inner(value_type neighbor) {
if (use_invalid_heap_ && !neighbor.valid()) {
push_invalid(neighbor);
return size();
}
const auto start = begin();

// Binary search to the first location where `distance` is less than the stored
Expand Down Expand Up @@ -557,6 +593,8 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {
auto new_end =
std::remove_if(begin(), end(), [](const auto& x) { return !x.valid(); });
candidates_.resize(new_end - begin());
invalid_heap_.clear();
invalid_seen_.clear();
}

/// @brief Return the size of the underlying vector.
Expand Down Expand Up @@ -619,6 +657,36 @@ template <typename Idx, typename Cmp = std::less<>> class MutableBuffer {
}

private:
// Heap order for `invalid_heap_`: the best (closest) entry on top.
auto heap_compare() const {
return [this](const value_type& a, const value_type& b) {
return compare_(b.distance(), a.distance());
};
}

// Queue an invalid entry once per search.
void push_invalid(value_type neighbor) {
if (invalid_seen_.insert(neighbor.id()).second) {
invalid_heap_.push_back(neighbor);
std::push_heap(invalid_heap_.begin(), invalid_heap_.end(), heap_compare());
}
}

// Is the best invalid entry worth expanding? Same rule as an invalid entry in the
// sorted buffer: always while fewer than `target_valid_` valid entries are found,
// afterwards only if it is closer than the `target_valid_`th valid entry.
bool invalid_ready() const {
if (invalid_heap_.empty()) {
return false;
}
if (valid() < target_valid_) {
return true;
}
return compare_(
invalid_heap_.front().distance(), candidates_[roi_end_ - 1].distance()
);
}

/// Return how many more valid candidates exist than required.
/// If the number of valid candidates is *less* than the target, a negative number
/// is returned.
Expand Down
36 changes: 34 additions & 2 deletions include/svs/index/vamana/extensions.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
#include "svs/lib/preprocessor.h"
#include "svs/lib/threads.h"

#include <functional>
#include <limits>

namespace svs::index::vamana::extensions {

/////
Expand Down Expand Up @@ -432,12 +435,18 @@ struct VamanaSingleSearchType {
/// with additional results.
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 std::function<bool(size_t)>* pred = nullptr
) {
if (search_buffer.valid() < search_buffer.target_window() &&
search_buffer.valid() < index.size()) {
search_buffer.sort();
for (auto external_id : index.external_ids()) {
if (pred != nullptr && !(*pred)(external_id)) {
continue;
}
auto internal_id = index.translate_external_id(external_id);
auto dist = index.get_distance(external_id, query);
auto builder = index.internal_search_builder();
Expand All @@ -449,6 +458,15 @@ void check_and_supplement_search_buffer(
}
}

/// A search closure that also carries the filter of a filtered search.
template <typename Search> struct FilteredSearch {
Search search;
const std::function<bool(size_t)>* pred;
template <typename... Args> void operator()(Args&&... args) const {
search(std::forward<Args>(args)...);
}
};

/// Customization point object for processing single queries.
inline constexpr VamanaSingleSearchType single_search{};

Expand Down Expand Up @@ -481,7 +499,11 @@ SVS_FORCE_INLINE void svs_invoke(
search(query, accessor, distance, search_buffer);

if constexpr (Index::needs_id_translation) {
check_and_supplement_search_buffer(index, search_buffer, query);
const std::function<bool(size_t)>* pred = nullptr;
if constexpr (requires { search.pred; }) {
pred = search.pred; // Filtered search: keep filtered-out ids out of the top-up.
}
check_and_supplement_search_buffer(index, search_buffer, query, pred);
}
}

Expand Down Expand Up @@ -586,6 +608,16 @@ void svs_invoke(

// Copy back results.
for (size_t j = 0; j < num_neighbors; ++j) {
if constexpr (requires { search.pred; }) {
if (j >= search_buffer.size()) { // Filtered: fewer than k passed.
result.index(i, j) = static_cast<I>(-1);
result.distance(i, j) =
distance::comparator(distance)(0.0f, 1.0f)
? std::numeric_limits<float>::infinity()
: -std::numeric_limits<float>::infinity();
continue;
}
}
result.set(search_buffer[j], i, j);
}
}
Expand Down
Loading
Loading