Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ jobs:
tests/python/test_ivf.py::test_save_load_roundtrip
tests/python/test_hnsw.py::test_save_load_roundtrip
tests/python/test_symqg.py::test_save_load_roundtrip
tests/python/test_qgemeans.py::test_train_populates_outputs_per_epoch
tests/python/test_qgkmeans.py::test_train_populates_faiss_style_outputs
tests/python/test_rabitqkmeans.py::test_flat_parameters_and_outputs
- name: Install FAISS comparison dependency
Expand Down Expand Up @@ -148,5 +149,6 @@ jobs:
tests/python/test_ivf.py::test_save_load_roundtrip
tests/python/test_hnsw.py::test_save_load_roundtrip
tests/python/test_symqg.py::test_save_load_roundtrip
tests/python/test_qgemeans.py::test_train_populates_outputs_per_epoch
tests/python/test_qgkmeans.py::test_train_populates_faiss_style_outputs
tests/python/test_rabitqkmeans.py::test_flat_parameters_and_outputs
9 changes: 7 additions & 2 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ factors estimate L2 distance or inner product.
| `include/rabitqlib/fastscan/` | All 32-vector batch layouts, encoding adapters, packing, LUT/estimation and FastScan/HACC |
| `include/rabitqlib/core/types.hpp`, `core/detail/eigen.hpp` | Numerical configuration/types and internal Eigen aliases, respectively |
| `include/rabitqlib/index/types.hpp` | Point IDs and ANN candidate values; no Eigen dependency |
| `include/rabitqlib/clustering/` | RaBitQKMeans flat assignment, QGKMeans graph assignment, and shared Lloyd training |
| `include/rabitqlib/clustering/` | RaBitQKMeans flat assignment, QGKMeans graph assignment, shared Lloyd training, QGEMeans mini-batch e-means, and the `QGAssigner` centroid graph both graph methods use (`qg_assigner.hpp`) |
| `include/rabitqlib/index/{ivf,hnsw,symqg}/` | Index construction, persistence, and search |
| `include/rabitqlib/{core,fastscan,index}/detail/` | Module-owned implementation headers; no public stability promise |
| `src/core/` | Compiled stable core v1 API and provisional API implementations, and the frozen `faster_config` scale table |
Expand Down Expand Up @@ -1054,6 +1054,11 @@ backends.
Indexed float32 rows accumulate into float64 sums through the matrix backends, preserving
per-cluster point order without additional workspace.

**QGEMeans mini-batch updates**

Scalar float32 per-cluster sums in mini-batch member order, as the Faiss e-means reference;
objectives are summed per cluster, then in cluster order, so they do not depend on scheduling.

**HNSW-RaBitQ search and IVF-RaBitQ centroid routing**

Cached HNSW search selection; centroid routing uses the common raw-distance dispatcher.
Expand All @@ -1070,7 +1075,7 @@ caller-owned.

**Example KMeans training**

Explicit RaBitQKMeans flat or QGKMeans graph assignment; FAISS is an optional comparison
Explicit RaBitQKMeans flat, QGKMeans graph or QGEMeans mini-batch assignment; FAISS is an optional comparison
dependency only.

#### Portable builds and test coverage
Expand Down
84 changes: 67 additions & 17 deletions docs/docs/clustering.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# Clustering

RaBitQ Library provides two implementations of Lloyd's k-means. Both compute
centroid means from the original float32 data, accumulate in float64, and require
no external clustering package. Choose the class explicitly; neither switches
algorithms based on the cluster count.
RaBitQ Library provides two implementations of Lloyd's k-means and one of
mini-batch [e-means](#qgemeans). The Lloyd classes compute centroid means from
the original float32 data and accumulate in float64. None requires an external
clustering package. Choose the class explicitly; none switches algorithms based
on the cluster count.

For installation, see [Quick start](quick_start.md#install).

Expand All @@ -21,17 +22,19 @@ per centroid; the classes below default to training on every vector.
| --- | --- | --- | --- |
| [RaBitQKMeans](#rabitqkmeans) | Flat RaBitQ scan | Small cluster counts | `n >= k >= 1` |
| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (C++ `graph_degree`; default 32) |
| [QGEMeans](#qgemeans) | SymphonyQG centroid graph, per mini-batch | Larger cluster counts, fewer passes over the data | `n >= k > max_degree` (C++ `graph_degree`; default 32) |

## Python

Both classes have the same training and result interface:
All three classes have the same training and result interface:

```python
from rabitqlib import QGKMeans, RaBitQKMeans
from rabitqlib import QGEMeans, QGKMeans, RaBitQKMeans

kmeans = RaBitQKMeans(d, 16, niter=25, num_threads=8)
# For larger cluster counts, use instead:
# kmeans = QGKMeans(d, 4096, niter=25, num_threads=8)
# kmeans = QGEMeans(d, 4096, epochs=8, num_threads=8)
last_iteration_obj = kmeans.train(x)

centroids = kmeans.centroids # shape (k, d)
Expand All @@ -52,14 +55,16 @@ Link that target; a core-only installation does not include clustering headers.

```cpp
#include <rabitqlib/clustering/rabitqkmeans.hpp>
#include <rabitqlib/clustering/qgemeans.hpp>
#include <rabitqlib/clustering/qgkmeans.hpp>

rabitqlib::rabitqkmeans::RaBitQKMeansParameters parameters;
parameters.niter = 25;
parameters.num_threads = 8;
rabitqlib::rabitqkmeans::RaBitQKMeans kmeans(dimension, 16, parameters);

// For graph assignment, use qgkmeans::QGKMeansParameters and qgkmeans::QGKMeans.
// For graph assignment, use qgkmeans::QGKMeansParameters and qgkmeans::QGKMeans,
// or qgemeans::QGEMeansParameters and qgemeans::QGEMeans.
kmeans.train(num_points, data); // row-major float32 input

const auto& centroids = kmeans.centroids;
Expand All @@ -74,22 +79,27 @@ kmeans.assign(num_queries, queries, query_assignments.data(), query_distances.da
```

Complete examples: [RaBitQKMeans](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/rabitqkmeans.cpp)
(`bin/rabitqkmeans`) and [QGKMeans](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/qgkmeans.cpp)
(`bin/qgkmeans`). Run either without arguments for a synthetic demo, or save
(`bin/rabitqkmeans`), [QGKMeans](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/qgkmeans.cpp)
(`bin/qgkmeans`) and [QGEMeans](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/qgemeans.cpp)
(`bin/qgemeans`). Run any of them without arguments for a synthetic demo, or save
clusters for the C++ indexing examples:

```bash
./bin/qgkmeans data.fvecs 4096 centroids.fvecs labels.ivecs
./bin/qgemeans data.fvecs 4096 centroids.fvecs labels.ivecs
./bin/rabitqkmeans data.fvecs 16 centroids.fvecs labels.ivecs
```

File mode uses exact final assignment and the default training parameters.
Append `ip` for spherical clustering of normalized input; the default is `l2`.
For the Lloyd examples, append `ip` for spherical clustering of normalized
input; the default is `l2`.
`sample/run_cpp.sh` runs the C++ clustering and indexing workflow without Python.

## Parameters and input

Set Python keyword arguments or fields of the corresponding C++ parameter type:
Set Python keyword arguments or fields of the corresponding C++ parameter type.
QGEMeans takes `num_threads`, `seed`, `verbose` and `final_assignment` from this
table; its other parameters are listed [with the method](#qgemeans).

| Parameter | Default | Meaning |
| --- | --- | --- |
Expand Down Expand Up @@ -182,10 +192,48 @@ Python those names still work, with a `DeprecationWarning`, until 0.9.
| `graph_build_iterations` | `1` | PiPNN initialization followed by one refinement; values ≥2 request that many graph passes, ending in refinement. Independent of `niter`. |

The seed also controls fallback neighbors; PiPNN uses fixed internal seeds.
`QGAssigner` in `qgkmeans.hpp` supports repeated vector-to-centroid assignment
`QGAssigner` in `qg_assigner.hpp` (also included by `qgkmeans.hpp`) supports repeated vector-to-centroid assignment
without the clustering loop. To assign vectors with trained QGKMeans centroids,
use [`assign`](#assign-new-vectors).

### QGEMeans

QGEMeans runs mini-batch e-means (Algorithm 1 of
[arXiv:2611.09501](https://arxiv.org/abs/2611.09501), with the constants of the
Faiss reference implementation in `faiss/contrib/e_means`) and assigns each
mini-batch through a SymphonyQG graph over the current centroids. It starts
from `k` distinct random training vectors chosen by `seed`. Each epoch visits
the vectors in a seeded random order, in mini-batches. Before every mini-batch
the raw-vector centroid graph is rebuilt and searched for each vector's nearest
centroid, without search hints. Each centroid then moves toward its mini-batch
mean, weighted by its batch count against an exponentially decaying mass.
Every fifth mini-batch, centroids whose mass falls below a tenth of the mean
are replaced by splitting heavier centroids, drawn in proportion to their mass.
The step size follows the e-means step law and a cosine schedule that decays to
a tenth of its initial value. After the last epoch, each centroid assigned in
that epoch becomes the mean of its last-epoch vectors.

| Parameter | Default | Meaning |
| --- | --- | --- |
| `epochs` | `8` | Positive number of passes over the training vectors. |
| `batch_size` | `0` | Vectors per mini-batch, capped at `n`; `0` selects the e-means batch-size law, a power of two of at most `n / 2`. |
| `max_degree` | `32` | A positive multiple of 32, strictly smaller than `k`. C++ `graph_degree`. |
| `ef_construction`, `ef_search` | `240`, `16` | Positive graph construction and search window sizes. C++ `ef_build`, `ef_search`. |
| `graph_build_iterations` | `1` | As for QGKMeans. |

Python uses these names from the start; there are no deprecated aliases. The
centroid graph always stores raw float32 centroids, and QGEMeans has no
`spherical`, sampling or early-stop setting. Mini-batch sums accumulate in
float32, as in the Faiss reference.

`obj` and `iteration_stats` have one entry per epoch: `obj` sums the mini-batch
assignment distances of that epoch, each measured before that mini-batch's
update; `shift` is the squared centroid displacement over the epoch; and
`nsplit` counts revived centroids. Python `train()` returns the last epoch's
`obj`. `train()` then assigns all vectors to the final centroids with
`final_assignment`: `'approximate'` searches a graph rebuilt over them, and
`'exact'` uses the exhaustive assignment described below.

## Results and final assignment

Python result properties are `None` until a successful fit; a failed fit
Expand All @@ -198,13 +246,14 @@ their sum (WCSS); spherical mode sums `1 - inner_product`. `obj` and
`train()` returns the last such objective.

`final_assignment='approximate'` (default) uses the selected class's assignment
algorithm. Labels need not identify the exact nearest centroids, but reported
algorithm. QGEMeans `obj` and `iteration_stats` are per epoch, as described
[with the method](#qgemeans). Labels need not identify the exact nearest centroids, but reported
distances and WCSS remain exact for those labels. Without sampling, quantized
QGKMeans final assignment retains a point's last-iteration label when it is
closer. After sampling, most points have no such label, so every point uses the
same graph search. Approximate training objectives need not decrease monotonically.

To require exact nearest-centroid **final** assignments with either class:
To require exact nearest-centroid **final** assignments with any class:

```python
from rabitqlib import RaBitQKMeans
Expand All @@ -219,8 +268,9 @@ are still accepted until 0.9, and `cp.final_assignment` reads back as a member
until then; importing `FinalAssignmentMode` raises a `DeprecationWarning`.

In C++, set `parameters.final_assignment` to
`rabitqlib::rabitqkmeans::FinalAssignmentMode::Exact` or
`rabitqlib::qgkmeans::FinalAssignmentMode::Exact`; both names refer to the same
`rabitqlib::rabitqkmeans::FinalAssignmentMode::Exact`,
`rabitqlib::qgkmeans::FinalAssignmentMode::Exact` or
`rabitqlib::qgemeans::FinalAssignmentMode::Exact`; all three name the same
enum. Training still uses the selected approximate assignment algorithm.

Exact final assignment screens all centroids with blocked GEMM and refines
Expand All @@ -247,7 +297,7 @@ C++ callers that change `centroids` or graph parameters cause one rebuild on
the next call. Each call still validates the `k * d` centroid coordinates.

For the training vectors, `assign` reproduces `assignments` and `distances`
with exact final assignment, for RaBitQKMeans, and whenever training
with exact final assignment, for RaBitQKMeans and QGEMeans, and whenever training
sampled the input, because the sampled final pass is the same assignment.
Unsampled approximate QGKMeans training also uses previous labels as graph
search hints, so its final labels can differ.
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ For input shapes, distance conventions, memory estimates, and threading, see
- **Bring your own storage:** use the [stable C++ core API](rabitq/core_api.md)
to encode vectors and estimate distances in caller-owned buffers. Add
[FastScan](cpp_integration.md#fastscan-integration) for batch scoring.
- **Train clusters:** use [RaBitQKMeans or QGKMeans](clustering.md) to prepare
- **Train clusters:** use [RaBitQKMeans, QGKMeans or QGEMeans](clustering.md) to prepare
centroids and assignments for IVF-RaBitQ or HNSW-RaBitQ.

## Compare measured performance
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/quick_start.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,6 @@ See [file compatibility](index/usage.md#index-file-compatibility) before downgra
- [IVF-RaBitQ](index/ivf.md): raw-vector reranking, precision, centroid routing and updates.
- [HNSW-RaBitQ](index/hnsw.md) and [SymphonyQG](index/qg.md): graph-index workflows and parameters.
- [Index usage contracts](index/usage.md): counts, threading, input lifetimes and file paths.
- [Clustering](clustering.md): choose flat RaBitQKMeans or graph-based QGKMeans.
- [Clustering](clustering.md): choose flat RaBitQKMeans, graph-based QGKMeans or mini-batch QGEMeans.
- [C++ integration](cpp_integration.md): builds, installation and component selection.
- [Stable core API](rabitq/core_api.md): integrate quantization into your own storage.
Loading
Loading