Skip to content

feat(clustering): add opt-in max_rebuild_gap to QGEMeans - #267

Draft
TamimEhsan wants to merge 6 commits into
VectorDB-NTU:mainfrom
TamimEhsan:qgemeans-rebuild-gap
Draft

TamimEhsan wants to merge 6 commits into
VectorDB-NTU:mainfrom
TamimEhsan:qgemeans-rebuild-gap

Conversation

@TamimEhsan

Copy link
Copy Markdown
Member

Summary

QGEMeans rebuilds its SymphonyQG centroid graph before every mini-batch. On Cohere 10M (k = 40,000) the rebuilds take about two thirds of training time. Late in training the centroids move little, so consecutive graphs are nearly the same: the share of each centroid's edges that survive from one batch's graph to the next rises from about 0.7 at the start to 0.95 at the end.

This PR adds max_rebuild_gap to QGEMeansParameters (Python: QGEMeans(..., max_rebuild_gap=...)), the largest number of mini-batches between graph rebuilds.

  • Default 1: rebuild before every mini-batch. Results are bit-identical to main.
  • Above 1:
    • Schedule: the graph is still rebuilt before every mini-batch for the first quarter of the run. After that, the gap between rebuilds grows linearly to max_rebuild_gap at the end.
    • Between rebuilds: the graph is refreshed. It keeps its edges, and its vertices, neighbour codes and entry point move to the current centroids (new QGBuilder::refresh).
    • Revival: a due revival waits until the mini-batch before the next rebuild. Kept edges cannot follow revival's long moves.
    • Final assignment: always uses a freshly built graph.

API: one new field and keyword argument with a backward-compatible default. There are no saved-format or dependency changes.

Changes:

  • QGBuilder::refresh(const float*): re-encodes every row's neighbour codes for the new vertex positions and re-picks the entry point as a build does.
    • Input: validated like reset; null and non-finite data raise std::invalid_argument.
    • Refused: an unbuilt or quantized graph raises std::logic_error.
    • On failure: leaves the graph unready.
  • GraphSchedule and rebuild_gap in clustering/detail/emeans.hpp decide between rebuild and refresh before each step, and when revival runs. The e-means Assignment interface gains refresh(centroids).
  • QGEMeans validates max_rebuild_gap >= 1 ("QGEMeans max_rebuild_gap must be positive").
  • Bindings, __init__.pyi, docstrings and docs/docs/clustering.md document the option and the schedule.

Benchmark

Seed 42, Xeon Gold 6418H, GCC 14 -march=native, one run of each. The machine is shared, so times vary between runs.

GIST1M, k = 4096, measured as in #261: one thread pinned to an idle physical core, exact WCSS (total), Recall@10 with 1% probes (40 clusters). The default row reproduces #261's QGEMeans quality exactly. All times here are 9–23% above #261's because of other users' load (load average 8–21), but the four runs share the same conditions.

Method Train time Exact WCSS Recall@10 Imbalance
QGKMeans, 25 iterations 265.4 s 1.03471e6 0.8159 1.413
QGEMeans, 8 iterations, max_rebuild_gap=1 (default) 171.8 s (1.54× faster than QGKMeans) 1.02790e6 (−0.66%) 0.8345 1.503
QGEMeans, 8 iterations, max_rebuild_gap=8 148.4 s (1.79×) 1.02810e6 (−0.64%) 0.8379 1.497
QGEMeans, 8 iterations, max_rebuild_gap=16 143.5 s (1.85×) 1.02809e6 (−0.64%) 0.8417 1.494

The Cohere runs below use 16 threads pinned to one socket with numactl, and the earlier protocol: WCSS per point from the trainer's labels, and Recall@100 at an equal number of vectors scanned (each query probes its nearest centroids until it has scanned N vectors; 1,000 queries).

Cohere 10M (768-d, VectorDBBench cohere_large_10m), k = 40000, 2 iterations:

Method Train time WCSS Recall@100 at 100k scanned Imbalance
QGEMeans, max_rebuild_gap=1 (default) 123.8 s 38.1393 0.9415 1.414
QGEMeans, max_rebuild_gap=16 70.6 s (1.75× faster) 38.1449 (+0.015%) 0.9430 1.416

Cohere 10M, k = 40000, 8 iterations:

Method Train time WCSS Recall@100 at 100k scanned Imbalance
QGEMeans, max_rebuild_gap=1 (default) 182.3 s 37.9735 0.9430 1.461
QGEMeans, max_rebuild_gap=16 132.8 s (1.37× faster) 37.9799 (+0.017%) 0.9431 1.458
  • On GIST1M gap 8 and gap 16 are 1.16× and 1.20× faster than gap 1. WCSS rises by 0.02% and Recall@10 by 0.003–0.007, within feat(clustering): add QGEMeans, mini-batch e-means with SymphonyQG assignment #261's ±0.01 seed spread. On Cohere seed 1 (2 iterations), WCSS is 0.044% higher and recall 0.0006 lower; that run overlapped other jobs, so its time (77.5 s) is left out.
  • The gain shrinks with more iterations: the e-means batch-size law makes batches 4× larger at 8 iterations with about the same number of mini-batches (78 to 80 on Cohere), so rebuilds are a smaller share of each step.
  • Imbalance does not change. At 8 iterations gap 16 left 6 empty clusters of 40000, against 1 for gap 1 (one seed).

Design choices that were measured (prototype, GIST and Cohere, 2 passes):

  • Fixed gaps are worse than growing ones. A fixed gap of 4 cost measurable recall on GIST: early graphs change too much to reuse.
  • Linear and doubling growth match at the same number of rebuilds. Time depends only on the number of rebuilds, about 1.9 s each on Cohere.
  • Refreshing beats a stale graph. A stale graph would keep the old vertices and re-score only the two returned centroids. Refresh costs about 0.16 s on Cohere, against 1.9 s for a rebuild.
  • Delaying revival to the next rebuild brings GIST WCSS back to the gap-1 level (it was 0.02–0.05% higher without it) at no time cost.
  • Re-picking the entry point on refresh leaves 5 of 6 GIST runs bit-identical and costs no measurable time.

Testing

  • C++ (portable build, RABITQ_ENABLE_NATIVE_OPTIMIZATION=OFF): ctest --no-tests=error, 667 passed (1 skipped by design). New tests:
    • QgConstructionTest.RefreshMovesVerticesAndKeepsEdges: edges kept; stored vectors replaced; built rows reproduced by refreshing with the original vectors; entry point matches a fresh build over the moved vectors. Runs with and without the build cache, at d 65 and 1025, L2 and IP, on 1 and 3 threads.
    • QgConstructionTest.RefreshRejectsUnbuiltQuantizedAndInvalidInput.
    • QGEMeansRecipeTest.RebuildGapGrowsLinearlyAfterTheFirstQuarter and QGEMeansRecipeTest.RevivalWaitsForTheNextRebuild.
    • QGEMeansAssignmentTest.RefreshSearchesTheMovedCentroids: searches after a refresh return exact distances to the moved centroids.
    • QGEMeansTest.SpacedRebuildsAreDeterministicAndKeepTheObjective: identical results on 1 and 4 threads, objective within 2% of gap 1.
    • Default and validation checks.
    • Sabotage checks: each check was made to fail on purpose, and the new tests caught it. Making refresh a no-op, ignoring the gap, reviving every 5 steps regardless of rebuilds, and dropping the entry-point update each fail at least one new test.
  • Python: python -m pytest, 1255 passed, 4 skipped. New tests in tests/python/test_qgemeans.py cover the default, the keyword and cp setting, the error message, rejection of negative values, and determinism across thread counts.
  • Editor and type checks: tests/python/test_editor_support.py and tests/test_mypy.py pass; tests/python/typing/public_api.py uses the new keyword.
  • Formatting and docs: ./scripts/check-format.sh, ./scripts/check-python.sh, python -m mkdocs build --strict --config-file docs/mkdocs.yml and git diff --check are clean.
  • Focused clang-tidy (the recipe in docs/development.md) on src/index/qg_builder.cpp and python_bindings/kmeans_bindings.cpp: passed.

Not run:

  • Full pre-merge clang-tidy (CXX=clang++-23 ./scripts/check-tidy.sh build-tidy): to do before merge.
  • tests/test_pyright.py: pyright isn't installed in the test environment, and Node 24 is unavailable.

@github-actions github-actions Bot added the release:added Release category managed from the PR title label Dec 1, 2026

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

release:added Release category managed from the PR title

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant