Initial commit

This commit is contained in:
sanyi
2025-12-30 11:02:17 +08:00
commit 6524fabd80
841 changed files with 293919 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
cc_library(
NAME core_knn_hnsw
STATIC SHARED STRICT ALWAYS_LINK
SRCS *.cc
LIBS core_framework sparsehash
INCS . ${PROJECT_ROOT_DIR}/src/core ${PROJECT_ROOT_DIR}/src/core/algorithm
VERSION "${PROXIMA_ZVEC_VERSION}"
)
+540
View File
@@ -0,0 +1,540 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_algorithm.h"
#include <chrono>
#include <iostream>
#include <ailego/internal/cpu_features.h>
namespace zvec {
namespace core {
HnswAlgorithm::HnswAlgorithm(HnswEntity &entity)
: entity_(entity),
mt_(std::chrono::system_clock::now().time_since_epoch().count()),
lock_pool_(kLockCnt) {}
int HnswAlgorithm::cleanup() {
return 0;
}
int HnswAlgorithm::add_node(node_id_t id, level_t level, HnswContext *ctx) {
spin_lock_.lock();
// std::cout << "id: " << id << ", level: " << level << std::endl;
auto cur_max_level = entity_.cur_max_level();
auto entry_point = entity_.entry_point();
if (ailego_unlikely(entry_point == kInvalidNodeId)) {
entity_.update_ep_and_level(id, level);
spin_lock_.unlock();
return 0;
}
spin_lock_.unlock();
if (ailego_unlikely(level > cur_max_level)) {
mutex_.lock();
// re-check max level
cur_max_level = entity_.cur_max_level();
entry_point = entity_.entry_point();
if (level <= cur_max_level) {
mutex_.unlock();
}
}
level_t cur_level = cur_max_level;
dist_t dist = ctx->dist_calculator()(entry_point);
for (; cur_level > level; --cur_level) {
select_entry_point(cur_level, &entry_point, &dist, ctx);
}
for (; cur_level >= 0; --cur_level) {
search_neighbors(cur_level, &entry_point, &dist, ctx->level_topk(cur_level),
ctx);
}
// add neighbors from down level to top level, to avoid upper level visible
// to knn_search but the under layer level not ready
for (cur_level = 0; cur_level <= level; ++cur_level) {
add_neighbors(id, cur_level, ctx->level_topk(cur_level), ctx);
ctx->level_topk(cur_level).clear();
}
if (ailego_unlikely(level > cur_max_level)) {
spin_lock_.lock();
entity_.update_ep_and_level(id, level);
spin_lock_.unlock();
mutex_.unlock();
}
return 0;
}
int HnswAlgorithm::search(HnswContext *ctx) const {
spin_lock_.lock();
auto maxLevel = entity_.cur_max_level();
auto entry_point = entity_.entry_point();
spin_lock_.unlock();
if (ailego_unlikely(entry_point == kInvalidNodeId)) {
return 0;
}
dist_t dist = ctx->dist_calculator().dist(entry_point);
for (level_t cur_level = maxLevel; cur_level >= 1; --cur_level) {
select_entry_point(cur_level, &entry_point, &dist, ctx);
}
auto &topk_heap = ctx->topk_heap();
topk_heap.clear();
search_neighbors(0, &entry_point, &dist, topk_heap, ctx);
if (ctx->group_by_search()) {
expand_neighbors_by_group(topk_heap, ctx);
}
return 0;
}
int HnswAlgorithm::fast_search(HnswContext *ctx) const {
auto max_level = entity_.cur_max_level();
auto entry_point = entity_.entry_point();
dist_t dist = ctx->dist_calculator().dist(entry_point);
for (level_t cur_level = max_level; cur_level >= 1; --cur_level) {
select_entry_point(cur_level, &entry_point, &dist, ctx);
}
auto &topk_heap = ctx->topk_heap();
topk_heap.clear();
search_neighbors(0, &entry_point, &dist, topk_heap, ctx);
if (ctx->group_by_search()) {
expand_neighbors_by_group(topk_heap, ctx);
}
return 0;
}
//! select_entry_point on hnsw level, ef = 1
void HnswAlgorithm::select_entry_point(level_t level, node_id_t *entry_point,
dist_t *dist, HnswContext *ctx) const {
auto &entity = ctx->get_entity();
HnswDistCalculator &dc = ctx->dist_calculator();
while (true) {
const Neighbors neighbors = entity.get_neighbors(level, *entry_point);
if (ailego_unlikely(ctx->debugging())) {
(*ctx->mutable_stats_get_neighbors())++;
}
uint32_t size = neighbors.size();
if (size == 0) {
break;
}
std::vector<IndexStorage::MemoryBlock> neighbor_vec_blocks;
int ret = entity.get_vector(&neighbors[0], size, neighbor_vec_blocks);
if (ailego_unlikely(ctx->debugging())) {
(*ctx->mutable_stats_get_vector())++;
}
if (ailego_unlikely(ret != 0)) {
break;
}
bool find_closer = false;
float dists[size];
const void *neighbor_vecs[size];
for (uint32_t i = 0; i < size; ++i) {
neighbor_vecs[i] = neighbor_vec_blocks[i].data();
}
dc.batch_dist(neighbor_vecs, size, dists);
for (uint32_t i = 0; i < size; ++i) {
dist_t cur_dist = dists[i];
if (cur_dist < *dist) {
*entry_point = neighbors[i];
*dist = cur_dist;
find_closer = true;
}
}
if (!find_closer) {
break;
}
}
return;
}
void HnswAlgorithm::add_neighbors(node_id_t id, level_t level,
TopkHeap &topk_heap, HnswContext *ctx) {
if (ailego_unlikely(topk_heap.size() == 0)) {
return;
}
HnswDistCalculator &dc = ctx->dist_calculator();
update_neighbors(dc, id, level, topk_heap);
// reverse update neighbors
for (size_t i = 0; i < topk_heap.size(); ++i) {
reverse_update_neighbors(dc, topk_heap[i].first, level, id,
topk_heap[i].second, ctx->update_heap());
}
return;
}
void HnswAlgorithm::search_neighbors(level_t level, node_id_t *entry_point,
dist_t *dist, TopkHeap &topk,
HnswContext *ctx) const {
const auto &entity = ctx->get_entity();
HnswDistCalculator &dc = ctx->dist_calculator();
VisitFilter &visit = ctx->visit_filter();
CandidateHeap &candidates = ctx->candidates();
std::function<bool(node_id_t)> filter = [](node_id_t) { return false; };
if (ctx->filter().is_valid()) {
filter = [&](node_id_t id) { return ctx->filter()(entity.get_key(id)); };
}
candidates.clear();
visit.clear();
visit.set_visited(*entry_point);
if (!filter(*entry_point)) {
topk.emplace(*entry_point, *dist);
}
candidates.emplace(*entry_point, *dist);
while (!candidates.empty() && !ctx->reach_scan_limit()) {
auto top = candidates.begin();
node_id_t main_node = top->first;
dist_t main_dist = top->second;
if (topk.full() && main_dist > topk[0].second) {
break;
}
candidates.pop();
const Neighbors neighbors = entity.get_neighbors(level, main_node);
ailego_prefetch(neighbors.data);
if (ailego_unlikely(ctx->debugging())) {
(*ctx->mutable_stats_get_neighbors())++;
}
node_id_t neighbor_ids[neighbors.size()];
uint32_t size = 0;
for (uint32_t i = 0; i < neighbors.size(); ++i) {
node_id_t node = neighbors[i];
if (visit.visited(node)) {
if (ailego_unlikely(ctx->debugging())) {
(*ctx->mutable_stats_visit_dup_cnt())++;
}
continue;
}
visit.set_visited(node);
neighbor_ids[size++] = node;
}
if (size == 0) {
continue;
}
std::vector<IndexStorage::MemoryBlock> neighbor_vec_blocks;
int ret = entity.get_vector(neighbor_ids, size, neighbor_vec_blocks);
if (ailego_unlikely(ctx->debugging())) {
(*ctx->mutable_stats_get_vector())++;
}
if (ailego_unlikely(ret != 0)) {
break;
}
// do prefetch
static constexpr node_id_t BATCH_SIZE = 12;
static constexpr node_id_t PREFETCH_STEP = 2;
for (uint32_t i = 0; i < std::min(BATCH_SIZE * PREFETCH_STEP, size); ++i) {
ailego_prefetch(neighbor_vec_blocks[i].data());
}
// done
float dists[size];
const void *neighbor_vecs[size];
for (uint32_t i = 0; i < size; ++i) {
neighbor_vecs[i] = neighbor_vec_blocks[i].data();
}
dc.batch_dist(neighbor_vecs, size, dists);
for (uint32_t i = 0; i < size; ++i) {
node_id_t node = neighbor_ids[i];
dist_t cur_dist = dists[i];
if ((!topk.full()) || cur_dist < topk[0].second) {
candidates.emplace(node, cur_dist);
// update entry_point for next level scan
if (cur_dist < *dist) {
*entry_point = node;
*dist = cur_dist;
}
if (!filter(node)) {
topk.emplace(node, cur_dist);
}
} // end if
} // end for
} // while
return;
}
void HnswAlgorithm::expand_neighbors_by_group(TopkHeap &topk,
HnswContext *ctx) const {
if (!ctx->group_by().is_valid()) {
return;
}
const auto &entity = ctx->get_entity();
std::function<std::string(node_id_t)> group_by = [&](node_id_t id) {
return ctx->group_by()(entity.get_key(id));
};
// devide into groups
std::map<std::string, TopkHeap> &group_topk_heaps = ctx->group_topk_heaps();
for (uint32_t i = 0; i < topk.size(); ++i) {
node_id_t id = topk[i].first;
auto score = topk[i].second;
std::string group_id = group_by(id);
auto &topk_heap = group_topk_heaps[group_id];
if (topk_heap.empty()) {
topk_heap.limit(ctx->group_topk());
}
topk_heap.emplace_back(id, score);
}
// stage 2, expand to reach group num as possible
if (group_topk_heaps.size() < ctx->group_num()) {
VisitFilter &visit = ctx->visit_filter();
CandidateHeap &candidates = ctx->candidates();
HnswDistCalculator &dc = ctx->dist_calculator();
std::function<bool(node_id_t)> filter = [](node_id_t) { return false; };
if (ctx->filter().is_valid()) {
filter = [&](node_id_t id) { return ctx->filter()(entity.get_key(id)); };
}
// refill to get enough groups
candidates.clear();
visit.clear();
for (uint32_t i = 0; i < topk.size(); ++i) {
node_id_t id = topk[i].first;
float score = topk[i].second;
visit.set_visited(id);
candidates.emplace_back(id, score);
}
// do expand
while (!candidates.empty() && !ctx->reach_scan_limit()) {
auto top = candidates.begin();
node_id_t main_node = top->first;
candidates.pop();
const Neighbors neighbors = entity.get_neighbors(0, main_node);
if (ailego_unlikely(ctx->debugging())) {
(*ctx->mutable_stats_get_neighbors())++;
}
node_id_t neighbor_ids[neighbors.size()];
uint32_t size = 0;
for (uint32_t i = 0; i < neighbors.size(); ++i) {
node_id_t node = neighbors[i];
if (visit.visited(node)) {
if (ailego_unlikely(ctx->debugging())) {
(*ctx->mutable_stats_visit_dup_cnt())++;
}
continue;
}
visit.set_visited(node);
neighbor_ids[size++] = node;
}
if (size == 0) {
continue;
}
std::vector<IndexStorage::MemoryBlock> neighbor_vec_blocks;
int ret = entity.get_vector(neighbor_ids, size, neighbor_vec_blocks);
if (ailego_unlikely(ctx->debugging())) {
(*ctx->mutable_stats_get_vector())++;
}
if (ailego_unlikely(ret != 0)) {
break;
}
static constexpr node_id_t PREFETCH_STEP = 2;
for (uint32_t i = 0; i < size; ++i) {
node_id_t node = neighbor_ids[i];
node_id_t prefetch_id = i + PREFETCH_STEP;
if (prefetch_id < size) {
ailego_prefetch(neighbor_vec_blocks[prefetch_id].data());
}
dist_t cur_dist = dc.dist(neighbor_vec_blocks[i].data());
if (!filter(node)) {
std::string group_id = group_by(node);
auto &topk_heap = group_topk_heaps[group_id];
if (topk_heap.empty()) {
topk_heap.limit(ctx->group_topk());
}
topk_heap.emplace_back(node, cur_dist);
if (group_topk_heaps.size() >= ctx->group_num()) {
break;
}
}
candidates.emplace(node, cur_dist);
} // end for
} // end while
} // end if
}
void HnswAlgorithm::update_neighbors(HnswDistCalculator &dc, node_id_t id,
level_t level, TopkHeap &topk_heap) {
topk_heap.sort();
uint32_t max_neighbor_cnt = entity_.neighbor_cnt(level);
if (topk_heap.size() <= static_cast<size_t>(entity_.prune_cnt())) {
if (topk_heap.size() <= static_cast<size_t>(max_neighbor_cnt)) {
entity_.update_neighbors(level, id, topk_heap);
return;
}
}
uint32_t cur_size = 0;
for (size_t i = 0; i < topk_heap.size(); ++i) {
node_id_t cur_node = topk_heap[i].first;
dist_t cur_node_dist = topk_heap[i].second;
bool good = true;
for (uint32_t j = 0; j < cur_size; ++j) {
dist_t tmp_dist = dc.dist(cur_node, topk_heap[j].first);
if (tmp_dist <= cur_node_dist) {
good = false;
break;
}
}
if (good) {
topk_heap[cur_size].first = cur_node;
topk_heap[cur_size].second = cur_node_dist;
cur_size++;
if (cur_size >= max_neighbor_cnt) {
break;
}
}
}
// when after-prune neighbor count is too seldom,
// we use this strategy to make-up enough edges
// not only just make-up out-degrees
// we also make-up enough in-degrees
uint32_t min_neighbors = entity_.min_neighbor_cnt();
for (size_t k = cur_size; cur_size < min_neighbors && k < topk_heap.size();
++k) {
bool exist = false;
for (size_t j = 0; j < cur_size; ++j) {
if (topk_heap[j].first == topk_heap[k].first) {
exist = true;
break;
}
}
if (!exist) {
topk_heap[cur_size].first = topk_heap[k].first;
topk_heap[cur_size].second = topk_heap[k].second;
cur_size++;
}
}
topk_heap.resize(cur_size);
entity_.update_neighbors(level, id, topk_heap);
return;
}
void HnswAlgorithm::reverse_update_neighbors(HnswDistCalculator &dc,
node_id_t id, level_t level,
node_id_t link_id, dist_t dist,
TopkHeap &update_heap) {
const size_t max_neighbor_cnt = entity_.neighbor_cnt(level);
uint32_t lock_idx = id & kLockMask;
lock_pool_[lock_idx].lock();
const Neighbors neighbors = entity_.get_neighbors(level, id);
size_t size = neighbors.size();
ailego_assert_with(size <= max_neighbor_cnt, "invalid neighbor size");
if (size < max_neighbor_cnt) {
entity_.add_neighbor(level, id, size, link_id);
lock_pool_[lock_idx].unlock();
return;
}
update_heap.emplace(link_id, dist);
for (size_t i = 0; i < size; ++i) {
node_id_t node = neighbors[i];
dist_t cur_dist = dc.dist(id, node);
update_heap.emplace(node, cur_dist);
}
//! TODO: optimize prune
//! prune edges
update_heap.sort();
size_t cur_size = 0;
for (size_t i = 0; i < update_heap.size(); ++i) {
node_id_t cur_node = update_heap[i].first;
dist_t cur_node_dist = update_heap[i].second;
bool good = true;
for (size_t j = 0; j < cur_size; ++j) {
dist_t tmp_dist = dc.dist(cur_node, update_heap[j].first);
if (tmp_dist <= cur_node_dist) {
good = false;
break;
}
}
if (good) {
update_heap[cur_size].first = cur_node;
update_heap[cur_size].second = cur_node_dist;
cur_size++;
if (cur_size >= max_neighbor_cnt) {
break;
}
}
}
update_heap.resize(cur_size);
entity_.update_neighbors(level, id, update_heap);
lock_pool_[lock_idx].unlock();
update_heap.clear();
return;
}
} // namespace core
} // namespace zvec
+134
View File
@@ -0,0 +1,134 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <stdint.h>
#include <ailego/parallel/lock.h>
#include "hnsw_context.h"
#include "hnsw_dist_calculator.h"
#include "hnsw_entity.h"
namespace zvec {
namespace core {
//! hnsw graph algorithm implement
class HnswAlgorithm {
public:
typedef std::unique_ptr<HnswAlgorithm> UPointer;
public:
//! Constructor
explicit HnswAlgorithm(HnswEntity &entity);
//! Destructor
~HnswAlgorithm() = default;
//! Cleanup HnswAlgorithm
int cleanup();
//! Add a node to hnsw graph
//! @id: the node unique id
//! @level: a node will be add to graph in each level [0, level]
//! return 0 on success, or errCode in failure
int add_node(node_id_t id, level_t level, HnswContext *ctx);
//! do knn search in graph with lock
//! return 0 on success, or errCode in failure. results saved in ctx
int search(HnswContext *ctx) const;
//! do knn search in graph without lock
//! return 0 on success, or errCode in failure. results saved in ctx
int fast_search(HnswContext *ctx) const;
//! Initiate HnswAlgorithm
int init() {
level_probas_.clear();
double level_mult =
1 / std::log(static_cast<double>(entity_.scaling_factor()));
for (int level = 0;; level++) {
// refers faiss get_random_level alg
double proba =
std::exp(-level / level_mult) * (1 - std::exp(-1 / level_mult));
if (proba < 1e-9) {
break;
}
level_probas_.push_back(proba);
}
return 0;
}
//! Generate a random level
//! return graph level
uint32_t get_random_level() const {
// gen rand float (0, 1)
double f = mt_() / static_cast<float>(mt_.max());
for (size_t level = 0; level < level_probas_.size(); level++) {
if (f < level_probas_[level]) {
return level;
}
f -= level_probas_[level];
}
return level_probas_.size() - 1;
}
private:
//! Select in upper layer to get entry point for next layer search
void select_entry_point(level_t level, node_id_t *entry_point, dist_t *dist,
HnswContext *ctx) const;
//! update node id neighbors from topkHeap, and reverse link is also updated
void add_neighbors(node_id_t id, level_t level, TopkHeap &topk_heap,
HnswContext *ctx);
//! Given a node id and level, search the nearest neighbors in graph
//! Note: the nearest neighbors result keeps in topk, and entry_point and
//! dist will be updated to current level nearest node id and distance
void search_neighbors(level_t level, node_id_t *entry_point, dist_t *dist,
TopkHeap &topk, HnswContext *ctx) const;
//! Update the node's neighbors
void update_neighbors(HnswDistCalculator &dc, node_id_t id, level_t level,
TopkHeap &topk_heap);
//! Checking linkId could be id's new neighbor, and add as neighbor if true
//! @dc distance calculator
//! @updateHeap temporary heap in updating neighbors
void reverse_update_neighbors(HnswDistCalculator &dc, node_id_t id,
level_t level, node_id_t link_id, dist_t dist,
TopkHeap &update_heap);
//! expand neighbors until group nums are reached
void expand_neighbors_by_group(TopkHeap &topk, HnswContext *ctx) const;
private:
HnswAlgorithm(const HnswAlgorithm &) = delete;
HnswAlgorithm &operator=(const HnswAlgorithm &) = delete;
private:
static constexpr uint32_t kLockCnt{1U << 8};
static constexpr uint32_t kLockMask{kLockCnt - 1U};
HnswEntity &entity_;
mutable std::mt19937 mt_{};
std::vector<double> level_probas_{};
mutable ailego::SpinMutex spin_lock_{}; // global spin lock
std::mutex mutex_{}; // global mutex
// TODO: spin lock?
std::vector<std::mutex> lock_pool_{};
};
} // namespace core
} // namespace zvec
+404
View File
@@ -0,0 +1,404 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_builder.h"
#include <iostream>
#include <thread>
#include <ailego/pattern/defer.h>
#include "framework/index_error.h"
#include "framework/index_factory.h"
#include "framework/index_logger.h"
#include "hnsw_algorithm.h"
#include "hnsw_params.h"
namespace zvec {
namespace core {
HnswBuilder::HnswBuilder() {}
int HnswBuilder::init(const IndexMeta &meta, const ailego::Params &params) {
LOG_INFO("Begin HnswBuilder::init");
meta_ = meta;
auto params_copy = params;
meta_.set_builder("HnswBuilder", HnswEntity::kRevision,
std::move(params_copy));
size_t memory_quota = 0UL;
params.get(PARAM_HNSW_BUILDER_MEMORY_QUOTA, &memory_quota);
params.get(PARAM_HNSW_BUILDER_THREAD_COUNT, &thread_cnt_);
params.get(PARAM_HNSW_BUILDER_MAX_NEIGHBOR_COUNT, &neighbor_cnt_);
params.get(PARAM_HNSW_BUILDER_MIN_NEIGHBOR_COUNT, &min_neighbor_cnt_);
float ratio = HnswEntity::kDefaultNeighborPruneRatio;
params.get(PARAM_HNSW_BUILDER_UPPER_NEIGHBOR_RATIO, &ratio);
upper_neighbor_cnt_ = ratio * neighbor_cnt_;
params.get(PARAM_HNSW_BUILDER_EFCONSTRUCTION, &ef_construction_);
params.get(PARAM_HNSW_BUILDER_SCALING_FACTOR, &scaling_factor_);
params.get(PARAM_HNSW_BUILDER_CHECK_INTERVAL_SECS, &check_interval_secs_);
ratio = HnswEntity::kDefaultNeighborPruneRatio;
params.get(PARAM_HNSW_BUILDER_NEIGHBOR_PRUNE_RATIO, &ratio);
size_t prune_cnt = neighbor_cnt_ * ratio;
if (ef_construction_ == 0) {
ef_construction_ = HnswEntity::kDefaultEfConstruction;
}
if (neighbor_cnt_ == 0) {
neighbor_cnt_ = HnswEntity::kDefaultNeighborCnt;
}
if (neighbor_cnt_ > kMaxNeighborCnt) {
LOG_ERROR("[%s] must be in range (0,%d]",
PARAM_HNSW_BUILDER_MAX_NEIGHBOR_COUNT.c_str(), kMaxNeighborCnt);
return IndexError_InvalidArgument;
}
if (min_neighbor_cnt_ > neighbor_cnt_) {
LOG_ERROR("[%s]-[%d] must be <= [%s]-[%d]",
PARAM_HNSW_BUILDER_MIN_NEIGHBOR_COUNT.c_str(), min_neighbor_cnt_,
PARAM_HNSW_BUILDER_MAX_NEIGHBOR_COUNT.c_str(), neighbor_cnt_);
return IndexError_InvalidArgument;
}
if (upper_neighbor_cnt_ == 0) {
neighbor_cnt_ = HnswEntity::kDefaultUpperNeighborCnt;
}
if (upper_neighbor_cnt_ > HnswEntity::kMaxNeighborCnt) {
LOG_ERROR("UpperNeighborCnt must be in range (0,%d)",
HnswEntity::kMaxNeighborCnt);
return IndexError_InvalidArgument;
}
if (scaling_factor_ == 0U) {
scaling_factor_ = HnswEntity::kDefaultScalingFactor;
}
if (scaling_factor_ < 5 || scaling_factor_ > 1000) {
LOG_ERROR("[%s] must be in range [5,1000]",
PARAM_HNSW_BUILDER_SCALING_FACTOR.c_str());
return IndexError_InvalidArgument;
}
if (thread_cnt_ == 0) {
thread_cnt_ = std::thread::hardware_concurrency();
}
if (thread_cnt_ > std::thread::hardware_concurrency()) {
LOG_WARN("[%s] greater than cpu cores %u",
PARAM_HNSW_BUILDER_THREAD_COUNT.c_str(),
std::thread::hardware_concurrency());
}
if (prune_cnt == 0UL) {
prune_cnt = upper_neighbor_cnt_;
}
metric_ = IndexFactory::CreateMetric(meta_.metric_name());
if (!metric_) {
LOG_ERROR("CreateMetric failed, name: %s", meta_.metric_name().c_str());
return IndexError_NoExist;
}
int ret = metric_->init(meta_, meta_.metric_params());
if (ret != 0) {
LOG_ERROR("IndexMetric init failed, ret=%d", ret);
return ret;
}
entity_.set_vector_size(meta_.element_size());
entity_.set_ef_construction(ef_construction_);
entity_.set_neighbor_cnt(neighbor_cnt_);
entity_.set_min_neighbor_cnt(min_neighbor_cnt_);
entity_.set_upper_neighbor_cnt(upper_neighbor_cnt_);
entity_.set_scaling_factor(scaling_factor_);
entity_.set_memory_quota(memory_quota);
entity_.set_prune_cnt(prune_cnt);
ret = entity_.init();
if (ret != 0) {
return ret;
}
alg_ = HnswAlgorithm::UPointer(new HnswAlgorithm(entity_));
ret = alg_->init();
if (ret != 0) {
return ret;
}
state_ = BUILD_STATE_INITED;
LOG_INFO(
"End HnswBuilder::init, params: vectorSize=%u efConstruction=%u "
"neighborCnt=%u upperNeighborCnt=%u scalingFactor=%u "
"memoryQuota=%zu neighborPruneCnt=%zu metricName=%s ",
meta_.element_size(), ef_construction_, neighbor_cnt_,
upper_neighbor_cnt_, scaling_factor_, memory_quota, prune_cnt,
meta_.metric_name().c_str());
return 0;
}
int HnswBuilder::cleanup(void) {
LOG_INFO("Begin HnswBuilder::cleanup");
neighbor_cnt_ = HnswEntity::kDefaultNeighborCnt;
min_neighbor_cnt_ = 0;
upper_neighbor_cnt_ = HnswEntity::kDefaultUpperNeighborCnt;
ef_construction_ = HnswEntity::kDefaultEfConstruction;
scaling_factor_ = HnswEntity::kDefaultScalingFactor;
check_interval_secs_ = kDefaultLogIntervalSecs;
errcode_ = 0;
error_ = false;
entity_.cleanup();
alg_->cleanup();
meta_.clear();
metric_.reset();
stats_.clear_attributes();
stats_.set_trained_count(0UL);
stats_.set_built_count(0UL);
stats_.set_dumped_count(0UL);
stats_.set_discarded_count(0UL);
stats_.set_trained_costtime(0UL);
stats_.set_built_costtime(0UL);
stats_.set_dumped_costtime(0UL);
state_ = BUILD_STATE_INIT;
LOG_INFO("End HnswBuilder::cleanup");
return 0;
}
int HnswBuilder::train(IndexThreads::Pointer, IndexHolder::Pointer holder) {
if (state_ != BUILD_STATE_INITED) {
LOG_ERROR("Init the builder before HnswBuilder::train");
return IndexError_NoReady;
}
if (!holder) {
LOG_ERROR("Input holder is nullptr while training index");
return IndexError_InvalidArgument;
}
if (!holder->is_matched(meta_)) {
LOG_ERROR("Input holder doesn't match index meta while training index");
return IndexError_Mismatch;
}
LOG_INFO("Begin HnswBuilder::train");
size_t trained_cost_time = 0;
size_t trained_count = 0;
if (metric_->support_train()) {
auto start_time = ailego::Monotime::MilliSeconds();
auto iter = holder->create_iterator();
if (!iter) {
LOG_ERROR("Create iterator for holder failed");
return IndexError_Runtime;
}
while (iter->is_valid()) {
int ret = metric_->train(iter->data(), meta_.dimension());
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw build measure train failed, ret=%d", ret);
return ret;
}
iter->next();
++trained_count;
}
trained_cost_time = ailego::Monotime::MilliSeconds() - start_time;
}
stats_.set_trained_count(trained_count);
stats_.set_trained_costtime(trained_cost_time);
state_ = BUILD_STATE_TRAINED;
LOG_INFO("End HnswBuilder::train");
return 0;
}
int HnswBuilder::train(const IndexTrainer::Pointer & /*trainer*/) {
if (state_ != BUILD_STATE_INITED) {
LOG_ERROR("Init the builder before HnswBuilder::train");
return IndexError_NoReady;
}
LOG_INFO("Begin HnswBuilder::train by trainer");
stats_.set_trained_count(0UL);
stats_.set_trained_costtime(0UL);
state_ = BUILD_STATE_TRAINED;
LOG_INFO("End HnswBuilder::train by trainer");
return 0;
}
int HnswBuilder::build(IndexThreads::Pointer threads,
IndexHolder::Pointer holder) {
if (state_ != BUILD_STATE_TRAINED) {
LOG_ERROR("Train the index before HnswBuilder::build");
return IndexError_NoReady;
}
if (!holder) {
LOG_ERROR("Input holder is nullptr while building index");
return IndexError_InvalidArgument;
}
if (!holder->is_matched(meta_)) {
LOG_ERROR("Input holder doesn't match index meta while building index");
return IndexError_Mismatch;
}
if (!threads) {
threads = std::make_shared<SingleQueueIndexThreads>(thread_cnt_, false);
if (!threads) {
return IndexError_NoMemory;
}
}
auto start_time = ailego::Monotime::MilliSeconds();
LOG_INFO("Begin HnswBuilder::build");
if (holder->count() != static_cast<size_t>(-1)) {
LOG_DEBUG("HnswBuilder holder documents count %lu", holder->count());
int ret = entity_.reserve_space(holder->count());
if (ret != 0) {
LOG_ERROR("HnswBuilde reserver space failed");
return ret;
}
}
auto iter = holder->create_iterator();
if (!iter) {
LOG_ERROR("Create iterator for holder failed");
return IndexError_Runtime;
}
int ret;
error_ = false;
while (iter->is_valid()) {
level_t level = alg_->get_random_level();
node_id_t id;
const void *vec = iter->data();
ret = entity_.add_vector(level, iter->key(), vec, &id);
if (ailego_unlikely(ret != 0)) {
return ret;
}
iter->next();
}
// Holder is not needed, cleanup it.
holder.reset();
LOG_INFO("Finished save vector, start build graph...");
auto task_group = threads->make_group();
if (!task_group) {
LOG_ERROR("Failed to create task group");
return IndexError_Runtime;
}
std::atomic<node_id_t> finished{0};
for (size_t i = 0; i < threads->count(); ++i) {
task_group->submit(ailego::Closure ::New(this, &HnswBuilder::do_build, i,
threads->count(), &finished));
}
while (!task_group->is_finished()) {
std::unique_lock<std::mutex> lk(mutex_);
cond_.wait_until(lk, std::chrono::system_clock::now() +
std::chrono::seconds(check_interval_secs_));
if (error_.load(std::memory_order_acquire)) {
LOG_ERROR("Failed to build index while waiting finish");
return errcode_;
}
LOG_INFO("Built cnt %u, finished percent %.3f%%", finished.load(),
finished.load() * 100.0f / entity_.doc_cnt());
}
if (error_.load(std::memory_order_acquire)) {
LOG_ERROR("Failed to build index while waiting finish");
return errcode_;
}
task_group->wait_finish();
stats_.set_built_count(finished.load());
stats_.set_built_costtime(ailego::Monotime::MilliSeconds() - start_time);
state_ = BUILD_STATE_BUILT;
LOG_INFO("End HnswBuilder::build");
return 0;
}
void HnswBuilder::do_build(node_id_t idx, size_t step_size,
std::atomic<node_id_t> *finished) {
AILEGO_DEFER([&]() {
std::lock_guard<std::mutex> latch(mutex_);
cond_.notify_one();
});
HnswContext *ctx = new (std::nothrow)
HnswContext(meta_.dimension(), metric_,
std::shared_ptr<HnswEntity>(&entity_, [](HnswEntity *) {}));
if (ailego_unlikely(ctx == nullptr)) {
if (!error_.exchange(true)) {
LOG_ERROR("Failed to create context");
errcode_ = IndexError_NoMemory;
}
return;
}
HnswContext::Pointer auto_ptr(ctx);
ctx->set_max_scan_num(entity_.doc_cnt());
int ret = ctx->init(HnswContext::kBuilderContext);
if (ret != 0) {
if (!error_.exchange(true)) {
LOG_ERROR("Failed to init context");
errcode_ = IndexError_Runtime;
}
return;
}
IndexQueryMeta qmeta(meta_.data_type(), meta_.dimension());
for (node_id_t id = idx; id < entity_.doc_cnt(); id += step_size) {
ctx->reset_query(entity_.get_vector(id));
ret = alg_->add_node(id, entity_.get_level(id), ctx);
if (ailego_unlikely(ret != 0)) {
if (!error_.exchange(true)) {
LOG_ERROR("Hnsw graph add node failed");
errcode_ = ret;
}
return;
}
ctx->clear();
(*finished)++;
}
}
int HnswBuilder::dump(const IndexDumper::Pointer &dumper) {
if (state_ != BUILD_STATE_BUILT) {
LOG_INFO("Build the index before HnswBuilder::dump");
return IndexError_NoReady;
}
LOG_INFO("Begin HnswBuilder::dump");
meta_.set_searcher("HnswSearcher", HnswEntity::kRevision, ailego::Params());
auto start_time = ailego::Monotime::MilliSeconds();
int ret = IndexHelper::SerializeToDumper(meta_, dumper.get());
if (ret != 0) {
LOG_ERROR("Failed to serialize meta into dumper.");
return ret;
}
ret = entity_.dump(dumper);
if (ret != 0) {
LOG_ERROR("HnswBuilder dump index failed");
return ret;
}
stats_.set_dumped_count(entity_.doc_cnt());
stats_.set_dumped_costtime(ailego::Monotime::MilliSeconds() - start_time);
LOG_INFO("EndHnswBuilder::dump");
return 0;
}
INDEX_FACTORY_REGISTER_BUILDER(HnswBuilder);
} // namespace core
} // namespace zvec
+93
View File
@@ -0,0 +1,93 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <ailego/parallel/thread_pool.h>
#include "framework/index_builder.h"
#include "hnsw_algorithm.h"
#include "hnsw_builder_entity.h"
namespace zvec {
namespace core {
class HnswBuilder : public IndexBuilder {
public:
//! Constructor
HnswBuilder();
//! Initialize the builder
virtual int init(const IndexMeta &meta,
const ailego::Params &params) override;
//! Cleanup the builder
virtual int cleanup(void) override;
//! Train the data
virtual int train(IndexThreads::Pointer,
IndexHolder::Pointer holder) override;
//! Train the data
virtual int train(const IndexTrainer::Pointer &trainer) override;
//! Build the index
virtual int build(IndexThreads::Pointer threads,
IndexHolder::Pointer holder) override;
//! Dump index into storage
virtual int dump(const IndexDumper::Pointer &dumper) override;
//! Retrieve statistics
virtual const Stats &stats(void) const override {
return stats_;
}
private:
void do_build(node_id_t idx, size_t step_size,
std::atomic<node_id_t> *finished);
constexpr static uint32_t kDefaultLogIntervalSecs = 15U;
constexpr static uint32_t kMaxNeighborCnt = 65535;
private:
enum BUILD_STATE {
BUILD_STATE_INIT = 0,
BUILD_STATE_INITED = 1,
BUILD_STATE_TRAINED = 2,
BUILD_STATE_BUILT = 3
};
HnswBuilderEntity entity_{};
HnswAlgorithm::UPointer alg_; // impl graph algorithm
uint32_t thread_cnt_{0};
uint32_t neighbor_cnt_{HnswEntity::kDefaultNeighborCnt};
uint32_t min_neighbor_cnt_{0};
uint32_t upper_neighbor_cnt_{HnswEntity::kDefaultUpperNeighborCnt};
uint32_t ef_construction_{HnswEntity::kDefaultEfConstruction};
uint32_t scaling_factor_{HnswEntity::kDefaultScalingFactor};
uint32_t check_interval_secs_{kDefaultLogIntervalSecs};
int errcode_{0};
std::atomic_bool error_{false};
IndexMeta meta_{};
IndexMetric::Pointer metric_{};
std::mutex mutex_{};
std::condition_variable cond_{};
Stats stats_{};
BUILD_STATE state_{BUILD_STATE_INIT};
};
} // namespace core
} // namespace zvec
@@ -0,0 +1,198 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_builder_entity.h"
#include <iostream>
#include <ailego/hash/crc32c.h>
#include "utility/sparse_utility.h"
namespace zvec {
namespace core {
HnswBuilderEntity::HnswBuilderEntity() {
update_ep_and_level(kInvalidNodeId, 0U);
}
int HnswBuilderEntity::cleanup() {
memory_quota_ = 0UL;
neighbors_size_ = 0U;
upper_neighbors_size_ = 0U;
padding_size_ = 0U;
vectors_buffer_.clear();
keys_buffer_.clear();
neighbors_buffer_.clear();
upper_neighbors_buffer_.clear();
neighbors_index_.clear();
vectors_buffer_.shrink_to_fit();
keys_buffer_.shrink_to_fit();
neighbors_buffer_.shrink_to_fit();
upper_neighbors_buffer_.shrink_to_fit();
neighbors_index_.shrink_to_fit();
this->HnswEntity::cleanup();
return 0;
}
int HnswBuilderEntity::init() {
size_t size = vector_size();
//! aligned size to 32
set_node_size(AlignSize(size));
//! if node size is aligned to 1k, the build performance will downgrade
if (node_size() % 1024 == 0) {
set_node_size(AlignSize(node_size() + 1));
}
padding_size_ = node_size() - size;
neighbors_size_ = neighbors_size();
upper_neighbors_size_ = upper_neighbors_size();
return 0;
}
int HnswBuilderEntity::reserve_space(size_t docs) {
if (memory_quota_ > 0 && (node_size() * docs + neighbors_size_ * docs +
sizeof(NeighborIndex) * docs >
memory_quota_)) {
return IndexError_NoMemory;
}
vectors_buffer_.reserve(node_size() * docs);
keys_buffer_.reserve(sizeof(key_t) * docs);
neighbors_buffer_.reserve(neighbors_size_ * docs);
neighbors_index_.reserve(docs);
return 0;
}
int HnswBuilderEntity::add_vector(level_t level, key_t key, const void *vec,
node_id_t *id) {
if (memory_quota_ > 0 &&
(vectors_buffer_.capacity() + keys_buffer_.capacity() +
neighbors_buffer_.capacity() + upper_neighbors_buffer_.capacity() +
neighbors_index_.capacity() * sizeof(NeighborIndex)) > memory_quota_) {
LOG_ERROR("Add vector failed, used memory exceed quota, cur_doc=%u",
doc_cnt());
return IndexError_NoMemory;
}
vectors_buffer_.append(reinterpret_cast<const char *>(vec), vector_size());
vectors_buffer_.append(padding_size_, '\0');
keys_buffer_.append(reinterpret_cast<const char *>(&key), sizeof(key));
// init level 0 neighbors
neighbors_buffer_.append(neighbors_size_, '\0');
neighbors_index_.emplace_back(upper_neighbors_buffer_.size(), level);
// init upper layer neighbors
for (level_t cur_level = 1; cur_level <= level; ++cur_level) {
upper_neighbors_buffer_.append(upper_neighbors_size_, '\0');
}
*id = (*mutable_doc_cnt())++;
return 0;
}
key_t HnswBuilderEntity::get_key(node_id_t id) const {
return *(reinterpret_cast<const key_t *>(keys_buffer_.data() +
id * sizeof(key_t)));
}
const void *HnswBuilderEntity::get_vector(node_id_t id) const {
return vectors_buffer_.data() + id * node_size();
}
int HnswBuilderEntity::get_vector(const node_id_t id,
IndexStorage::MemoryBlock &block) const {
const void *vec = get_vector(id);
block.reset((void *)vec);
return 0;
}
int HnswBuilderEntity::get_vector(const node_id_t *ids, uint32_t count,
const void **vecs) const {
for (uint32_t i = 0; i < count; ++i) {
vecs[i] = vectors_buffer_.data() + ids[i] * node_size();
}
return 0;
}
int HnswBuilderEntity::get_vector(
const node_id_t *ids, uint32_t count,
std::vector<IndexStorage::MemoryBlock> &vec_blocks) const {
const void *vecs[count];
get_vector(ids, count, vecs);
for (uint32_t i = 0; i < count; ++i) {
vec_blocks.emplace_back(IndexStorage::MemoryBlock((void *)vecs[i]));
}
return 0;
}
const Neighbors HnswBuilderEntity::get_neighbors(level_t level,
node_id_t id) const {
const NeighborsHeader *hd = get_neighbor_header(level, id);
return {hd->neighbor_cnt, hd->neighbors};
}
int HnswBuilderEntity::update_neighbors(
level_t level, node_id_t id,
const std::vector<std::pair<node_id_t, dist_t>> &neighbors) {
NeighborsHeader *hd =
const_cast<NeighborsHeader *>(get_neighbor_header(level, id));
for (size_t i = 0; i < neighbors.size(); ++i) {
hd->neighbors[i] = neighbors[i].first;
}
hd->neighbor_cnt = neighbors.size();
// std::cout << "id: " << id << ", neighbour, id: ";
// for (size_t i = 0; i < neighbors.size(); ++i) {
// if (i == neighbors.size()-1)
// std::cout << neighbors[i].first << ", score:" << neighbors[i].second <<
// std::endl;
// else
// std::cout << neighbors[i].first << ", score:" << neighbors[i].second <<
// ", id: ";
// }
return 0;
}
void HnswBuilderEntity::add_neighbor(level_t level, node_id_t id,
uint32_t /*size*/, node_id_t neighbor_id) {
NeighborsHeader *hd =
const_cast<NeighborsHeader *>(get_neighbor_header(level, id));
hd->neighbors[hd->neighbor_cnt++] = neighbor_id;
return;
}
int HnswBuilderEntity::dump(const IndexDumper::Pointer &dumper) {
key_t *keys =
reinterpret_cast<key_t *>(const_cast<char *>(keys_buffer_.data()));
auto ret =
dump_segments(dumper, keys, [&](node_id_t id) { return get_level(id); });
if (ailego_unlikely(ret < 0)) {
return ret;
}
return 0;
}
} // namespace core
} // namespace zvec
@@ -0,0 +1,138 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <ailego/internal/platform.h>
#include "hnsw_entity.h"
namespace zvec {
namespace core {
class HnswBuilderEntity : public HnswEntity {
public:
//! Add vector and key to hnsw entity, and local id will be saved to id
virtual int add_vector(level_t level, key_t key, const void *vec,
node_id_t *id) override;
//! Get primary key of the node id
virtual key_t get_key(node_id_t id) const override;
//! Get vector feature data by key
virtual const void *get_vector(node_id_t id) const override;
//! Batch get vectors feature data by keys
virtual int get_vector(const node_id_t *ids, uint32_t count,
const void **vecs) const override;
virtual int get_vector(const node_id_t id,
IndexStorage::MemoryBlock &block) const override;
virtual int get_vector(
const node_id_t *ids, uint32_t count,
std::vector<IndexStorage::MemoryBlock> &vec_blocks) const override;
//! Get the node id's neighbors on graph level
const NeighborsHeader *get_neighbor_header(level_t level,
node_id_t id) const {
if (level == 0) {
return reinterpret_cast<const NeighborsHeader *>(
neighbors_buffer_.data() + neighbors_size_ * id);
} else {
size_t offset = neighbors_index_[id].offset;
return reinterpret_cast<const NeighborsHeader *>(
upper_neighbors_buffer_.data() + offset +
(level - 1) * upper_neighbors_size_);
}
}
//! Get the node id's neighbors on graph level
virtual const Neighbors get_neighbors(level_t level,
node_id_t id) const override;
//! Replace node id in level's neighbors
virtual int update_neighbors(
level_t level, node_id_t id,
const std::vector<std::pair<node_id_t, dist_t>> &neighbors) override;
//! add a neighbor to id in graph level
virtual void add_neighbor(level_t level, node_id_t id, uint32_t size,
node_id_t neighbor_id) override;
//! Dump the hnsw graph to dumper
virtual int dump(const IndexDumper::Pointer &dumper) override;
//! Cleanup the entity
virtual int cleanup(void) override;
public:
//! Constructor
HnswBuilderEntity();
//! Get the node graph level by id
level_t get_level(node_id_t id) const {
return neighbors_index_[id].level;
}
//! Init builerEntity
int init();
//! reserve buffer space for documents
//! @param docs number of documents
int reserve_space(size_t docs);
//! Set memory quota params
inline void set_memory_quota(size_t memory_quota) {
memory_quota_ = memory_quota;
}
//! Get neighbors size
inline size_t neighbors_size() const {
return sizeof(NeighborsHeader) + neighbor_cnt() * sizeof(node_id_t);
}
//! Get upper neighbors size
inline size_t upper_neighbors_size() const {
return sizeof(NeighborsHeader) + upper_neighbor_cnt() * sizeof(node_id_t);
}
public:
HnswBuilderEntity(const HnswBuilderEntity &) = delete;
HnswBuilderEntity &operator=(const HnswBuilderEntity &) = delete;
private:
friend class HnswSearcherEntity;
//! class internal used only
struct NeighborIndex {
NeighborIndex(size_t off, level_t l) : offset(off), level(l) {}
uint64_t offset : 48;
uint64_t level : 16;
};
std::string vectors_buffer_{}; // aligned vectors
std::string keys_buffer_{}; // aligned vectors
std::string neighbors_buffer_{}; // level 0 neighbors buffer
std::string upper_neighbors_buffer_{}; // upper layer neighbors buffer
std::string sparse_data_buffer_{}; // aligned spase data buffer
size_t sparse_data_offset_{0}; //
// upper layer offset + level in upper_neighbors_buffer_
std::vector<NeighborIndex> neighbors_index_{};
size_t memory_quota_{0UL};
size_t neighbors_size_{0U}; // level 0 neighbors size
size_t upper_neighbors_size_{0U}; // level 0 neighbors size
size_t padding_size_{}; // padding size for each vector element
};
} // namespace core
} // namespace zvec
+220
View File
@@ -0,0 +1,220 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_chunk.h"
#include <chrono>
#include <random>
#include <ailego/hash/crc32c.h>
#include <ailego/utility/time_helper.h>
#include "framework/index_error.h"
#include "framework/index_helper.h"
#include "framework/index_logger.h"
#include "framework/index_streamer.h"
namespace zvec {
namespace core {
int ChunkBroker::init_storage(size_t chunk_size) {
chunk_meta_.clear();
chunk_meta_.chunk_size = chunk_size;
chunk_meta_.create_time = ailego::Realtime::Seconds();
stats_.set_create_time(chunk_meta_.create_time);
chunk_meta_.update_time = ailego::Realtime::Seconds();
stats_.set_update_time(chunk_meta_.update_time);
//! alloc meta chunk
size_t size = sizeof(HnswChunkMeta);
size = (size + page_mask_) & (~page_mask_);
const std::string segment_id =
make_segment_id(CHUNK_TYPE_META, kDefaultChunkSeqId);
int ret = stg_->append(segment_id, size);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Storage append segment failed for %s", IndexError::What(ret));
return ret;
}
chunk_meta_segment_ = get_chunk(CHUNK_TYPE_META, kDefaultChunkSeqId);
if (ailego_unlikely(!chunk_meta_segment_)) {
LOG_ERROR("Get meta segment failed");
return IndexError_Runtime;
}
//! update meta info and write to storage
chunk_meta_.chunk_cnts[CHUNK_TYPE_META] += 1;
chunk_meta_.total_size += size;
(*stats_.mutable_index_size()) += size;
size = chunk_meta_segment_->write(0UL, &chunk_meta_, sizeof(HnswChunkMeta));
if (ailego_unlikely(size != sizeof(HnswChunkMeta))) {
LOG_ERROR("Storage write data failed, wsize=%zu", size);
return IndexError_WriteData;
}
return 0;
}
int ChunkBroker::load_storage(size_t chunk_size) {
IndexStorage::MemoryBlock data_block;
size_t size = chunk_meta_segment_->read(0UL, data_block,
chunk_meta_segment_->data_size());
if (size != sizeof(HnswChunkMeta)) {
LOG_ERROR("Invalid hnsw meta chunk, read size=%zu chunk size=%zu", size,
chunk_meta_segment_->data_size());
return IndexError_InvalidFormat;
}
std::memcpy(&chunk_meta_, data_block.data(), size);
if (chunk_meta_.chunk_size != chunk_size) {
LOG_ERROR(
"Params hnsw chunk size=%zu mismatch from previous %zu "
"in index",
chunk_size, (size_t)chunk_meta_.chunk_size);
return IndexError_Mismatch;
}
*stats_.mutable_check_point() = stg_->check_point();
stats_.set_revision_id(chunk_meta_.revision_id);
stats_.set_update_time(chunk_meta_.update_time);
stats_.set_create_time(chunk_meta_.create_time);
char create_time[32];
char update_time[32];
ailego::Realtime::Gmtime(chunk_meta_.create_time, "%Y-%m-%d %H:%M:%S",
create_time, sizeof(create_time));
ailego::Realtime::Gmtime(chunk_meta_.update_time, "%Y-%m-%d %H:%M:%S",
update_time, sizeof(update_time));
LOG_DEBUG(
"Load index, indexSize=%zu chunkSize=%zu nodeChunks=%zu "
"upperNeighborChunks=%zu revisionId=%zu "
"createTime=%s updateTime=%s",
(size_t)chunk_meta_.total_size, (size_t)chunk_meta_.chunk_size,
(size_t)chunk_meta_.chunk_cnts[CHUNK_TYPE_NODE],
(size_t)chunk_meta_.chunk_cnts[CHUNK_TYPE_UPPER_NEIGHBOR],
(size_t)chunk_meta_.revision_id, create_time, update_time);
return 0;
}
int ChunkBroker::open(IndexStorage::Pointer stg, size_t max_index_size,
size_t chunk_size, bool check_crc) {
if (ailego_unlikely(stg_)) {
LOG_ERROR("An storage instance is already opened");
return IndexError_Duplicate;
}
stg_ = std::move(stg);
if (stg_->isHugePage()) {
page_mask_ = ailego::MemoryHelper::HugePageSize() - 1;
} else {
page_mask_ = ailego::MemoryHelper::PageSize() - 1;
}
check_crc_ = check_crc;
max_chunks_size_ = max_index_size;
dirty_ = false;
const std::string segment_id =
make_segment_id(CHUNK_TYPE_META, kDefaultChunkSeqId);
chunk_meta_segment_ = stg_->get(segment_id);
if (!chunk_meta_segment_) {
LOG_DEBUG("Create new index");
return init_storage(chunk_size);
}
return load_storage(chunk_size);
}
int ChunkBroker::close(void) {
flush(0UL);
stg_.reset();
check_crc_ = false;
dirty_ = false;
return 0;
}
int ChunkBroker::flush(uint64_t checkpoint) {
ailego_assert_with(chunk_meta_segment_, "invalid meta segment");
chunk_meta_.update_time = ailego::Realtime::Seconds();
stats_.set_update_time(chunk_meta_.update_time);
size_t size =
chunk_meta_segment_->write(0UL, &chunk_meta_, sizeof(HnswChunkMeta));
if (ailego_unlikely(size != sizeof(HnswChunkMeta))) {
LOG_ERROR("Storage write data failed, wsize=%zu", size);
}
stg_->refresh(checkpoint);
int ret = stg_->flush();
if (ret == 0) {
(*stats_.mutable_check_point()) = checkpoint;
} else {
LOG_ERROR("Storage flush failed for %s", IndexError::What(ret));
}
return ret;
}
std::pair<int, Chunk::Pointer> ChunkBroker::alloc_chunk(int type,
uint64_t seq_id,
size_t size) {
ailego_assert_with(type < CHUNK_TYPE_MAX, "chunk type overflow");
Chunk::Pointer chunk;
if (ailego_unlikely(!stg_)) {
LOG_ERROR("Init storage first");
return std::make_pair(IndexError_Uninitialized, chunk);
}
//! check exist a empty chunk with the same name
chunk = get_chunk(type, seq_id);
if (chunk) {
if (ailego_unlikely(chunk->capacity() == size &&
chunk->data_size() == 0UL)) {
LOG_ERROR("Exist invalid chunk size %zu, expect size %zu",
chunk->capacity(), size);
chunk.reset();
return std::make_pair(IndexError_Runtime, chunk);
}
return std::make_pair(0, chunk);
}
//! align to page size
size = (size + page_mask_) & (~page_mask_);
if (ailego_unlikely(chunk_meta_.total_size + size >= max_chunks_size_)) {
LOG_ERROR("No space to new a chunk, curIndexSize=%zu allocSize=%zu",
(size_t)chunk_meta_.total_size, size);
return std::make_pair(IndexError_IndexFull, chunk);
}
std::string segment_id = make_segment_id(type, seq_id);
int ret = stg_->append(segment_id, size);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Storage append segment failed for %s", IndexError::What(ret));
return std::make_pair(ret, chunk);
}
chunk_meta_.chunk_cnts[type] += 1;
chunk_meta_.total_size += size;
(*stats_.mutable_index_size()) += size;
size = chunk_meta_segment_->write(0UL, &chunk_meta_, sizeof(HnswChunkMeta));
if (ailego_unlikely(size != sizeof(HnswChunkMeta))) {
LOG_ERROR("Storage append segment failed, wsize=%zu", size);
}
chunk = get_chunk(type, seq_id);
return std::make_pair(chunk ? 0 : IndexError_NoMemory, chunk);
}
Chunk::Pointer ChunkBroker::get_chunk(int type, uint64_t seq_id) const {
std::string segment_id = make_segment_id(type, seq_id);
return stg_->get(segment_id);
}
} // namespace core
} // namespace zvec
+140
View File
@@ -0,0 +1,140 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <atomic>
#include <cstddef>
#include <mutex>
#include <ailego/internal/platform.h>
#include <ailego/utility/memory_helper.h>
#include <ailego/utility/string_helper.h>
#include "framework/index_error.h"
#include "framework/index_logger.h"
#include "framework/index_storage.h"
#include "framework/index_streamer.h"
namespace zvec {
namespace core {
using Chunk = IndexStorage::Segment;
class ChunkBroker {
public:
typedef std::shared_ptr<ChunkBroker> Pointer;
enum CHUNK_TYPE {
CHUNK_TYPE_HEADER = 1,
CHUNK_TYPE_META = 2,
CHUNK_TYPE_NODE = 3,
CHUNK_TYPE_UPPER_NEIGHBOR = 4,
CHUNK_TYPE_NEIGHBOR_INDEX = 5,
CHUNK_TYPE_SPARSE_NODE = 6,
CHUNK_TYPE_MAX = 8
};
static constexpr size_t kDefaultChunkSeqId = 0UL;
ChunkBroker(IndexStreamer::Stats &stats) : stats_(stats) {}
//! Open storage
int open(IndexStorage::Pointer stg, size_t max_index_size, size_t chunk_size,
bool check_crc);
int close(void);
int flush(uint64_t checkpoint);
//! alloc a new chunk with size, not thread-safe
std::pair<int, Chunk::Pointer> alloc_chunk(int type, uint64_t seq_id,
size_t size);
//! alloc a new chunk with chunk size
inline std::pair<int, Chunk::Pointer> alloc_chunk(int type, uint64_t seq_id) {
return alloc_chunk(type, seq_id, chunk_meta_.chunk_size);
}
Chunk::Pointer get_chunk(int type, uint64_t seq_id) const;
inline size_t get_chunk_cnt(int type) const {
ailego_assert_with(type < CHUNK_TYPE_MAX, "chunk type overflow");
return chunk_meta_.chunk_cnts[type];
}
inline bool dirty(void) const {
return dirty_;
}
inline void mark_dirty(void) {
if (!dirty_) {
dirty_ = true;
chunk_meta_.revision_id += 1;
stats_.set_revision_id(chunk_meta_.revision_id);
}
}
const IndexStorage::Pointer storage(void) const {
return stg_;
}
private:
ChunkBroker(const ChunkBroker &) = delete;
ChunkBroker &operator=(const ChunkBroker &) = delete;
struct HnswChunkMeta {
HnswChunkMeta(void) {
memset(this, 0, sizeof(HnswChunkMeta));
}
void clear() {
memset(this, 0, sizeof(HnswChunkMeta));
}
uint64_t chunk_cnts[CHUNK_TYPE_MAX];
uint64_t chunk_size; // size of per chunk
uint64_t total_size; // total size of allocated chunk
uint64_t revision_id; // index revision
uint64_t create_time;
uint64_t update_time;
uint64_t reserved[3];
};
static_assert(sizeof(HnswChunkMeta) % 32 == 0,
"HnswChunkMeta must be aligned with 32 bytes");
//! Init the storage after open an empty index
int init_storage(size_t chunk_size);
//! Load index from storage
int load_storage(size_t chunk_size);
static inline const std::string make_segment_id(int type, uint64_t seq_id) {
return "HnswT" + ailego::StringHelper::ToString(type) + "S" +
ailego::StringHelper::ToString(seq_id);
}
private:
IndexStreamer::Stats &stats_;
HnswChunkMeta chunk_meta_{};
size_t page_mask_{0UL};
size_t max_chunks_size_{0UL};
IndexStorage::Pointer stg_{};
IndexStorage::Segment::Pointer chunk_meta_segment_{};
bool check_crc_{false};
bool dirty_{false}; // set as true if index is modified , the flag
// will not be cleared even if flushed
};
} // namespace core
} // namespace zvec
+296
View File
@@ -0,0 +1,296 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_context.h"
#include <chrono>
#include "hnsw_params.h"
namespace zvec {
namespace core {
HnswContext::HnswContext(size_t dimension, const IndexMetric::Pointer &metric,
const HnswEntity::Pointer &entity)
: IndexContext(metric),
entity_(entity),
dc_(entity_.get(), metric, dimension) {}
HnswContext::HnswContext(const IndexMetric::Pointer &metric,
const HnswEntity::Pointer &entity)
: IndexContext(metric), entity_(entity), dc_(entity_.get(), metric) {}
HnswContext::~HnswContext() {
visit_filter_.destroy();
}
int HnswContext::init(ContextType type) {
int ret;
uint32_t doc_cnt;
type_ = type;
switch (type) {
case kBuilderContext:
ret = visit_filter_.init(VisitFilter::ByteMap, entity_->doc_cnt(),
max_scan_num_, negative_probility_);
if (ret != 0) {
LOG_ERROR("Create filter failed, mode %d", filter_mode_);
return ret;
}
candidates_.limit(max_scan_num_);
update_heap_.limit(entity_->neighbor_cnt() + 1);
break;
case kSearcherContext:
ret = visit_filter_.init(filter_mode_, entity_->doc_cnt(), max_scan_num_,
negative_probility_);
if (ret != 0) {
LOG_ERROR("Create filter failed, mode %d", filter_mode_);
return ret;
}
candidates_.limit(max_scan_num_);
break;
case kStreamerContext:
// maxScanNum is unknown if inited from streamer, so the docCnt may
// change. we need to compute maxScanNum by scan ratio, and preserve
// max_doc_cnt space from visit filter
doc_cnt = entity_->doc_cnt();
max_scan_num_ = compute_max_scan_num(doc_cnt);
reserve_max_doc_cnt_ = doc_cnt + compute_reserve_cnt(doc_cnt);
ret = visit_filter_.init(filter_mode_, reserve_max_doc_cnt_,
max_scan_num_, negative_probility_);
if (ret != 0) {
LOG_ERROR("Create filter failed, mode %d", filter_mode_);
return ret;
}
update_heap_.limit(entity_->neighbor_cnt() + 1);
candidates_.limit(max_scan_num_);
check_need_adjuct_ctx();
break;
default:
LOG_ERROR("Init context failed");
return IndexError_Runtime;
}
return 0;
}
int HnswContext::update(const ailego::Params &params) {
auto update_visit_filter_param = [&]() {
bool need_update = false;
std::string p;
switch (type_) {
case kSearcherContext:
p = PARAM_HNSW_SEARCHER_VISIT_BLOOMFILTER_ENABLE;
break;
case kStreamerContext:
p = PARAM_HNSW_STREAMER_VISIT_BLOOMFILTER_ENABLE;
break;
}
if (params.has(p)) {
bool bf_enabled;
params.get(p, &bf_enabled);
if (bf_enabled ^ (filter_mode_ == VisitFilter::BloomFilter)) {
need_update = true;
filter_mode_ =
bf_enabled ? VisitFilter::BloomFilter : VisitFilter::ByteMap;
}
}
float prob = negative_probility_;
p.clear();
switch (type_) {
case kSearcherContext:
p = PARAM_HNSW_SEARCHER_VISIT_BLOOMFILTER_NEGATIVE_PROB;
break;
case kStreamerContext:
p = PARAM_HNSW_STREAMER_VISIT_BLOOMFILTER_NEGATIVE_PROB;
break;
}
params.get(p, &prob);
if (filter_mode_ == VisitFilter::BloomFilter &&
std::abs(prob - negative_probility_) > 1e-6) {
need_update = true;
}
if (need_update) {
visit_filter_.destroy();
int max_doc_cnt = 0;
if (type_ == kSearcherContext) {
max_doc_cnt = entity_->doc_cnt();
} else {
max_doc_cnt = reserve_max_doc_cnt_;
}
int ret = visit_filter_.init(filter_mode_, max_doc_cnt, max_scan_num_,
negative_probility_);
if (ret != 0) {
LOG_ERROR("Create filter failed, mode %d", filter_mode_);
return ret;
}
}
return 0;
};
switch (type_) {
case kSearcherContext:
if (params.has(PARAM_HNSW_SEARCHER_EF)) {
params.get(PARAM_HNSW_SEARCHER_EF, &ef_);
topk_heap_.limit(std::max(topk_, ef_));
}
if (params.has(PARAM_HNSW_SEARCHER_MAX_SCAN_RATIO)) {
params.get(PARAM_HNSW_SEARCHER_MAX_SCAN_RATIO, &max_scan_ratio_);
max_scan_num_ =
static_cast<uint32_t>(max_scan_ratio_ * entity_->doc_cnt());
max_scan_num_ = std::max(10000U, max_scan_num_);
}
if (params.has(PARAM_HNSW_SEARCHER_BRUTE_FORCE_THRESHOLD)) {
params.get(PARAM_HNSW_SEARCHER_BRUTE_FORCE_THRESHOLD,
&bruteforce_threshold_);
}
return update_visit_filter_param();
case kStreamerContext:
if (params.has(PARAM_HNSW_STREAMER_EF)) {
params.get(PARAM_HNSW_STREAMER_EF, &ef_);
topk_heap_.limit(std::max(topk_, ef_));
}
params.get(PARAM_HNSW_STREAMER_EF, &ef_);
params.get(PARAM_HNSW_STREAMER_MAX_SCAN_RATIO, &max_scan_ratio_);
params.get(PARAM_HNSW_STREAMER_MAX_SCAN_LIMIT, &max_scan_limit_);
params.get(PARAM_HNSW_STREAMER_MIN_SCAN_LIMIT, &min_scan_limit_);
if (max_scan_ratio_ <= 0.0f || max_scan_ratio_ > 1.0f) {
LOG_ERROR("[%s] must be in range (0.0f,1.0f]",
PARAM_HNSW_STREAMER_MAX_SCAN_RATIO.c_str());
return IndexError_InvalidArgument;
}
if (max_scan_limit_ < min_scan_limit_) {
LOG_ERROR("[%s] must be >= [%s]",
PARAM_HNSW_STREAMER_MAX_SCAN_LIMIT.c_str(),
PARAM_HNSW_STREAMER_MIN_SCAN_LIMIT.c_str());
return IndexError_InvalidArgument;
}
if (params.has(PARAM_HNSW_STREAMER_BRUTE_FORCE_THRESHOLD)) {
params.get(PARAM_HNSW_STREAMER_BRUTE_FORCE_THRESHOLD,
&bruteforce_threshold_);
}
return update_visit_filter_param();
default:
LOG_ERROR("update context failed, type=%u", type_);
return IndexError_Runtime;
}
}
int HnswContext::update_context(ContextType type, const IndexMeta &meta,
const IndexMetric::Pointer &metric,
const HnswEntity::Pointer &entity,
uint32_t magic_num) {
uint32_t doc_cnt;
if (ailego_unlikely(type != type_)) {
LOG_ERROR(
"HnswContext doesn't support shared by different type, "
"src=%u dst=%u",
type_, type);
return IndexError_Unsupported;
}
magic_ = kInvalidMgic;
// TODO: support change filter mode?
switch (type) {
case kBuilderContext:
LOG_ERROR("BuildContext doesn't support update");
return IndexError_NotImplemented;
case kSearcherContext:
if (!visit_filter_.reset(entity->doc_cnt(), max_scan_num_)) {
LOG_ERROR("Reset filter failed, mode %d", visit_filter_.get_mode());
return IndexError_Runtime;
}
candidates_.limit(max_scan_num_);
topk_heap_.limit(std::max(topk_, ef_));
break;
case kStreamerContext:
doc_cnt = entity->doc_cnt();
max_scan_num_ = compute_max_scan_num(doc_cnt);
reserve_max_doc_cnt_ = doc_cnt + compute_reserve_cnt(doc_cnt);
if (!visit_filter_.reset(reserve_max_doc_cnt_, max_scan_num_)) {
LOG_ERROR("Reset filter failed, mode %d", visit_filter_.get_mode());
return IndexError_Runtime;
}
update_heap_.limit(entity->neighbor_cnt() + 1);
candidates_.limit(max_scan_num_);
topk_heap_.limit(std::max(topk_, ef_));
break;
default:
LOG_ERROR("update context failed");
return IndexError_Runtime;
}
entity_ = entity;
dc_.update(entity_.get(), metric, meta.dimension());
magic_ = magic_num;
level_topks_.clear();
return 0;
}
void HnswContext::fill_random_to_topk_full(void) {
static std::mt19937 mt(
std::chrono::system_clock::now().time_since_epoch().count());
std::uniform_int_distribution<node_id_t> dt(0, entity_->doc_cnt() - 1);
std::function<node_id_t()> gen;
node_id_t seqid;
std::function<bool(node_id_t)> myfilter = [](node_id_t) { return false; };
if (this->filter().is_valid()) {
myfilter = [&](node_id_t id) {
return this->filter()(entity_->get_key(id));
};
}
if (topk_heap_.limit() < entity_->doc_cnt() / 2) {
gen = [&](void) { return dt(mt); };
} else {
// If topk limit is big value, gen sequential id from an random initial
seqid = dt(mt);
gen = [&](void) {
seqid = seqid == (entity_->doc_cnt() - 1) ? 0 : (seqid + 1);
return seqid;
};
}
for (size_t i = 0; !topk_heap_.full() && i < entity_->doc_cnt(); ++i) {
const auto id = gen();
if (!visit_filter_.visited(id) && !myfilter(id)) {
visit_filter_.set_visited(id);
topk_heap_.emplace(id, dc_.dist(id));
}
}
return;
}
} // namespace core
} // namespace zvec
+530
View File
@@ -0,0 +1,530 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "framework/index_context.h"
#include "utility/sparse_utility.h"
#include "utility/visit_filter.h"
#include "hnsw_dist_calculator.h"
#include "hnsw_entity.h"
namespace zvec {
namespace core {
class HnswContext : public IndexContext {
public:
//! Index Context Pointer
typedef std::unique_ptr<HnswContext> Pointer;
enum ContextType {
kUnknownContext = 0,
kSearcherContext = 1,
kBuilderContext = 2,
kStreamerContext = 3
};
//! Construct
HnswContext(size_t dimension, const IndexMetric::Pointer &metric,
const HnswEntity::Pointer &entity);
//! Construct
HnswContext(const IndexMetric::Pointer &metric,
const HnswEntity::Pointer &entity);
//! Destructor
virtual ~HnswContext();
public:
//! Set topk of search result
virtual void set_topk(uint32_t val) override {
topk_ = val;
topk_heap_.limit(std::max(val, ef_));
}
//! Retrieve search result
virtual const IndexDocumentList &result(void) const override {
return results_[0];
}
//! Retrieve search result
virtual const IndexDocumentList &result(size_t idx) const override {
return results_[idx];
}
//! Retrieve result object for output
virtual IndexDocumentList *mutable_result(size_t idx) override {
ailego_assert_with(idx < results_.size(), "invalid idx");
return &results_[idx];
}
//! Retrieve search group result with index
virtual const IndexGroupDocumentList &group_result(void) const override {
return group_results_[0];
}
//! Retrieve search group result with index
virtual const IndexGroupDocumentList &group_result(
size_t idx) const override {
return group_results_[idx];
}
virtual uint32_t magic(void) const override {
return magic_;
}
//! Set mode of debug
virtual void set_debug_mode(bool enable) override {
debug_mode_ = enable;
}
//! Retrieve mode of debug
virtual bool debug_mode(void) const override {
return this->debugging();
}
//! Retrieve string of debug
virtual std::string debug_string(void) const override {
char buf[4096];
size_t size = snprintf(
buf, sizeof(buf),
"scan_cnt=%zu,get_vector_cnt=%u,get_neighbors_cnt=%u,dup_node=%u",
get_scan_num(), stats_get_vector_cnt_, stats_get_neighbors_cnt_,
stats_visit_dup_cnt_);
return std::string(buf, size);
}
//! Update the parameters of context
virtual int update(const ailego::Params &params) override;
public:
//! Init context
int init(ContextType type);
//! Update context, the context may be shared by different searcher/streamer
int update_context(ContextType type, const IndexMeta &meta,
const IndexMetric::Pointer &metric,
const HnswEntity::Pointer &entity, uint32_t magic_num);
inline const HnswEntity &get_entity() const {
return *entity_;
}
inline void resize_results(size_t size) {
if (group_by_search()) {
group_results_.resize(size);
} else {
results_.resize(size);
}
}
inline void topk_to_result() {
return topk_to_result(0);
}
//! Construct result from topk heap, result will be normalized
inline void topk_to_result(uint32_t idx) {
if (group_by_search()) {
topk_to_group_result(idx);
} else {
topk_to_single_result(idx);
}
}
inline void recal_topk_dist() {
TopkHeap heap(topk_heap_);
topk_heap_.clear();
for (size_t i = 0; i < heap.size(); ++i) {
node_id_t id = heap[i].first;
dist_t dist = dc_.dist(id);
topk_heap_.emplace_back(id, dist);
}
}
inline void topk_to_single_result(uint32_t idx) {
if (force_padding_topk_ && !topk_heap_.full() &&
topk_heap_.size() < entity_->doc_cnt()) {
this->fill_random_to_topk_full();
}
if (ailego_unlikely(topk_heap_.size() == 0)) {
return;
}
ailego_assert_with(idx < results_.size(), "invalid idx");
int size = std::min(topk_, static_cast<uint32_t>(topk_heap_.size()));
topk_heap_.sort();
results_[idx].clear();
for (int i = 0; i < size; ++i) {
auto score = topk_heap_[i].second;
if (score > this->threshold()) {
break;
}
node_id_t id = topk_heap_[i].first;
if (fetch_vector_) {
results_[idx].emplace_back(entity_->get_key(id), score, id,
entity_->get_vector(id));
} else {
results_[idx].emplace_back(entity_->get_key(id), score, id);
}
}
return;
}
//! Construct result from topk heap, result will be normalized
inline void topk_to_group_result(uint32_t idx) {
ailego_assert_with(idx < group_results_.size(), "invalid idx");
group_results_[idx].clear();
std::vector<std::pair<std::string, TopkHeap>> group_topk_list;
std::vector<std::pair<std::string, float>> best_score_in_groups;
for (auto itr = group_topk_heaps_.begin(); itr != group_topk_heaps_.end();
itr++) {
const std::string &group_id = (*itr).first;
auto &heap = (*itr).second;
heap.sort();
if (heap.size() > 0) {
float best_score = heap[0].second;
best_score_in_groups.push_back(std::make_pair(group_id, best_score));
}
}
std::sort(best_score_in_groups.begin(), best_score_in_groups.end(),
[](const std::pair<std::string, float> &a,
const std::pair<std::string, float> &b) -> int {
return a.second < b.second;
});
// truncate to group num
for (uint32_t i = 0; i < group_num() && i < best_score_in_groups.size();
++i) {
const std::string &group_id = best_score_in_groups[i].first;
group_topk_list.emplace_back(
std::make_pair(group_id, group_topk_heaps_[group_id]));
}
group_results_[idx].resize(group_topk_list.size());
for (uint32_t i = 0; i < group_topk_list.size(); ++i) {
const std::string &group_id = group_topk_list[i].first;
group_results_[idx][i].set_group_id(group_id);
uint32_t size = std::min(
group_topk_, static_cast<uint32_t>(group_topk_list[i].second.size()));
for (uint32_t j = 0; j < size; ++j) {
auto score = group_topk_list[i].second[j].second;
if (score > this->threshold()) {
break;
}
node_id_t id = group_topk_list[i].second[j].first;
if (fetch_vector_) {
group_results_[idx][i].mutable_docs()->emplace_back(
entity_->get_key(id), score, id, entity_->get_vector(id));
} else {
group_results_[idx][i].mutable_docs()->emplace_back(
entity_->get_key(id), score, id);
}
}
}
}
inline void reset_query(const void *query) {
if (auto query_preprocess_func = index_metric_->get_query_preprocess_func();
query_preprocess_func != nullptr) {
size_t dim = dc_.dimension();
preprocess_buffer_.resize(dim);
memcpy(preprocess_buffer_.data(), query, dim);
query_preprocess_func(preprocess_buffer_.data(), dim);
query = preprocess_buffer_.data();
}
dc_.reset_query(query);
dc_.clear_compare_cnt();
}
inline HnswDistCalculator &dist_calculator() {
return dc_;
}
inline TopkHeap &topk_heap() {
return topk_heap_;
}
inline TopkHeap &update_heap() {
return update_heap_;
}
inline VisitFilter &visit_filter() {
return visit_filter_;
}
inline CandidateHeap &candidates() {
return candidates_;
}
inline void set_max_scan_num(uint32_t max_scan_num) {
max_scan_num_ = max_scan_num;
}
inline void set_max_scan_limit(uint32_t max_scan_limit) {
max_scan_limit_ = max_scan_limit;
}
inline void set_min_scan_limit(uint32_t min_scan_limit) {
min_scan_limit_ = min_scan_limit;
}
inline void set_ef(uint32_t v) {
ef_ = v;
}
inline void set_filter_mode(uint32_t v) {
filter_mode_ = v;
}
inline void set_filter_negative_probility(float v) {
negative_probility_ = v;
}
inline void set_max_scan_ratio(float v) {
max_scan_ratio_ = v;
}
virtual void set_magic(uint32_t v) {
magic_ = v;
}
virtual void set_force_padding_topk(bool v) {
force_padding_topk_ = v;
}
void set_bruteforce_threshold(uint32_t v) override {
bruteforce_threshold_ = v;
}
inline uint32_t get_bruteforce_threshold() const {
return bruteforce_threshold_;
}
void set_fetch_vector(bool v) override {
fetch_vector_ = v;
}
bool fetch_vector() const override {
return fetch_vector_;
}
//! Reset context
void reset(void) override {
set_filter(nullptr);
reset_threshold();
set_fetch_vector(false);
set_group_params(0, 0);
reset_group_by();
}
inline std::map<std::string, TopkHeap> &group_topk_heaps() {
return group_topk_heaps_;
}
inline TopkHeap &level_topk(int level) {
if (ailego_unlikely(level_topks_.size() <= static_cast<size_t>(level))) {
int cur_level = level_topks_.size();
level_topks_.resize(level + 1);
for (; cur_level <= level; ++cur_level) {
size_t heap_size = std::max(entity_->neighbor_cnt(cur_level),
entity_->ef_construction());
level_topks_[cur_level].clear();
level_topks_[cur_level].limit(heap_size);
}
}
return level_topks_[level];
}
inline void check_need_adjuct_ctx(void) {
check_need_adjuct_ctx(entity_->doc_cnt());
}
inline size_t compute_reserve_cnt(uint32_t cur_doc) const {
if (cur_doc > kMaxReserveDocCnt) {
return kMaxReserveDocCnt;
} else if (cur_doc < kMinReserveDocCnt) {
return kMinReserveDocCnt;
}
return cur_doc;
}
//! candidates heap and visitfilter need to resize as doc cnt growing up
inline void check_need_adjuct_ctx(uint32_t doc_cnt) {
if (ailego_unlikely(doc_cnt + kTriggerReserveCnt > reserve_max_doc_cnt_)) {
while (doc_cnt + kTriggerReserveCnt > reserve_max_doc_cnt_) {
reserve_max_doc_cnt_ =
reserve_max_doc_cnt_ + compute_reserve_cnt(reserve_max_doc_cnt_);
}
uint32_t max_scan_cnt = compute_max_scan_num(reserve_max_doc_cnt_);
max_scan_num_ = max_scan_cnt;
visit_filter_.reset(reserve_max_doc_cnt_, max_scan_cnt);
candidates_.clear();
candidates_.limit(max_scan_num_);
}
}
inline uint32_t compute_max_scan_num(uint32_t max_doc_cnt) const {
uint32_t max_scan = max_doc_cnt * max_scan_ratio_;
if (max_scan < min_scan_limit_) {
max_scan = min_scan_limit_;
} else if (max_scan > max_scan_limit_) {
max_scan = max_scan_limit_;
}
return max_scan;
}
inline size_t get_scan_num() const {
return dc_.compare_cnt();
}
inline uint64_t reach_scan_limit() const {
return dc_.compare_cnt() >= max_scan_num_;
}
inline bool error() const {
return dc_.error();
}
inline void clear() {
dc_.clear();
if (ailego_unlikely(this->debugging())) {
stats_get_neighbors_cnt_ = 0u;
stats_get_vector_cnt_ = 0u;
stats_visit_dup_cnt_ = 0u;
}
// do not clear results_ for the next query will need it
for (auto &it : results_) {
it.clear();
}
}
uint32_t *mutable_stats_get_neighbors() {
return &stats_get_neighbors_cnt_;
}
uint32_t *mutable_stats_get_vector() {
return &stats_get_vector_cnt_;
}
uint32_t *mutable_stats_visit_dup_cnt() {
return &stats_visit_dup_cnt_;
}
inline bool debugging(void) const {
return debug_mode_;
}
inline void update_dist_caculator_distance(
const IndexMetric::MatrixDistance &distance,
const IndexMetric::MatrixBatchDistance &batch_distance) {
dc_.update_distance(distance, batch_distance);
}
//! Get topk
inline uint32_t topk() const override {
return topk_;
}
//! Get group topk
inline uint32_t group_topk() const {
return group_topk_;
}
//! Get group num
inline uint32_t group_num() const {
return group_num_;
}
//! Get if group by search
inline bool group_by_search() {
return group_num_ > 0;
}
//! Set group params
void set_group_params(uint32_t group_num, uint32_t group_topk) override {
group_num_ = group_num;
group_topk_ = group_topk;
topk_ = group_topk_ * group_num_;
topk_heap_.limit(std::max(topk_, ef_));
group_topk_heaps_.clear();
}
private:
// Filling random nodes if topk not full
void fill_random_to_topk_full(void);
constexpr static uint32_t kTriggerReserveCnt = 4096UL;
constexpr static uint32_t kMinReserveDocCnt = 4096UL;
constexpr static uint32_t kMaxReserveDocCnt = 128 * 1024UL;
constexpr static uint32_t kInvalidMgic = -1U;
private:
HnswEntity::Pointer entity_;
HnswDistCalculator dc_;
IndexMetric::Pointer metric_;
bool debug_mode_{false};
bool force_padding_topk_{false};
uint32_t max_scan_num_{0};
uint32_t max_scan_limit_{0};
uint32_t min_scan_limit_{0};
uint32_t reserve_max_doc_cnt_{kMinReserveDocCnt};
uint32_t topk_{0};
uint32_t group_topk_{0};
uint32_t filter_mode_{VisitFilter::ByteMap};
float negative_probility_{HnswEntity::kDefaultBFNegativeProbility};
uint32_t ef_{HnswEntity::kDefaultEf};
float max_scan_ratio_{HnswEntity::kDefaultScanRatio};
uint32_t magic_{0U};
std::vector<IndexDocumentList> results_{};
std::vector<IndexGroupDocumentList> group_results_{};
TopkHeap topk_heap_{};
TopkHeap update_heap_{};
std::vector<TopkHeap> level_topks_{};
CandidateHeap candidates_{};
VisitFilter visit_filter_{};
uint32_t bruteforce_threshold_{};
bool fetch_vector_{false};
uint32_t group_num_{0};
std::map<std::string, TopkHeap> group_topk_heaps_{};
uint32_t type_{kUnknownContext};
//! debug stats info
uint32_t stats_get_neighbors_cnt_{0u};
uint32_t stats_get_vector_cnt_{0u};
uint32_t stats_visit_dup_cnt_{0u};
std::string preprocess_buffer_;
};
} // namespace core
} // namespace zvec
@@ -0,0 +1,218 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "framework/index_meta.h"
#include "hnsw_entity.h"
namespace zvec {
namespace core {
class HnswDistCalculator {
public:
typedef std::shared_ptr<HnswDistCalculator> Pointer;
public:
enum DistType {
DIST_NONE = 0,
DIST_DENSE = 1,
DIST_HYBRID = 2,
DIST_SPARSE = 3
};
public:
//! Constructor
HnswDistCalculator(const HnswEntity *entity,
const IndexMetric::Pointer &metric, uint32_t dim)
: entity_(entity),
distance_(metric->distance()),
batch_distance_(metric->batch_distance()),
query_(nullptr),
dim_(dim),
compare_cnt_(0) {}
//! Constructor
HnswDistCalculator(const HnswEntity *entity,
const IndexMetric::Pointer &metric, uint32_t dim,
const void *query)
: entity_(entity),
distance_(metric->distance()),
batch_distance_(metric->batch_distance()),
query_(query),
dim_(dim),
compare_cnt_(0) {}
//! Constructor
HnswDistCalculator(const HnswEntity *entity,
const IndexMetric::Pointer &metric)
: entity_(entity),
distance_(metric->distance()),
batch_distance_(metric->batch_distance()),
query_(nullptr),
dim_(0),
compare_cnt_(0) {}
void update(const HnswEntity *entity, const IndexMetric::Pointer &metric) {
entity_ = entity;
distance_ = metric->distance();
batch_distance_ = metric->batch_distance();
}
void update(const HnswEntity *entity, const IndexMetric::Pointer &metric,
uint32_t dim) {
entity_ = entity;
distance_ = metric->distance();
batch_distance_ = metric->batch_distance();
dim_ = dim;
}
inline void update_distance(
const IndexMetric::MatrixDistance &distance,
const IndexMetric::MatrixBatchDistance &batch_distance) {
distance_ = distance;
batch_distance_ = batch_distance;
}
//! Reset query vector data
inline void reset_query(const void *query) {
error_ = false;
query_ = query;
}
//! Returns distance
inline dist_t dist(const void *vec_lhs, const void *vec_rhs) {
if (ailego_unlikely(vec_lhs == nullptr || vec_rhs == nullptr)) {
LOG_ERROR("Nullptr of dense vector");
error_ = true;
return 0.0f;
}
float score{0.0f};
distance_(vec_lhs, vec_rhs, dim_, &score);
return score;
}
//! Returns distance between query and vec.
inline dist_t dist(const void *vec) {
compare_cnt_++;
return dist(vec, query_);
}
//! Return distance between query and node id.
inline dist_t dist(node_id_t id) {
compare_cnt_++;
const void *feat = entity_->get_vector(id);
if (ailego_unlikely(feat == nullptr)) {
LOG_ERROR("Get nullptr vector, id=%u", id);
error_ = true;
return 0.0f;
}
return dist(feat, query_);
}
//! Return dist node lhs between node rhs
inline dist_t dist(node_id_t lhs, node_id_t rhs) {
compare_cnt_++;
const void *feat = entity_->get_vector(lhs);
const void *query = entity_->get_vector(rhs);
if (ailego_unlikely(feat == nullptr || query == nullptr)) {
LOG_ERROR("Get nullptr vector");
error_ = true;
return 0.0f;
}
return dist(feat, query);
}
dist_t operator()(const void *vec) {
return dist(vec);
}
dist_t operator()(id_t i) {
return dist(i);
}
dist_t operator()(id_t lhs, id_t rhs) {
return dist(lhs, rhs);
}
void batch_dist(const void **vecs, size_t num, dist_t *distances) {
compare_cnt_++;
batch_distance_(vecs, query_, num, dim_, distances);
}
inline dist_t batch_dist(node_id_t id) {
compare_cnt_++;
const void *feat = entity_->get_vector(id);
if (ailego_unlikely(feat == nullptr)) {
LOG_ERROR("Get nullptr vector, id=%u", id);
error_ = true;
return 0.0f;
}
dist_t score = 0;
batch_distance_(&feat, query_, 1, dim_, &score);
return score;
}
inline void clear() {
compare_cnt_ = 0;
error_ = false;
}
inline void clear_compare_cnt() {
compare_cnt_ = 0;
}
inline bool error() const {
return error_;
}
//! Get distances compute times
inline uint32_t compare_cnt() const {
return compare_cnt_;
}
inline uint32_t dimension() const {
return dim_;
}
private:
HnswDistCalculator(const HnswDistCalculator &) = delete;
HnswDistCalculator &operator=(const HnswDistCalculator &) = delete;
private:
const HnswEntity *entity_;
IndexMetric::MatrixDistance distance_;
IndexMetric::MatrixBatchDistance batch_distance_;
const void *query_;
uint32_t dim_;
uint32_t compare_cnt_; // record distance compute times
uint32_t compare_cnt_batch_; // record batch distance compute time
bool error_{false};
};
} // namespace core
} // namespace zvec
+362
View File
@@ -0,0 +1,362 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_entity.h"
#include "framework/index_stats.h"
#include "utility/sparse_utility.h"
namespace zvec {
namespace core {
const std::string HnswEntity::kGraphHeaderSegmentId = "graph.header";
const std::string HnswEntity::kGraphFeaturesSegmentId = "graph.features";
const std::string HnswEntity::kGraphKeysSegmentId = "graph.keys";
const std::string HnswEntity::kGraphNeighborsSegmentId = "graph.neighbors";
const std::string HnswEntity::kGraphOffsetsSegmentId = "graph.offsets";
const std::string HnswEntity::kGraphMappingSegmentId = "graph.mapping";
const std::string HnswEntity::kHnswHeaderSegmentId = "hnsw.header";
const std::string HnswEntity::kHnswNeighborsSegmentId = "hnsw.neighbors";
const std::string HnswEntity::kHnswOffsetsSegmentId = "hnsw.offsets";
int HnswEntity::CalcAndAddPadding(const IndexDumper::Pointer &dumper,
size_t data_size, size_t *padding_size) {
*padding_size = AlignSize(data_size) - data_size;
if (*padding_size == 0) {
return 0;
}
std::string padding(*padding_size, '\0');
if (dumper->write(padding.data(), *padding_size) != *padding_size) {
LOG_ERROR("Append padding failed, size %lu", *padding_size);
return IndexError_WriteData;
}
return 0;
}
int64_t HnswEntity::dump_segment(const IndexDumper::Pointer &dumper,
const std::string &segment_id,
const void *data, size_t size) const {
size_t len = dumper->write(data, size);
if (len != size) {
LOG_ERROR("Dump segment %s data failed, expect: %lu, actual: %lu",
segment_id.c_str(), size, len);
return IndexError_WriteData;
}
size_t padding_size = AlignSize(size) - size;
if (padding_size > 0) {
std::string padding(padding_size, '\0');
if (dumper->write(padding.data(), padding_size) != padding_size) {
LOG_ERROR("Append padding failed, size %lu", padding_size);
return IndexError_WriteData;
}
}
uint32_t crc = ailego::Crc32c::Hash(data, size);
int ret = dumper->append(segment_id, size, padding_size, crc);
if (ret != 0) {
LOG_ERROR("Dump segment %s meta failed, ret=%d", segment_id.c_str(), ret);
return ret;
}
return len + padding_size;
}
int64_t HnswEntity::dump_header(const IndexDumper::Pointer &dumper,
const HNSWHeader &hd) const {
//! dump basic graph header. header is aligned and does not need padding
int64_t graph_hd_size =
dump_segment(dumper, kGraphHeaderSegmentId, &hd.graph, hd.graph.size);
if (graph_hd_size < 0) {
return graph_hd_size;
}
//! dump basic graph header. header is aligned and does not need padding
int64_t hnsw_hd_size =
dump_segment(dumper, kHnswHeaderSegmentId, &hd.hnsw, hd.hnsw.size);
if (hnsw_hd_size < 0) {
return hnsw_hd_size;
}
return graph_hd_size + hnsw_hd_size;
}
void HnswEntity::reshuffle_vectors(
const std::function<level_t(node_id_t)> & /*get_level*/,
std::vector<node_id_t> * /*n2o_mapping*/,
std::vector<node_id_t> * /*o2n_mapping*/, key_t * /*keys*/) const {
// TODO
return;
}
int64_t HnswEntity::dump_mapping_segment(const IndexDumper::Pointer &dumper,
const key_t *keys) const {
std::vector<node_id_t> mapping(doc_cnt());
std::iota(mapping.begin(), mapping.end(), 0U);
std::sort(mapping.begin(), mapping.end(),
[&](node_id_t i, node_id_t j) { return keys[i] < keys[j]; });
size_t size = mapping.size() * sizeof(node_id_t);
return dump_segment(dumper, kGraphMappingSegmentId, mapping.data(), size);
}
int64_t HnswEntity::dump_segments(
const IndexDumper::Pointer &dumper, key_t *keys,
const std::function<level_t(node_id_t)> &get_level) const {
HNSWHeader dump_hd(header());
dump_hd.graph.node_size = AlignSize(vector_size());
std::vector<node_id_t> n2o_mapping; // map new id to origin id
std::vector<node_id_t> o2n_mapping; // map origin id to new id
reshuffle_vectors(get_level, &n2o_mapping, &o2n_mapping, keys);
if (!o2n_mapping.empty()) {
dump_hd.hnsw.entry_point = o2n_mapping[entry_point()];
}
//! Dump header
int64_t hd_size = dump_header(dumper, dump_hd);
if (hd_size < 0) {
return hd_size;
}
//! Dump vectors
int64_t vecs_size = dump_vectors(dumper, n2o_mapping);
if (vecs_size < 0) {
return vecs_size;
}
//! Dump neighbors
auto neighbors_size =
dump_neighbors(dumper, get_level, n2o_mapping, o2n_mapping);
if (neighbors_size < 0) {
return neighbors_size;
}
//! free memory
n2o_mapping = std::vector<node_id_t>();
o2n_mapping = std::vector<node_id_t>();
//! Dump keys
size_t key_segment_size = doc_cnt() * sizeof(key_t);
int64_t keys_size =
dump_segment(dumper, kGraphKeysSegmentId, keys, key_segment_size);
if (keys_size < 0) {
return keys_size;
}
//! Dump mapping
int64_t mapping_size = dump_mapping_segment(dumper, keys);
if (mapping_size < 0) {
return mapping_size;
}
return hd_size + keys_size + vecs_size + neighbors_size + mapping_size;
}
int64_t HnswEntity::dump_vectors(
const IndexDumper::Pointer &dumper,
const std::vector<node_id_t> &reorder_mapping) const {
size_t vector_dump_size = vector_size();
size_t padding_size = AlignSize(vector_dump_size) - vector_dump_size;
char padding[padding_size];
memset(padding, 0, sizeof(padding));
const void *data = nullptr;
uint32_t crc = 0U;
size_t vecs_size = 0UL;
//! dump vectors
for (node_id_t id = 0; id < doc_cnt(); ++id) {
data = get_vector(reorder_mapping.empty() ? id : reorder_mapping[id]);
if (ailego_unlikely(!data)) {
return IndexError_ReadData;
}
size_t len = dumper->write(data, vector_size());
if (len != vector_size()) {
LOG_ERROR("Dump vectors failed, write=%zu expect=%zu", len,
vector_size());
return IndexError_WriteData;
}
crc = ailego::Crc32c::Hash(data, vector_size(), crc);
vecs_size += vector_size();
if (padding_size == 0) {
continue;
}
len = dumper->write(padding, padding_size);
if (len != padding_size) {
LOG_ERROR("Dump vectors failed, write=%zu expect=%zu", len, padding_size);
return IndexError_WriteData;
}
crc = ailego::Crc32c::Hash(padding, padding_size, crc);
vecs_size += padding_size;
}
int ret = dumper->append(kGraphFeaturesSegmentId, vecs_size, 0UL, crc);
if (ret != 0) {
LOG_ERROR("Dump vectors segment meta failed, ret %d", ret);
return ret;
}
return vecs_size;
}
int64_t HnswEntity::dump_graph_neighbors(
const IndexDumper::Pointer &dumper,
const std::vector<node_id_t> &reorder_mapping,
const std::vector<node_id_t> &neighbor_mapping) const {
std::vector<GraphNeighborMeta> graph_meta;
graph_meta.reserve(doc_cnt());
size_t offset = 0;
uint32_t crc = 0;
node_id_t mapping[neighbor_cnt()];
uint32_t min_neighbor_count = 10000;
uint32_t max_neighbor_count = 0;
size_t sum_neighbor_count = 0;
for (node_id_t id = 0; id < doc_cnt(); ++id) {
const Neighbors neighbors =
get_neighbors(0, reorder_mapping.empty() ? id : reorder_mapping[id]);
ailego_assert_with(!!neighbors.data, "invalid neighbors");
ailego_assert_with(neighbors.size() <= neighbor_cnt(), "invalid neighbors");
uint32_t neighbor_count = neighbors.size();
if (neighbor_count < min_neighbor_count) {
min_neighbor_count = neighbor_count;
}
if (neighbor_count > max_neighbor_count) {
max_neighbor_count = neighbor_count;
}
sum_neighbor_count += neighbor_count;
graph_meta.emplace_back(offset, neighbor_count);
size_t size = neighbors.size() * sizeof(node_id_t);
const node_id_t *data = &neighbors[0];
if (!neighbor_mapping.empty()) {
for (node_id_t i = 0; i < neighbors.size(); ++i) {
mapping[i] = neighbor_mapping[neighbors[i]];
}
data = mapping;
}
if (dumper->write(data, size) != size) {
LOG_ERROR("Dump graph neighbor id=%u failed, size %lu", id, size);
return IndexError_WriteData;
}
crc = ailego::Crc32c::Hash(data, size, crc);
offset += size;
}
uint32_t average_neighbor_count = 0;
if (doc_cnt() > 0) {
average_neighbor_count = sum_neighbor_count / doc_cnt();
}
LOG_INFO(
"Dump hnsw graph: min_neighbor_count[%u] max_neighbor_count[%u] "
"average_neighbor_count[%u]",
min_neighbor_count, max_neighbor_count, average_neighbor_count);
size_t padding_size = 0;
int ret = CalcAndAddPadding(dumper, offset, &padding_size);
if (ret != 0) {
return ret;
}
ret = dumper->append(kGraphNeighborsSegmentId, offset, padding_size, crc);
if (ret != 0) {
LOG_ERROR("Dump segment %s failed, ret %d",
kGraphNeighborsSegmentId.c_str(), ret);
return ret;
}
//! dump level 0 neighbors meta
auto len = dump_segment(dumper, kGraphOffsetsSegmentId, graph_meta.data(),
graph_meta.size() * sizeof(GraphNeighborMeta));
if (len < 0) {
return len;
}
return len + offset + padding_size;
}
int64_t HnswEntity::dump_upper_neighbors(
const IndexDumper::Pointer &dumper,
const std::function<level_t(node_id_t)> &get_level,
const std::vector<node_id_t> &reorder_mapping,
const std::vector<node_id_t> &neighbor_mapping) const {
std::vector<HnswNeighborMeta> hnsw_meta;
hnsw_meta.reserve(doc_cnt());
size_t offset = 0;
uint32_t crc = 0;
node_id_t buffer[upper_neighbor_cnt() + 1];
for (node_id_t id = 0; id < doc_cnt(); ++id) {
node_id_t new_id = reorder_mapping.empty() ? id : reorder_mapping[id];
auto level = get_level(new_id);
if (level == 0) {
hnsw_meta.emplace_back(0U, 0U);
continue;
}
hnsw_meta.emplace_back(offset, level);
ailego_assert_with((size_t)level < kMaxGraphLayers, "invalid level");
for (level_t cur_level = 1; cur_level <= level; ++cur_level) {
const Neighbors neighbors = get_neighbors(cur_level, new_id);
ailego_assert_with(!!neighbors.data, "invalid neighbors");
ailego_assert_with(neighbors.size() <= neighbor_cnt(cur_level),
"invalid neighbors");
memset(buffer, 0, sizeof(buffer));
buffer[0] = neighbors.size();
if (neighbor_mapping.empty()) {
memcpy(&buffer[1], &neighbors[0], neighbors.size() * sizeof(node_id_t));
} else {
for (node_id_t i = 0; i < neighbors.size(); ++i) {
buffer[i + 1] = neighbor_mapping[neighbors[i]];
}
}
if (dumper->write(buffer, sizeof(buffer)) != sizeof(buffer)) {
LOG_ERROR("Dump graph neighbor id=%u failed, size %lu", id,
sizeof(buffer));
return IndexError_WriteData;
}
crc = ailego::Crc32c::Hash(buffer, sizeof(buffer), crc);
offset += sizeof(buffer);
}
}
size_t padding_size = 0;
int ret = CalcAndAddPadding(dumper, offset, &padding_size);
if (ret != 0) {
return ret;
}
ret = dumper->append(kHnswNeighborsSegmentId, offset, padding_size, crc);
if (ret != 0) {
LOG_ERROR("Dump segment %s failed, ret %d", kHnswNeighborsSegmentId.c_str(),
ret);
return ret;
}
//! dump level 0 neighbors meta
auto len = dump_segment(dumper, kHnswOffsetsSegmentId, hnsw_meta.data(),
hnsw_meta.size() * sizeof(HnswNeighborMeta));
if (len < 0) {
return len;
}
return len + offset + padding_size;
}
} // namespace core
} // namespace zvec
+527
View File
@@ -0,0 +1,527 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <string.h>
#include <ailego/container/heap.h>
#include <ailego/utility/memory_helper.h>
#include "ailego/logger/logger.h"
#include "framework/index_dumper.h"
#include "framework/index_error.h"
#include "framework/index_storage.h"
namespace zvec {
namespace core {
using node_id_t = uint32_t;
using key_t = uint64_t;
using level_t = int32_t;
using dist_t = float;
using TopkHeap = ailego::KeyValueHeap<node_id_t, dist_t>;
using CandidateHeap =
ailego::KeyValueHeap<node_id_t, dist_t, std::greater<dist_t>>;
constexpr node_id_t kInvalidNodeId = static_cast<node_id_t>(-1);
constexpr key_t kInvalidKey = static_cast<key_t>(-1);
class DistCalculator;
struct GraphHeader {
uint32_t size;
uint32_t version;
uint32_t graph_type;
uint32_t doc_count;
uint32_t vector_size;
uint32_t node_size;
uint32_t max_neighbor_count;
uint32_t prune_type;
uint32_t prune_neighbor_count;
uint32_t ef_construction;
uint32_t options;
uint32_t min_neighbor_count;
uint8_t reserved_[4080];
};
static_assert(sizeof(GraphHeader) % 32 == 0,
"GraphHeader must be aligned with 32 bytes");
//! Hnsw upper neighbor header
struct HnswHeader {
uint32_t size; // header size
uint32_t revision; // current total docs of the graph
uint32_t thumb_neighbor_count;
uint32_t ef_construction;
uint32_t scaling_factor;
uint32_t max_level;
uint32_t entry_point;
uint32_t options;
uint8_t reserved_[30];
};
static_assert(sizeof(HnswHeader) % 32 == 0,
"GraphHeader must be aligned with 32 bytes");
//! Hnsw common header and upper neighbor header
struct HNSWHeader {
HNSWHeader() {
clear();
}
HNSWHeader(const HNSWHeader &header) {
memcpy(this, &header, sizeof(header));
}
HNSWHeader &operator=(const HNSWHeader &header) {
memcpy(this, &header, sizeof(header));
return *this;
}
//! Reset state to zero, and the params is untouched
void inline reset() {
graph.doc_count = 0U;
hnsw.entry_point = kInvalidNodeId;
hnsw.max_level = 0;
}
//! Clear all fields to init value
void inline clear() {
memset(this, 0, sizeof(HNSWHeader));
hnsw.entry_point = kInvalidNodeId;
graph.size = sizeof(GraphHeader);
hnsw.size = sizeof(HnswHeader);
}
size_t neighbor_cnt() const {
return graph.max_neighbor_count;
}
size_t upper_neighbor_cnt() const {
return hnsw.thumb_neighbor_count;
}
size_t vector_size() const {
return graph.vector_size;
}
size_t ef_construction() const {
return graph.ef_construction;
}
size_t scaling_factor() const {
return hnsw.scaling_factor;
}
size_t neighbor_prune_cnt() const {
return graph.prune_neighbor_count;
}
node_id_t entry_point() const {
return hnsw.entry_point;
}
node_id_t doc_cnt() const {
return graph.doc_count;
}
GraphHeader graph;
HnswHeader hnsw;
};
struct NeighborsHeader {
uint32_t neighbor_cnt;
node_id_t neighbors[0];
};
struct Neighbors {
Neighbors() : cnt{0}, data{nullptr} {}
Neighbors(uint32_t cnt_in, const node_id_t *data_in)
: cnt{cnt_in}, data{data_in} {}
Neighbors(IndexStorage::MemoryBlock &&mem_block)
: neighbor_block{std::move(mem_block)} {
auto hd = reinterpret_cast<const NeighborsHeader *>(neighbor_block.data());
cnt = hd->neighbor_cnt;
data = hd->neighbors;
}
size_t size(void) const {
return cnt;
}
const node_id_t &operator[](size_t idx) const {
return data[idx];
}
uint32_t cnt;
const node_id_t *data;
IndexStorage::MemoryBlock neighbor_block;
};
//! level 0 neighbors offset
struct GraphNeighborMeta {
GraphNeighborMeta(size_t o, size_t cnt) : offset(o), neighbor_cnt(cnt) {}
uint64_t offset : 48;
uint64_t neighbor_cnt : 16;
};
//! hnsw upper neighbors meta
struct HnswNeighborMeta {
HnswNeighborMeta(size_t o, size_t l) : offset(o), level(l) {}
uint64_t offset : 48; // offset = idx * upper neighors size
uint64_t level : 16;
};
class HnswEntity {
public:
//! Constructor
HnswEntity() {}
//! Constructor
HnswEntity(const HNSWHeader &hd) {
header_ = hd;
}
//! Destructor
virtual ~HnswEntity() {}
//! HnswEntity Pointerd;
typedef std::shared_ptr<HnswEntity> Pointer;
//! Get max neighbor size of graph level
inline size_t neighbor_cnt(level_t level) const {
return level == 0 ? header_.graph.max_neighbor_count
: header_.hnsw.thumb_neighbor_count;
}
//! get max neighbor size of graph level 0
inline size_t neighbor_cnt() const {
return header_.graph.max_neighbor_count;
}
//! get min neighbor size of graph
inline size_t min_neighbor_cnt() const {
return header_.graph.min_neighbor_count;
}
//! get upper neighbor size of graph level other than 0
inline size_t upper_neighbor_cnt() const {
return header_.hnsw.thumb_neighbor_count;
}
//! Get current total doc of the hnsw graph
inline node_id_t *mutable_doc_cnt() {
return &header_.graph.doc_count;
}
inline node_id_t doc_cnt() const {
return header_.graph.doc_count;
}
//! Get hnsw graph scaling params
inline size_t scaling_factor() const {
return header_.hnsw.scaling_factor;
}
//! Get prune_size
inline size_t prune_cnt() const {
return header_.graph.prune_neighbor_count;
}
//! Current entity of top level graph
inline node_id_t entry_point() const {
return header_.hnsw.entry_point;
}
//! Current max graph level
inline level_t cur_max_level() const {
return header_.hnsw.max_level;
}
//! Retrieve index vector size
size_t vector_size() const {
return header_.graph.vector_size;
}
//! Retrieve node size
size_t node_size() const {
return header_.graph.node_size;
}
//! Retrieve ef constuction
size_t ef_construction() const {
return header_.graph.ef_construction;
}
void set_vector_size(size_t size) {
header_.graph.vector_size = size;
}
void set_prune_cnt(size_t v) {
header_.graph.prune_neighbor_count = v;
}
void set_scaling_factor(size_t val) {
header_.hnsw.scaling_factor = val;
}
void set_neighbor_cnt(size_t cnt) {
header_.graph.max_neighbor_count = cnt;
}
void set_min_neighbor_cnt(size_t cnt) {
header_.graph.min_neighbor_count = cnt;
}
void set_upper_neighbor_cnt(size_t cnt) {
header_.hnsw.thumb_neighbor_count = cnt;
}
void set_ef_construction(size_t ef) {
header_.graph.ef_construction = ef;
}
protected:
inline const HNSWHeader &header() const {
return header_;
}
inline HNSWHeader *mutable_header() {
return &header_;
}
inline size_t header_size() const {
return sizeof(header_);
}
void set_node_size(size_t size) {
header_.graph.node_size = size;
}
//! Dump all segment by dumper
//! Return dump size if success, errno(<0) in failure
int64_t dump_segments(
const IndexDumper::Pointer &dumper, key_t *keys,
const std::function<level_t(node_id_t)> &get_level) const;
private:
//! dump mapping segment, for get_vector_by_key in provider
int64_t dump_mapping_segment(const IndexDumper::Pointer &dumper,
const key_t *keys) const;
//! dump hnsw head by dumper
//! Return dump size if success, errno(<0) in failure
int64_t dump_header(const IndexDumper::Pointer &dumper,
const HNSWHeader &hd) const;
//! dump vectors by dumper
//! Return dump size if success, errno(<0) in failure
int64_t dump_vectors(const IndexDumper::Pointer &dumper,
const std::vector<node_id_t> &reorder_mapping) const;
//! dump hnsw neighbors by dumper
//! Return dump size if success, errno(<0) in failure
int64_t dump_neighbors(const IndexDumper::Pointer &dumper,
const std::function<level_t(node_id_t)> &get_level,
const std::vector<node_id_t> &reorder_mapping,
const std::vector<node_id_t> &neighbor_mapping) const {
auto len1 = dump_graph_neighbors(dumper, reorder_mapping, neighbor_mapping);
if (len1 < 0) {
return len1;
}
auto len2 = dump_upper_neighbors(dumper, get_level, reorder_mapping,
neighbor_mapping);
if (len2 < 0) {
return len2;
}
return len1 + len2;
}
//! dump segment by dumper
//! Return dump size if success, errno(<0) in failure
int64_t dump_segment(const IndexDumper::Pointer &dumper,
const std::string &segment_id, const void *data,
size_t size) const;
//! Dump level 0 neighbors
//! Return dump size if success, errno(<0) in failure
int64_t dump_graph_neighbors(
const IndexDumper::Pointer &dumper,
const std::vector<node_id_t> &reorder_mapping,
const std::vector<node_id_t> &neighbor_mapping) const;
//! Dump upper level neighbors
//! Return dump size if success, errno(<0) in failure
int64_t dump_upper_neighbors(
const IndexDumper::Pointer &dumper,
const std::function<level_t(node_id_t)> &get_level,
const std::vector<node_id_t> &reorder_mapping,
const std::vector<node_id_t> &neighbor_mapping) const;
public:
//! Cleanup the entity
virtual int cleanup(void) {
header_.clear();
return 0;
}
//! Make a copy of searcher entity, to support thread-safe operation.
//! The segment in container cannot be read concurrenly
virtual const HnswEntity::Pointer clone() const {
LOG_ERROR("Update neighbors not implemented");
return HnswEntity::Pointer();
}
//! Get primary key of the node id
virtual key_t get_key(node_id_t id) const = 0;
//! Get vector feature data by key
virtual const void *get_vector(node_id_t id) const = 0;
//! Get vectors feature data by keys
virtual int get_vector(const node_id_t *ids, uint32_t count,
const void **vecs) const = 0;
virtual int get_vector(const node_id_t id,
IndexStorage::MemoryBlock &block) const = 0;
virtual int get_vector(
const node_id_t *ids, uint32_t count,
std::vector<IndexStorage::MemoryBlock> &vec_blocks) const = 0;
//! Retrieve a vector using a primary key
virtual const void *get_vector_by_key(uint64_t /*key*/) const {
LOG_ERROR("get vector not implemented");
return nullptr;
}
virtual int get_vector_by_key(const key_t /*key*/,
IndexStorage::MemoryBlock & /*block*/) const {
return IndexError_NotImplemented;
}
//! Get the node id's neighbors on graph level
//! Note: the neighbors cannot be modified, using the following
//! method to get WritableNeighbors if want to
virtual const Neighbors get_neighbors(level_t level, node_id_t id) const = 0;
//! Add vector and key to hnsw entity, and local id will be saved in id
virtual int add_vector(level_t /*level*/, key_t /*key*/, const void * /*vec*/,
node_id_t * /*id*/) {
return IndexError_NotImplemented;
}
//! Add vector and id to hnsw entity
virtual int add_vector_with_id(level_t /*level*/, node_id_t /*id*/,
const void * /*vec*/) {
return IndexError_NotImplemented;
}
virtual int update_neighbors(
level_t /*level*/, node_id_t /*id*/,
const std::vector<std::pair<node_id_t, dist_t>> & /*neighbors*/) {
LOG_ERROR("Update neighbors dense not implemented");
return 0;
}
//! Append neighbor_id to node id neighbors on level, size is the current
//! neighbors size. Notice: the caller must be ensure the neighbors not full
virtual void add_neighbor(level_t /*level*/, node_id_t /*id*/,
uint32_t /*size*/, node_id_t /*neighbor_id*/) {
LOG_ERROR("Add neighbor not implemented");
}
//! Update entry point and max level
virtual void update_ep_and_level(node_id_t ep, level_t level) {
header_.hnsw.entry_point = ep;
header_.hnsw.max_level = level;
}
virtual int load(const IndexStorage::Pointer & /*container*/,
bool /*check_crc*/) {
LOG_ERROR("Load not implemented");
return IndexError_NotImplemented;
}
virtual int dump(const IndexDumper::Pointer & /*dumper*/) {
LOG_ERROR("Dump not implemented");
return IndexError_NotImplemented;
}
static int CalcAndAddPadding(const IndexDumper::Pointer &dumper,
size_t data_size, size_t *padding_size);
protected:
static inline size_t AlignSize(size_t size) {
return (size + 0x1F) & (~0x1F);
}
static inline size_t AlignPageSize(size_t size) {
size_t page_mask = ailego::MemoryHelper::PageSize() - 1;
return (size + page_mask) & (~page_mask);
}
static inline size_t AlignHugePageSize(size_t size) {
size_t page_mask = ailego::MemoryHelper::HugePageSize() - 1;
return (size + page_mask) & (~page_mask);
}
//! rearrange vectors to improve cache locality
void reshuffle_vectors(const std::function<level_t(node_id_t)> &get_level,
std::vector<node_id_t> *n2o_mapping,
std::vector<node_id_t> *o2n_mapping,
key_t *keys) const;
public:
const static std::string kGraphHeaderSegmentId;
const static std::string kGraphFeaturesSegmentId;
const static std::string kGraphKeysSegmentId;
const static std::string kGraphNeighborsSegmentId;
const static std::string kGraphOffsetsSegmentId;
const static std::string kGraphMappingSegmentId;
const static std::string kHnswHeaderSegmentId;
const static std::string kHnswNeighborsSegmentId;
const static std::string kHnswOffsetsSegmentId;
constexpr static uint32_t kRevision = 0U;
constexpr static size_t kMaxGraphLayers = 15;
constexpr static uint32_t kDefaultEfConstruction = 500;
constexpr static uint32_t kDefaultEf = 500;
constexpr static uint32_t kDefaultNeighborCnt = 100;
constexpr static uint32_t kDefaultUpperNeighborCnt = 50;
constexpr static uint32_t kMaxNeighborCnt = 65535;
constexpr static float kDefaultScanRatio = 0.1f;
constexpr static uint32_t kDefaultMinScanLimit = 10000;
constexpr static uint32_t kDefaultMaxScanLimit =
std::numeric_limits<uint32_t>::max();
constexpr static float kDefaultBFNegativeProbility = 0.001f;
constexpr static uint32_t kDefaultScalingFactor = 50U;
constexpr static uint32_t kDefaultBruteForceThreshold = 1000U;
constexpr static uint32_t kDefaultDocsHardLimit = 1 << 30U; // 1 billion
constexpr static float kDefaultDocsSoftLimitRatio = 0.9f;
constexpr static size_t kMaxChunkSize = 0xFFFFFFFF;
constexpr static size_t kDefaultChunkSize = 2UL * 1024UL * 1024UL;
constexpr static size_t kDefaultMaxChunkCnt = 50000UL;
constexpr static float kDefaultNeighborPruneRatio =
0.5f; // prune count / neighbor count
constexpr static float kDefaultUpperNeighborRatio =
0.5f; // upper neighbor count / neighbor count
protected:
HNSWHeader header_{};
};
} // namespace core
} // namespace zvec
+231
View File
@@ -0,0 +1,231 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "hnsw_chunk.h"
namespace zvec {
namespace core {
//! Persistent hashmap implement through open addressing algorithm
template <class Key, class Val, Val EmptyVal = 0U,
typename =
typename std::enable_if<std::is_integral<Key>::value>::type>
class HnswIndexHashMap {
using key_type = Key;
using val_type = Val;
struct Iterator {
key_type first;
val_type second;
};
typedef Iterator *iterator;
typedef Iterator Item;
typedef const Iterator *const_iterator;
class Slot {
public:
Slot(Chunk::Pointer &&chunk, const void *data)
: chunk_(std::move(chunk)),
items_(reinterpret_cast<const Item *>(data)) {}
//! Return a empty loc or the key item loc
Slot(Chunk::Pointer &&chunk, IndexStorage::MemoryBlock &&mem_block)
: chunk_(std::move(chunk)), items_block_(std::move(mem_block)) {
items_ = reinterpret_cast<const Item *>(items_block_.data());
}
const_iterator find(key_type key, uint32_t max_items, uint32_t mask) const {
auto it = &items_[key & mask];
for (auto i = 0U; i < max_items; ++i) {
if (it->first == key || it->second == EmptyVal) {
// LOG_DEBUG("i=%u", i);
return it;
}
++it;
if (it == &items_[max_items]) {
it = &items_[0];
}
}
return nullptr;
}
bool update(const_iterator it) {
uint32_t offset = reinterpret_cast<const uint8_t *>(it) -
reinterpret_cast<const uint8_t *>(&items_[0]);
if (ailego_unlikely(chunk_->write(offset, it, sizeof(Item)) !=
sizeof(Item))) {
LOG_ERROR("Chunk write failed");
return false;
}
return true;
}
private:
Chunk::Pointer chunk_{};
const Item *items_{nullptr}; // point to chunk data
IndexStorage::MemoryBlock items_block_{};
};
public:
//! Init the hash
//! broker the index allocator
//! chunk_size the size of per chunk allocated, actual size may greater
//! factor factor = 1/ratio, ratio is the probability of a squence
//! number inserted to this container
//! max the max number key can be inserted
//! expansion_ratio memory expansion ratio
int init(ChunkBroker::Pointer &broker, uint32_t chunk_size, uint32_t factor,
size_t max, float expansion_ratio) {
ailego_assert_with(expansion_ratio > 1.0f, "ratio must > 1.0f");
broker_ = broker;
size_t items = std::ceil(chunk_size * 1.0f / sizeof(Item));
slot_items_ = 1UL << static_cast<size_t>((std::ceil(std::log2(items))));
size_t range = slot_items_ * factor / expansion_ratio;
mask_bits_ = std::floor(std::log2(range));
range = 1UL << mask_bits_;
size_t max_slots = std::ceil(max * 1.0f / range);
slots_.reserve(max_slots);
slot_loc_mask_ = slot_items_ - 1U;
int ret = load();
if (ret != 0) {
return ret;
}
LOG_DEBUG(
"HnswIndexHash init, chunkSize=%u factor=%u max=%zu "
"ratio=%f slotItems=%u maxSlots=%zu maskBits=%u "
"range=%zu",
chunk_size, factor, max, expansion_ratio, slot_items_, max_slots,
mask_bits_, range);
return 0;
}
int cleanup(void) {
broker_.reset();
slots_.clear();
slots_.shrink_to_fit();
mask_bits_ = 0U;
slot_items_ = 0U;
slot_loc_mask_ = 0U;
return 0;
}
const_iterator end(void) const {
return nullptr;
}
const_iterator find(const key_type key) const {
auto idx = key >> mask_bits_;
if (idx >= slots_.size()) {
return end();
}
auto it = slots_[idx].find(key, slot_items_, slot_loc_mask_);
return it && it->second != EmptyVal ? it : nullptr;
}
bool insert(key_type key, val_type val) {
auto idx = key >> mask_bits_;
if (idx >= slots_.size()) {
if (ailego_unlikely(idx >= slots_.capacity())) {
LOG_ERROR("no space to insert");
return false;
}
for (auto i = slots_.size(); i <= idx; ++i) {
if (ailego_unlikely(!alloc_slot(i))) {
return false;
}
}
}
auto it = slots_[idx].find(key, slot_items_, slot_loc_mask_);
if (ailego_unlikely(it == nullptr)) {
LOG_ERROR("no space to insert");
return false;
}
//! TODO: write memory is ok?
const_cast<iterator>(it)->first = key;
const_cast<iterator>(it)->second = val;
return slots_[idx].update(it);
}
private:
bool alloc_slot(size_t idx) {
ailego_assert_with(idx == slots_.size(), "invalid idx");
size_t size = slot_items_ * sizeof(Item);
auto p =
broker_->alloc_chunk(ChunkBroker::CHUNK_TYPE_NEIGHBOR_INDEX, idx, size);
if (ailego_unlikely(p.first != 0)) {
LOG_ERROR("Alloc data chunk failed");
return false;
}
Chunk::Pointer chunk = p.second;
if (ailego_unlikely(chunk->resize(size) != size)) {
LOG_ERROR("Chunk resize failed, size=%zu", size);
return false;
}
//! Read the whole data to memory
IndexStorage::MemoryBlock data_block;
if (ailego_unlikely(chunk->read(0U, data_block, size) != size)) {
LOG_ERROR("Chunk read failed, size=%zu", size);
return false;
}
slots_.emplace_back(std::move(chunk), std::move(data_block));
return true;
}
int load(void) {
size_t slots_cnt =
broker_->get_chunk_cnt(ChunkBroker::CHUNK_TYPE_NEIGHBOR_INDEX);
for (size_t i = 0UL; i < slots_cnt; ++i) {
auto chunk =
broker_->get_chunk(ChunkBroker::CHUNK_TYPE_NEIGHBOR_INDEX, i);
if (!chunk) {
LOG_ERROR("Get chunk failed, seq=%zu", i);
return IndexError_InvalidFormat;
}
size_t size = sizeof(Item) * slot_items_;
if (chunk->data_size() < size) {
LOG_ERROR(
"Hash params may be mismatch, seq=%zu, data_size=%zu "
"expect=%zu",
i, chunk->data_size(), size);
return IndexError_InvalidFormat;
}
//! Read the whole data to memory
IndexStorage::MemoryBlock data_block;
if (ailego_unlikely(chunk->read(0U, data_block, size) != size)) {
LOG_ERROR("Chunk read failed, size=%zu", size);
return false;
}
slots_.emplace_back(std::move(chunk), std::move(data_block));
}
return 0;
}
private:
ChunkBroker::Pointer broker_{}; // chunk broker
std::vector<Slot> slots_{};
uint32_t mask_bits_{0U};
uint32_t slot_items_{}; // must be a power of 2
uint32_t slot_loc_mask_{};
};
} // namespace core
} // namespace zvec
@@ -0,0 +1,133 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "framework/index_provider.h"
#include "framework/index_searcher.h"
#include "framework/index_streamer.h"
#include "hnsw_entity.h"
namespace zvec {
namespace core {
class HnswIndexProvider : public IndexProvider {
public:
HnswIndexProvider(const IndexMeta &meta, const HnswEntity::Pointer &entity,
const std::string &owner)
: meta_(meta), entity_(entity), owner_class_(owner) {}
HnswIndexProvider(const HnswIndexProvider &) = delete;
HnswIndexProvider &operator=(const HnswIndexProvider &) = delete;
public: // holder interface
//! Create a new iterator
IndexProvider::Iterator::Pointer create_iterator() override {
return HnswIndexProvider::Iterator::Pointer(new (std::nothrow)
Iterator(entity_));
}
//! Retrieve count of vectors
size_t count(void) const override {
return entity_->doc_cnt();
}
//! Retrieve dimension of vector
size_t dimension(void) const override {
return meta_.dimension();
}
//! Retrieve type of vector
IndexMeta::DataType data_type(void) const override {
return meta_.data_type();
}
//! Retrieve vector size in bytes
size_t element_size(void) const override {
return meta_.element_size();
}
public: // provider's unique interface
//! Retrieve a vector using a primary key
const void *get_vector(uint64_t key) const override {
return entity_->get_vector_by_key(key);
}
int get_vector(const uint64_t key,
IndexStorage::MemoryBlock &block) const override {
return entity_->get_vector_by_key(key, block);
}
//! Retrieve the owner class
const std::string &owner_class(void) const override {
return owner_class_;
}
private:
class Iterator : public IndexProvider::Iterator {
public:
Iterator(const HnswEntity::Pointer &entity)
: entity_(entity), cur_id_(0U) {}
//! Retrieve pointer of data
//! NOTICE: the vec feature will be changed after iterating to next, so
//! the caller need to keep a copy of it before iterator to next vector
virtual const void *data(void) const override {
return entity_->get_vector(cur_id_);
}
//! Test if the iterator is valid
virtual bool is_valid(void) const override {
return cur_id_ < entity_->doc_cnt();
}
//! Retrieve primary key
virtual uint64_t key(void) const override {
return entity_->get_key(cur_id_);
}
//! Next iterator
virtual void next(void) override {
// cur_id_ += 1;
cur_id_ = get_next_valid_id(cur_id_ + 1);
}
//! Reset the iterator
void reset(void) {
cur_id_ = get_next_valid_id(0);
}
private:
node_id_t get_next_valid_id(node_id_t start_id) {
for (node_id_t i = start_id; i < entity_->doc_cnt(); i++) {
if (entity_->get_key(i) != kInvalidNodeId) {
cur_id_ = i;
return i;
}
}
return kInvalidNodeId;
}
private:
const HnswEntity::Pointer entity_;
node_id_t cur_id_;
};
private:
const IndexMeta &meta_;
const HnswEntity::Pointer entity_;
const std::string owner_class_;
};
} // namespace core
} // namespace zvec
+124
View File
@@ -0,0 +1,124 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <string>
namespace zvec {
namespace core {
static const std::string PARAM_HNSW_BUILDER_THREAD_COUNT(
"proxima.hnsw.builder.thread_count");
static const std::string PARAM_HNSW_BUILDER_MEMORY_QUOTA(
"proxima.hnsw.builder.memory_quota");
static const std::string PARAM_HNSW_BUILDER_EFCONSTRUCTION(
"proxima.hnsw.builder.efconstruction");
static const std::string PARAM_HNSW_BUILDER_SCALING_FACTOR(
"proxima.hnsw.builder.scaling_factor");
static const std::string PARAM_HNSW_BUILDER_CHECK_INTERVAL_SECS(
"proxima.hnsw.builder.check_interval_secs");
static const std::string PARAM_HNSW_BUILDER_NEIGHBOR_PRUNE_RATIO(
"proxima.hnsw.builder.neighbor_prune_ratio");
static const std::string PARAM_HNSW_BUILDER_MAX_NEIGHBOR_COUNT(
"proxima.hnsw.builder.max_neighbor_count");
static const std::string PARAM_HNSW_BUILDER_MIN_NEIGHBOR_COUNT(
"proxima.hnsw.builder.min_neighbor_count");
static const std::string PARAM_HNSW_BUILDER_UPPER_NEIGHBOR_RATIO(
"proxima.hnsw.builder.upper_neighbor_ratio");
static const std::string PARAM_HNSW_BUILDER_HYBRID_VECTOR_ENABLE(
"proxima.hnsw.builder.hybrid_vector_enable");
static const std::string PARAM_HNSW_BUILDER_HYBRID_VECTOR_SEPARATE_NEIGHBOR(
"proxima.hnsw.builder.hybrid_vector_separate_neighbor");
static const std::string PARAM_HNSW_BUILDER_SPARSE_NEIGHBOR_RATIO(
"proxima.hnsw.builder.sparse_neighbor_ratio");
static const std::string PARAM_HNSW_SEARCHER_EF("proxima.hnsw.searcher.ef");
static const std::string PARAM_HNSW_SEARCHER_BRUTE_FORCE_THRESHOLD(
"proxima.hnsw.searcher.brute_force_threshold");
static const std::string PARAM_HNSW_SEARCHER_NEIGHBORS_IN_MEMORY_ENABLE(
"proxima.hnsw.searcher.neighbors_in_memory_enable");
static const std::string PARAM_HNSW_SEARCHER_MAX_SCAN_RATIO(
"proxima.hnsw.searcher.max_scan_ratio");
static const std::string PARAM_HNSW_SEARCHER_CHECK_CRC_ENABLE(
"proxima.hnsw.searcher.check_crc_enable");
static const std::string PARAM_HNSW_SEARCHER_VISIT_BLOOMFILTER_ENABLE(
"proxima.hnsw.searcher.visit_bloomfilter_enable");
static const std::string PARAM_HNSW_SEARCHER_VISIT_BLOOMFILTER_NEGATIVE_PROB(
"proxima.hnsw.searcher.visit_bloomfilter_negative_prob");
static const std::string PARAM_HNSW_SEARCHER_FORCE_PADDING_RESULT_ENABLE(
"proxima.hnsw.searcher.force_padding_result_enable");
static const std::string PARAM_HNSW_STREAMER_MAX_SCAN_RATIO(
"proxima.hnsw.streamer.max_scan_ratio");
static const std::string PARAM_HNSW_STREAMER_MIN_SCAN_LIMIT(
"proxima.hnsw.streamer.min_scan_limit");
static const std::string PARAM_HNSW_STREAMER_MAX_SCAN_LIMIT(
"proxima.hnsw.streamer.max_scan_limit");
static const std::string PARAM_HNSW_STREAMER_EF("proxima.hnsw.streamer.ef");
static const std::string PARAM_HNSW_STREAMER_EFCONSTRUCTION(
"proxima.hnsw.streamer.efconstruction");
static const std::string PARAM_HNSW_STREAMER_MAX_NEIGHBOR_COUNT(
"proxima.hnsw.streamer.max_neighbor_count");
static const std::string PARAM_HNSW_STREAMER_UPPER_NEIGHBOR_RATIO(
"proxima.hnsw.streamer.upper_neighbor_ratio");
static const std::string PARAM_HNSW_STREAMER_SCALING_FACTOR(
"proxima.hnsw.streamer.scaling_factor");
static const std::string PARAM_HNSW_STREAMER_BRUTE_FORCE_THRESHOLD(
"proxima.hnsw.streamer.brute_force_threshold");
static const std::string PARAM_HNSW_STREAMER_DOCS_HARD_LIMIT(
"proxima.hnsw.streamer.docs_hard_limit");
static const std::string PARAM_HNSW_STREAMER_DOCS_SOFT_LIMIT(
"proxima.hnsw.streamer.docs_soft_limit");
static const std::string PARAM_HNSW_STREAMER_MAX_INDEX_SIZE(
"proxima.hnsw.streamer.max_index_size");
static const std::string PARAM_HNSW_STREAMER_VISIT_BLOOMFILTER_ENABLE(
"proxima.hnsw.streamer.visit_bloomfilter_enable");
static const std::string PARAM_HNSW_STREAMER_VISIT_BLOOMFILTER_NEGATIVE_PROB(
"proxima.hnsw.streamer.visit_bloomfilter_negative_prob");
static const std::string PARAM_HNSW_STREAMER_CHECK_CRC_ENABLE(
"proxima.hnsw.streamer.check_crc_enable");
static const std::string PARAM_HNSW_STREAMER_NEIGHBOR_PRUNE_RATIO(
"proxima.hnsw.streamer.neighbor_prune_ratio");
static const std::string PARAM_HNSW_STREAMER_CHUNK_SIZE(
"proxima.hnsw.streamer.chunk_size");
static const std::string PARAM_HNSW_STREAMER_FILTER_SAME_KEY(
"proxima.hnsw.streamer.filter_same_key");
static const std::string PARAM_HNSW_STREAMER_GET_VECTOR_ENABLE(
"proxima.hnsw.streamer.get_vector_enable");
static const std::string PARAM_HNSW_STREAMER_MIN_NEIGHBOR_COUNT(
"proxima.hnsw.streamer.min_neighbor_count");
static const std::string PARAM_HNSW_STREAMER_FORCE_PADDING_RESULT_ENABLE(
"proxima.hnsw.streamer.force_padding_result_enable");
static const std::string PARAM_HNSW_STREAMER_HYBRID_VECTOR_ENABLE(
"proxima.hnsw.streamer.hybrid_vector_enable");
static const std::string PARAM_HNSW_STREAMER_HYBRID_VECTOR_SEPARATE_NEIGHBOR(
"proxima.hnsw.streamer.hybrid_vector_separate_neighbor");
static const std::string PARAM_HNSW_STREAMER_SPARSE_NEIGHBOR_RATIO(
"proxima.hnsw.streamer.sparse_neighbor_ratio");
static const std::string PARAM_HNSW_STREAMER_ESTIMATE_DOC_COUNT(
"proxima.hnsw.streamer.estimate_doc_count");
static const std::string PARAM_HNSW_STREAMER_USE_ID_MAP(
"proxima.hnsw.streamer.use_id_map");
static const std::string PARAM_HNSW_REDUCER_WORKING_PATH(
"proxima.hnsw.reducer.working_path");
static const std::string PARAM_HNSW_REDUCER_NUM_OF_ADD_THREADS(
"proxima.hnsw.reducer.num_of_add_threads");
static const std::string PARAM_HNSW_REDUCER_INDEX_NAME(
"proxima.hnsw.reducer.index_name");
static const std::string PARAM_HNSW_REDUCER_EFCONSTRUCTION(
"proxima.hnsw.reducer.efconstruction");
} // namespace core
} // namespace zvec
+460
View File
@@ -0,0 +1,460 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_searcher.h"
#include "hnsw_algorithm.h"
#include "hnsw_index_provider.h"
#include "hnsw_params.h"
namespace zvec {
namespace core {
HnswSearcher::HnswSearcher() {}
HnswSearcher::~HnswSearcher() {}
int HnswSearcher::init(const ailego::Params &search_params) {
params_ = search_params;
params_.get(PARAM_HNSW_SEARCHER_EF, &ef_);
params_.get(PARAM_HNSW_SEARCHER_MAX_SCAN_RATIO, &max_scan_ratio_);
params_.get(PARAM_HNSW_SEARCHER_VISIT_BLOOMFILTER_ENABLE, &bf_enabled_);
params_.get(PARAM_HNSW_SEARCHER_CHECK_CRC_ENABLE, &check_crc_enabled_);
params_.get(PARAM_HNSW_SEARCHER_NEIGHBORS_IN_MEMORY_ENABLE,
&neighbors_in_memory_enabled_);
params_.get(PARAM_HNSW_SEARCHER_VISIT_BLOOMFILTER_NEGATIVE_PROB,
&bf_negative_probility_);
params_.get(PARAM_HNSW_SEARCHER_BRUTE_FORCE_THRESHOLD,
&bruteforce_threshold_);
params_.get(PARAM_HNSW_SEARCHER_FORCE_PADDING_RESULT_ENABLE,
&force_padding_topk_enabled_);
if (ef_ == 0) {
ef_ = HnswEntity::kDefaultEf;
}
if (bf_negative_probility_ <= 0.0f || bf_negative_probility_ >= 1.0f) {
LOG_ERROR("[%s] must be in range (0,1)",
PARAM_HNSW_SEARCHER_VISIT_BLOOMFILTER_NEGATIVE_PROB.c_str());
return IndexError_InvalidArgument;
}
entity_.set_neighbors_in_memory(neighbors_in_memory_enabled_);
state_ = STATE_INITED;
LOG_DEBUG(
"Init params: ef=%u maxScanRatio=%f bfEnabled=%u checkCrcEnabled=%u "
"neighborsInMemoryEnabled=%u bfNagtiveProb=%f bruteForceThreshold=%u "
"forcePadding=%u",
ef_, max_scan_ratio_, bf_enabled_, check_crc_enabled_,
neighbors_in_memory_enabled_, bf_negative_probility_,
bruteforce_threshold_, force_padding_topk_enabled_);
return 0;
}
void HnswSearcher::print_debug_info() {
for (node_id_t id = 0; id < entity_.doc_cnt(); ++id) {
Neighbors neighbours = entity_.get_neighbors(0, id);
std::cout << "node: " << id << "; ";
for (uint32_t i = 0; i < neighbours.size(); ++i) {
std::cout << neighbours[i];
if (i == neighbours.size() - 1) {
std::cout << std::endl;
} else {
std::cout << ", ";
}
}
}
}
int HnswSearcher::cleanup() {
LOG_INFO("Begin HnswSearcher:cleanup");
metric_.reset();
meta_.clear();
stats_.clear_attributes();
stats_.set_loaded_count(0UL);
stats_.set_loaded_costtime(0UL);
max_scan_ratio_ = HnswEntity::kDefaultScanRatio;
max_scan_num_ = 0U;
ef_ = HnswEntity::kDefaultEf;
bf_enabled_ = false;
bf_negative_probility_ = HnswEntity::kDefaultBFNegativeProbility;
bruteforce_threshold_ = HnswEntity::kDefaultBruteForceThreshold;
check_crc_enabled_ = false;
neighbors_in_memory_enabled_ = false;
entity_.cleanup();
state_ = STATE_INIT;
LOG_INFO("End HnswSearcher:cleanup");
return 0;
}
int HnswSearcher::load(IndexStorage::Pointer container,
IndexMetric::Pointer metric) {
if (state_ != STATE_INITED) {
LOG_ERROR("Init the searcher first before load index");
return IndexError_Runtime;
}
LOG_INFO("Begin HnswSearcher:load");
auto start_time = ailego::Monotime::MilliSeconds();
int ret = IndexHelper::DeserializeFromStorage(container.get(), &meta_);
if (ret != 0) {
LOG_ERROR("Failed to deserialize meta from container");
return ret;
}
ret = entity_.load(container, check_crc_enabled_);
if (ret != 0) {
LOG_ERROR("HnswSearcher load index failed");
return ret;
}
alg_ = HnswAlgorithm::UPointer(new HnswAlgorithm(entity_));
if (metric) {
metric_ = metric;
} else {
metric_ = IndexFactory::CreateMetric(meta_.metric_name());
if (!metric_) {
LOG_ERROR("CreateMetric failed, name: %s", meta_.metric_name().c_str());
return IndexError_NoExist;
}
ret = metric_->init(meta_, meta_.metric_params());
if (ret != 0) {
LOG_ERROR("IndexMetric init failed, ret=%d", ret);
return ret;
}
if (metric_->query_metric()) {
metric_ = metric_->query_metric();
}
}
if (!metric_->is_matched(meta_)) {
LOG_ERROR("IndexMetric not match index meta");
return IndexError_Mismatch;
}
max_scan_num_ = static_cast<uint32_t>(max_scan_ratio_ * entity_.doc_cnt());
max_scan_num_ = std::max(4096U, max_scan_num_);
stats_.set_loaded_count(entity_.doc_cnt());
stats_.set_loaded_costtime(ailego::Monotime::MilliSeconds() - start_time);
state_ = STATE_LOADED;
magic_ = IndexContext::GenerateMagic();
LOG_INFO("End HnswSearcher::load");
return 0;
}
int HnswSearcher::unload() {
LOG_INFO("HnswSearcher unload index");
meta_.clear();
entity_.cleanup();
metric_.reset();
max_scan_num_ = 0;
stats_.set_loaded_count(0UL);
stats_.set_loaded_costtime(0UL);
state_ = STATE_INITED;
return 0;
}
int HnswSearcher::update_context(HnswContext *ctx) const {
const HnswEntity::Pointer entity = entity_.clone();
if (!entity) {
LOG_ERROR("Failed to clone search context entity");
return IndexError_Runtime;
}
ctx->set_max_scan_num(max_scan_num_);
ctx->set_bruteforce_threshold(bruteforce_threshold_);
return ctx->update_context(HnswContext::kSearcherContext, meta_, metric_,
entity, magic_);
}
int HnswSearcher::search_impl(const void *query, const IndexQueryMeta &qmeta,
uint32_t count, Context::Pointer &context) const {
if (ailego_unlikely(!query || !context)) {
LOG_ERROR("The context is not created by this searcher");
return IndexError_Mismatch;
}
HnswContext *ctx = dynamic_cast<HnswContext *>(context.get());
ailego_do_if_false(ctx) {
LOG_ERROR("Cast context to HnswContext failed");
return IndexError_Cast;
}
if (entity_.doc_cnt() <= ctx->get_bruteforce_threshold()) {
return search_bf_impl(query, qmeta, count, context);
}
if (ctx->magic() != magic_) {
//! context is created by another searcher or streamer
int ret = update_context(ctx);
if (ret != 0) {
return ret;
}
}
ctx->clear();
ctx->resize_results(count);
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
int ret = alg_->fast_search(ctx);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw searcher fast search failed");
return ret;
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
if (ailego_unlikely(ctx->error())) {
return IndexError_Runtime;
}
return 0;
}
int HnswSearcher::search_bf_impl(const void *query, const IndexQueryMeta &qmeta,
uint32_t count,
Context::Pointer &context) const {
if (ailego_unlikely(!query || !context)) {
LOG_ERROR("The context is not created by this searcher");
return IndexError_Mismatch;
}
HnswContext *ctx = dynamic_cast<HnswContext *>(context.get());
ailego_do_if_false(ctx) {
LOG_ERROR("Cast context to HnswContext failed");
return IndexError_Cast;
}
if (ctx->magic() != magic_) {
//! context is created by another searcher or streamer
int ret = update_context(ctx);
if (ret != 0) {
return ret;
}
}
ctx->clear();
ctx->resize_results(count);
if (ctx->group_by_search()) {
if (!ctx->group_by().is_valid()) {
LOG_ERROR("Invalid group-by function");
return IndexError_InvalidArgument;
}
std::function<std::string(node_id_t)> group_by = [&](node_id_t id) {
return ctx->group_by()(entity_.get_key(id));
};
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
ctx->group_topk_heaps().clear();
for (node_id_t id = 0; id < entity_.doc_cnt(); ++id) {
if (entity_.get_key(id) == kInvalidKey) {
continue;
}
if (!ctx->filter().is_valid() || !ctx->filter()(entity_.get_key(id))) {
dist_t dist = ctx->dist_calculator().dist(id);
std::string group_id = group_by(id);
auto &topk_heap = ctx->group_topk_heaps()[group_id];
if (topk_heap.empty()) {
topk_heap.limit(ctx->group_topk());
}
topk_heap.emplace_back(id, dist);
}
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
} else {
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
ctx->topk_heap().clear();
for (node_id_t id = 0; id < entity_.doc_cnt(); ++id) {
if (entity_.get_key(id) == kInvalidKey) {
continue;
}
if (!ctx->filter().is_valid() || !ctx->filter()(entity_.get_key(id))) {
dist_t dist = ctx->dist_calculator().dist(id);
ctx->topk_heap().emplace(id, dist);
}
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
}
if (ailego_unlikely(ctx->error())) {
return IndexError_Runtime;
}
return 0;
}
int HnswSearcher::search_bf_by_p_keys_impl(
const void *query, const std::vector<std::vector<uint64_t>> &p_keys,
const IndexQueryMeta &qmeta, uint32_t count,
Context::Pointer &context) const {
if (ailego_unlikely(!query || !context)) {
LOG_ERROR("The context is not created by this searcher");
return IndexError_Mismatch;
}
if (ailego_unlikely(p_keys.size() != count)) {
LOG_ERROR("The size of p_keys is not equal to count");
return IndexError_InvalidArgument;
}
HnswContext *ctx = dynamic_cast<HnswContext *>(context.get());
ailego_do_if_false(ctx) {
LOG_ERROR("Cast context to HnswContext failed");
return IndexError_Cast;
}
if (ctx->magic() != magic_) {
//! context is created by another searcher or streamer
int ret = update_context(ctx);
if (ret != 0) {
return ret;
}
}
ctx->clear();
ctx->resize_results(count);
if (ctx->group_by_search()) {
if (!ctx->group_by().is_valid()) {
LOG_ERROR("Invalid group-by function");
return IndexError_InvalidArgument;
}
std::function<std::string(node_id_t)> group_by = [&](node_id_t id) {
return ctx->group_by()(entity_.get_key(id));
};
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
ctx->group_topk_heaps().clear();
for (size_t idx = 0; idx < p_keys[q].size(); ++idx) {
uint64_t pk = p_keys[q][idx];
if (!ctx->filter().is_valid() || !ctx->filter()(pk)) {
node_id_t id = entity_.get_id(pk);
if (id != kInvalidNodeId) {
dist_t dist = ctx->dist_calculator().dist(id);
std::string group_id = group_by(id);
auto &topk_heap = ctx->group_topk_heaps()[group_id];
if (topk_heap.empty()) {
topk_heap.limit(ctx->group_topk());
}
topk_heap.emplace_back(id, dist);
}
}
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
} else {
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
ctx->topk_heap().clear();
for (size_t idx = 0; idx < p_keys[q].size(); ++idx) {
uint64_t pk = p_keys[q][idx];
if (!ctx->filter().is_valid() || !ctx->filter()(pk)) {
node_id_t id = entity_.get_id(pk);
if (id != kInvalidNodeId) {
dist_t dist = ctx->dist_calculator().dist(id);
ctx->topk_heap().emplace(id, dist);
}
}
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
}
if (ailego_unlikely(ctx->error())) {
return IndexError_Runtime;
}
return 0;
}
IndexSearcher::Context::Pointer HnswSearcher::create_context() const {
if (ailego_unlikely(state_ != STATE_LOADED)) {
LOG_ERROR("Load the index first before create context");
return Context::Pointer();
}
const HnswEntity::Pointer search_ctx_entity = entity_.clone();
if (!search_ctx_entity) {
LOG_ERROR("Failed to create search context entity");
return Context::Pointer();
}
HnswContext *ctx = new (std::nothrow)
HnswContext(meta_.dimension(), metric_, search_ctx_entity);
if (ailego_unlikely(ctx == nullptr)) {
LOG_ERROR("Failed to new HnswContext");
return Context::Pointer();
}
ctx->set_ef(ef_);
ctx->set_max_scan_num(max_scan_num_);
uint32_t filter_mode =
bf_enabled_ ? VisitFilter::BloomFilter : VisitFilter::ByteMap;
ctx->set_filter_mode(filter_mode);
ctx->set_filter_negative_probility(bf_negative_probility_);
ctx->set_magic(magic_);
ctx->set_force_padding_topk(force_padding_topk_enabled_);
ctx->set_bruteforce_threshold(bruteforce_threshold_);
if (ailego_unlikely(ctx->init(HnswContext::kSearcherContext)) != 0) {
LOG_ERROR("Init HnswContext failed");
delete ctx;
return Context::Pointer();
}
return Context::Pointer(ctx);
}
IndexProvider::Pointer HnswSearcher::create_provider(void) const {
LOG_DEBUG("HnswSearcher create provider");
auto entity = entity_.clone();
if (ailego_unlikely(!entity)) {
LOG_ERROR("Clone HnswEntity failed");
return Provider::Pointer();
}
return Provider::Pointer(
new (std::nothrow) HnswIndexProvider(meta_, entity, "HnswSearcher"));
}
const void *HnswSearcher::get_vector(uint64_t key) const {
return entity_.get_vector_by_key(key);
}
INDEX_FACTORY_REGISTER_SEARCHER(HnswSearcher);
} // namespace core
} // namespace zvec
+139
View File
@@ -0,0 +1,139 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "framework/index_framework.h"
#include "hnsw_searcher_entity.h"
#include "hnsw_streamer.h"
namespace zvec {
namespace core {
class HnswSearcher : public IndexSearcher {
public:
using ContextPointer = IndexSearcher::Context::Pointer;
public:
HnswSearcher(void);
~HnswSearcher(void);
HnswSearcher(const HnswSearcher &) = delete;
HnswSearcher &operator=(const HnswSearcher &) = delete;
protected:
//! Initialize Searcher
virtual int init(const ailego::Params &params) override;
//! Cleanup Searcher
virtual int cleanup(void) override;
//! Load Index from storage
virtual int load(IndexStorage::Pointer container,
IndexMetric::Pointer metric) override;
//! Unload index from storage
virtual int unload(void) override;
//! KNN Search
virtual int search_impl(const void *query, const IndexQueryMeta &qmeta,
ContextPointer &context) const override {
return search_impl(query, qmeta, 1, context);
}
//! KNN Search
virtual int search_impl(const void *query, const IndexQueryMeta &qmeta,
uint32_t count,
ContextPointer &context) const override;
//! Linear Search
virtual int search_bf_impl(const void *query, const IndexQueryMeta &qmeta,
ContextPointer &context) const override {
return search_bf_impl(query, qmeta, 1, context);
}
//! Linear Search
virtual int search_bf_impl(const void *query, const IndexQueryMeta &qmeta,
uint32_t count,
ContextPointer &context) const override;
//! Linear search by primary keys
virtual int search_bf_by_p_keys_impl(
const void *query, const std::vector<std::vector<uint64_t>> &p_keys,
const IndexQueryMeta &qmeta, ContextPointer &context) const override {
return search_bf_by_p_keys_impl(query, p_keys, qmeta, 1, context);
}
//! Linear search by primary keys
virtual int search_bf_by_p_keys_impl(
const void *query, const std::vector<std::vector<uint64_t>> &p_keys,
const IndexQueryMeta &qmeta, uint32_t count,
ContextPointer &context) const override;
//! Fetch vector by key
virtual const void *get_vector(uint64_t key) const override;
//! Create a searcher context
virtual ContextPointer create_context() const override;
//! Create a new iterator
virtual IndexProvider::Pointer create_provider(void) const override;
//! Retrieve statistics
virtual const Stats &stats(void) const override {
return stats_;
}
//! Retrieve meta of index
virtual const IndexMeta &meta(void) const override {
return meta_;
}
//! Retrieve params of index
virtual const ailego::Params &params(void) const override {
return params_;
}
virtual void print_debug_info() override;
private:
//! To share ctx across streamer/searcher, we need to update the context for
//! current streamer/searcher
int update_context(HnswContext *ctx) const;
private:
enum State { STATE_INIT = 0, STATE_INITED = 1, STATE_LOADED = 2 };
HnswSearcherEntity entity_{};
HnswAlgorithm::UPointer alg_; // impl graph algorithm
IndexMetric::Pointer metric_{};
IndexMeta meta_{};
ailego::Params params_{};
Stats stats_;
uint32_t ef_{HnswEntity::kDefaultEf};
uint32_t max_scan_num_{0U};
uint32_t bruteforce_threshold_{HnswEntity::kDefaultBruteForceThreshold};
float max_scan_ratio_{HnswEntity::kDefaultScanRatio};
bool bf_enabled_{false};
bool check_crc_enabled_{false};
bool neighbors_in_memory_enabled_{false};
bool force_padding_topk_enabled_{false};
float bf_negative_probility_{HnswEntity::kDefaultBFNegativeProbility};
uint32_t magic_{0U};
State state_{STATE_INIT};
};
} // namespace core
} // namespace zvec
@@ -0,0 +1,515 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_searcher_entity.h"
#include <ailego/hash/crc32c.h>
#include "utility/sparse_utility.h"
namespace zvec {
namespace core {
HnswSearcherEntity::HnswSearcherEntity() {}
int HnswSearcherEntity::cleanup(void) {
storage_.reset();
vectors_.reset();
keys_.reset();
neighbors_.reset();
neighbors_meta_.reset();
neighbors_in_memory_enabled_ = false;
loaded_ = false;
this->HnswEntity::cleanup();
return 0;
}
key_t HnswSearcherEntity::get_key(node_id_t id) const {
const void *key;
if (ailego_unlikely(keys_->read(id * sizeof(key_t), &key, sizeof(key_t)) !=
sizeof(key_t))) {
LOG_ERROR("Read key from segment failed");
return kInvalidKey;
}
return *(reinterpret_cast<const key_t *>(key));
}
//! Get vector local id by key
node_id_t HnswSearcherEntity::get_id(key_t key) const {
if (ailego_unlikely(!mapping_)) {
LOG_ERROR("Index missing mapping segment");
return kInvalidNodeId;
}
//! Do binary search
node_id_t start = 0UL;
node_id_t end = doc_cnt();
const void *data;
node_id_t idx = 0u;
while (start < end) {
idx = start + (end - start) / 2;
if (ailego_unlikely(
mapping_->read(idx * sizeof(node_id_t), &data, sizeof(node_id_t)) !=
sizeof(node_id_t))) {
LOG_ERROR("Read key from segment failed");
return kInvalidNodeId;
}
const key_t *mkey;
node_id_t local_id = *reinterpret_cast<const node_id_t *>(data);
if (ailego_unlikely(keys_->read(local_id * sizeof(key_t),
(const void **)(&mkey),
sizeof(key_t)) != sizeof(key_t))) {
LOG_ERROR("Read key from segment failed");
return kInvalidNodeId;
}
if (*mkey < key) {
start = idx + 1;
} else if (*mkey > key) {
end = idx;
} else {
return local_id;
}
}
return kInvalidNodeId;
}
const void *HnswSearcherEntity::get_vector_by_key(key_t key) const {
node_id_t local_id = get_id(key);
if (ailego_unlikely(local_id == kInvalidNodeId)) {
return nullptr;
}
return get_vector(local_id);
}
const void *HnswSearcherEntity::get_vector(node_id_t id) const {
size_t read_size = vector_size();
size_t offset = node_size() * id;
const void *vec;
if (ailego_unlikely(vectors_->read(offset, &vec, read_size) != read_size)) {
LOG_ERROR("Read vector from segment failed");
return nullptr;
}
return vec;
}
int HnswSearcherEntity::get_vector(const node_id_t id,
IndexStorage::MemoryBlock &block) const {
const void *vec = get_vector(id);
block.reset((void *)vec);
return 0;
}
const void *HnswSearcherEntity::get_vectors() const {
const void *vec;
size_t len = node_size() * doc_cnt();
if (vectors_->read(0, &vec, len) != len) {
LOG_ERROR("Read vectors from segment failed");
return nullptr;
}
return vec;
}
int HnswSearcherEntity::get_vector(const node_id_t *ids, uint32_t count,
const void **vecs) const {
ailego_assert_with(count <= segment_datas_.size(), "invalid count");
size_t read_size = vector_size();
for (uint32_t i = 0; i < count; ++i) {
segment_datas_[i].offset = node_size() * ids[i];
segment_datas_[i].length = read_size;
ailego_assert_with(segment_datas_[i].offset < vectors_->data_size(),
"invalid offset");
}
if (ailego_unlikely(!vectors_->read(&segment_datas_[0], count))) {
LOG_ERROR("Read vectors from segment failed");
return IndexError_ReadData;
}
for (uint32_t i = 0; i < count; ++i) {
vecs[i] = segment_datas_[i].data;
}
return 0;
}
int HnswSearcherEntity::get_vector(
const node_id_t *ids, uint32_t count,
std::vector<IndexStorage::MemoryBlock> &vec_blocks) const {
const void *vecs[count];
get_vector(ids, count, vecs);
for (uint32_t i = 0; i < count; ++i) {
vec_blocks.emplace_back(IndexStorage::MemoryBlock((void *)vecs[i]));
}
return 0;
}
const Neighbors HnswSearcherEntity::get_neighbors(level_t level,
node_id_t id) const {
if (level == 0) {
if (neighbors_in_memory_enabled_) {
auto hd = reinterpret_cast<const NeighborsHeader *>(
fixed_neighbors_.get() + neighbors_size() * id);
return {hd->neighbor_cnt, hd->neighbors};
}
const GraphNeighborMeta *m;
if (ailego_unlikely(neighbors_meta_->read(id * sizeof(GraphNeighborMeta),
(const void **)(&m),
sizeof(GraphNeighborMeta)) !=
sizeof(GraphNeighborMeta))) {
LOG_ERROR("Read neighbors meta from segment failed");
return {0, nullptr};
}
const void *data;
if (ailego_unlikely(neighbors_->read(m->offset, &data,
m->neighbor_cnt * sizeof(node_id_t)) !=
m->neighbor_cnt * sizeof(node_id_t))) {
LOG_ERROR("Read neighbors from segment failed");
return {0, nullptr};
}
return {static_cast<uint32_t>(m->neighbor_cnt),
reinterpret_cast<const node_id_t *>(data)};
}
//! Read level > 0 neighbors
const HnswNeighborMeta *m;
if (ailego_unlikely(upper_neighbors_meta_->read(id * sizeof(HnswNeighborMeta),
(const void **)(&m),
sizeof(HnswNeighborMeta)) !=
sizeof(HnswNeighborMeta))) {
LOG_ERROR("Read neighbors meta from segment failed");
return {0, nullptr};
}
ailego_assert_with(level <= m->level, "invalid level");
size_t offset = m->offset + (level - 1) * upper_neighbors_size();
ailego_assert_with(offset <= upper_neighbors_->data_size(), "invalid offset");
const void *data;
if (ailego_unlikely(
upper_neighbors_->read(offset, &data, upper_neighbors_size()) !=
upper_neighbors_size())) {
LOG_ERROR("Read neighbors from segment failed");
return {0, nullptr};
}
auto hd = reinterpret_cast<const NeighborsHeader *>(data);
return {hd->neighbor_cnt, hd->neighbors};
}
int HnswSearcherEntity::load(const IndexStorage::Pointer &container,
bool check_crc) {
storage_ = container;
int ret = load_segments(check_crc);
if (ret != 0) {
return ret;
}
loaded_ = true;
LOG_INFO(
"Index info: docCnt=%u entryPoint=%u maxLevel=%d efConstruct=%zu "
"neighborCnt=%zu upperNeighborCnt=%zu scalingFactor=%zu "
"vectorSize=%zu nodeSize=%zu vectorSegmentSize=%zu keySegmentSize=%zu "
"neighborsSegmentSize=%zu neighborsMetaSegmentSize=%zu ",
doc_cnt(), entry_point(), cur_max_level(), ef_construction(),
neighbor_cnt(), upper_neighbor_cnt(), scaling_factor(), vector_size(),
node_size(), vectors_->data_size(), keys_->data_size(),
neighbors_ == nullptr ? 0 : neighbors_->data_size(),
neighbors_meta_ == nullptr ? 0 : neighbors_meta_->data_size());
return 0;
}
int HnswSearcherEntity::load_segments(bool check_crc) {
//! load header
const void *data = nullptr;
HNSWHeader hd;
auto graph_hd_segment = storage_->get(kGraphHeaderSegmentId);
if (!graph_hd_segment || graph_hd_segment->data_size() < sizeof(hd.graph)) {
LOG_ERROR("Miss or invalid segment %s", kGraphHeaderSegmentId.c_str());
return IndexError_InvalidFormat;
}
if (graph_hd_segment->read(0, reinterpret_cast<const void **>(&data),
sizeof(hd.graph)) != sizeof(hd.graph)) {
LOG_ERROR("Read segment %s failed", kGraphHeaderSegmentId.c_str());
return IndexError_ReadData;
}
memcpy(&hd.graph, data, sizeof(hd.graph));
auto hnsw_hd_segment = storage_->get(kHnswHeaderSegmentId);
if (!hnsw_hd_segment || hnsw_hd_segment->data_size() < sizeof(hd.hnsw)) {
LOG_ERROR("Miss or invalid segment %s", kHnswHeaderSegmentId.c_str());
return IndexError_InvalidFormat;
}
if (hnsw_hd_segment->read(0, reinterpret_cast<const void **>(&data),
sizeof(hd.hnsw)) != sizeof(hd.hnsw)) {
LOG_ERROR("Read segment %s failed", kHnswHeaderSegmentId.c_str());
return IndexError_ReadData;
}
memcpy(&hd.hnsw, data, sizeof(hd.hnsw));
*mutable_header() = hd;
segment_datas_.resize(std::max(neighbor_cnt(), upper_neighbor_cnt()));
vectors_ = storage_->get(kGraphFeaturesSegmentId);
if (!vectors_) {
LOG_ERROR("IndexStorage get segment %s failed",
kGraphFeaturesSegmentId.c_str());
return IndexError_InvalidFormat;
}
keys_ = storage_->get(kGraphKeysSegmentId);
if (!keys_) {
LOG_ERROR("IndexStorage get segment %s failed",
kGraphKeysSegmentId.c_str());
return IndexError_InvalidFormat;
}
neighbors_ = storage_->get(kGraphNeighborsSegmentId);
if (!neighbors_ || (neighbors_->data_size() == 0 && doc_cnt() > 1)) {
LOG_ERROR("IndexStorage get segment %s failed or empty",
kGraphNeighborsSegmentId.c_str());
return IndexError_InvalidArgument;
}
neighbors_meta_ = storage_->get(kGraphOffsetsSegmentId);
if (!neighbors_meta_ ||
neighbors_meta_->data_size() < sizeof(GraphNeighborMeta) * doc_cnt()) {
LOG_ERROR("IndexStorage get segment %s failed or invalid size",
kGraphOffsetsSegmentId.c_str());
return IndexError_InvalidArgument;
}
upper_neighbors_ = storage_->get(kHnswNeighborsSegmentId);
if (!upper_neighbors_ ||
(upper_neighbors_->data_size() == 0 && cur_max_level() > 0)) {
LOG_ERROR("IndexStorage get segment %s failed or empty",
kHnswNeighborsSegmentId.c_str());
return IndexError_InvalidArgument;
}
upper_neighbors_meta_ = storage_->get(kHnswOffsetsSegmentId);
if (!upper_neighbors_meta_ || upper_neighbors_meta_->data_size() <
sizeof(HnswNeighborMeta) * doc_cnt()) {
LOG_ERROR("IndexStorage get segment %s failed or invalid size",
kHnswOffsetsSegmentId.c_str());
return IndexError_InvalidArgument;
}
mapping_ = storage_->get(kGraphMappingSegmentId);
if (!mapping_ || mapping_->data_size() < sizeof(node_id_t) * doc_cnt()) {
LOG_ERROR("IndexStorage get segment %s failed or invalid size",
kGraphMappingSegmentId.c_str());
return IndexError_InvalidArgument;
}
if (check_crc) {
std::vector<SegmentPointer> segments;
segments.emplace_back(graph_hd_segment);
segments.emplace_back(hnsw_hd_segment);
segments.emplace_back(vectors_);
segments.emplace_back(keys_);
segments.emplace_back(neighbors_);
segments.emplace_back(neighbors_meta_);
segments.emplace_back(upper_neighbors_);
segments.emplace_back(upper_neighbors_meta_);
if (!do_crc_check(segments)) {
LOG_ERROR("Check index crc failed, the index may broken");
return IndexError_Runtime;
}
}
if (neighbors_in_memory_enabled_) {
int ret = load_and_flat_neighbors();
if (ret != 0) {
return ret;
}
}
return 0;
}
int HnswSearcherEntity::load_and_flat_neighbors() {
fixed_neighbors_.reset(
new (std::nothrow) char[neighbors_size() * doc_cnt()]{},
std::default_delete<char[]>());
if (!fixed_neighbors_) {
LOG_ERROR("Malloc memory failed");
return IndexError_NoMemory;
}
//! Get a new segemnt to release the buffer after loading neighbors
auto neighbors_meta = storage_->get(kGraphOffsetsSegmentId);
if (!neighbors_meta) {
LOG_ERROR("IndexStorage get segment graph.offsets failed");
return IndexError_InvalidArgument;
}
const GraphNeighborMeta *neighbors_index = nullptr;
if (neighbors_meta->read(0, reinterpret_cast<const void **>(&neighbors_index),
neighbors_meta->data_size()) !=
neighbors_meta->data_size()) {
LOG_ERROR("Read segment %s data failed", kGraphOffsetsSegmentId.c_str());
return IndexError_InvalidArgument;
}
const char *neighbor_data;
for (node_id_t id = 0; id < doc_cnt(); ++id) {
size_t rd_size = neighbors_index[id].neighbor_cnt * sizeof(node_id_t);
if (ailego_unlikely(
neighbors_->read(neighbors_index[id].offset,
reinterpret_cast<const void **>(&neighbor_data),
rd_size) != rd_size)) {
LOG_ERROR("Read neighbors from segment failed");
return IndexError_ReadData;
}
// copy level 0 neighbors to fixed size neighbors memory
char *dst = fixed_neighbors_.get() + neighbors_size() * id;
*reinterpret_cast<uint32_t *>(dst) = neighbors_index[id].neighbor_cnt;
memcpy(dst + sizeof(uint32_t), neighbor_data, rd_size);
}
return 0;
}
int HnswSearcherEntity::get_fixed_neighbors(
std::vector<uint32_t> *fixed_neighbors) const {
//! Get a new segemnt to release the buffer after loading neighbors
auto neighbors_meta = storage_->get(kGraphOffsetsSegmentId);
if (!neighbors_meta) {
LOG_ERROR("IndexStorage get segment graph.offsets failed");
return IndexError_InvalidArgument;
}
const GraphNeighborMeta *neighbors_index = nullptr;
size_t meta_size = neighbors_meta->data_size();
if (neighbors_meta->read(0, reinterpret_cast<const void **>(&neighbors_index),
meta_size) != meta_size) {
LOG_ERROR("Read segment %s data failed", kGraphOffsetsSegmentId.c_str());
return IndexError_InvalidArgument;
}
size_t fixed_neighbor_cnt = neighbor_cnt();
fixed_neighbors->resize((fixed_neighbor_cnt + 1) * doc_cnt(), kInvalidNodeId);
size_t neighbors_cnt_offset = fixed_neighbor_cnt * doc_cnt();
size_t total_neighbor_cnt = 0;
for (node_id_t id = 0; id < doc_cnt(); ++id) {
size_t cur_neighbor_cnt = neighbors_index[id].neighbor_cnt;
if (cur_neighbor_cnt == 0) {
(*fixed_neighbors)[neighbors_cnt_offset + id] = 0;
continue;
}
size_t rd_size = cur_neighbor_cnt * sizeof(node_id_t);
const uint32_t *neighbors;
if (neighbors_->read(neighbors_index[id].offset,
reinterpret_cast<const void **>(&neighbors),
rd_size) != rd_size) {
LOG_ERROR("Read neighbors from segment failed");
return IndexError_ReadData;
}
// copy level 0 neighbors to fixed size neighbors memory
auto it = fixed_neighbors->begin() + id * fixed_neighbor_cnt;
std::copy(neighbors, neighbors + cur_neighbor_cnt, it);
(*fixed_neighbors)[neighbors_cnt_offset + id] = cur_neighbor_cnt;
total_neighbor_cnt += cur_neighbor_cnt;
}
LOG_INFO("total neighbor cnt: %zu, average neighbor cnt: %zu",
total_neighbor_cnt, total_neighbor_cnt / doc_cnt());
return 0;
}
bool HnswSearcherEntity::do_crc_check(
std::vector<SegmentPointer> &segments) const {
constexpr size_t blk_size = 4096;
const void *data;
for (auto &segment : segments) {
size_t offset = 0;
size_t rd_size;
uint32_t crc = 0;
while (offset < segment->data_size()) {
size_t size = std::min(blk_size, segment->data_size() - offset);
if ((rd_size = segment->read(offset, &data, size)) <= 0) {
break;
}
offset += rd_size;
crc = ailego::Crc32c::Hash(data, rd_size, crc);
}
if (crc != segment->data_crc()) {
return false;
}
}
return true;
}
const HnswEntity::Pointer HnswSearcherEntity::clone() const {
auto vectors = vectors_->clone();
if (ailego_unlikely(!vectors)) {
LOG_ERROR("clone segment %s failed", kGraphFeaturesSegmentId.c_str());
return HnswEntity::Pointer();
}
auto keys = keys_->clone();
if (ailego_unlikely(!keys)) {
LOG_ERROR("clone segment %s failed", kGraphKeysSegmentId.c_str());
return HnswEntity::Pointer();
}
auto mapping = mapping_->clone();
if (ailego_unlikely(!mapping)) {
LOG_ERROR("clone segment %s failed", kGraphMappingSegmentId.c_str());
return HnswEntity::Pointer();
}
auto neighbors = neighbors_->clone();
if (ailego_unlikely(!neighbors)) {
LOG_ERROR("clone segment %s failed", kGraphNeighborsSegmentId.c_str());
return HnswEntity::Pointer();
}
auto upper_neighbors = upper_neighbors_->clone();
if (ailego_unlikely(!neighbors)) {
LOG_ERROR("clone segment %s failed", kHnswNeighborsSegmentId.c_str());
return HnswEntity::Pointer();
}
auto neighbors_meta = neighbors_meta_->clone();
if (ailego_unlikely(!neighbors_meta)) {
LOG_ERROR("clone segment %s failed", kGraphOffsetsSegmentId.c_str());
return HnswEntity::Pointer();
}
auto upper_neighbors_meta = upper_neighbors_meta_->clone();
if (ailego_unlikely(!upper_neighbors_meta)) {
LOG_ERROR("clone segment %s failed", kHnswOffsetsSegmentId.c_str());
return HnswEntity::Pointer();
}
SegmentGroupParam neighbor_group{neighbors, neighbors_meta, upper_neighbors,
upper_neighbors_meta};
HnswSearcherEntity *entity = new (std::nothrow)
HnswSearcherEntity(header(), vectors, keys, mapping, neighbor_group,
fixed_neighbors_, neighbors_in_memory_enabled_);
if (ailego_unlikely(!entity)) {
LOG_ERROR("HnswSearcherEntity new failed");
}
return HnswEntity::Pointer(entity);
}
} // namespace core
} // namespace zvec
@@ -0,0 +1,156 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "hnsw_builder_entity.h"
#include "hnsw_entity.h"
namespace zvec {
namespace core {
class HnswSearcherEntity : public HnswEntity {
public:
using Pointer = std::shared_ptr<HnswSearcherEntity>;
using SegmentPointer = IndexStorage::Segment::Pointer;
public:
struct SegmentGroupParam {
SegmentGroupParam(SegmentPointer neighbors_in,
SegmentPointer neighbors_meta_in,
SegmentPointer upper_neighbors_in,
SegmentPointer upper_neighbors_meta_in)
: neighbors{neighbors_in},
neighbors_meta{neighbors_meta_in},
upper_neighbors{upper_neighbors_in},
upper_neighbors_meta{upper_neighbors_meta_in} {}
SegmentPointer neighbors{nullptr};
SegmentPointer neighbors_meta{nullptr};
SegmentPointer upper_neighbors{nullptr};
SegmentPointer upper_neighbors_meta{nullptr};
};
//! Constructor
HnswSearcherEntity();
//! Make a copy of searcher entity, to support thread-safe operation.
//! The segment in container cannot be read concurrenly
virtual const HnswEntity::Pointer clone() const override;
//! Get primary key of the node id
virtual key_t get_key(node_id_t id) const override;
//! Get vector local id by key
node_id_t get_id(key_t key) const;
//! Get vector feature data by key
virtual const void *get_vector_by_key(key_t key) const override;
//! Get vector feature data by id
virtual const void *get_vector(node_id_t id) const override;
//! Get vector feature data by id
virtual int get_vector(const node_id_t *ids, uint32_t count,
const void **vecs) const override;
virtual int get_vector(const node_id_t id,
IndexStorage::MemoryBlock &block) const override;
virtual int get_vector(
const node_id_t *ids, uint32_t count,
std::vector<IndexStorage::MemoryBlock> &vec_blocks) const override;
//! Get all vectors
const void *get_vectors() const;
//! Get the node id's neighbors on graph level
virtual const Neighbors get_neighbors(level_t level,
node_id_t id) const override;
virtual int load(const IndexStorage::Pointer &container,
bool check_crc) override;
int load_segments(bool check_crc);
virtual int cleanup(void) override;
public:
bool is_loaded() const {
return loaded_;
}
void set_neighbors_in_memory(bool enabled) {
neighbors_in_memory_enabled_ = enabled;
}
//! get fixed length neighbors data
int get_fixed_neighbors(std::vector<uint32_t> *fixed_neighbors) const;
private:
//! Constructor
HnswSearcherEntity(const HNSWHeader &hd, const SegmentPointer &vectors,
const SegmentPointer &keys, const SegmentPointer &mapping,
const SegmentGroupParam &neighbor_group,
const std::shared_ptr<char> &fixed_neighbors,
bool neighbors_in_memory_enabled)
: HnswEntity(hd),
vectors_(vectors),
keys_(keys),
mapping_(mapping),
neighbors_(neighbor_group.neighbors),
neighbors_meta_(neighbor_group.neighbors_meta),
upper_neighbors_(neighbor_group.upper_neighbors),
upper_neighbors_meta_(neighbor_group.upper_neighbors_meta),
neighbors_in_memory_enabled_(neighbors_in_memory_enabled) {
segment_datas_.resize(std::max(neighbor_cnt(), upper_neighbor_cnt()),
IndexStorage::SegmentData(0U, 0U));
fixed_neighbors_ = fixed_neighbors;
}
bool do_crc_check(std::vector<SegmentPointer> &segments) const;
inline size_t neighbors_size() const {
return sizeof(NeighborsHeader) + neighbor_cnt() * sizeof(node_id_t);
}
inline size_t upper_neighbors_size() const {
return sizeof(NeighborsHeader) + upper_neighbor_cnt() * sizeof(node_id_t);
}
//! If neighbors_in_memory_enabled, load the level0 neighbors to memory
int load_and_flat_neighbors(void);
public:
HnswSearcherEntity(const HnswSearcherEntity &) = delete;
HnswSearcherEntity &operator=(const HnswSearcherEntity &) = delete;
private:
IndexStorage::Pointer storage_{};
SegmentPointer vectors_{};
SegmentPointer keys_{};
SegmentPointer mapping_{};
SegmentPointer neighbors_{};
SegmentPointer neighbors_meta_{};
SegmentPointer upper_neighbors_{};
SegmentPointer upper_neighbors_meta_{};
mutable std::vector<IndexStorage::SegmentData> segment_datas_{};
std::shared_ptr<char> fixed_neighbors_{}; // level 0 fixed size neighbors
bool neighbors_in_memory_enabled_{false};
bool loaded_{false};
};
} // namespace core
} // namespace zvec
+848
View File
@@ -0,0 +1,848 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_streamer.h"
#include <iostream>
#include <ailego/internal/cpu_features.h>
#include <ailego/pattern/defer.h>
#include <ailego/utility/memory_helper.h>
#include "utility/sparse_utility.h"
#include "hnsw_algorithm.h"
#include "hnsw_context.h"
#include "hnsw_dist_calculator.h"
#include "hnsw_index_provider.h"
namespace zvec {
namespace core {
HnswStreamer::HnswStreamer() : entity_(stats_) {}
HnswStreamer::~HnswStreamer() {
if (state_ == STATE_INITED) {
this->cleanup();
}
}
int HnswStreamer::init(const IndexMeta &imeta, const ailego::Params &params) {
meta_ = imeta;
meta_.set_streamer("HnswStreamer", HnswEntity::kRevision, params);
params.get(PARAM_HNSW_STREAMER_MAX_INDEX_SIZE, &max_index_size_);
params.get(PARAM_HNSW_STREAMER_MAX_NEIGHBOR_COUNT, &neighbor_cnt_);
float ratio = HnswEntity::kDefaultUpperNeighborRatio;
params.get(PARAM_HNSW_STREAMER_UPPER_NEIGHBOR_RATIO, &ratio);
upper_neighbor_cnt_ = ratio * neighbor_cnt_;
params.get(PARAM_HNSW_STREAMER_DOCS_HARD_LIMIT, &docs_hard_limit_);
params.get(PARAM_HNSW_STREAMER_EF, &ef_);
params.get(PARAM_HNSW_STREAMER_EFCONSTRUCTION, &ef_construction_);
params.get(PARAM_HNSW_STREAMER_VISIT_BLOOMFILTER_ENABLE, &bf_enabled_);
params.get(PARAM_HNSW_STREAMER_VISIT_BLOOMFILTER_NEGATIVE_PROB,
&bf_negative_prob_);
params.get(PARAM_HNSW_STREAMER_SCALING_FACTOR, &scaling_factor_);
params.get(PARAM_HNSW_STREAMER_BRUTE_FORCE_THRESHOLD, &bruteforce_threshold_);
params.get(PARAM_HNSW_STREAMER_MAX_SCAN_RATIO, &max_scan_ratio_);
params.get(PARAM_HNSW_STREAMER_MAX_SCAN_LIMIT, &max_scan_limit_);
params.get(PARAM_HNSW_STREAMER_MIN_SCAN_LIMIT, &min_scan_limit_);
params.get(PARAM_HNSW_STREAMER_CHECK_CRC_ENABLE, &check_crc_enabled_);
ratio = HnswEntity::kDefaultNeighborPruneRatio;
params.get(PARAM_HNSW_STREAMER_NEIGHBOR_PRUNE_RATIO, &ratio);
size_t prune_cnt = ratio * neighbor_cnt_;
params.get(PARAM_HNSW_STREAMER_CHUNK_SIZE, &chunk_size_);
params.get(PARAM_HNSW_STREAMER_FILTER_SAME_KEY, &filter_same_key_);
params.get(PARAM_HNSW_STREAMER_GET_VECTOR_ENABLE, &get_vector_enabled_);
params.get(PARAM_HNSW_STREAMER_MIN_NEIGHBOR_COUNT, &min_neighbor_cnt_);
params.get(PARAM_HNSW_STREAMER_FORCE_PADDING_RESULT_ENABLE,
&force_padding_topk_enabled_);
params.get(PARAM_HNSW_STREAMER_USE_ID_MAP, &use_id_map_);
entity_.set_use_key_info_map(use_id_map_);
params.get(PARAM_HNSW_STREAMER_DOCS_SOFT_LIMIT, &docs_soft_limit_);
if (docs_soft_limit_ > 0 && docs_soft_limit_ > docs_hard_limit_) {
LOG_ERROR("[%s] must be >= [%s]",
PARAM_HNSW_STREAMER_DOCS_HARD_LIMIT.c_str(),
PARAM_HNSW_STREAMER_DOCS_SOFT_LIMIT.c_str());
return IndexError_InvalidArgument;
} else if (docs_soft_limit_ == 0UL) {
docs_soft_limit_ =
docs_hard_limit_ * HnswEntity::kDefaultDocsSoftLimitRatio;
}
if (ef_ == 0U) {
ef_ = HnswEntity::kDefaultEf;
}
if (ef_construction_ == 0U) {
ef_construction_ = HnswEntity::kDefaultEfConstruction;
}
if (neighbor_cnt_ == 0U) {
neighbor_cnt_ = HnswEntity::kDefaultNeighborCnt;
}
if (neighbor_cnt_ > HnswEntity::kMaxNeighborCnt) {
LOG_ERROR("[%s] must be in range (0,%d)",
PARAM_HNSW_STREAMER_MAX_NEIGHBOR_COUNT.c_str(),
HnswEntity::kMaxNeighborCnt);
return IndexError_InvalidArgument;
}
if (upper_neighbor_cnt_ == 0U) {
upper_neighbor_cnt_ = HnswEntity::kDefaultUpperNeighborCnt;
}
if (upper_neighbor_cnt_ > HnswEntity::kMaxNeighborCnt) {
LOG_ERROR("UpperNeighborCnt must be in range (0,%d)",
HnswEntity::kMaxNeighborCnt);
return IndexError_InvalidArgument;
}
if (min_neighbor_cnt_ > neighbor_cnt_) {
LOG_ERROR("[%s]-[%u] must be <= [%s]-[%u]",
PARAM_HNSW_STREAMER_MIN_NEIGHBOR_COUNT.c_str(), min_neighbor_cnt_,
PARAM_HNSW_STREAMER_MAX_NEIGHBOR_COUNT.c_str(), neighbor_cnt_);
return IndexError_InvalidArgument;
}
if (bf_negative_prob_ <= 0.0f || bf_negative_prob_ >= 1.0f) {
LOG_ERROR("[%s] must be in range (0,1)",
PARAM_HNSW_STREAMER_VISIT_BLOOMFILTER_NEGATIVE_PROB.c_str());
return IndexError_InvalidArgument;
}
if (scaling_factor_ == 0U) {
scaling_factor_ = HnswEntity::kDefaultScalingFactor;
}
if (scaling_factor_ < 5 || scaling_factor_ > 1000) {
LOG_ERROR("[%s] must be in range [5,1000]",
PARAM_HNSW_STREAMER_SCALING_FACTOR.c_str());
return IndexError_InvalidArgument;
}
if (max_scan_ratio_ <= 0.0f || max_scan_ratio_ > 1.0f) {
LOG_ERROR("[%s] must be in range (0.0f,1.0f]",
PARAM_HNSW_STREAMER_MAX_SCAN_RATIO.c_str());
return IndexError_InvalidArgument;
}
if (max_scan_limit_ < min_scan_limit_) {
LOG_ERROR("[%s] must be >= [%s]",
PARAM_HNSW_STREAMER_MAX_SCAN_LIMIT.c_str(),
PARAM_HNSW_STREAMER_MIN_SCAN_LIMIT.c_str());
return IndexError_InvalidArgument;
}
if (prune_cnt == 0UL) {
prune_cnt = upper_neighbor_cnt_;
}
if (chunk_size_ == 0UL) {
chunk_size_ = HnswEntity::kDefaultChunkSize;
}
if (chunk_size_ > HnswEntity::kMaxChunkSize) {
LOG_ERROR("[%s] must be < %zu", PARAM_HNSW_STREAMER_CHUNK_SIZE.c_str(),
HnswEntity::kMaxChunkSize);
return IndexError_InvalidArgument;
}
entity_.set_ef_construction(ef_construction_);
entity_.set_neighbor_cnt(neighbor_cnt_);
entity_.set_upper_neighbor_cnt(upper_neighbor_cnt_);
entity_.set_scaling_factor(scaling_factor_);
entity_.set_prune_cnt(prune_cnt);
entity_.set_vector_size(meta_.element_size());
entity_.set_chunk_size(chunk_size_);
entity_.set_filter_same_key(filter_same_key_);
entity_.set_get_vector(get_vector_enabled_);
entity_.set_min_neighbor_cnt(min_neighbor_cnt_);
int ret = entity_.init(docs_hard_limit_);
if (ret != 0) {
LOG_ERROR("Hnsw entity init failed for %s", IndexError::What(ret));
return ret;
}
LOG_DEBUG(
"Init params: maxIndexSize=%zu docsHardLimit=%zu docsSoftLimit=%zu "
"efConstruction=%u ef=%u neighborCnt=%u upperNeighborCnt=%u "
"scalingFactor=%u maxScanRatio=%.3f minScanLimit=%zu maxScanLimit=%zu "
"bfEnabled=%d bruteFoceThreshold=%zu bfNegativeProbility=%.5f "
"checkCrcEnabled=%d pruneSize=%zu vectorSize=%u chunkSize=%zu "
"filterSameKey=%u getVectorEnabled=%u minNeighborCount=%u "
"forcePadding=%u ",
max_index_size_, docs_hard_limit_, docs_soft_limit_, ef_construction_,
ef_, neighbor_cnt_, upper_neighbor_cnt_, scaling_factor_, max_scan_ratio_,
min_scan_limit_, max_scan_limit_, bf_enabled_, bruteforce_threshold_,
bf_negative_prob_, check_crc_enabled_, prune_cnt, meta_.element_size(),
chunk_size_, filter_same_key_, get_vector_enabled_, min_neighbor_cnt_,
force_padding_topk_enabled_);
alg_ = HnswAlgorithm::UPointer(new HnswAlgorithm(entity_));
ret = alg_->init();
if (ret != 0) {
return ret;
}
state_ = STATE_INITED;
return 0;
}
int HnswStreamer::cleanup(void) {
if (state_ == STATE_OPENED) {
this->close();
}
LOG_INFO("HnswStreamer cleanup");
meta_.clear();
metric_.reset();
stats_.clear();
entity_.cleanup();
if (alg_) {
alg_->cleanup();
}
max_index_size_ = 0UL;
docs_hard_limit_ = HnswEntity::kDefaultDocsHardLimit;
docs_soft_limit_ = 0UL;
neighbor_cnt_ = HnswEntity::kDefaultNeighborCnt;
upper_neighbor_cnt_ = HnswEntity::kDefaultUpperNeighborCnt;
ef_ = HnswEntity::kDefaultEf;
ef_construction_ = HnswEntity::kDefaultEfConstruction;
bf_enabled_ = false;
scaling_factor_ = HnswEntity::kDefaultScalingFactor;
bruteforce_threshold_ = HnswEntity::kDefaultBruteForceThreshold;
max_scan_limit_ = HnswEntity::kDefaultMaxScanLimit;
min_scan_limit_ = HnswEntity::kDefaultMinScanLimit;
chunk_size_ = HnswEntity::kDefaultChunkSize;
bf_negative_prob_ = HnswEntity::kDefaultBFNegativeProbility;
max_scan_ratio_ = HnswEntity::kDefaultScanRatio;
state_ = STATE_INIT;
check_crc_enabled_ = false;
filter_same_key_ = false;
get_vector_enabled_ = false;
return 0;
}
int HnswStreamer::open(IndexStorage::Pointer stg) {
LOG_INFO("HnswStreamer open");
if (ailego_unlikely(state_ != STATE_INITED)) {
LOG_ERROR("Open storage failed, init streamer first!");
return IndexError_NoReady;
}
int ret = entity_.open(std::move(stg), max_index_size_, check_crc_enabled_);
if (ret != 0) {
return ret;
}
IndexMeta index_meta;
ret = entity_.get_index_meta(&index_meta);
if (ret == IndexError_NoExist) {
// Set IndexMeta for the new index
ret = entity_.set_index_meta(meta_);
if (ret != 0) {
LOG_ERROR("Failed to set index meta for %s", IndexError::What(ret));
return ret;
}
} else if (ret != 0) {
LOG_ERROR("Failed to get index meta for %s", IndexError::What(ret));
return ret;
} else {
if (index_meta.dimension() != meta_.dimension() ||
index_meta.element_size() != meta_.element_size() ||
index_meta.metric_name() != meta_.metric_name() ||
index_meta.data_type() != meta_.data_type()) {
LOG_ERROR("IndexMeta mismatch from the previous in index");
return IndexError_Mismatch;
}
// The IndexMetric Params may be updated like MipsSquaredEuclidean
auto metric_params = index_meta.metric_params();
metric_params.merge(meta_.metric_params());
meta_.set_metric(index_meta.metric_name(), 0, metric_params);
}
metric_ = IndexFactory::CreateMetric(meta_.metric_name());
if (!metric_) {
LOG_ERROR("Failed to create metric %s", meta_.metric_name().c_str());
return IndexError_NoExist;
}
ret = metric_->init(meta_, meta_.metric_params());
if (ret != 0) {
LOG_ERROR("Failled to init metric, ret=%d", ret);
return ret;
}
if (!metric_->distance()) {
LOG_ERROR("Invalid metric distance");
return IndexError_InvalidArgument;
}
if (!metric_->batch_distance()) {
LOG_ERROR("Invalid metric batch distance");
return IndexError_InvalidArgument;
}
add_distance_ = metric_->distance();
add_batch_distance_ = metric_->batch_distance();
search_distance_ = add_distance_;
search_batch_distance_ = add_batch_distance_;
if (metric_->query_metric() && metric_->query_metric()->distance() &&
metric_->query_metric()->batch_distance()) {
search_distance_ = metric_->query_metric()->distance();
search_batch_distance_ = metric_->query_metric()->batch_distance();
}
state_ = STATE_OPENED;
magic_ = IndexContext::GenerateMagic();
return 0;
}
int HnswStreamer::close(void) {
LOG_INFO("HnswStreamer close");
stats_.clear();
meta_.set_metric(metric_->name(), 0, metric_->params());
entity_.set_index_meta(meta_);
int ret = entity_.close();
if (ret != 0) {
return ret;
}
state_ = STATE_INITED;
return 0;
}
int HnswStreamer::flush(uint64_t checkpoint) {
LOG_INFO("HnswStreamer flush checkpoint=%zu", (size_t)checkpoint);
meta_.set_metric(metric_->name(), 0, metric_->params());
entity_.set_index_meta(meta_);
return entity_.flush(checkpoint);
}
int HnswStreamer::dump(const IndexDumper::Pointer &dumper) {
LOG_INFO("HnswStreamer dump");
shared_mutex_.lock();
AILEGO_DEFER([&]() { shared_mutex_.unlock(); });
meta_.set_searcher("HnswSearcher", HnswEntity::kRevision, ailego::Params());
int ret = IndexHelper::SerializeToDumper(meta_, dumper.get());
if (ret != 0) {
LOG_ERROR("Failed to serialize meta into dumper.");
return ret;
}
return entity_.dump(dumper);
}
IndexStreamer::Context::Pointer HnswStreamer::create_context(void) const {
if (ailego_unlikely(state_ != STATE_OPENED)) {
LOG_ERROR("Create context failed, open storage first!");
return Context::Pointer();
}
HnswEntity::Pointer entity = entity_.clone();
if (ailego_unlikely(!entity)) {
LOG_ERROR("CreateContext clone init failed");
return Context::Pointer();
}
HnswContext *ctx =
new (std::nothrow) HnswContext(meta_.dimension(), metric_, entity);
if (ailego_unlikely(ctx == nullptr)) {
LOG_ERROR("Failed to new HnswContext");
return Context::Pointer();
}
ctx->set_ef(ef_);
ctx->set_max_scan_limit(max_scan_limit_);
ctx->set_min_scan_limit(min_scan_limit_);
ctx->set_max_scan_ratio(max_scan_ratio_);
ctx->set_filter_mode(bf_enabled_ ? VisitFilter::BloomFilter
: VisitFilter::ByteMap);
ctx->set_filter_negative_probility(bf_negative_prob_);
ctx->set_magic(magic_);
ctx->set_force_padding_topk(force_padding_topk_enabled_);
ctx->set_bruteforce_threshold(bruteforce_threshold_);
if (ailego_unlikely(ctx->init(HnswContext::kStreamerContext)) != 0) {
LOG_ERROR("Init HnswContext failed");
delete ctx;
return Context::Pointer();
}
uint32_t estimate_doc_count = 0;
if (meta_.streamer_params().get(PARAM_HNSW_STREAMER_ESTIMATE_DOC_COUNT,
&estimate_doc_count)) {
LOG_DEBUG("HnswStreamer doc_count[%zu] estimate[%zu]",
(size_t)entity_.doc_cnt(), (size_t)estimate_doc_count);
}
ctx->check_need_adjuct_ctx(std::max(entity_.doc_cnt(), estimate_doc_count));
return Context::Pointer(ctx);
}
IndexProvider::Pointer HnswStreamer::create_provider(void) const {
LOG_DEBUG("HnswStreamer create provider");
auto entity = entity_.clone();
if (ailego_unlikely(!entity)) {
LOG_ERROR("Clone HnswEntity failed");
return nullptr;
}
return Provider::Pointer(
new HnswIndexProvider(meta_, entity, "HnswStreamer"));
}
int HnswStreamer::update_context(HnswContext *ctx) const {
const HnswEntity::Pointer entity = entity_.clone();
if (!entity) {
LOG_ERROR("Failed to clone search context entity");
return IndexError_Runtime;
}
ctx->set_max_scan_limit(max_scan_limit_);
ctx->set_min_scan_limit(min_scan_limit_);
ctx->set_max_scan_ratio(max_scan_ratio_);
ctx->set_bruteforce_threshold(bruteforce_threshold_);
return ctx->update_context(HnswContext::kStreamerContext, meta_, metric_,
entity, magic_);
}
//! Add a vector with id into index
int HnswStreamer::add_with_id_impl(uint32_t id, const void *query,
const IndexQueryMeta &qmeta,
IndexStreamer::Context::Pointer &context) {
int ret = check_params(query, qmeta);
if (ailego_unlikely(ret != 0)) {
return ret;
}
HnswContext *ctx = dynamic_cast<HnswContext *>(context.get());
ailego_do_if_false(ctx) {
LOG_ERROR("Cast context to HnswContext failed");
return IndexError_Cast;
}
if (ctx->magic() != magic_) {
//! context is created by another searcher or streamer
ret = update_context(ctx);
if (ret != 0) {
return ret;
}
}
if (ailego_unlikely(entity_.doc_cnt() >= docs_soft_limit_)) {
if (entity_.doc_cnt() >= docs_hard_limit_) {
LOG_ERROR("Current docs %u exceed [%s]", entity_.doc_cnt(),
PARAM_HNSW_STREAMER_DOCS_HARD_LIMIT.c_str());
const std::lock_guard<std::mutex> lk(mutex_);
(*stats_.mutable_discarded_count())++;
return IndexError_IndexFull;
} else {
LOG_WARN("Current docs %u exceed [%s]", entity_.doc_cnt(),
PARAM_HNSW_STREAMER_DOCS_SOFT_LIMIT.c_str());
}
}
if (ailego_unlikely(!shared_mutex_.try_lock_shared())) {
LOG_ERROR("Cannot add vector while dumping index");
(*stats_.mutable_discarded_count())++;
return IndexError_Unsupported;
}
AILEGO_DEFER([&]() { shared_mutex_.unlock_shared(); });
ctx->clear();
ctx->update_dist_caculator_distance(add_distance_, add_batch_distance_);
ctx->reset_query(query);
ctx->check_need_adjuct_ctx(entity_.doc_cnt());
if (metric_->support_train()) {
const std::lock_guard<std::mutex> lk(mutex_);
ret = metric_->train(query, meta_.dimension());
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw streamer metric train failed");
(*stats_.mutable_discarded_count())++;
return ret;
}
}
level_t level = alg_->get_random_level();
ret = entity_.add_vector_with_id(level, id, query);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw streamer add vector failed");
(*stats_.mutable_discarded_count())++;
return ret;
}
ret = alg_->add_node(id, level, ctx);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw stramer add node failed");
(*stats_.mutable_discarded_count())++;
return ret;
}
if (ailego_unlikely(ctx->error())) {
(*stats_.mutable_discarded_count())++;
return IndexError_Runtime;
}
(*stats_.mutable_added_count())++;
return 0;
}
//! Add a vector into index
int HnswStreamer::add_impl(uint64_t pkey, const void *query,
const IndexQueryMeta &qmeta,
IndexStreamer::Context::Pointer &context) {
int ret = check_params(query, qmeta);
if (ailego_unlikely(ret != 0)) {
return ret;
}
HnswContext *ctx = dynamic_cast<HnswContext *>(context.get());
ailego_do_if_false(ctx) {
LOG_ERROR("Cast context to HnswContext failed");
return IndexError_Cast;
}
if (ctx->magic() != magic_) {
//! context is created by another searcher or streamer
ret = update_context(ctx);
if (ret != 0) {
return ret;
}
}
if (ailego_unlikely(entity_.doc_cnt() >= docs_soft_limit_)) {
if (entity_.doc_cnt() >= docs_hard_limit_) {
LOG_ERROR("Current docs %u exceed [%s]", entity_.doc_cnt(),
PARAM_HNSW_STREAMER_DOCS_HARD_LIMIT.c_str());
const std::lock_guard<std::mutex> lk(mutex_);
(*stats_.mutable_discarded_count())++;
return IndexError_IndexFull;
} else {
LOG_WARN("Current docs %u exceed [%s]", entity_.doc_cnt(),
PARAM_HNSW_STREAMER_DOCS_SOFT_LIMIT.c_str());
}
}
if (ailego_unlikely(!shared_mutex_.try_lock_shared())) {
LOG_ERROR("Cannot add vector while dumping index");
(*stats_.mutable_discarded_count())++;
return IndexError_Unsupported;
}
AILEGO_DEFER([&]() { shared_mutex_.unlock_shared(); });
ctx->clear();
ctx->update_dist_caculator_distance(add_distance_, add_batch_distance_);
ctx->reset_query(query);
ctx->check_need_adjuct_ctx(entity_.doc_cnt());
if (metric_->support_train()) {
const std::lock_guard<std::mutex> lk(mutex_);
ret = metric_->train(query, meta_.dimension());
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw streamer metric train failed");
(*stats_.mutable_discarded_count())++;
return ret;
}
}
level_t level = alg_->get_random_level();
node_id_t id;
ret = entity_.add_vector(level, pkey, query, &id);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw streamer add vector failed");
(*stats_.mutable_discarded_count())++;
return ret;
}
ret = alg_->add_node(id, level, ctx);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw stramer add node failed");
(*stats_.mutable_discarded_count())++;
return ret;
}
if (ailego_unlikely(ctx->error())) {
(*stats_.mutable_discarded_count())++;
return IndexError_Runtime;
}
(*stats_.mutable_added_count())++;
return 0;
}
int HnswStreamer::search_impl(const void *query, const IndexQueryMeta &qmeta,
IndexStreamer::Context::Pointer &context) const {
return search_impl(query, qmeta, 1, context);
}
//! Similarity search
int HnswStreamer::search_impl(const void *query, const IndexQueryMeta &qmeta,
uint32_t count,
IndexStreamer::Context::Pointer &context) const {
int ret = check_params(query, qmeta);
if (ailego_unlikely(ret != 0)) {
return ret;
}
HnswContext *ctx = dynamic_cast<HnswContext *>(context.get());
ailego_do_if_false(ctx) {
LOG_ERROR("Cast context to HnswContext failed");
return IndexError_Cast;
}
if (entity_.doc_cnt() <= ctx->get_bruteforce_threshold()) {
return search_bf_impl(query, qmeta, count, context);
}
if (ctx->magic() != magic_) {
//! context is created by another searcher or streamer
ret = update_context(ctx);
if (ret != 0) {
return ret;
}
}
ctx->clear();
ctx->update_dist_caculator_distance(search_distance_, search_batch_distance_);
ctx->resize_results(count);
ctx->check_need_adjuct_ctx(entity_.doc_cnt());
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
ret = alg_->search(ctx);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Hnsw searcher fast search failed");
return ret;
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
if (ailego_unlikely(ctx->error())) {
return IndexError_Runtime;
}
return 0;
}
void HnswStreamer::print_debug_info() {
for (node_id_t id = 0; id < entity_.doc_cnt(); ++id) {
if (entity_.get_key(id) == kInvalidKey) {
continue;
}
Neighbors neighbours = entity_.get_neighbors(0, id);
std::cout << "node: " << id << "; ";
if (neighbours.size() == 0) std::cout << std::endl;
for (uint32_t i = 0; i < neighbours.size(); ++i) {
std::cout << neighbours[i];
if (i == neighbours.size() - 1) {
std::cout << std::endl;
} else {
std::cout << ", ";
}
}
}
// entity_.print_key_map();
}
int HnswStreamer::search_bf_impl(
const void *query, const IndexQueryMeta &qmeta,
IndexStreamer::Context::Pointer &context) const {
return search_bf_impl(query, qmeta, 1, context);
}
int HnswStreamer::search_bf_impl(
const void *query, const IndexQueryMeta &qmeta, uint32_t count,
IndexStreamer::Context::Pointer &context) const {
int ret = check_params(query, qmeta);
if (ailego_unlikely(ret != 0)) {
return ret;
}
HnswContext *ctx = dynamic_cast<HnswContext *>(context.get());
ailego_do_if_false(ctx) {
LOG_ERROR("Cast context to HnswContext failed");
return IndexError_Cast;
}
if (ctx->magic() != magic_) {
//! context is created by another searcher or streamer
ret = update_context(ctx);
if (ret != 0) {
return ret;
}
}
ctx->clear();
ctx->update_dist_caculator_distance(search_distance_, search_batch_distance_);
ctx->resize_results(count);
if (ctx->group_by_search()) {
if (!ctx->group_by().is_valid()) {
LOG_ERROR("Invalid group-by function");
return IndexError_InvalidArgument;
}
std::function<std::string(node_id_t)> group_by = [&](node_id_t id) {
return ctx->group_by()(entity_.get_key(id));
};
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
ctx->group_topk_heaps().clear();
for (node_id_t id = 0; id < entity_.doc_cnt(); ++id) {
if (entity_.get_key(id) == kInvalidKey) {
continue;
}
if (!ctx->filter().is_valid() || !ctx->filter()(entity_.get_key(id))) {
dist_t dist = ctx->dist_calculator().dist(id);
std::string group_id = group_by(id);
auto &topk_heap = ctx->group_topk_heaps()[group_id];
if (topk_heap.empty()) {
topk_heap.limit(ctx->group_topk());
}
topk_heap.emplace_back(id, dist);
}
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
} else {
auto &filter = ctx->filter();
auto &topk = ctx->topk_heap();
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
topk.clear();
for (node_id_t id = 0; id < entity_.doc_cnt(); ++id) {
if (entity_.get_key(id) == kInvalidKey) {
continue;
}
if (!filter.is_valid() || !filter(entity_.get_key(id))) {
dist_t dist = ctx->dist_calculator().batch_dist(id);
topk.emplace(id, dist);
}
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
}
if (ailego_unlikely(ctx->error())) {
return IndexError_Runtime;
}
return 0;
}
int HnswStreamer::search_bf_by_p_keys_impl(
const void *query, const std::vector<std::vector<uint64_t>> &p_keys,
const IndexQueryMeta &qmeta, uint32_t count,
Context::Pointer &context) const {
int ret = check_params(query, qmeta);
if (ailego_unlikely(ret != 0)) {
return ret;
}
if (ailego_unlikely(p_keys.size() != count)) {
LOG_ERROR("The size of p_keys is not equal to count");
return IndexError_InvalidArgument;
}
HnswContext *ctx = dynamic_cast<HnswContext *>(context.get());
ailego_do_if_false(ctx) {
LOG_ERROR("Cast context to HnswContext failed");
return IndexError_Cast;
}
if (ctx->magic() != magic_) {
//! context is created by another searcher or streamer
ret = update_context(ctx);
if (ret != 0) {
return ret;
}
}
ctx->clear();
ctx->update_dist_caculator_distance(search_distance_, search_batch_distance_);
ctx->resize_results(count);
if (ctx->group_by_search()) {
if (!ctx->group_by().is_valid()) {
LOG_ERROR("Invalid group-by function");
return IndexError_InvalidArgument;
}
std::function<std::string(node_id_t)> group_by = [&](node_id_t id) {
return ctx->group_by()(entity_.get_key(id));
};
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
ctx->group_topk_heaps().clear();
for (size_t idx = 0; idx < p_keys[q].size(); ++idx) {
uint64_t pk = p_keys[q][idx];
if (!ctx->filter().is_valid() || !ctx->filter()(pk)) {
node_id_t id = entity_.get_id(pk);
if (id != kInvalidNodeId) {
dist_t dist = ctx->dist_calculator().dist(id);
std::string group_id = group_by(id);
auto &topk_heap = ctx->group_topk_heaps()[group_id];
if (topk_heap.empty()) {
topk_heap.limit(ctx->group_topk());
}
topk_heap.emplace_back(id, dist);
}
}
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
} else {
auto &filter = ctx->filter();
auto &topk = ctx->topk_heap();
for (size_t q = 0; q < count; ++q) {
ctx->reset_query(query);
topk.clear();
for (size_t idx = 0; idx < p_keys[q].size(); ++idx) {
key_t pk = p_keys[q][idx];
if (!filter.is_valid() || !filter(pk)) {
node_id_t id = entity_.get_id(pk);
if (id != kInvalidNodeId) {
dist_t dist = ctx->dist_calculator().dist(id);
topk.emplace(id, dist);
}
}
}
ctx->topk_to_result(q);
query = static_cast<const char *>(query) + qmeta.element_size();
}
}
if (ailego_unlikely(ctx->error())) {
return IndexError_Runtime;
}
return 0;
}
INDEX_FACTORY_REGISTER_STREAMER(HnswStreamer);
} // namespace core
} // namespace zvec
+228
View File
@@ -0,0 +1,228 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <ailego/parallel/lock.h>
#include "framework/index_framework.h"
#include "hnsw_algorithm.h"
#include "hnsw_streamer_entity.h"
namespace zvec {
namespace core {
class HnswStreamer : public IndexStreamer {
public:
using ContextPointer = IndexStreamer::Context::Pointer;
HnswStreamer(void);
virtual ~HnswStreamer(void);
HnswStreamer(const HnswStreamer &streamer) = delete;
HnswStreamer &operator=(const HnswStreamer &streamer) = delete;
protected:
//! Initialize Streamer
virtual int init(const IndexMeta &imeta,
const ailego::Params &params) override;
//! Cleanup Streamer
virtual int cleanup(void) override;
//! Create a context
virtual Context::Pointer create_context(void) const override;
//! Create a new iterator
virtual IndexProvider::Pointer create_provider(void) const override;
//! Add a vector into index
virtual int add_impl(uint64_t pkey, const void *query,
const IndexQueryMeta &qmeta,
Context::Pointer &context) override;
//! Add a vector with id into index
virtual int add_with_id_impl(uint32_t id, const void *query,
const IndexQueryMeta &qmeta,
Context::Pointer &context) override;
//! Similarity search
virtual int search_impl(const void *query, const IndexQueryMeta &qmeta,
Context::Pointer &context) const override;
//! Similarity search
virtual int search_impl(const void *query, const IndexQueryMeta &qmeta,
uint32_t count,
Context::Pointer &context) const override;
//! Similarity brute force search
virtual int search_bf_impl(const void *query, const IndexQueryMeta &qmeta,
Context::Pointer &context) const override;
//! Similarity brute force search
virtual int search_bf_impl(const void *query, const IndexQueryMeta &qmeta,
uint32_t count,
Context::Pointer &context) const override;
//! Linear search by primary keys
virtual int search_bf_by_p_keys_impl(
const void *query, const std::vector<std::vector<uint64_t>> &p_keys,
const IndexQueryMeta &qmeta, ContextPointer &context) const override {
return search_bf_by_p_keys_impl(query, p_keys, qmeta, 1, context);
}
//! Linear search by primary keys
virtual int search_bf_by_p_keys_impl(
const void *query, const std::vector<std::vector<uint64_t>> &p_keys,
const IndexQueryMeta &qmeta, uint32_t count,
ContextPointer &context) const override;
//! Fetch vector by key
virtual const void *get_vector(uint64_t key) const override {
return entity_.get_vector_by_key(key);
}
virtual int get_vector(const uint64_t key,
IndexStorage::MemoryBlock &block) const override {
return entity_.get_vector_by_key(key, block);
}
//! Fetch vector by id
virtual const void *get_vector_by_id(uint32_t id) const override {
return entity_.get_vector(id);
}
virtual int get_vector_by_id(
const uint32_t id, IndexStorage::MemoryBlock &block) const override {
return entity_.get_vector(id, block);
}
//! Open index from file path
virtual int open(IndexStorage::Pointer stg) override;
//! Close file
virtual int close(void) override;
//! flush file
virtual int flush(uint64_t checkpoint) override;
//! Dump index into storage
virtual int dump(const IndexDumper::Pointer &dumper) override;
//! Retrieve statistics
virtual const Stats &stats(void) const override {
return stats_;
}
//! Retrieve meta of index
virtual const IndexMeta &meta(void) const override {
return meta_;
}
virtual void print_debug_info() override;
private:
inline int check_params(const void *query,
const IndexQueryMeta &qmeta) const {
if (ailego_unlikely(!query)) {
LOG_ERROR("null query");
return IndexError_InvalidArgument;
}
if (ailego_unlikely(qmeta.dimension() != meta_.dimension() ||
qmeta.data_type() != meta_.data_type() ||
qmeta.element_size() != meta_.element_size())) {
LOG_ERROR("Unsupported query meta");
return IndexError_Mismatch;
}
return 0;
}
inline int check_sparse_count_is_zero(const uint32_t *sparse_count,
uint32_t count) const {
for (uint32_t i = 0; i < count; ++i) {
if (sparse_count[i] != 0)
LOG_ERROR("Sparse cout is not empty. Index: %u, Sparse Count: %u", i,
sparse_count[i]);
return IndexError_InvalidArgument;
}
return 0;
}
private:
//! To share ctx across streamer/searcher, we need to update the context for
//! current streamer/searcher
int update_context(HnswContext *ctx) const;
private:
enum State { STATE_INIT = 0, STATE_INITED = 1, STATE_OPENED = 2 };
class Stats : public IndexStreamer::Stats {
public:
void clear(void) {
set_revision_id(0u);
set_loaded_count(0u);
set_added_count(0u);
set_discarded_count(0u);
set_index_size(0u);
set_dumped_size(0u);
set_check_point(0u);
set_create_time(0u);
set_update_time(0u);
clear_attributes();
}
};
HnswStreamerEntity entity_;
HnswAlgorithm::UPointer alg_;
IndexMeta meta_{};
IndexMetric::Pointer metric_{};
IndexMetric::MatrixDistance add_distance_{};
IndexMetric::MatrixDistance search_distance_{};
IndexMetric::MatrixBatchDistance add_batch_distance_{};
IndexMetric::MatrixBatchDistance search_batch_distance_{};
Stats stats_{};
std::mutex mutex_{};
size_t max_index_size_{0UL};
size_t chunk_size_{HnswEntity::kDefaultChunkSize};
size_t docs_hard_limit_{HnswEntity::kDefaultDocsHardLimit};
size_t docs_soft_limit_{0UL};
uint32_t neighbor_cnt_{HnswEntity::kDefaultNeighborCnt};
uint32_t min_neighbor_cnt_{0u};
uint32_t upper_neighbor_cnt_{HnswEntity::kDefaultUpperNeighborCnt};
uint32_t ef_{HnswEntity::kDefaultEf};
uint32_t ef_construction_{HnswEntity::kDefaultEfConstruction};
uint32_t scaling_factor_{HnswEntity::kDefaultScalingFactor};
size_t bruteforce_threshold_{HnswEntity::kDefaultBruteForceThreshold};
size_t max_scan_limit_{HnswEntity::kDefaultMaxScanLimit};
size_t min_scan_limit_{HnswEntity::kDefaultMinScanLimit};
float bf_negative_prob_{HnswEntity::kDefaultBFNegativeProbility};
float max_scan_ratio_{HnswEntity::kDefaultScanRatio};
uint32_t magic_{0U};
State state_{STATE_INIT};
bool bf_enabled_{false};
bool check_crc_enabled_{false};
bool filter_same_key_{false};
bool get_vector_enabled_{false};
bool force_padding_topk_enabled_{false};
bool use_id_map_{true};
//! avoid add vector while dumping index
ailego::SharedMutex shared_mutex_{};
};
} // namespace core
} // namespace zvec
@@ -0,0 +1,701 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "hnsw_streamer_entity.h"
#include <ailego/utility/memory_helper.h>
// #define DEBUG_PRINT
namespace zvec {
namespace core {
HnswStreamerEntity::HnswStreamerEntity(IndexStreamer::Stats &stats)
: stats_(stats) {}
HnswStreamerEntity::~HnswStreamerEntity() {}
int HnswStreamerEntity::init(size_t max_doc_cnt) {
if (std::pow(scaling_factor(), kMaxGraphLayers) < max_doc_cnt) {
LOG_ERROR("scalingFactor=%zu is too small", scaling_factor());
return IndexError_InvalidArgument;
}
std::lock_guard<std::mutex> lock(mutex_);
broker_ = std::make_shared<ChunkBroker>(stats_);
upper_neighbor_index_ = std::make_shared<NIHashMap>();
keys_map_lock_ = std::make_shared<ailego::SharedMutex>();
keys_map_ = std::make_shared<HashMap<key_t, node_id_t>>();
if (!keys_map_ || !upper_neighbor_index_ || !broker_ || !keys_map_lock_) {
LOG_ERROR("HnswStreamerEntity new object failed");
return IndexError_NoMemory;
}
keys_map_->set_empty_key(kInvalidKey);
neighbor_size_ = neighbors_size();
upper_neighbor_size_ = upper_neighbors_size();
//! vector + key + level 0 neighbors
size_t size = vector_size() + sizeof(key_t) + neighbor_size_;
size = AlignSize(size);
set_node_size(size);
return 0;
}
int HnswStreamerEntity::cleanup() {
std::lock_guard<std::mutex> lock(mutex_);
mutable_header()->clear();
chunk_size_ = kDefaultChunkSize;
node_index_mask_bits_ = 0U;
node_index_mask_ = 0U;
node_cnt_per_chunk_ = 0U;
neighbor_size_ = 0U;
upper_neighbor_size_ = 0U;
if (upper_neighbor_index_) {
upper_neighbor_index_->cleanup();
}
if (keys_map_) {
keys_map_->clear();
}
node_chunks_.clear();
upper_neighbor_chunks_.clear();
filter_same_key_ = false;
get_vector_enabled_ = false;
broker_.reset();
return 0;
}
int HnswStreamerEntity::update_neighbors(
level_t level, node_id_t id,
const std::vector<std::pair<node_id_t, dist_t>> &neighbors) {
char buffer[neighbor_size_];
NeighborsHeader *hd = reinterpret_cast<NeighborsHeader *>(buffer);
hd->neighbor_cnt = neighbors.size();
size_t i = 0;
for (; i < neighbors.size(); ++i) {
hd->neighbors[i] = neighbors[i].first;
}
auto loc = get_neighbor_chunk_loc(level, id);
size_t size = reinterpret_cast<char *>(&hd->neighbors[i]) - &buffer[0];
size_t ret = loc.first->write(loc.second, hd, size);
if (ailego_unlikely(ret != size)) {
LOG_ERROR("Write neighbor header failed, ret=%zu", ret);
return IndexError_Runtime;
}
return 0;
}
const Neighbors HnswStreamerEntity::get_neighbors(level_t level,
node_id_t id) const {
Chunk *chunk = nullptr;
size_t offset = 0UL;
size_t neighbor_size = neighbor_size_;
if (level == 0UL) {
uint32_t chunk_idx = id >> node_index_mask_bits_;
offset =
(id & node_index_mask_) * node_size() + vector_size() + sizeof(key_t);
sync_chunks(ChunkBroker::CHUNK_TYPE_NODE, chunk_idx, &node_chunks_);
ailego_assert_with(chunk_idx < node_chunks_.size(), "invalid chunk idx");
chunk = node_chunks_[chunk_idx].get();
} else {
auto p = get_upper_neighbor_chunk_loc(level, id);
chunk = upper_neighbor_chunks_[p.first].get();
offset = p.second;
neighbor_size = upper_neighbor_size_;
}
ailego_assert_with(offset < chunk->data_size(), "invalid chunk offset");
IndexStorage::MemoryBlock neighbor_block;
size_t size = chunk->read(offset, neighbor_block, neighbor_size);
if (ailego_unlikely(size != neighbor_size)) {
LOG_ERROR("Read neighbor header failed, ret=%zu", size);
return Neighbors();
}
return Neighbors(std::move(neighbor_block));
}
//! Get vector data by key
const void *HnswStreamerEntity::get_vector(node_id_t id) const {
auto loc = get_vector_chunk_loc(id);
const void *vec = nullptr;
ailego_assert_with(loc.first < node_chunks_.size(), "invalid chunk idx");
ailego_assert_with(loc.second < node_chunks_[loc.first]->data_size(),
"invalid chunk offset");
size_t read_size = vector_size();
size_t ret = node_chunks_[loc.first]->read(loc.second, &vec, read_size);
if (ailego_unlikely(ret != read_size)) {
LOG_ERROR("Read vector failed, offset=%u, read size=%zu, ret=%zu",
loc.second, read_size, ret);
}
return vec;
}
int HnswStreamerEntity::get_vector(const node_id_t *ids, uint32_t count,
const void **vecs) const {
for (auto i = 0U; i < count; ++i) {
auto loc = get_vector_chunk_loc(ids[i]);
ailego_assert_with(loc.first < node_chunks_.size(), "invalid chunk idx");
ailego_assert_with(loc.second < node_chunks_[loc.first]->data_size(),
"invalid chunk offset");
size_t read_size = vector_size();
size_t ret = node_chunks_[loc.first]->read(loc.second, &vecs[i], read_size);
if (ailego_unlikely(ret != read_size)) {
LOG_ERROR("Read vector failed, offset=%u, read size=%zu, ret=%zu",
loc.second, read_size, ret);
return IndexError_ReadData;
}
}
return 0;
}
int HnswStreamerEntity::get_vector(const node_id_t id,
IndexStorage::MemoryBlock &block) const {
auto loc = get_vector_chunk_loc(id);
ailego_assert_with(loc.first < node_chunks_.size(), "invalid chunk idx");
ailego_assert_with(loc.second < node_chunks_[loc.first]->data_size(),
"invalid chunk offset");
size_t read_size = vector_size();
size_t ret = node_chunks_[loc.first]->read(loc.second, block, read_size);
if (ailego_unlikely(ret != read_size)) {
LOG_ERROR("Read vector failed, offset=%u, read size=%zu, ret=%zu",
loc.second, read_size, ret);
return IndexError_ReadData;
}
return 0;
}
int HnswStreamerEntity::get_vector(
const node_id_t *ids, uint32_t count,
std::vector<IndexStorage::MemoryBlock> &vec_blocks) const {
vec_blocks.resize(count);
for (auto i = 0U; i < count; ++i) {
auto loc = get_vector_chunk_loc(ids[i]);
ailego_assert_with(loc.first < node_chunks_.size(), "invalid chunk idx");
ailego_assert_with(loc.second < node_chunks_[loc.first]->data_size(),
"invalid chunk offset");
size_t read_size = vector_size();
size_t ret =
node_chunks_[loc.first]->read(loc.second, vec_blocks[i], read_size);
if (ailego_unlikely(ret != read_size)) {
LOG_ERROR("Read vector failed, offset=%u, read size=%zu, ret=%zu",
loc.second, read_size, ret);
return IndexError_ReadData;
}
}
return 0;
}
key_t HnswStreamerEntity::get_key(node_id_t id) const {
if (use_key_info_map_) {
auto loc = get_key_chunk_loc(id);
IndexStorage::MemoryBlock key_block;
ailego_assert_with(loc.first < node_chunks_.size(), "invalid chunk idx");
ailego_assert_with(loc.second < node_chunks_[loc.first]->data_size(),
"invalid chunk offset");
size_t ret =
node_chunks_[loc.first]->read(loc.second, key_block, sizeof(key_t));
if (ailego_unlikely(ret != sizeof(key_t))) {
LOG_ERROR("Read vector failed, ret=%zu", ret);
return kInvalidKey;
}
return *reinterpret_cast<const key_t *>(key_block.data());
} else {
return id;
}
}
void HnswStreamerEntity::add_neighbor(level_t level, node_id_t id,
uint32_t size, node_id_t neighbor_id) {
auto loc = get_neighbor_chunk_loc(level, id);
size_t offset =
loc.second + sizeof(NeighborsHeader) + size * sizeof(node_id_t);
ailego_assert_with(size < neighbor_cnt(level), "invalid neighbor size");
ailego_assert_with(offset < loc.first->data_size(), "invalid chunk offset");
size_t ret = loc.first->write(offset, &neighbor_id, sizeof(node_id_t));
if (ailego_unlikely(ret != sizeof(node_id_t))) {
LOG_ERROR("Write neighbor id failed, ret=%zu", ret);
return;
}
uint32_t neighbors = size + 1;
ret = loc.first->write(loc.second, &neighbors, sizeof(uint32_t));
if (ailego_unlikely(ret != sizeof(uint32_t))) {
LOG_ERROR("Write neighbor cnt failed, ret=%zu", ret);
}
return;
}
int HnswStreamerEntity::init_chunks(const Chunk::Pointer &header_chunk) {
if (header_chunk->data_size() < header_size()) {
LOG_ERROR("Invalid header chunk size");
return IndexError_InvalidFormat;
}
IndexStorage::MemoryBlock header_block;
size_t size = header_chunk->read(0UL, header_block, header_size());
if (ailego_unlikely(size != header_size())) {
LOG_ERROR("Read header chunk failed");
return IndexError_ReadData;
}
*mutable_header() =
*reinterpret_cast<const HNSWHeader *>(header_block.data());
int ret = check_hnsw_index(&header());
if (ret != 0) {
broker_->close();
return ret;
}
node_chunks_.resize(broker_->get_chunk_cnt(ChunkBroker::CHUNK_TYPE_NODE));
for (auto seq = 0UL; seq < node_chunks_.size(); ++seq) {
node_chunks_[seq] = broker_->get_chunk(ChunkBroker::CHUNK_TYPE_NODE, seq);
if (!node_chunks_[seq]) {
LOG_ERROR("Missing hnsw streamer data chunk %zu th of %zu", seq,
node_chunks_.size());
return IndexError_InvalidFormat;
}
}
upper_neighbor_chunks_.resize(
broker_->get_chunk_cnt(ChunkBroker::CHUNK_TYPE_UPPER_NEIGHBOR));
for (auto seq = 0UL; seq < upper_neighbor_chunks_.size(); ++seq) {
upper_neighbor_chunks_[seq] =
broker_->get_chunk(ChunkBroker::CHUNK_TYPE_UPPER_NEIGHBOR, seq);
if (!upper_neighbor_chunks_[seq]) {
LOG_ERROR("Missing hnsw streamer index chunk %zu th of %zu", seq,
upper_neighbor_chunks_.size());
return IndexError_InvalidFormat;
}
}
return 0;
}
int HnswStreamerEntity::open(IndexStorage::Pointer stg, uint64_t max_index_size,
bool check_crc) {
std::lock_guard<std::mutex> lock(mutex_);
bool huge_page = stg->isHugePage();
LOG_DEBUG("huge_page: %d", (int)huge_page);
int ret = init_chunk_params(max_index_size, huge_page);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("init_chunk_params failed for %s", IndexError::What(ret));
return ret;
}
ret = broker_->open(std::move(stg), max_index_size_, chunk_size_, check_crc);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Open index failed for %s", IndexError::What(ret));
return ret;
}
ret = upper_neighbor_index_->init(broker_, upper_neighbor_chunk_size_,
scaling_factor(), estimate_doc_capacity(),
kUpperHashMemoryInflateRatio);
if (ailego_unlikely(ret != 0)) {
LOG_ERROR("Init neighbor hash map failed");
return ret;
}
//! init header
auto header_chunk = broker_->get_chunk(ChunkBroker::CHUNK_TYPE_HEADER,
ChunkBroker::kDefaultChunkSeqId);
if (!header_chunk) { // open empty index, create one
auto p =
broker_->alloc_chunk(ChunkBroker::CHUNK_TYPE_HEADER,
ChunkBroker::kDefaultChunkSeqId, header_size());
if (ailego_unlikely(p.first != 0)) {
LOG_ERROR("Alloc header chunk failed");
return p.first;
}
size_t size = p.second->write(0UL, &header(), header_size());
if (ailego_unlikely(size != header_size())) {
LOG_ERROR("Write header chunk failed");
return IndexError_WriteData;
}
return 0;
}
//! Open an exist hnsw index
ret = init_chunks(header_chunk);
if (ailego_unlikely(ret != 0)) {
return ret;
}
//! total docs including features wrote in index but neighbors may not ready
node_id_t total_vecs = 0;
if (node_chunks_.size() > 0) {
size_t last_idx = node_chunks_.size() - 1;
auto last_chunk = node_chunks_[last_idx];
if (last_chunk->data_size() % node_size()) {
LOG_WARN("The index may broken");
return IndexError_InvalidFormat;
}
total_vecs = last_idx * node_cnt_per_chunk_ +
node_chunks_[last_idx]->data_size() / node_size();
}
LOG_INFO(
"Open index, neighborCnt=%zu upperneighborCnt=%zu "
"efConstruction=%zu curDocCnt=%u totalVecs=%u maxLevel=%u",
neighbor_cnt(), upper_neighbor_cnt(), ef_construction(), doc_cnt(),
total_vecs, cur_max_level());
//! try to correct the docCnt if index not fully flushed
if (doc_cnt() != total_vecs) {
LOG_WARN("Index closed abnormally, using totalVecs as curDocCnt");
*mutable_doc_cnt() = total_vecs;
}
if (filter_same_key_ || get_vector_enabled_) {
if (use_key_info_map_) {
for (node_id_t id = 0U; id < doc_cnt(); ++id) {
if (get_key(id) == kInvalidKey) {
continue;
}
(*keys_map_)[get_key(id)] = id;
}
}
}
stats_.set_loaded_count(doc_cnt());
return 0;
}
int HnswStreamerEntity::close() {
LOG_DEBUG("close index");
std::lock_guard<std::mutex> lock(mutex_);
flush_header();
mutable_header()->reset();
upper_neighbor_index_->cleanup();
keys_map_->clear();
header_.clear();
node_chunks_.clear();
upper_neighbor_chunks_.clear();
return broker_->close();
}
int HnswStreamerEntity::flush(uint64_t checkpoint) {
LOG_INFO("Flush index, curDocs=%u", doc_cnt());
std::lock_guard<std::mutex> lock(mutex_);
flush_header();
int ret = broker_->flush(checkpoint);
if (ret != 0) {
return ret;
}
return 0;
}
int HnswStreamerEntity::dump(const IndexDumper::Pointer &dumper) {
LOG_INFO("Dump index, curDocs=%u", doc_cnt());
//! sort by keys, to support get_vector by key in searcher
std::vector<key_t> keys(doc_cnt());
for (node_id_t i = 0; i < doc_cnt(); ++i) {
keys[i] = get_key(i);
}
//! dump neighbors
auto get_level = [&](node_id_t id) {
auto it = upper_neighbor_index_->find(id);
if (it == upper_neighbor_index_->end()) {
return 0U;
};
auto meta = reinterpret_cast<const UpperNeighborIndexMeta *>(&it->second);
return meta->level;
};
auto ret = dump_segments(dumper, keys.data(), get_level);
if (ailego_unlikely(ret < 0)) {
return ret;
}
*stats_.mutable_dumped_size() += ret;
return 0;
}
int HnswStreamerEntity::check_hnsw_index(const HNSWHeader *hd) const {
if (neighbor_cnt() != hd->neighbor_cnt() ||
upper_neighbor_cnt() != hd->upper_neighbor_cnt()) {
LOG_ERROR("Param neighbors:%zu:%zu mismatch index previous %zu:%zu",
neighbor_cnt(), upper_neighbor_cnt(), hd->neighbor_cnt(),
hd->upper_neighbor_cnt());
return IndexError_Mismatch;
}
if (vector_size() != hd->vector_size()) {
LOG_ERROR("vector size %zu mismatch index previous %zu", vector_size(),
hd->vector_size());
return IndexError_Mismatch;
}
if (ef_construction() != hd->ef_construction()) {
LOG_WARN("Param efConstruction %zu mismatch index previous %zu",
ef_construction(), hd->ef_construction());
}
if (scaling_factor() != hd->scaling_factor()) {
LOG_WARN("Param scalingFactor %zu mismatch index previous %zu",
scaling_factor(), hd->scaling_factor());
return IndexError_Mismatch;
}
if (prune_cnt() != hd->neighbor_prune_cnt()) {
LOG_WARN("Param pruneCnt %zu mismatch index previous %zu", prune_cnt(),
hd->neighbor_prune_cnt());
return IndexError_Mismatch;
}
if ((hd->entry_point() != kInvalidNodeId &&
hd->entry_point() >= hd->doc_cnt()) ||
(hd->entry_point() == kInvalidNodeId && hd->doc_cnt() > 0U)) {
LOG_WARN("Invalid entryPoint %u, docCnt %u", hd->entry_point(),
hd->doc_cnt());
return IndexError_InvalidFormat;
}
if (hd->entry_point() == kInvalidNodeId &&
broker_->get_chunk_cnt(ChunkBroker::CHUNK_TYPE_NODE) > 0) {
LOG_WARN("The index is broken, maybe it haven't flush");
return IndexError_InvalidFormat;
}
return 0;
}
int HnswStreamerEntity::add_vector(level_t level, key_t key, const void *vec,
node_id_t *id) {
Chunk::Pointer node_chunk;
size_t chunk_offset = -1UL;
std::lock_guard<std::mutex> lock(mutex_);
// duplicate check
if (ailego_unlikely(filter_same_key_ && get_id(key) != kInvalidNodeId)) {
LOG_WARN("Try to add duplicate key, ignore it");
return IndexError_Duplicate;
}
node_id_t local_id = static_cast<node_id_t>(doc_cnt());
uint32_t chunk_index = node_chunks_.size() - 1U;
if (chunk_index == -1U ||
(node_chunks_[chunk_index]->data_size() >=
node_cnt_per_chunk_ * node_size())) { // no space left and need to alloc
if (ailego_unlikely(node_chunks_.capacity() == node_chunks_.size())) {
LOG_ERROR("add vector failed for no memory quota");
return IndexError_IndexFull;
}
chunk_index++;
auto p = broker_->alloc_chunk(ChunkBroker::CHUNK_TYPE_NODE, chunk_index,
chunk_size_);
if (ailego_unlikely(p.first != 0)) {
LOG_ERROR("Alloc data chunk failed");
return p.first;
}
node_chunk = p.second;
chunk_offset = 0UL;
node_chunks_.emplace_back(node_chunk);
} else {
node_chunk = node_chunks_[chunk_index];
chunk_offset = node_chunk->data_size();
}
size_t size = node_chunk->write(chunk_offset, vec, vector_size());
if (ailego_unlikely(size != vector_size())) {
LOG_ERROR("Chunk write vec failed, ret=%zu", size);
return IndexError_WriteData;
}
size = node_chunk->write(chunk_offset + vector_size(), &key, sizeof(key_t));
if (ailego_unlikely(size != sizeof(key_t))) {
LOG_ERROR("Chunk write vec failed, ret=%zu", size);
return IndexError_WriteData;
}
//! level 0 neighbors is inited to zero by default
int ret = add_upper_neighbor(level, local_id);
if (ret != 0) {
return ret;
}
chunk_offset += node_size();
if (ailego_unlikely(node_chunk->resize(chunk_offset) != chunk_offset)) {
LOG_ERROR("Chunk resize to %zu failed", chunk_offset);
return IndexError_Runtime;
}
if (filter_same_key_ || get_vector_enabled_) {
if (use_key_info_map_) {
keys_map_lock_->lock();
(*keys_map_)[key] = local_id;
keys_map_lock_->unlock();
}
}
*mutable_doc_cnt() += 1;
broker_->mark_dirty();
*id = local_id;
return 0;
}
int HnswStreamerEntity::add_vector_with_id(level_t level, node_id_t id,
const void *vec) {
Chunk::Pointer node_chunk;
size_t chunk_offset = -1UL;
key_t key = id;
std::lock_guard<std::mutex> lock(mutex_);
// duplicate check
if (ailego_unlikely(filter_same_key_ && get_id(key) != kInvalidNodeId)) {
LOG_WARN("Try to add duplicate key, ignore it");
return IndexError_Duplicate;
}
// set node_chunk & chunk_offset if succeed
auto func_get_node_chunk_and_offset = [&](node_id_t node_id) -> int {
uint32_t chunk_index = node_id >> node_index_mask_bits_;
ailego_assert_with(chunk_index <= node_chunks_.size(), "invalid chunk idx");
// belongs to next chunk
if (chunk_index == node_chunks_.size()) {
if (ailego_unlikely(node_chunks_.capacity() == node_chunks_.size())) {
LOG_ERROR("add vector failed for no memory quota");
return IndexError_IndexFull;
}
auto p = broker_->alloc_chunk(ChunkBroker::CHUNK_TYPE_NODE, chunk_index,
chunk_size_);
if (ailego_unlikely(p.first != 0)) {
LOG_ERROR("Alloc data chunk failed");
return p.first;
}
node_chunk = p.second;
node_chunks_.emplace_back(node_chunk);
}
node_chunk = node_chunks_[chunk_index];
chunk_offset = (node_id & node_index_mask_) * node_size();
return 0;
};
for (size_t start_id = doc_cnt(); start_id < id; ++start_id) {
if (auto ret = func_get_node_chunk_and_offset(start_id); ret != 0) {
LOG_ERROR("func_get_node_chunk_and_offset failed");
return ret;
}
size_t size = node_chunk->write(chunk_offset + vector_size(), &kInvalidKey,
sizeof(key_t));
if (ailego_unlikely(size != sizeof(key_t))) {
LOG_ERROR("Chunk write key failed, ret=%zu", size);
return IndexError_WriteData;
}
chunk_offset += node_size();
if (ailego_unlikely(node_chunk->resize(chunk_offset) != chunk_offset)) {
LOG_ERROR("Chunk resize to %zu failed", chunk_offset);
return IndexError_Runtime;
}
}
if (auto ret = func_get_node_chunk_and_offset(id); ret != 0) {
LOG_ERROR("func_get_node_chunk_and_offset failed");
return ret;
}
size_t size = node_chunk->write(chunk_offset, vec, vector_size());
if (ailego_unlikely(size != vector_size())) {
LOG_ERROR("Chunk write vec failed, ret=%zu", size);
return IndexError_WriteData;
}
size = node_chunk->write(chunk_offset + vector_size(), &key, sizeof(key_t));
if (ailego_unlikely(size != sizeof(key_t))) {
LOG_ERROR("Chunk write vec failed, ret=%zu", size);
return IndexError_WriteData;
}
//! level 0 neighbors is inited to zero by default
int ret = add_upper_neighbor(level, id);
if (ret != 0) {
return ret;
}
if (*mutable_doc_cnt() <= id) {
*mutable_doc_cnt() = id + 1;
chunk_offset += node_size();
if (ailego_unlikely(node_chunk->resize(chunk_offset) != chunk_offset)) {
LOG_ERROR("Chunk resize to %zu failed", chunk_offset);
return IndexError_Runtime;
}
}
if (filter_same_key_ || get_vector_enabled_) {
if (use_key_info_map_) {
keys_map_lock_->lock();
(*keys_map_)[key] = id;
keys_map_lock_->unlock();
}
}
broker_->mark_dirty();
return 0;
}
void HnswStreamerEntity::update_ep_and_level(node_id_t ep, level_t level) {
HnswEntity::update_ep_and_level(ep, level);
flush_header();
return;
}
const HnswEntity::Pointer HnswStreamerEntity::clone() const {
std::vector<Chunk::Pointer> node_chunks;
node_chunks.reserve(node_chunks_.size());
for (size_t i = 0UL; i < node_chunks_.size(); ++i) {
node_chunks.emplace_back(node_chunks_[i]->clone());
if (ailego_unlikely(!node_chunks[i])) {
LOG_ERROR("HnswStreamerEntity get chunk failed in clone");
return HnswEntity::Pointer();
}
}
std::vector<Chunk::Pointer> upper_neighbor_chunks;
upper_neighbor_chunks.reserve(upper_neighbor_chunks_.size());
for (size_t i = 0UL; i < upper_neighbor_chunks_.size(); ++i) {
upper_neighbor_chunks.emplace_back(upper_neighbor_chunks_[i]->clone());
if (ailego_unlikely(!upper_neighbor_chunks[i])) {
LOG_ERROR("HnswStreamerEntity get chunk failed in clone");
return HnswEntity::Pointer();
}
}
HnswStreamerEntity *entity = new (std::nothrow) HnswStreamerEntity(
stats_, header(), chunk_size_, node_index_mask_bits_,
upper_neighbor_mask_bits_, filter_same_key_, get_vector_enabled_,
upper_neighbor_index_, keys_map_lock_, keys_map_, use_key_info_map_,
std::move(node_chunks), std::move(upper_neighbor_chunks), broker_);
if (ailego_unlikely(!entity)) {
LOG_ERROR("HnswStreamerEntity new failed");
}
return HnswEntity::Pointer(entity);
}
} // namespace core
} // namespace zvec
@@ -0,0 +1,525 @@
// Copyright 2025-present the zvec project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <iostream>
#include <ailego/container/heap.h>
#include <ailego/parallel/lock.h>
#include <sparsehash/dense_hash_map>
#include <sparsehash/dense_hash_set>
#include "framework/index_framework.h"
#include "hnsw_chunk.h"
#include "hnsw_entity.h"
#include "hnsw_index_hash.h"
#include "hnsw_params.h"
namespace zvec {
namespace core {
//! HnswStreamerEntity manage vector data, pkey, and node's neighbors
class HnswStreamerEntity : public HnswEntity {
public:
//! Cleanup
//! return 0 on success, or errCode in failure
virtual int cleanup() override;
//! Make a copy of streamer entity, to support thread-safe operation.
//! The segment in container cannot be read concurrenly
virtual const HnswEntity::Pointer clone() const override;
//! Get primary key of the node id
virtual key_t get_key(node_id_t id) const override;
//! Get vector feature data by key
virtual const void *get_vector(node_id_t id) const override;
//! Get vectors feature data by local ids
virtual int get_vector(const node_id_t *ids, uint32_t count,
const void **vecs) const override;
virtual int get_vector(const node_id_t id,
IndexStorage::MemoryBlock &block) const override;
virtual int get_vector(
const node_id_t *ids, uint32_t count,
std::vector<IndexStorage::MemoryBlock> &vec_blocks) const override;
//! Get the node id's neighbors on graph level
//! Note: the neighbors cannot be modified, using the following
//! method to get WritableNeighbors if want to
virtual const Neighbors get_neighbors(level_t level,
node_id_t id) const override;
//! Add vector and key to hnsw entity, and local id will be saved in id
virtual int add_vector(level_t level, key_t key, const void *vec,
node_id_t *id) override;
//! Add vector and id to hnsw entity
virtual int add_vector_with_id(level_t level, node_id_t id,
const void *vec) override;
virtual int update_neighbors(
level_t level, node_id_t id,
const std::vector<std::pair<node_id_t, dist_t>> &neighbors) override;
//! Append neighbor_id to node id neighbors on level
//! Notice: the caller must be ensure the neighbors not full
virtual void add_neighbor(level_t level, node_id_t id, uint32_t size,
node_id_t neighbor_id) override;
//! Dump index by dumper
virtual int dump(const IndexDumper::Pointer &dumper) override;
virtual void update_ep_and_level(node_id_t ep, level_t level) override;
void set_use_key_info_map(bool use_id_map) {
use_key_info_map_ = use_id_map;
LOG_DEBUG("use_key_info_map_: %d", (int)use_key_info_map_);
}
public:
//! Constructor
HnswStreamerEntity(IndexStreamer::Stats &stats);
//! Destructor
~HnswStreamerEntity();
//! Get vector feature data by key
virtual const void *get_vector_by_key(key_t key) const override {
auto id = get_id(key);
return id == kInvalidNodeId ? nullptr : get_vector(id);
}
virtual int get_vector_by_key(
const key_t key, IndexStorage::MemoryBlock &block) const override {
auto id = get_id(key);
if (id != kInvalidNodeId) {
return get_vector(id, block);
} else {
return IndexError_InvalidArgument;
}
}
//! Init entity
int init(size_t max_doc_cnt);
//! Flush graph entity to disk
//! return 0 on success, or errCode in failure
int flush(uint64_t checkpoint);
//! Open entity from storage
//! return 0 on success, or errCode in failure
int open(IndexStorage::Pointer stg, uint64_t max_index_size, bool check_crc);
//! Close entity
//! return 0 on success, or errCode in failure
int close();
//! Set meta information from entity
int set_index_meta(const IndexMeta &meta) const {
return IndexHelper::SerializeToStorage(meta, broker_->storage().get());
}
//! Get meta information from entity
int get_index_meta(IndexMeta *meta) const {
return IndexHelper::DeserializeFromStorage(broker_->storage().get(), meta);
}
//! Set params: chunk size
inline void set_chunk_size(size_t val) {
chunk_size_ = val;
}
//! Set params
inline void set_filter_same_key(bool val) {
filter_same_key_ = val;
}
//! Set params
inline void set_get_vector(bool val) {
get_vector_enabled_ = val;
}
//! Get vector local id by key
inline node_id_t get_id(key_t key) const {
if (use_key_info_map_) {
keys_map_lock_->lock_shared();
auto it = keys_map_->find(key);
keys_map_lock_->unlock_shared();
return it == keys_map_->end() ? kInvalidNodeId : it->second;
} else {
return key;
}
}
void print_key_map() const {
std::cout << "key map begins" << std::endl;
auto iter = keys_map_->begin();
while (iter != keys_map_->end()) {
std::cout << "key: " << iter->first << ", id: " << iter->second
<< std::endl;
;
iter++;
}
std::cout << "key map ends" << std::endl;
}
//! Get neighbors size
inline size_t neighbors_size() const {
return sizeof(NeighborsHeader) + neighbor_cnt() * sizeof(node_id_t);
}
//! Get neighbors size in hybrid mode
inline size_t neighbors_size_hybrid() const {
return sizeof(NeighborsHeader) * 2 + neighbor_cnt() * sizeof(node_id_t);
}
//! Get upper neighbors size
inline size_t upper_neighbors_size() const {
return sizeof(NeighborsHeader) + upper_neighbor_cnt() * sizeof(node_id_t);
}
//! Get upper neighbors size in hybrid mode
inline size_t upper_neighbors_size_hybrid() const {
return 2 *
(sizeof(NeighborsHeader) + upper_neighbor_cnt() * sizeof(node_id_t));
}
private:
union UpperNeighborIndexMeta {
struct {
uint32_t level : 4;
uint32_t index : 28; // index is composite type: chunk idx, and the
// N th neighbors in chunk, they two composite
// the 28 bits location
};
uint32_t data;
};
template <class Key, class T>
using HashMap = google::dense_hash_map<Key, T, std::hash<Key>>;
template <class Key, class T>
using HashMapPointer = std::shared_ptr<HashMap<Key, T>>;
template <class Key>
using HashSet = google::dense_hash_set<Key, std::hash<Key>>;
template <class Key>
using HashSetPointer = std::shared_ptr<HashSet<Key>>;
//! upper neighbor index hashmap
using NIHashMap = HnswIndexHashMap<node_id_t, uint32_t>;
using NIHashMapPointer = std::shared_ptr<NIHashMap>;
//! Private construct, only be called by clone method
HnswStreamerEntity(IndexStreamer::Stats &stats, const HNSWHeader &hd,
size_t chunk_size, uint32_t node_index_mask_bits,
uint32_t upper_neighbor_mask_bits, bool filter_same_key,
bool get_vector_enabled,
const NIHashMapPointer &upper_neighbor_index,
std::shared_ptr<ailego::SharedMutex> &keys_map_lock,
const HashMapPointer<key_t, node_id_t> &keys_map,
bool use_key_info_map,
std::vector<Chunk::Pointer> &&node_chunks,
std::vector<Chunk::Pointer> &&upper_neighbor_chunks,
const ChunkBroker::Pointer &broker)
: stats_(stats),
chunk_size_(chunk_size),
node_index_mask_bits_(node_index_mask_bits),
node_cnt_per_chunk_(1UL << node_index_mask_bits_),
node_index_mask_(node_cnt_per_chunk_ - 1),
upper_neighbor_mask_bits_(upper_neighbor_mask_bits),
upper_neighbor_mask_((1U << upper_neighbor_mask_bits_) - 1),
filter_same_key_(filter_same_key),
get_vector_enabled_(get_vector_enabled),
use_key_info_map_(use_key_info_map),
upper_neighbor_index_(upper_neighbor_index),
keys_map_lock_(keys_map_lock),
keys_map_(keys_map),
node_chunks_(std::move(node_chunks)),
upper_neighbor_chunks_(std::move(upper_neighbor_chunks)),
broker_(broker) {
*mutable_header() = hd;
neighbor_size_ = neighbors_size();
upper_neighbor_size_ = upper_neighbors_size();
}
//! Called only in searching procedure per context, so no need to lock
void sync_chunks(ChunkBroker::CHUNK_TYPE type, size_t idx,
std::vector<Chunk::Pointer> *chunks) const {
if (ailego_likely(idx < chunks->size())) {
return;
}
for (size_t i = chunks->size(); i <= idx; ++i) {
auto chunk = broker_->get_chunk(type, i);
// the storage can ensure get chunk will success after the first get
ailego_assert_with(!!chunk, "get chunk failed");
chunks->emplace_back(std::move(chunk));
}
}
//! return pair: chunk index + chunk offset
inline std::pair<uint32_t, uint32_t> get_vector_chunk_loc(
node_id_t id) const {
uint32_t chunk_idx = id >> node_index_mask_bits_;
uint32_t offset = (id & node_index_mask_) * node_size();
sync_chunks(ChunkBroker::CHUNK_TYPE_NODE, chunk_idx, &node_chunks_);
return std::make_pair(chunk_idx, offset);
}
//! return pair: chunk index + chunk offset
inline std::pair<uint32_t, uint32_t> get_key_chunk_loc(node_id_t id) const {
uint32_t chunk_idx = id >> node_index_mask_bits_;
uint32_t offset = (id & node_index_mask_) * node_size() + vector_size();
sync_chunks(ChunkBroker::CHUNK_TYPE_NODE, chunk_idx, &node_chunks_);
return std::make_pair(chunk_idx, offset);
}
inline std::pair<uint32_t, uint32_t> get_upper_neighbor_chunk_loc(
level_t level, node_id_t id) const {
auto it = upper_neighbor_index_->find(id);
ailego_assert_abort(it != upper_neighbor_index_->end(),
"Get upper neighbor header failed");
auto meta = reinterpret_cast<const UpperNeighborIndexMeta *>(&it->second);
uint32_t chunk_idx = (meta->index) >> upper_neighbor_mask_bits_;
uint32_t offset = (((meta->index) & upper_neighbor_mask_) + level - 1) *
upper_neighbor_size_;
sync_chunks(ChunkBroker::CHUNK_TYPE_UPPER_NEIGHBOR, chunk_idx,
&upper_neighbor_chunks_);
ailego_assert_abort(chunk_idx < upper_neighbor_chunks_.size(),
"invalid chunk idx");
ailego_assert_abort(offset < upper_neighbor_chunks_[chunk_idx]->data_size(),
"invalid chunk offset");
return std::make_pair(chunk_idx, offset);
}
//! return pair: chunk + chunk offset
inline std::pair<Chunk *, size_t> get_neighbor_chunk_loc(level_t level,
node_id_t id) const {
if (level == 0UL) {
uint32_t chunk_idx = id >> node_index_mask_bits_;
uint32_t offset =
(id & node_index_mask_) * node_size() + vector_size() + sizeof(key_t);
sync_chunks(ChunkBroker::CHUNK_TYPE_NODE, chunk_idx, &node_chunks_);
ailego_assert_abort(chunk_idx < node_chunks_.size(), "invalid chunk idx");
ailego_assert_abort(offset < node_chunks_[chunk_idx]->data_size(),
"invalid chunk offset");
return std::make_pair(node_chunks_[chunk_idx].get(), offset);
} else {
auto p = get_upper_neighbor_chunk_loc(level, id);
return std::make_pair(upper_neighbor_chunks_[p.first].get(), p.second);
}
}
//! Chunk hnsw index valid
int check_hnsw_index(const HNSWHeader *hd) const;
size_t get_total_upper_neighbors_size(level_t level) const {
return level * upper_neighbor_size_;
}
//! Add upper neighbor header and reserve space for upper neighbor
int add_upper_neighbor(level_t level, node_id_t id) {
if (level == 0) {
return 0;
}
Chunk::Pointer chunk;
uint64_t chunk_offset = -1UL;
size_t neighbors_size = get_total_upper_neighbors_size(level);
uint64_t chunk_index = upper_neighbor_chunks_.size() - 1UL;
if (chunk_index == -1UL ||
(upper_neighbor_chunks_[chunk_index]->padding_size() <
neighbors_size)) { // no space left and need to alloc
chunk_index++;
if (ailego_unlikely(upper_neighbor_chunks_.capacity() ==
upper_neighbor_chunks_.size())) {
LOG_ERROR("add upper neighbor failed for no memory quota");
return IndexError_IndexFull;
}
auto p = broker_->alloc_chunk(ChunkBroker::CHUNK_TYPE_UPPER_NEIGHBOR,
chunk_index, upper_neighbor_chunk_size_);
if (ailego_unlikely(p.first != 0)) {
LOG_ERROR("Alloc data chunk failed");
return p.first;
}
chunk = p.second;
chunk_offset = 0UL;
upper_neighbor_chunks_.emplace_back(chunk);
} else {
chunk = upper_neighbor_chunks_[chunk_index];
chunk_offset = chunk->data_size();
}
ailego_assert_with((size_t)level < kMaxGraphLayers, "invalid level");
ailego_assert_with(chunk_offset % upper_neighbor_size_ == 0,
"invalid offset");
ailego_assert_with((chunk_offset / upper_neighbor_size_) <
(1U << upper_neighbor_mask_bits_),
"invalid offset");
ailego_assert_with(chunk_index < (1U << (28 - upper_neighbor_mask_bits_)),
"invalid chunk index");
UpperNeighborIndexMeta meta;
meta.level = level;
meta.index = (chunk_index << upper_neighbor_mask_bits_) |
(chunk_offset / upper_neighbor_size_);
chunk_offset += upper_neighbor_size_ * level;
if (ailego_unlikely(!upper_neighbor_index_->insert(id, meta.data))) {
LOG_ERROR("HashMap insert value failed");
return IndexError_Runtime;
}
if (ailego_unlikely(chunk->resize(chunk_offset) != chunk_offset)) {
LOG_ERROR("Chunk resize to %zu failed", (size_t)chunk_offset);
return IndexError_Runtime;
}
return 0;
}
size_t estimate_doc_capacity() const {
return node_chunks_.capacity() * node_cnt_per_chunk_;
}
int init_chunk_params(size_t max_index_size, bool huge_page) {
node_cnt_per_chunk_ = std::max<uint32_t>(1, chunk_size_ / node_size());
//! align node cnt per chunk to pow of 2
node_index_mask_bits_ = std::ceil(std::log2(node_cnt_per_chunk_));
node_cnt_per_chunk_ = 1UL << node_index_mask_bits_;
if (huge_page) {
chunk_size_ = AlignHugePageSize(node_cnt_per_chunk_ * node_size());
} else {
chunk_size_ = AlignPageSize(node_cnt_per_chunk_ * node_size());
}
node_index_mask_ = node_cnt_per_chunk_ - 1;
if (max_index_size == 0UL) {
max_index_size_ = chunk_size_ * kDefaultMaxChunkCnt;
} else {
max_index_size_ = max_index_size;
}
//! To get a balanced upper neighbor chunk size.
//! If the upper chunk size is equal to node chunk size, it may waste
//! upper neighbor chunk space; if the upper neighbor chunk size is too
//! small, the will need large upper neighbor chunks index space. So to
//! get a balanced ratio be sqrt of the node/neighbor size ratio
float ratio =
std::sqrt(node_size() * scaling_factor() * 1.0f / upper_neighbor_size_);
if (huge_page) {
upper_neighbor_chunk_size_ = AlignHugePageSize(
std::max(get_total_upper_neighbors_size(kMaxGraphLayers),
static_cast<size_t>(chunk_size_ / ratio)));
} else {
upper_neighbor_chunk_size_ = AlignPageSize(
std::max(get_total_upper_neighbors_size(kMaxGraphLayers),
static_cast<size_t>(chunk_size_ / ratio)));
}
upper_neighbor_mask_bits_ =
std::ceil(std::log2(upper_neighbor_chunk_size_ / upper_neighbor_size_));
upper_neighbor_mask_ = (1 << upper_neighbor_mask_bits_) - 1;
size_t max_node_chunk_cnt = std::ceil(max_index_size_ / chunk_size_);
size_t max_upper_chunk_cnt = std::ceil(
(max_node_chunk_cnt * node_cnt_per_chunk_ * 1.0f / scaling_factor()) /
(upper_neighbor_chunk_size_ / upper_neighbor_size_));
max_upper_chunk_cnt =
max_upper_chunk_cnt + std::ceil(max_upper_chunk_cnt / scaling_factor());
//! reserve space to avoid memmove in chunks vector emplace chunk, so
//! as to lock-free in reading chunk
node_chunks_.reserve(max_node_chunk_cnt);
upper_neighbor_chunks_.reserve(max_upper_chunk_cnt);
LOG_DEBUG(
"Settings: nodeSize=%zu chunkSize=%u upperNeighborSize=%u "
"upperNeighborChunkSize=%u "
"nodeCntPerChunk=%u maxChunkCnt=%zu maxNeighborChunkCnt=%zu "
"maxIndexSize=%zu ratio=%.3f",
node_size(), chunk_size_, upper_neighbor_size_,
upper_neighbor_chunk_size_, node_cnt_per_chunk_, max_node_chunk_cnt,
max_upper_chunk_cnt, max_index_size_, ratio);
return 0;
}
//! Init node chunk and neighbor chunks
int init_chunks(const Chunk::Pointer &header_chunk);
int flush_header(void) {
if (!broker_->dirty()) {
// do not need to flush
return 0;
}
auto header_chunk = broker_->get_chunk(ChunkBroker::CHUNK_TYPE_HEADER,
ChunkBroker::kDefaultChunkSeqId);
if (ailego_unlikely(!header_chunk)) {
LOG_ERROR("get header chunk failed");
return IndexError_Runtime;
}
size_t size = header_chunk->write(0UL, &header(), header_size());
if (ailego_unlikely(size != header_size())) {
LOG_ERROR("Write header chunk failed");
return IndexError_WriteData;
}
return 0;
}
private:
HnswStreamerEntity(const HnswStreamerEntity &) = delete;
HnswStreamerEntity &operator=(const HnswStreamerEntity &) = delete;
static constexpr uint64_t kUpperHashMemoryInflateRatio = 2.0f;
private:
IndexStreamer::Stats &stats_;
HNSWHeader header_{};
std::mutex mutex_{};
size_t max_index_size_{0UL};
uint32_t chunk_size_{kDefaultChunkSize};
uint32_t upper_neighbor_chunk_size_{kDefaultChunkSize};
uint32_t node_index_mask_bits_{0U};
uint32_t node_cnt_per_chunk_{0U};
uint32_t node_index_mask_{0U};
uint32_t neighbor_size_{0U};
uint32_t upper_neighbor_size_{0U};
//! UpperNeighborIndex.index composite chunkIdx and offset in chunk by the
//! following mask
uint32_t upper_neighbor_mask_bits_{0U};
uint32_t upper_neighbor_mask_{0U};
bool filter_same_key_{false};
bool get_vector_enabled_{false};
bool use_key_info_map_{true};
NIHashMapPointer upper_neighbor_index_{};
mutable std::shared_ptr<ailego::SharedMutex> keys_map_lock_{};
HashMapPointer<key_t, node_id_t> keys_map_{};
//! the chunks will be changed in searcher, so need mutable
//! data chunk include: vector, key, level 0 neighbors
mutable std::vector<Chunk::Pointer> node_chunks_{};
//! upper neighbor chunk inlude: UpperNeighborHeader + (1~level) neighbors
mutable std::vector<Chunk::Pointer> upper_neighbor_chunks_{};
ChunkBroker::Pointer broker_{}; // chunk broker
};
} // namespace core
} // namespace zvec