Skip to content

feat(index): add rabitqlib::HnswIndex and build the Python binding on it - #243

Merged
gouyt13 merged 2 commits into
dev/0.9from
feat/hnsw-index
Nov 16, 2026
Merged

gouyt13 merged 2 commits into
dev/0.9from
feat/hnsw-index

Conversation

@gouyt13

@gouyt13 gouyt13 commented Nov 16, 2026

Copy link
Copy Markdown
Member

Part of #234 (step 2 of 4: HnswIndex and the HNSW binding; step 1 was #240).

Summary

The workflow of the Python HnswIndex lived in python_bindings/hnsw_bindings.cpp. This adds rabitqlib::HnswIndex in rabitqlib/index/hnsw_index.hpp, which implements it in C++, and rebuilds the binding on it. It follows the IvfIndex pattern from #240.

  • 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, 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.
  • Capacity starts at one point and grows on add to max(needed, min(2 * capacity, 2^31)). Growth happens only after the points and cluster IDs are checked, so invalid input leaves the capacity unchanged. reserve only grows it.
  • search takes a GraphSearchOptions, which lives in index/types.hpp because SymqgIndex will share it. Without an ef_search it uses max(k, 64), an explicit 0 throws, and missing results are padded with kNoId and +inf.
  • add uses every available CPU unless num_threads is set, as Python does; hnsw::HierarchicalNSW::add uses one. A reproducible graph needs one thread and a seed.
  • The checks IvfIndex and HnswIndex share move to the private src/index/index_facade.hpp, and IvfIndex uses it with unchanged messages. They cover k, an explicit zero breadth, the training thread override, and the output pointer and size.
  • hnsw::HierarchicalNSW and the file formats are unchanged.

The binding keeps the NumPy conversions and 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 IndexAccess. cp stays binding state and is copied into the native index with the GIL and the write guard held. checked_removal_ids has no caller left and is removed.

Behaviour changes

  • Results and the messages of single-fault calls do not change. The Python suite passes without edits.
  • A call with two faults may report a different one first. The release notes list both kinds:
    • search on an untrained index: a wrong dimension, k=0 or ef_search=0 raises ValueError instead of RuntimeError.
    • add on an untrained index: a wrong dimension, or cluster_ids of the wrong length or out of range, raises ValueError. On an untrained index, cluster_ids are checked against the configured num_clusters.
    • train and set_centroids on an index that stores points: a wrong dimension, too few rows or a wrong centroid shape raises ValueError instead of "cannot be trained once it stores points".
    • The constructor: an invalid metric or seed is reported before an out-of-range num_clusters.

Notes for review

  • seed() returns std::optional<uint64_t>, not uint32_t: a file written by hnsw::HierarchicalNSW may record a seed above 32 bits, and the Python seed property reports it in full, as before. The HnswOptions::seed option is std::optional<uint32_t>, as New C++ index classes that match the Python API #234 proposes.
  • HnswOptions::M keeps the HNSW name. .clang-tidy gains PublicMemberIgnoredRegexp: '^M$', next to its existing M exceptions for parameters, methods and private members.
  • The consumer target ivf_index_header_boundary from feat(index): add rabitqlib::IvfIndex and build the Python binding on it #240 becomes index_api_header_boundary. It compiles smoke tests of both index API headers, ivf_index.hpp and the new hnsw_index.hpp, and also poisons index/hnsw/hnsw.hpp.
  • An empty, untrained file saved by 0.7 loads untrained with 16 clusters to train, and needs train or set_centroids before add, 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

  • New tests/unit/rabitqlib/index/hnsw_index_test.cpp, 17 tests:
    • defaults and drawn seeds;
    • the first add, including cp(), the rotation seed, fast_quantization, null data, and fewer points than clusters;
    • a failed first add keeping the capacity;
    • capacity growth, doubling and reserve, with invalid points, cluster IDs and null data leaving the capacity unchanged;
    • state errors;
    • retraining only while empty;
    • the default ef_search;
    • zero breadth and k bounds;
    • padding;
    • remove range checks before narrowing;
    • option forwarding;
    • save and load, also of a 0.8.3 file without a seed and of a file with a 64-bit seed;
    • moves.
  • A new test in tests/failures/hnsw_add_allocation_test.cpp, HnswIndexFirstAddAllocationTest: a single-threaded sweep that makes each operator new of 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.
  • Mutation checks on hnsw_index.cpp, 21 mutants:
    • 17 run before the review fixes: 15 were caught. The 2 survivors behave identically to the original code in these tests:
      • a default ef_search of 64, because HierarchicalNSW raises ef_search to k;
      • doubling without the 2^31 cap.
    • 4 run after the review fixes, all caught: no null-data check, no fast_quantization on the staged add, growing the live index before staging, no cluster-ID check.
    • The C++ reviewer's mutants that change only thread counts or skip the training thread override also survive. Results did not depend on them in these tests.

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 --check and MkDocs were rerun:

  • ctest: 590 tests, 589 passed, 1 skipped (ThreadCount.BoundParallelForUsesRuntimePlacementAndPropagatesErrors, which needs OpenMP thread binding).
  • Python suite with the branch installed: 1196 passed, 2 skipped (the macOS and Linux ARM64 wheel tests).
  • test_editor_support.py, test_mypy.py, test_pyright.py: 18 passed.
  • Installed consumer: 4 passed.
  • Full 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:

  • Build: GCC 14 Release wheels built with pip wheel, native optimization ON (-march=native), the same way for both. This is not the portable release configuration.
  • CPU and memory: Xeon Gold 6418H, 8 physical cores of NUMA node 0 (6, 11, 14, 15, 17, 18, 20, 21) that, with their SMT siblings, had no busy thread when I picked them, with memory on node 0. The host load average was 30–37 during these runs.
  • Runs: 3 interleaved runs per build, each a fresh process with one timed call per measurement and no warm-up. The 200-call row times the whole Python loop.
  • Code: the "after" wheel was built before the review added the cluster-ID range check to HnswIndex::add. The benchmark never passes cluster_ids, so that check does not run in it.
Measurement Before: runs, median After: runs, median
First add 200k, 8 threads (includes training) 8.06 / 10.78 / 9.98 s, 9.98 11.75 / 11.88 / 9.91 s, 11.75
200 add calls of 10 rows, 1 thread 1.53 / 1.59 / 1.54 s, 1.54 1.55 / 1.64 / 1.54 s, 1.55
search 10k, ef 64, 1 thread (recall@10 0.961) 11795 / 13024 / 12497 QPS, 12497 12505 / 12877 / 12908 QPS, 12877
search 10k, ef 64, 8 threads 85719 / 81674 / 97503 QPS, 85719 78160 / 99689 / 87172 QPS, 87172
search 10k, ef 256, 1 thread (recall@10 0.975) 4081 / 4023 / 4134 QPS, 4081 3995 / 3926 / 4083 QPS, 3995
search 10k, ef 256, 8 threads 28350 / 22405 / 34376 QPS, 28350 29266 / 30381 / 26968 QPS, 29266
2000 single queries, ef 64: p50 88.6 / 87.6 / 85.3 µs 90.6 / 89.8 / 85.0 µs
same: p99 117.4 / 117.7 / 114.4 µs 124.2 / 122.4 / 114.9 µs

Correctness 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:

  • Five more interleaved runs per build:
    • 200k with 8 threads: before 10.21 / 10.80 / 10.57 / 13.95 / 12.69 s (median 10.80), after 11.50 / 10.50 / 11.46 / 13.05 / 12.12 s (median 11.50).
    • 50k with 1 thread: before 15.01 / 14.26 / 14.99 / 16.35 / 15.33 s (median 15.01), after 14.46 / 15.21 / 16.54 / 16.15 / 15.69 s (median 15.69).
    • The ranges overlap.
  • One C++ process linked against one library build: a portable Release build (native optimization OFF), pinned to the same cores. It alternated HnswIndex::add with the old binding's steps (staged HierarchicalNSW, train, coordinate check, resize, add), 5 times each with HnswIndex first, at load averages up to 56.
    • 50k, 1 thread: 12.55 s versus 12.62 s median.
    • 200k, 8 threads: 11.09 s versus 11.09 s median.

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.

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.
@github-actions github-actions Bot added the release:added Release category managed from the PR title label Nov 16, 2026
@gouyt13
gouyt13 merged commit 897c41b into dev/0.9 Nov 16, 2026
35 checks passed
@gouyt13
gouyt13 deleted the feat/hnsw-index branch November 16, 2026 05:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:added Release category managed from the PR title

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant