refactor: turbo quantizer (#546)
This commit is contained in:
@@ -12,8 +12,8 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
if(NOT DEFINED HOST_BUILD_DIR)
|
||||
set(HOST_BUILD_DIR "build")
|
||||
endif()
|
||||
|
||||
get_filename_component(ZVEC_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE)
|
||||
|
||||
set(ZVEC_INCLUDE_DIR ${ZVEC_ROOT_DIR}/src/include)
|
||||
set(ZVEC_LIB_DIR ${ZVEC_ROOT_DIR}/${HOST_BUILD_DIR}/lib)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <turbo/quantizer/quantizer.h>
|
||||
#include <zvec/core/framework/index_factory.h>
|
||||
|
||||
namespace zvec {
|
||||
@@ -257,5 +258,18 @@ std::vector<std::string> IndexFactory::AllRefiners(void) {
|
||||
return ailego::Factory<IndexRefiner>::Classes();
|
||||
}
|
||||
|
||||
std::shared_ptr<turbo::Quantizer> IndexFactory::CreateQuantizer(
|
||||
const std::string &name) {
|
||||
return ailego::Factory<zvec::turbo::Quantizer>::MakeShared(name.c_str());
|
||||
}
|
||||
|
||||
bool IndexFactory::HasQuantizer(const std::string &name) {
|
||||
return ailego::Factory<turbo::Quantizer>::Has(name.c_str());
|
||||
}
|
||||
|
||||
std::vector<std::string> IndexFactory::AllQuantizers(void) {
|
||||
return ailego::Factory<turbo::Quantizer>::Classes();
|
||||
}
|
||||
|
||||
} // namespace core
|
||||
} // namespace zvec
|
||||
|
||||
@@ -30,7 +30,8 @@ struct IndexMetaFormatHeader {
|
||||
uint32_t space_id;
|
||||
uint32_t attachment_offset;
|
||||
uint32_t attachment_size;
|
||||
uint8_t reserved_[4092];
|
||||
uint32_t extra_meta_size;
|
||||
uint8_t reserved_[4088];
|
||||
};
|
||||
|
||||
static_assert(sizeof(IndexMetaFormatHeader) % 32 == 0,
|
||||
@@ -47,6 +48,7 @@ void IndexMeta::serialize(std::string *out) const {
|
||||
format.dimension = dimension_;
|
||||
format.unit_size = unit_size_;
|
||||
format.space_id = space_id_;
|
||||
format.extra_meta_size = extra_meta_size_;
|
||||
|
||||
if (!metric_name_.empty()) {
|
||||
ailego::Params item;
|
||||
@@ -141,7 +143,9 @@ bool IndexMeta::deserialize(const void *data, size_t len) {
|
||||
data_type_ = static_cast<IndexMeta::DataType>(format->data_type);
|
||||
dimension_ = format->dimension;
|
||||
unit_size_ = format->unit_size;
|
||||
element_size_ = IndexMeta::ElementSizeof(data_type_, unit_size_, dimension_);
|
||||
extra_meta_size_ = format->extra_meta_size;
|
||||
element_size_ = IndexMeta::ElementSizeof(data_type_, unit_size_, dimension_) +
|
||||
extra_meta_size_;
|
||||
space_id_ = format->space_id;
|
||||
|
||||
// Read attachment
|
||||
|
||||
@@ -29,6 +29,12 @@
|
||||
#include <zvec/core/framework/index_streamer.h>
|
||||
#include <zvec/core/framework/index_trainer.h>
|
||||
|
||||
namespace zvec {
|
||||
namespace turbo {
|
||||
class Quantizer;
|
||||
} // namespace turbo
|
||||
} // namespace zvec
|
||||
|
||||
namespace zvec {
|
||||
namespace core {
|
||||
|
||||
@@ -167,6 +173,16 @@ struct IndexFactory {
|
||||
|
||||
//! Retrieve all refiner classes
|
||||
static std::vector<std::string> AllRefiners(void);
|
||||
|
||||
//! Create a quantizer by name
|
||||
static std::shared_ptr<zvec::turbo::Quantizer> CreateQuantizer(
|
||||
const std::string &name);
|
||||
|
||||
//! Test if the quantizer exists
|
||||
static bool HasQuantizer(const std::string &name);
|
||||
|
||||
//! Retrieve all quantizer classes
|
||||
static std::vector<std::string> AllQuantizers(void);
|
||||
};
|
||||
|
||||
//! Register Index Metric
|
||||
@@ -283,5 +299,13 @@ struct IndexFactory {
|
||||
#define INDEX_FACTORY_REGISTER_REFINER(__IMPL__, ...) \
|
||||
INDEX_FACTORY_REGISTER_REFINER_ALIAS(__IMPL__, __IMPL__, ##__VA_ARGS__)
|
||||
|
||||
//! Register Quantizer
|
||||
#define INDEX_FACTORY_REGISTER_QUANTIZER_ALIAS(__NAME__, __IMPL__, ...) \
|
||||
AILEGO_FACTORY_REGISTER(__NAME__, turbo::Quantizer, __IMPL__, ##__VA_ARGS__)
|
||||
|
||||
//! Register Quantizer
|
||||
#define INDEX_FACTORY_REGISTER_QUANTIZER(__IMPL__, ...) \
|
||||
INDEX_FACTORY_REGISTER_QUANTIZER_ALIAS(__IMPL__, __IMPL__, ##__VA_ARGS__)
|
||||
|
||||
} // namespace core
|
||||
} // namespace zvec
|
||||
|
||||
@@ -40,6 +40,7 @@ class IndexMeta {
|
||||
DT_BINARY64 = 8,
|
||||
};
|
||||
|
||||
|
||||
/*! Major Orders
|
||||
*/
|
||||
enum MajorOrder {
|
||||
@@ -77,6 +78,7 @@ class IndexMeta {
|
||||
dimension_(rhs.dimension_),
|
||||
unit_size_(rhs.unit_size_),
|
||||
element_size_(rhs.element_size_),
|
||||
extra_meta_size_(rhs.extra_meta_size_),
|
||||
space_id_(rhs.space_id_),
|
||||
metric_revision_(rhs.metric_revision_),
|
||||
converter_revision_(rhs.converter_revision_),
|
||||
@@ -112,6 +114,7 @@ class IndexMeta {
|
||||
dimension_(rhs.dimension_),
|
||||
unit_size_(rhs.unit_size_),
|
||||
element_size_(rhs.element_size_),
|
||||
extra_meta_size_(rhs.extra_meta_size_),
|
||||
space_id_(rhs.space_id_),
|
||||
metric_revision_(rhs.metric_revision_),
|
||||
converter_revision_(rhs.converter_revision_),
|
||||
@@ -173,6 +176,7 @@ class IndexMeta {
|
||||
searcher_params_ = std::move(rhs.searcher_params_);
|
||||
streamer_params_ = std::move(rhs.streamer_params_);
|
||||
attributes_ = std::move(rhs.attributes_);
|
||||
extra_meta_size_ = rhs.extra_meta_size_;
|
||||
|
||||
return *this;
|
||||
}
|
||||
@@ -211,6 +215,7 @@ class IndexMeta {
|
||||
searcher_params_ = std::move(rhs.searcher_params_);
|
||||
streamer_params_ = std::move(rhs.streamer_params_);
|
||||
attributes_ = std::move(rhs.attributes_);
|
||||
extra_meta_size_ = rhs.extra_meta_size_;
|
||||
|
||||
return *this;
|
||||
}
|
||||
@@ -249,6 +254,7 @@ class IndexMeta {
|
||||
searcher_params_.clear();
|
||||
streamer_params_.clear();
|
||||
attributes_.clear();
|
||||
extra_meta_size_ = 0;
|
||||
}
|
||||
|
||||
//! Retrieve major order information
|
||||
@@ -281,6 +287,11 @@ class IndexMeta {
|
||||
return element_size_;
|
||||
}
|
||||
|
||||
//! Retrieve extra meta size in bytes
|
||||
uint32_t extra_meta_size(void) const {
|
||||
return extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Retrieve space id
|
||||
uint64_t space_id(void) const {
|
||||
return space_id_;
|
||||
@@ -429,7 +440,8 @@ class IndexMeta {
|
||||
//! Set dimension of feature
|
||||
void set_dimension(uint32_t dim) {
|
||||
dimension_ = dim;
|
||||
element_size_ = IndexMeta::ElementSizeof(data_type_, unit_size_, dim);
|
||||
element_size_ = IndexMeta::ElementSizeof(data_type_, unit_size_, dim) +
|
||||
extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Set meta information of feature
|
||||
@@ -443,7 +455,7 @@ class IndexMeta {
|
||||
data_type_ = data_type;
|
||||
dimension_ = dim;
|
||||
unit_size_ = unit;
|
||||
element_size_ = ElementSizeof(data_type, unit, dim);
|
||||
element_size_ = ElementSizeof(data_type, unit, dim) + extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Set meta information of feature
|
||||
@@ -451,6 +463,13 @@ class IndexMeta {
|
||||
this->set_meta(data_type, UnitSizeof(data_type), dim);
|
||||
}
|
||||
|
||||
//! Set extra meta size
|
||||
void set_extra_meta_size(uint32_t size) {
|
||||
extra_meta_size_ = size;
|
||||
element_size_ =
|
||||
ElementSizeof(data_type_, unit_size_, dimension_) + extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Set information of metric
|
||||
template <typename TName, typename TParams>
|
||||
void set_metric(TName &&name, uint32_t rev, TParams &¶ms) {
|
||||
@@ -586,6 +605,7 @@ class IndexMeta {
|
||||
uint32_t dimension_{0};
|
||||
uint32_t unit_size_{0};
|
||||
uint32_t element_size_{0};
|
||||
uint32_t extra_meta_size_{0};
|
||||
uint64_t space_id_{0};
|
||||
uint32_t metric_revision_{0};
|
||||
uint32_t converter_revision_{0};
|
||||
@@ -632,6 +652,19 @@ class IndexQueryMeta {
|
||||
unit_size_(unit),
|
||||
element_size_(IndexMeta::ElementSizeof(data_type, unit, dim)) {}
|
||||
|
||||
//! Constructor
|
||||
IndexQueryMeta(IndexMeta::MetaType meta_type, IndexMeta::DataType data_type,
|
||||
uint32_t unit, uint32_t dim, uint32_t quantize_type,
|
||||
uint32_t extra_meta_size)
|
||||
: meta_type_(meta_type),
|
||||
data_type_(data_type),
|
||||
dimension_(dim),
|
||||
unit_size_(unit),
|
||||
quantize_type_(quantize_type),
|
||||
extra_meta_size_(extra_meta_size),
|
||||
element_size_(IndexMeta::ElementSizeof(data_type, unit, dim) +
|
||||
extra_meta_size_) {}
|
||||
|
||||
//! Constructor
|
||||
IndexQueryMeta(IndexMeta::DataType data_type, uint32_t dim)
|
||||
: IndexQueryMeta{IndexMeta::MetaType::MT_DENSE, data_type,
|
||||
@@ -673,10 +706,21 @@ class IndexQueryMeta {
|
||||
return element_size_;
|
||||
}
|
||||
|
||||
//! Retrieve quantize type
|
||||
uint32_t quantize_type(void) const {
|
||||
return quantize_type_;
|
||||
}
|
||||
|
||||
//! Retrieve extra meta size in bytes
|
||||
uint32_t extra_meta_size(void) const {
|
||||
return extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Set dimension of feature
|
||||
void set_dimension(uint32_t dim) {
|
||||
dimension_ = dim;
|
||||
element_size_ = IndexMeta::ElementSizeof(data_type_, unit_size_, dim);
|
||||
element_size_ = IndexMeta::ElementSizeof(data_type_, unit_size_, dim) +
|
||||
extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Set meta type
|
||||
@@ -689,12 +733,21 @@ class IndexQueryMeta {
|
||||
data_type_ = data_type;
|
||||
}
|
||||
|
||||
//! Set extra meta size
|
||||
void set_extra_meta_size(uint32_t size) {
|
||||
extra_meta_size_ = size;
|
||||
element_size_ =
|
||||
IndexMeta::ElementSizeof(data_type_, unit_size_, dimension_) +
|
||||
extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Set meta information of feature
|
||||
void set_meta(IndexMeta::DataType data_type, uint32_t unit, uint32_t dim) {
|
||||
data_type_ = data_type;
|
||||
dimension_ = dim;
|
||||
unit_size_ = unit;
|
||||
element_size_ = IndexMeta::ElementSizeof(data_type, unit, dim);
|
||||
element_size_ =
|
||||
IndexMeta::ElementSizeof(data_type, unit, dim) + extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Set meta information of feature
|
||||
@@ -702,11 +755,25 @@ class IndexQueryMeta {
|
||||
this->set_meta(data_type, IndexMeta::UnitSizeof(data_type), dim);
|
||||
}
|
||||
|
||||
//! Set meta information of feature with quantize type and extra meta size
|
||||
void set_meta(IndexMeta::DataType data_type, uint32_t dim,
|
||||
uint32_t quantize_type, uint32_t extra_meta_size) {
|
||||
data_type_ = data_type;
|
||||
dimension_ = dim;
|
||||
unit_size_ = IndexMeta::UnitSizeof(data_type);
|
||||
quantize_type_ = quantize_type;
|
||||
extra_meta_size_ = extra_meta_size;
|
||||
element_size_ =
|
||||
IndexMeta::ElementSizeof(data_type, unit_size_, dim) + extra_meta_size_;
|
||||
}
|
||||
|
||||
private:
|
||||
IndexMeta::MetaType meta_type_{IndexMeta::MetaType::MT_DENSE};
|
||||
IndexMeta::DataType data_type_{IndexMeta::DataType::DT_UNDEFINED};
|
||||
uint32_t dimension_{0};
|
||||
uint32_t unit_size_{0};
|
||||
uint32_t quantize_type_{0};
|
||||
uint32_t extra_meta_size_{0};
|
||||
uint32_t element_size_{0};
|
||||
};
|
||||
|
||||
|
||||
@@ -36,30 +36,56 @@ using UniformQuantizeFunc = void (*)(const float *in, size_t dim, float scale,
|
||||
enum class MetricType {
|
||||
kSquaredEuclidean,
|
||||
kCosine,
|
||||
kInnerProduct,
|
||||
kMipsSquaredEuclidean,
|
||||
kUnknown,
|
||||
};
|
||||
|
||||
enum class DataType {
|
||||
kInt4,
|
||||
kInt8,
|
||||
kFp16,
|
||||
kFp32,
|
||||
kUnknown,
|
||||
};
|
||||
|
||||
enum class QuantizeType {
|
||||
kDefault,
|
||||
kUniform,
|
||||
kRecord,
|
||||
kFp16,
|
||||
kFp32,
|
||||
kPQ,
|
||||
kRabit
|
||||
};
|
||||
|
||||
enum class CpuArchType {
|
||||
kAuto,
|
||||
kScalar,
|
||||
// x86 SIMD
|
||||
kSSE,
|
||||
kAVX,
|
||||
kAVX2,
|
||||
kAVX512,
|
||||
kAVX512VNNI,
|
||||
kAVX512FP16,
|
||||
// ARM SIMD
|
||||
kNEON,
|
||||
kSVE,
|
||||
kSVE2
|
||||
};
|
||||
|
||||
DistanceFunc get_distance_func(MetricType metric_type, DataType data_type,
|
||||
QuantizeType quantize_type);
|
||||
QuantizeType quantize_type,
|
||||
CpuArchType cpu_arch_type = CpuArchType::kAuto);
|
||||
|
||||
BatchDistanceFunc get_batch_distance_func(MetricType metric_type,
|
||||
DataType data_type,
|
||||
QuantizeType quantize_type);
|
||||
BatchDistanceFunc get_batch_distance_func(
|
||||
MetricType metric_type, DataType data_type, QuantizeType quantize_type,
|
||||
CpuArchType cpu_arch_type = CpuArchType::kAuto);
|
||||
|
||||
QueryPreprocessFunc get_query_preprocess_func(MetricType metric_type,
|
||||
DataType data_type,
|
||||
QuantizeType quantize_type);
|
||||
QueryPreprocessFunc get_query_preprocess_func(
|
||||
MetricType metric_type, DataType data_type, QuantizeType quantize_type,
|
||||
CpuArchType cpu_arch_type = CpuArchType::kAuto);
|
||||
|
||||
// Returns the SIMD kernel for the uniform quantizer on the current CPU for
|
||||
// the given output data_type, or nullptr if no SIMD implementation is
|
||||
|
||||
@@ -19,7 +19,7 @@ file(GLOB_RECURSE ALL_SRCS *.cc *.c *.h)
|
||||
# subdirectory).
|
||||
if(NOT ANDROID AND AUTO_DETECT_ARCH)
|
||||
if (HOST_ARCH MATCHES "^(x86|x64)$")
|
||||
file(GLOB_RECURSE AVX512_VNNI_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/avx512_vnni/*.cc)
|
||||
file(GLOB_RECURSE AVX512_VNNI_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/distance/avx512_vnni/*.cc)
|
||||
set_source_files_properties(
|
||||
${AVX512_VNNI_SRCS}
|
||||
PROPERTIES
|
||||
@@ -29,8 +29,8 @@ if(NOT ANDROID AND AUTO_DETECT_ARCH)
|
||||
endif()
|
||||
|
||||
cc_library(
|
||||
NAME zvec_turbo STATIC STRICT PACKED
|
||||
NAME zvec_turbo STATIC STRICT ALWAYS_LINK PACKED
|
||||
SRCS ${ALL_SRCS}
|
||||
LIBS zvec_ailego
|
||||
INCS ${CMAKE_CURRENT_SOURCE_DIR} ${PROJECT_ROOT_DIR}/src/include
|
||||
INCS ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/distance ${PROJECT_ROOT_DIR}/src/include
|
||||
)
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// 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 "scalar/fp32/cosine.h"
|
||||
#include "scalar/fp32/inner_product.h"
|
||||
|
||||
namespace zvec::turbo::scalar {
|
||||
|
||||
void cosine_fp32_distance(const void *a, const void *b, size_t dim,
|
||||
float *distance) {
|
||||
// inner_product_fp32_distance returns -real_IP; cosine = 1 - real_IP = 1 +
|
||||
// ip.
|
||||
float ip;
|
||||
inner_product_fp32_distance(a, b, dim, &ip);
|
||||
|
||||
*distance = 1 + ip;
|
||||
}
|
||||
|
||||
void cosine_fp32_batch_distance(const void *const *vectors, const void *query,
|
||||
size_t n, size_t dim, float *distances) {
|
||||
inner_product_fp32_batch_distance(vectors, query, n, dim, distances);
|
||||
// inner_product batch returns -real_IP per element; cosine = 1 - real_IP = 1
|
||||
// + d.
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
distances[i] = 1 + distances[i];
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec::turbo::scalar
|
||||
@@ -0,0 +1,30 @@
|
||||
// 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 <cstddef>
|
||||
|
||||
namespace zvec::turbo::scalar {
|
||||
|
||||
// Compute cosine distance (negative inner product after normalization) between
|
||||
// a single quantized FP32 vector pair.
|
||||
void cosine_fp32_distance(const void *a, const void *b, size_t dim,
|
||||
float *distance);
|
||||
|
||||
// Batch version of cosine_fp32_distance.
|
||||
void cosine_fp32_batch_distance(const void *const *vectors, const void *query,
|
||||
size_t n, size_t dim, float *distances);
|
||||
|
||||
} // namespace zvec::turbo::scalar
|
||||
@@ -0,0 +1,43 @@
|
||||
// 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 "scalar/fp32/inner_product.h"
|
||||
|
||||
namespace zvec::turbo::scalar {
|
||||
|
||||
// Compute negated inner product between a single FP32 vector pair.
|
||||
// Returns -dot(a, b) so that callers can derive cosine distance as 1 + ip.
|
||||
void inner_product_fp32_distance(const void *a, const void *b, size_t dim,
|
||||
float *distance) {
|
||||
const float *m = reinterpret_cast<const float *>(a);
|
||||
const float *q = reinterpret_cast<const float *>(b);
|
||||
|
||||
float sum = 0.0;
|
||||
for (size_t i = 0; i < dim; ++i) {
|
||||
sum += static_cast<float>(m[i] * q[i]);
|
||||
}
|
||||
|
||||
*distance = -sum;
|
||||
}
|
||||
|
||||
// Batch version of inner_product_fp32_distance.
|
||||
void inner_product_fp32_batch_distance(const void *const *vectors,
|
||||
const void *query, size_t n, size_t dim,
|
||||
float *distances) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
inner_product_fp32_distance(vectors[i], query, dim, &distances[i]);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec::turbo::scalar
|
||||
@@ -0,0 +1,31 @@
|
||||
// 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 <cstddef>
|
||||
|
||||
namespace zvec::turbo::scalar {
|
||||
|
||||
// Compute inner product distance between a single quantized FP32
|
||||
// vector pair.
|
||||
void inner_product_fp32_distance(const void *a, const void *b, size_t dim,
|
||||
float *distance);
|
||||
|
||||
// Batch version of inner_product_fp32_distance.
|
||||
void inner_product_fp32_batch_distance(const void *const *vectors,
|
||||
const void *query, size_t n, size_t dim,
|
||||
float *distances);
|
||||
|
||||
} // namespace zvec::turbo::scalar
|
||||
@@ -0,0 +1,41 @@
|
||||
// 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 "scalar/fp32/squared_euclidean.h"
|
||||
#include <ailego/utility/math_helper.h>
|
||||
|
||||
namespace zvec::turbo::scalar {
|
||||
|
||||
void squared_euclidean_fp32_distance(const void *a, const void *b, size_t dim,
|
||||
float *distance) {
|
||||
const float *m = reinterpret_cast<const float *>(a);
|
||||
const float *q = reinterpret_cast<const float *>(b);
|
||||
|
||||
float sum = 0.0;
|
||||
for (size_t i = 0; i < dim; ++i) {
|
||||
sum += zvec::ailego::MathHelper::SquaredDifference(m[i], q[i]);
|
||||
}
|
||||
|
||||
*distance = sum;
|
||||
}
|
||||
|
||||
void squared_euclidean_fp32_batch_distance(const void *const *vectors,
|
||||
const void *query, size_t n,
|
||||
size_t dim, float *distances) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
squared_euclidean_fp32_distance(vectors[i], query, dim, &distances[i]);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace zvec::turbo::scalar
|
||||
@@ -0,0 +1,31 @@
|
||||
// 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 <cstddef>
|
||||
|
||||
namespace zvec::turbo::scalar {
|
||||
|
||||
// Compute squared euclidean distance between a single quantized FP32
|
||||
// vector pair.
|
||||
void squared_euclidean_fp32_distance(const void *a, const void *b, size_t dim,
|
||||
float *distance);
|
||||
|
||||
// Batch version of squared euclidean FP32.
|
||||
void squared_euclidean_fp32_batch_distance(const void *const *vectors,
|
||||
const void *query, size_t n,
|
||||
size_t dim, float *distances);
|
||||
|
||||
} // namespace zvec::turbo::scalar
|
||||
@@ -0,0 +1,107 @@
|
||||
// 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 <cstddef>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <zvec/turbo/turbo.h>
|
||||
|
||||
namespace zvec {
|
||||
namespace turbo {
|
||||
|
||||
//! A callable distance handle bound to a quantized query vector.
|
||||
//!
|
||||
//! DistanceImpl owns the quantized query bytes and a dispatched
|
||||
//! DistanceFunc. Invoking `operator()(candidate)` computes the distance
|
||||
//! between the stored query and the given candidate vector, which is
|
||||
//! expected to already be in the same quantized layout.
|
||||
class DistanceImpl {
|
||||
public:
|
||||
DistanceImpl() = default;
|
||||
|
||||
DistanceImpl(DistanceFunc func, std::string quantized_query, size_t dim)
|
||||
: func_(std::move(func)),
|
||||
query_storage_(std::move(quantized_query)),
|
||||
dim_(dim) {}
|
||||
|
||||
DistanceImpl(DistanceFunc func, BatchDistanceFunc batch_func,
|
||||
std::string quantized_query, size_t dim)
|
||||
: func_(std::move(func)),
|
||||
batch_func_(std::move(batch_func)),
|
||||
query_storage_(std::move(quantized_query)),
|
||||
dim_(dim) {}
|
||||
|
||||
//! Whether the handle is ready to compute distances.
|
||||
bool valid() const {
|
||||
return static_cast<bool>(func_);
|
||||
}
|
||||
|
||||
//! Whether a batch distance function is available.
|
||||
bool batch_valid() const {
|
||||
return static_cast<bool>(batch_func_);
|
||||
}
|
||||
|
||||
//! Compute the distance between the stored query and `candidate`.
|
||||
float operator()(const void *candidate) const {
|
||||
float d = 0.0f;
|
||||
func_(candidate, query_storage_.data(), dim_, &d);
|
||||
return d;
|
||||
}
|
||||
|
||||
//! Compute distances for a batch of `num` candidates against the
|
||||
//! stored query. Falls back to the scalar path when no batch function
|
||||
//! is bound.
|
||||
void batch(const void **candidates, size_t num, float *out) const {
|
||||
if (batch_func_) {
|
||||
batch_func_(candidates, query_storage_.data(), num, dim_, out);
|
||||
return;
|
||||
}
|
||||
for (size_t i = 0; i < num; ++i) {
|
||||
out[i] = 0.0f;
|
||||
func_(candidates[i], query_storage_.data(), dim_, out + i);
|
||||
}
|
||||
}
|
||||
|
||||
//! Access the quantized query bytes (for pairwise helpers).
|
||||
const std::string &query_storage() const {
|
||||
return query_storage_;
|
||||
}
|
||||
|
||||
size_t dim() const {
|
||||
return dim_;
|
||||
}
|
||||
|
||||
//! Raw scalar distance function (operates on already-quantized
|
||||
//! candidates). Useful for pairwise node-vs-node distance where no
|
||||
//! stored query is involved.
|
||||
const DistanceFunc &func() const {
|
||||
return func_;
|
||||
}
|
||||
|
||||
//! Raw batch distance function.
|
||||
const BatchDistanceFunc &batch_func() const {
|
||||
return batch_func_;
|
||||
}
|
||||
|
||||
private:
|
||||
DistanceFunc func_{};
|
||||
BatchDistanceFunc batch_func_{};
|
||||
std::string query_storage_{};
|
||||
size_t dim_{0};
|
||||
};
|
||||
|
||||
} // namespace turbo
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,192 @@
|
||||
// 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 "quantizer/fp32_quantizer/fp32_quantizer.h"
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <ailego/math/normalizer.h>
|
||||
#include <zvec/core/framework/index_factory.h>
|
||||
#include <zvec/core/framework/index_logger.h>
|
||||
#include "core/quantizer/record_quantizer.h"
|
||||
|
||||
namespace zvec {
|
||||
namespace turbo {
|
||||
|
||||
int Fp32Quantizer::init(const IndexMeta &meta,
|
||||
const ailego::Params & /*params*/) {
|
||||
meta_ = meta;
|
||||
|
||||
meta_.set_meta(IndexMeta::DataType::DT_FP32, meta.dimension());
|
||||
|
||||
|
||||
original_dim_ = meta.dimension();
|
||||
auto metric_name = meta.metric_name();
|
||||
if (metric_name == "Cosine") {
|
||||
extra_meta_size_ = EXTRA_META_SIZE_COSINE;
|
||||
meta_.set_extra_meta_size(extra_meta_size_);
|
||||
}
|
||||
|
||||
// Cache the distance dispatch for the new Quantizer interface.
|
||||
dp_query_func_ =
|
||||
get_distance_func(metric_from_name(metric_name), DataType::kFp32,
|
||||
QuantizeType::kDefault, CpuArchType::kAuto);
|
||||
dp_query_batch_func_ =
|
||||
get_batch_distance_func(metric_from_name(metric_name), DataType::kFp32,
|
||||
QuantizeType::kDefault, CpuArchType::kAuto);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Fp32Quantizer::quantize(const void *query, const IndexQueryMeta &qmeta,
|
||||
std::string *out, IndexQueryMeta *ometa) const {
|
||||
if (qmeta.unit_size() != sizeof(float)) {
|
||||
return kErrUnsupported;
|
||||
}
|
||||
|
||||
// qmeta.dimension() may be the inflated (data + extras) dimension when the
|
||||
// caller uses meta_.dimension() directly (e.g. HnswDistCalculator). Use the
|
||||
// raw original dim we recorded at init() to avoid over-reading the query.
|
||||
size_t raw_dim = (original_dim_ != 0 && qmeta.dimension() >= original_dim_)
|
||||
? original_dim_
|
||||
: qmeta.dimension();
|
||||
size_t byte_size = raw_dim * sizeof(float) + extra_meta_size_;
|
||||
out->resize(byte_size);
|
||||
|
||||
if (meta_.metric_name() == "Cosine") {
|
||||
// L2-normalize the vector in-place and store the norm at the end so the
|
||||
// original vector can be reconstructed during dequantize.
|
||||
float *buf = reinterpret_cast<float *>(&(*out)[0]);
|
||||
std::memcpy(buf, query, raw_dim * sizeof(float));
|
||||
float norm = 0.0f;
|
||||
ailego::Normalizer<float>::L2(buf, raw_dim, &norm);
|
||||
std::memcpy(
|
||||
reinterpret_cast<uint8_t *>(&(*out)[0]) + raw_dim * sizeof(float),
|
||||
&norm, extra_meta_size_);
|
||||
} else {
|
||||
std::memcpy(&(*out)[0], query, byte_size);
|
||||
}
|
||||
|
||||
*ometa = qmeta;
|
||||
ometa->set_meta(IndexMeta::DataType::DT_FP32, raw_dim,
|
||||
static_cast<uint32_t>(type_), extra_meta_size_);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int Fp32Quantizer::dequantize(const void *in, const IndexQueryMeta &qmeta,
|
||||
std::string *out) const {
|
||||
size_t raw_dim = (original_dim_ != 0 && qmeta.dimension() >= original_dim_)
|
||||
? original_dim_
|
||||
: qmeta.dimension();
|
||||
size_t byte_size = raw_dim * sizeof(float);
|
||||
|
||||
if (meta_.metric_name() == "Cosine") {
|
||||
// Denormalize the vector using the stored norm.
|
||||
out->resize(byte_size);
|
||||
const float *in_buf = reinterpret_cast<const float *>(in);
|
||||
float *out_buf = reinterpret_cast<float *>(&(*out)[0]);
|
||||
float norm = 0.0f;
|
||||
std::memcpy(&norm, reinterpret_cast<const uint8_t *>(in) + byte_size,
|
||||
extra_meta_size_);
|
||||
for (size_t i = 0; i < raw_dim; ++i) {
|
||||
out_buf[i] = in_buf[i] * norm;
|
||||
}
|
||||
} else {
|
||||
out->resize(byte_size);
|
||||
std::memcpy(out->data(), in, byte_size);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
DistanceImpl Fp32Quantizer::distance(const void *query,
|
||||
const IndexQueryMeta &qmeta) const {
|
||||
auto metric = metric_from_name(meta_.metric_name());
|
||||
auto func = get_distance_func(metric, DataType::kFp32, QuantizeType::kDefault,
|
||||
CpuArchType::kAuto);
|
||||
if (!func) {
|
||||
return DistanceImpl{};
|
||||
}
|
||||
auto batch_func = get_batch_distance_func(
|
||||
metric, DataType::kFp32, QuantizeType::kDefault, CpuArchType::kAuto);
|
||||
|
||||
// The query is assumed to be already quantized — copy it directly.
|
||||
std::string quantized_query(static_cast<const char *>(query),
|
||||
qmeta.element_size());
|
||||
return DistanceImpl(std::move(func), std::move(batch_func),
|
||||
std::move(quantized_query), original_dim_);
|
||||
}
|
||||
|
||||
void Fp32Quantizer::quantize_one(const void *input, void *output) const {
|
||||
size_t byte_size = static_cast<size_t>(original_dim_) * sizeof(float);
|
||||
|
||||
if (meta_.metric_name() == "Cosine") {
|
||||
// L2-normalize and store the norm at the end.
|
||||
std::memcpy(output, input, byte_size);
|
||||
float *buf = reinterpret_cast<float *>(output);
|
||||
float norm = 0.0f;
|
||||
ailego::Normalizer<float>::L2(buf, original_dim_, &norm);
|
||||
std::memcpy(reinterpret_cast<uint8_t *>(output) + byte_size, &norm,
|
||||
extra_meta_size_);
|
||||
} else {
|
||||
std::memcpy(output, input, byte_size);
|
||||
}
|
||||
}
|
||||
|
||||
float Fp32Quantizer::calc_distance_dp_query(const void *dp,
|
||||
const void *query) const {
|
||||
float d = 0.0f;
|
||||
if (dp_query_func_) {
|
||||
dp_query_func_(dp, query, original_dim_, &d);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
void Fp32Quantizer::calc_distance_dp_query_batch(const void *const *dp_list,
|
||||
int dp_num, const void *query,
|
||||
float *dist_list) const {
|
||||
if (dp_query_batch_func_) {
|
||||
dp_query_batch_func_(const_cast<const void **>(dp_list), query,
|
||||
static_cast<size_t>(dp_num), original_dim_, dist_list);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < dp_num; ++i) {
|
||||
dist_list[i] = calc_distance_dp_query(dp_list[i], query);
|
||||
}
|
||||
}
|
||||
|
||||
float Fp32Quantizer::calc_distance_dp_query_unquantized(
|
||||
const void *dp, const void *query) const {
|
||||
std::string buf(quantized_length(), '\0');
|
||||
quantize_one(query, &buf[0]);
|
||||
return calc_distance_dp_query(dp, buf.data());
|
||||
}
|
||||
|
||||
void Fp32Quantizer::calc_distance_dp_query_batch_unquantized(
|
||||
const void *const *dp_list, int dp_num, const void *query,
|
||||
float *dist_list) const {
|
||||
std::string buf(quantized_length(), '\0');
|
||||
quantize_one(query, &buf[0]);
|
||||
calc_distance_dp_query_batch(dp_list, dp_num, buf.data(), dist_list);
|
||||
}
|
||||
|
||||
float Fp32Quantizer::calc_distance_dp_dp(const void *dp1,
|
||||
const void *dp2) const {
|
||||
return calc_distance_dp_query(dp1, dp2);
|
||||
}
|
||||
|
||||
INDEX_FACTORY_REGISTER_QUANTIZER(Fp32Quantizer);
|
||||
|
||||
} // namespace turbo
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,127 @@
|
||||
// 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 <zvec/core/framework/index_holder.h>
|
||||
#include <zvec/core/framework/index_meta.h>
|
||||
#include <zvec/core/framework/index_reformer.h>
|
||||
#include <zvec/core/framework/index_stats.h>
|
||||
#include "quantizer/quantizer.h"
|
||||
|
||||
namespace zvec {
|
||||
namespace turbo {
|
||||
|
||||
using namespace zvec::core;
|
||||
|
||||
class Fp32Quantizer : public Quantizer {
|
||||
public:
|
||||
Fp32Quantizer() {
|
||||
type_ = QuantizeType::kFp32;
|
||||
}
|
||||
|
||||
virtual ~Fp32Quantizer() {}
|
||||
|
||||
public:
|
||||
int init(const core::IndexMeta &meta, const ailego::Params ¶ms) override;
|
||||
|
||||
const core::IndexMeta &meta(void) const override {
|
||||
return meta_;
|
||||
}
|
||||
|
||||
DataType input_data_type() const override {
|
||||
return DataType::kFp32;
|
||||
}
|
||||
|
||||
QuantizeType type() const override {
|
||||
return type_;
|
||||
}
|
||||
|
||||
int dim() const override {
|
||||
return static_cast<int>(original_dim_);
|
||||
}
|
||||
|
||||
bool require_train() const override {
|
||||
return false;
|
||||
}
|
||||
|
||||
int train(core::IndexHolder::Pointer /*holder*/) override {
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t quantized_datapoint_vector_length() const override {
|
||||
return quantized_length();
|
||||
}
|
||||
|
||||
size_t quantized_query_vector_length() const override {
|
||||
return quantized_length();
|
||||
}
|
||||
|
||||
void quantize_data(const void *input, void *output) const override {
|
||||
quantize_one(input, output);
|
||||
}
|
||||
|
||||
void quantize_query(const void *input, void *output) const override {
|
||||
quantize_one(input, output);
|
||||
}
|
||||
|
||||
float calc_distance_dp_query(const void *dp,
|
||||
const void *query) const override;
|
||||
|
||||
void calc_distance_dp_query_batch(const void *const *dp_list, int dp_num,
|
||||
const void *query,
|
||||
float *dist_list) const override;
|
||||
|
||||
float calc_distance_dp_query_unquantized(const void *dp,
|
||||
const void *query) const override;
|
||||
|
||||
void calc_distance_dp_query_batch_unquantized(
|
||||
const void *const *dp_list, int dp_num, const void *query,
|
||||
float *dist_list) const override;
|
||||
|
||||
float calc_distance_dp_dp(const void *dp1, const void *dp2) const override;
|
||||
|
||||
int quantize(const void *query, const core::IndexQueryMeta &qmeta,
|
||||
std::string *out, core::IndexQueryMeta *ometa) const override;
|
||||
|
||||
int dequantize(const void *in, const core::IndexQueryMeta &qmeta,
|
||||
std::string *out) const override;
|
||||
|
||||
DistanceImpl distance(const void *query,
|
||||
const core::IndexQueryMeta &qmeta) const override;
|
||||
|
||||
private:
|
||||
//! Byte length of a quantized vector (raw fp32 data + extra meta).
|
||||
size_t quantized_length() const {
|
||||
return static_cast<size_t>(original_dim_) * sizeof(float) +
|
||||
extra_meta_size_;
|
||||
}
|
||||
|
||||
//! Quantize a single fp32 vector into a caller-provided buffer of
|
||||
//! quantized_length() bytes.
|
||||
void quantize_one(const void *input, void *output) const;
|
||||
|
||||
static constexpr uint32_t EXTRA_META_SIZE_COSINE = 4;
|
||||
|
||||
IndexMeta meta_{};
|
||||
uint32_t original_dim_{0};
|
||||
|
||||
//! Cached distance dispatch (bound in init()).
|
||||
DistanceFunc dp_query_func_{};
|
||||
BatchDistanceFunc dp_query_batch_func_{};
|
||||
};
|
||||
|
||||
|
||||
} // namespace turbo
|
||||
} // namespace zvec
|
||||
@@ -0,0 +1,194 @@
|
||||
// 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 <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <zvec/ailego/container/params.h>
|
||||
#include <zvec/core/framework/index_holder.h>
|
||||
#include <zvec/core/framework/index_meta.h>
|
||||
#include <zvec/turbo/turbo.h>
|
||||
#include "distance.h"
|
||||
|
||||
namespace zvec {
|
||||
namespace turbo {
|
||||
|
||||
using namespace zvec::core;
|
||||
|
||||
//! Error code literals mirroring core::IndexError::Code integer values.
|
||||
//!
|
||||
//! Turbo quantizer sources use these directly instead of the
|
||||
//! `IndexError_NotImplemented` / `IndexError_Unsupported` const objects
|
||||
//! because MSVC's WINDOWS_EXPORT_ALL_SYMBOLS does not export const data
|
||||
//! with constructors from zvec_shared.dll. zvec_turbo is a static library
|
||||
//! linked with /WHOLEARCHIVE, so referencing those unexported symbols across
|
||||
//! the DLL boundary triggers LNK2019 on Windows.
|
||||
//!
|
||||
//! IndexError::Code stores -val in its constructor, so NotImplemented(11)
|
||||
//! yields -11 and Unsupported(12) yields -12.
|
||||
constexpr int kErrNotImplemented = -11;
|
||||
constexpr int kErrUnsupported = -12;
|
||||
|
||||
//! Magic number ('QTZR') stamped at the start of a serialized quantizer blob.
|
||||
constexpr uint32_t kQuantizerMagic = 0x52545A51u;
|
||||
|
||||
//! Current quantizer serialization format version.
|
||||
constexpr uint16_t kQuantizerSerVersion = 1;
|
||||
|
||||
//! Self-describing, fixed-size header that prefixes every serialized quantizer.
|
||||
//! The type-specific payload (scalar params, codebook, rotation matrix, ...)
|
||||
//! follows immediately after this header.
|
||||
struct QuantizerSerHeader {
|
||||
uint32_t magic; // kQuantizerMagic
|
||||
uint16_t version; // kQuantizerSerVersion
|
||||
uint16_t quant_type; // QuantizeType
|
||||
uint32_t dim; // original dim (sanity check)
|
||||
uint32_t metric; // MetricType (sanity check)
|
||||
uint32_t payload_size; // bytes following the header
|
||||
uint32_t reserved; // 0, for future use / alignment
|
||||
};
|
||||
static_assert(sizeof(QuantizerSerHeader) == 24,
|
||||
"QuantizerSerHeader must be 24 bytes");
|
||||
|
||||
class Quantizer {
|
||||
public:
|
||||
typedef std::shared_ptr<Quantizer> Pointer;
|
||||
|
||||
Quantizer() {}
|
||||
virtual ~Quantizer() {}
|
||||
|
||||
//! Initialize quantizer with index metadata and parameters
|
||||
virtual int init(const IndexMeta &meta, const ailego::Params ¶ms) = 0;
|
||||
|
||||
//! Get the output metadata after initialization
|
||||
virtual const IndexMeta &meta() const = 0;
|
||||
|
||||
//! Input data type accepted by the quantizer
|
||||
virtual DataType input_data_type() const = 0;
|
||||
|
||||
//! Data type
|
||||
virtual QuantizeType type() const {
|
||||
return type_;
|
||||
}
|
||||
|
||||
//! Dimensionality of the input vectors
|
||||
virtual int dim() const = 0;
|
||||
|
||||
//! Train the quantizer with a contiguous batch of data
|
||||
virtual int train(const void * /*data*/, size_t /*num*/, size_t /*stride*/) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Whether the quantizer requires training before use
|
||||
virtual bool require_train() const = 0;
|
||||
|
||||
//! Train the quantizer with data from an IndexHolder
|
||||
virtual int train(IndexHolder::Pointer /*holder*/) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Byte length of a quantized datapoint vector
|
||||
virtual size_t quantized_datapoint_vector_length() const = 0;
|
||||
|
||||
//! Byte length of a quantized query vector
|
||||
virtual size_t quantized_query_vector_length() const = 0;
|
||||
|
||||
//! Quantize a datapoint vector
|
||||
virtual void quantize_data(const void *input, void *output) const = 0;
|
||||
|
||||
//! Quantize a query vector
|
||||
virtual void quantize_query(const void *input, void *output) const = 0;
|
||||
|
||||
//! Distance between a quantized datapoint and a quantized query
|
||||
virtual float calc_distance_dp_query(const void *dp,
|
||||
const void *query) const = 0;
|
||||
|
||||
//! Batched distance between quantized datapoints and a quantized query
|
||||
virtual void calc_distance_dp_query_batch(const void *const *dp_list,
|
||||
int dp_num, const void *query,
|
||||
float *dist_list) const = 0;
|
||||
|
||||
//! Distance between a quantized datapoint and an unquantized query
|
||||
virtual float calc_distance_dp_query_unquantized(const void *dp,
|
||||
const void *query) const = 0;
|
||||
|
||||
//! Batched distance between quantized datapoints and an unquantized query
|
||||
virtual void calc_distance_dp_query_batch_unquantized(
|
||||
const void *const *dp_list, int dp_num, const void *query,
|
||||
float *dist_list) const = 0;
|
||||
|
||||
//! Distance between two quantized datapoints
|
||||
virtual float calc_distance_dp_dp(const void *dp1, const void *dp2) const = 0;
|
||||
|
||||
//! Quantize a query vector for search
|
||||
virtual int quantize(const void * /*query*/, const IndexQueryMeta & /*qmeta*/,
|
||||
std::string * /*out*/,
|
||||
IndexQueryMeta * /*ometa*/) const {
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Dequantize a result vector back to original format
|
||||
virtual int dequantize(const void * /*in*/, const IndexQueryMeta & /*qmeta*/,
|
||||
std::string * /*out*/) const {
|
||||
return 0;
|
||||
}
|
||||
|
||||
virtual DistanceImpl distance(const void * /*query*/,
|
||||
const IndexQueryMeta & /*qmeta*/) const {
|
||||
return DistanceImpl{};
|
||||
}
|
||||
|
||||
//! Serialize quantizer parameters
|
||||
virtual int serialize(std::string * /*out*/) const {
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Deserialize quantizer parameters
|
||||
virtual int deserialize(std::string & /*in*/) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Deserialize quantizer parameters from a raw, possibly mmap-backed buffer
|
||||
//! (zero-copy entry point for large payloads such as codebooks/matrices).
|
||||
virtual int deserialize(const void * /*data*/, size_t /*len*/) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected:
|
||||
//! Map a metric name (e.g. "SquaredEuclidean", "Cosine",
|
||||
//! "InnerProduct", "MipsSquaredEuclidean") to its MetricType.
|
||||
static MetricType metric_from_name(const std::string &name) {
|
||||
if (name == "SquaredEuclidean") {
|
||||
return MetricType::kSquaredEuclidean;
|
||||
}
|
||||
if (name == "Cosine") {
|
||||
return MetricType::kCosine;
|
||||
}
|
||||
if (name == "InnerProduct") {
|
||||
return MetricType::kInnerProduct;
|
||||
}
|
||||
if (name == "MipsSquaredEuclidean") {
|
||||
return MetricType::kMipsSquaredEuclidean;
|
||||
}
|
||||
return MetricType::kUnknown;
|
||||
}
|
||||
|
||||
QuantizeType type_{QuantizeType::kDefault};
|
||||
uint32_t extra_meta_size_{0};
|
||||
};
|
||||
|
||||
} // namespace turbo
|
||||
} // namespace zvec
|
||||
+55
-8
@@ -18,14 +18,35 @@
|
||||
#include "avx512_vnni/record_quantized_int8/squared_euclidean.h"
|
||||
#include "avx512_vnni/uniform_int8/quantize.h"
|
||||
#include "avx512_vnni/uniform_int8/squared_euclidean.h"
|
||||
#include "scalar/fp32/cosine.h"
|
||||
#include "scalar/fp32/inner_product.h"
|
||||
#include "scalar/fp32/squared_euclidean.h"
|
||||
|
||||
namespace zvec::turbo {
|
||||
|
||||
DistanceFunc get_distance_func(MetricType metric_type, DataType data_type,
|
||||
QuantizeType quantize_type) {
|
||||
QuantizeType quantize_type,
|
||||
CpuArchType cpu_arch_type) {
|
||||
if (data_type == DataType::kFp32) {
|
||||
if (quantize_type == QuantizeType::kDefault ||
|
||||
quantize_type == QuantizeType::kFp32) {
|
||||
if (metric_type == MetricType::kCosine) {
|
||||
return scalar::cosine_fp32_distance;
|
||||
}
|
||||
if (metric_type == MetricType::kSquaredEuclidean) {
|
||||
return scalar::squared_euclidean_fp32_distance;
|
||||
}
|
||||
if (metric_type == MetricType::kInnerProduct) {
|
||||
return scalar::inner_product_fp32_distance;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
if (data_type == DataType::kInt8) {
|
||||
if (quantize_type == QuantizeType::kDefault) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI &&
|
||||
(cpu_arch_type == CpuArchType::kAuto ||
|
||||
cpu_arch_type == CpuArchType::kAVX512VNNI)) {
|
||||
if (metric_type == MetricType::kSquaredEuclidean) {
|
||||
return avx512_vnni::squared_euclidean_int8_distance;
|
||||
}
|
||||
@@ -35,7 +56,9 @@ DistanceFunc get_distance_func(MetricType metric_type, DataType data_type,
|
||||
}
|
||||
}
|
||||
if (quantize_type == QuantizeType::kUniform) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI &&
|
||||
(cpu_arch_type == CpuArchType::kAuto ||
|
||||
cpu_arch_type == CpuArchType::kAVX512VNNI)) {
|
||||
if (metric_type == MetricType::kSquaredEuclidean) {
|
||||
return avx512_vnni::uniform_squared_euclidean_int8_distance;
|
||||
}
|
||||
@@ -47,10 +70,28 @@ DistanceFunc get_distance_func(MetricType metric_type, DataType data_type,
|
||||
|
||||
BatchDistanceFunc get_batch_distance_func(MetricType metric_type,
|
||||
DataType data_type,
|
||||
QuantizeType quantize_type) {
|
||||
QuantizeType quantize_type,
|
||||
CpuArchType cpu_arch_type) {
|
||||
if (data_type == DataType::kFp32) {
|
||||
if (quantize_type == QuantizeType::kDefault ||
|
||||
quantize_type == QuantizeType::kFp32) {
|
||||
if (metric_type == MetricType::kCosine) {
|
||||
return scalar::cosine_fp32_batch_distance;
|
||||
}
|
||||
if (metric_type == MetricType::kSquaredEuclidean) {
|
||||
return scalar::squared_euclidean_fp32_batch_distance;
|
||||
}
|
||||
if (metric_type == MetricType::kInnerProduct) {
|
||||
return scalar::inner_product_fp32_batch_distance;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
if (data_type == DataType::kInt8) {
|
||||
if (quantize_type == QuantizeType::kDefault) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI &&
|
||||
(cpu_arch_type == CpuArchType::kAuto ||
|
||||
cpu_arch_type == CpuArchType::kAVX512VNNI)) {
|
||||
if (metric_type == MetricType::kSquaredEuclidean) {
|
||||
return avx512_vnni::squared_euclidean_int8_batch_distance;
|
||||
}
|
||||
@@ -60,22 +101,28 @@ BatchDistanceFunc get_batch_distance_func(MetricType metric_type,
|
||||
}
|
||||
}
|
||||
if (quantize_type == QuantizeType::kUniform) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI &&
|
||||
(cpu_arch_type == CpuArchType::kAuto ||
|
||||
cpu_arch_type == CpuArchType::kAVX512VNNI)) {
|
||||
if (metric_type == MetricType::kSquaredEuclidean) {
|
||||
return avx512_vnni::uniform_squared_euclidean_int8_batch_distance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
QueryPreprocessFunc get_query_preprocess_func(MetricType metric_type,
|
||||
DataType data_type,
|
||||
QuantizeType quantize_type) {
|
||||
QuantizeType quantize_type,
|
||||
CpuArchType cpu_arch_type) {
|
||||
if (data_type == DataType::kInt8) {
|
||||
if (quantize_type == QuantizeType::kDefault) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI) {
|
||||
if (zvec::ailego::internal::CpuFeatures::static_flags_.AVX512_VNNI &&
|
||||
(cpu_arch_type == CpuArchType::kAuto ||
|
||||
cpu_arch_type == CpuArchType::kAVX512VNNI)) {
|
||||
if (metric_type == MetricType::kSquaredEuclidean) {
|
||||
return avx512_vnni::squared_euclidean_int8_query_preprocess;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ include_directories(${PROJECT_ROOT_DIR})
|
||||
cc_directories(ailego)
|
||||
cc_directories(db)
|
||||
cc_directories(core)
|
||||
cc_directories(turbo)
|
||||
if(BUILD_C_BINDINGS)
|
||||
cc_directories(c)
|
||||
endif()
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
include(${PROJECT_ROOT_DIR}/cmake/bazel.cmake)
|
||||
|
||||
file(GLOB_RECURSE ALL_TEST_SRCS *_test.cc)
|
||||
|
||||
foreach(CC_SRCS ${ALL_TEST_SRCS})
|
||||
get_filename_component(CC_TARGET ${CC_SRCS} NAME_WE)
|
||||
cc_gtest(
|
||||
NAME ${CC_TARGET}
|
||||
STRICT
|
||||
LIBS zvec_ailego core_framework core_metric core_quantizer zvec_turbo
|
||||
SRCS ${CC_SRCS}
|
||||
INCS . ${PROJECT_ROOT_DIR}/src/core/ ${PROJECT_ROOT_DIR}/src/turbo/
|
||||
)
|
||||
endforeach()
|
||||
@@ -0,0 +1,203 @@
|
||||
// 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 <cmath>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <gtest/gtest.h>
|
||||
#include <turbo/quantizer/quantizer.h>
|
||||
#include <zvec/ailego/container/params.h>
|
||||
#include <zvec/turbo/turbo.h>
|
||||
#include "zvec/core/framework/index_factory.h"
|
||||
|
||||
using namespace zvec;
|
||||
using namespace zvec::core;
|
||||
using namespace zvec::ailego;
|
||||
|
||||
// Helper: reference cosine distance between two raw fp32 vectors.
|
||||
static float reference_cosine(const float *a, const float *b, size_t dim) {
|
||||
float dot = 0.0f, na = 0.0f, nb = 0.0f;
|
||||
for (size_t i = 0; i < dim; ++i) {
|
||||
dot += a[i] * b[i];
|
||||
na += a[i] * a[i];
|
||||
nb += b[i] * b[i];
|
||||
}
|
||||
float denom = std::sqrt(na) * std::sqrt(nb);
|
||||
return (denom < 1e-12f) ? 1.0f : 1.0f - dot / denom;
|
||||
}
|
||||
|
||||
TEST(Fp32Quantizer, General) {
|
||||
std::mt19937 gen(15583);
|
||||
std::uniform_real_distribution<float> dist(0.0, 1.0);
|
||||
|
||||
const size_t COUNT = 10000;
|
||||
const size_t DIMENSION = 12;
|
||||
|
||||
IndexMeta meta;
|
||||
meta.set_meta(IndexMeta::DataType::DT_FP32, DIMENSION);
|
||||
meta.set_metric("Cosine", 0, Params());
|
||||
|
||||
auto quantizer = IndexFactory::CreateQuantizer("Fp32Quantizer");
|
||||
ASSERT_TRUE(quantizer);
|
||||
zvec::ailego::Params params;
|
||||
ASSERT_EQ(0u, quantizer->init(meta, params));
|
||||
|
||||
auto holder =
|
||||
std::make_shared<MultiPassIndexHolder<IndexMeta::DataType::DT_FP32>>(
|
||||
DIMENSION);
|
||||
for (size_t i = 0; i < COUNT; ++i) {
|
||||
zvec::ailego::NumericalVector<float> vec(DIMENSION);
|
||||
for (size_t j = 0; j < DIMENSION; ++j) {
|
||||
vec[j] = dist(gen);
|
||||
}
|
||||
holder->emplace(i + 1, vec);
|
||||
}
|
||||
EXPECT_EQ(COUNT, holder->count());
|
||||
EXPECT_EQ(IndexMeta::DataType::DT_FP32, holder->data_type());
|
||||
|
||||
ASSERT_EQ(0u, quantizer->train(holder));
|
||||
|
||||
auto iter = holder->create_iterator();
|
||||
std::string quant_buffer;
|
||||
std::string dequant_buffer;
|
||||
|
||||
for (; iter->is_valid(); iter->next()) {
|
||||
EXPECT_TRUE(iter->data());
|
||||
|
||||
IndexQueryMeta qmeta;
|
||||
quant_buffer.clear();
|
||||
EXPECT_EQ(0, quantizer->quantize(
|
||||
iter->data(),
|
||||
IndexQueryMeta(holder->data_type(), holder->dimension()),
|
||||
&quant_buffer, &qmeta));
|
||||
EXPECT_EQ(IndexMeta::DataType::DT_FP32, qmeta.data_type());
|
||||
EXPECT_EQ(holder->dimension(), qmeta.dimension());
|
||||
|
||||
dequant_buffer.clear();
|
||||
EXPECT_EQ(
|
||||
0, quantizer->dequantize(quant_buffer.data(), qmeta, &dequant_buffer));
|
||||
|
||||
const float *original_data = reinterpret_cast<const float *>(iter->data());
|
||||
const float *dequantize_data =
|
||||
reinterpret_cast<const float *>(dequant_buffer.data());
|
||||
for (size_t i = 0; i < holder->dimension(); ++i) {
|
||||
EXPECT_NEAR(original_data[i], dequantize_data[i], 1e-3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(Fp32Quantizer, Score) {
|
||||
std::mt19937 gen(42);
|
||||
std::uniform_real_distribution<float> dist(0.0, 1.0);
|
||||
|
||||
const size_t DIMENSION = 12;
|
||||
const size_t COUNT = 100;
|
||||
|
||||
IndexMeta meta;
|
||||
meta.set_meta(IndexMeta::DataType::DT_FP32, DIMENSION);
|
||||
meta.set_metric("Cosine", 0, Params());
|
||||
|
||||
auto quantizer = IndexFactory::CreateQuantizer("Fp32Quantizer");
|
||||
ASSERT_TRUE(quantizer);
|
||||
zvec::ailego::Params params;
|
||||
ASSERT_EQ(0u, quantizer->init(meta, params));
|
||||
|
||||
// Generate raw vectors and quantize them.
|
||||
std::vector<std::vector<float>> raw_vecs(COUNT);
|
||||
std::vector<std::string> quant_vecs(COUNT);
|
||||
for (size_t i = 0; i < COUNT; ++i) {
|
||||
raw_vecs[i].resize(DIMENSION);
|
||||
for (size_t j = 0; j < DIMENSION; ++j) {
|
||||
raw_vecs[i][j] = dist(gen);
|
||||
}
|
||||
IndexQueryMeta ometa;
|
||||
EXPECT_EQ(0, quantizer->quantize(
|
||||
raw_vecs[i].data(),
|
||||
IndexQueryMeta(IndexMeta::DataType::DT_FP32, DIMENSION),
|
||||
&quant_vecs[i], &ometa));
|
||||
}
|
||||
|
||||
// --- calc_distance_dp_query (single) ---
|
||||
for (size_t i = 1; i < COUNT; ++i) {
|
||||
float d = quantizer->calc_distance_dp_query(quant_vecs[i].data(),
|
||||
quant_vecs[0].data());
|
||||
float expected =
|
||||
reference_cosine(raw_vecs[i].data(), raw_vecs[0].data(), DIMENSION);
|
||||
EXPECT_NEAR(d, expected, 1e-4) << "i=" << i;
|
||||
}
|
||||
|
||||
// --- calc_distance_dp_query_batch ---
|
||||
{
|
||||
std::vector<const void *> dp_list(COUNT - 1);
|
||||
for (size_t i = 1; i < COUNT; ++i) {
|
||||
dp_list[i - 1] = quant_vecs[i].data();
|
||||
}
|
||||
std::vector<float> results(COUNT - 1);
|
||||
quantizer->calc_distance_dp_query_batch(
|
||||
dp_list.data(), static_cast<int>(dp_list.size()), quant_vecs[0].data(),
|
||||
results.data());
|
||||
|
||||
for (size_t i = 0; i < dp_list.size(); ++i) {
|
||||
float expected = reference_cosine(raw_vecs[i + 1].data(),
|
||||
raw_vecs[0].data(), DIMENSION);
|
||||
EXPECT_NEAR(results[i], expected, 1e-4) << "i=" << i;
|
||||
}
|
||||
}
|
||||
|
||||
// --- distance() + DistanceImpl (single + batch) ---
|
||||
{
|
||||
IndexQueryMeta qmeta(IndexMeta::DataType::DT_FP32, DIMENSION);
|
||||
auto dist_impl = quantizer->distance(quant_vecs[0].data(), qmeta);
|
||||
ASSERT_TRUE(dist_impl.valid());
|
||||
|
||||
for (size_t i = 1; i < COUNT; ++i) {
|
||||
float d = dist_impl(quant_vecs[i].data());
|
||||
float expected =
|
||||
reference_cosine(raw_vecs[0].data(), raw_vecs[i].data(), DIMENSION);
|
||||
EXPECT_NEAR(d, expected, 1e-4) << "i=" << i;
|
||||
}
|
||||
|
||||
// Batch via DistanceImpl.
|
||||
ASSERT_TRUE(dist_impl.batch_valid());
|
||||
std::vector<const void *> dp_list(COUNT - 1);
|
||||
for (size_t i = 1; i < COUNT; ++i) {
|
||||
dp_list[i - 1] = quant_vecs[i].data();
|
||||
}
|
||||
std::vector<float> batch_results(COUNT - 1);
|
||||
dist_impl.batch(dp_list.data(), dp_list.size(), batch_results.data());
|
||||
for (size_t i = 0; i < dp_list.size(); ++i) {
|
||||
float expected = reference_cosine(raw_vecs[0].data(),
|
||||
raw_vecs[i + 1].data(), DIMENSION);
|
||||
EXPECT_NEAR(batch_results[i], expected, 1e-4) << "i=" << i;
|
||||
}
|
||||
}
|
||||
|
||||
// --- calc_distance_dp_dp (pairwise) ---
|
||||
for (size_t i = 1; i < 10; ++i) {
|
||||
float d = quantizer->calc_distance_dp_dp(quant_vecs[i].data(),
|
||||
quant_vecs[0].data());
|
||||
float expected =
|
||||
reference_cosine(raw_vecs[i].data(), raw_vecs[0].data(), DIMENSION);
|
||||
EXPECT_NEAR(d, expected, 1e-4) << "i=" << i;
|
||||
}
|
||||
|
||||
// --- calc_distance_dp_query_unquantized ---
|
||||
for (size_t i = 1; i < 10; ++i) {
|
||||
float d = quantizer->calc_distance_dp_query_unquantized(
|
||||
quant_vecs[i].data(), raw_vecs[0].data());
|
||||
float expected =
|
||||
reference_cosine(raw_vecs[i].data(), raw_vecs[0].data(), DIMENSION);
|
||||
EXPECT_NEAR(d, expected, 1e-4) << "i=" << i;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user