Skip to content

Proposal: QGEMeans, mini-batch e-means with SymphonyQG assignment - #261

Open
TamimEhsan wants to merge 10 commits into
VectorDB-NTU:mainfrom
TamimEhsan:qg-e-means
Open

TamimEhsan wants to merge 10 commits into
VectorDB-NTU:mainfrom
TamimEhsan:qg-e-means

Conversation

@TamimEhsan

@TamimEhsan TamimEhsan commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

QGEMeans, mini-batch e-means with SymphonyQG assignment

Adds rabitqlib::qgemeans::QGEMeans (C++) and rabitqlib.QGEMeans (Python). It is the e-means recipe (arXiv:2611.09501, Algorithm 1, with the constants and the cost-based revival of Faiss contrib/e_means at b14b3d693), with each mini-batch assigned through a SymphonyQG graph over the current centroids. This is a new class; QGKMeans and RaBitQKMeans keep their current behaviour.

  • Training: each iteration is one pass over the training vectors (an e-means epoch): a seeded shuffle, then fixed-size mini-batches; the batch size follows the batch-size law. Before every mini-batch the raw-vector centroid graph is rebuilt and searched for each vector's two nearest centroids. Centroids take an EMA mass-weighted step under the step law with a cosine schedule. The last iteration's means become the final centroids.
  • Revival: cost-based, as in current Faiss. Each centroid tracks a removal cost (a decaying average of d2 − d1 over its vectors) and a long axis (Oja's rule). Every five mini-batches, centroids whose cost is at most zero or below 0.3 × the median move, cheapest first, to split the centroid with the longest axis, for as long as the split's expected gain exceeds the cost. A centroid split in the last iteration closes from the vectors it receives after the split. Faiss's optional closing handover is not implemented, so this matches Faiss with closing_handover=False. Split, updated and closing coordinates stay within the bound train and assign accept, so a trained model always assigns.
  • API: the same as the other clustering classes: train, train_centroids, assign, centroids, assignments, distances, iteration_stats (one entry per iteration) and final_obj. final_assignment is 'approximate' by default, or 'exact'. A failed train keeps the previous results, and results are identical for any thread count. assign searches the same kind of graph as training, so it reproduces the training labels.
  • Parameters: niter=8, batch_size=0 (use the batch-size law), max_degree=32, ef_construction=240, ef_search=16 (at least 2, since each search returns the two nearest centroids), graph_build_iterations=1, seed, num_threads, verbose. Names follow QGKMeans (niter, max_degree, ef_construction, ...), in C++ and Python alike, so there are no deprecated aliases; batch_size is the only new one.
  • Structure: it mirrors QGKMeans. detail/emeans.hpp holds EMeans<Parameters, Assignment>, the counterpart of LloydKMeans: the training loop, API, validation and final assignment over a pluggable assignment. qgemeans.hpp holds the parameters and the SymphonyQG plug-in, QGEAssignment, and QGEMeans is a two-constructor class on top, like QGKMeans. The plug-in contract follows LloydKMeans (kName, ModelState, assign_with_state, ...) and adds prepare, a top-2 assign_batch over the batch's row indices, and end_pass, so a later RaBitQ e-means only needs its own plug-in.
  • No changes to existing clustering code: qgkmeans.hpp, detail/kmeans.hpp and their tests are identical to main. QGEMeans carries its own copy of the centroid-graph assigner and graph cache (in qgemeans.hpp) and of the Lloyd parameter checks (in detail/emeans.hpp). This duplicates some code once, in exchange for a diff that leaves QGKMeans untouched; the copies can be merged in a follow-up.
  • Also included: a sample (bin/qgemeans), C++ and Python tests, the type stub, and docs in clustering.md.

Benchmark

Seed 42, Xeon Gold 6418H, GCC 14 -march=native, one thread pinned to an idle physical core, one run of each. The machine is shared: the GIST1M runs started while other users' jobs were running, so their times may be somewhat inflated.

GIST1M, k = 4096:

Method Train time Exact WCSS Recall@10 Imbalance
QGKMeans, 25 iterations 215.2 s 1.03471e6 0.8159 1.413
QGKMeans, 8 iterations 81.1 s 1.04032e6 0.8108 1.427
QGEMeans, 8 iterations 157.7 s (1.36× faster than 25 iterations) 1.02790e6 (−0.66%) 0.8345 1.503

SIFT1M, k = 2048:

Method Train time Exact WCSS Recall@10 Imbalance
QGKMeans, 25 iterations 94.3 s 4.74279e10 0.9198 1.098
QGKMeans, 8 iterations 33.3 s 4.78449e10 0.9156 1.119
QGEMeans, 8 iterations 53.4 s (1.77× faster than 25 iterations) 4.72418e10 (−0.39%) 0.9244 1.107
  • Compared with the earlier mass-based revival on GIST1M (150 s, WCSS 1.03166e6, recall 0.8185, imbalance 1.257), cost-based revival lowers WCSS by 0.36% and raises recall by 0.016. Imbalance rises from 1.26 to 1.50: cost revival keeps cheap small clusters that the mass rule used to revive. On SIFT1M the imbalance stays close to QGKMeans.
  • Recall@10 varies by about ±0.01 across seeds, so WCSS is the main comparison.
  • With 8 threads pinned to physical cores, QGEMeans trains SIFT1M in 8.8 s, with centroids and labels byte-identical to the one-thread run. A full 8-thread comparison will be added.

Next: quantized graph build

I'm working on a quantized (8-bit, AVX-512 VNNI) SymphonyQG graph build. On a full GIST1M index it cuts build time from 31.8 s to 19.4 s at 48 threads, and from 662 s to 407 s on one thread, with recall within noise. QGEMeans rebuilds its centroid graph before every mini-batch, so a faster build should lower its total time further. That will come as a follow-up PR once this one is merged.

Checks

  • clang-format and full clang-tidy.
  • The C++ suite: 660 tests (one skipped by design), including 29 QGEMeans tests.
  • The installed CMake consumer test.
  • The Python suite: 1253 passed, 4 skipped, plus the mypy editor checks.
  • Ruff and the unit tests of .github/scripts, for the workflow test-name update.
  • mkdocs build --strict.
  • Not run: Pyright, which is not installed locally; CI runs it.

@gouyt13

gouyt13 commented Nov 21, 2026

Copy link
Copy Markdown
Member

Thanks for the proposal! 0.9 is in its final release steps, so we're holding new features until it lands on main. Once it does, could you rebase this branch onto the new main? It starts from main before the 0.9 work, and a trial merge with dev/0.9 conflicts in seven files. The main one is qgkmeans.hpp: on dev/0.9, QGAssigner rejects METRIC_COSINE (#256), the QGKMeans parameters are renamed (#233), and the k-means coordinate bound changed (#249). So the moved qg_assigner.hpp needs to start from the 0.9 version.

After the rebase we'll review it in full. In case you want to prepare, we'll check:

  • that QGKMeans and RaBitQKMeans give the same results as before the shared-helper refactor;
  • the benchmark on a second dataset, with the exact commands;
  • the e-means references (the paper and the Faiss contrib code) for the constants you use.

@gouyt13

gouyt13 commented Nov 23, 2026

Copy link
Copy Markdown
Member

0.9.0 is now on main (v0.9.0). Could you rebase this branch onto the current main when you have time? The notes in my previous comment still apply, especially starting the moved qg_assigner.hpp from the 0.9 version. Then we'll do the full review.

@TamimEhsan
TamimEhsan marked this pull request as ready for review November 28, 2026 14:18
@TamimEhsan
TamimEhsan requested a review from gouyt13 as a code owner November 28, 2026 14:18
@gouyt13

gouyt13 commented Nov 30, 2026

Copy link
Copy Markdown
Member

Thanks for the rebase. I checked 0c72848 against Faiss contrib/e_means at b14b3d693, and the update and revival rules match. My SIFT1M rerun reproduces your WCSS numbers, with the same result on 1 and 8 threads. Before this can merge, one change is needed:

Share the centroid-graph assigner instead of copying it. qgemeans.hpp copies QGAssigner, QuerySumCache and the graph cache, and detail/emeans.hpp copies the Lloyd validation. Recent fixes (#233, #249, #256) went into exactly this code, so with two copies every fix has to be made twice. Please:

  • move the assigner into a shared detail header, starting from main's version, with a result count (1 or 2) and an optional second-distance output;
  • make the Lloyd checks free functions in detail/kmeans.hpp that both classes call;
  • show that QGKMeans output is byte-identical to main for fixed seeds, both raw and quantized, with hints on and off.

Two small doc fixes:

  • detail/emeans.hpp:678 promises that ties go to the lower ID, which the graph search doesn't guarantee. Line 323, "in the reference's draw order", implies values that match Faiss, but only the distribution does.
  • clustering.md should say that the last iteration matches Faiss with closing_handover=False, which is not Faiss's default.

@TamimEhsan

Copy link
Copy Markdown
Member Author

Thanks for the review.

Done:

  • Shared assigner (137781f): QGAssigner, QuerySumCache and the centroid graph cache now live once in clustering/detail/qg_assigner.hpp, starting from main's version. Each search returns 1 or 2 results, with an optional second-distance output and an optional row index for mini-batches. qgkmeans::QGAssigner keeps its public constructor, assign(), clear_hints() and messages. qgemeans.hpp dropped from 541 to 164 lines.
  • Lloyd checks (fee8d16): validate_points, validate_common_parameters, assign_trained and assign_with_mode are free functions in detail/kmeans.hpp, called by both LloydKMeans and EMeans. All error messages are unchanged.
  • Byte identity at fixed seeds. Data: synthetic 128-d, 50k SIFT and 20k GIST. Settings: nbits 32/4/8, L2 and spherical, Approximate and Exact final assignment, with and without sampling. QGAssigner was also run directly with hints on and off, and with and without the query-sum cache.
    • QGKMeans vs main: 144/144 single-thread cases identical. At 8 threads, the direct assigner (k=200) is identical in 48/48 cases.
    • QGEMeans vs the previous branch head: 16/16 identical at 1 thread and 16/16 at 8 threads.
    • RaBitQKMeans: 16/16 identical at 1 thread.
    • QGKMeans and RaBitQKMeans training at 8 threads doesn't give the same bytes twice even on main, so identity there can't be shown byte for byte. This predates the change, and I can look into it separately.
  • Docs (6979833): the "ties to the lower ID" promise is removed. The initial-axes comment now says it matches the reference's distribution, not its values. clustering.md says the last iteration matches closing_handover=False, which is not the default.

Also: QGEMeans now only allocates the query-sum cache when a row is searched more than once, and a new test covers the row index together with the cache at d=512.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants