Initial commit
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
include(${PROJECT_ROOT_DIR}/cmake/option.cmake)
|
||||
|
||||
cc_library(
|
||||
NAME core_interface STATIC STRICT ALWAYS_LINK
|
||||
SRCS *.cc indexes/*.cc
|
||||
INCS . ${PROJECT_ROOT_DIR}/src/ ${PROJECT_ROOT_DIR}/src/core
|
||||
LIBS zvec_ailego core_framework_static sparsehash magic_enum
|
||||
VERSION "${PROXIMA_ZVEC_VERSION}"
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
constexpr static uint32_t kDefaultHnswEfConstruction = 500;
|
||||
constexpr static uint32_t kDefaultHnswNeighborCnt = 100;
|
||||
|
||||
constexpr static uint32_t kDefaultHnswEfSearch = 300;
|
||||
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
@@ -0,0 +1,773 @@
|
||||
// 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 "index.h"
|
||||
#include "framework/index_error.h"
|
||||
#include "framework/index_storage.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
int Index::ParseMetricName(const BaseIndexParam ¶m) {
|
||||
std::string metric_name;
|
||||
if (is_sparse_) {
|
||||
// only inner product is supported for sparse index
|
||||
switch (param.metric_type) {
|
||||
case MetricType::kInnerProduct:
|
||||
metric_name = "InnerProductSparse";
|
||||
break;
|
||||
case MetricType::kMIPSL2sq:
|
||||
metric_name = "MipsSquaredEuclideanSparse";
|
||||
break;
|
||||
default:
|
||||
LOG_ERROR("Unsupported metric type");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
} else {
|
||||
switch (param.metric_type) {
|
||||
case MetricType::kL2sq:
|
||||
metric_name = "SquaredEuclidean";
|
||||
break;
|
||||
case MetricType::kInnerProduct:
|
||||
metric_name = "InnerProduct";
|
||||
break;
|
||||
case MetricType::kCosine:
|
||||
metric_name = "Cosine"; // This is already the normalizedCosine
|
||||
break;
|
||||
case MetricType::kMIPSL2sq:
|
||||
metric_name = "MipsSquaredEuclidean";
|
||||
break;
|
||||
default:
|
||||
LOG_ERROR("Unsupported metric type");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
// TODO: MIPS need to set some param
|
||||
// for streamer open()
|
||||
proxima_index_meta_.set_metric(metric_name, 0, ailego::Params());
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Index::CreateAndInitMetric(const BaseIndexParam & /*param*/) {
|
||||
auto &metric_name = proxima_index_meta_.metric_name();
|
||||
|
||||
metric_ = core::IndexFactory::CreateMetric(metric_name);
|
||||
if (const auto ret = metric_->init(proxima_index_meta_,
|
||||
proxima_index_meta_.metric_params());
|
||||
ret != 0) {
|
||||
LOG_ERROR("Failed to create and init metric, name %s, code %d, desc: %s",
|
||||
metric_name.c_str(), ret, core::IndexError::What(ret));
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (metric_->query_metric()) {
|
||||
metric_ = metric_->query_metric();
|
||||
}
|
||||
|
||||
return core::IndexError_Success;
|
||||
}
|
||||
|
||||
int Index::CreateAndInitConverterReformer(const QuantizerParam ¶m,
|
||||
const BaseIndexParam &index_param) {
|
||||
ailego::Params converter_params;
|
||||
std::string converter_name;
|
||||
if (is_sparse_) {
|
||||
switch (param.type) {
|
||||
case QuantizerType::kNone:
|
||||
return core::IndexError_Success;
|
||||
case QuantizerType::kFP16:
|
||||
converter_name = "HalfFloatSparseConverter";
|
||||
break;
|
||||
default:
|
||||
LOG_ERROR("Unsupported quantizer type: ");
|
||||
return core::IndexError_Unsupported;
|
||||
}
|
||||
} else {
|
||||
if (index_param.metric_type == MetricType::kCosine) {
|
||||
switch (param.type) {
|
||||
case QuantizerType::kNone:
|
||||
if (index_param.data_type == DataType::DT_FP16) {
|
||||
converter_name = "CosineHalfFloatConverter";
|
||||
} else if (index_param.data_type == DataType::DT_FP32) {
|
||||
converter_name = "CosineNormalizeConverter";
|
||||
} else {
|
||||
LOG_ERROR("Unsupported data type: ");
|
||||
return core::IndexError_Unsupported;
|
||||
}
|
||||
break;
|
||||
case QuantizerType::kFP16:
|
||||
converter_name = "CosineFp16Converter";
|
||||
break;
|
||||
case QuantizerType::kInt8:
|
||||
converter_name = "CosineInt8Converter";
|
||||
break;
|
||||
case QuantizerType::kInt4:
|
||||
converter_name = "CosineInt4Converter";
|
||||
break;
|
||||
default:
|
||||
LOG_ERROR("Unsupported quantizer type: ");
|
||||
return core::IndexError_Unsupported;
|
||||
}
|
||||
} else {
|
||||
switch (param.type) {
|
||||
case QuantizerType::kNone:
|
||||
return core::IndexError_Success;
|
||||
case QuantizerType::kFP16:
|
||||
converter_name = "HalfFloatConverter";
|
||||
break;
|
||||
case QuantizerType::kInt8:
|
||||
converter_name = "Int8StreamingConverter";
|
||||
break;
|
||||
case QuantizerType::kInt4:
|
||||
converter_name = "Int4StreamingConverter";
|
||||
break;
|
||||
default:
|
||||
LOG_ERROR("Unsupported quantizer type: ");
|
||||
return core::IndexError_Unsupported;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proxima_index_meta_.set_converter(converter_name, 0, converter_params);
|
||||
converter_ = core::IndexFactory::CreateConverter(converter_name);
|
||||
if (converter_ == nullptr ||
|
||||
converter_->init(proxima_index_meta_, converter_params) != 0) {
|
||||
LOG_ERROR("Failed to create and init converter");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
proxima_index_meta_ = converter_->meta();
|
||||
reformer_ =
|
||||
core::IndexFactory::CreateReformer(proxima_index_meta_.reformer_name());
|
||||
if (reformer_ == nullptr ||
|
||||
reformer_->init(proxima_index_meta_.reformer_params()) != 0) {
|
||||
LOG_ERROR("Failed to create and init reformer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
streamer_vector_meta_.set_meta(proxima_index_meta_.data_type(),
|
||||
proxima_index_meta_.dimension());
|
||||
streamer_vector_meta_.set_meta_type(proxima_index_meta_.meta_type());
|
||||
|
||||
return core::IndexError_Success;
|
||||
}
|
||||
|
||||
int Index::Init(const BaseIndexParam ¶m) {
|
||||
param_ = param; // will lose the original type info
|
||||
|
||||
is_sparse_ = param.is_sparse;
|
||||
is_huge_page_ = param.is_huge_page;
|
||||
|
||||
proxima_index_meta_.set_meta(param.data_type, param.dimension);
|
||||
proxima_index_meta_.set_meta_type(is_sparse_ ? IndexMeta::MetaType::MT_SPARSE
|
||||
: IndexMeta::MetaType::MT_DENSE);
|
||||
|
||||
input_vector_meta_.set_meta(proxima_index_meta_.data_type(),
|
||||
proxima_index_meta_.dimension());
|
||||
input_vector_meta_.set_meta_type(proxima_index_meta_.meta_type());
|
||||
streamer_vector_meta_ = input_vector_meta_;
|
||||
|
||||
|
||||
// when quantizer=int8/int4, the converter.init() will change the metric to
|
||||
// QuantizedInteger with params
|
||||
if (ParseMetricName(param) != 0) {
|
||||
LOG_ERROR("Failed to parse metric name");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (CreateAndInitConverterReformer(param.quantizer_param, param) != 0) {
|
||||
LOG_ERROR("Failed to create and init converter");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
// must after quantizer handled. e.g., cosine doesn't support int8 quantizer
|
||||
if (CreateAndInitMetric(param) != 0) {
|
||||
LOG_ERROR("Failed to create and init metric");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (CreateAndInitStreamer(param) != 0) {
|
||||
LOG_ERROR("Failed to create and init streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int Index::Open(const std::string &file_path, StorageOptions storage_options) {
|
||||
ailego::Params storage_params;
|
||||
// storage_params.set("proxima.mmap_file.storage.memory_warmup", true);
|
||||
// storage_params.set("proxima.mmap_file.storage.segment_meta_capacity",
|
||||
// 1024);
|
||||
switch (storage_options.type) {
|
||||
case StorageOptions::StorageType::kMMAP: {
|
||||
storage_ = core::IndexFactory::CreateStorage("MMapFileStorage");
|
||||
if (storage_ == nullptr) {
|
||||
LOG_ERROR("Failed to create MMapFileStorage");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
int ret = storage_->init(storage_params);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to init MMapFileStorage, path: %s, err: %s",
|
||||
file_path.c_str(), core::IndexError::What(ret));
|
||||
return ret;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case StorageOptions::StorageType::kBufferPool: {
|
||||
storage_ = core::IndexFactory::CreateStorage("BufferStorage");
|
||||
if (storage_ == nullptr) {
|
||||
LOG_ERROR("Failed to create BufferStorage");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
int ret = storage_->init(storage_params);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to init BufferStorage, path: %s, err: %s",
|
||||
file_path.c_str(), core::IndexError::What(ret));
|
||||
return ret;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
LOG_ERROR("Unsupported storage type");
|
||||
return core::IndexError_Unsupported;
|
||||
}
|
||||
|
||||
// read_options.create_new
|
||||
int ret = storage_->open(file_path, storage_options.create_new);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to open storage, path: %s, err: %s", file_path.c_str(),
|
||||
core::IndexError::What(ret));
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (streamer_ == nullptr || streamer_->open(storage_) != 0) {
|
||||
LOG_ERROR("Failed to open streamer, path: %s", file_path.c_str());
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
// converter/reformer/metric are created in IndexFactory::CreateIndex
|
||||
// TODO: init
|
||||
|
||||
// TODO: context pool
|
||||
if (!init_context()) { // to validate if any error, will be overwritten
|
||||
LOG_ERROR("Failed to init context");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
is_open_ = true;
|
||||
is_read_only_ = storage_options.read_only;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Index::Close() {
|
||||
if (!is_open_) {
|
||||
LOG_ERROR("Index is not open");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (!is_read_only_) {
|
||||
if (ailego_unlikely(Flush() != 0)) {
|
||||
LOG_ERROR("Failed to cleanup streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
if (ailego_unlikely(streamer_->cleanup() != 0)) {
|
||||
LOG_ERROR("Failed to cleanup streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (ailego_unlikely(storage_->close() != 0)) {
|
||||
LOG_ERROR("Failed to close storage");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
is_open_ = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Index::Flush() {
|
||||
if (!is_open_) {
|
||||
LOG_ERROR("Index is not open");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (is_read_only_) {
|
||||
LOG_ERROR("Cannot flush read-only index");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (ailego_unlikely(streamer_->flush(0) != 0)) {
|
||||
LOG_ERROR("Failed to flush streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (ailego_unlikely(storage_->flush() != 0)) {
|
||||
LOG_ERROR("Failed to flush storage");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Index::Fetch(const uint32_t doc_id, VectorDataBuffer *vector_data_buffer) {
|
||||
if (!is_open_) {
|
||||
LOG_ERROR("Index is not open");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (is_sparse_) {
|
||||
return _sparse_fetch(doc_id, vector_data_buffer);
|
||||
}
|
||||
return _dense_fetch(doc_id, vector_data_buffer);
|
||||
}
|
||||
|
||||
int Index::Add(const VectorData &vector_data, const uint32_t doc_id) {
|
||||
if (!is_open_) {
|
||||
LOG_ERROR("Index is not open");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (is_read_only_) {
|
||||
LOG_ERROR("Cannot add to read-only index");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
auto &context = acquire_context();
|
||||
if (!context) {
|
||||
LOG_ERROR("Failed to acquire context");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (is_sparse_) {
|
||||
return _sparse_add(vector_data, doc_id, context);
|
||||
}
|
||||
return _dense_add(vector_data, doc_id, context);
|
||||
}
|
||||
|
||||
|
||||
int Index::Search(const VectorData &vector_data,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
SearchResult *result) {
|
||||
if (!is_open_) {
|
||||
LOG_ERROR("Index is not open");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (!is_trained_ && this->Train() != 0) {
|
||||
LOG_ERROR("Failed to train index");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
auto &context = acquire_context();
|
||||
if (!context) {
|
||||
LOG_ERROR("Failed to acquire context");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (_prepare_for_search(vector_data, search_param, context) != 0) {
|
||||
LOG_ERROR("Failed to prepare for search");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (is_sparse_) {
|
||||
return _sparse_search(vector_data, search_param, result, context);
|
||||
}
|
||||
|
||||
// dense support refiner, but sparse doesn't
|
||||
if (search_param->refiner_param == nullptr) {
|
||||
return _dense_search(vector_data, search_param, result, context);
|
||||
} else {
|
||||
auto &reference_index = search_param->refiner_param->reference_index;
|
||||
if (reference_index == nullptr) {
|
||||
LOG_ERROR("Reference index is not set");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
// TODO: tackle query_param's type info loss to loosen the constraint
|
||||
if (reference_index->param_.index_type != IndexType::kFlat) {
|
||||
LOG_ERROR("Reference index is not flat");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
context->set_topk(_get_coarse_search_topk(search_param));
|
||||
context->set_fetch_vector(false); // no need to fetch vector
|
||||
if (_dense_search(vector_data, search_param, result, context) != 0) {
|
||||
LOG_ERROR("Failed to search");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
auto &base_result = context->result();
|
||||
std::vector<uint64_t> keys(base_result.size());
|
||||
for (size_t i = 0; i < base_result.size(); ++i) {
|
||||
keys[i] = base_result[i].key();
|
||||
}
|
||||
|
||||
FlatQueryParam::Pointer flat_search_param =
|
||||
std::make_shared<FlatQueryParam>();
|
||||
flat_search_param->topk = search_param->topk;
|
||||
flat_search_param->fetch_vector = search_param->fetch_vector;
|
||||
flat_search_param->filter = search_param->filter;
|
||||
// TODO: should copy other params?
|
||||
flat_search_param->bf_pks = std::make_shared<std::vector<uint64_t>>(keys);
|
||||
|
||||
return reference_index->Search(vector_data, flat_search_param, result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int Index::_dense_fetch(const uint32_t doc_id,
|
||||
VectorDataBuffer *vector_data_buffer) {
|
||||
core::IndexStorage::MemoryBlock vector_block;
|
||||
int ret = streamer_->get_vector_by_id(doc_id, vector_block);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to fetch vector, doc_id: %u", doc_id);
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
const void *vector = vector_block.data();
|
||||
|
||||
DenseVectorBuffer dense_vector_buffer;
|
||||
std::string &out_vector_buffer = dense_vector_buffer.data;
|
||||
// for int4, unit_size * dim != element_size
|
||||
out_vector_buffer.resize(input_vector_meta_.element_size());
|
||||
|
||||
if (reformer_ != nullptr) {
|
||||
if (reformer_->revert(vector, streamer_vector_meta_, &out_vector_buffer) !=
|
||||
0) {
|
||||
LOG_ERROR("Failed to convert vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
} else {
|
||||
out_vector_buffer = std::string(
|
||||
static_cast<const char *>(vector),
|
||||
input_vector_meta_.dimension() * input_vector_meta_.unit_size());
|
||||
}
|
||||
vector_data_buffer->vector_buffer = std::move(dense_vector_buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int Index::_sparse_fetch(const uint32_t doc_id,
|
||||
VectorDataBuffer *vector_data_buffer) {
|
||||
SparseVectorBuffer sparse_vector_buffer;
|
||||
|
||||
if (0 != streamer_->get_sparse_vector_by_id(
|
||||
doc_id, &sparse_vector_buffer.count,
|
||||
&sparse_vector_buffer.indices, &sparse_vector_buffer.values)) {
|
||||
LOG_ERROR("Failed to fetch vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (reformer_ != nullptr) {
|
||||
std::string reverted_sparse_values_buffer;
|
||||
if (reformer_->revert(
|
||||
sparse_vector_buffer.count, sparse_vector_buffer.get_indices(),
|
||||
sparse_vector_buffer.get_values(), streamer_vector_meta_,
|
||||
&reverted_sparse_values_buffer) != 0) {
|
||||
LOG_ERROR("Failed to convert vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
sparse_vector_buffer.values = std::move(reverted_sparse_values_buffer);
|
||||
}
|
||||
vector_data_buffer->vector_buffer = std::move(sparse_vector_buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Index::_dense_add(const VectorData &vector_data, const uint32_t doc_id,
|
||||
core::IndexContext::Pointer &context) {
|
||||
if (!std::holds_alternative<DenseVector>(vector_data.vector)) {
|
||||
LOG_ERROR("Invalid vector data");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
const DenseVector &dense_vector = std::get<DenseVector>(vector_data.vector);
|
||||
if (reformer_ != nullptr) {
|
||||
core::IndexQueryMeta new_meta;
|
||||
std::string new_vector;
|
||||
int ret;
|
||||
ret = reformer_->convert(dense_vector.data, input_vector_meta_, &new_vector,
|
||||
&new_meta);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to convert vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
ret = streamer_->add_with_id_impl(doc_id, new_vector.data(), new_meta,
|
||||
context);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to add vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
} else {
|
||||
int ret = streamer_->add_with_id_impl(doc_id, dense_vector.data,
|
||||
input_vector_meta_, context);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to add vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int Index::_sparse_add(const VectorData &vector_data, const uint32_t doc_id,
|
||||
core::IndexContext::Pointer &context) {
|
||||
if (!std::holds_alternative<SparseVector>(vector_data.vector)) {
|
||||
LOG_ERROR("Invalid vector data");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
const SparseVector &sparse_vector =
|
||||
std::get<SparseVector>(vector_data.vector);
|
||||
|
||||
if (reformer_ != nullptr) {
|
||||
std::string converted_sparse_values_buffer;
|
||||
core::IndexQueryMeta new_meta;
|
||||
int ret;
|
||||
ret = reformer_->convert(sparse_vector.count, sparse_vector.get_indices(),
|
||||
sparse_vector.get_values(), input_vector_meta_,
|
||||
&converted_sparse_values_buffer, &new_meta);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to convert vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
ret = streamer_->add_with_id_impl(
|
||||
doc_id, sparse_vector.count, sparse_vector.get_indices(),
|
||||
converted_sparse_values_buffer.data(), new_meta, context);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to add vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
} else {
|
||||
int ret = streamer_->add_with_id_impl(
|
||||
doc_id, sparse_vector.count, sparse_vector.get_indices(),
|
||||
sparse_vector.get_values(), input_vector_meta_, context);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to add vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int Index::_dense_search(const VectorData &vector_data,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
SearchResult *result,
|
||||
core::IndexContext::Pointer &context) {
|
||||
if (!std::holds_alternative<DenseVector>(vector_data.vector)) {
|
||||
LOG_ERROR("Invalid vector data");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
const DenseVector &dense_vector = std::get<DenseVector>(vector_data.vector);
|
||||
auto vector = dense_vector.data;
|
||||
// Check if need to transform feature
|
||||
std::string new_vector;
|
||||
core::IndexQueryMeta new_meta = input_vector_meta_;
|
||||
if (reformer_ != nullptr) {
|
||||
if (reformer_->transform(dense_vector.data, input_vector_meta_, &new_vector,
|
||||
&new_meta) != 0) {
|
||||
LOG_ERROR("Failed to transform vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
vector = new_vector.data();
|
||||
}
|
||||
// TODO: group by
|
||||
if (search_param->bf_pks != nullptr) {
|
||||
// should we elimate the copy of bf_pks?
|
||||
if (streamer_->search_bf_by_p_keys_impl(
|
||||
vector, std::vector<std::vector<uint64_t>>{*search_param->bf_pks},
|
||||
new_meta, 1, context) != 0) {
|
||||
LOG_ERROR("Failed to search_bf_by_p_keys_impl vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
} else if (search_param->is_linear) {
|
||||
if (streamer_->search_bf_impl(vector, new_meta, 1, context) != 0) {
|
||||
LOG_ERROR("Failed to search vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
} else {
|
||||
if (streamer_->search_impl(vector, new_meta, 1, context) != 0) {
|
||||
LOG_ERROR("Failed to search vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
result->doc_list_ = std::move(context->result());
|
||||
|
||||
if (metric_->support_normalize()) {
|
||||
for (uint32_t i = 0; i < result->doc_list_.size(); ++i) {
|
||||
metric_->normalize(result->doc_list_[i].mutable_score());
|
||||
}
|
||||
}
|
||||
if (reformer_) {
|
||||
if (reformer_->normalize(dense_vector.data, input_vector_meta_,
|
||||
result->doc_list_) != 0) {
|
||||
LOG_ERROR("Failed to normalize vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (context->fetch_vector() && reformer_->need_revert()) {
|
||||
// TODO: use std::pmr to optimize memory allocation
|
||||
result->reverted_vector_list_.resize(context->result().size());
|
||||
for (uint32_t i = 0; i < context->result().size(); ++i) {
|
||||
std::string &reverted_vector = result->reverted_vector_list_[i];
|
||||
reverted_vector.resize(input_vector_meta_.dimension() *
|
||||
input_vector_meta_.unit_size());
|
||||
if (reformer_->revert(context->result()[i].vector(), new_meta,
|
||||
&reverted_vector) != 0) {
|
||||
LOG_ERROR("Failed to revert vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int Index::_sparse_search(const VectorData &vector_data,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
SearchResult *result,
|
||||
core::IndexContext::Pointer &context) {
|
||||
if (!std::holds_alternative<SparseVector>(vector_data.vector)) {
|
||||
LOG_ERROR("Invalid vector data");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
const SparseVector &sparse_vector =
|
||||
std::get<SparseVector>(vector_data.vector);
|
||||
auto indices = sparse_vector.get_indices();
|
||||
auto values = sparse_vector.get_values();
|
||||
|
||||
std::string converted_sparse_values_buffer;
|
||||
core::IndexQueryMeta new_meta = input_vector_meta_;
|
||||
if (reformer_ != nullptr) {
|
||||
if (reformer_->transform(sparse_vector.count, indices, values,
|
||||
input_vector_meta_,
|
||||
&converted_sparse_values_buffer, &new_meta) != 0) {
|
||||
LOG_ERROR("Failed to transform vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
values = converted_sparse_values_buffer.data();
|
||||
}
|
||||
|
||||
if (search_param->bf_pks != nullptr) {
|
||||
if (streamer_->search_bf_by_p_keys_impl(
|
||||
sparse_vector.count, indices, values,
|
||||
std::vector<std::vector<uint64_t>>{*search_param->bf_pks}, new_meta,
|
||||
context) != 0) {
|
||||
LOG_ERROR("Failed to search_bf_by_p_keys_impl vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
} else if (search_param->is_linear) {
|
||||
if (streamer_->search_bf_impl(sparse_vector.count, indices, values,
|
||||
new_meta, context) != 0) {
|
||||
LOG_ERROR("Failed to search vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
} else {
|
||||
if (streamer_->search_impl(sparse_vector.count, indices, values, new_meta,
|
||||
context) != 0) {
|
||||
LOG_ERROR("Failed to search vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
result->doc_list_ = std::move(context->result());
|
||||
|
||||
if (metric_->support_normalize()) {
|
||||
for (uint32_t i = 0; i < result->doc_list_.size(); ++i) {
|
||||
metric_->normalize(result->doc_list_[i].mutable_score());
|
||||
}
|
||||
}
|
||||
if (reformer_) {
|
||||
// TODO: no need to call reformer_->normalize() when sparse?
|
||||
if (context->fetch_vector() && reformer_->need_revert()) {
|
||||
// TODO: use std::pmr to optimize memory allocation
|
||||
auto &result_doc_list = context->result();
|
||||
result->reverted_sparse_values_list_.resize(result_doc_list.size());
|
||||
for (uint32_t i = 0; i < result_doc_list.size(); ++i) {
|
||||
auto &result_doc = result_doc_list[i].sparse_doc();
|
||||
std::string &reverted_sparse_values =
|
||||
result->reverted_sparse_values_list_[i];
|
||||
reverted_sparse_values.resize(result_doc.sparse_count() *
|
||||
input_vector_meta_.unit_size());
|
||||
if (reformer_->revert(result_doc.sparse_count(),
|
||||
reinterpret_cast<const uint32_t *>(
|
||||
result_doc.sparse_indices().data()),
|
||||
reinterpret_cast<const void *>(
|
||||
result_doc.sparse_values().data()),
|
||||
new_meta, &reverted_sparse_values) != 0) {
|
||||
LOG_ERROR("Failed to revert sparse vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int Index::Merge(const std::vector<Index::Pointer> &indexes,
|
||||
const IndexFilter &filter, const MergeOptions &options) {
|
||||
if (indexes.empty()) {
|
||||
return core::IndexError_Success;
|
||||
}
|
||||
// ivf need builder
|
||||
auto reducer =
|
||||
core::IndexFactory::CreateStreamerReducer("MixedStreamerReducer");
|
||||
if (reducer == nullptr) {
|
||||
LOG_ERROR("Failed to create reducer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (options.write_concurrency == 0) {
|
||||
LOG_ERROR("Write concurrency must be greater than 0");
|
||||
return core::IndexError_InvalidArgument;
|
||||
}
|
||||
// must declare here to ensure its lifespan can cover reducer->reduce()
|
||||
std::unique_ptr<ailego::ThreadPool> local_thread_pool = nullptr;
|
||||
if (options.pool != nullptr) {
|
||||
reducer->set_thread_pool(options.pool);
|
||||
} else {
|
||||
local_thread_pool =
|
||||
std::make_unique<ailego::ThreadPool>(options.write_concurrency);
|
||||
reducer->set_thread_pool(local_thread_pool.get());
|
||||
}
|
||||
|
||||
ailego::Params reducer_params;
|
||||
reducer_params.set(core::PARAM_MIXED_STREAMER_REDUCER_ENABLE_PK_REWRITE,
|
||||
true);
|
||||
reducer_params.set(core::PARAM_MIXED_STREAMER_REDUCER_NUM_OF_ADD_THREADS,
|
||||
options.write_concurrency);
|
||||
if (reducer->init(reducer_params) != 0) {
|
||||
LOG_ERROR("Failed to init reducer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (reducer->set_target_streamer_wiht_info(builder_, streamer_, converter_,
|
||||
reformer_,
|
||||
input_vector_meta_) != 0) {
|
||||
LOG_ERROR("Failed to set target streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
for (const auto &index : indexes) {
|
||||
if (reducer->feed_streamer_with_reformer(index->streamer_,
|
||||
index->reformer_) != 0) {
|
||||
LOG_ERROR("Failed to feed streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
if (reducer->reduce(filter) != 0) {
|
||||
LOG_ERROR("Failed to reduce");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
is_trained_ = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Index::_get_coarse_search_topk(
|
||||
const BaseIndexQueryParam::Pointer &search_param) {
|
||||
float scale_factor = search_param->refiner_param->scale_factor_;
|
||||
if (scale_factor == 0) {
|
||||
scale_factor = 1;
|
||||
}
|
||||
return floor(search_param->topk * scale_factor);
|
||||
}
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
@@ -0,0 +1,321 @@
|
||||
// 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 <cmath>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
#include <magic_enum/magic_enum.hpp>
|
||||
#include "core/framework/index_context.h"
|
||||
#include "core/framework/index_converter.h"
|
||||
#include "core/framework/index_factory.h"
|
||||
#include "core/framework/index_filter.h"
|
||||
#include "core/framework/index_holder.h"
|
||||
#include "core/framework/index_meta.h"
|
||||
#include "core/framework/index_metric.h"
|
||||
#include "core/framework/index_reducer.h"
|
||||
#include "core/framework/index_reformer.h"
|
||||
#include "core/framework/index_searcher.h"
|
||||
#include "core/framework/index_storage.h"
|
||||
#include "core/mixed_reducer/mixed_reducer_params.h"
|
||||
#include "index_param.h"
|
||||
#include "index_param_builders.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
class IndexFactory;
|
||||
|
||||
struct DenseVector {
|
||||
const void *data;
|
||||
// core::IndexQueryMeta meta;
|
||||
// DenseVector(void *data) : data(data) {
|
||||
// meta.set_meta_type(core::IndexMeta::MetaType::MT_DENSE);
|
||||
// };
|
||||
};
|
||||
|
||||
struct SparseVector {
|
||||
uint32_t count;
|
||||
const void *indices;
|
||||
const void *values;
|
||||
|
||||
const uint32_t *get_indices() const {
|
||||
return reinterpret_cast<const uint32_t *>(indices);
|
||||
}
|
||||
|
||||
template <typename T = void>
|
||||
const T *get_values() const {
|
||||
return reinterpret_cast<const T *>(values);
|
||||
}
|
||||
};
|
||||
|
||||
struct VectorData {
|
||||
std::variant<DenseVector, SparseVector> vector;
|
||||
|
||||
// DenseVector dense_vector;
|
||||
// SparseVector sparse_vector;
|
||||
};
|
||||
|
||||
// Used to pass mutable vectors
|
||||
struct DenseVectorBuffer {
|
||||
std::string data; // use string to manage memory
|
||||
};
|
||||
|
||||
struct SparseVectorBuffer {
|
||||
uint32_t count;
|
||||
std::string indices;
|
||||
std::string values;
|
||||
|
||||
uint32_t *get_indices() {
|
||||
return reinterpret_cast<uint32_t *>(indices.data());
|
||||
}
|
||||
|
||||
template <typename T = void>
|
||||
T *get_values() {
|
||||
return reinterpret_cast<T *>(values.data());
|
||||
}
|
||||
};
|
||||
|
||||
struct VectorDataBuffer {
|
||||
std::variant<DenseVectorBuffer, SparseVectorBuffer> vector_buffer;
|
||||
};
|
||||
|
||||
|
||||
struct SearchResult {
|
||||
core::IndexDocumentList doc_list_;
|
||||
// use string to manage memory
|
||||
std::vector<std::string> reverted_vector_list_{};
|
||||
std::vector<std::string> reverted_sparse_values_list_{};
|
||||
};
|
||||
|
||||
// eliminate the pre-alloc of the context pool
|
||||
thread_local static std::array<core::IndexContext::Pointer,
|
||||
(magic_enum::enum_count<IndexType>() - 1) * 2>
|
||||
_context_list;
|
||||
|
||||
class Index {
|
||||
public:
|
||||
typedef std::shared_ptr<Index> Pointer;
|
||||
virtual ~Index() = default;
|
||||
|
||||
// static Index::Pointer Create(const BaseIndexParam ¶m); //IndexFactory
|
||||
virtual int Open(const std::string &file_path,
|
||||
StorageOptions storage_options);
|
||||
int Close();
|
||||
int Flush();
|
||||
// virtual int Serialize(const std::string &file_path);
|
||||
// virtual int Deserialize(const std::string &file_path);
|
||||
|
||||
// // TODO: use holder
|
||||
// virtual int Build() = 0;
|
||||
virtual int Train() {
|
||||
is_trained_ = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// virtual int Dump(const std::string &file_path) = 0;
|
||||
virtual int Merge(const std::vector<Index::Pointer> &indexes,
|
||||
const IndexFilter &filter,
|
||||
const MergeOptions &options = {});
|
||||
// TODO: static reduce
|
||||
|
||||
virtual int Add(const VectorData &vector, uint32_t doc_id);
|
||||
virtual int Fetch(const uint32_t doc_id,
|
||||
VectorDataBuffer *vector_data_buffer);
|
||||
virtual int Search(const VectorData &query,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
SearchResult *result);
|
||||
|
||||
virtual BaseIndexParam::Pointer GetParam() const {
|
||||
return std::make_shared<BaseIndexParam>(param_);
|
||||
}
|
||||
|
||||
virtual bool IsTrained() const {
|
||||
return is_trained_;
|
||||
}
|
||||
|
||||
uint32_t GetDocCount() const {
|
||||
if (streamer_ == nullptr) {
|
||||
return -1;
|
||||
}
|
||||
if (is_sparse_) {
|
||||
return streamer_->create_sparse_provider()->count();
|
||||
} else {
|
||||
return streamer_->create_provider()->count();
|
||||
}
|
||||
}
|
||||
|
||||
core::IndexStreamer::Pointer index_searcher() {
|
||||
return streamer_;
|
||||
}
|
||||
|
||||
protected:
|
||||
int _sparse_fetch(const uint32_t doc_id,
|
||||
VectorDataBuffer *vector_data_buffer);
|
||||
virtual int _dense_fetch(const uint32_t doc_id,
|
||||
VectorDataBuffer *vector_data_buffer);
|
||||
|
||||
int _sparse_add(const VectorData &vector, const uint32_t doc_id,
|
||||
core::IndexContext::Pointer &context);
|
||||
int _dense_add(const VectorData &vector, const uint32_t doc_id,
|
||||
core::IndexContext::Pointer &context);
|
||||
int _sparse_search(const VectorData &query,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
SearchResult *result,
|
||||
core::IndexContext::Pointer &context);
|
||||
int _dense_search(const VectorData &query,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
SearchResult *result, core::IndexContext::Pointer &context);
|
||||
virtual int _prepare_for_search(
|
||||
const VectorData &query, const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context) = 0;
|
||||
virtual int _get_coarse_search_topk(
|
||||
const BaseIndexQueryParam::Pointer &search_param);
|
||||
|
||||
protected:
|
||||
friend class IndexFactory;
|
||||
Index() = default;
|
||||
int Init(const BaseIndexParam ¶m);
|
||||
|
||||
|
||||
protected:
|
||||
int ParseMetricName(const BaseIndexParam ¶m);
|
||||
int CreateAndInitMetric(const BaseIndexParam ¶m);
|
||||
int CreateAndInitConverterReformer(const QuantizerParam ¶m,
|
||||
const BaseIndexParam &index_param);
|
||||
virtual int CreateAndInitStreamer(const BaseIndexParam ¶m) = 0;
|
||||
|
||||
protected:
|
||||
bool init_context() {
|
||||
context_index_ = (magic_enum::enum_integer(param_.index_type) - 1) * 2 +
|
||||
static_cast<size_t>(is_sparse_);
|
||||
if (_context_list[context_index_] == nullptr) {
|
||||
if ((_context_list[context_index_] = streamer_->create_context()) ==
|
||||
nullptr) {
|
||||
LOG_ERROR("Failed to create context");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
core::IndexContext::Pointer &acquire_context() {
|
||||
init_context();
|
||||
return _context_list[context_index_];
|
||||
}
|
||||
|
||||
void release_context() {
|
||||
// context_list_[get_context_index()]->reset();
|
||||
}
|
||||
|
||||
protected:
|
||||
bool is_trained_{false};
|
||||
|
||||
BaseIndexParam param_;
|
||||
ailego::Params proxima_index_params_{};
|
||||
core::IndexMeta proxima_index_meta_{}; // IndexQueryMeta + other index config
|
||||
core::IndexQueryMeta input_vector_meta_; // input
|
||||
core::IndexQueryMeta streamer_vector_meta_; // after reformer.convert()
|
||||
|
||||
core::IndexBuilder::Pointer builder_{};
|
||||
core::IndexStreamer::Pointer streamer_{};
|
||||
core::IndexReformer::Pointer reformer_{};
|
||||
core::IndexConverter::Pointer converter_{}; // for build()
|
||||
core::IndexMetric::Pointer metric_{}; // to do normalization
|
||||
|
||||
size_t context_index_;
|
||||
core::IndexStorage::Pointer storage_{};
|
||||
|
||||
bool is_open_{false};
|
||||
bool is_sparse_{false};
|
||||
bool is_huge_page_{false};
|
||||
bool is_read_only_{false};
|
||||
};
|
||||
|
||||
|
||||
class FlatIndex : public Index {
|
||||
public:
|
||||
FlatIndex() = default;
|
||||
// FlatIndex(const FlatIndexParam ¶m) : param_(param) {}
|
||||
// FlatIndex(FlatIndexParam &¶m) : param(std::move(param)) {}
|
||||
|
||||
|
||||
protected:
|
||||
virtual int CreateAndInitStreamer(const BaseIndexParam ¶m) override;
|
||||
|
||||
virtual int _prepare_for_search(
|
||||
const VectorData &query, const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context) override;
|
||||
|
||||
private:
|
||||
FlatIndexParam param_{};
|
||||
};
|
||||
|
||||
class IVFIndex : public Index {
|
||||
public:
|
||||
IVFIndex() = default;
|
||||
|
||||
protected:
|
||||
virtual int CreateAndInitStreamer(const BaseIndexParam ¶m) override;
|
||||
|
||||
virtual int _prepare_for_search(
|
||||
const VectorData &query, const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context) override;
|
||||
|
||||
virtual int Add(const VectorData &vector, uint32_t doc_id) override;
|
||||
|
||||
virtual int Train() override;
|
||||
|
||||
virtual int Open(const std::string &file_path,
|
||||
StorageOptions storage_options) override;
|
||||
|
||||
virtual int _dense_fetch(const uint32_t doc_id,
|
||||
VectorDataBuffer *vector_data_buffer) override;
|
||||
virtual int Merge(const std::vector<Index::Pointer> &indexes,
|
||||
const IndexFilter &filter,
|
||||
const MergeOptions &options) override;
|
||||
int GenerateHolder();
|
||||
|
||||
private:
|
||||
IVFIndexParam param_{};
|
||||
std::mutex mutex_{};
|
||||
std::vector<std::pair<uint64_t, std::string>> doc_cache_;
|
||||
core::IndexHolder::Pointer holder_{};
|
||||
std::string file_path_;
|
||||
};
|
||||
|
||||
|
||||
class HNSWIndex : public Index {
|
||||
public:
|
||||
HNSWIndex() = default;
|
||||
|
||||
protected:
|
||||
virtual int CreateAndInitStreamer(const BaseIndexParam ¶m) override;
|
||||
|
||||
virtual int _prepare_for_search(
|
||||
const VectorData &query, const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context) override;
|
||||
virtual int _get_coarse_search_topk(
|
||||
const BaseIndexQueryParam::Pointer &search_param);
|
||||
|
||||
|
||||
private:
|
||||
HNSWIndexParam param_{};
|
||||
};
|
||||
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
@@ -0,0 +1,116 @@
|
||||
// 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.
|
||||
//
|
||||
// Created by wangjianning.wjn on 8/28/25.
|
||||
//
|
||||
|
||||
#include "core/framework/index_factory.h"
|
||||
#include "ailego/container/params.h"
|
||||
#include "core/framework/index_meta.h"
|
||||
#include "utils/utils.h"
|
||||
#include "index_factory.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
|
||||
Index::Pointer IndexFactory::CreateAndInitIndex(const BaseIndexParam ¶m) {
|
||||
Index::Pointer ptr = nullptr;
|
||||
// if (param.index_type == IndexType::kIVF) {
|
||||
// const IVFIndexParam *_param = dynamic_cast<const IVFIndexParam
|
||||
// *>(¶m); ptr = std::make_shared<IVFIndex>(param);
|
||||
|
||||
// if (_param->l1Index) {
|
||||
// // TODO: create l1 index
|
||||
// }
|
||||
// if (_param->l2Index) {
|
||||
// // TODO: create l2 index
|
||||
// }
|
||||
// }
|
||||
// if (param.index_type == IndexType::kHNSW) {
|
||||
// ptr = std::make_shared<HNSWIndex>(param);
|
||||
// }
|
||||
if (param.index_type == IndexType::kFlat) {
|
||||
// ptr = std::make_shared<FlatIndex>(param);
|
||||
ptr = std::make_shared<FlatIndex>();
|
||||
} else if (param.index_type == IndexType::kHNSW) {
|
||||
ptr = std::make_shared<HNSWIndex>();
|
||||
} else if (param.index_type == IndexType::kIVF) {
|
||||
ptr = std::make_shared<IVFIndex>();
|
||||
} else {
|
||||
LOG_ERROR("Unsupported index type: ");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (!ptr) {
|
||||
LOG_ERROR("Failed to create index");
|
||||
return nullptr;
|
||||
}
|
||||
if (0 != ptr->Init(param)) {
|
||||
LOG_ERROR("Failed to init index");
|
||||
return nullptr;
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
|
||||
BaseIndexParam::Pointer IndexFactory::DeserializeIndexParamFromJson(
|
||||
const std::string &json_str) {
|
||||
ailego::JsonValue json_value;
|
||||
if (!json_value.parse(json_str)) {
|
||||
LOG_ERROR("Failed to parse json string: %s", json_str.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
ailego::JsonObject json_obj = json_value.as_object();
|
||||
ailego::JsonValue tmp_json_value;
|
||||
|
||||
IndexType index_type;
|
||||
|
||||
if (!extract_enum_from_json<IndexType>(json_obj, "index_type", index_type,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize index type");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
switch (index_type) {
|
||||
case IndexType::kFlat: {
|
||||
FlatIndexParam::Pointer param = std::make_shared<FlatIndexParam>();
|
||||
if (!param->DeserializeFromJson(json_str)) {
|
||||
LOG_ERROR("Failed to deserialize flat index param");
|
||||
return nullptr;
|
||||
}
|
||||
return param;
|
||||
}
|
||||
case IndexType::kHNSW: {
|
||||
HNSWIndexParam::Pointer param = std::make_shared<HNSWIndexParam>();
|
||||
if (!param->DeserializeFromJson(json_str)) {
|
||||
LOG_ERROR("Failed to deserialize hnsw index param");
|
||||
return nullptr;
|
||||
}
|
||||
return param;
|
||||
}
|
||||
case IndexType::kIVF: {
|
||||
IVFIndexParam::Pointer param = std::make_shared<IVFIndexParam>();
|
||||
if (!param->DeserializeFromJson(json_str)) {
|
||||
LOG_ERROR("Failed to deserialize hnsw index param");
|
||||
return nullptr;
|
||||
}
|
||||
return param;
|
||||
}
|
||||
default:
|
||||
LOG_ERROR("Unsupported index type: %s",
|
||||
magic_enum::enum_name(index_type).data());
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
@@ -0,0 +1,225 @@
|
||||
// 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.
|
||||
//
|
||||
// Created by wangjianning.wjn on 8/28/25.
|
||||
//
|
||||
|
||||
#ifndef ZVEC_INDEX_FACTORY_H
|
||||
#define ZVEC_INDEX_FACTORY_H
|
||||
|
||||
#pragma once
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "index.h"
|
||||
#include "index_param.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
// 索引的工厂类
|
||||
class IndexFactory {
|
||||
public:
|
||||
static Index::Pointer CreateAndInitIndex(const BaseIndexParam ¶m);
|
||||
|
||||
static BaseIndexParam::Pointer DeserializeIndexParamFromJson(
|
||||
const std::string &json_str);
|
||||
|
||||
|
||||
static std::string QueryParamSerializeToJson(
|
||||
const BaseIndexQueryParam ¶m);
|
||||
|
||||
|
||||
template <
|
||||
typename QueryParamType,
|
||||
std::enable_if_t<std::is_base_of_v<BaseIndexQueryParam, QueryParamType>,
|
||||
bool> = true>
|
||||
static std::string QueryParamSerializeToJson(const QueryParamType ¶m,
|
||||
bool omit_empty_value = false);
|
||||
|
||||
template <
|
||||
typename QueryParamType,
|
||||
std::enable_if_t<std::is_base_of_v<BaseIndexQueryParam, QueryParamType>,
|
||||
bool> = true>
|
||||
static typename QueryParamType::Pointer QueryParamDeserializeFromJson(
|
||||
const std::string &json_str);
|
||||
|
||||
// register() -- Index class should have a `create` interface
|
||||
};
|
||||
|
||||
|
||||
template <typename QueryParamType,
|
||||
std::enable_if_t<
|
||||
std::is_base_of_v<BaseIndexQueryParam, QueryParamType>, bool> >
|
||||
std::string IndexFactory::QueryParamSerializeToJson(const QueryParamType ¶m,
|
||||
bool omit_empty_value) {
|
||||
ailego::JsonObject json_obj;
|
||||
|
||||
// BaseIndexQueryParam
|
||||
// omit filter & bf_pks
|
||||
if (!omit_empty_value || param.topk != 0) {
|
||||
json_obj.set("topk", ailego::JsonValue(param.topk));
|
||||
}
|
||||
if (!omit_empty_value || param.fetch_vector) {
|
||||
json_obj.set("fetch_vector", ailego::JsonValue(param.fetch_vector));
|
||||
}
|
||||
if (!omit_empty_value || param.radius != 0.0f) {
|
||||
json_obj.set("radius", ailego::JsonValue(param.radius));
|
||||
}
|
||||
if (!omit_empty_value || param.is_linear) {
|
||||
json_obj.set("is_linear", ailego::JsonValue(param.is_linear));
|
||||
}
|
||||
|
||||
IndexType index_type;
|
||||
if constexpr (std::is_same_v<QueryParamType, FlatQueryParam>) {
|
||||
// index_type
|
||||
index_type = IndexType::kFlat;
|
||||
} else if constexpr (std::is_same_v<QueryParamType, HNSWQueryParam>) {
|
||||
if (!omit_empty_value || param.ef_search != 0) {
|
||||
json_obj.set("ef_search", ailego::JsonValue(param.ef_search));
|
||||
}
|
||||
index_type = IndexType::kHNSW;
|
||||
} else if constexpr (std::is_same_v<QueryParamType, IVFQueryParam>) {
|
||||
if (!omit_empty_value || param.nprobe != 0) {
|
||||
json_obj.set("nprobe", ailego::JsonValue(param.nprobe));
|
||||
}
|
||||
index_type = IndexType::kIVF;
|
||||
// json_obj.set("l1QueryParam",
|
||||
// ailego::JsonValue(QueryParamSerializeToJson(param.l1QueryParam)));
|
||||
// json_obj.set("l2QueryParam",
|
||||
// ailego::JsonValue(QueryParamSerializeToJson(param.l2QueryParam)));
|
||||
}
|
||||
|
||||
json_obj.set("index_type",
|
||||
ailego::JsonValue(magic_enum::enum_name(index_type).data()));
|
||||
|
||||
return ailego::JsonValue(json_obj).as_json_string().as_stl_string();
|
||||
}
|
||||
|
||||
template <typename QueryParamType,
|
||||
std::enable_if_t<
|
||||
std::is_base_of_v<BaseIndexQueryParam, QueryParamType>, bool> >
|
||||
typename QueryParamType::Pointer IndexFactory::QueryParamDeserializeFromJson(
|
||||
const std::string &json_str) {
|
||||
ailego::JsonValue tmp_json_value;
|
||||
if (!tmp_json_value.parse(json_str)) {
|
||||
LOG_ERROR("Failed to parse json string: %s", json_str.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
ailego::JsonObject json_obj = tmp_json_value.as_object();
|
||||
|
||||
auto parse_common_fields = [&](auto ¶m) -> bool {
|
||||
if (!extract_value_from_json(json_obj, "topk", param->topk,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize topk");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!extract_value_from_json(json_obj, "fetch_vector", param->fetch_vector,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize fetch_vector");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!extract_value_from_json(json_obj, "radius", param->radius,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize radius");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!extract_value_from_json(json_obj, "is_linear", param->is_linear,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize is_linear");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
IndexType index_type;
|
||||
|
||||
if (!extract_enum_from_json<IndexType>(json_obj, "index_type", index_type,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize index type");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if constexpr (std::is_same_v<QueryParamType, BaseIndexQueryParam>) {
|
||||
if (index_type == IndexType::kFlat) {
|
||||
auto param = std::make_shared<FlatQueryParam>();
|
||||
if (!parse_common_fields(param)) {
|
||||
return nullptr;
|
||||
}
|
||||
return param;
|
||||
} else if (index_type == IndexType::kHNSW) {
|
||||
auto param = std::make_shared<HNSWQueryParam>();
|
||||
if (!parse_common_fields(param)) {
|
||||
return nullptr;
|
||||
}
|
||||
if (!extract_value_from_json(json_obj, "ef_search", param->ef_search,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize ef_search");
|
||||
return nullptr;
|
||||
}
|
||||
return param;
|
||||
} else if (index_type == IndexType::kIVF) {
|
||||
auto param = std::make_shared<IVFQueryParam>();
|
||||
if (!parse_common_fields(param)) {
|
||||
return nullptr;
|
||||
}
|
||||
if (!extract_value_from_json(json_obj, "nprobe", param->nprobe,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize nprobe");
|
||||
return nullptr;
|
||||
}
|
||||
return param;
|
||||
} else {
|
||||
LOG_ERROR("Unsupported index type: %s",
|
||||
magic_enum::enum_name(index_type).data());
|
||||
return nullptr;
|
||||
}
|
||||
} else {
|
||||
auto param = std::make_shared<QueryParamType>();
|
||||
if (!parse_common_fields(param)) {
|
||||
return nullptr;
|
||||
}
|
||||
if constexpr (std::is_same_v<QueryParamType, FlatQueryParam>) {
|
||||
} else if constexpr (std::is_same_v<QueryParamType, HNSWQueryParam>) {
|
||||
if (!extract_value_from_json(json_obj, "ef_search", param->ef_search,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize ef_search");
|
||||
return nullptr;
|
||||
}
|
||||
} else if constexpr (std::is_same_v<QueryParamType, IVFQueryParam>) {
|
||||
if (!extract_value_from_json(json_obj, "nprobe", param->nprobe,
|
||||
tmp_json_value)) {
|
||||
LOG_ERROR("Failed to deserialize nprobe");
|
||||
return nullptr;
|
||||
}
|
||||
} else {
|
||||
LOG_ERROR("Unsupported index type: %s",
|
||||
magic_enum::enum_name(index_type).data());
|
||||
return nullptr;
|
||||
}
|
||||
return param;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
|
||||
|
||||
#endif // ZVEC_INDEX_FACTORY_H
|
||||
@@ -0,0 +1,206 @@
|
||||
#include "index_param.h"
|
||||
#include <type_traits>
|
||||
#include <ailego/logger/logger.h>
|
||||
|
||||
namespace zvec {
|
||||
namespace core_interface {
|
||||
ailego::JsonObject BaseIndexParam::SerializeToJsonObject(
|
||||
bool omit_empty_value) const {
|
||||
ailego::JsonObject json_obj;
|
||||
|
||||
if (!omit_empty_value || index_type != IndexType::kNone) {
|
||||
json_obj.set("index_type",
|
||||
ailego::JsonValue(magic_enum::enum_name(index_type).data()));
|
||||
}
|
||||
if (!omit_empty_value || metric_type != MetricType::kNone) {
|
||||
json_obj.set("metric_type",
|
||||
ailego::JsonValue(magic_enum::enum_name(metric_type).data()));
|
||||
}
|
||||
if (!omit_empty_value || dimension != 0) {
|
||||
json_obj.set("dimension", ailego::JsonValue(dimension));
|
||||
}
|
||||
if (!omit_empty_value || version != 0) {
|
||||
json_obj.set("version", ailego::JsonValue(version));
|
||||
}
|
||||
if (!omit_empty_value || is_sparse) {
|
||||
json_obj.set("is_sparse", ailego::JsonValue(is_sparse));
|
||||
}
|
||||
if (!omit_empty_value || data_type != DataType::DT_UNDEFINED) {
|
||||
json_obj.set("data_type",
|
||||
ailego::JsonValue(magic_enum::enum_name(data_type).data()));
|
||||
}
|
||||
if (!omit_empty_value || use_id_map) {
|
||||
json_obj.set("use_id_map", ailego::JsonValue(use_id_map));
|
||||
}
|
||||
if (!omit_empty_value || is_huge_page) {
|
||||
json_obj.set("is_huge_page", ailego::JsonValue(is_huge_page));
|
||||
}
|
||||
|
||||
// if (preprocess_param) {
|
||||
// json.set("preprocess_param", preprocess_param->SerializeToJson());
|
||||
// }
|
||||
if (!omit_empty_value || quantizer_param.type != QuantizerType::kNone) {
|
||||
json_obj.set("quantizer_param",
|
||||
quantizer_param.SerializeToJsonObject(omit_empty_value));
|
||||
}
|
||||
// if (refiner_param) {
|
||||
// json.set("refiner_param", refiner_param->SerializeToJson());
|
||||
// }
|
||||
// if (default_query_param) {
|
||||
// json.set("default_query_param",
|
||||
// default_query_param->SerializeToJson());
|
||||
// }
|
||||
return json_obj;
|
||||
}
|
||||
|
||||
|
||||
ailego::JsonObject FlatIndexParam::SerializeToJsonObject(
|
||||
bool omit_empty_value) const {
|
||||
auto json_obj = BaseIndexParam::SerializeToJsonObject(omit_empty_value);
|
||||
if (!omit_empty_value || major_order != IndexMeta::MajorOrder::MO_UNDEFINED) {
|
||||
json_obj.set("major_order",
|
||||
ailego::JsonValue(magic_enum::enum_name(major_order).data()));
|
||||
}
|
||||
return json_obj;
|
||||
}
|
||||
|
||||
ailego::JsonObject HNSWIndexParam::SerializeToJsonObject(
|
||||
bool omit_empty_value) const {
|
||||
auto json_obj = BaseIndexParam::SerializeToJsonObject(omit_empty_value);
|
||||
json_obj.set("m", ailego::JsonValue(m));
|
||||
json_obj.set("ef_construction", ailego::JsonValue(ef_construction));
|
||||
return json_obj;
|
||||
}
|
||||
|
||||
bool BaseIndexParam::DeserializeFromJsonObject(
|
||||
const ailego::JsonObject &json_obj) {
|
||||
DESERIALIZE_ENUM_FIELD(json_obj, index_type, IndexType);
|
||||
DESERIALIZE_ENUM_FIELD(json_obj, metric_type, MetricType);
|
||||
DESERIALIZE_ENUM_FIELD(json_obj, data_type, DataType);
|
||||
|
||||
DESERIALIZE_VALUE_FIELD(json_obj, dimension);
|
||||
DESERIALIZE_VALUE_FIELD(json_obj, version);
|
||||
DESERIALIZE_VALUE_FIELD(json_obj, is_sparse);
|
||||
DESERIALIZE_VALUE_FIELD(json_obj, use_id_map);
|
||||
DESERIALIZE_VALUE_FIELD(json_obj, is_huge_page);
|
||||
|
||||
ailego::JsonValue tmp_json_value;
|
||||
if (json_obj.has("quantizer_param")) {
|
||||
if (json_obj.get("quantizer_param", &tmp_json_value);
|
||||
tmp_json_value.is_object()) {
|
||||
quantizer_param.DeserializeFromJsonObject(tmp_json_value.as_object());
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FlatIndexParam::DeserializeFromJsonObject(
|
||||
const ailego::JsonObject &json_obj) {
|
||||
if (!BaseIndexParam::DeserializeFromJsonObject(json_obj)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (index_type != IndexType::kFlat) {
|
||||
LOG_ERROR("index_type is not kFlat");
|
||||
return false;
|
||||
}
|
||||
|
||||
DESERIALIZE_ENUM_FIELD(json_obj, major_order, IndexMeta::MajorOrder);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HNSWIndexParam::DeserializeFromJsonObject(
|
||||
const ailego::JsonObject &json_obj) {
|
||||
if (!BaseIndexParam::DeserializeFromJsonObject(json_obj)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (index_type != IndexType::kHNSW) {
|
||||
LOG_ERROR("index_type is not kHNSW");
|
||||
return false;
|
||||
}
|
||||
|
||||
DESERIALIZE_VALUE_FIELD(json_obj, m);
|
||||
DESERIALIZE_VALUE_FIELD(json_obj, ef_construction);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// bool BaseIndexQueryParam::DeserializeFromJsonObject(
|
||||
// const ailego::JsonObject &json_obj) {
|
||||
// DESERIALIZE_ENUM_FIELD(json_obj, index_type, IndexType);
|
||||
// DESERIALIZE_VALUE_FIELD(json_obj, topk);
|
||||
// DESERIALIZE_VALUE_FIELD(json_obj, fetch_vector);
|
||||
// DESERIALIZE_VALUE_FIELD(json_obj, radius);
|
||||
// DESERIALIZE_VALUE_FIELD(json_obj, is_linear);
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// ailego::JsonObject BaseIndexQueryParam::SerializeToJsonObject(
|
||||
// bool omit_empty_value) const {
|
||||
// ailego::JsonObject json_obj;
|
||||
// if (!omit_empty_value || index_type != IndexType::kNone) {
|
||||
// json_obj.set("index_type",
|
||||
// ailego::JsonValue(magic_enum::enum_name(index_type).data()));
|
||||
// }
|
||||
// if (!omit_empty_value || topk != 0) {
|
||||
// json_obj.set("topk", ailego::JsonValue(topk));
|
||||
// }
|
||||
// if (!omit_empty_value || fetch_vector) {
|
||||
// json_obj.set("fetch_vector", ailego::JsonValue(fetch_vector));
|
||||
// }
|
||||
// if (!omit_empty_value || radius != 0.0f) {
|
||||
// json_obj.set("radius", ailego::JsonValue(radius));
|
||||
// }
|
||||
// if (!omit_empty_value || is_linear) {
|
||||
// json_obj.set("is_linear", ailego::JsonValue(is_linear));
|
||||
// }
|
||||
// return json_obj;
|
||||
// }
|
||||
|
||||
// bool FlatQueryParam::DeserializeFromJsonObject(
|
||||
// const ailego::JsonObject &json_obj) {
|
||||
// if (!BaseIndexQueryParam::DeserializeFromJsonObject(json_obj)) {
|
||||
// return false;
|
||||
// }
|
||||
// if (index_type != IndexType::kFlat) {
|
||||
// LOG_ERROR("index_type is not kFlat");
|
||||
// return false;
|
||||
// }
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// ailego::JsonObject FlatQueryParam::SerializeToJsonObject(
|
||||
// bool omit_empty_value) const {
|
||||
// auto json_obj =
|
||||
// BaseIndexQueryParam::SerializeToJsonObject(omit_empty_value);
|
||||
// return json_obj;
|
||||
// }
|
||||
|
||||
// bool HNSWQueryParam::DeserializeFromJsonObject(
|
||||
// const ailego::JsonObject &json_obj) {
|
||||
// if (!BaseIndexQueryParam::DeserializeFromJsonObject(json_obj)) {
|
||||
// return false;
|
||||
// }
|
||||
// if (index_type != IndexType::kHNSW) {
|
||||
// LOG_ERROR("index_type is not kHNSW");
|
||||
// return false;
|
||||
// }
|
||||
// DESERIALIZE_VALUE_FIELD(json_obj, ef_search);
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// ailego::JsonObject HNSWQueryParam::SerializeToJsonObject(
|
||||
// bool omit_empty_value) const {
|
||||
// auto json_obj =
|
||||
// BaseIndexQueryParam::SerializeToJsonObject(omit_empty_value);
|
||||
// if (!omit_empty_value || ef_search != 0) {
|
||||
// json_obj.set("ef_search", ailego::JsonValue(ef_search));
|
||||
// }
|
||||
// return json_obj;
|
||||
// }
|
||||
|
||||
|
||||
} // namespace core_interface
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,340 @@
|
||||
// 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.
|
||||
//
|
||||
// Created by wangjianning.wjn on 8/28/25.
|
||||
//
|
||||
|
||||
#ifndef ZVEC_INDEX_PARAM_H
|
||||
#define ZVEC_INDEX_PARAM_H
|
||||
#pragma once
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ailego/encoding/json.h>
|
||||
#include <ailego/parallel/thread_pool.h>
|
||||
#include <magic_enum/magic_enum.hpp>
|
||||
#include "core/framework/index_filter.h"
|
||||
#include "core/framework/index_meta.h"
|
||||
#include "utils/utils.h"
|
||||
#include "constants.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
#define MAX_DIMENSION 65536
|
||||
// #define MAX_EF_CONSTRUCTION 65536
|
||||
// #define MAX_EF_SEARCH 100
|
||||
|
||||
class IndexFactory;
|
||||
class Index;
|
||||
class BaseIndexParam;
|
||||
class BaseIndexQueryParam;
|
||||
|
||||
struct StorageOptions {
|
||||
enum class StorageType { kNone, kMMAP, kMemory, kBufferPool };
|
||||
|
||||
StorageType type = StorageType::kNone;
|
||||
bool create_new = false;
|
||||
bool read_only = false;
|
||||
};
|
||||
|
||||
struct MergeOptions {
|
||||
uint32_t write_concurrency = 1;
|
||||
ailego::ThreadPool *pool = nullptr;
|
||||
};
|
||||
|
||||
using IndexMeta = core::IndexMeta;
|
||||
using IndexQueryMeta = core::IndexQueryMeta;
|
||||
using DataType = core::IndexMeta::DataType;
|
||||
using IndexFilter = core::IndexFilter;
|
||||
|
||||
|
||||
// 定义支持的索引类型
|
||||
enum class IndexType {
|
||||
// to do: support factory's register, may change to
|
||||
// `static constexpr std::string_view`, which may incur str comp overhead
|
||||
kNone,
|
||||
kFlat,
|
||||
kIVF, // it's actual a two-layer index
|
||||
kHNSW,
|
||||
};
|
||||
|
||||
enum class IVFSearchMethod { kBF, kHNSW };
|
||||
|
||||
enum class MetricType {
|
||||
kNone,
|
||||
kL2sq, // Euclidean
|
||||
kInnerProduct,
|
||||
kCosine,
|
||||
kMIPSL2sq // spherical?
|
||||
};
|
||||
|
||||
enum class QuantizerType {
|
||||
kNone,
|
||||
kPQ, // Product Quantization
|
||||
kQuickADC, // TODO: +refiner ? // should be a type of index?
|
||||
kAQ,
|
||||
kFP16,
|
||||
kInt8,
|
||||
kInt4
|
||||
};
|
||||
|
||||
struct SerializableBase {
|
||||
std::string SerializeToJson(bool omit_empty_value = false) const {
|
||||
return zvec::ailego::JsonValue(SerializeToJsonObject(omit_empty_value))
|
||||
.as_json_string()
|
||||
.as_stl_string();
|
||||
}
|
||||
|
||||
bool DeserializeFromJson(const std::string &json_str) {
|
||||
ailego::JsonValue json_value;
|
||||
if (!json_value.parse(json_str)) {
|
||||
return false;
|
||||
}
|
||||
return DeserializeFromJsonObject(json_value.as_object());
|
||||
}
|
||||
|
||||
protected:
|
||||
virtual ailego::JsonObject SerializeToJsonObject(
|
||||
bool omit_empty_value = false) const = 0;
|
||||
virtual bool DeserializeFromJsonObject(
|
||||
const ailego::JsonObject &json_obj) = 0;
|
||||
};
|
||||
|
||||
// TODO: maybe a base class for quantizer?
|
||||
struct QuantizerParam : public SerializableBase {
|
||||
QuantizerType type = QuantizerType::kNone;
|
||||
int num_subquantizers = 8; // M
|
||||
int num_bits = 8; // bits per subquantizer
|
||||
|
||||
// Constructors
|
||||
// QuantizerParam() = default;
|
||||
QuantizerParam(QuantizerType t = QuantizerType::kNone, int subquantizers = 8,
|
||||
int bits = 8)
|
||||
: type(t), num_subquantizers(subquantizers), num_bits(bits) {}
|
||||
|
||||
|
||||
protected:
|
||||
friend class BaseIndexParam;
|
||||
virtual ailego::JsonObject SerializeToJsonObject(
|
||||
bool omit_empty_value = false) const override {
|
||||
ailego::JsonObject json_obj;
|
||||
if (!omit_empty_value || type != QuantizerType::kNone) {
|
||||
json_obj.set("type",
|
||||
zvec::ailego::JsonValue(magic_enum::enum_name(type).data()));
|
||||
}
|
||||
return json_obj;
|
||||
}
|
||||
|
||||
virtual bool DeserializeFromJsonObject(
|
||||
const ailego::JsonObject &json_obj) override {
|
||||
DESERIALIZE_ENUM_FIELD(json_obj, type, QuantizerType);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// preprocessor
|
||||
enum class PreprocessorType {
|
||||
kNone,
|
||||
kPCA,
|
||||
kOPQ,
|
||||
};
|
||||
|
||||
struct PreprocessorParam {
|
||||
PreprocessorType type = PreprocessorType::kNone;
|
||||
|
||||
// Constructors
|
||||
// PreprocessorParam() = default;
|
||||
explicit PreprocessorParam(PreprocessorType t = PreprocessorType::kNone)
|
||||
: type(t) {}
|
||||
};
|
||||
|
||||
struct RefinerParam {
|
||||
using Pointer = std::shared_ptr<RefinerParam>;
|
||||
|
||||
float scale_factor_{0};
|
||||
std::shared_ptr<Index> reference_index = nullptr;
|
||||
};
|
||||
|
||||
// --- Query Parameters (can be passed to search methods) ---
|
||||
class BaseIndexQueryParam {
|
||||
public:
|
||||
using Pointer = std::shared_ptr<BaseIndexQueryParam>;
|
||||
|
||||
virtual ~BaseIndexQueryParam() = default;
|
||||
|
||||
uint32_t topk = 10;
|
||||
bool fetch_vector = false;
|
||||
std::shared_ptr<IndexFilter> filter = nullptr;
|
||||
std::shared_ptr<std::vector<uint64_t>> bf_pks = nullptr;
|
||||
float radius = 0.0f;
|
||||
bool is_linear = false;
|
||||
RefinerParam::Pointer refiner_param = nullptr;
|
||||
|
||||
virtual Pointer Clone() const = 0;
|
||||
};
|
||||
|
||||
struct FlatQueryParam : public BaseIndexQueryParam {
|
||||
using Pointer = std::shared_ptr<FlatQueryParam>;
|
||||
|
||||
BaseIndexQueryParam::Pointer Clone() const override {
|
||||
return std::make_shared<FlatQueryParam>(*this);
|
||||
}
|
||||
};
|
||||
|
||||
struct HNSWQueryParam : public BaseIndexQueryParam {
|
||||
using Pointer = std::shared_ptr<HNSWQueryParam>;
|
||||
|
||||
uint32_t ef_search = kDefaultHnswEfSearch;
|
||||
|
||||
BaseIndexQueryParam::Pointer Clone() const override {
|
||||
return std::make_shared<HNSWQueryParam>(*this);
|
||||
}
|
||||
};
|
||||
|
||||
struct IVFQueryParam : public BaseIndexQueryParam {
|
||||
int nprobe = 10;
|
||||
std::shared_ptr<BaseIndexQueryParam> l1QueryParam = nullptr;
|
||||
std::shared_ptr<BaseIndexQueryParam> l2QueryParam = nullptr;
|
||||
|
||||
using Pointer = std::shared_ptr<IVFQueryParam>;
|
||||
|
||||
BaseIndexQueryParam::Pointer Clone() const override {
|
||||
auto cloned_this = std::make_shared<IVFQueryParam>(*this);
|
||||
cloned_this->l1QueryParam = l1QueryParam ? l1QueryParam->Clone() : nullptr;
|
||||
cloned_this->l2QueryParam = l2QueryParam ? l2QueryParam->Clone() : nullptr;
|
||||
return cloned_this;
|
||||
}
|
||||
};
|
||||
|
||||
// --- Construction Parameters ---
|
||||
// template<typename IndexQueryParamType>
|
||||
class BaseIndexParam : public SerializableBase {
|
||||
public:
|
||||
using Pointer = std::shared_ptr<BaseIndexParam>;
|
||||
|
||||
explicit BaseIndexParam(IndexType type = IndexType::kNone,
|
||||
MetricType metric = MetricType::kL2sq, int dim = 0,
|
||||
int ver = 0)
|
||||
: index_type(type), metric_type(metric), dimension(dim), version(ver) {}
|
||||
|
||||
virtual ~BaseIndexParam() = default;
|
||||
|
||||
IndexType index_type = IndexType::kNone;
|
||||
MetricType metric_type = MetricType::kL2sq;
|
||||
int dimension = 0; // [1, MAX_DIMENSION]
|
||||
int version = 0; // for compatibility
|
||||
bool is_sparse = false;
|
||||
bool is_huge_page = false;
|
||||
DataType data_type = DataType::DT_UNDEFINED;
|
||||
bool use_id_map = true;
|
||||
|
||||
// IndexMeta meta;
|
||||
ailego::Params params;
|
||||
|
||||
// pipeline
|
||||
PreprocessorParam preprocess_param;
|
||||
QuantizerParam quantizer_param;
|
||||
|
||||
BaseIndexQueryParam::Pointer default_query_param = nullptr;
|
||||
// virtual std::shared_ptr<BaseIndexQueryParam> GetDefaultQueryParam() const
|
||||
// {
|
||||
// return std::make_shared<BaseIndexQueryParam>();
|
||||
// }
|
||||
//
|
||||
|
||||
protected:
|
||||
virtual bool DeserializeFromJsonObject(
|
||||
const ailego::JsonObject &json_obj) override;
|
||||
virtual ailego::JsonObject SerializeToJsonObject(
|
||||
bool omit_empty_value = false) const override;
|
||||
};
|
||||
|
||||
struct FlatIndexParam : public BaseIndexParam {
|
||||
using Pointer = std::shared_ptr<FlatIndexParam>;
|
||||
FlatIndexParam() : BaseIndexParam(IndexType::kFlat) {}
|
||||
|
||||
IndexMeta::MajorOrder major_order = IndexMeta::MajorOrder::MO_ROW;
|
||||
|
||||
protected:
|
||||
bool DeserializeFromJsonObject(const ailego::JsonObject &json_obj) override;
|
||||
ailego::JsonObject SerializeToJsonObject(
|
||||
bool omit_empty_value = false) const override;
|
||||
};
|
||||
|
||||
struct IVFIndexParam : public BaseIndexParam {
|
||||
using Pointer = std::shared_ptr<IVFIndexParam>;
|
||||
int nlist = 1024;
|
||||
int niters = 10;
|
||||
std::shared_ptr<BaseIndexParam> l1Index = nullptr;
|
||||
std::shared_ptr<BaseIndexParam> l2Index = nullptr;
|
||||
bool use_soar = false;
|
||||
|
||||
// Constructors with delegation
|
||||
IVFIndexParam() : BaseIndexParam(IndexType::kIVF) {}
|
||||
|
||||
IVFIndexParam(int nlist, int niters, std::shared_ptr<BaseIndexParam> l1Index,
|
||||
std::shared_ptr<BaseIndexParam> l2Index)
|
||||
: BaseIndexParam(IndexType::kIVF),
|
||||
nlist(nlist),
|
||||
niters(niters),
|
||||
l1Index(std::move(l1Index)),
|
||||
l2Index(std::move(l2Index)) {}
|
||||
|
||||
IVFIndexParam(MetricType metric, int dim, int nlist, int niters,
|
||||
std::shared_ptr<BaseIndexParam> l1Index,
|
||||
std::shared_ptr<BaseIndexParam> l2Index)
|
||||
: BaseIndexParam(IndexType::kIVF, metric, dim),
|
||||
nlist(nlist),
|
||||
niters(niters),
|
||||
l1Index(std::move(l1Index)),
|
||||
l2Index(std::move(l2Index)) {}
|
||||
|
||||
// query param:
|
||||
// topk of l1Index's param ==== IVFIndexQueryParam.nprobe
|
||||
// topk of l2Index's param ==== IVFIndexQueryParam.topK
|
||||
|
||||
// IVFIndexParam.metric_type === l2Index's metric_type
|
||||
// IVFIndexParam.quantization === l2Index's quantization
|
||||
};
|
||||
|
||||
struct HNSWIndexParam : public BaseIndexParam {
|
||||
using Pointer = std::shared_ptr<HNSWIndexParam>;
|
||||
int m = kDefaultHnswNeighborCnt; // 图中每个点的邻居数
|
||||
int ef_construction = kDefaultHnswEfConstruction; // 构建时的邻居候选大小
|
||||
|
||||
// Constructors with delegation
|
||||
HNSWIndexParam() : BaseIndexParam(IndexType::kHNSW) {}
|
||||
|
||||
HNSWIndexParam(int m, int ef_construction)
|
||||
: BaseIndexParam(IndexType::kHNSW),
|
||||
m(m),
|
||||
ef_construction(ef_construction) {}
|
||||
|
||||
HNSWIndexParam(MetricType metric, int dim, int m, int ef_construction)
|
||||
: BaseIndexParam(IndexType::kHNSW, metric, dim),
|
||||
m(m),
|
||||
ef_construction(ef_construction) {}
|
||||
|
||||
protected:
|
||||
bool DeserializeFromJsonObject(const ailego::JsonObject &json_obj) override;
|
||||
ailego::JsonObject SerializeToJsonObject(
|
||||
bool omit_empty_value = false) const override;
|
||||
};
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
#endif // ZVEC_INDEX_PARAM_H
|
||||
@@ -0,0 +1,341 @@
|
||||
#ifndef ZVEC_INDEX_PARAM_BUILDERS_H
|
||||
#define ZVEC_INDEX_PARAM_BUILDERS_H
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include "index_param.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
|
||||
// struct ConditionalIndexParam {
|
||||
// // predicate / rule / threshold
|
||||
// // candidate
|
||||
// };
|
||||
|
||||
|
||||
// chaining calls builder
|
||||
template <typename ActualIndexParamBuilderType, typename ActualIndexParamType>
|
||||
class BaseIndexParamBuilder { // : public
|
||||
// std::enable_shared_from_this<Resource>
|
||||
public:
|
||||
BaseIndexParamBuilder() : param(std::make_shared<ActualIndexParamType>()) {};
|
||||
virtual ~BaseIndexParamBuilder() = default;
|
||||
|
||||
ActualIndexParamBuilderType &WithVersion(int version) {
|
||||
param.version = version;
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
ActualIndexParamBuilderType &WithIndexType(IndexType index_type) {
|
||||
param->index_type = index_type;
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
ActualIndexParamBuilderType &WithMetricType(MetricType metric_type) {
|
||||
param->metric_type = metric_type;
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
ActualIndexParamBuilderType &WithDimension(int dimension) {
|
||||
param->dimension = dimension;
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
ActualIndexParamBuilderType &WithPreprocessParam(
|
||||
const PreprocessorParam &preprocess_param) {
|
||||
param->preprocess_param =
|
||||
std::make_shared<PreprocessorParam>(preprocess_param);
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
ActualIndexParamBuilderType &WithQuantizerParam(
|
||||
const QuantizerParam &quantizer_param) {
|
||||
param->quantizer_param = quantizer_param;
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
// ActualIndexParamBuilderType &WithRefinerParam(
|
||||
// const RefinerParam &refiner_param) {
|
||||
// param->refiner_param = refiner_param;
|
||||
// return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
// }
|
||||
// ActualIndexParamBuilderType &WithDefaultQueryParam(
|
||||
// const BaseIndexQueryParam &default_query_param) {
|
||||
// param->default_query_param = default_query_param;
|
||||
// return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
// }
|
||||
|
||||
ActualIndexParamBuilderType &WithIsSparse(bool is_sparse) {
|
||||
param->is_sparse = is_sparse;
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
ActualIndexParamBuilderType &WithDataType(DataType data_type) {
|
||||
param->data_type = data_type;
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
|
||||
ActualIndexParamBuilderType &WithUseIDMap(bool use_id_map) {
|
||||
param->use_id_map = use_id_map;
|
||||
return static_cast<ActualIndexParamBuilderType &>(*this);
|
||||
}
|
||||
|
||||
virtual std::shared_ptr<ActualIndexParamType> Build() = 0;
|
||||
|
||||
protected:
|
||||
std::shared_ptr<ActualIndexParamType> param;
|
||||
};
|
||||
|
||||
class FlatIndexParamBuilder
|
||||
: public BaseIndexParamBuilder<FlatIndexParamBuilder, FlatIndexParam> {
|
||||
public:
|
||||
FlatIndexParamBuilder() = default;
|
||||
std::shared_ptr<FlatIndexParam> Build() override {
|
||||
return param;
|
||||
}
|
||||
};
|
||||
|
||||
class IVFIndexParamBuilder
|
||||
: public BaseIndexParamBuilder<IVFIndexParamBuilder, IVFIndexParam> {
|
||||
public:
|
||||
IVFIndexParamBuilder() = default;
|
||||
IVFIndexParamBuilder &WithNList(int nlist) {
|
||||
param->nlist = nlist;
|
||||
return *this;
|
||||
}
|
||||
IVFIndexParamBuilder &WithNiters(int niters) {
|
||||
param->niters = niters;
|
||||
return *this;
|
||||
}
|
||||
IVFIndexParamBuilder &WithL1Index(const BaseIndexParam &l1Index) {
|
||||
param->l1Index = std::make_shared<BaseIndexParam>(l1Index);
|
||||
return *this;
|
||||
}
|
||||
IVFIndexParamBuilder &WithL2Index(const BaseIndexParam &l2Index) {
|
||||
param->l2Index = std::make_shared<BaseIndexParam>(l2Index);
|
||||
return *this;
|
||||
}
|
||||
IVFIndexParamBuilder &WithUseSoar(bool use_soar) {
|
||||
param->use_soar = use_soar;
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::shared_ptr<IVFIndexParam> Build() override {
|
||||
return param;
|
||||
}
|
||||
};
|
||||
|
||||
class HNSWIndexParamBuilder
|
||||
: public BaseIndexParamBuilder<HNSWIndexParamBuilder, HNSWIndexParam> {
|
||||
public:
|
||||
HNSWIndexParamBuilder() = default;
|
||||
HNSWIndexParamBuilder &WithM(int m) {
|
||||
param->m = m;
|
||||
return *this;
|
||||
}
|
||||
HNSWIndexParamBuilder &WithEFConstruction(int ef_construction) {
|
||||
param->ef_construction = ef_construction;
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::shared_ptr<HNSWIndexParam> Build() override {
|
||||
return param;
|
||||
}
|
||||
};
|
||||
|
||||
// class CompositeIndexParamBuilder : public
|
||||
// BaseIndexParamBuilder<CompositeIndexParamBuilder, CompositeIndexParam>
|
||||
// { public:
|
||||
// CompositeIndexParamBuilder() = default;
|
||||
// CompositeIndexParamBuilder &WithLayers(const
|
||||
// std::vector<std::shared_ptr<BaseIndexParam>> &layers) {
|
||||
// param.layers = layers;
|
||||
// return *this;
|
||||
// }
|
||||
// // with layer
|
||||
// CompositeIndexParamBuilder &WithLayer(const BaseIndexParam &layer)
|
||||
// {
|
||||
// param.layers.push_back(std::make_shared<BaseIndexParam>(layer));
|
||||
// return *this;
|
||||
// }
|
||||
|
||||
// CompositeIndexParamBuilder &WithLayer(const BaseIndexParam &layer,
|
||||
// const BaseIndexQueryParam
|
||||
// &default_query_param) {
|
||||
// param.layers.push_back(std::make_shared<BaseIndexParam>(layer));
|
||||
// param.layers.back()->default_query_param =
|
||||
// std::make_shared<BaseIndexQueryParam>(default_query_param);
|
||||
// return *this;
|
||||
// }
|
||||
// std::shared_ptr<CompositeIndexParam> Build() { return
|
||||
// std::make_shared<CompositeIndexParam>(param); }
|
||||
|
||||
// private:
|
||||
// CompositeIndexParam param;
|
||||
// };
|
||||
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
template <typename T, typename Derived>
|
||||
class BaseIndexQueryParamBuilder {
|
||||
public:
|
||||
// This allows derived builders to access the protected member
|
||||
T m_param;
|
||||
|
||||
// Fluent setters for BaseIndexQueryParam fields
|
||||
Derived &with_topk(int topk) {
|
||||
m_param.topk = topk;
|
||||
return static_cast<Derived &>(*this);
|
||||
}
|
||||
|
||||
Derived &with_fetch_vector(bool fetch_vector) {
|
||||
m_param.fetch_vector = fetch_vector;
|
||||
return static_cast<Derived &>(*this);
|
||||
}
|
||||
|
||||
Derived &with_filter(std::shared_ptr<IndexFilter> filter) {
|
||||
m_param.filter = std::move(filter);
|
||||
return static_cast<Derived &>(*this);
|
||||
}
|
||||
|
||||
// Using a vector of uint64_t for the next one
|
||||
Derived &with_bf_pks(std::shared_ptr<std::vector<uint64_t>> bf_pks) {
|
||||
m_param.bf_pks = std::move(bf_pks);
|
||||
return static_cast<Derived &>(*this);
|
||||
}
|
||||
|
||||
Derived &with_radius(float radius) {
|
||||
m_param.radius = radius;
|
||||
return static_cast<Derived &>(*this);
|
||||
}
|
||||
|
||||
Derived &with_is_linear(bool is_linear) {
|
||||
m_param.is_linear = is_linear;
|
||||
return static_cast<Derived &>(*this);
|
||||
}
|
||||
|
||||
Derived &with_refiner_param(RefinerParam::Pointer refiner_param) {
|
||||
m_param.refiner_param = std::move(refiner_param);
|
||||
return static_cast<Derived &>(*this);
|
||||
}
|
||||
};
|
||||
|
||||
// FLAT builder (no extra fields, just inherits base functionality)
|
||||
class FlatQueryParamBuilder
|
||||
: public BaseIndexQueryParamBuilder<FlatQueryParam, FlatQueryParamBuilder> {
|
||||
public:
|
||||
FlatQueryParam::Pointer build() {
|
||||
return std::make_shared<FlatQueryParam>(std::move(m_param));
|
||||
}
|
||||
};
|
||||
|
||||
// Example Usage:
|
||||
// FlatQueryParam::Pointer flat_config = FlatQueryParamBuilder()
|
||||
// .with_topk(20)
|
||||
// .with_fetch_vector(true)
|
||||
// .build();
|
||||
|
||||
// HNSW builder (adds one specific field: ef_search)
|
||||
class HNSWQueryParamBuilder
|
||||
: public BaseIndexQueryParamBuilder<HNSWQueryParam, HNSWQueryParamBuilder> {
|
||||
public:
|
||||
HNSWQueryParamBuilder &with_ef_search(int ef_search) {
|
||||
m_param.ef_search = ef_search;
|
||||
return *this;
|
||||
}
|
||||
|
||||
HNSWQueryParam::Pointer build() {
|
||||
return std::make_shared<HNSWQueryParam>(std::move(m_param));
|
||||
}
|
||||
};
|
||||
|
||||
// Example Usage:
|
||||
// HNSWQueryParam::Pointer hnsw_config = HNSWQueryParamBuilder()
|
||||
// .with_topk(5)
|
||||
// .with_ef_search(128) // HNSW specific
|
||||
// .with_is_linear(false)
|
||||
// .build();
|
||||
|
||||
// IVF builder (adds specific fields: nprobe, l1QueryParam, l2QueryParam)
|
||||
class IVFQueryParamBuilder
|
||||
: public BaseIndexQueryParamBuilder<IVFQueryParam, IVFQueryParamBuilder> {
|
||||
public:
|
||||
IVFQueryParamBuilder &with_nprobe(int nprobe) {
|
||||
m_param.nprobe = nprobe;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Since l1QueryParam and l2QueryParam are shared_ptr to BaseIndexQueryParam,
|
||||
// they can accept ANY derived configuration object.
|
||||
IVFQueryParamBuilder &with_l1_query_param(
|
||||
BaseIndexQueryParam::Pointer l1QueryParam) {
|
||||
m_param.l1QueryParam = std::move(l1QueryParam);
|
||||
return *this;
|
||||
}
|
||||
|
||||
IVFQueryParamBuilder &with_l2_query_param(
|
||||
BaseIndexQueryParam::Pointer l2QueryParam) {
|
||||
m_param.l2QueryParam = std::move(l2QueryParam);
|
||||
return *this;
|
||||
}
|
||||
|
||||
IVFQueryParam::Pointer build() {
|
||||
return std::make_shared<IVFQueryParam>(std::move(m_param));
|
||||
}
|
||||
};
|
||||
|
||||
// Example Usage:
|
||||
// // First, build the required nested params
|
||||
// auto nested_hnsw = HNSWQueryParamBuilder().with_ef_search(64).build();
|
||||
//
|
||||
// // Then, build the IVF param
|
||||
// IVFQueryParam::Pointer ivf_config = IVFQueryParamBuilder()
|
||||
// .with_topk(10)
|
||||
// .with_nprobe(50) // IVF specific
|
||||
// .with_l1_query_param(nested_hnsw) // Set a nested config object
|
||||
// .build();
|
||||
|
||||
|
||||
namespace predefined {
|
||||
// some predefined index param builders, e.g., SCANN
|
||||
class SCANNIndexParamBuilder {
|
||||
public:
|
||||
// alias SCANNIIndexParam = xxxxx
|
||||
std::shared_ptr<IVFIndexParam> Build() {
|
||||
// SCANN
|
||||
auto param_ptr =
|
||||
IVFIndexParamBuilder()
|
||||
.WithNList(40000) // 10000000 -> 40000
|
||||
.WithUseSoar(
|
||||
true) // 由于1个数据点可能对应2个partition,因此140个点中可能有重复,需要去重(保留一个取均值)
|
||||
.WithQuantizerParam(QuantizerParam(QuantizerType::kQuickADC))
|
||||
// .WithDefaultQueryParam(
|
||||
// IVFQueryParamBuilder().with_topk(140).with_nprobe(68).build())
|
||||
// .WithRefinerParam(RefinerParam{
|
||||
// 10, // 140 -> 10
|
||||
// nullptr,
|
||||
// std::make_shared<QuantizerParam>(
|
||||
// QuantizerParam{QuantizerType::kFP16}),
|
||||
// })
|
||||
.WithL1Index(*(
|
||||
IVFIndexParamBuilder()
|
||||
.WithMetricType(
|
||||
MetricType::kInnerProduct) // Layer2 flat index
|
||||
.WithNList(700) // 40000 -> 700
|
||||
.WithQuantizerParam(
|
||||
QuantizerParam{QuantizerType::kQuickADC})
|
||||
// .WithDefaultQueryParam(IVFQueryParamBuilder()
|
||||
// .with_topk(68)
|
||||
// .with_nprobe(20)
|
||||
// .build())
|
||||
.WithL1Index(*(
|
||||
FlatIndexParamBuilder()
|
||||
.WithMetricType(MetricType::kL2sq)
|
||||
// implicit :
|
||||
// .WithDefaultQueryParam(FlatQueryParamBuilder().with_topk(20).build())
|
||||
.Build()))
|
||||
.Build()))
|
||||
.Build();
|
||||
|
||||
return param_ptr;
|
||||
}
|
||||
};
|
||||
} // namespace predefined
|
||||
} // namespace zvec::core_interface
|
||||
#endif // ZVEC_INDEX_PARAM_BUILDERS_H
|
||||
@@ -0,0 +1,74 @@
|
||||
// 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.
|
||||
//
|
||||
// Created by wangjianning.wjn on 8/28/25.
|
||||
//
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include "algorithm/flat/flat_utility.h"
|
||||
#include "interface/index.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
int FlatIndex::CreateAndInitStreamer(const BaseIndexParam ¶m) {
|
||||
param_ = dynamic_cast<const FlatIndexParam &>(param);
|
||||
|
||||
proxima_index_params_.set(core::FLAT_BUILDER_COLUMN_MAJOR_ORDER,
|
||||
param_.major_order == IndexMeta::MO_COLUMN);
|
||||
proxima_index_params_.set(core::FLAT_SEARCHER_USE_ID_MAP, param_.use_id_map);
|
||||
if (is_sparse_) {
|
||||
streamer_ = core::IndexFactory::CreateStreamer("FlatSparseStreamer");
|
||||
} else {
|
||||
streamer_ = core::IndexFactory::CreateStreamer("FlatStreamer");
|
||||
}
|
||||
|
||||
if (ailego_unlikely(!streamer_)) {
|
||||
LOG_ERROR("Failed to create streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (ailego_unlikely(
|
||||
streamer_->init(proxima_index_meta_, proxima_index_params_) != 0)) {
|
||||
LOG_ERROR("Failed to init streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int FlatIndex::_prepare_for_search(
|
||||
const VectorData & /*vector_data*/,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context) {
|
||||
auto flat_search_param =
|
||||
std::dynamic_pointer_cast<FlatQueryParam>(search_param);
|
||||
|
||||
if (ailego_unlikely(!flat_search_param)) {
|
||||
LOG_ERROR("Invalid search param type, expected FlatQueryParam");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
context->set_topk(flat_search_param->topk);
|
||||
context->set_fetch_vector(flat_search_param->fetch_vector);
|
||||
if (flat_search_param->filter) {
|
||||
context->set_filter(std::move(*flat_search_param->filter));
|
||||
}
|
||||
if (flat_search_param->radius > 0.0f) {
|
||||
context->set_threshold(flat_search_param->radius);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
@@ -0,0 +1,121 @@
|
||||
// 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 <memory>
|
||||
#include <string>
|
||||
#include "algorithm/hnsw/hnsw_params.h"
|
||||
#include "algorithm/hnsw_sparse/hnsw_sparse_params.h"
|
||||
#include "interface/index.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
int HNSWIndex::CreateAndInitStreamer(const BaseIndexParam ¶m) {
|
||||
param_ = dynamic_cast<const HNSWIndexParam &>(param);
|
||||
|
||||
// valid
|
||||
param_.ef_construction = std::max(1, std::min(2048, param_.ef_construction));
|
||||
param_.m = std::max(5, std::min(1024, param_.m));
|
||||
|
||||
if (is_sparse_) {
|
||||
proxima_index_params_.set(core::PARAM_HNSW_SPARSE_STREAMER_EFCONSTRUCTION,
|
||||
param_.ef_construction);
|
||||
proxima_index_params_.set(
|
||||
core::PARAM_HNSW_SPARSE_STREAMER_MAX_NEIGHBOR_COUNT, param_.m);
|
||||
|
||||
// TODO: add_vector_with_id & fetch_by_id don't rely on this param
|
||||
proxima_index_params_.set(
|
||||
core::PARAM_HNSW_SPARSE_STREAMER_GET_VECTOR_ENABLE, true);
|
||||
|
||||
// TODO: use index params' default query param here
|
||||
proxima_index_params_.set(core::PARAM_HNSW_SPARSE_STREAMER_EF,
|
||||
kDefaultHnswEfSearch);
|
||||
streamer_ = core::IndexFactory::CreateStreamer("HnswSparseStreamer");
|
||||
|
||||
} else {
|
||||
proxima_index_params_.set(core::PARAM_HNSW_STREAMER_EFCONSTRUCTION,
|
||||
param_.ef_construction);
|
||||
proxima_index_params_.set(core::PARAM_HNSW_STREAMER_MAX_NEIGHBOR_COUNT,
|
||||
param_.m);
|
||||
|
||||
// TODO: add_vector_with_id & fetch_by_id don't rely on this param
|
||||
proxima_index_params_.set(core::PARAM_HNSW_STREAMER_GET_VECTOR_ENABLE,
|
||||
true);
|
||||
|
||||
// TODO: use index params' default query param here
|
||||
proxima_index_params_.set(core::PARAM_HNSW_STREAMER_EF,
|
||||
kDefaultHnswEfSearch);
|
||||
proxima_index_params_.set(core::PARAM_HNSW_STREAMER_USE_ID_MAP,
|
||||
param_.use_id_map);
|
||||
streamer_ = core::IndexFactory::CreateStreamer("HnswStreamer");
|
||||
}
|
||||
|
||||
if (ailego_unlikely(!streamer_)) {
|
||||
LOG_ERROR("Failed to create streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (ailego_unlikely(
|
||||
streamer_->init(proxima_index_meta_, proxima_index_params_) != 0)) {
|
||||
LOG_ERROR("Failed to init streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int HNSWIndex::_prepare_for_search(
|
||||
const VectorData & /*vector_data*/,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context) {
|
||||
const auto &hnsw_search_param =
|
||||
std::dynamic_pointer_cast<HNSWQueryParam>(search_param);
|
||||
|
||||
if (ailego_unlikely(!hnsw_search_param)) {
|
||||
LOG_ERROR("Invalid search param type, expected HNSWQueryParam");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
if (0 >= hnsw_search_param->ef_search ||
|
||||
hnsw_search_param->ef_search > 2048) {
|
||||
LOG_ERROR(
|
||||
"ef_search must be greater than 0 and less than or equal to 2048.");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
|
||||
context->set_topk(hnsw_search_param->topk);
|
||||
context->set_fetch_vector(hnsw_search_param->fetch_vector);
|
||||
if (hnsw_search_param->filter) {
|
||||
context->set_filter(std::move(*hnsw_search_param->filter));
|
||||
}
|
||||
if (hnsw_search_param->radius > 0.0f) {
|
||||
context->set_threshold(hnsw_search_param->radius);
|
||||
}
|
||||
ailego::Params params;
|
||||
const int real_search_ef =
|
||||
std::max(1u, std::min(2048u, hnsw_search_param->ef_search));
|
||||
params.set(core::PARAM_HNSW_STREAMER_EF, real_search_ef);
|
||||
context->update(params);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int HNSWIndex::_get_coarse_search_topk(
|
||||
const BaseIndexQueryParam::Pointer &search_param) {
|
||||
const auto &hnsw_search_param =
|
||||
std::dynamic_pointer_cast<HNSWQueryParam>(search_param);
|
||||
|
||||
// scale_factor doesn't take effect for hnsw.
|
||||
auto ret = std::max(search_param->topk, hnsw_search_param->ef_search);
|
||||
return ret;
|
||||
}
|
||||
|
||||
} // namespace zvec::core_interface
|
||||
@@ -0,0 +1,292 @@
|
||||
// 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 <memory>
|
||||
#include <string>
|
||||
#include "algorithm/ivf/ivf_params.h"
|
||||
#include "interface/index.h"
|
||||
|
||||
namespace zvec::core_interface {
|
||||
|
||||
static constexpr uint64_t kInvalidKey = std::numeric_limits<uint64_t>::max();
|
||||
|
||||
int IVFIndex::CreateAndInitStreamer(const BaseIndexParam ¶m) {
|
||||
if (is_sparse_) {
|
||||
LOG_ERROR("IVF Index not support sparse vector");
|
||||
return core::IndexError_InvalidArgument;
|
||||
}
|
||||
|
||||
param_ = dynamic_cast<const IVFIndexParam &>(param);
|
||||
param_.nlist = std::max(1, std::min(1024, param_.nlist));
|
||||
param_.niters = std::max(1, std::min(1024, param_.niters));
|
||||
|
||||
proxima_index_params_.set(core::PARAM_IVF_BUILDER_CENTROID_COUNT,
|
||||
param_.nlist);
|
||||
|
||||
// TODO: add_vector_with_id & fetch_by_id don't rely on this param
|
||||
builder_ = core::IndexFactory::CreateBuilder("IVFBuilder");
|
||||
streamer_ = core::IndexFactory::CreateStreamer("IVFStreamer");
|
||||
|
||||
if (ailego_unlikely(!builder_)) {
|
||||
LOG_ERROR("Failed to create builder");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (ailego_unlikely(!streamer_)) {
|
||||
LOG_ERROR("Failed to create streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
IndexMeta real_meta;
|
||||
if (converter_) {
|
||||
real_meta = converter_->meta();
|
||||
} else {
|
||||
real_meta = proxima_index_meta_;
|
||||
}
|
||||
if (ailego_unlikely(builder_->init(real_meta, proxima_index_params_) != 0)) {
|
||||
LOG_ERROR("Failed to init builder");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (ailego_unlikely(streamer_->init(real_meta, proxima_index_params_) != 0)) {
|
||||
LOG_ERROR("Failed to init streamer");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int IVFIndex::Open(const std::string &file_path,
|
||||
StorageOptions storage_options) {
|
||||
ailego::Params storage_params;
|
||||
file_path_ = file_path;
|
||||
is_read_only_ = storage_options.read_only;
|
||||
switch (storage_options.type) {
|
||||
case StorageOptions::StorageType::kMMAP: {
|
||||
storage_ = core::IndexFactory::CreateStorage("MMapFileReadStorage");
|
||||
if (storage_ == nullptr) {
|
||||
LOG_ERROR("Failed to create MMapFileStorage");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
int ret = storage_->init(storage_params);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to init MMapFileStorage, path: %s, err: %s",
|
||||
file_path_.c_str(), core::IndexError::What(ret));
|
||||
return ret;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case StorageOptions::StorageType::kBufferPool: {
|
||||
storage_ = core::IndexFactory::CreateStorage("BufferStorage");
|
||||
if (storage_ == nullptr) {
|
||||
LOG_ERROR("Failed to create BufferStorage");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
int ret = storage_->init(storage_params);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to init BufferStorage, path: %s, err: %s",
|
||||
file_path_.c_str(), core::IndexError::What(ret));
|
||||
return ret;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
LOG_ERROR("Unsupported storage type");
|
||||
return core::IndexError_Unsupported;
|
||||
}
|
||||
}
|
||||
|
||||
if (is_read_only_ || !storage_options.create_new) {
|
||||
// read_options.create_new
|
||||
int ret = storage_->open(file_path_, false);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to open storage, path: %s, err: %s", file_path_.c_str(),
|
||||
core::IndexError::What(ret));
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (streamer_ == nullptr || streamer_->open(storage_) != 0) {
|
||||
LOG_ERROR("Failed to open streamer, path: %s", file_path_.c_str());
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
is_trained_ = true;
|
||||
}
|
||||
is_open_ = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int IVFIndex::GenerateHolder() {
|
||||
if (param_.data_type == DataType::DT_FP16) {
|
||||
auto holder =
|
||||
std::make_shared<zvec::core::MultiPassIndexHolder<DataType::DT_FP16>>(
|
||||
param_.dimension);
|
||||
for (auto doc : doc_cache_) {
|
||||
ailego::NumericalVector<uint16_t> vec(doc.second);
|
||||
if (doc.first == kInvalidKey) {
|
||||
continue;
|
||||
}
|
||||
if (!holder->emplace(doc.first, vec)) {
|
||||
LOG_ERROR("Failed to add vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
holder_ = holder;
|
||||
} else if (param_.data_type == DataType::DT_FP32) {
|
||||
auto holder =
|
||||
std::make_shared<zvec::core::MultiPassIndexHolder<DataType::DT_FP32>>(
|
||||
param_.dimension);
|
||||
for (auto doc : doc_cache_) {
|
||||
ailego::NumericalVector<float> vec(doc.second);
|
||||
if (doc.first == kInvalidKey) {
|
||||
continue;
|
||||
}
|
||||
if (!holder->emplace(doc.first, vec)) {
|
||||
LOG_ERROR("Failed to add vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
holder_ = holder;
|
||||
} else if (param_.data_type == DataType::DT_INT8) {
|
||||
auto holder =
|
||||
std::make_shared<zvec::core::MultiPassIndexHolder<DataType::DT_INT8>>(
|
||||
param_.dimension);
|
||||
for (auto doc : doc_cache_) {
|
||||
ailego::NumericalVector<uint8_t> vec(doc.second);
|
||||
if (doc.first == kInvalidKey) {
|
||||
continue;
|
||||
}
|
||||
if (!holder->emplace(doc.first, vec)) {
|
||||
LOG_ERROR("Failed to add vector");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
}
|
||||
holder_ = holder;
|
||||
} else {
|
||||
LOG_ERROR("data_type is not support");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (converter_) {
|
||||
core::IndexConverter::TrainAndTransform(converter_, holder_);
|
||||
holder_ = converter_->result();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int IVFIndex::Add(const VectorData &vector, uint32_t doc_id) {
|
||||
if (is_trained_) {
|
||||
LOG_ERROR("this IVF index is trained");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (!std::holds_alternative<DenseVector>(vector.vector)) {
|
||||
LOG_ERROR("Invalid vector data");
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
const DenseVector &dense_vector = std::get<DenseVector>(vector.vector);
|
||||
std::string out_vector_buffer = std::string(
|
||||
static_cast<const char *>(dense_vector.data),
|
||||
input_vector_meta_.dimension() * input_vector_meta_.unit_size());
|
||||
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
while (doc_cache_.size() <= doc_id) {
|
||||
std::string fake_data(
|
||||
input_vector_meta_.dimension() * input_vector_meta_.unit_size(), 0);
|
||||
doc_cache_.push_back(std::make_pair(kInvalidKey, fake_data));
|
||||
}
|
||||
doc_cache_[doc_id] = std::make_pair(doc_id, out_vector_buffer);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int IVFIndex::Train() {
|
||||
GenerateHolder();
|
||||
builder_->train(holder_);
|
||||
builder_->build(holder_);
|
||||
auto dumper = core::IndexFactory::CreateDumper("FileDumper");
|
||||
|
||||
dumper->create(file_path_);
|
||||
builder_->dump(dumper);
|
||||
dumper->close();
|
||||
int ret = storage_->open(file_path_, false);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to open storage, path: %s, err: %s", file_path_.c_str(),
|
||||
core::IndexError::What(ret));
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (streamer_ == nullptr || streamer_->open(storage_) != 0) {
|
||||
LOG_ERROR("Failed to open streamer, path: %s", file_path_.c_str());
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
is_trained_ = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int IVFIndex::_dense_fetch(const uint32_t doc_id,
|
||||
VectorDataBuffer *vector_data_buffer) {
|
||||
if (is_trained_) {
|
||||
return Index::_dense_fetch(doc_id, vector_data_buffer);
|
||||
} else {
|
||||
DenseVectorBuffer dense_vector_buffer;
|
||||
std::string &out_vector_buffer = dense_vector_buffer.data;
|
||||
out_vector_buffer = doc_cache_[doc_id].second;
|
||||
vector_data_buffer->vector_buffer = std::move(dense_vector_buffer);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int IVFIndex::_prepare_for_search(
|
||||
const VectorData & /*query*/,
|
||||
const BaseIndexQueryParam::Pointer &search_param,
|
||||
core::IndexContext::Pointer &context) {
|
||||
const auto &ivf_search_param =
|
||||
std::dynamic_pointer_cast<IVFQueryParam>(search_param);
|
||||
|
||||
context->set_topk(ivf_search_param->topk);
|
||||
context->set_fetch_vector(ivf_search_param->fetch_vector);
|
||||
if (ivf_search_param->filter) {
|
||||
context->set_filter(std::move(*ivf_search_param->filter));
|
||||
}
|
||||
if (ivf_search_param->radius > 0.0f) {
|
||||
context->set_threshold(ivf_search_param->radius);
|
||||
}
|
||||
|
||||
if (ivf_search_param->nprobe > 0) {
|
||||
// TODO: 1. sparse; 2. default ef
|
||||
ailego::Params params;
|
||||
// need fix
|
||||
params.set(core::PARAM_IVF_BUILDER_CENTROID_COUNT,
|
||||
ivf_search_param->nprobe);
|
||||
context->update(params);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int IVFIndex::Merge(const std::vector<Index::Pointer> &indexes,
|
||||
const IndexFilter &filter, const MergeOptions &options) {
|
||||
int pre_ret = Index::Merge(indexes, filter, options);
|
||||
if (pre_ret != 0) {
|
||||
return pre_ret;
|
||||
}
|
||||
auto dumper = core::IndexFactory::CreateDumper("FileDumper");
|
||||
|
||||
dumper->create(file_path_);
|
||||
builder_->dump(dumper);
|
||||
dumper->close();
|
||||
int ret = storage_->open(file_path_, false);
|
||||
if (ret != 0) {
|
||||
LOG_ERROR("Failed to open storage, path: %s, err: %s", file_path_.c_str(),
|
||||
core::IndexError::What(ret));
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
if (streamer_ == nullptr || streamer_->open(storage_) != 0) {
|
||||
LOG_ERROR("Failed to open streamer, path: %s", file_path_.c_str());
|
||||
return core::IndexError_Runtime;
|
||||
}
|
||||
is_trained_ = true;
|
||||
return 0;
|
||||
}
|
||||
} // namespace zvec::core_interface
|
||||
@@ -0,0 +1,103 @@
|
||||
// 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/encoding/json.h>
|
||||
#include <ailego/logger/logger.h>
|
||||
#include <magic_enum/magic_enum.hpp>
|
||||
|
||||
namespace zvec {
|
||||
namespace core_interface {
|
||||
template <typename EnumType>
|
||||
constexpr bool extract_enum_from_json(const ailego::JsonObject &json_obj,
|
||||
const char *key, EnumType &enum_value,
|
||||
ailego::JsonValue &tmp_json_value) {
|
||||
if (json_obj.has(key)) {
|
||||
if (json_obj.get(key, &tmp_json_value); tmp_json_value.is_string()) {
|
||||
auto optional_enum_value =
|
||||
magic_enum::enum_cast<EnumType>(tmp_json_value.as_stl_string());
|
||||
if (optional_enum_value.has_value()) {
|
||||
enum_value = optional_enum_value.value();
|
||||
} else {
|
||||
LOG_ERROR("Invalid enum value for key: %s, value: %s", key,
|
||||
tmp_json_value.as_c_string());
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
LOG_ERROR("Invalid json field type for key: %s", key);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
constexpr bool extract_value_from_json(const ailego::JsonObject &json_obj,
|
||||
const char *key, T &value,
|
||||
ailego::JsonValue &tmp_json_value) {
|
||||
if (json_obj.has(key)) {
|
||||
json_obj.get(key, &tmp_json_value);
|
||||
if constexpr (std::is_same_v<T, bool>) {
|
||||
if (tmp_json_value.is_boolean()) {
|
||||
value = tmp_json_value.as_bool();
|
||||
} else {
|
||||
LOG_ERROR("Invalid json field type for key: %s; expected: boolean",
|
||||
key);
|
||||
return false;
|
||||
}
|
||||
} else if constexpr (std::is_floating_point_v<T>) {
|
||||
if (tmp_json_value.is_float() || tmp_json_value.is_integer()) {
|
||||
value = static_cast<T>(tmp_json_value.as_float());
|
||||
} else {
|
||||
LOG_ERROR("Invalid json field type for key: %s; expected: float", key);
|
||||
return false;
|
||||
}
|
||||
} else if constexpr (std::is_integral_v<T>) {
|
||||
if (tmp_json_value.is_integer()) {
|
||||
value = static_cast<T>(tmp_json_value.as_integer());
|
||||
} else {
|
||||
LOG_ERROR("Invalid json field type for key: %s; expected: integer",
|
||||
key);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
abort();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#define DESERIALIZE_ENUM_FIELD(json_obj, field_name, EnumType) \
|
||||
{ \
|
||||
ailego::JsonValue tmp_json_value; \
|
||||
if (!extract_enum_from_json<EnumType>(json_obj, #field_name, field_name, \
|
||||
tmp_json_value)) { \
|
||||
LOG_ERROR("Error when deserialize json - field:%s", #field_name); \
|
||||
return false; \
|
||||
} \
|
||||
}
|
||||
|
||||
|
||||
#define DESERIALIZE_VALUE_FIELD(json_obj, field_name) \
|
||||
{ \
|
||||
ailego::JsonValue tmp_json_value; \
|
||||
if (!extract_value_from_json(json_obj, #field_name, field_name, \
|
||||
tmp_json_value)) { \
|
||||
LOG_ERROR("Error when deserialize json - field:%s", #field_name); \
|
||||
return false; \
|
||||
} \
|
||||
}
|
||||
} // namespace core_interface
|
||||
} // namespace zvec
|
||||
Reference in New Issue
Block a user