feat: add diskann index (#369)
This commit is contained in:
@@ -83,6 +83,11 @@ set_target_properties(zvec_c_api PROPERTIES
|
||||
VISIBILITY_INLINES_HIDDEN ON
|
||||
)
|
||||
|
||||
# On Windows, define ZVEC_BUILD_SHARED so that c_api.h uses __declspec(dllexport)
|
||||
if(MSVC OR WIN32)
|
||||
target_compile_definitions(zvec_c_api PRIVATE ZVEC_BUILD_SHARED)
|
||||
endif()
|
||||
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
# Static linking of C++ standard library is handled in platform-specific sections
|
||||
|
||||
@@ -19,6 +19,33 @@ set(SRC_LISTS
|
||||
|
||||
pybind11_add_module(_zvec ${SRC_LISTS})
|
||||
|
||||
# pybind11_add_module() defaults to CXX_VISIBILITY_PRESET=hidden +
|
||||
# VISIBILITY_INLINES_HIDDEN=ON, which hides the compiler-generated helper
|
||||
# symbols attached to inline functions (guard variables for static locals,
|
||||
# vtables, typeinfo ...). The DiskAnn runtime plugin has its own copy of
|
||||
# Factory<IndexStreamer>::Instance()'s guard variable; if _zvec.so's copy
|
||||
# is hidden, the two guards are separate and the factory constructor runs
|
||||
# twice during plugin load, wiping out the registrations that happened
|
||||
# during _zvec.so import. We switch to default visibility here and rely on
|
||||
# the version script (exports.map / exports.mac) to keep the dynamic
|
||||
# symbol table small by exporting only zvec::* and PyInit_*.
|
||||
set_target_properties(_zvec PROPERTIES
|
||||
CXX_VISIBILITY_PRESET default
|
||||
C_VISIBILITY_PRESET default
|
||||
VISIBILITY_INLINES_HIDDEN OFF)
|
||||
|
||||
# Ensure any change to the linker version script (exports.map) triggers a
|
||||
# re-link of _zvec.so. target_link_options() alone is a command-line flag
|
||||
# and does not register the script file as a build dependency, so stale
|
||||
# wheels would silently keep the old export set otherwise.
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
set_property(TARGET _zvec APPEND PROPERTY LINK_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/exports.map")
|
||||
elseif (APPLE)
|
||||
set_property(TARGET _zvec APPEND PROPERTY LINK_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/exports.mac")
|
||||
endif()
|
||||
|
||||
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_libraries(_zvec PRIVATE
|
||||
-Wl,--whole-archive
|
||||
@@ -34,12 +61,29 @@ if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
$<TARGET_FILE:core_metric_static>
|
||||
$<TARGET_FILE:core_utility_static>
|
||||
$<TARGET_FILE:core_quantizer_static>
|
||||
$<TARGET_FILE:core_plugin>
|
||||
-Wl,--no-whole-archive
|
||||
zvec_db
|
||||
${CMAKE_DL_LIBS}
|
||||
)
|
||||
target_link_options(_zvec PRIVATE
|
||||
"LINKER:--version-script=${CMAKE_CURRENT_SOURCE_DIR}/exports.map"
|
||||
)
|
||||
# DiskAnn is x86-only (it depends on libaio, unavailable on ARM64), so the
|
||||
# runtime plugin (libzvec_diskann_plugin.so) is only produced on non-ARM
|
||||
# builds. It is shipped as a runtime-loaded shared module and brought up
|
||||
# implicitly the first time a DiskAnn index is created — users never need to
|
||||
# call any load function. If libaio is missing at runtime the auto-load
|
||||
# fails cleanly and the error is surfaced only when DiskAnn is actually
|
||||
# used; other index types (HNSW/IVF/Flat/Vamana) remain fully functional.
|
||||
# The .so must therefore be discoverable next to the extension module,
|
||||
# hence the $ORIGIN rpath below.
|
||||
if (NOT CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|arm64|arm")
|
||||
set_target_properties(_zvec PROPERTIES
|
||||
BUILD_RPATH "$ORIGIN"
|
||||
INSTALL_RPATH "$ORIGIN"
|
||||
)
|
||||
endif()
|
||||
elseif (APPLE)
|
||||
target_link_libraries(_zvec PRIVATE
|
||||
-Wl,-force_load,$<TARGET_FILE:core_knn_flat_static>
|
||||
@@ -54,6 +98,7 @@ elseif (APPLE)
|
||||
-Wl,-force_load,$<TARGET_FILE:core_metric_static>
|
||||
-Wl,-force_load,$<TARGET_FILE:core_utility_static>
|
||||
-Wl,-force_load,$<TARGET_FILE:core_quantizer_static>
|
||||
-Wl,-force_load,$<TARGET_FILE:core_plugin>
|
||||
zvec_db
|
||||
)
|
||||
target_link_libraries(_zvec PRIVATE
|
||||
@@ -72,6 +117,7 @@ elseif (MSVC)
|
||||
core_metric_static
|
||||
core_utility_static
|
||||
core_quantizer_static
|
||||
core_plugin
|
||||
)
|
||||
target_link_libraries(_zvec PRIVATE
|
||||
${_zvec_whole_archive_libs}
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <zvec/plugin/diskann_plugin.h>
|
||||
#include "python_collection.h"
|
||||
#include "python_config.h"
|
||||
#include "python_doc.h"
|
||||
@@ -21,6 +23,40 @@
|
||||
#include "python_type.h"
|
||||
|
||||
namespace zvec {
|
||||
|
||||
namespace {
|
||||
|
||||
// Expose DiskAnn plugin management to Python. The DiskAnn runtime normally
|
||||
// auto-loads on first use, but tests (and diagnostic tooling) need a way to
|
||||
// force a load up-front and get actionable errors when libaio is missing or
|
||||
// the plugin shared object cannot be located.
|
||||
void InitializeDiskAnnPluginBindings(pybind11::module_ &m) {
|
||||
m.def(
|
||||
"load_diskann_plugin",
|
||||
[](const std::string &path) { return ::zvec::LoadDiskAnnPlugin(path); },
|
||||
pybind11::arg("path") = std::string(),
|
||||
"Load the DiskAnn runtime plugin. Returns 0 on success or a negative "
|
||||
"DiskAnnPluginStatus code on failure (unsupported platform, libaio "
|
||||
"missing, or dlopen failure).");
|
||||
m.def("is_diskann_plugin_loaded", &::zvec::IsDiskAnnPluginLoaded,
|
||||
"Return True if the DiskAnn runtime plugin is currently loaded.");
|
||||
m.def("is_libaio_available", &::zvec::IsLibAioAvailable,
|
||||
"Return True if libaio is resolvable on this host (required by the "
|
||||
"DiskAnn runtime).");
|
||||
|
||||
// Status constants so callers can compare against well-known codes without
|
||||
// hard-coding integers.
|
||||
m.attr("DISKANN_PLUGIN_OK") = static_cast<int>(::zvec::kDiskAnnPluginOk);
|
||||
m.attr("DISKANN_PLUGIN_UNSUPPORTED_PLATFORM") =
|
||||
static_cast<int>(::zvec::kDiskAnnPluginUnsupportedPlatform);
|
||||
m.attr("DISKANN_PLUGIN_LIBAIO_MISSING") =
|
||||
static_cast<int>(::zvec::kDiskAnnPluginLibAioMissing);
|
||||
m.attr("DISKANN_PLUGIN_DLOPEN_FAILED") =
|
||||
static_cast<int>(::zvec::kDiskAnnPluginDlopenFailed);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
PYBIND11_MODULE(_zvec, m) {
|
||||
m.doc() = "Zvec core module";
|
||||
|
||||
@@ -31,5 +67,6 @@ PYBIND11_MODULE(_zvec, m) {
|
||||
ZVecPyConfig::Initialize(m);
|
||||
ZVecPyDoc::Initialize(m);
|
||||
ZVecPyCollection::Initialize(m);
|
||||
InitializeDiskAnnPluginBindings(m);
|
||||
}
|
||||
} // namespace zvec
|
||||
|
||||
@@ -1,6 +1,34 @@
|
||||
{
|
||||
global:
|
||||
PyInit_*; # export only python related functions
|
||||
# Python module entry point(s).
|
||||
PyInit_*;
|
||||
|
||||
# Expose the full zvec C++ namespace so the DiskAnn runtime plugin
|
||||
# (libzvec_diskann_plugin.so), which is dlopen()ed with
|
||||
# RTLD_NOW | RTLD_GLOBAL after the interpreter has loaded _zvec.so,
|
||||
# can resolve its undefined references against this module. Without
|
||||
# this, the plugin fails to load with errors like
|
||||
# undefined symbol: _ZN4zvec6ailego6Logger10LEVEL_INFOE
|
||||
# because the default version script hides every internal symbol.
|
||||
extern "C++" {
|
||||
"zvec::*";
|
||||
zvec::*;
|
||||
# Also export the compiler-generated helper symbols that live
|
||||
# alongside symbols in the zvec namespace (guard variables for
|
||||
# static locals, vtables, typeinfo, VTT, construction vtables,
|
||||
# thunks). Without these, the DiskAnn plugin and _zvec.so each
|
||||
# get their own copy of e.g. the guard for Factory<T>::Instance's
|
||||
# static local, which causes the factory constructor to run
|
||||
# twice - wiping out registrations done during _zvec.so load.
|
||||
"guard variable for zvec::*";
|
||||
"vtable for zvec::*";
|
||||
"VTT for zvec::*";
|
||||
"typeinfo for zvec::*";
|
||||
"typeinfo name for zvec::*";
|
||||
"construction vtable for zvec::*";
|
||||
"non-virtual thunk to zvec::*";
|
||||
"virtual thunk to zvec::*";
|
||||
};
|
||||
local:
|
||||
*;
|
||||
};
|
||||
|
||||
@@ -34,6 +34,8 @@ static std::string index_type_to_string(const IndexType type) {
|
||||
return "HNSW";
|
||||
case IndexType::HNSW_RABITQ:
|
||||
return "HNSW_RABITQ";
|
||||
case IndexType::DISKANN:
|
||||
return "DISKANN";
|
||||
case IndexType::VAMANA:
|
||||
return "VAMANA";
|
||||
case IndexType::FTS:
|
||||
@@ -876,6 +878,112 @@ Args:
|
||||
t[0].cast<MetricType>(), t[1].cast<int>(), t[2].cast<int>(),
|
||||
t[3].cast<bool>(), t[4].cast<QuantizeType>());
|
||||
}));
|
||||
|
||||
// DiskAnnIndexParams
|
||||
py::class_<DiskAnnIndexParams, VectorIndexParams,
|
||||
std::shared_ptr<DiskAnnIndexParams>>
|
||||
diskann_params(m, "DiskAnnIndexParam", R"pbdoc(
|
||||
Parameters for configuring an DiskAnn index.
|
||||
|
||||
DiskAnn stores compressed vector in memory and high-definition vector on disk. At query time,
|
||||
only compressed vector will be loaded into memory. By this way, search memory at runtime is diminished.
|
||||
|
||||
Attributes:
|
||||
metric_type (MetricType): Distance metric used for similarity computation.
|
||||
Default is ``MetricType.IP`` (inner product).
|
||||
max_degree (int): Maximum out-degree of each node in the Vamana graph.
|
||||
Larger values improve recall at the cost of build time and index size.
|
||||
Clamped to the range [1, 100]. Default is 100.
|
||||
list_size (int): Candidate list size used during graph construction.
|
||||
Larger values improve graph quality and recall at the cost of build time.
|
||||
Clamped to the range [10, 100]. Default is 50.
|
||||
pq_chunk_num (int): Number of PQ chunks used for product-quantizing the
|
||||
in-memory compressed vectors. ``0`` means auto-pick based on dimension.
|
||||
Clamped to the range [1, 1024]. Default is 0.
|
||||
quantize_type (QuantizeType): Optional quantization type for vector
|
||||
compression (e.g., FP16, INT8). Default is ``QuantizeType.UNDEFINED``.
|
||||
|
||||
Examples:
|
||||
>>> from zvec.typing import MetricType, QuantizeType
|
||||
>>> params = DiskAnnIndexParam(
|
||||
... metric_type=MetricType.COSINE,
|
||||
... max_degree=100,
|
||||
... list_size=50,
|
||||
... pq_chunk_num=8,
|
||||
... quantize_type=QuantizeType.FP16
|
||||
... )
|
||||
>>> print(params.max_degree)
|
||||
100
|
||||
)pbdoc");
|
||||
diskann_params
|
||||
.def(py::init<MetricType, int, int, int, QuantizeType>(),
|
||||
py::arg("metric_type") = MetricType::IP, py::arg("max_degree") = 100,
|
||||
py::arg("list_size") = 100, py::arg("pq_chunk_num") = 0,
|
||||
py::arg("quantize_type") = QuantizeType::UNDEFINED,
|
||||
R"pbdoc(
|
||||
Constructs an DiskAnnIndexParams instance.
|
||||
|
||||
Args:
|
||||
metric_type (MetricType, optional): Distance metric. Defaults to MetricType.IP.
|
||||
max_degree (int, optional): Maximum out-degree of each node in the Vamana
|
||||
graph. Clamped to [1, 100]. Defaults to 100.
|
||||
list_size (int, optional): Candidate list size used during graph
|
||||
construction. Clamped to [10, 100]. Defaults to 50.
|
||||
pq_chunk_num (int, optional): Number of PQ chunks for product
|
||||
quantization. ``0`` means auto-pick based on dimension.
|
||||
Clamped to [1, 1024]. Defaults to 0.
|
||||
quantize_type (QuantizeType, optional): Vector quantization type.
|
||||
Defaults to QuantizeType.UNDEFINED.
|
||||
)pbdoc")
|
||||
.def_property_readonly("max_degree", &DiskAnnIndexParams::max_degree,
|
||||
"int: max node degree.")
|
||||
.def_property_readonly("list_size", &DiskAnnIndexParams::list_size,
|
||||
"int: list size of graph construction")
|
||||
.def_property_readonly(
|
||||
"pq_chunk_num",
|
||||
[](const DiskAnnIndexParams &self) -> int {
|
||||
return self.pq_chunk_num();
|
||||
},
|
||||
"int: chunk num of production quantization.")
|
||||
.def(
|
||||
"to_dict",
|
||||
[](const DiskAnnIndexParams &self) -> py::dict {
|
||||
py::dict dict;
|
||||
dict["type"] = index_type_to_string(self.type());
|
||||
dict["metric_type"] = metric_type_to_string(self.metric_type());
|
||||
dict["max_degree"] = self.max_degree();
|
||||
dict["list_size"] = self.list_size();
|
||||
dict["pq_chunk_num"] = self.pq_chunk_num();
|
||||
dict["quantize_type"] =
|
||||
quantize_type_to_string(self.quantize_type());
|
||||
return dict;
|
||||
},
|
||||
"Convert to dictionary with all fields")
|
||||
.def(
|
||||
"__repr__",
|
||||
[](const DiskAnnIndexParams &self) {
|
||||
return "{"
|
||||
"\"metric_type\":" +
|
||||
metric_type_to_string(self.metric_type()) +
|
||||
", \"max_degree\":" + std::to_string(self.max_degree()) +
|
||||
", \"list_size\":" + std::to_string(self.list_size()) +
|
||||
", \"pq_chunk_num\":" + std::to_string(self.pq_chunk_num()) +
|
||||
", \"quantize_type\":" +
|
||||
quantize_type_to_string(self.quantize_type()) + "}";
|
||||
})
|
||||
.def(py::pickle(
|
||||
[](const DiskAnnIndexParams &self) {
|
||||
return py::make_tuple(self.metric_type(), self.max_degree(),
|
||||
self.list_size(), self.pq_chunk_num(),
|
||||
self.quantize_type());
|
||||
},
|
||||
[](py::tuple t) {
|
||||
if (t.size() != 5)
|
||||
throw std::runtime_error("Invalid state for DiskAnnIndexParams");
|
||||
return std::make_shared<DiskAnnIndexParams>(
|
||||
t[0].cast<MetricType>(), t[1].cast<int>(), t[2].cast<int>(),
|
||||
t[3].cast<int>(), t[4].cast<QuantizeType>());
|
||||
}));
|
||||
}
|
||||
|
||||
void ZVecPyParams::bind_query_params(py::module_ &m) {
|
||||
@@ -1118,6 +1226,54 @@ Args:
|
||||
return obj;
|
||||
}));
|
||||
|
||||
// binding diskann query params
|
||||
py::class_<DiskAnnQueryParams, QueryParams,
|
||||
std::shared_ptr<DiskAnnQueryParams>>
|
||||
diskann_params(m, "DiskAnnQueryParam", R"pbdoc(
|
||||
Query parameters for DiskAnn index.
|
||||
|
||||
Attributes:
|
||||
type (IndexType): Always ``IndexType.DISKANN``.
|
||||
list_size (int): Beam-search candidate list size used at query time.
|
||||
Higher values improve recall but increase latency. Default is 10.
|
||||
|
||||
Examples:
|
||||
>>> params = DiskAnnQueryParam(list_size=20)
|
||||
>>> print(params.list_size)
|
||||
20
|
||||
)pbdoc");
|
||||
diskann_params
|
||||
.def(py::init<int>(), py::arg("list_size") = 300, R"pbdoc(
|
||||
Constructs an DiskAnnQueryParams instance.
|
||||
|
||||
Args:
|
||||
list_size (int, optional): Beam-search candidate list size during
|
||||
graph search. Higher values improve recall at the cost of latency.
|
||||
Defaults to 300.
|
||||
)pbdoc")
|
||||
.def_property_readonly(
|
||||
"list_size",
|
||||
[](const DiskAnnQueryParams &self) -> int {
|
||||
return self.list_size();
|
||||
},
|
||||
"int: Beam-search candidate list size during DiskAnn query.")
|
||||
.def("__repr__",
|
||||
[](const DiskAnnQueryParams &self) -> std::string {
|
||||
return "{"
|
||||
"\"type\":" +
|
||||
index_type_to_string(self.type()) +
|
||||
", \"list_size\":" + std::to_string(self.list_size()) + "}";
|
||||
})
|
||||
.def(py::pickle(
|
||||
[](const DiskAnnQueryParams &self) {
|
||||
return py::make_tuple(self.list_size());
|
||||
},
|
||||
[](py::tuple t) {
|
||||
if (t.size() != 1)
|
||||
throw std::runtime_error("Invalid state for DiskAnnQueryParams");
|
||||
return std::make_shared<DiskAnnQueryParams>(t[0].cast<int>());
|
||||
}));
|
||||
|
||||
// binding vamana query params
|
||||
py::class_<VamanaQueryParams, QueryParams, std::shared_ptr<VamanaQueryParams>>
|
||||
vamana_query_params(m, "VamanaQueryParam", R"pbdoc(
|
||||
|
||||
Reference in New Issue
Block a user