Repository navigation
feat(index): add rabitqlib::HnswIndex and build the Python binding on it - #243
Merged
Merged
Conversation
The workflow of the Python HnswIndex was implemented in its binding, so a C++ caller had to rebuild it on hnsw::HierarchicalNSW. HnswIndex implements it in C++, as step 2 of #234: - HnswIndex(dim, HnswOptions), a static load, and train, set_centroids, add, remove, reserve, search and save with the names, defaults and state errors of the Python class. - The first add trains min(num_clusters, points) centroids on a staged copy with the same seed and capacity, so a failure leaves the index untrained, empty and with its capacity. - Capacity starts at one point and grows on add, at least doubling, after the points and cluster IDs are checked; reserve only grows it. - search takes a GraphSearchOptions (in index/types.hpp), defaults ef_search to max(k, 64), rejects 0 and pads with kNoId and +inf. - seed() is a std::optional<uint64_t>: files written by HierarchicalNSW may record a seed above 32 bits; cp() takes its low 32 bits. The checks IvfIndex and HnswIndex share (k, an explicit zero breadth, the training thread override and the output size) move to the private src/index/index_facade.hpp; IvfIndex keeps its messages. The consumer header-boundary target now covers both headers, and .clang-tidy keeps the HNSW name M for HnswOptions::M as it does elsewhere. hnsw::HierarchicalNSW is unchanged.
The binding drops the staged first-add training, the capacity growth, the default ef_search, the result padding and the state checks, which rabitqlib::HnswIndex now implements. It keeps the NumPy conversions, shape checks, the checks whose messages name Python values, the k check before the outputs are allocated, the reserve fast path under a read guard, the GIL release and the IndexAccess guards. cp stays binding state, copied into the native index with the GIL and the write guard held before train and add. checked_removal_ids has no caller left and is removed. Results, messages and the Python suite are unchanged. A call with two faults may now report a different one first; the release notes list the cases.
This was referenced Nov 16, 2026
Open
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #234 (step 2 of 4:
HnswIndexand the HNSW binding; step 1 was #240).Summary
The workflow of the Python
HnswIndexlived inpython_bindings/hnsw_bindings.cpp. This addsrabitqlib::HnswIndexinrabitqlib/index/hnsw_index.hpp, which implements it in C++, and rebuilds the binding on it. It follows theIvfIndexpattern from #240.HnswIndex(dim, HnswOptions), a staticload, andtrain,set_centroids,add,remove,reserve,searchandsave, with the names, defaults and state errors of the Python class.addtrainsmin(num_clusters, number of points)centroids on a staged copy with the same seed and capacity. A failure leaves the index untrained, empty and with its capacity.addtomax(needed, min(2 * capacity, 2^31)). Growth happens only after the points and cluster IDs are checked, so invalid input leaves the capacity unchanged.reserveonly grows it.searchtakes aGraphSearchOptions, which lives inindex/types.hppbecauseSymqgIndexwill share it. Without anef_searchit usesmax(k, 64), an explicit 0 throws, and missing results are padded withkNoIdand+inf.adduses every available CPU unlessnum_threadsis set, as Python does;hnsw::HierarchicalNSW::adduses one. A reproducible graph needs one thread and a seed.IvfIndexandHnswIndexshare move to the privatesrc/index/index_facade.hpp, andIvfIndexuses it with unchanged messages. They coverk, an explicit zero breadth, the training thread override, and the output pointer and size.hnsw::HierarchicalNSWand the file formats are unchanged.The binding keeps the NumPy conversions and shape checks, the checks whose messages name Python values, the
kcheck before the outputs are allocated, thereservefast path under a read guard, the GIL release andIndexAccess.cpstays binding state and is copied into the native index with the GIL and the write guard held.checked_removal_idshas no caller left and is removed.Behaviour changes
searchon an untrained index: a wrong dimension,k=0oref_search=0raisesValueErrorinstead ofRuntimeError.addon an untrained index: a wrong dimension, orcluster_idsof the wrong length or out of range, raisesValueError. On an untrained index,cluster_idsare checked against the configurednum_clusters.trainandset_centroidson an index that stores points: a wrong dimension, too few rows or a wrong centroid shape raisesValueErrorinstead of "cannot be trained once it stores points".metricorseedis reported before an out-of-rangenum_clusters.Notes for review
seed()returnsstd::optional<uint64_t>, notuint32_t: a file written byhnsw::HierarchicalNSWmay record a seed above 32 bits, and the Pythonseedproperty reports it in full, as before. TheHnswOptions::seedoption isstd::optional<uint32_t>, as New C++ index classes that match the Python API #234 proposes.HnswOptions::Mkeeps the HNSW name..clang-tidygainsPublicMemberIgnoredRegexp: '^M$', next to its existingMexceptions for parameters, methods and private members.ivf_index_header_boundaryfrom feat(index): add rabitqlib::IvfIndex and build the Python binding on it #240 becomesindex_api_header_boundary. It compiles smoke tests of both index API headers,ivf_index.hppand the newhnsw_index.hpp, and also poisonsindex/hnsw/hnsw.hpp.trainorset_centroidsbeforeadd, as in the old binding. No fixture exists for such a file, and the current writer cannot produce one, so this path has no test.Tests
tests/unit/rabitqlib/index/hnsw_index_test.cpp, 17 tests:cp(), the rotation seed,fast_quantization, null data, and fewer points than clusters;reserve, with invalid points, cluster IDs and null data leaving the capacity unchanged;ef_search;kbounds;removerange checks before narrowing;tests/failures/hnsw_add_allocation_test.cpp,HnswIndexFirstAddAllocationTest: a single-threaded sweep that makes eachoperator newof a first add fail in turn, with and without a reserved capacity. It is the only test that fails if the add is not staged.hnsw_index.cpp, 21 mutants:ef_searchof 64, becauseHierarchicalNSWraisesef_searchtok;fast_quantizationon the staged add, growing the live index before staging, no cluster-ID check.Verification
Local, Linux x86-64, GCC 14,
RABITQ_ENABLE_NATIVE_OPTIMIZATION=OFF. The test logs predate only a comment-only edit, after which format,git diff --checkand MkDocs were rerun:ctest: 590 tests, 589 passed, 1 skipped (ThreadCount.BoundParallelForUsesRuntimePlacementAndPropagatesErrors, which needs OpenMP thread binding).test_editor_support.py,test_mypy.py,test_pyright.py: 18 passed.check-tidy.sh(clang-tidy 23),check-format.sh,mkdocs build --strict,git diff --check.Benchmark
Python
HnswIndex, before (afc0d0e) and after, on the first 200,000 SIFT1M base vectors with 10,000 queries and exact top-10 ground truth computed for that subset. Defaults:nbits=7,num_clusters=16,M=16,ef_construction=200; seed 1 (seed 2 for the 20k check below); k=10.Setup:
pip wheel, native optimization ON (-march=native), the same way for both. This is not the portable release configuration.HnswIndex::add. The benchmark never passescluster_ids, so that check does not run in it.add200k, 8 threads (includes training)addcalls of 10 rows, 1 threadsearch10k, ef 64, 1 thread (recall@10 0.961)search10k, ef 64, 8 threadssearch10k, ef 256, 1 thread (recall@10 0.975)search10k, ef 256, 8 threadsCorrectness check: in each of the six runs, a 20,000-point single-threaded build (deterministic) saved byte-identical files and returned identical IDs and distances for 1,000 queries in both builds. The 8-thread 200k builds are not deterministic, so their recall differs slightly between runs (0.9607 to 0.9609).
The first-add medians differ by more than the other rows, so it was measured twice more:
HnswIndex::addwith the old binding's steps (stagedHierarchicalNSW,train, coordinate check,resize,add), 5 times each withHnswIndexfirst, at load averages up to 56.The new wheel's first-add median was higher in all three wheel comparisons, but the ranges overlap, and the same-build comparison shows no difference between the two code paths. Host load or the two separate native builds may explain the wheel gap; I did not separate them. I make no performance claim.