Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HierarchicalNSW::indexFileSize() function for precise memory footprint control #427

Merged
merged 1 commit into from
May 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions hnswlib/hnswalg.h
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,32 @@ class HierarchicalNSW : public AlgorithmInterface<dist_t> {
max_elements_ = new_max_elements;
}

size_t indexFileSize() const {
size_t size = 0;
size += sizeof(offsetLevel0_);
size += sizeof(max_elements_);
size += sizeof(cur_element_count);
size += sizeof(size_data_per_element_);
size += sizeof(label_offset_);
size += sizeof(offsetData_);
size += sizeof(maxlevel_);
size += sizeof(enterpoint_node_);
size += sizeof(maxM_);

size += sizeof(maxM0_);
size += sizeof(M_);
size += sizeof(mult_);
size += sizeof(ef_construction_);

size += cur_element_count * size_data_per_element_;

for (size_t i = 0; i < cur_element_count; i++) {
unsigned int linkListSize = element_levels_[i] > 0 ? size_links_per_element_ * element_levels_[i] : 0;
size += sizeof(linkListSize);
size += linkListSize;
}
return size;
}

void saveIndex(const std::string &location) {
std::ofstream output(location, std::ios::binary);
Expand Down
4 changes: 4 additions & 0 deletions python_bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,9 @@ class Index {
this->num_threads_default = num_threads;
}

size_t indexFileSize() const {
return appr_alg->indexFileSize();
}

void saveIndex(const std::string &path_to_index) {
appr_alg->saveIndex(path_to_index);
Expand Down Expand Up @@ -904,6 +907,7 @@ PYBIND11_PLUGIN(hnswlib) {
.def("get_ids_list", &Index<float>::getIdsList)
.def("set_ef", &Index<float>::set_ef, py::arg("ef"))
.def("set_num_threads", &Index<float>::set_num_threads, py::arg("num_threads"))
.def("index_file_size", &Index<float>::indexFileSize)
.def("save_index", &Index<float>::saveIndex, py::arg("path_to_index"))
.def("load_index",
&Index<float>::loadIndex,
Expand Down