Skip to content

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

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

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

Conversation

@gouyt13

@gouyt13 gouyt13 commented Nov 15, 2026

Copy link
Copy Markdown
Member

Part of #234 (step 1 of 4: Id, kNoId, IvfIndex and the IVF binding).

Summary

The workflow of the Python IvfIndex lived in python_bindings/ivf_bindings.cpp, so C++ callers had to rebuild it on ivf::IVF. This adds rabitqlib::IvfIndex in rabitqlib/index/ivf_index.hpp, which implements it in C++, and rebuilds the Python binding on top of it.

  • 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) and kNoId (-1) marks a missing result. search takes a batch and an IvfSearchOptions, pads with kNoId and +inf, and without an nprobe probes num_clusters / 16 clusters, rounded and at least 1. An explicit 0 throws.
  • A seed is drawn unless given. num_threads == 0 means every available CPU, capped by OMP_NUM_THREADS.
  • Id, kNoId and AddOptions live in index/types.hpp. ivf::Routing is an alias of ivf::InitializerType.
  • The header forward-declares ivf::IVF and RaBitQKMeansParameters and pulls in no implementation header. A new consumer target, ivf_index_header_boundary, checks that: it poisons index/ivf/ivf.hpp, index/ivf/cluster.hpp and clustering/rabitqkmeans.hpp on top of the headers index_header_boundary already forbids. Changing cp() fields therefore needs rabitqlib/clustering/rabitqkmeans.hpp.
  • ivf::IVF and the file formats are unchanged.

The binding keeps:

  • the NumPy conversions and shape checks;
  • the add cluster-ID range and the reserve_cluster num_points sign, both checked before narrowing;
  • the k range, checked before it allocates the outputs;
  • the checks whose messages name Python values (nprobe=0 with "pass None");
  • the GIL release and the IndexAccess guards.

cp stays binding state. It 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.

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:

    • In train, set_centroids, add, reserve_cluster and search, an invalid argument is reported before the wrong state. For example, search(q, k, 0) on an untrained index now raises ValueError instead of RuntimeError.
    • In reserve_cluster, a negative num_points is reported before an out-of-range cluster_id. Both are ValueError.

    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.
  • Messages and New C++ index classes that match the Python API #234 rule 8:
    • C++ argument messages keep the Python wording, without the class prefix rule 8 proposed, for example ids must be in [0, num_stored_points). The C++ k message writes 2^31 where Python writes 2**31.
    • State messages start with IvfIndex.
    • Errors from ivf::IVF keep their IVF prefix and errors from k-means their RaBitQKMeans prefix. For L2 and IP, k-means also runs the finite and range checks on training data.
  • The rollback of the first add after training succeeds is reachable only through an allocation failure. tests/failures/ivf_index_allocation_test.cpp makes each operator new of 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.
  • Thread-count forwarding (num_threads of search, add and train) is not covered by a test, because results do not depend on it.

Tests

  • New tests/unit/rabitqlib/index/ivf_index_test.cpp, 15 tests:
    • defaults and drawn seeds;
    • the first add equal to train + add, including cp();
    • a failed first add;
    • state errors;
    • retraining only while empty;
    • the default nprobe, including rounding;
    • zero breadth and k bounds;
    • padding;
    • remove range checks before narrowing;
    • reserve_cluster;
    • save and load, also of a 0.8.3 file without a seed;
    • option forwarding (cluster_ids, fast_quantization, high_accuracy);
    • moves.
  • Each of these mutants of ivf_index.cpp makes a test fail: training in place instead of on a staged copy, a fixed seed, the cp seed used as the rotation seed, ignored cluster_ids, ignored fast_quantization, ignored high_accuracy, a wrong nprobe default, narrowing IDs before checking them, a missing state check, a wrong default cp seed after load.
  • The new allocation-failure sweep and consumer boundary target, described above.

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).
  • Python suite with the branch installed: 1194 passed, 2 skipped.
  • Installed consumer: 4 passed.
  • Full check-tidy.sh (clang-tidy 23), check-format.sh, mkdocs build --strict, git diff --check.
  • Not run locally: MSVC, macOS, NEON.

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:

  • Build: GCC 14 Release wheels built with pip wheel and the default RABITQ_ENABLE_NATIVE_OPTIMIZATION=ON (-march=native on this Sapphire Rapids host), the same way for both builds. This is not the portable release configuration.
  • CPU and memory: Xeon Gold 6418H, pinned to physical cores 16-23 (NUMA node 0) with memory on node 0. Their SMT siblings were not reserved. The host load average was about 51 of 96 logical CPUs during the runs.
  • Runs: 3 runs per build, interleaved, each a fresh process. Each run times one call per measurement, with no warm-up. The 200-call row times the whole Python loop.
Measurement Before: runs, median After: runs, median
add 1M with cluster_ids, 8 threads 1.428 / 1.425 / 1.408 s, 1.425 s 1.418 / 1.404 / 1.437 s, 1.418 s
200 routed add calls of 10 rows, 1 thread 71.9 / 79.7 / 71.9 ms, 72 ms 76.6 / 74.1 / 72.8 ms, 74 ms
search 10k, nprobe 16, 1 thread (recall@10 0.8419) 11121 / 10700 / 10422 QPS, 10700 10956 / 10758 / 11416 QPS, 10956
search 10k, nprobe 16, 8 threads 79194 / 81004 / 78655 QPS, 79194 79433 / 79040 / 81343 QPS, 79433
search 10k, nprobe 64, 1 thread (recall@10 0.9663) 6297 / 6180 / 6074 QPS, 6180 6630 / 6282 / 6514 QPS, 6514
search 10k, nprobe 64, 8 threads 44970 / 46057 / 41647 QPS, 44970 44463 / 41150 / 45121 QPS, 44463
2000 single-query calls, nprobe 16: p50 91.5 / 93.0 / 102.5 µs 84.1 / 103.0 / 83.5 µs
same: p99 115.4 / 126.1 / 126.7 µs 107.9 / 130.1 / 112.1 µs
same: max 151 / 208 / 201 µs 140 / 210 / 145 µs

The 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 train and add call. They do not touch search, and the benchmark was not rerun.

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.
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