Repository navigation
feat(index): add rabitqlib::IvfIndex and build the Python binding on it - #240
Merged
Merged
Conversation
The workflow of the Python IvfIndex was implemented in the binding, so a C++ caller had to rebuild it on ivf::IVF. IvfIndex implements it in C++, as step 1 of #234: - IvfIndex(dim, num_clusters, IvfOptions), a static load, and train, set_centroids, add, remove, reserve_cluster, search and save with the names, defaults and state errors of the Python class. - The first add trains an untrained index on a staged copy, so a failure leaves it untrained and empty. - IDs are rabitqlib::Id (int64_t), kNoId marks a missing result, and search takes a batch, pads with kNoId and +inf, and probes num_clusters / 16 clusters, rounded and at least 1, by default. - A seed is drawn unless given; cp() holds the clustering defaults. The header forward-declares ivf::IVF and the k-means parameters, so it pulls in no implementation header; a separate consumer boundary checks that. ivf::IVF is unchanged. An allocation-failure sweep covers the rollback of the first add after training has succeeded.
The binding drops the staged first-add training, the default nprobe, the result padding and the state checks, which rabitqlib::IvfIndex now implements. It keeps the NumPy conversions, shape checks, the checks whose messages name Python values, the GIL release and the IndexAccess guards. cp stays binding state and is copied into the native index with the GIL and the write guard held before train and add release the GIL, because Python writes its fields without a guard. Results, messages and the Python suite are unchanged. A call with both an invalid argument and the wrong state may now report the argument first, for example ValueError for nprobe=0 on an untrained index.
This was referenced Nov 15, 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 1 of 4:
Id,kNoId,IvfIndexand the IVF binding).Summary
The workflow of the Python
IvfIndexlived inpython_bindings/ivf_bindings.cpp, so C++ callers had to rebuild it onivf::IVF. This addsrabitqlib::IvfIndexinrabitqlib/index/ivf_index.hpp, which implements it in C++, and rebuilds the Python binding on top of it.IvfIndex(dim, num_clusters, IvfOptions), a staticload, andtrain,set_centroids,add,remove,reserve_cluster,searchandsave, with the names, defaults and state errors of the Python class.addtrains an untrained index on a staged copy, so a failure leaves it untrained and empty.rabitqlib::Id(int64_t) andkNoId(-1) marks a missing result.searchtakes a batch and anIvfSearchOptions, pads withkNoIdand+inf, and without annprobeprobesnum_clusters / 16clusters, rounded and at least 1. An explicit 0 throws.num_threads == 0means every available CPU, capped byOMP_NUM_THREADS.Id,kNoIdandAddOptionslive inindex/types.hpp.ivf::Routingis an alias ofivf::InitializerType.ivf::IVFandRaBitQKMeansParametersand pulls in no implementation header. A new consumer target,ivf_index_header_boundary, checks that: it poisonsindex/ivf/ivf.hpp,index/ivf/cluster.hppandclustering/rabitqkmeans.hppon top of the headersindex_header_boundaryalready forbids. Changingcp()fields therefore needsrabitqlib/clustering/rabitqkmeans.hpp.ivf::IVFand the file formats are unchanged.The binding keeps:
addcluster-ID range and thereserve_clusternum_pointssign, both checked before narrowing;krange, checked before it allocates the outputs;nprobe=0with "pass None");IndexAccessguards.cpstays binding state. It is copied into the native index with the GIL and the write guard held, beforetrainandaddrelease the GIL, because Python writes its fields without a guard.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 now report a different one first:
train,set_centroids,add,reserve_clusterandsearch, an invalid argument is reported before the wrong state. For example,search(q, k, 0)on an untrained index now raisesValueErrorinstead ofRuntimeError.reserve_cluster, a negativenum_pointsis reported before an out-of-rangecluster_id. Both areValueError.The release notes mention the first kind.
Notes for review
IvfIndex(dim, n, {METRIC_IP}), the positional form New C++ index classes that match the Python API #234 mentions, compiles but warns under GCC-Wextra(missing-field-initializers). The header therefore says to set fields by name.{4}still fails to compile.ids must be in [0, num_stored_points). The C++kmessage writes2^31where Python writes2**31.IvfIndex.ivf::IVFkeep theirIVFprefix and errors from k-means theirRaBitQKMeansprefix. For L2 and IP, k-means also runs the finite and range checks on training data.tests/failures/ivf_index_allocation_test.cppmakes eachoperator newof a first add fail in turn, and fails if the add does not train on a staged copy. Aligned storage and Eigen allocations are not injected.num_threadsofsearch,addandtrain) is not covered by a test, because results do not depend on it.Tests
tests/unit/rabitqlib/index/ivf_index_test.cpp, 15 tests:train+add, includingcp();nprobe, including rounding;kbounds;removerange checks before narrowing;reserve_cluster;cluster_ids,fast_quantization,high_accuracy);ivf_index.cppmakes a test fail: training in place instead of on a staged copy, a fixed seed, thecpseed used as the rotation seed, ignoredcluster_ids, ignoredfast_quantization, ignoredhigh_accuracy, a wrongnprobedefault, narrowing IDs before checking them, a missing state check, a wrong defaultcpseed after load.Verification
Local, Linux x86-64, GCC 14,
RABITQ_ENABLE_NATIVE_OPTIMIZATION=OFF, on the final commits:ctest: 572 tests, 571 passed, 1 skipped (ThreadCount.BoundParallelForUsesRuntimePlacementAndPropagatesErrors, which needs thread placement).check-tidy.sh(clang-tidy 23),check-format.sh,mkdocs build --strict,git diff --check.Benchmark
Python
IvfIndex, before (3685e81) and after, on SIFT1M (1M x 128, 10k queries, the provided ground truth). 4096 precomputed centroids and cluster IDs,nbits=7,seed=1, k=10.Setup:
pip wheeland the defaultRABITQ_ENABLE_NATIVE_OPTIMIZATION=ON(-march=nativeon this Sapphire Rapids host), the same way for both builds. This is not the portable release configuration.add1M withcluster_ids, 8 threadsaddcalls of 10 rows, 1 threadsearch10k, nprobe 16, 1 thread (recall@10 0.8419)search10k, nprobe 16, 8 threadssearch10k, nprobe 64, 1 thread (recall@10 0.9663)search10k, nprobe 64, 8 threadsThe batch searches return bit-identical IDs and distances in both builds and all runs. The single-query calls return identical IDs; their distances were not saved. The built indexes were not compared.
The ranges overlap in every row. With three runs this supports "no measurable change" only weakly. The nprobe 64, 1-thread row comes closest to a difference: the after build is faster in all three pairs, but the ranges still overlap. I make no performance claim. The new layer allocates a 32-bit ID buffer per search and widens it, as the binding did before.
The benchmark ran on the first version of this branch. The review fixes after it add one copy of the clustering parameters per
trainandaddcall. They do not touchsearch, and the benchmark was not rerun.