diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index cc439598..d0669e2e 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -152,11 +152,18 @@ require the full [static analysis check](../docs/development.md#static-analysis)
Tests and examples are intentionally excluded from CI clang-tidy; use focused
local analysis for substantial logic changes.
For a first contribution, the formatting check and the affected tests are
-enough to open a PR. If a check needs a tool, compiler or CPU you do not have
-(for example clang-tidy 23 or a particular SIMD instruction set), say so in the
-PR and a maintainer will run it. See [CI routing](../docs/maintaining.md#checks-selected-by-changed-files)
+enough to open a PR. Code PRs must be built and tested locally: CI does not
+replace building the code you change and running its affected tests. If another
+check needs a tool, compiler or CPU you do not have (for example clang-tidy 23 or
+a particular SIMD instruction set), say so in the PR and a maintainer will run it.
+See [CI routing](../docs/maintaining.md#checks-selected-by-changed-files)
for details.
+You are responsible for every change you submit, including changes produced
+with automated tools: verify it yourself, report the results, and respond to
+review. Code PRs that were not built and tested locally, or that are updated
+without addressing review feedback, are closed.
+
## If setup fails
| Problem | What to check |
@@ -184,7 +191,9 @@ are small, self-contained tasks that say where to start and when they are done;
[help wanted](https://github.com/VectorDB-NTU/RaBitQ-Library/labels/help%20wanted)
issues are larger. The [roadmap issue](https://github.com/VectorDB-NTU/RaBitQ-Library/issues/220)
lists the goals for the next releases. Comment on an issue before starting so work
-is not duplicated.
+is not duplicated. When claiming a code issue, say how you will verify the change
+locally, such as the tests or benchmark you will run. A maintainer may unassign an
+issue when review feedback goes unanswered.
## Feedback and further reading
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 62d257c5..1c1d2e72 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.20)
-project(RaBitQLib VERSION 0.8.4 LANGUAGES CXX)
+project(RaBitQLib VERSION 0.8.5 LANGUAGES CXX)
include(CMakePackageConfigHelpers)
include(GNUInstallDirs)
diff --git a/README.md b/README.md
index 6dee7017..b890bbcc 100644
--- a/README.md
+++ b/README.md
@@ -27,14 +27,14 @@ approximate nearest-neighbor search. See the [research papers](https://vectordb-
## News
+- **v0.8.5:** accepts the names 0.9 will use (`capacity`, `routing`, `ef_search`,
+ k-means `nbits`) and deprecates the 0.8 spellings they replace
+ ([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.5/)).
- **v0.8.4:** input validation reads each batch once instead of twice
([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.4/)).
- **v0.8.3:** provisional `rabitqlib.quant` module: rotate, quantize, pack and score
RaBitQ codes stored outside an index
([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.3/)).
-- **v0.8.2:** three lines to an index: the first `add` trains, `nbits` defaults to 7
- and search settings are optional; faster IVF-RaBitQ `add`
- ([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.2/)).
Earlier versions: [all releases](https://github.com/VectorDB-NTU/RaBitQ-Library/releases).
@@ -62,7 +62,7 @@ settings, and limitations.
### Python
```bash
-python -m pip install --upgrade "rabitqlib>=0.8.4"
+python -m pip install --upgrade "rabitqlib>=0.8.5"
```
Wheels support CPython 3.11–3.14 on Linux x86-64/ARM64, Windows x86-64,
diff --git a/benchmarks/run.py b/benchmarks/run.py
index ee770e59..d7565be5 100644
--- a/benchmarks/run.py
+++ b/benchmarks/run.py
@@ -120,7 +120,7 @@ def build_index(cfg, base, path):
from rabitqlib import IvfIndex
# The library's default training: QGKMeans above 2,000 clusters, then add
- # routes each vector with the index's centroid initializer.
+ # routes each vector with the index's routing strategy.
index = IvfIndex(
dim, cfg["nlist"], nbits=cfg["bits"], metric=cfg["metric"], seed=42
)
@@ -141,7 +141,7 @@ def build_index(cfg, base, path):
"assignment": "add routing",
}
elif method == "rabitq-hnsw":
- from rabitqlib import FinalAssignmentMode, HnswIndex, RaBitQKMeans
+ from rabitqlib import HnswIndex, RaBitQKMeans
cluster_count = cfg["hnsw_clusters"]
kmeans = RaBitQKMeans(
@@ -152,7 +152,7 @@ def build_index(cfg, base, path):
spherical=cfg["metric"] == "ip",
seed=42,
min_points_per_centroid=1,
- final_assignment=FinalAssignmentMode.Exact,
+ final_assignment="exact",
)
stage_start = time.perf_counter()
kmeans.train(base)
@@ -167,7 +167,7 @@ def build_index(cfg, base, path):
metric=cfg["metric"],
seed=42,
)
- index.resize(n)
+ index.reserve(n)
index.set_centroids(kmeans.centroids)
index.add(base, cluster_ids=kmeans.assignments, num_threads=cfg["threads"])
indexing_s = time.perf_counter() - stage_start
@@ -259,7 +259,9 @@ def search(index, cfg, queries, threads):
if method == "rabitq-ivf":
return index.search(queries, k=k, nprobe=cfg["nprobe"], num_threads=threads)
if method in ("rabitq-hnsw", "rabitq-symqg"):
- return index.search(queries, k=k, ef=cfg["ef_search"], num_threads=threads)
+ return index.search(
+ queries, k=k, ef_search=cfg["ef_search"], num_threads=threads
+ )
raise ValueError(f"unsupported benchmark method: {method}")
diff --git a/benchmarks/run_kmeans.py b/benchmarks/run_kmeans.py
index f956f7f6..3a3c775d 100644
--- a/benchmarks/run_kmeans.py
+++ b/benchmarks/run_kmeans.py
@@ -64,7 +64,7 @@ def load_base(cfg):
def train_python(method, x, k, threads, seed):
if method == "qgkmeans":
- from rabitqlib import FinalAssignmentMode, QGKMeans
+ from rabitqlib import QGKMeans
start = time.perf_counter()
model = QGKMeans(
@@ -74,13 +74,13 @@ def train_python(method, x, k, threads, seed):
num_threads=threads,
seed=seed,
spherical=False,
- quantization_bits=0,
- graph_degree=32,
- ef_build=240,
+ nbits=32,
+ max_degree=32,
+ ef_construction=240,
ef_search=16,
graph_build_iterations=1,
early_stop_threshold=0.0,
- final_assignment=FinalAssignmentMode.Exact,
+ final_assignment="exact",
)
model.train(x)
total = time.perf_counter() - start
diff --git a/docs/development.md b/docs/development.md
index 7deda505..c1618824 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -700,9 +700,13 @@ of 32. These settings are not interchangeable.
Public names and Python keywords are compatibility contracts. For example,
`Cluster::num()`, the protected `Initializer::num_cluster_`, QG's
-`degree_bound()`/`set_ef()`, Python's `ef`, and `QGKMeansParameters::ef_build`
+`degree_bound()`/`set_ef()` and `QGKMeansParameters::ef_build`
retain their existing spellings, as do the Python vocabulary `random_seed`/`seed`,
-`train`/`build`, `obj`, `nsplit`, `final_obj` and `niter`. C++ parameter names may be clarified without
+`train`/`build`, `obj`, `nsplit`, `final_obj` and `niter`. Python's search breadth is
+`ef_search` since 0.8.5; `ef` is deprecated and removed in 0.9 (#232). Python's `QGKMeans`
+and `QGKMeansParameters` take `nbits`, `max_degree` and `ef_construction` since 0.8.5;
+`quantization_bits`, `graph_degree` and `ef_build` are deprecated there and removed in
+0.9 (#233), while the C++ struct keeps them until 0.9. C++ parameter names may be clarified without
changing types, order or defaults. Keep declarations, definitions and comments
in agreement; do not rename methods or literals by textual substitution.
diff --git a/docs/docs/benchmarks/kmeans.md b/docs/docs/benchmarks/kmeans.md
index 189e4340..0afd9bad 100644
--- a/docs/docs/benchmarks/kmeans.md
+++ b/docs/docs/benchmarks/kmeans.md
@@ -49,7 +49,7 @@ search. Centroids are not normalized.
| Method | Additional settings |
| --- | --- |
-| `rabitqlib.QGKMeans` | `quantization_bits=0`, degree 32, `ef_build=240`, `ef_search=16`, one graph refinement, `early_stop_threshold=0`, `FinalAssignmentMode.Exact` |
+| `rabitqlib.QGKMeans` | raw centroid storage (`nbits=32`; `quantization_bits=0` before 0.8.5), degree 32, `ef_construction=240` (`ef_build` before 0.8.5), `ef_search=16`, one graph refinement, `early_stop_threshold=0`, exact final assignment |
| `faiss.Kmeans` | CPU, `nredo=1`, `max_points_per_centroid=N`, `spherical=False`, `early_stop_threshold=0`; exact final `index.search(x, 1)` |
| `superkmeans.SuperKMeans` | v0.2.0, `quantizer="f32"`, `hierarchical=False`, `sampling_fraction=1`, `angular=False`, `use_blas_only=False`, `early_termination=True`, `tol=1e-4`; exact final `assign(x, centroids)` |
diff --git a/docs/docs/clustering.md b/docs/docs/clustering.md
index 9c7b162e..26f85ec7 100644
--- a/docs/docs/clustering.md
+++ b/docs/docs/clustering.md
@@ -20,7 +20,7 @@ per centroid; the classes below default to training on every vector.
| Class | Assignment | Recommended use | Cluster count |
| --- | --- | --- | --- |
| [RaBitQKMeans](#rabitqkmeans) | Flat RaBitQ scan | Small cluster counts | `n >= k >= 1` |
-| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > graph_degree` (default 32) |
+| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (C++ `graph_degree`; default 32) |
## Python
@@ -101,7 +101,7 @@ Set Python keyword arguments or fields of the corresponding C++ parameter type:
| `min_points_per_centroid` | `39` | Warn below this training-points-per-centroid ratio when verbose. |
| `max_points_per_centroid` | `0` | When positive, train on a random sample above `k * max_points_per_centroid` vectors; `0` trains on all vectors. See [sampling](#training-set-sampling). |
| `verbose` | `false` | Print training progress and warnings. |
-| `final_assignment` | `Approximate` | Use the selected method for final labels, or `Exact` for nearest-centroid labels. |
+| `final_assignment` | `'approximate'` (C++ `Approximate`) | Use the selected method for final labels, or `'exact'` (C++ `Exact`) for nearest-centroid labels. |
`num_threads` sets an upper limit, not a fixed worker count for every stage.
QGKMeans may use fewer workers to build small centroid graphs. That additional
@@ -164,18 +164,21 @@ encodes new vectors around it.
Each iteration compares every training point with every centroid. The batch size of 32
is not a cluster-count limit. This method uses one-bit point codes throughout;
-it has no graph parameters or `quantization_bits` setting.
+it has no graph parameters or `nbits` (C++ `quantization_bits`) setting.
### QGKMeans
QGKMeans builds a SymphonyQG graph over the centroids and uses previous
-assignments as search hints. Its additional parameters are:
+assignments as search hints. Its additional parameters are below, under their Python
+names since 0.8.5. C++ and Python before 0.8.5 name the first three
+`quantization_bits` (with `0` for raw storage), `graph_degree` and `ef_build`; in
+Python those names still work, with a `DeprecationWarning`, until 0.9.
| Parameter | Default | Meaning |
| --- | --- | --- |
-| `quantization_bits` | `0` | Graph centroid storage: raw, or `4`/`8` bits. |
-| `graph_degree` | `32` | A positive multiple of 32, strictly smaller than `k`. |
-| `ef_build`, `ef_search` | `240`, `16` | Positive graph construction and search window sizes. |
+| `nbits` | `32` | Graph centroid storage: `32` for raw vectors, or `4`/`8` bits. |
+| `max_degree` | `32` | A positive multiple of 32, strictly smaller than `k`. |
+| `ef_construction`, `ef_search` | `240`, `16` | Positive graph construction and search window sizes. |
| `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.
@@ -194,9 +197,8 @@ their sum (WCSS); spherical mode sums `1 - inner_product`. `obj` and
`iteration_stats` record objectives before each centroid update; Python
`train()` returns the last such objective.
-`FinalAssignmentMode.Approximate` (default) uses the selected class's assignment
-algorithm. The legacy name `FinalAssignmentMode.SymphonyQG` remains an alias for
-`Approximate`. Labels need not identify the exact nearest centroids, but reported
+`final_assignment='approximate'` (default) uses the selected class's assignment
+algorithm. 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
@@ -205,12 +207,17 @@ same graph search. Approximate training objectives need not decrease monotonical
To require exact nearest-centroid **final** assignments with either class:
```python
-from rabitqlib import FinalAssignmentMode, RaBitQKMeans
+from rabitqlib import RaBitQKMeans
-kmeans = RaBitQKMeans(d, 16, final_assignment=FinalAssignmentMode.Exact)
+kmeans = RaBitQKMeans(d, 16, final_assignment="exact")
kmeans.train(x)
```
+Python takes the strings `'approximate'` and `'exact'` since 0.8.5. The
+`FinalAssignmentMode` members `Approximate`, `Exact` and the legacy alias `SymphonyQG`
+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
@@ -240,7 +247,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 `FinalAssignmentMode.Exact`, for RaBitQKMeans, and whenever training
+with exact final assignment, for RaBitQKMeans, 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.
diff --git a/docs/docs/cpp_integration.md b/docs/docs/cpp_integration.md
index 2961e043..686a490d 100644
--- a/docs/docs/cpp_integration.md
+++ b/docs/docs/cpp_integration.md
@@ -58,12 +58,12 @@ The core example is built as the `core_example` CMake target. For the GIST bench
The [core quantization v1 API](rabitq/core_api.md) has a C++ source-compatibility contract.
Other C++ APIs may evolve, and no cross-version C++ binary ABI is promised.
-Pin the `v0.8.4` release and include RaBitQ-Library as a Git submodule:
+Pin the `v0.8.5` release and include RaBitQ-Library as a Git submodule:
```bash
git submodule add https://github.com/VectorDB-NTU/RaBitQ-Library.git third_party/rabitqlib
git submodule update --init --recursive
-git -C third_party/rabitqlib checkout v0.8.4
+git -C third_party/rabitqlib checkout v0.8.5
git add third_party/rabitqlib
```
diff --git a/docs/docs/index.md b/docs/docs/index.md
index 160395c8..71a74a18 100644
--- a/docs/docs/index.md
+++ b/docs/docs/index.md
@@ -26,7 +26,7 @@ estimation into your own C++ search engine.
```bash
-python -m pip install "rabitqlib>=0.8.4"
+python -m pip install "rabitqlib>=0.8.5"
```
[Installation and supported platforms](installation.md) ·
@@ -112,5 +112,5 @@ on your own dataset when choosing an index.
## Explore further
- [Algorithm overview](rabitq/rabitq.md) for the rotation, encoding, and scoring workflow.
-- [RaBitQ Library 0.8.4 release notes](releases/0.8.4.md) for the latest changes and upgrade guidance.
+- [RaBitQ Library 0.8.5 release notes](releases/0.8.5.md) for the latest changes and upgrade guidance.
- [Papers and citations](papers.md) for the original RaBitQ method, its multi-bit extension, and SymphonyQG.
diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md
index 04ed8b26..45660c59 100644
--- a/docs/docs/index/hnsw.md
+++ b/docs/docs/index/hnsw.md
@@ -20,7 +20,7 @@ from rabitqlib import HnswIndex
index = HnswIndex(data.shape[1], M=16, ef_construction=100) # nbits=7 by default
index.add(data, num_threads=1) # trains 16 centroids, then links; 1 thread is reproducible
-ids, distances = index.search(queries, k=10) # ef defaults to max(k, 64)
+ids, distances = index.search(queries, k=10) # ef_search defaults to max(k, 64)
index.save("hnsw.index")
loaded = HnswIndex.load("hnsw.index")
```
@@ -70,9 +70,9 @@ see [C++ integration](../cpp_integration.md).
| `nbits` / C++ `total_bits` | 1–9 total bits including the sign bit. Python's keyword-only `nbits` defaults to 7; C++ requires it. Raw-vector storage is not supported. |
| `num_clusters` | Python keyword, default 16: centroids `train` or the first `add` learns, or `set_centroids` supplies; the first `add` caps it at its row count. |
| `M`, `ef_construction` | Graph connectivity and construction search budget; Python defaults are 16 and 200, and the index reports both as properties. `M` must be at least 2 and is capped at 10,000; `ef_construction` is raised to at least `M`. The base layer keeps up to `2 * M` edges per node. |
-| `metric`, `seed` | Python defaults are `"l2"` and 100; `"ip"` and [`"cosine"`](usage.md#the-cosine-metric) are also supported. `seed` was called `random_seed` before 0.8. |
-| `max_elements` | Python reports the current capacity, which `add` grows geometrically (at least doubling) and `resize` can preallocate. C++ `add` never grows it. |
-| `k`, `ef` | Positive result count and search window. `k` may exceed the stored point count; Python pads missing results, while C++ returns fewer pairs. Omitted, `None` or zero `ef` uses `max(k, 64)` in Python, positive `ef` is raised to at least `k`, and `ef` above the stored point count is clamped to it. |
+| `metric`, `seed` | Python defaults are `"l2"` and 100; `"ip"` and [`"cosine"`](usage.md#the-cosine-metric) are also supported. `seed` was called `random_seed` before 0.8. A seed is in `[0, 2**32 - 1]`; larger values are deprecated since 0.8.5, and 0.9 draws a seed when it is omitted. |
+| `capacity` (C++ `max_elements()`) | Python reports the current capacity, which `add` grows geometrically (at least doubling) and `reserve` can preallocate; they were named `max_elements` and `resize` before 0.8.5. C++ `add` never grows it. |
+| `k`, `ef_search` | Positive result count and search window. `k` may exceed the stored point count; Python pads missing results, while C++ returns fewer pairs. An omitted or `None` `ef_search` uses `max(k, 64)` in Python (0 does the same and is deprecated since 0.8.5), a smaller value is raised to at least `k`, and a value above the stored point count is clamped to it. Python named it `ef` before 0.8.5. |
`seed` controls graph levels and the FHT/Kac rotation (using its low 32 bits).
With identical inputs and parameters, single-threaded construction is reproducible
@@ -177,7 +177,7 @@ Python follows the shared [concurrency contract](usage.md#threading-and-file-pat
## Updating an index
-A constructed or loaded index supports `add()`, `resize()`,
+A constructed or loaded index supports `add()`, `resize()` (Python `reserve`),
and `remove()` without the original data; C++ also adds to a
[trained](#training-centroids-in-c) index. Adding points and resizing preserve
the index file format; files with removals have
@@ -233,8 +233,9 @@ records still occupy capacity.
C++ `add` never grows the index: it rejects a whole batch whose size exceeds
`max_elements() - num_stored_points()`, and `resize` is the only way to raise
-that. Python `add` calls `resize` first when the batch does not fit, to at least
-double the capacity. Reserving capacity avoids reallocating and copying the whole base-layer record storage during `add`.
+that. Python `add` grows the capacity first when the batch does not fit, to at least
+double it, and `reserve(num_points)` preallocates it (since 0.8.5; `resize` still works,
+with a `DeprecationWarning`, until 0.9, and `capacity` replaces `max_elements`). Reserving capacity avoids reallocating and copying the whole base-layer record storage during `add`.
It does not make insertion allocation-free: batch scratch, upper-layer link lists,
and label-map entries still require allocations, and the label map may rehash.
@@ -276,12 +277,12 @@ with an infinite distance. Removed points still count in
`num_stored_points()` and cannot be restored. Removal requires the same
exclusive access as other updates.
-#### Choosing `ef` after removals
+#### Choosing `ef_search` after removals
Removed points still take slots in the `ef_search` candidate set, so a search with
`ef_search` close to `k` finds fewer live points as removals accumulate. C++ search
uses `max(ef_search, k)`, clamped to `num_stored_points()`. Python uses `max(k, 64)`
-when `ef` is omitted or zero; an explicit positive `ef` is also raised to at least `k`,
+when `ef_search` is omitted (it was named `ef` before 0.8.5); an explicit value is also raised to at least `k`,
and both are clamped to the stored point count.
To keep about the same number of live candidates as before the removals, scale
the effective window by the share of live points (search clamps the result to
diff --git a/docs/docs/index/ivf.md b/docs/docs/index/ivf.md
index 40b917ff..3319bf28 100644
--- a/docs/docs/index/ivf.md
+++ b/docs/docs/index/ivf.md
@@ -51,8 +51,8 @@ See [C++ integration](../cpp_integration.md) for build setup and
| `nbits` / C++ `total_bits` | 1–9 total bits including the sign bit, or 32 for owned raw-vector reranking. Python's keyword-only `nbits` defaults to 7; C++ requires it. |
| `seed` | Rotation seed in `[0, 2**32 - 1]` and the initial `cp.seed`. Python's default `None` draws one at random; `index.seed` reports it, and passing it back reproduces the index. |
| `metric` | Python `"l2"`, `"ip"` or `"cosine"`; defaults to `"l2"`. See [the cosine metric](usage.md#the-cosine-metric). |
-| `initializer` | Defaults to `"auto"`; see [centroid routing](#centroid-routing). |
-| `k`, `nprobe` | Positive result count and cluster probe count. `k` may exceed the stored point count; missing results are padded with `kPidMax` (`-1` in Python) and `+inf`. Python's `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted, `None` or 0; C++ requires a positive `nprobe`. |
+| `routing` | Defaults to `"auto"`; see [centroid routing](#centroid-routing). Named `initializer` before 0.8.5; the old name still works, with a `DeprecationWarning`, until 0.9. |
+| `k`, `nprobe` | Positive result count and cluster probe count. `k` may exceed the stored point count; missing results are padded with `kPidMax` (`-1` in Python) and `+inf`. Python's `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted or `None` (0 does the same and is deprecated since 0.8.5); C++ requires a positive `nprobe`. |
| `high_accuracy` | Python defaults to `None`: HACC for 4–9 bits, standard FastScan otherwise. |
Results contain IDs and squared L2 or `1 - dot` distances, ordered from smallest
@@ -123,11 +123,11 @@ index_type ivf(num_points, dim, num_clusters, total_bits);
The optional final C++ constructor argument selects `InitializerType::Auto`,
`Flat`, `FlatRaBitQ`, or `HNSW` from the `rabitqlib::ivf` namespace. Python accepts
-`initializer="auto"`, `"flat"`, `"flat_rabitq"`, or `"hnsw"`:
+`routing="auto"`, `"flat"`, `"flat_rabitq"`, or `"hnsw"`:
```python
-index = IvfIndex(dim, num_clusters, nbits=4, initializer="flat_rabitq")
-print(index.initializer) # resolved routing type
+index = IvfIndex(dim, num_clusters, nbits=4, routing="flat_rabitq")
+print(index.routing) # resolved routing type
```
```c++
@@ -171,7 +171,7 @@ To retain the earlier policy when rebuilding, choose `flat` below 20,000 cluster
and `hnsw` otherwise. Loading an old index preserves its historical routing.
Routing is fixed for an index and is also used by `add` when cluster IDs are
-omitted. `initializer_type()` (Python `initializer`) reports the resolved type,
+omitted. `initializer_type()` (Python `routing`) reports the resolved type,
including after loading; loading never re-runs the current `auto` policy for a
new-format file.
@@ -229,7 +229,7 @@ index.add(vectors)
- Training or setting centroids again replaces them while the index stores no
vectors; once it stores any (including removed ones), both raise
`RuntimeError`. A failed call leaves the index unchanged.
-- Before training, `add` with `cluster_ids`, `search`, `remove`, `reserve` and
+- Before training, `add` with `cluster_ids`, `search`, `remove`, `reserve_cluster` and
`save` raise `RuntimeError`; `add` without `cluster_ids` trains first, except
on an index created with `max_elements`, which `build` fills. If that
first `add` fails, the index stays untrained and empty; an empty first `add`
@@ -395,9 +395,12 @@ new_ids = index.add(vectors, num_threads=1, fast_quantization=False)
# To choose clusters explicitly, use this instead of the call above:
# new_ids = index.add(vectors, cluster_ids=labels)
removed = index.remove(new_ids[:10])
-index.reserve(cluster_id, num_points)
+index.reserve_cluster(cluster_id, num_points)
```
+Python names this method `reserve_cluster` since 0.8.5; `reserve` still works, with a
+`DeprecationWarning`, until 0.9.
+
Python `vectors` has shape `(n, index.dim)` and is converted to contiguous float32.
`add()` returns a uint32 array of the new IDs. Optional `cluster_ids` must be a
one-dimensional integer array or sequence with one valid cluster ID per vector;
@@ -424,7 +427,7 @@ index is unchanged if `add` throws. As a result:
time.**
A rebuilt cluster gets exactly the room it needs. To grow a cluster without
-copying it, call `reserve` first: later `add` calls then write into the reserved
+copying it, call `reserve` (Python `reserve_cluster`) first: later `add` calls then write into the reserved
room in place until the cluster outgrows it. The reserved room is memory the index
holds but does not use yet. It is not saved, so a loaded index has none.
diff --git a/docs/docs/index/qg.md b/docs/docs/index/qg.md
index 58e97681..4adab0cf 100644
--- a/docs/docs/index/qg.md
+++ b/docs/docs/index/qg.md
@@ -28,7 +28,7 @@ ids = index.add(data) # builds the whole graph; ids are the row numbers
index.save("qg_example.index")
loaded = SymqgIndex.load("qg_example.index")
-ids, distances = loaded.search(queries, k=10, ef=100)
+ids, distances = loaded.search(queries, k=10, ef_search=100)
```
SymphonyQG follows the same `train` → `add` → `search` workflow as the other
@@ -77,7 +77,7 @@ qg.save("qg_example.index");
| `init` | Python keyword: `"pipnn"` (default) or `"random"`. |
| `metric` | Python keyword: `"l2"` (default), `"ip"` or [`"cosine"`](usage.md#the-cosine-metric). |
| `seed` | Python keyword: rotation and graph-construction seed in `[0, 2**32 - 1]`. The default `None` draws one at random; `index.seed` reports it, and passing it back with `num_threads=1` rebuilds the same graph from the same data. |
-| `k`, `ef` | `k` is at least 1 and may exceed the point count; slots the graph cannot fill are padded with ID `-1` in Python (`kPidMax` in C++) and distance `+inf`. Omitted or zero `ef` uses `max(k, 64)` in Python, and smaller values are raised to `k`, as for HNSW-RaBitQ. |
+| `k`, `ef_search` | `k` is at least 1 and may exceed the point count; slots the graph cannot fill are padded with ID `-1` in Python (`kPidMax` in C++) and distance `+inf`. An omitted `ef_search` uses `max(k, 64)` in Python, and smaller values are raised to `k`, as for HNSW-RaBitQ. Python named it `ef` before 0.8.5. |
| `num_threads` | Python `add` defaults to every available logical CPU, capped by `OMP_NUM_THREADS`, and `search` to 1; `None` selects these defaults. |
Python search returns `(ids, distances)` arrays. Distances are squared
@@ -180,14 +180,14 @@ do no work and may use null buffers. Inputs and outputs must not overlap.
Concurrent searches need separate outputs; do not modify the index or call
`set_ef()` while searches are running.
-Python `search(queries, k, ef=None, num_threads=None)` accepts a two-dimensional
+Python `search(queries, k, ef_search=None, *, num_threads=None)` accepts a two-dimensional
query array and returns `(ids, distances)` arrays of shape `(num_queries, k)`,
including empty batches. It defaults to one worker; `num_threads=0` selects the
available logical CPU count, capped by the number of queries. The 0.7 name
`search_batch` still works in 0.8 with a `DeprecationWarning`.
Queries use the original dimension, including when the internal rotation pads it.
-Python searches use per-call `ef` values. For access rules, see the
+Python searches use per-call `ef_search` values. For access rules, see the
[concurrency contract](usage.md#threading-and-file-paths).
For C++, use
diff --git a/docs/docs/index/usage.md b/docs/docs/index/usage.md
index 5973036f..d09f2a60 100644
--- a/docs/docs/index/usage.md
+++ b/docs/docs/index/usage.md
@@ -58,15 +58,20 @@ HNSW-RaBitQ's `num_points` now excludes removed records; see the
[count migration guide](../modular_migration.md#unified-index-counts) when upgrading.
IVF-RaBitQ, HNSW-RaBitQ, and SymphonyQG expose these read-only Python properties
-(C++ uses the same names with `()`):
+(C++ uses the same names with `()`, and `max_elements()` for the capacity of all
+three indexes):
| Property | Meaning |
| --- | --- |
-| `max_elements` | Logical record capacity, excluding SIMD padding |
| `num_points` | Nonremoved points |
| `num_stored_points` | Stored records, including removed ones |
+| `capacity` (HNSW-RaBitQ only) | Logical record capacity, excluding SIMD padding |
-`0 <= num_points <= num_stored_points <= max_elements`. Before vectors are
+`0 <= num_points <= num_stored_points`, and `num_stored_points <= capacity` for
+HNSW-RaBitQ. Before 0.8.5 Python named the capacity `max_elements` on all three
+classes; that property is deprecated and is removed in 0.9. On `IvfIndex` and
+`SymqgIndex` it equals `num_stored_points`, except on an `IvfIndex` created in the
+0.7 form before `build`, where it is the declared row count. Before vectors are
added, both point counts are zero; configured capacity may be nonzero. For
all three indexes, `len(index)` equals `num_points`. `is_trained` reports
whether IVF-RaBitQ or HNSW-RaBitQ centroids are set (by `train`, `set_centroids`,
@@ -77,13 +82,13 @@ start at the previous `num_stored_points`. Use this stored count for ID bounds,
and `num_points` for a live count. Counts survive save/load.
IVF-RaBitQ grows automatically and has no spare logical capacity after an append.
-HNSW-RaBitQ's Python `add` grows its capacity geometrically, and `resize` changes
-only capacity, for example to preallocate it. SymphonyQG has no incremental
-updates: `add` builds the graph once, and all three counts are equal afterwards.
+HNSW-RaBitQ's Python `add` grows its capacity geometrically, and `reserve` preallocates
+it (`resize` before 0.8.5). SymphonyQG has no incremental
+updates: `add` builds the graph once, and both counts are equal afterwards.
`repr(index)` shows dimension, metric, quantization bits and live point count,
plus the training state for IVF/HNSW. IVF/HNSW also show stored count, capacity and centroid count; IVF includes
-the resolved initializer, and SymphonyQG includes its degree bound. The summary
+the resolved routing strategy, and SymphonyQG includes its degree bound. The summary
reads only metadata and follows the same concurrency rules as property reads.
## Estimate storage
@@ -143,7 +148,7 @@ construction, updates, and file I/O. The following contract applies to
| Operation on the same index | Concurrent access |
| --- | --- |
| `search`, `search_batch`, `save`, `repr`, and property reads | May run together |
-| `train`, `set_centroids`, `build`, `add`, `remove`, `reserve`, `resize`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input and may run with reads |
+| `train`, `set_centroids`, `build`, `add`, `remove`, `reserve`, `reserve_cluster`, `resize`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input and may run with reads |
A conflicting call immediately raises
`RuntimeError("Index is busy: conflicting operation in progress")`.
@@ -152,7 +157,7 @@ conversion and is released when the operation returns or raises an exception.
Different index objects can operate independently. Concurrent saves must use
different output paths.
-Search parameters such as `ef`, `nprobe`, precision, and `num_threads` belong to
+Search parameters such as `ef_search`, `nprobe`, precision, and `num_threads` belong to
each call. When using a Python thread pool, consider `num_threads=1` to avoid
starting multiple native worker pools. Keep input arrays and any shared backing
storage unchanged for the entire call; do not resize or modify them from another
diff --git a/docs/docs/installation.md b/docs/docs/installation.md
index 5d5c3627..d907f92f 100644
--- a/docs/docs/installation.md
+++ b/docs/docs/installation.md
@@ -1,6 +1,6 @@
# Installation
-Platform requirements and source installation for RaBitQ Library **0.8.4**.
+Platform requirements and source installation for RaBitQ Library **0.8.5**.
For the first Python example, see [Quick Start](quick_start.md).
## Requirements
@@ -40,7 +40,7 @@ build can use scalar kernels without the FastScan CPU baseline.
## Python wheels
```bash
-python -m pip install "rabitqlib>=0.8.4"
+python -m pip install "rabitqlib>=0.8.5"
```
For changes from 0.6.0, see the [0.7.0 upgrade notes](releases/0.7.0.md).
@@ -61,11 +61,11 @@ importing those classes. Array shapes and parameter ranges are still checked at
## Get the source
-For Python source builds or C++ use, obtain the 0.8.4 checkout once. With Git
+For Python source builds or C++ use, obtain the 0.8.5 checkout once. With Git
installed, run:
```bash
-git clone --branch v0.8.4 --depth 1 https://github.com/VectorDB-NTU/RaBitQ-Library.git
+git clone --branch v0.8.5 --depth 1 https://github.com/VectorDB-NTU/RaBitQ-Library.git
cd RaBitQ-Library
```
diff --git a/docs/docs/python_migration.md b/docs/docs/python_migration.md
index 51f2a672..3038f0b8 100644
--- a/docs/docs/python_migration.md
+++ b/docs/docs/python_migration.md
@@ -9,6 +9,10 @@ nothing to train and builds its graph in `add`. Code written for 0.7
still runs in 0.8. Each old form raises a `DeprecationWarning` at your call site
and will be removed in **0.9**.
+If your code already uses the 0.8 forms, go to
+[From 0.8 to 0.9](#from-08-to-09): 0.9 renames some of them, and 0.8.5 accepts
+the new names.
+
Unless an item below says otherwise, a 0.7 call that raises a deprecation
warning keeps its 0.7 behavior. Calls that are valid in both versions, such as
`add(x)` and `search`, follow the 0.8 rules.
@@ -19,9 +23,9 @@ warning keeps its 0.7 behavior. Calls that are valid in both versions, such as
| 0.7 | 0.8 |
| --- | --- |
-| `IvfIndex(dim, max_elements, num_clusters, nbits, metric, initializer)` | `IvfIndex(dim, num_clusters, nbits=..., metric=..., initializer=..., seed=None)`; storage grows on `add` |
+| `IvfIndex(dim, max_elements, num_clusters, nbits, metric, initializer)` | `IvfIndex(dim, num_clusters, nbits=..., metric=..., routing=..., seed=None)` (`initializer=` before 0.8.5); storage grows on `add` |
| `IvfIndex(dim=..., max_elements=..., num_clusters=..., nbits=...)` | the same, without `max_elements` |
-| `HnswIndex(dim, max_elements, M=16, ef_construction=200, nbits=8, metric="l2", random_seed=100)` | `HnswIndex(dim, nbits=..., num_clusters=16, M=16, ef_construction=200, metric="l2", seed=100)`; capacity grows on `add`, and `resize(n)` preallocates it |
+| `HnswIndex(dim, max_elements, M=16, ef_construction=200, nbits=8, metric="l2", random_seed=100)` | `HnswIndex(dim, nbits=..., num_clusters=16, M=16, ef_construction=200, metric="l2", seed=100)`; capacity grows on `add`, and `reserve(n)` preallocates it (`resize(n)` before 0.8.5) |
| `HnswIndex(..., random_seed=s)` | `HnswIndex(..., seed=s)` |
| `kmeans = RaBitQKMeans(dim, k)`
`kmeans.train(x)`
`index.build(x, kmeans.centroids, kmeans.assignments)` | `index.add(x)`, which trains on `x` first (since 0.8.2; in 0.8.0 and 0.8.1, call `index.train(x)` first) |
| `index.build(x, centroids, cluster_ids)` | `index.set_centroids(centroids)`
`index.add(x, cluster_ids=cluster_ids)` |
@@ -68,7 +72,7 @@ work if you want to run k-means yourself.
to `add` on indexes created in the old form, and to the deprecated `build`,
which no longer rejects more rows than `max_elements`.
- **State errors.** Calling `add` with `cluster_ids`, `search`, `remove`,
- `reserve` or `save` before training raises `RuntimeError("IvfIndex must be
+ `reserve_cluster` (`reserve` before 0.8.5) or `save` before training raises `RuntimeError("IvfIndex must be
trained or loaded before ...")`; the 0.7 message said "built". Since 0.8.2,
`add` without `cluster_ids` trains first. A trained index without vectors
cannot be saved. `repr` shows `is_trained` instead of `is_built`.
@@ -98,7 +102,8 @@ a second `add`, or `add` on a loaded index, raises `RuntimeError`, as Faiss's
NSG index does. The deprecated `build` keeps its 0.7 behavior: it replaces any
existing graph and, unless you passed `seed`, draws a new random seed each time.
-`search` now treats `ef` like HNSW-RaBitQ: an omitted or zero `ef` uses
+`search` now treats its breadth (`ef_search`; `ef` before 0.8.5) like HNSW-RaBitQ:
+omitted, it uses
`max(k, 64)` (`max(k, 10)` before 0.8.2), and a smaller one is raised to `k`. In 0.7, both raised
`ValueError`. `add` uses every CPU by default, while the deprecated `build`
keeps one thread. The seed now also drives graph construction: without `seed`,
@@ -108,9 +113,10 @@ separate random seeds for the rotation and the graph. Before vectors are added,
## Files and C++
-Saved files and the `max_elements` property are unchanged. `HnswIndex.search`
-without `ef` uses `max(k, 64)` since 0.8.2 (`max(k, 10)` before), which changes
-its results and latency; pass `ef=` to keep the old window. Files written by 0.7
+Saved files are unchanged, and so is the `max_elements` property up to 0.8.4 (see
+[From 0.8 to 0.9](#from-08-to-09)). `HnswIndex.search`
+without a search breadth uses `max(k, 64)` since 0.8.2 (`max(k, 10)` before), which changes
+its results and latency; pass the breadth as the third argument to keep the old window. Files written by 0.7
load as trained indexes, except empty, untrained HNSW-RaBitQ files, which need
`train` before `add`.
@@ -121,3 +127,62 @@ points. C++ behavior changes: since 0.8.0, saving an index without stored points
throws `std::logic_error`; since 0.8.2, IVF and SymphonyQG searches pad `k` above
the point count instead of throwing, and `default_training_parameters` runs 10
iterations. See the [0.8.2 notes](releases/0.8.2.md#c-changes).
+
+## From 0.8 to 0.9
+
+0.9 gives the three index classes one name for each concept
+([#232](https://github.com/VectorDB-NTU/RaBitQ-Library/issues/232)). Since 0.8.5 the
+0.8 form in the first column raises a `DeprecationWarning` at your call site; 0.9
+removes it.
+
+| 0.8 | Use instead | Works since |
+| --- | --- | --- |
+| `IvfIndex.max_elements`, `SymqgIndex.max_elements` | `num_stored_points` | Every 0.8 release. The two are equal, except on an `IvfIndex` created in the 0.7 form before `build`. |
+| `HnswIndex.max_elements` | `HnswIndex.capacity` | 0.8.5 |
+| `HnswIndex.resize(n)` | `HnswIndex.reserve(n)`, which only grows the capacity; `resize` could also shrink it | 0.8.5 |
+| `IvfIndex.reserve(cluster_id, num_points)` | `IvfIndex.reserve_cluster(cluster_id, num_points)` | 0.8.5 |
+| `IvfIndex(initializer=...)`, `index.initializer` | `IvfIndex(routing=...)`, `index.routing`, with the same values | 0.8.5 |
+| `search(queries, k, ef=...)` on `HnswIndex` and `SymqgIndex` | `search(queries, k, ef_search=...)` | 0.8.5; passing the breadth by position works in every release |
+| `search(queries, k, nprobe, high_accuracy, num_threads)`, `search(queries, k, ef, num_threads)` | `high_accuracy=` and `num_threads=` by keyword; only `nprobe` or `ef_search` stays positional | Every 0.8 release |
+| `nprobe=0`, `ef=0` for the default | `None`, or omit the argument; 0.9 raises `ValueError` for 0, while `num_threads=0` keeps meaning every available CPU | 0.8.2 |
+| `HnswIndex(seed=s)` with `s` above `2**32 - 1` | A seed in `[0, 2**32 - 1]`, the range of the other two classes | Every 0.8 release |
+
+The k-means classes take the names of the index parameters
+([#233](https://github.com/VectorDB-NTU/RaBitQ-Library/issues/233)), as keywords and as
+attributes of `cp`:
+
+| 0.8 | Use instead | Works since |
+| --- | --- | --- |
+| `QGKMeans(quantization_bits=0 \| 4 \| 8)` | `nbits=32 \| 4 \| 8`: 32, not 0, keeps raw vectors | 0.8.5 |
+| `QGKMeans(graph_degree=...)` | `max_degree=...` | 0.8.5 |
+| `QGKMeans(ef_build=...)` | `ef_construction=...` | 0.8.5 |
+| `final_assignment=FinalAssignmentMode.Approximate \| .Exact`, also as `index.cp.final_assignment` on `IvfIndex` and `HnswIndex` | `final_assignment='approximate' \| 'exact'`; `'approximate'` also replaces the alias `FinalAssignmentMode.SymphonyQG` | 0.8.5 |
+| `QGKMeansIterationStats`, `RaBitQKMeansIterationStats` | `KMeansIterationStats`, the one class both always were; since 0.8.5 it also reports that name | 0.8.5 |
+
+Passing a `FinalAssignmentMode` member does not warn by itself; the warning comes where
+one of the three old names is imported or read from `rabitqlib`, including through
+`from rabitqlib import *`.
+
+Until 0.9, `cp.final_assignment` still reads back as a `FinalAssignmentMode` member,
+whose `.name` is `'Approximate'` or `'Exact'`; 0.9 returns `'approximate'` or
+`'exact'`. Reading it does not warn. Code that reads it on both releases can
+normalize the value:
+
+```python
+mode = cp.final_assignment
+mode = mode if isinstance(mode, str) else mode.name.lower()
+```
+
+Code that must also run on releases before 0.8.5 needs a version check for the rows
+marked 0.8.5; the other replacements work on every release named.
+
+Three of these changes come without a warning in 0.9. `HnswIndex()` without `seed=` draws a seed,
+as `IvfIndex` and `SymqgIndex` already do, instead of using 100: pass `seed=` (and
+`num_threads=1` to `add`) if you rely on a reproducible build. `repr(index)` prints
+`capacity=` and `routing=` where it prints `max_elements=` and `initializer=`. And
+`cp.final_assignment` reads back as a string, as described above.
+
+0.9 also changes behavior that no warning can announce: `search` and `add` return
+`int64` IDs with `-1` instead of `2**32 - 1` for a missing result, `save` writes index
+format 2, which releases up to 0.8 cannot read, and `load` restores the seed. See the
+[0.9 notes](releases/unreleased.md).
diff --git a/docs/docs/quick_start.md b/docs/docs/quick_start.md
index 0e107c4d..83f55e68 100644
--- a/docs/docs/quick_start.md
+++ b/docs/docs/quick_start.md
@@ -1,14 +1,14 @@
# Quick start
Build, search, save and reload a small IVF-RaBitQ index with Python. This guide describes
-**0.8.4** and uses synthetic data, so no dataset download is required. Coming from 0.7?
+**0.8.5** and uses synthetic data, so no dataset download is required. Coming from 0.7?
See the [migration guide](python_migration.md).
For C++, go directly to [C++ integration](cpp_integration.md).
## Install
```bash
-python -m pip install "rabitqlib>=0.8.4"
+python -m pip install "rabitqlib>=0.8.5"
```
Wheels support CPython 3.11–3.14 on Linux x86-64/ARM64, Windows x86-64 and
diff --git a/docs/docs/releases/0.8.5.md b/docs/docs/releases/0.8.5.md
new file mode 100644
index 00000000..78318d34
--- /dev/null
+++ b/docs/docs/releases/0.8.5.md
@@ -0,0 +1,71 @@
+# RaBitQ Library 0.8.5
+
+This release prepares for 0.9: it adds the names that 0.9 will use and deprecates
+the 0.8 spellings they replace. Every 0.8 call keeps working, with the same results;
+index files and C++ are unchanged.
+
+## Python: names that change in 0.9
+
+0.9 gives the three index classes one name for each concept (#232). This release
+accepts both spellings and raises a `DeprecationWarning` for the old one, at your call
+site. The [migration guide](../python_migration.md#from-08-to-09) lists each change.
+
+- `HnswIndex.capacity` replaces `max_elements`, and `HnswIndex.reserve(num_points)`
+ replaces `resize`. `reserve` only grows the capacity.
+- `max_elements` is deprecated on `IvfIndex` and `SymqgIndex`; use `num_stored_points`.
+- `IvfIndex.reserve_cluster(cluster_id, num_points)` replaces `reserve`.
+- `IvfIndex(routing=...)` and `index.routing` replace `initializer`.
+- `HnswIndex.search` and `SymqgIndex.search` take `ef_search=` instead of `ef=`. Passing
+ the breadth by position is unaffected.
+- Passing the `search` options after the breadth (`high_accuracy`, `num_threads`) by
+ position is deprecated; 0.9 makes them keyword-only.
+- `nprobe=0` and `ef_search=0` for the default are deprecated; pass `None` or omit the
+ argument. `num_threads=0` keeps meaning every available CPU.
+- `HnswIndex` seeds above `2**32 - 1` are deprecated.
+
+The k-means classes take the names of the index parameters (#233):
+
+- `QGKMeans` and `QGKMeansParameters` take `nbits` (32, 4 or 8), `max_degree` and
+ `ef_construction` for `quantization_bits` (0, 4 or 8), `graph_degree` and `ef_build`.
+- `final_assignment` takes `'approximate'` or `'exact'`, also as
+ `index.cp.final_assignment` on `IvfIndex` and `HnswIndex`. `FinalAssignmentMode`
+ members are still accepted, and the attribute still reads back as a member until 0.9.
+- `KMeansIterationStats` is the one name of the statistics class.
+ `QGKMeansIterationStats`, `RaBitQKMeansIterationStats` and `FinalAssignmentMode` warn
+ when imported or read from the package. The class now reports its name as
+ `KMeansIterationStats`.
+
+The type stubs mark the renamed 0.8 forms as deprecated, so mypy and Pyright can
+report them (mypy with `--enable-error-code deprecated`, Pyright with
+`reportDeprecated`). Three forms warn only at run time: `nprobe=0` or `ef_search=0`,
+an `HnswIndex` seed above `2**32 - 1`, and the two old names of
+`KMeansIterationStats`.
+
+## Python: other changes
+
+- `IvfIndex.set_centroids` takes `num_threads` (#231). Without it, `set_centroids` now
+ follows `OMP_NUM_THREADS`, as `train` and `add` do; before, it always used every
+ CPU. Only the HNSW routing graph varies with the thread count: build it with one
+ thread and a fixed `seed` for a reproducible graph.
+
+## Coming in 0.9 without a warning
+
+- `HnswIndex()` without `seed=` will draw a seed, as `IvfIndex` and `SymqgIndex` do,
+ instead of using 100. Pass `seed=`, and `num_threads=1` to `add`, for a reproducible
+ build.
+- `repr(index)` will print `capacity=` and `routing=` where it prints `max_elements=`
+ and `initializer=`.
+- `cp.final_assignment` will read back as `'approximate'` or `'exact'` instead of a
+ `FinalAssignmentMode` member.
+
+## Upgrading
+
+From 0.8.4, index file formats, the stable core API v1 and C++ are unchanged, and every
+0.8 Python call keeps its result. Code that uses a deprecated spelling now raises a
+`DeprecationWarning`; move to the new names with the
+[migration guide](../python_migration.md#from-08-to-09) before 0.9 removes the old ones.
+Rebuild C++ consumers with matching headers and libraries; no cross-version C++ binary
+ABI is promised.
+
+When upgrading from 0.7, follow the [0.8.0 release notes](0.8.0.md) and the
+[migration guide](../python_migration.md).
diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml
index 5f45bf9a..b8c33f30 100644
--- a/docs/mkdocs.yml
+++ b/docs/mkdocs.yml
@@ -16,6 +16,7 @@ nav:
- Release notes:
- Unreleased: releases/unreleased.md
- "0.8":
+ - "0.8.5": releases/0.8.5.md
- "0.8.4": releases/0.8.4.md
- "0.8.3": releases/0.8.3.md
- "0.8.2": releases/0.8.2.md
diff --git a/pyproject.toml b/pyproject.toml
index 5ea7ac0b..795886a0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build"
[project]
name = "rabitqlib"
-version = "0.8.4"
+version = "0.8.5"
description = "Official RaBitQ library for vector quantization and approximate nearest-neighbor search"
readme = "README.md"
requires-python = ">=3.11"
diff --git a/python_bindings/__init__.py b/python_bindings/__init__.py
index 1c29aea8..a1057203 100644
--- a/python_bindings/__init__.py
+++ b/python_bindings/__init__.py
@@ -5,21 +5,26 @@
"""
import inspect
+import operator
+import sys
import warnings
from ._rabitqlib import (
- FinalAssignmentMode,
+ FinalAssignmentMode as _FinalAssignmentMode,
+)
+from ._rabitqlib import (
FormatError,
HnswIndex,
IvfIndex,
- QGKMeansIterationStats,
QGKMeansParameters,
- RaBitQKMeansIterationStats,
RaBitQKMeansParameters,
SymqgIndex,
_QGKMeans,
_RaBitQKMeans,
)
+from ._rabitqlib import (
+ QGKMeansIterationStats as KMeansIterationStats,
+)
from ._rabitqlib import (
__version__ as __version__,
)
@@ -36,6 +41,29 @@
_MISSING = object()
+def _is_zero(value):
+ """Whether an optional integer argument is one the extension reads as 0."""
+ if value is None or isinstance(value, (float, str, bytes)):
+ return False
+ try:
+ return operator.index(value) == 0
+ except TypeError:
+ pass
+ try:
+ # pybind11 also converts objects that only define __int__, such as
+ # numpy floating scalars.
+ return int(value) == 0
+ except (TypeError, ValueError, OverflowError):
+ return False
+
+
+def _exceeds_32_bits(value):
+ try:
+ return operator.index(value) > 0xFFFFFFFF
+ except TypeError:
+ return False
+
+
def _deprecated(message):
# Called from a replacement method, so the caller of that method is two up.
warnings.warn(f"{message}; {_MIGRATION}", DeprecationWarning, stacklevel=3)
@@ -53,7 +81,7 @@ def _bind(signature, name, args, kwargs, hint=""):
def _ivf_signature(
- self, dim, num_clusters, *, nbits=7, metric="l2", initializer="auto", seed=None
+ self, dim, num_clusters, *, nbits=7, metric="l2", routing="auto", seed=None
): ...
@@ -127,7 +155,28 @@ def __init__(self, *args, **kwargs):
_max_elements=arguments["max_elements"],
)
return
- native_init(self, **_bind(signature, "IvfIndex", (self, *args), kwargs))
+ # 0.9 names the routing strategy routing; initializer is its 0.8 spelling.
+ initializer = kwargs.pop("initializer", _MISSING)
+ if initializer is not _MISSING:
+ if "routing" in kwargs:
+ raise TypeError(
+ "IvfIndex() got both routing and its old name initializer"
+ )
+ _deprecated("IvfIndex(initializer=...) is deprecated; use routing=")
+ kwargs["routing"] = initializer
+ arguments = _bind(signature, "IvfIndex", (self, *args), kwargs)
+ arguments["initializer"] = arguments.pop("routing")
+ try:
+ native_init(self, **arguments)
+ except ValueError as error:
+ # The extension names the argument initializer; a caller who wrote
+ # routing= gets that name back.
+ message = str(error)
+ if initializer is not _MISSING or not message.startswith(
+ "initializer must be"
+ ):
+ raise
+ raise ValueError("routing" + message[len("initializer") :]) from None
__init__.__doc__ = cls.__doc__
__init__.__signature__ = signature
@@ -172,7 +221,13 @@ def __init__(self, *args, **kwargs):
)
_deprecated("HnswIndex(random_seed=...) is deprecated; use seed=")
kwargs["seed"] = random_seed
- native_init(self, **_bind(signature, "HnswIndex", (self, *args), kwargs))
+ arguments = _bind(signature, "HnswIndex", (self, *args), kwargs)
+ if _exceeds_32_bits(arguments["seed"]):
+ _deprecated(
+ "HnswIndex seeds above 2**32 - 1 are deprecated; 0.9 accepts "
+ "[0, 2**32 - 1], as the other indexes do"
+ )
+ native_init(self, **arguments)
__init__.__doc__ = cls.__doc__
__init__.__signature__ = signature
@@ -278,6 +333,7 @@ def _symqg_nbits(quantization_bits):
def _patch_symqg(cls):
native_init = cls.__init__
+ native_search = cls.search
signature = inspect.signature(_symqg_signature)
legacy_signature = inspect.signature(_symqg_legacy_signature)
@@ -346,7 +402,7 @@ def build(self, data, ef_construction, num_threads=1, init="pipnn"):
def search_batch(self, queries, k, ef, num_threads=1):
"""Deprecated since 0.8: the same as search(); use search()."""
_deprecated("SymqgIndex.search_batch() is deprecated; use search()")
- return self.search(queries, k, ef, num_threads)
+ return native_search(self, queries, k, ef, num_threads)
def quantization_bits(self):
"""Deprecated since 0.8: storage bits with 0 for raw vectors; use nbits."""
@@ -380,6 +436,473 @@ def is_built(self):
# --- end of the 0.8 compatibility layer -------------------------------------
+# --- 0.9 names; the 0.8 spellings they replace are removed in 0.9 -----------
+# 0.9 renames these members and arguments (issue #232). This release accepts both
+# spellings and warns on the old one. The extension classes still carry the 0.8
+# names, so the new ones are added here, again by replacing members on the classes.
+
+
+def _member(cls, function, name=None):
+ """function named as a member of cls, so errors and help() show the class."""
+ if name is not None:
+ function.__name__ = name
+ function.__qualname__ = f"{cls.__name__}.{function.__name__}"
+ function.__module__ = cls.__module__
+ return function
+
+
+def _renamed_property(cls, old, new, new_doc, replacement):
+ """Add property new for the native property old, which then warns."""
+ native = vars(cls)[old]
+ name = cls.__name__
+
+ def current(self):
+ return native.__get__(self, cls)
+
+ def former(self):
+ _deprecated(f"{name}.{old} is deprecated; use {replacement}")
+ return native.__get__(self, cls)
+
+ _member(cls, former, old)
+ if new is not None:
+ _member(cls, current, new)
+ _set_property(cls, new, current, new_doc)
+ _set_property(cls, old, former, f"Deprecated since 0.8.5: use {replacement}.")
+
+
+def _set_property(cls, name, getter, documentation, setter=None):
+ """Assign a property, named as a class body would name it."""
+ member = property(getter, setter, doc=documentation)
+ setattr(cls, name, member)
+ # Assignment after class creation skips __set_name__, and before Python 3.13
+ # a property without it reports errors without its name.
+ member.__set_name__(cls, name)
+
+
+def _options_from_positions(name, options, args, kwargs):
+ if len(args) > len(options):
+ raise TypeError(
+ f"{name}.search() takes at most {len(options) + 2} positional "
+ f"arguments ({len(args) + 2} given)"
+ )
+ for option, value in zip(options, args, strict=False):
+ if option in kwargs:
+ raise TypeError(
+ f"{name}.search() got multiple values for argument {option!r}"
+ )
+ kwargs[option] = value
+
+
+def _edited(documentation, replacements):
+ """A docstring with replacements applied; fails if the native text moved."""
+ for old, new in replacements:
+ if old not in documentation:
+ raise AssertionError(f"native documentation changed: {old!r}")
+ documentation = documentation.replace(old, new)
+ return documentation
+
+
+def _redocumented(native, replacements):
+ """The native docstring without pybind11's signature line, with edits applied."""
+ return _edited(native.__doc__.split("\n\n", 1)[1], replacements)
+
+
+_THREADS_DOC = (
+ " Worker count. None (default) selects 1; 0 selects the available CPU\n"
+ " count, capped by OMP_NUM_THREADS.",
+ " Keyword-only; passing it by position is deprecated since 0.8.5. Worker\n"
+ " count. None (default) selects 1; 0 selects the available CPU count,\n"
+ " capped by OMP_NUM_THREADS.",
+)
+
+
+def _ivf_search_signature(
+ self, queries, k, nprobe=None, *, high_accuracy=None, num_threads=None
+): ...
+
+
+def _graph_search_signature(self, queries, k, ef_search=None, *, num_threads=None): ...
+
+
+def _patch_ivf_names(cls):
+ native_reserve = cls.reserve
+ native_search = cls.search
+ options = ("nprobe", "high_accuracy", "num_threads")
+
+ def reserve_cluster(self, cluster_id, num_points):
+ """Preallocate storage for a cluster.
+
+ Parameters
+ ----------
+ cluster_id : int
+ Cluster ID in [0, num_clusters).
+ num_points : int
+ Nonnegative capacity to reserve for this cluster: the total number
+ of points it can hold, including its current ones.
+
+ Notes
+ -----
+ Requires a trained or loaded index. Reserved room is not saved. Named
+ reserve before 0.8.5.
+ """
+ try:
+ native_reserve(self, cluster_id, num_points)
+ except RuntimeError as error:
+ # The extension still names the operation reserve.
+ if not str(error).endswith("before reserve"):
+ raise
+ raise RuntimeError(f"{error}_cluster") from None
+
+ def reserve(self, cluster_id, num_points):
+ """Deprecated since 0.8.5: the same as reserve_cluster(); use reserve_cluster()."""
+ _deprecated("IvfIndex.reserve() is deprecated; use reserve_cluster()")
+ native_reserve(self, cluster_id, num_points)
+
+ def search(self, queries, k, *args, **kwargs):
+ _options_from_positions("IvfIndex", options, args, kwargs)
+ if len(args) > 1:
+ _deprecated(
+ f"passing {', '.join(options[1 : len(args)])} to IvfIndex.search() "
+ "by position is deprecated; use keywords"
+ )
+ if _is_zero(kwargs.get("nprobe")):
+ _deprecated(
+ "IvfIndex.search(nprobe=0) is deprecated; pass None, or omit nprobe, "
+ "for the default"
+ )
+ return native_search(self, queries, k, **kwargs)
+
+ search.__doc__ = _redocumented(
+ native_search,
+ [
+ (
+ " Number of clusters to probe, capped at num_clusters. None (default) and\n"
+ " 0 select num_clusters / 16, rounded to the nearest integer and at least 1.",
+ " Number of clusters to probe, capped at num_clusters. None (default)\n"
+ " selects num_clusters / 16, rounded to the nearest integer and at least\n"
+ " 1; 0 does the same and is deprecated since 0.8.5.",
+ ),
+ (
+ " Enable HACC. None (default) selects it for 4-9 bits and standard\n"
+ " FastScan otherwise. Raw storage uses standard FastScan.",
+ " Keyword-only; passing it by position is deprecated since 0.8.5.\n"
+ " Enable HACC. None (default) selects it for 4-9 bits and standard\n"
+ " FastScan otherwise. Raw storage uses standard FastScan.",
+ ),
+ _THREADS_DOC,
+ ],
+ )
+ search.__signature__ = inspect.signature(_ivf_search_signature)
+ cls.__doc__ = _edited(
+ cls.__doc__,
+ [
+ (
+ "initializer : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional\n"
+ " Centroid routing strategy. Default is 'auto'.",
+ "routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional\n"
+ " Centroid routing strategy. Default is 'auto'. Named initializer\n"
+ " before 0.8.5.",
+ )
+ ],
+ )
+ cls.__init__.__doc__ = cls.__doc__
+ cls.add.__doc__ = _edited(
+ cls.add.__doc__,
+ [
+ ("reserve can preallocate room.", "reserve_cluster can preallocate room."),
+ (
+ "index's configured centroid initializer; routing may be approximate.",
+ "index's configured routing strategy, which may be approximate.",
+ ),
+ ],
+ )
+ cls.reserve_cluster = _member(cls, reserve_cluster)
+ cls.reserve = _member(cls, reserve)
+ cls.search = _member(cls, search)
+ _renamed_property(
+ cls,
+ "initializer",
+ "routing",
+ "Resolved centroid routing strategy. Named initializer before 0.8.5.",
+ "routing",
+ )
+ _renamed_property(cls, "max_elements", None, None, "num_stored_points")
+
+
+def _patch_graph_search(cls, breadth_doc):
+ native_search = cls.search
+ name = cls.__name__
+ options = ("ef_search", "num_threads")
+
+ def search(self, queries, k, *args, **kwargs):
+ _options_from_positions(name, options, args, kwargs)
+ if "ef" in kwargs and "ef_search" in kwargs:
+ raise TypeError(f"{name}.search() got both ef_search and its old name ef")
+ if len(args) == len(options):
+ _deprecated(
+ f"passing num_threads to {name}.search() by position is deprecated; "
+ "use the keyword"
+ )
+ if "ef" in kwargs:
+ _deprecated(f"{name}.search(ef=...) is deprecated; use ef_search=")
+ kwargs["ef_search"] = kwargs.pop("ef")
+ ef_search = kwargs.pop("ef_search", None)
+ if _is_zero(ef_search):
+ _deprecated(
+ f"{name}.search(ef_search=0) is deprecated; pass None, or omit "
+ "ef_search, for the default"
+ )
+ return native_search(self, queries, k, ef_search, **kwargs)
+
+ search.__doc__ = _redocumented(native_search, [breadth_doc, _THREADS_DOC])
+ search.__signature__ = inspect.signature(_graph_search_signature)
+ cls.search = _member(cls, search)
+
+
+def _patch_hnsw_names(cls):
+ native_resize = cls.resize
+ native_max_elements = vars(cls)["max_elements"]
+
+ def reserve(self, num_points):
+ """Preallocate room for at least num_points stored points.
+
+ Parameters
+ ----------
+ num_points : int
+ Nonnegative number of stored points to make room for, including the
+ current ones.
+
+ Notes
+ -----
+ Capacity only grows: a value at or below capacity changes nothing. add
+ also grows the capacity when needed, so reserve is an optimization.
+ """
+ needed = operator.index(num_points)
+ if needed < 0:
+ raise ValueError("num_points must be non-negative")
+ if needed > native_max_elements.__get__(self, cls):
+ native_resize(self, needed)
+
+ def resize(self, max_elements):
+ """Deprecated since 0.8.5: change the capacity; use reserve(), which only grows it."""
+ _deprecated(
+ "HnswIndex.resize() is deprecated; use reserve(), which only grows the "
+ "capacity"
+ )
+ native_resize(self, max_elements)
+
+ cls.__doc__ = _edited(
+ cls.__doc__,
+ [
+ ("resize can preallocate it.", "reserve can preallocate it."),
+ (
+ "32 bits). Default is 100.",
+ "32 bits), in [0, 2**32 - 1]; larger values are deprecated since\n"
+ " 0.8.5. Default is 100.",
+ ),
+ ],
+ )
+ cls.__init__.__doc__ = cls.__doc__
+ cls.reserve = _member(cls, reserve)
+ cls.resize = _member(cls, resize)
+ _renamed_property(
+ cls,
+ "max_elements",
+ "capacity",
+ "Current storage capacity, in stored points. Named max_elements before 0.8.5.",
+ "capacity",
+ )
+
+
+_patch_ivf_names(IvfIndex)
+_patch_hnsw_names(HnswIndex)
+_renamed_property(SymqgIndex, "max_elements", None, None, "num_stored_points")
+_patch_graph_search(
+ HnswIndex,
+ (
+ "ef : int, optional\n Search breadth. None or 0 (default) selects max(k, 64); values above the stored\n"
+ " point count are clamped.",
+ "ef_search : int, optional\n Search breadth. None (default) selects max(k, 64); values above the stored\n"
+ " point count are clamped. 0 selects the default and is deprecated since\n"
+ " 0.8.5. Named ef before 0.8.5.",
+ ),
+)
+_patch_graph_search(
+ SymqgIndex,
+ (
+ "ef : int, optional\n Search breadth. None or 0 (default) selects max(k, 64); smaller values\n"
+ " are raised to k.",
+ "ef_search : int, optional\n Search breadth. None (default) selects max(k, 64); smaller values\n"
+ " are raised to k. 0 selects the default and is deprecated since 0.8.5.\n"
+ " Named ef before 0.8.5.",
+ ),
+)
+# k-means (issue #233): the graph parameters take the index names, final_assignment
+# takes a string, and the two statistics class names become one.
+
+KMeansIterationStats.__name__ = KMeansIterationStats.__qualname__ = (
+ "KMeansIterationStats"
+)
+# Pickle and pydoc find a class by its name in its module, which is the extension.
+sys.modules[KMeansIterationStats.__module__].KMeansIterationStats = KMeansIterationStats
+
+_FINAL_ASSIGNMENTS = {
+ "approximate": _FinalAssignmentMode.Approximate,
+ "exact": _FinalAssignmentMode.Exact,
+}
+
+
+def _patch_final_assignment(cls):
+ native = vars(cls)["final_assignment"]
+
+ def final_assignment(self):
+ return native.__get__(self, cls)
+
+ def set_final_assignment(self, value):
+ if isinstance(value, str):
+ try:
+ value = _FINAL_ASSIGNMENTS[value]
+ except KeyError:
+ raise ValueError(
+ "final_assignment must be 'approximate' or 'exact'"
+ ) from None
+ elif not isinstance(value, _FinalAssignmentMode):
+ raise TypeError(
+ "final_assignment must be 'approximate' or 'exact', not "
+ f"{type(value).__name__}"
+ )
+ native.__set__(self, value)
+
+ _set_property(
+ cls,
+ "final_assignment",
+ _member(cls, final_assignment),
+ "'approximate' uses the training assignment method; 'exact' uses exhaustive "
+ "assignment against final centroids. Default is 'approximate'. Until 0.9 it "
+ "reads back as the FinalAssignmentMode member, which is still accepted.",
+ _member(cls, set_final_assignment, "final_assignment"),
+ )
+
+
+def _qg_nbits_to_native(value):
+ bits = operator.index(value)
+ if bits not in (4, 8, 32):
+ raise ValueError("nbits must be 4, 8, or 32")
+ return 0 if bits == 32 else bits
+
+
+def _qg_nbits_from_native(value):
+ return 32 if value == 0 else value
+
+
+def _rename_parameter(cls, old, new, documentation, to_native=None, from_native=None):
+ """Add attribute new for the native attribute old, which then warns."""
+ native = vars(cls)[old]
+ name = cls.__name__
+
+ def current(self):
+ value = native.__get__(self, cls)
+ return value if from_native is None else from_native(value)
+
+ def set_current(self, value):
+ native.__set__(self, value if to_native is None else to_native(value))
+
+ def former(self):
+ _deprecated(f"{name}.{old} is deprecated; use {new}")
+ return native.__get__(self, cls)
+
+ def set_former(self, value):
+ _deprecated(f"{name}.{old} is deprecated; use {new}")
+ native.__set__(self, value)
+
+ _set_property(
+ cls,
+ new,
+ _member(cls, current, new),
+ documentation,
+ _member(cls, set_current, new),
+ )
+ _set_property(
+ cls,
+ old,
+ _member(cls, former, old),
+ f"Deprecated since 0.8.5: use {new}.",
+ _member(cls, set_former, old),
+ )
+ return native
+
+
+# Old keyword and attribute name -> (new name, the native attribute behind both).
+_QG_RENAMED = {
+ "graph_degree": (
+ "max_degree",
+ _rename_parameter(
+ QGKMeansParameters,
+ "graph_degree",
+ "max_degree",
+ "Centroid graph degree; a positive multiple of 32. Default is 32. Named "
+ "graph_degree before 0.8.5.",
+ ),
+ ),
+ "ef_build": (
+ "ef_construction",
+ _rename_parameter(
+ QGKMeansParameters,
+ "ef_build",
+ "ef_construction",
+ "Positive centroid-graph construction search breadth. Default is 240. "
+ "Named ef_build before 0.8.5.",
+ ),
+ ),
+ "quantization_bits": (
+ "nbits",
+ _rename_parameter(
+ QGKMeansParameters,
+ "quantization_bits",
+ "nbits",
+ "Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is "
+ "32. Named quantization_bits, with 0 for raw float32, before 0.8.5.",
+ _qg_nbits_to_native,
+ _qg_nbits_from_native,
+ ),
+ ),
+}
+_patch_final_assignment(QGKMeansParameters)
+_patch_final_assignment(RaBitQKMeansParameters)
+
+_RENAMED_EXPORTS = {
+ "FinalAssignmentMode": (
+ _FinalAssignmentMode,
+ "FinalAssignmentMode is deprecated; pass 'approximate' or 'exact' as "
+ "final_assignment",
+ ),
+ "QGKMeansIterationStats": (
+ KMeansIterationStats,
+ "QGKMeansIterationStats is deprecated; use KMeansIterationStats",
+ ),
+ "RaBitQKMeansIterationStats": (
+ KMeansIterationStats,
+ "RaBitQKMeansIterationStats is deprecated; use KMeansIterationStats",
+ ),
+}
+
+
+def __getattr__(name):
+ try:
+ value, message = _RENAMED_EXPORTS[name]
+ except KeyError:
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
+ # "from rabitqlib import " asks twice: importlib checks the name before
+ # the import statement reads it. Warn for the statement only, at its line.
+ caller = sys._getframe().f_back # None when no Python code is calling
+ if caller is None or caller.f_code.co_name != "_handle_fromlist":
+ warnings.warn(f"{message}; {_MIGRATION}", DeprecationWarning, stacklevel=2)
+ return value
+
+
+# --- end of the 0.9 names ----------------------------------------------------
+
+
class _KMeans:
"""Shared result handling for the two clustering methods."""
@@ -387,15 +910,36 @@ def __init__(self, d, k, **kwargs):
self.d = int(d)
self.k = int(k)
self.cp = self._parameters_type()
+ self._keywords = frozenset(kwargs)
for name, value in kwargs.items():
+ renamed = self._renamed_parameters.get(name)
+ if renamed is not None:
+ new, native = renamed
+ if new in kwargs:
+ raise TypeError(
+ f"{type(self).__name__}() got both {new} and its old name {name}"
+ )
+ _deprecated(
+ f"{type(self).__name__}({name}=...) is deprecated; use {new}="
+ + (
+ ", with 32 instead of 0 for raw vectors"
+ if new == "nbits"
+ else ""
+ )
+ )
+ else:
+ try:
+ getattr(self.cp, name)
+ except AttributeError:
+ raise AttributeError(
+ f"{type(self).__name__}() got an unexpected keyword argument "
+ f"{name!r}"
+ ) from None
try:
- getattr(self.cp, name)
- except AttributeError:
- raise AttributeError(
- f"{type(self).__name__}() got an unexpected keyword argument {name!r}"
- ) from None
- try:
- setattr(self.cp, name, value)
+ if renamed is not None:
+ native.__set__(self.cp, value)
+ else:
+ setattr(self.cp, name, value)
except TypeError as error:
raise TypeError(
f"{type(self).__name__}() could not convert parameter {name!r} "
@@ -424,8 +968,19 @@ def train(self, x):
A failed fit preserves the last successful results. Returned arrays are
copies.
"""
- implementation = self._implementation_type(self.d, self.k, self.cp)
- objective = implementation.train(x)
+ try:
+ implementation = self._implementation_type(self.d, self.k, self.cp)
+ objective = implementation.train(x)
+ except ValueError as error:
+ # The extension names the 0.8 setting. A caller who wrote the 0.9
+ # keyword gets that name back; every 0.8 call keeps its message. A
+ # subclass may not have run __init__, hence the getattr.
+ message = str(error)
+ if "ef_build" not in message or "ef_construction" not in getattr(
+ self, "_keywords", ()
+ ):
+ raise
+ raise ValueError(message.replace("ef_build", "ef_construction")) from None
self._impl = implementation
return objective
@@ -505,7 +1060,7 @@ class QGKMeans(_KMeans):
d : int
Original vector dimension, from 64 through 65536.
k : int
- Number of centroids; greater than graph_degree and no more than the
+ Number of centroids; greater than max_degree and no more than the
number of training vectors.
niter : int, optional
Maximum number of clustering iterations. Default is 25.
@@ -529,22 +1084,24 @@ class QGKMeans(_KMeans):
num_threads : int, optional
Worker count; 0 selects the available CPU count,
capped by OMP_NUM_THREADS. Default is 0.
- final_assignment : FinalAssignmentMode, optional
- Approximate uses the training assignment method; Exact uses exhaustive
- assignment against final centroids. Default is
- FinalAssignmentMode.Approximate.
- graph_degree : int, optional
- Centroid graph degree; a positive multiple of 32. Default is 32.
- ef_build : int, optional
+ final_assignment : {'approximate', 'exact'}, optional
+ 'approximate' uses the training assignment method; 'exact' uses exhaustive
+ assignment against final centroids. Default is 'approximate'. A
+ FinalAssignmentMode member is still accepted until 0.9.
+ max_degree : int, optional
+ Centroid graph degree; a positive multiple of 32. Default is 32. Named
+ graph_degree before 0.8.5.
+ ef_construction : int, optional
Positive centroid-graph construction search breadth. Default is 240.
+ Named ef_build before 0.8.5.
ef_search : int, optional
Positive centroid-graph assignment search breadth. Default is 16.
graph_build_iterations : int, optional
Positive number of graph-building passes after initialization. Default
is 1.
- quantization_bits : int, optional
- Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is
- 0.
+ nbits : int, optional
+ Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is
+ 32. Named quantization_bits, with 0 for raw float32, before 0.8.5.
Notes
-----
@@ -561,6 +1118,7 @@ class QGKMeans(_KMeans):
_parameters_type = QGKMeansParameters
_implementation_type = _QGKMeans
+ _renamed_parameters = _QG_RENAMED
class RaBitQKMeans(_KMeans):
@@ -594,10 +1152,10 @@ class RaBitQKMeans(_KMeans):
num_threads : int, optional
Worker count; 0 selects the available CPU count,
capped by OMP_NUM_THREADS. Default is 0.
- final_assignment : FinalAssignmentMode, optional
- Approximate uses the training assignment method; Exact uses exhaustive
- assignment against final centroids. Default is
- FinalAssignmentMode.Approximate.
+ final_assignment : {'approximate', 'exact'}, optional
+ 'approximate' uses the training assignment method; 'exact' uses exhaustive
+ assignment against final centroids. Default is 'approximate'. A
+ FinalAssignmentMode member is still accepted until 0.9.
Notes
-----
@@ -624,6 +1182,7 @@ class RaBitQKMeans(_KMeans):
_parameters_type = RaBitQKMeansParameters
_implementation_type = _RaBitQKMeans
+ _renamed_parameters = {}
__all__ = [
@@ -631,6 +1190,7 @@ class RaBitQKMeans(_KMeans):
"FormatError",
"HnswIndex",
"IvfIndex",
+ "KMeansIterationStats",
"QGKMeans",
"QGKMeansIterationStats",
"QGKMeansParameters",
diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi
index be276ee6..6539dccd 100644
--- a/python_bindings/__init__.pyi
+++ b/python_bindings/__init__.pyi
@@ -18,6 +18,7 @@ __all__ = [
"FormatError",
"HnswIndex",
"IvfIndex",
+ "KMeansIterationStats",
"QGKMeans",
"QGKMeansIterationStats",
"QGKMeansParameters",
@@ -30,8 +31,9 @@ __all__ = [
_Path: TypeAlias = str | bytes | bytearray | PathLike[str] | PathLike[bytes]
_Metric: TypeAlias = Literal["l2", "ip", "innerproduct", "cosine"]
-_Initializer: TypeAlias = Literal["auto", "flat", "flat_rabitq", "hnsw"]
+_Routing: TypeAlias = Literal["auto", "flat", "flat_rabitq", "hnsw"]
_QGInit: TypeAlias = Literal["pipnn", "random"]
+_FinalAssignment: TypeAlias = Literal["approximate", "exact"]
# Rank, ID ranges and Python bool (an int subtype) are validated at runtime.
_IntegerIds: TypeAlias = npt.NDArray[np.integer[Any]] | Sequence[int | np.integer[Any]]
@@ -39,6 +41,10 @@ class FormatError(ValueError, RuntimeError):
"""A damaged or mismatched index file or serialized byte string, or one this release cannot read. A subclass of both ValueError and RuntimeError."""
# pybind11 enums are not subclasses of enum.Enum.
+@deprecated(
+ "FinalAssignmentMode is deprecated since 0.8.5; pass 'approximate' or 'exact' "
+ "as final_assignment"
+)
class FinalAssignmentMode:
"""Final centroid assignment policy.
@@ -59,7 +65,7 @@ class FinalAssignmentMode:
def __int__(self) -> int: ...
def __index__(self) -> int: ...
-class QGKMeansIterationStats:
+class KMeansIterationStats:
"""Read-only statistics for one completed clustering iteration."""
@property
@@ -75,7 +81,9 @@ class QGKMeansIterationStats:
def nsplit(self) -> int:
"""Number of empty centroids repaired by splitting."""
-RaBitQKMeansIterationStats = QGKMeansIterationStats
+# The two 0.8 names of KMeansIterationStats; deprecated since 0.8.5.
+QGKMeansIterationStats = KMeansIterationStats
+RaBitQKMeansIterationStats = KMeansIterationStats
class IvfIndex:
"""An approximate nearest-neighbor index using IVF.
@@ -92,8 +100,9 @@ class IvfIndex:
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine'
scales data and queries to unit length.
- initializer : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
- Centroid routing strategy. Default is 'auto'.
+ routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
+ Centroid routing strategy. Default is 'auto'. Named initializer before
+ 0.8.5.
seed : int, optional
Rotation seed in [0, 2**32 - 1], also the initial cp.seed. None
(default) draws one at random; the seed property reports it.
@@ -130,7 +139,7 @@ class IvfIndex:
*,
nbits: SupportsIndex = 7,
metric: _Metric = "l2",
- initializer: _Initializer = "auto",
+ routing: _Routing = "auto",
seed: SupportsIndex | None = None,
) -> None:
"""An approximate nearest-neighbor index using IVF.
@@ -147,8 +156,9 @@ class IvfIndex:
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine'
scales data and queries to unit length.
- initializer : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
- Centroid routing strategy. Default is 'auto'.
+ routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
+ Centroid routing strategy. Default is 'auto'. Named initializer before
+ 0.8.5.
seed : int, optional
Rotation seed in [0, 2**32 - 1], also the initial cp.seed. None
(default) draws one at random; the seed property reports it.
@@ -177,7 +187,19 @@ class IvfIndex:
num_clusters: SupportsIndex,
nbits: SupportsIndex,
metric: _Metric = "l2",
- initializer: _Initializer = "auto",
+ initializer: _Routing = "auto",
+ ) -> None: ...
+ @overload
+ @deprecated("IvfIndex(initializer=...) is deprecated since 0.8.5; use routing=")
+ def __init__(
+ self,
+ dim: SupportsIndex,
+ num_clusters: SupportsIndex,
+ *,
+ nbits: SupportsIndex = 7,
+ metric: _Metric = "l2",
+ initializer: _Routing,
+ seed: SupportsIndex | None = None,
) -> None: ...
def __repr__(self) -> str:
"""Return a one-line summary of configuration, counts and training state."""
@@ -190,8 +212,11 @@ class IvfIndex:
"""Original vector dimension."""
@property
+ @deprecated(
+ "IvfIndex.max_elements is deprecated since 0.8.5; use num_stored_points"
+ )
def max_elements(self) -> int:
- """Logical capacity: stored points, or the build row count of a 0.7-form index before build."""
+ """Deprecated since 0.8.5: use num_stored_points."""
@property
def num_points(self) -> int:
@@ -333,7 +358,7 @@ class IvfIndex:
float32; a copy may be made.
cluster_ids : array_like of int, shape (n,), optional
Keyword-only. Existing centroid IDs. None routes each vector using the
- index's configured centroid initializer; routing may be approximate.
+ index's configured routing strategy, which may be approximate.
Centroids do not move.
num_threads : int, optional
Keyword-only. Worker count. None (default) and 0 select the available
@@ -355,7 +380,7 @@ class IvfIndex:
untrained index raises RuntimeError, as does add on an index created with
max_elements, which build fills. If the call fails, the index stays
untrained and empty. Batch additions to reduce repeated cluster copying;
- reserve can preallocate room. Passing the options positionally is
+ reserve_cluster can preallocate room. Passing the options positionally is
deprecated.
"""
@overload
@@ -389,11 +414,13 @@ class IvfIndex:
Removal does not reclaim storage and cannot be undone.
"""
+ @overload
def search(
self,
queries: npt.ArrayLike,
k: SupportsIndex,
nprobe: SupportsIndex | None = None,
+ *,
high_accuracy: bool | np.bool_ | None = None,
num_threads: SupportsIndex | None = None,
) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]:
@@ -408,14 +435,17 @@ class IvfIndex:
Number of neighbors requested, at least 1. It may exceed the number of
points; slots without a neighbor are padded as described below.
nprobe : int, optional
- Number of clusters to probe, capped at num_clusters. None (default) and
- 0 select num_clusters / 16, rounded to the nearest integer and at least 1.
+ Number of clusters to probe, capped at num_clusters. None (default)
+ selects num_clusters / 16, rounded to the nearest integer and at least
+ 1; 0 does the same and is deprecated since 0.8.5.
high_accuracy : bool, optional
+ Keyword-only; passing it by position is deprecated since 0.8.5.
Enable HACC. None (default) selects it for 4-9 bits and standard
FastScan otherwise. Raw storage uses standard FastScan.
num_threads : int, optional
- Worker count. None (default) selects 1; 0 selects the available CPU
- count, capped by OMP_NUM_THREADS.
+ Keyword-only; passing it by position is deprecated since 0.8.5. Worker
+ count. None (default) selects 1; 0 selects the available CPU count,
+ capped by OMP_NUM_THREADS.
Returns
-------
@@ -432,7 +462,18 @@ class IvfIndex:
np.isfinite(distances) to find them. Array shapes
and value ranges are checked at runtime, not by static type checkers.
"""
-
+ @overload
+ @deprecated(
+ "Passing high_accuracy or num_threads to IvfIndex.search() by position is deprecated since 0.8.5; use keywords"
+ )
+ def search(
+ self,
+ queries: npt.ArrayLike,
+ k: SupportsIndex,
+ nprobe: SupportsIndex | None,
+ high_accuracy: bool | np.bool_ | None,
+ num_threads: SupportsIndex | None = ...,
+ ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]: ...
def save(self, path: _Path) -> None:
"""Save an index with stored vectors to disk.
@@ -470,10 +511,17 @@ class IvfIndex:
"""
@property
- def initializer(self) -> _Initializer:
- """Resolved centroid routing strategy."""
+ def routing(self) -> _Routing:
+ """Resolved centroid routing strategy. Named initializer before 0.8.5."""
- def reserve(self, cluster_id: SupportsIndex, num_points: SupportsIndex) -> None:
+ @property
+ @deprecated("IvfIndex.initializer is deprecated since 0.8.5; use routing")
+ def initializer(self) -> _Routing:
+ """Deprecated since 0.8.5: use routing."""
+
+ def reserve_cluster(
+ self, cluster_id: SupportsIndex, num_points: SupportsIndex
+ ) -> None:
"""Preallocate storage for a cluster.
Parameters
@@ -481,13 +529,19 @@ class IvfIndex:
cluster_id : int
Cluster ID in [0, num_clusters).
num_points : int
- Nonnegative capacity to reserve for this cluster.
+ Nonnegative capacity to reserve for this cluster: the total number
+ of points it can hold, including its current ones.
Notes
-----
- Requires a trained or loaded index. Reserved room is not saved.
+ Requires a trained or loaded index. Reserved room is not saved. Named
+ reserve before 0.8.5.
"""
+ @deprecated("IvfIndex.reserve() is deprecated since 0.8.5; use reserve_cluster()")
+ def reserve(self, cluster_id: SupportsIndex, num_points: SupportsIndex) -> None:
+ """Deprecated since 0.8.5: the same as reserve_cluster(); use reserve_cluster()."""
+
class HnswIndex:
"""An approximate nearest-neighbor index using HNSW.
@@ -511,7 +565,8 @@ class HnswIndex:
'l2'. 'cosine' scales data and queries to unit length.
seed : int, optional
Keyword-only. Graph and rotation seed, also the initial cp.seed (its low
- 32 bits). Default is 100.
+ 32 bits), in [0, 2**32 - 1]; larger values are deprecated since 0.8.5.
+ Default is 100.
Notes
-----
@@ -519,7 +574,7 @@ class HnswIndex:
on a sample, or set_centroids, first to choose the training data or the
centroids. Loaded indexes are trained, except empty files saved untrained
by 0.7. Capacity grows automatically
- on add; resize can preallocate it. Concurrent reads are supported; an
+ on add; reserve can preallocate it. Concurrent reads are supported; an
overlapping mutation raises RuntimeError.
Data, centroids and queries must be finite float32 values within the index
coordinate range; other values raise ValueError.
@@ -574,7 +629,8 @@ class HnswIndex:
'l2'. 'cosine' scales data and queries to unit length.
seed : int, optional
Keyword-only. Graph and rotation seed, also the initial cp.seed (its low
- 32 bits). Default is 100.
+ 32 bits), in [0, 2**32 - 1]; larger values are deprecated since 0.8.5.
+ Default is 100.
Notes
-----
@@ -582,7 +638,7 @@ class HnswIndex:
on a sample, or set_centroids, first to choose the training data or the
centroids. Loaded indexes are trained, except empty files saved untrained
by 0.7. Capacity grows automatically
- on add; resize can preallocate it. Concurrent reads are supported; an
+ on add; reserve can preallocate it. Concurrent reads are supported; an
overlapping mutation raises RuntimeError.
Data, centroids and queries must be finite float32 values within the index
coordinate range; other values raise ValueError.
@@ -630,8 +686,13 @@ class HnswIndex:
"""Original vector dimension."""
@property
+ def capacity(self) -> int:
+ """Current storage capacity, in stored points. Named max_elements before 0.8.5."""
+
+ @property
+ @deprecated("HnswIndex.max_elements is deprecated since 0.8.5; use capacity")
def max_elements(self) -> int:
- """Current storage capacity."""
+ """Deprecated since 0.8.5: use capacity."""
@property
def num_points(self) -> int:
@@ -831,11 +892,13 @@ class HnswIndex:
Removal does not reclaim storage and cannot be undone.
"""
+ @overload
def search(
self,
queries: npt.ArrayLike,
k: SupportsIndex,
- ef: SupportsIndex | None = None,
+ ef_search: SupportsIndex | None = None,
+ *,
num_threads: SupportsIndex | None = None,
) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]:
"""Search a batch of query vectors.
@@ -848,12 +911,14 @@ class HnswIndex:
k : int
Number of neighbors requested, at least 1. It may exceed the number of
points; slots without a neighbor are padded as described below.
- ef : int, optional
- Search breadth. None or 0 (default) selects max(k, 64); values above the stored
- point count are clamped.
+ ef_search : int, optional
+ Search breadth. None (default) selects max(k, 64); values above the stored
+ point count are clamped. 0 selects the default and is deprecated since
+ 0.8.5. Named ef before 0.8.5.
num_threads : int, optional
- Worker count. None (default) selects 1; 0 selects the available CPU
- count, capped by OMP_NUM_THREADS.
+ Keyword-only; passing it by position is deprecated since 0.8.5. Worker
+ count. None (default) selects 1; 0 selects the available CPU count,
+ capped by OMP_NUM_THREADS.
Returns
-------
@@ -870,7 +935,27 @@ class HnswIndex:
np.isfinite(distances) to find them. Array shapes
and value ranges are checked at runtime, not by static type checkers.
"""
-
+ @overload
+ @deprecated("HnswIndex.search(ef=...) is deprecated since 0.8.5; use ef_search=")
+ def search(
+ self,
+ queries: npt.ArrayLike,
+ k: SupportsIndex,
+ *,
+ ef: SupportsIndex | None,
+ num_threads: SupportsIndex | None = None,
+ ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]: ...
+ @overload
+ @deprecated(
+ "Passing num_threads to HnswIndex.search() by position is deprecated since 0.8.5; use the keyword"
+ )
+ def search(
+ self,
+ queries: npt.ArrayLike,
+ k: SupportsIndex,
+ ef_search: SupportsIndex | None,
+ num_threads: SupportsIndex | None,
+ ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]: ...
def save(self, path: _Path) -> None:
"""Save an index with stored vectors to disk.
@@ -903,15 +988,28 @@ class HnswIndex:
A trained index ready for search.
"""
- def resize(self, max_elements: SupportsIndex) -> None:
- """Change the storage capacity, for example to preallocate before add.
+ def reserve(self, num_points: SupportsIndex) -> None:
+ """Preallocate room for at least num_points stored points.
Parameters
----------
- max_elements : int
- New capacity; must be at least num_stored_points.
+ num_points : int
+ Nonnegative number of stored points to make room for, including the
+ current ones.
+
+ Notes
+ -----
+ Capacity only grows: a value at or below capacity changes nothing. add
+ also grows the capacity when needed, so reserve is an optimization.
"""
+ @deprecated(
+ "HnswIndex.resize() is deprecated since 0.8.5; use reserve(), which only "
+ "grows the capacity"
+ )
+ def resize(self, max_elements: SupportsIndex) -> None:
+ """Deprecated since 0.8.5: change the capacity; use reserve(), which only grows it."""
+
class SymqgIndex:
"""An approximate nearest-neighbor index using SymphonyQG.
@@ -1050,8 +1148,11 @@ class SymqgIndex:
"""Original vector dimension."""
@property
+ @deprecated(
+ "SymqgIndex.max_elements is deprecated since 0.8.5; use num_stored_points"
+ )
def max_elements(self) -> int:
- """Current storage capacity."""
+ """Deprecated since 0.8.5: use num_stored_points."""
@property
def num_points(self) -> int:
@@ -1181,11 +1282,13 @@ class SymqgIndex:
Graph initialization method. Default is 'pipnn'.
"""
+ @overload
def search(
self,
queries: npt.ArrayLike,
k: SupportsIndex,
- ef: SupportsIndex | None = None,
+ ef_search: SupportsIndex | None = None,
+ *,
num_threads: SupportsIndex | None = None,
) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]:
"""Search a batch of query vectors.
@@ -1198,12 +1301,14 @@ class SymqgIndex:
k : int
Number of neighbors requested, at least 1. It may exceed the number of
points; slots without a neighbor are padded as described below.
- ef : int, optional
- Search breadth. None or 0 (default) selects max(k, 64); smaller values
- are raised to k.
+ ef_search : int, optional
+ Search breadth. None (default) selects max(k, 64); smaller values
+ are raised to k. 0 selects the default and is deprecated since 0.8.5.
+ Named ef before 0.8.5.
num_threads : int, optional
- Worker count. None (default) selects 1; 0 selects the available CPU
- count, capped by OMP_NUM_THREADS.
+ Keyword-only; passing it by position is deprecated since 0.8.5. Worker
+ count. None (default) selects 1; 0 selects the available CPU count,
+ capped by OMP_NUM_THREADS.
Returns
-------
@@ -1220,7 +1325,27 @@ class SymqgIndex:
np.isfinite(distances) to find them. Array shapes and value ranges are
checked at runtime, not by static type checkers.
"""
-
+ @overload
+ @deprecated("SymqgIndex.search(ef=...) is deprecated since 0.8.5; use ef_search=")
+ def search(
+ self,
+ queries: npt.ArrayLike,
+ k: SupportsIndex,
+ *,
+ ef: SupportsIndex | None,
+ num_threads: SupportsIndex | None = None,
+ ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]: ...
+ @overload
+ @deprecated(
+ "Passing num_threads to SymqgIndex.search() by position is deprecated since 0.8.5; use the keyword"
+ )
+ def search(
+ self,
+ queries: npt.ArrayLike,
+ k: SupportsIndex,
+ ef_search: SupportsIndex | None,
+ num_threads: SupportsIndex | None,
+ ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]: ...
@deprecated("SymqgIndex.search_batch() is deprecated since 0.8; use search()")
def search_batch(
self,
@@ -1270,7 +1395,7 @@ class QGKMeans:
d : int
Original vector dimension, from 64 through 65536.
k : int
- Number of centroids; greater than graph_degree and no more than the
+ Number of centroids; greater than max_degree and no more than the
number of training vectors.
niter : int, optional
Maximum number of clustering iterations. Default is 25.
@@ -1294,22 +1419,24 @@ class QGKMeans:
num_threads : int, optional
Worker count; 0 selects the available CPU count,
capped by OMP_NUM_THREADS. Default is 0.
- final_assignment : FinalAssignmentMode, optional
- Approximate uses the training assignment method; Exact uses exhaustive
- assignment against final centroids. Default is
- FinalAssignmentMode.Approximate.
- graph_degree : int, optional
- Centroid graph degree; a positive multiple of 32. Default is 32.
- ef_build : int, optional
+ final_assignment : {'approximate', 'exact'}, optional
+ 'approximate' uses the training assignment method; 'exact' uses exhaustive
+ assignment against final centroids. Default is 'approximate'. A
+ FinalAssignmentMode member is still accepted until 0.9.
+ max_degree : int, optional
+ Centroid graph degree; a positive multiple of 32. Default is 32. Named
+ graph_degree before 0.8.5.
+ ef_construction : int, optional
Positive centroid-graph construction search breadth. Default is 240.
+ Named ef_build before 0.8.5.
ef_search : int, optional
Positive centroid-graph assignment search breadth. Default is 16.
graph_build_iterations : int, optional
Positive number of graph-building passes after initialization. Default
is 1.
- quantization_bits : int, optional
- Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is
- 0.
+ nbits : int, optional
+ Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is
+ 32. Named quantization_bits, with 0 for raw float32, before 0.8.5.
Notes
-----
@@ -1328,6 +1455,7 @@ class QGKMeans:
k: int
cp: QGKMeansParameters
+ @overload
def __init__(
self,
d: SupportsIndex,
@@ -1341,12 +1469,12 @@ class QGKMeans:
max_points_per_centroid: SupportsIndex = 0,
early_stop_threshold: float = 0.0,
num_threads: SupportsIndex = 0,
- final_assignment: FinalAssignmentMode = FinalAssignmentMode.Approximate,
- graph_degree: SupportsIndex = 32,
- ef_build: SupportsIndex = 240,
+ final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate",
+ max_degree: SupportsIndex = 32,
+ ef_construction: SupportsIndex = 240,
ef_search: SupportsIndex = 16,
graph_build_iterations: SupportsIndex = 1,
- quantization_bits: SupportsIndex = 0,
+ nbits: SupportsIndex = 32,
) -> None:
"""Cluster vectors using SymphonyQG graph assignment.
@@ -1355,7 +1483,7 @@ class QGKMeans:
d : int
Original vector dimension, from 64 through 65536.
k : int
- Number of centroids; greater than graph_degree and no more than the
+ Number of centroids; greater than max_degree and no more than the
number of training vectors.
niter : int, optional
Maximum number of clustering iterations. Default is 25.
@@ -1379,22 +1507,24 @@ class QGKMeans:
num_threads : int, optional
Worker count; 0 selects the available CPU count,
capped by OMP_NUM_THREADS. Default is 0.
- final_assignment : FinalAssignmentMode, optional
- Approximate uses the training assignment method; Exact uses exhaustive
- assignment against final centroids. Default is
- FinalAssignmentMode.Approximate.
- graph_degree : int, optional
- Centroid graph degree; a positive multiple of 32. Default is 32.
- ef_build : int, optional
+ final_assignment : {'approximate', 'exact'}, optional
+ 'approximate' uses the training assignment method; 'exact' uses exhaustive
+ assignment against final centroids. Default is 'approximate'. A
+ FinalAssignmentMode member is still accepted until 0.9.
+ max_degree : int, optional
+ Centroid graph degree; a positive multiple of 32. Default is 32. Named
+ graph_degree before 0.8.5.
+ ef_construction : int, optional
Positive centroid-graph construction search breadth. Default is 240.
+ Named ef_build before 0.8.5.
ef_search : int, optional
Positive centroid-graph assignment search breadth. Default is 16.
graph_build_iterations : int, optional
Positive number of graph-building passes after initialization. Default
is 1.
- quantization_bits : int, optional
- Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is
- 0.
+ nbits : int, optional
+ Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is
+ 32. Named quantization_bits, with 0 for raw float32, before 0.8.5.
Notes
-----
@@ -1409,6 +1539,79 @@ class QGKMeans:
kinds of objective are not directly comparable.
"""
+ @overload
+ @deprecated(
+ "QGKMeans(quantization_bits=...) is deprecated since 0.8.5; use nbits=, with 32 instead of 0 for raw vectors"
+ )
+ def __init__(
+ self,
+ d: SupportsIndex,
+ k: SupportsIndex,
+ *,
+ quantization_bits: SupportsIndex,
+ niter: SupportsIndex = 25,
+ verbose: bool | np.bool_ = False,
+ spherical: bool | np.bool_ = False,
+ seed: SupportsIndex = 42,
+ min_points_per_centroid: SupportsIndex = 39,
+ max_points_per_centroid: SupportsIndex = 0,
+ early_stop_threshold: float = 0.0,
+ num_threads: SupportsIndex = 0,
+ final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate",
+ ef_search: SupportsIndex = 16,
+ graph_build_iterations: SupportsIndex = 1,
+ graph_degree: SupportsIndex = ...,
+ ef_build: SupportsIndex = ...,
+ max_degree: SupportsIndex = 32,
+ ef_construction: SupportsIndex = 240,
+ ) -> None: ...
+ @overload
+ @deprecated("QGKMeans(graph_degree=...) is deprecated since 0.8.5; use max_degree=")
+ def __init__(
+ self,
+ d: SupportsIndex,
+ k: SupportsIndex,
+ *,
+ graph_degree: SupportsIndex,
+ niter: SupportsIndex = 25,
+ verbose: bool | np.bool_ = False,
+ spherical: bool | np.bool_ = False,
+ seed: SupportsIndex = 42,
+ min_points_per_centroid: SupportsIndex = 39,
+ max_points_per_centroid: SupportsIndex = 0,
+ early_stop_threshold: float = 0.0,
+ num_threads: SupportsIndex = 0,
+ final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate",
+ ef_search: SupportsIndex = 16,
+ graph_build_iterations: SupportsIndex = 1,
+ ef_build: SupportsIndex = ...,
+ ef_construction: SupportsIndex = 240,
+ nbits: SupportsIndex = 32,
+ ) -> None: ...
+ @overload
+ @deprecated(
+ "QGKMeans(ef_build=...) is deprecated since 0.8.5; use ef_construction="
+ )
+ def __init__(
+ self,
+ d: SupportsIndex,
+ k: SupportsIndex,
+ *,
+ ef_build: SupportsIndex,
+ niter: SupportsIndex = 25,
+ verbose: bool | np.bool_ = False,
+ spherical: bool | np.bool_ = False,
+ seed: SupportsIndex = 42,
+ min_points_per_centroid: SupportsIndex = 39,
+ max_points_per_centroid: SupportsIndex = 0,
+ early_stop_threshold: float = 0.0,
+ num_threads: SupportsIndex = 0,
+ final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate",
+ ef_search: SupportsIndex = 16,
+ graph_build_iterations: SupportsIndex = 1,
+ max_degree: SupportsIndex = 32,
+ nbits: SupportsIndex = 32,
+ ) -> None: ...
def train(self, x: npt.ArrayLike) -> float:
"""Train centroids and retain the final assignments.
@@ -1488,7 +1691,7 @@ class QGKMeans:
"""Objective for the final assignments of all n vectors, or None before training."""
@property
- def iteration_stats(self) -> list[QGKMeansIterationStats] | None:
+ def iteration_stats(self) -> list[KMeansIterationStats] | None:
"""Per-iteration statistics over the vectors used for iterations, or None before training."""
class QGKMeansParameters:
@@ -1539,19 +1742,44 @@ class QGKMeansParameters:
"""Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0."""
@num_threads.setter
def num_threads(self, value: SupportsIndex) -> None: ...
-
- final_assignment: FinalAssignmentMode
- """Approximate uses the training assignment method; Exact uses exhaustive assignment against final centroids. Default is FinalAssignmentMode.Approximate."""
-
@property
+ def final_assignment(self) -> FinalAssignmentMode:
+ """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'. Until 0.9 it reads back as the FinalAssignmentMode member, which is still accepted."""
+ @final_assignment.setter
+ def final_assignment(
+ self, value: _FinalAssignment | FinalAssignmentMode
+ ) -> None: ...
+ @property
+ def max_degree(self) -> int:
+ """Centroid graph degree; a positive multiple of 32. Default is 32. Named graph_degree before 0.8.5."""
+ @max_degree.setter
+ def max_degree(self, value: SupportsIndex) -> None: ...
+ @property
+ @deprecated(
+ "QGKMeansParameters.graph_degree is deprecated since 0.8.5; use max_degree"
+ )
def graph_degree(self) -> int:
- """Centroid graph degree; a positive multiple of 32. Default is 32."""
+ """Deprecated since 0.8.5: use max_degree."""
@graph_degree.setter
+ @deprecated(
+ "QGKMeansParameters.graph_degree is deprecated since 0.8.5; use max_degree"
+ )
def graph_degree(self, value: SupportsIndex) -> None: ...
@property
+ def ef_construction(self) -> int:
+ """Positive centroid-graph construction search breadth. Default is 240. Named ef_build before 0.8.5."""
+ @ef_construction.setter
+ def ef_construction(self, value: SupportsIndex) -> None: ...
+ @property
+ @deprecated(
+ "QGKMeansParameters.ef_build is deprecated since 0.8.5; use ef_construction"
+ )
def ef_build(self) -> int:
- """Positive centroid-graph construction search breadth. Default is 240."""
+ """Deprecated since 0.8.5: use ef_construction."""
@ef_build.setter
+ @deprecated(
+ "QGKMeansParameters.ef_build is deprecated since 0.8.5; use ef_construction"
+ )
def ef_build(self, value: SupportsIndex) -> None: ...
@property
def ef_search(self) -> int:
@@ -1564,9 +1792,20 @@ class QGKMeansParameters:
@graph_build_iterations.setter
def graph_build_iterations(self, value: SupportsIndex) -> None: ...
@property
+ def nbits(self) -> int:
+ """Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is 32. Named quantization_bits, with 0 for raw float32, before 0.8.5."""
+ @nbits.setter
+ def nbits(self, value: SupportsIndex) -> None: ...
+ @property
+ @deprecated(
+ "QGKMeansParameters.quantization_bits is deprecated since 0.8.5; use nbits"
+ )
def quantization_bits(self) -> int:
- """Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is 0."""
+ """Deprecated since 0.8.5: use nbits."""
@quantization_bits.setter
+ @deprecated(
+ "QGKMeansParameters.quantization_bits is deprecated since 0.8.5; use nbits"
+ )
def quantization_bits(self, value: SupportsIndex) -> None: ...
def __init__(self) -> None:
"""Create parameters with their documented defaults."""
@@ -1602,10 +1841,10 @@ class RaBitQKMeans:
num_threads : int, optional
Worker count; 0 selects the available CPU count,
capped by OMP_NUM_THREADS. Default is 0.
- final_assignment : FinalAssignmentMode, optional
- Approximate uses the training assignment method; Exact uses exhaustive
- assignment against final centroids. Default is
- FinalAssignmentMode.Approximate.
+ final_assignment : {'approximate', 'exact'}, optional
+ 'approximate' uses the training assignment method; 'exact' uses exhaustive
+ assignment against final centroids. Default is 'approximate'. A
+ FinalAssignmentMode member is still accepted until 0.9.
Notes
-----
@@ -1647,7 +1886,7 @@ class RaBitQKMeans:
max_points_per_centroid: SupportsIndex = 0,
early_stop_threshold: float = 0.0,
num_threads: SupportsIndex = 0,
- final_assignment: FinalAssignmentMode = FinalAssignmentMode.Approximate,
+ final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate",
) -> None:
"""Cluster vectors using flat RaBitQ assignment.
@@ -1679,10 +1918,10 @@ class RaBitQKMeans:
num_threads : int, optional
Worker count; 0 selects the available CPU count,
capped by OMP_NUM_THREADS. Default is 0.
- final_assignment : FinalAssignmentMode, optional
- Approximate uses the training assignment method; Exact uses exhaustive
- assignment against final centroids. Default is
- FinalAssignmentMode.Approximate.
+ final_assignment : {'approximate', 'exact'}, optional
+ 'approximate' uses the training assignment method; 'exact' uses exhaustive
+ assignment against final centroids. Default is 'approximate'. A
+ FinalAssignmentMode member is still accepted until 0.9.
Notes
-----
@@ -1786,7 +2025,7 @@ class RaBitQKMeans:
"""Objective for the final assignments of all n vectors, or None before training."""
@property
- def iteration_stats(self) -> list[QGKMeansIterationStats] | None:
+ def iteration_stats(self) -> list[KMeansIterationStats] | None:
"""Per-iteration statistics over the vectors used for iterations, or None before training."""
class RaBitQKMeansParameters:
@@ -1837,9 +2076,12 @@ class RaBitQKMeansParameters:
"""Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0."""
@num_threads.setter
def num_threads(self, value: SupportsIndex) -> None: ...
-
- final_assignment: FinalAssignmentMode
- """Approximate uses the training assignment method; Exact uses exhaustive assignment against final centroids. Default is FinalAssignmentMode.Approximate."""
-
+ @property
+ def final_assignment(self) -> FinalAssignmentMode:
+ """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'. Until 0.9 it reads back as the FinalAssignmentMode member, which is still accepted."""
+ @final_assignment.setter
+ def final_assignment(
+ self, value: _FinalAssignment | FinalAssignmentMode
+ ) -> None: ...
def __init__(self) -> None:
"""Create parameters with their documented defaults."""
diff --git a/sample/python/README.md b/sample/python/README.md
index 8806618b..20513d56 100644
--- a/sample/python/README.md
+++ b/sample/python/README.md
@@ -1,7 +1,7 @@
# Python examples
Run these commands from the repository root in your project Python environment
-with `rabitqlib>=0.8.1` and NumPy installed. When working from source,
+with `rabitqlib>=0.8.5` and NumPy installed. When working from source,
[install the library from the same checkout](../../.github/CONTRIBUTING.md#python-changes)
so the examples and native extension use matching APIs. Clustering and indexing
both use RaBitQ Library; FAISS is needed only for `compare_with_faiss.py`.
diff --git a/sample/python/clustering_cli/ivf.py b/sample/python/clustering_cli/ivf.py
index 5bb589d4..bd20f4b4 100644
--- a/sample/python/clustering_cli/ivf.py
+++ b/sample/python/clustering_cli/ivf.py
@@ -1,7 +1,7 @@
import argparse
from time import time
-from rabitqlib import FinalAssignmentMode, QGKMeans, RaBitQKMeans
+from rabitqlib import QGKMeans, RaBitQKMeans
from utils.io import read_fvecs, write_fvecs, write_ivecs
if __name__ == "__main__":
@@ -45,7 +45,7 @@
dim,
K,
spherical=metric == "ip",
- final_assignment=FinalAssignmentMode.Exact,
+ final_assignment="exact",
verbose=True,
)
kmeans.train(X)
diff --git a/sample/python/hnsw_rabitq_querying.py b/sample/python/hnsw_rabitq_querying.py
index 7f276c1c..f8132140 100644
--- a/sample/python/hnsw_rabitq_querying.py
+++ b/sample/python/hnsw_rabitq_querying.py
@@ -37,7 +37,7 @@ def main(args=None) -> None:
for r in range(args.test_rounds):
t0 = perf_counter()
ids, _ = idx.search(
- queries, k=args.topk, ef=ef, num_threads=args.num_threads
+ queries, k=args.topk, ef_search=ef, num_threads=args.num_threads
)
elapsed = perf_counter() - t0 # seconds
diff --git a/sample/python/kmeans_clustering.py b/sample/python/kmeans_clustering.py
index 79b99e6d..ddd20ade 100644
--- a/sample/python/kmeans_clustering.py
+++ b/sample/python/kmeans_clustering.py
@@ -4,7 +4,7 @@
from time import time
import numpy as np
-from rabitqlib import FinalAssignmentMode, QGKMeans, RaBitQKMeans
+from rabitqlib import QGKMeans, RaBitQKMeans
from rabitqlib._rabitqlib import _available_cpu_count, _default_thread_count
from utils import read_fvecs
@@ -37,7 +37,7 @@ def cluster_data(
num_clusters,
spherical=metric == "ip",
num_threads=threads,
- final_assignment=FinalAssignmentMode.Exact,
+ final_assignment="exact",
verbose=True,
)
start = time()
@@ -71,7 +71,7 @@ def main(args) -> None:
"--method",
choices=["rabitq", "qg"],
default="qg",
- help="rabitq for few centroids; qg for many (requires k > graph_degree)",
+ help="rabitq for few centroids; qg for many (requires k > max_degree)",
)
parser.add_argument(
"--num-threads",
diff --git a/sample/python/symqg_querying.py b/sample/python/symqg_querying.py
index 035282a4..91750333 100644
--- a/sample/python/symqg_querying.py
+++ b/sample/python/symqg_querying.py
@@ -38,7 +38,7 @@ def main(args=None) -> None:
for r in range(args.test_rounds):
t0 = perf_counter()
ids, _ = idx.search(
- queries, k=args.topk, ef=ef, num_threads=args.num_threads
+ queries, k=args.topk, ef_search=ef, num_threads=args.num_threads
)
elapsed = perf_counter() - t0 # seconds
diff --git a/tests/python/test_compat_09.py b/tests/python/test_compat_09.py
new file mode 100644
index 00000000..d7f35596
--- /dev/null
+++ b/tests/python/test_compat_09.py
@@ -0,0 +1,697 @@
+"""The 0.8 spellings that 0.9 renames: both work in 0.8.5, and the old one warns."""
+
+import _thread
+import inspect
+import pickle
+import sys
+import time
+import warnings
+
+import numpy as np
+import pytest
+import rabitqlib
+from conftest import DIM
+from rabitqlib import HnswIndex, IvfIndex, QGKMeans, RaBitQKMeans, SymqgIndex
+
+
+def single_deprecation(call, at=None):
+ """Run call and return its result and its one DeprecationWarning.
+
+ The warning must point at the code that used the old form: the lines of call,
+ or of the helper function at when call reaches the old form through it.
+ """
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ result = call()
+ assert [w.category for w in caught] == [DeprecationWarning], [
+ str(w.message) for w in caught
+ ]
+ # Attributed to the caller, so users see their own line.
+ assert caught[0].filename == __file__
+ lines = [
+ line for _, _, line in (at or call).__code__.co_lines() if line is not None
+ ]
+ assert min(lines) <= caught[0].lineno <= max(lines), (caught[0].lineno, lines)
+ assert "python_migration" in str(caught[0].message)
+ return result, str(caught[0].message)
+
+
+def silently(call):
+ """Run call, failing on any warning."""
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ return call()
+
+
+def assert_same(left, right):
+ np.testing.assert_array_equal(left[0], right[0])
+ np.testing.assert_array_equal(left[1], right[1])
+
+
+@pytest.fixture(scope="module")
+def ivf(base_data):
+ index = IvfIndex(DIM, 8, nbits=4, routing="flat", seed=3)
+ index.add(base_data, num_threads=1)
+ return index
+
+
+@pytest.fixture(scope="module")
+def hnsw(base_data):
+ index = HnswIndex(DIM, nbits=4, num_clusters=4, seed=3)
+ index.add(base_data, num_threads=1)
+ return index
+
+
+@pytest.fixture(scope="module")
+def symqg(base_data):
+ index = SymqgIndex(DIM, ef_construction=60, seed=3)
+ index.add(base_data, num_threads=1)
+ return index
+
+
+def test_routing_replaces_initializer(ivf):
+ assert silently(lambda: ivf.routing) == "flat"
+ value, message = single_deprecation(lambda: ivf.initializer)
+ assert value == "flat"
+ assert message.startswith("IvfIndex.initializer is deprecated; use routing")
+ old, message = single_deprecation(lambda: IvfIndex(DIM, 8, initializer="hnsw"))
+ assert message.startswith("IvfIndex(initializer=...) is deprecated; use routing=")
+ assert silently(lambda: old.routing) == "hnsw"
+ assert silently(lambda: IvfIndex(DIM, 8).routing) == "flat" # 'auto' resolves
+ with pytest.raises(
+ TypeError,
+ match="^IvfIndex\\(\\) got both routing and its old name initializer$",
+ ):
+ IvfIndex(DIM, 8, routing="flat", initializer="flat")
+ with pytest.raises(ValueError, match="^routing must be 'auto', 'flat'"):
+ IvfIndex(DIM, 8, routing="unknown")
+ assert "routing" in inspect.signature(IvfIndex).parameters
+ assert "initializer" not in inspect.signature(IvfIndex).parameters
+
+
+@pytest.mark.parametrize("kind", ["ivf", "symqg"])
+def test_max_elements_is_the_stored_count(kind, request):
+ index = request.getfixturevalue(kind)
+ value, message = single_deprecation(lambda: index.max_elements)
+ assert value == index.num_stored_points
+ assert message.startswith(
+ f"{type(index).__name__}.max_elements is deprecated; use num_stored_points"
+ )
+ assert not hasattr(type(index), "capacity")
+
+
+def test_hnsw_capacity_replaces_max_elements(hnsw):
+ capacity = silently(lambda: hnsw.capacity)
+ value, message = single_deprecation(lambda: hnsw.max_elements)
+ assert value == capacity >= hnsw.num_stored_points
+ assert message.startswith("HnswIndex.max_elements is deprecated; use capacity")
+
+
+def test_hnsw_reserve_only_grows(base_data):
+ index = HnswIndex(DIM, nbits=4, num_clusters=4, seed=3)
+ silently(lambda: index.reserve(500))
+ assert index.capacity == 500
+ index.add(base_data, num_threads=1)
+ for smaller in (0, len(base_data), 499, np.int64(500)):
+ silently(lambda smaller=smaller: index.reserve(smaller))
+ assert index.capacity == 500
+ silently(lambda: index.reserve(600))
+ assert index.capacity == 600
+ with pytest.raises(ValueError, match="^num_points must be non-negative$"):
+ index.reserve(-1)
+ with pytest.raises(TypeError):
+ index.reserve(1.5)
+ # resize still shrinks, as in 0.8, and warns.
+ _, message = single_deprecation(lambda: index.resize(len(base_data)))
+ assert message.startswith("HnswIndex.resize() is deprecated; use reserve()")
+ assert index.capacity == len(base_data)
+
+
+def test_reserve_cluster_replaces_ivf_reserve(base_data):
+ index = IvfIndex(DIM, 4, nbits=4, routing="flat", seed=3)
+ index.train(base_data, num_threads=1)
+ silently(lambda: index.reserve_cluster(0, 500))
+ silently(lambda: index.reserve_cluster(cluster_id=1, num_points=np.int64(500)))
+ _, message = single_deprecation(lambda: index.reserve(2, 500))
+ assert message.startswith("IvfIndex.reserve() is deprecated; use reserve_cluster()")
+ index.add(base_data, num_threads=1)
+ assert len(index) == len(base_data)
+ # Both names reach the extension: it rejects the same arguments for each.
+ for reserve in (index.reserve_cluster, index.reserve):
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ with pytest.raises(ValueError, match="^cluster_id must be in"):
+ reserve(4, 1)
+ with pytest.raises(ValueError, match="^num_points must be non-negative$"):
+ reserve(0, -1)
+ untrained = IvfIndex(DIM, 4)
+ with pytest.raises(
+ RuntimeError,
+ match="^IvfIndex must be trained or loaded before reserve_cluster$",
+ ):
+ untrained.reserve_cluster(0, 1)
+ with (
+ pytest.warns(DeprecationWarning),
+ pytest.raises(
+ RuntimeError, match="^IvfIndex must be trained or loaded before reserve$"
+ ),
+ ):
+ untrained.reserve(0, 1)
+
+
+@pytest.mark.parametrize("kind", ["hnsw", "symqg"])
+def test_ef_search_replaces_ef(kind, request, query_data):
+ index = request.getfixturevalue(kind)
+ name = type(index).__name__
+ queries = query_data
+ # A breadth of k finds other neighbors than the default of max(k, 64), so a
+ # wrapper that dropped the argument would fail the comparisons below.
+ expected = silently(lambda: index.search(queries, 3, ef_search=3))
+ assert not np.array_equal(expected[0], index.search(queries, 3)[0])
+ assert_same(silently(lambda: index.search(queries, 3, 3)), expected)
+ assert_same(
+ silently(lambda: index.search(queries, k=3, ef_search=3, num_threads=1)),
+ expected,
+ )
+ actual, message = single_deprecation(lambda: index.search(queries, 3, ef=3))
+ assert message.startswith(f"{name}.search(ef=...) is deprecated; use ef_search=")
+ assert_same(actual, expected)
+ actual, message = single_deprecation(lambda: index.search(queries, 3, 3, 1))
+ assert message.startswith(
+ f"passing num_threads to {name}.search() by position is deprecated"
+ )
+ assert_same(actual, expected)
+ # Every spelling reaches the extension, which rejects a negative value.
+ for call in (
+ lambda: index.search(queries, 3, -1),
+ lambda: index.search(queries, 3, ef_search=-1),
+ lambda: index.search(queries, 3, ef=-1),
+ lambda: index.search(queries, 3, num_threads=-1),
+ lambda: index.search(queries, 3, 3, -1),
+ ):
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ with pytest.raises(TypeError):
+ call()
+ parameters = inspect.signature(type(index).search).parameters
+ assert list(parameters) == ["self", "queries", "k", "ef_search", "num_threads"]
+ assert parameters["num_threads"].kind is inspect.Parameter.KEYWORD_ONLY
+
+
+@pytest.mark.parametrize("kind", ["ivf", "hnsw", "symqg"])
+def test_malformed_search_calls_raise_before_any_warning(kind, request, query_data):
+ index = request.getfixturevalue(kind)
+ name = type(index).__name__
+ queries = query_data
+ breadth = "nprobe" if kind == "ivf" else "ef_search"
+ calls = [
+ (lambda: index.search(queries, 3, 4, **{breadth: 4}), "multiple values"),
+ (lambda: index.search(queries, 3, 4, 1, 2, 3), "positional arguments"),
+ ]
+ if kind == "ivf":
+ calls.append(
+ (
+ lambda: index.search(queries, 3, 4, False, high_accuracy=False),
+ "got multiple values for argument 'high_accuracy'",
+ )
+ )
+ calls.append(
+ (
+ lambda: index.search(queries, 3, 4, False, 1, num_threads=1),
+ "got multiple values for argument 'num_threads'",
+ )
+ )
+ else:
+ calls.append(
+ (
+ lambda: index.search(queries, 3, 4, 1, num_threads=1),
+ "got multiple values for argument 'num_threads'",
+ )
+ )
+ calls.append(
+ (
+ lambda: index.search(queries, 3, ef=4, ef_search=4),
+ "got both ef_search and its old name ef",
+ )
+ )
+ calls.append(
+ (
+ lambda: index.search(queries, 3, 4, ef=4),
+ "got both ef_search and its old name ef",
+ )
+ )
+ for call, message in calls:
+ # silently turns a warning into an error, so a TypeError here means the
+ # call was rejected first.
+ with pytest.raises(TypeError, match=f"^{name}\\.search\\(\\) .*{message}"):
+ silently(call)
+
+
+@pytest.mark.parametrize("kind", ["hnsw", "symqg"])
+@pytest.mark.parametrize("zero", [0, np.int64(0), False, np.float32(0)])
+def test_zero_breadth_selects_the_default_and_warns(kind, zero, request, base_data):
+ index = request.getfixturevalue(kind)
+ queries = base_data[:5]
+ expected = silently(lambda: index.search(queries, 3))
+ assert_same(silently(lambda: index.search(queries, 3, None)), expected)
+ for call in (
+ lambda: index.search(queries, 3, zero),
+ lambda: index.search(queries, 3, ef_search=zero),
+ ):
+ actual, message = single_deprecation(call)
+ assert message.startswith(
+ f"{type(index).__name__}.search(ef_search=0) is deprecated; pass None"
+ )
+ assert_same(actual, expected)
+
+
+def test_ivf_search_options_become_keyword_only(ivf, base_data):
+ queries = base_data[:5]
+ expected = silently(
+ lambda: ivf.search(queries, 3, 4, high_accuracy=False, num_threads=1)
+ )
+ assert_same(
+ silently(lambda: ivf.search(queries, 3, nprobe=4, high_accuracy=False)),
+ expected,
+ )
+ actual, message = single_deprecation(lambda: ivf.search(queries, 3, 4, False))
+ assert message.startswith(
+ "passing high_accuracy to IvfIndex.search() by position is deprecated"
+ )
+ assert_same(actual, expected)
+ actual, message = single_deprecation(lambda: ivf.search(queries, 3, 4, False, 1))
+ assert message.startswith(
+ "passing high_accuracy, num_threads to IvfIndex.search() by position"
+ )
+ assert_same(actual, expected)
+ parameters = inspect.signature(IvfIndex.search).parameters
+ assert [
+ name
+ for name, parameter in parameters.items()
+ if parameter.kind is inspect.Parameter.KEYWORD_ONLY
+ ] == ["high_accuracy", "num_threads"]
+
+
+@pytest.mark.parametrize("zero", [0, np.int64(0), False, np.float32(0)])
+def test_zero_nprobe_selects_the_default_and_warns(ivf, zero, base_data):
+ queries = base_data[:5]
+ expected = silently(lambda: ivf.search(queries, 3))
+ for call in (
+ lambda: ivf.search(queries, 3, zero),
+ lambda: ivf.search(queries, 3, nprobe=zero),
+ ):
+ actual, message = single_deprecation(call)
+ assert message.startswith("IvfIndex.search(nprobe=0) is deprecated; pass None")
+ assert_same(actual, expected)
+
+
+def test_hnsw_seed_above_32_bits_warns():
+ for seed in (0, 100, 2**32 - 1, np.uint32(7)):
+ assert silently(lambda seed=seed: HnswIndex(DIM, seed=seed)).seed == seed
+ index, message = single_deprecation(lambda: HnswIndex(DIM, seed=2**40 + 5))
+ assert message.startswith("HnswIndex seeds above 2**32 - 1 are deprecated")
+ assert index.seed == 2**40 + 5
+ assert index.cp.seed == 5 # the low 32 bits, as before
+
+
+def test_deprecated_search_batch_warns_once(symqg, query_data):
+ expected = silently(lambda: symqg.search(query_data, 3, 3))
+ assert not np.array_equal(expected[0], symqg.search(query_data, 3)[0])
+ actual, message = single_deprecation(
+ lambda: symqg.search_batch(query_data, 3, 3, 1)
+ )
+ assert message.startswith("SymqgIndex.search_batch() is deprecated; use search()")
+ assert_same(actual, expected)
+
+
+def test_unchanged_forms_stay_silent(ivf, hnsw, symqg, query_data):
+ # 0.9 changes the HnswIndex default seed without a warning in this release.
+ assert silently(lambda: HnswIndex(DIM)).seed == 100
+ # num_threads=0 keeps meaning every available CPU.
+ for index in (ivf, hnsw, symqg):
+ silently(lambda index=index: index.search(query_data, 3, num_threads=0))
+
+
+def test_old_spelling_keeps_its_error_message():
+ with (
+ pytest.warns(DeprecationWarning, match="use routing="),
+ pytest.raises(ValueError, match="^initializer must be 'auto', 'flat'"),
+ ):
+ IvfIndex(DIM, 8, initializer="unknown")
+
+
+def test_new_members_are_named_after_their_class(ivf, hnsw):
+ assert HnswIndex.reserve.__qualname__ == "HnswIndex.reserve"
+ assert IvfIndex.reserve_cluster.__qualname__ == "IvfIndex.reserve_cluster"
+ for cls in (IvfIndex, HnswIndex, SymqgIndex):
+ assert cls.search.__qualname__ == f"{cls.__name__}.search"
+ with pytest.raises(
+ TypeError, match="^HnswIndex\\.reserve\\(\\) missing 1 required"
+ ):
+ hnsw.reserve()
+ with pytest.raises(AttributeError, match="'routing' of 'IvfIndex'"):
+ ivf.routing = "flat"
+ with pytest.raises(AttributeError, match="'capacity' of 'HnswIndex'"):
+ hnsw.capacity = 1
+
+
+def test_new_members_are_documented():
+ for member in (
+ IvfIndex.reserve_cluster,
+ HnswIndex.reserve,
+ IvfIndex.search,
+ HnswIndex.search,
+ SymqgIndex.search,
+ ):
+ assert member.__doc__.strip()
+ assert "(self:" not in member.__doc__ # no stale native signature line
+ for cls in (HnswIndex, SymqgIndex):
+ assert "ef_search : int, optional" in cls.search.__doc__
+ assert "\nef : int" not in cls.search.__doc__
+ assert "routing : {'auto'" in IvfIndex.__doc__
+ assert "initializer :" not in IvfIndex.__doc__
+ assert "reserve can preallocate it" in HnswIndex.__doc__
+ assert "reserve_cluster can preallocate room" in IvfIndex.add.__doc__
+ assert "centroid initializer" not in IvfIndex.add.__doc__
+
+
+# --- k-means: the names of issue #233 -----------------------------------------
+
+
+def qg_kmeans(**parameters):
+ return QGKMeans(DIM, 80, niter=2, num_threads=1, seed=1, **parameters)
+
+
+def test_qgkmeans_takes_the_index_parameter_names(base_data):
+ new = silently(lambda: qg_kmeans(nbits=4, max_degree=64, ef_construction=100))
+ assert (new.cp.nbits, new.cp.max_degree, new.cp.ef_construction) == (4, 64, 100)
+ for keyword, value, hint, current in (
+ ("quantization_bits", 4, "use nbits=, with 32 instead of 0", "nbits"),
+ ("graph_degree", 64, "use max_degree=", "max_degree"),
+ ("ef_build", 100, "use ef_construction=", "ef_construction"),
+ ):
+ model, message = single_deprecation(
+ lambda keyword=keyword, value=value: qg_kmeans(**{keyword: value}),
+ at=qg_kmeans,
+ )
+ assert message.startswith(f"QGKMeans({keyword}=...) is deprecated; {hint}")
+ # The old keyword reaches the same setting, which differs from its default.
+ assert (
+ getattr(model.cp, current)
+ == value
+ != getattr(QGKMeans(DIM, 80).cp, current)
+ )
+ with pytest.raises(
+ TypeError,
+ match=f"^QGKMeans\\(\\) got both {current} and its old name {keyword}$",
+ ):
+ silently(
+ lambda keyword=keyword, value=value, current=current: qg_kmeans(
+ **{keyword: value, current: value}
+ )
+ )
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ old = qg_kmeans(quantization_bits=4, graph_degree=64, ef_build=100)
+ new.train(base_data)
+ old.train(base_data)
+ np.testing.assert_array_equal(new.centroids, old.centroids)
+ np.testing.assert_array_equal(new.assignments, old.assignments)
+
+
+def test_qgkmeans_nbits_uses_32_for_raw_vectors():
+ assert silently(lambda: QGKMeans(DIM, 80).cp.nbits) == 32
+ for nbits, stored in ((32, 0), (4, 4), (8, 8), (np.int64(32), 0)):
+ model = silently(lambda nbits=nbits: qg_kmeans(nbits=nbits))
+ assert model.cp.nbits == nbits
+ with pytest.warns(DeprecationWarning, match="use nbits"):
+ assert model.cp.quantization_bits == stored
+ raw, _ = single_deprecation(lambda: qg_kmeans(quantization_bits=0), at=qg_kmeans)
+ assert raw.cp.nbits == 32
+ for invalid in (0, 16, 33, True):
+ with pytest.raises(ValueError, match="^nbits must be 4, 8, or 32$"):
+ qg_kmeans(nbits=invalid)
+ with pytest.raises(ValueError, match="^nbits must be 4, 8, or 32$"):
+ QGKMeans(DIM, 80).cp.nbits = invalid
+ with pytest.raises(TypeError, match="could not convert parameter 'nbits'"):
+ qg_kmeans(nbits="4")
+
+
+def test_qgkmeans_parameter_attributes_are_renamed():
+ cp = QGKMeans(DIM, 80).cp
+ for old, new, value in (
+ ("graph_degree", "max_degree", 64),
+ ("ef_build", "ef_construction", 100),
+ ("quantization_bits", "nbits", 8),
+ ):
+ silently(lambda new=new, value=value: setattr(cp, new, value))
+ assert silently(lambda new=new: getattr(cp, new)) == value
+ read, message = single_deprecation(lambda old=old: getattr(cp, old))
+ assert read == value
+ assert message.startswith(f"QGKMeansParameters.{old} is deprecated; use {new}")
+ _, message = single_deprecation(
+ lambda old=old: setattr(cp, old, 4 if new == "nbits" else 32)
+ )
+ assert message.startswith(f"QGKMeansParameters.{old} is deprecated; use {new}")
+ assert getattr(cp, new) == (4 if new == "nbits" else 32)
+ for name in ("nbits", "max_degree", "ef_construction", "graph_degree"):
+ with pytest.raises(AttributeError, match="unexpected keyword argument"):
+ RaBitQKMeans(DIM, 4, **{name: 32})
+
+
+@pytest.mark.parametrize("cls", [QGKMeans, RaBitQKMeans])
+def test_final_assignment_takes_a_string(cls, base_data):
+ def trained(final_assignment):
+ model = cls(
+ DIM, 80, niter=2, num_threads=1, seed=1, final_assignment=final_assignment
+ )
+ model.train(base_data)
+ return model
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ modes = rabitqlib.FinalAssignmentMode
+ for text, member in (("exact", modes.Exact), ("approximate", modes.Approximate)):
+ by_text = silently(lambda text=text: trained(text))
+ # A member is still accepted, silently: its name warned where it was read.
+ by_member = silently(lambda member=member: trained(member))
+ assert by_text.cp.final_assignment == member # reads back as the member
+ np.testing.assert_array_equal(by_text.assignments, by_member.assignments)
+ np.testing.assert_array_equal(by_text.distances, by_member.distances)
+ cp = cls(DIM, 80).cp
+ silently(lambda cp=cp, text=text: setattr(cp, "final_assignment", text))
+ assert cp.final_assignment == member
+ for invalid in ("Exact", "EXACT", "", "symphonyqg"):
+ with pytest.raises(
+ ValueError, match="^final_assignment must be 'approximate' or 'exact'$"
+ ):
+ cls(DIM, 80, final_assignment=invalid)
+ with pytest.raises(
+ TypeError, match="could not convert parameter 'final_assignment'"
+ ):
+ cls(DIM, 80, final_assignment=1)
+
+
+def test_index_training_parameters_take_the_string(base_data):
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ modes = rabitqlib.FinalAssignmentMode
+ for index in (IvfIndex(DIM, 8, seed=3), HnswIndex(DIM, num_clusters=8, seed=3)):
+ for value, member in (
+ ("exact", modes.Exact),
+ ("approximate", modes.Approximate),
+ (modes.Exact, modes.Exact),
+ (modes.SymphonyQG, modes.Approximate),
+ ):
+ silently(
+ lambda index=index, value=value: setattr(
+ index.cp, "final_assignment", value
+ )
+ )
+ assert index.cp.final_assignment == member
+ with pytest.raises(
+ ValueError, match="^final_assignment must be 'approximate' or 'exact'$"
+ ):
+ index.cp.final_assignment = "Exact"
+ with pytest.raises(
+ TypeError,
+ match="^final_assignment must be 'approximate' or 'exact', not int$",
+ ):
+ index.cp.final_assignment = 1
+ assert index.cp.final_assignment == modes.Approximate # unchanged by failures
+ silently(lambda index=index: index.train(base_data, num_threads=1))
+ assert index.is_trained
+
+
+def _import_final_assignment_mode():
+ from rabitqlib import FinalAssignmentMode
+
+ return FinalAssignmentMode
+
+
+def _import_qg_stats():
+ from rabitqlib import QGKMeansIterationStats
+
+ return QGKMeansIterationStats
+
+
+def _import_rabitq_stats():
+ from rabitqlib import RaBitQKMeansIterationStats
+
+ return RaBitQKMeansIterationStats
+
+
+@pytest.mark.parametrize(
+ "name,importer,message",
+ [
+ (
+ "FinalAssignmentMode",
+ _import_final_assignment_mode,
+ "FinalAssignmentMode is deprecated; pass 'approximate'",
+ ),
+ (
+ "QGKMeansIterationStats",
+ _import_qg_stats,
+ "QGKMeansIterationStats is deprecated; use KMeansIterationStats",
+ ),
+ (
+ "RaBitQKMeansIterationStats",
+ _import_rabitq_stats,
+ "RaBitQKMeansIterationStats is deprecated; use KMeansIterationStats",
+ ),
+ ],
+)
+def test_names_that_leave_the_package_warn_once(name, importer, message):
+ value, text = single_deprecation(lambda: getattr(rabitqlib, name))
+ assert text.startswith(message)
+ imported, text = single_deprecation(importer, at=importer)
+ assert text.startswith(message)
+ assert imported is value
+ assert name in rabitqlib.__all__
+ # hasattr reads the name too.
+ found, text = single_deprecation(lambda: hasattr(rabitqlib, name))
+ assert found and text.startswith(message)
+
+
+def test_old_names_can_be_read_without_a_python_caller():
+ # A thread whose entry point is a builtin has no Python frame for the warning
+ # to point at; the read must still succeed. list.extend and map are builtins,
+ # so getattr runs in the new thread with no Python code calling it.
+ read = []
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ expected = rabitqlib.FinalAssignmentMode
+ _thread.start_new_thread(
+ read.extend, (map(getattr, [rabitqlib], ["FinalAssignmentMode"]),)
+ )
+ # A failed read leaves the list empty, so this waits out the deadline.
+ deadline = time.monotonic() + 5
+ while not read and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert read == [expected]
+
+
+def test_kmeans_iteration_stats_is_one_class(base_data):
+ stats = silently(lambda: rabitqlib.KMeansIterationStats)
+ assert stats.__name__ == stats.__qualname__ == "KMeansIterationStats"
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ assert rabitqlib.QGKMeansIterationStats is stats
+ assert rabitqlib.RaBitQKMeansIterationStats is stats
+ for cls in (QGKMeans, RaBitQKMeans):
+ model = cls(DIM, 80, niter=2, num_threads=1, seed=1)
+ model.train(base_data)
+ assert all(type(item) is stats for item in model.iteration_stats)
+ with pytest.raises(
+ AttributeError, match="^module 'rabitqlib' has no attribute 'missing'$"
+ ):
+ rabitqlib.missing
+
+
+def test_star_import_still_provides_the_old_names():
+ namespace = {}
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ exec("from rabitqlib import *", namespace)
+ assert set(rabitqlib.__all__) <= set(namespace)
+ assert [w.category for w in caught] == [DeprecationWarning] * 3
+
+
+def test_old_attribute_keeps_the_08_encoding():
+ cp = QGKMeans(DIM, 80).cp
+ cp.nbits = 8
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ cp.quantization_bits = 0 # raw vectors in the 0.8 encoding
+ assert cp.quantization_bits == 0
+ assert cp.nbits == 32
+
+
+def test_subclass_warnings_name_the_subclass():
+ class Clustering(QGKMeans):
+ pass
+
+ def make():
+ return Clustering(DIM, 80, graph_degree=64)
+
+ model, message = single_deprecation(make, at=make)
+ assert message.startswith(
+ "Clustering(graph_degree=...) is deprecated; use max_degree="
+ )
+ assert model.cp.max_degree == 64
+
+
+@pytest.mark.parametrize("cls", [QGKMeans, RaBitQKMeans])
+@pytest.mark.parametrize("name", ["unknown", "mro", "__dict__"])
+def test_unknown_kmeans_keyword_message_is_unchanged(cls, name):
+ with pytest.raises(
+ AttributeError,
+ match=f"^{cls.__name__}\\(\\) got an unexpected keyword argument '{name}'$",
+ ):
+ cls(DIM, 80, **{name: 1})
+
+
+def test_train_error_names_the_keyword_the_caller_used(base_data):
+ old_message = "^QGKMeans ef_build and ef_search must be positive$"
+ with pytest.raises(
+ ValueError, match="^QGKMeans ef_construction and ef_search must be positive$"
+ ):
+ QGKMeans(DIM, 80, niter=1, ef_construction=0).train(base_data)
+ # Every call that 0.8 accepts keeps the message 0.8 gave it.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ old = QGKMeans(DIM, 80, niter=1, ef_build=0)
+ with pytest.raises(ValueError, match=old_message):
+ old.train(base_data)
+ with pytest.raises(ValueError, match=old_message):
+ QGKMeans(DIM, 80, niter=1, ef_search=0).train(base_data)
+
+ class WithoutInit(QGKMeans):
+ def __init__(self):
+ self.d, self.k, self._impl = DIM, 80, None
+ self.cp = rabitqlib.QGKMeansParameters()
+ self.cp.ef_search = 0
+
+ with pytest.raises(ValueError, match=old_message):
+ WithoutInit().train(base_data)
+ # Other errors pass through as the extension raised them.
+ with pytest.raises(
+ ValueError, match="^QGKMeans graph_build_iterations must be positive$"
+ ) as raised:
+ QGKMeans(DIM, 80, niter=1, ef_construction=100, graph_build_iterations=0).train(
+ base_data
+ )
+ assert raised.value.__context__ is None # not re-raised as a new object
+ # The 0.8 name with a value only nbits would accept is still rejected at train.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ wrong = QGKMeans(DIM, 80, niter=1, quantization_bits=32)
+ with pytest.raises(ValueError, match="quantization_bits must be 0, 4, or 8"):
+ wrong.train(base_data)
+
+
+def test_statistics_class_pickles_by_reference():
+ stats = rabitqlib.KMeansIterationStats
+ assert pickle.loads(pickle.dumps(stats)) is stats
+ assert stats.__module__ == "rabitqlib._rabitqlib"
+ assert getattr(sys.modules[stats.__module__], "KMeansIterationStats") is stats
diff --git a/tests/python/test_editor_support.py b/tests/python/test_editor_support.py
index 2bf26ab2..87b9830a 100644
--- a/tests/python/test_editor_support.py
+++ b/tests/python/test_editor_support.py
@@ -157,16 +157,23 @@ def test_native_signature_names_and_defaults(name):
def test_clustering_keyword_defaults(name):
cls = declarations()[name]
init = next(
- n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "__init__"
+ n
+ for n in cls.body
+ if isinstance(n, ast.FunctionDef)
+ and n.name == "__init__"
+ and not is_deprecated(n)
)
instance = getattr(rabitqlib, name)(64, 40)
for arg, default in zip(init.args.kwonlyargs, init.args.kw_defaults):
assert default is not None, (name, arg.arg)
- if isinstance(default, ast.Attribute):
- expected = getattr(rabitqlib.FinalAssignmentMode, default.attr)
- else:
- expected = ast.literal_eval(default)
- assert getattr(instance.cp, arg.arg) == expected
+ expected = ast.literal_eval(default)
+ actual = getattr(instance.cp, arg.arg)
+ if arg.arg == "final_assignment":
+ # Reads back as the enum member until 0.9: compare with what passing
+ # the declared default explicitly gives.
+ explicit = getattr(rabitqlib, name)(64, 40, final_assignment=expected)
+ expected = explicit.cp.final_assignment
+ assert actual == expected
for name in (
"centroids",
"assignments",
@@ -198,7 +205,7 @@ def test_documented_search_result_types(kind):
if kind == "symqg":
index = rabitqlib.SymqgIndex(64, ef_construction=40)
index.add(data)
- result = index.search(data[:2], 3, ef=20)
+ result = index.search(data[:2], 3, ef_search=20)
else:
if kind == "ivf":
index = rabitqlib.IvfIndex(64, 2, nbits=4)
@@ -209,7 +216,7 @@ def test_documented_search_result_types(kind):
if isinstance(index, rabitqlib.IvfIndex):
result = index.search(data[:2], 3, nprobe=2)
else:
- result = index.search(data[:2], 3, ef=20)
+ result = index.search(data[:2], 3, ef_search=20)
ids, distances = result
assert ids.shape == distances.shape == (2, 3)
assert ids.dtype == np.int64
diff --git a/tests/python/test_examples.py b/tests/python/test_examples.py
index a66655ac..b988eb28 100644
--- a/tests/python/test_examples.py
+++ b/tests/python/test_examples.py
@@ -197,7 +197,7 @@ def check_saved_index_and_query(tmp_path, kind, metric, data):
index_type = {"ivf": IvfIndex, "hnsw": HnswIndex, "symqg": SymqgIndex}[kind]
index = index_type.load(str(index_path))
queries = data[:4].copy()
- search_args = {"nprobe": 2} if kind == "ivf" else {"ef": len(data)}
+ search_args = {"nprobe": 2} if kind == "ivf" else {"ef_search": len(data)}
ids, distances = index.search(queries, k=5, num_threads=2, **search_args)
assert index.metric == metric
if kind == "ivf":
diff --git a/tests/python/test_ivf_initializers.py b/tests/python/test_ivf_initializers.py
index ded155df..db8b1d65 100644
--- a/tests/python/test_ivf_initializers.py
+++ b/tests/python/test_ivf_initializers.py
@@ -254,8 +254,8 @@ def test_legacy_formats_infer_historical_initializer(
def test_initializer_rejects_invalid_argument():
- with pytest.raises(ValueError, match="initializer must be"):
- IvfIndex(64, 1, nbits=1, initializer="unknown")
+ with pytest.raises(ValueError, match="^routing must be"):
+ IvfIndex(64, 1, nbits=1, routing="unknown")
@pytest.mark.parametrize("initializer", ["flat", "flat_rabitq"])
diff --git a/tests/python/test_symqg_api.py b/tests/python/test_symqg_api.py
index a00f0f7a..253c8df3 100644
--- a/tests/python/test_symqg_api.py
+++ b/tests/python/test_symqg_api.py
@@ -161,8 +161,7 @@ def test_search_ef_defaults_to_max_of_k_and_64_and_is_raised_to_k(base_data):
queries = base_data[:10]
for k, implied_ef in ((3, 64), (80, 80)):
expected = index.search(queries, k, implied_ef)
- for ef in (None, 0):
- actual = index.search(queries, k, ef)
+ for actual in (index.search(queries, k), index.search(queries, k, None)):
np.testing.assert_array_equal(actual[0], expected[0])
np.testing.assert_array_equal(actual[1], expected[1])
np.testing.assert_array_equal(
diff --git a/tests/python/test_train_api.py b/tests/python/test_train_api.py
index 9048d5a2..cefcc53a 100644
--- a/tests/python/test_train_api.py
+++ b/tests/python/test_train_api.py
@@ -120,14 +120,14 @@ def test_ivf_seed_range_and_random_default():
@pytest.mark.parametrize("metric", ["l2", "ip"])
def test_cp_defaults_follow_metric_and_seed(metric):
ivf = IvfIndex(DIM, 4, nbits=4, metric=metric, seed=11)
- hnsw = HnswIndex(DIM, nbits=4, metric=metric, seed=2**40 + 5)
+ hnsw = HnswIndex(DIM, nbits=4, metric=metric, seed=5)
for index, seed in ((ivf, 11), (hnsw, 5)):
assert index.cp.niter == 10
assert index.cp.max_points_per_centroid == 256
assert index.cp.spherical is (metric == "ip")
assert index.cp.seed == seed
assert index.cp.num_threads == 0
- assert hnsw.seed == 2**40 + 5
+ assert hnsw.seed == 5
# cp is the index's own object: changes persist, and assignment copies.
ivf.cp.niter = 3
assert ivf.cp.niter == 3
@@ -254,7 +254,7 @@ def test_operations_before_training_raise_and_change_nothing(kind, base_data, tm
"save": lambda: index.save(tmp_path / "untrained.index"),
}
if kind == "ivf":
- operations["reserve"] = lambda: index.reserve(0, 10)
+ operations["reserve_cluster"] = lambda: index.reserve_cluster(0, 10)
for operation, call in operations.items():
with pytest.raises(
RuntimeError, match=f"^{name} must be trained or loaded before {operation}$"
@@ -345,29 +345,31 @@ def test_ivf_point_count_index_cannot_be_trained(base_data):
index.train(base_data)
with pytest.raises(RuntimeError, match=message):
index.set_centroids(base_data[:4])
- assert index.max_elements == N_VECTORS
+ assert index.num_stored_points == 0
+ with pytest.warns(DeprecationWarning):
+ assert index.max_elements == N_VECTORS # the declared row count is kept
-def test_hnsw_capacity_grows_and_resize_preallocates(base_data):
+def test_hnsw_capacity_grows_and_reserve_preallocates(base_data):
index = HnswIndex(DIM, nbits=4, num_clusters=4)
- assert index.max_elements == 1
+ assert index.capacity == 1
index.train(base_data)
index.add(base_data[:100])
- assert index.max_elements == 100
+ assert index.capacity == 100
index.add(base_data[100:110])
- assert index.max_elements == 200 # doubled
+ assert index.capacity == 200 # doubled
preallocated = HnswIndex(DIM, nbits=4, num_clusters=4)
- preallocated.resize(1000)
+ preallocated.reserve(1000)
preallocated.train(base_data)
preallocated.add(base_data)
- assert preallocated.max_elements == 1000
+ assert preallocated.capacity == 1000
def test_hnsw_search_ef_none_means_the_default(base_data):
index = HnswIndex(DIM, nbits=4, num_clusters=4)
index.train(base_data)
index.add(base_data, num_threads=1)
- expected = index.search(base_data[:10], 5, 0)
+ expected = index.search(base_data[:10], 5, 64)
for found in (
index.search(base_data[:10], 5, None),
index.search(base_data[:10], 5),
@@ -384,7 +386,7 @@ def test_hnsw_failed_add_keeps_the_capacity(base_data):
bad[150, 0] = np.nan
with pytest.raises(ValueError, match="must contain only finite values"):
index.add(bad)
- assert index.max_elements == 100
+ assert index.capacity == 100
assert len(index) == 100
@@ -461,7 +463,6 @@ def test_ivf_nprobe_defaults_to_a_sixteenth_of_the_clusters(base_data):
for found in (index.search(queries, 5), index.search(queries, 5, None)):
np.testing.assert_array_equal(found[0], expected[0])
np.testing.assert_array_equal(found[1], expected[1])
- np.testing.assert_array_equal(index.search(queries, 5, 0)[0], expected[0])
small = IvfIndex(DIM, 4, nbits=4, seed=3)
small.add(base_data)
np.testing.assert_array_equal(
@@ -476,7 +477,7 @@ def test_num_threads_none_selects_the_defaults(kind, base_data):
found = (
index.search(base_data[:5], 3, None, num_threads=None)
if kind == "hnsw"
- else index.search(base_data[:5], 3, None, None, None)
+ else index.search(base_data[:5], 3, None, high_accuracy=None, num_threads=None)
)
assert found[0].shape == (5, 3)
@@ -498,8 +499,8 @@ def test_package_reports_its_version():
"options",
[
{"nbits": 32},
- {"initializer": "flat_rabitq"},
- {"initializer": "hnsw"},
+ {"routing": "flat_rabitq"},
+ {"routing": "hnsw"},
{"niter": 3, "max_points_per_centroid": 64},
],
)
@@ -540,11 +541,11 @@ def test_ivf_first_add_uses_the_drawn_seed(base_data, tmp_path):
def test_hnsw_first_add_keeps_a_preallocated_capacity(base_data, tmp_path):
implicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50)
- implicit.resize(2 * N_VECTORS)
+ implicit.reserve(2 * N_VECTORS)
implicit.add(base_data, num_threads=1)
- assert implicit.max_elements == 2 * N_VECTORS
+ assert implicit.capacity == 2 * N_VECTORS
explicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50)
- explicit.resize(2 * N_VECTORS)
+ explicit.reserve(2 * N_VECTORS)
explicit.train(base_data)
explicit.add(base_data, num_threads=1)
assert saved_bytes(implicit, tmp_path / "implicit.index") == saved_bytes(
diff --git a/tests/python/typing/public_api.py b/tests/python/typing/public_api.py
index 2aecb8cb..97c733e3 100644
--- a/tests/python/typing/public_api.py
+++ b/tests/python/typing/public_api.py
@@ -11,6 +11,7 @@
FinalAssignmentMode,
HnswIndex,
IvfIndex,
+ KMeansIterationStats,
QGKMeans,
QGKMeansIterationStats,
QGKMeansParameters,
@@ -59,10 +60,10 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None:
assert_type(IvfIndex.load("index.bin"), IvfIndex)
assert_type(HnswIndex.load("index.bin"), HnswIndex)
assert_type(SymqgIndex.load("index.bin"), SymqgIndex)
- ivf.reserve(0, 128)
- hnsw.resize(256)
- qg = QGKMeans(64, 40, niter=2, quantization_bits=4)
- flat = RaBitQKMeans(64, 2, final_assignment=FinalAssignmentMode.Exact)
+ ivf.reserve_cluster(0, 128)
+ hnsw.reserve(256)
+ qg = QGKMeans(64, 40, niter=2, nbits=4)
+ flat = RaBitQKMeans(64, 2, final_assignment="exact")
assert_type(qg.cp, QGKMeansParameters)
assert_type(flat.cp, RaBitQKMeansParameters)
for model in (qg, flat):
@@ -77,21 +78,37 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None:
tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]],
)
if model.iteration_stats is not None:
- assert_type(model.iteration_stats[0], QGKMeansIterationStats)
- qg.cp.final_assignment = FinalAssignmentMode.Approximate
- ivf.search(x, "five", 2) # type: ignore[arg-type]
+ assert_type(model.iteration_stats[0], KMeansIterationStats)
+ qg.cp.final_assignment = "approximate"
+ ivf.search(x, "five", 2) # type: ignore[call-overload]
ivf.dim = 16 # type: ignore[misc]
qg.cp.niter = "two" # type: ignore[assignment]
RaBitQKMeans(64, 2, graph_degree=32) # type: ignore[call-arg]
- hnsw.search(x, 5, nprobe=2) # type: ignore[call-arg]
+ hnsw.search(x, 5, nprobe=2) # type: ignore[call-overload]
IvfIndex(64, 2, 4) # type: ignore[call-overload]
hnsw.train(x, 1) # type: ignore[call-arg]
+ qg.cp.final_assignment = "Exact" # type: ignore[assignment]
+ QGKMeans(64, 40, ef_build=1, bogus=1) # type: ignore[call-overload]
+
+
+def deprecated_forms_still_type_check(qg: QGKMeans, flat: RaBitQKMeans) -> None:
+ # Accepted until 0.9; the stubs mark them deprecated without rejecting them.
+ RaBitQKMeans(64, 2, final_assignment=FinalAssignmentMode.Exact)
+ QGKMeans(64, 40, final_assignment=FinalAssignmentMode.Approximate)
+ qg.cp.final_assignment = FinalAssignmentMode.Exact
+ assert_type(flat.cp.final_assignment, FinalAssignmentMode)
+ QGKMeans(64, 40, quantization_bits=4, niter=2)
+ QGKMeans(64, 40, graph_degree=32, ef_build=100)
def stats_alias(stats: RaBitQKMeansIterationStats) -> QGKMeansIterationStats:
return stats
+def stats_name(stats: QGKMeansIterationStats) -> KMeansIterationStats:
+ return stats
+
+
def check_parameter_reads(
parameters: QGKMeansParameters | RaBitQKMeansParameters,
) -> None:
@@ -131,14 +148,14 @@ def check_numpy_scalars() -> None:
)
assert_type(index.dim, int)
assert type(index.dim) is int
- ivf.reserve(np.uint32(0), np.int64(100))
+ ivf.reserve_cluster(np.uint32(0), np.int64(100))
ids, distances = ivf.search(
x[:2], k=np.int64(3), nprobe=np.int64(1), high_accuracy=np.bool_(True)
)
assert_type(ids, npt.NDArray[np.int64])
assert_type(distances, npt.NDArray[np.float32])
- hnsw.resize(np.int64(100))
- hnsw.search(x[:2], np.int64(3), ef=np.int64(10))
+ hnsw.reserve(np.int64(100))
+ hnsw.search(x[:2], np.int64(3), ef_search=np.int64(10))
graph.add(x, num_threads=np.int64(1))
graph.search(x[:2], np.int64(3), np.int64(10))
flat = RaBitQKMeans(
@@ -152,7 +169,7 @@ def check_numpy_scalars() -> None:
np.int64(64),
np.int64(40),
niter=np.int64(1),
- graph_degree=np.int64(32),
+ max_degree=np.int64(32),
num_threads=np.int64(1),
)
for model in (flat, qg):
@@ -167,11 +184,11 @@ def check_numpy_scalars() -> None:
assert_type(model.train(x), float)
assignments, distances = model.assign(x[:3])
assert assignments.shape == distances.shape == (3,)
- qg.cp.graph_degree = np.int64(32)
- qg.cp.ef_build = np.int64(40)
+ qg.cp.max_degree = np.int64(32)
+ qg.cp.ef_construction = np.int64(40)
qg.cp.ef_search = np.int64(16)
qg.cp.graph_build_iterations = np.int64(1)
- qg.cp.quantization_bits = np.int64(4)
+ qg.cp.nbits = np.int64(4)
members = FinalAssignmentMode.__members__
assert_type(members, dict[str, FinalAssignmentMode])
assert_type(members["Exact"], FinalAssignmentMode)
@@ -196,14 +213,14 @@ def check_input_contracts() -> None:
ivf = IvfIndex(64, 1, nbits=4, metric=metric)
HnswIndex(64, nbits=4, metric=metric)
SymqgIndex(64, metric=metric)
- initializers: tuple[Literal["auto", "flat", "flat_rabitq", "hnsw"], ...] = (
+ routings: tuple[Literal["auto", "flat", "flat_rabitq", "hnsw"], ...] = (
"auto",
"flat",
"flat_rabitq",
"hnsw",
)
- for initializer in initializers:
- IvfIndex(64, 1, nbits=4, initializer=initializer)
+ for routing in routings:
+ IvfIndex(64, 1, nbits=4, routing=routing)
for ids in (signed, unsigned, [0] * 80, (0,) * 80):
ivf = IvfIndex(64, 1, nbits=4)
ivf.set_centroids(centroids, num_threads=1)
@@ -227,7 +244,7 @@ def check_input_contracts() -> None:
graph = SymqgIndex(64, ef_construction=40, init=init)
graph.add(x)
# Returned option values must be usable as inputs without casts.
- IvfIndex(64, 1, nbits=4, metric=ivf.metric, initializer=ivf.initializer)
+ IvfIndex(64, 1, nbits=4, metric=ivf.metric, routing=ivf.routing)
assert_type(ivf.metric, Literal["l2", "ip", "cosine"])
@@ -241,7 +258,7 @@ def reject_invalid_inputs(x: npt.NDArray[np.float32]) -> None:
IvfIndex(64, 1, nbits=4, metric="cos") # type: ignore[call-overload]
HnswIndex(64, nbits=4, metric="L2") # type: ignore[call-overload]
SymqgIndex(64, metric="inner_product") # type: ignore[call-overload]
- IvfIndex(64, 1, nbits=4, initializer="flat_rabit") # type: ignore[call-overload]
+ IvfIndex(64, 1, nbits=4, routing="flat_rabit") # type: ignore[call-overload]
SymqgIndex(64, init="pippn") # type: ignore[call-overload]
graph.add(x, 1) # type: ignore[call-arg]
ivf.add(x, cluster_ids=[0.0] * 80) # type: ignore[list-item]
@@ -338,3 +355,18 @@ def check_quant(x: npt.NDArray[np.float32]) -> None:
quant.code_factors(residuals, codes, nbits=4, metric="cosine") # type: ignore[arg-type]
quant.quantize(residuals, 4) # type: ignore[call-overload]
quant.Rotator(64, method="hadamard") # type: ignore[arg-type]
+
+
+def deprecated_search_forms_return_int64_ids(
+ ivf: IvfIndex, hnsw: HnswIndex, graph: SymqgIndex, x: npt.NDArray[np.float32]
+) -> None:
+ # The deprecated overloads return the same types as the current forms.
+ for found in (
+ ivf.search(x, 5, 1, None, 1),
+ hnsw.search(x, 5, ef=32),
+ hnsw.search(x, 5, 32, 1),
+ graph.search(x, 5, ef=32),
+ graph.search(x, 5, 32, 1),
+ graph.search_batch(x, 5, 32),
+ ):
+ assert_type(found, tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]])
diff --git a/tests/test_mypy.py b/tests/test_mypy.py
index 430f2322..3ab2d3eb 100644
--- a/tests/test_mypy.py
+++ b/tests/test_mypy.py
@@ -58,11 +58,16 @@ def test_static_public_usage(tmp_path):
assert error_lines == expected_lines, result.stdout
-# Each 0.7 call form the compatibility layer accepts is marked deprecated in the
-# stubs, so editors flag it while it still type-checks.
+# Each 0.7 call form the compatibility layer accepts, and each 0.8 spelling that 0.9
+# renames, is marked deprecated in the stubs, so editors flag it while it still
+# type-checks. Deprecations that depend on a value (a breadth of 0, a seed above
+# 2**32 - 1) cannot be declared and are documented in the docstrings only. The two
+# old statistics class names are plain aliases, which PEP 702 cannot mark; only the
+# runtime warns for them.
DEPRECATED_USAGE = """\
import numpy as np
-from rabitqlib import HnswIndex, IvfIndex, SymqgIndex
+import rabitqlib
+from rabitqlib import HnswIndex, IvfIndex, QGKMeans, SymqgIndex
x = np.zeros((80, 64), dtype=np.float32)
labels = np.zeros(80, dtype=np.uint32)
@@ -79,12 +84,64 @@ def test_static_public_usage(tmp_path):
graph.search_batch(x, 5, 32)
bits = graph.quantization_bits
built = graph.is_built
+routed = IvfIndex(64, 1, initializer="flat")
+strategy = routed.initializer
+stored = routed.max_elements
+routed.reserve(0, 8)
+routed.search(x, 5, 1, None)
+capacity = seeded.max_elements
+seeded.resize(128)
+seeded.search(x, 5, ef=32)
+seeded.search(x, 5, 32, 1)
+count = graph.max_elements
+graph.search(x, 5, ef=32)
+graph.search(x, 5, 32, 1)
+kmeans = QGKMeans(64, 40, quantization_bits=4)
+kmeans = QGKMeans(64, 40, graph_degree=32)
+kmeans = QGKMeans(64, 40, ef_build=100)
+kmeans.cp.quantization_bits = 4
+kmeans.cp.graph_degree = 32
+kmeans.cp.ef_build = 100
+mode = rabitqlib.FinalAssignmentMode.Exact
+storage = kmeans.cp.quantization_bits
+degree = kmeans.cp.graph_degree
+breadth = kmeans.cp.ef_build
"""
+# The forms 0.9 keeps: none may be flagged as deprecated.
+CURRENT_USAGE = """\
+import numpy as np
+from rabitqlib import HnswIndex, IvfIndex, QGKMeans, RaBitQKMeans, SymqgIndex
-def test_deprecated_forms_are_flagged(tmp_path):
- usage = tmp_path / "deprecated_usage.py"
- usage.write_text(DEPRECATED_USAGE)
+x = np.zeros((80, 64), dtype=np.float32)
+ivf = IvfIndex(64, 1, nbits=4, routing="flat")
+strategy = ivf.routing
+stored = ivf.num_stored_points
+ivf.reserve_cluster(0, 8)
+ivf.search(x, 5, 1, high_accuracy=None, num_threads=1)
+hnsw = HnswIndex(64, nbits=4, seed=5)
+capacity = hnsw.capacity
+hnsw.reserve(128)
+hnsw.search(x, 5, 32, num_threads=1)
+hnsw.search(x, 5, ef_search=32)
+graph = SymqgIndex(64)
+graph.search(x, 5, ef_search=32, num_threads=1)
+kmeans = QGKMeans(
+ 64, 40, nbits=4, max_degree=32, ef_construction=100, final_assignment="exact"
+)
+kmeans.cp.nbits = 8
+kmeans.cp.max_degree = 32
+kmeans.cp.ef_construction = 100
+kmeans.cp.final_assignment = "approximate"
+width = kmeans.cp.nbits
+flat = RaBitQKMeans(64, 2, final_assignment="exact")
+"""
+
+
+def deprecated_lines(tmp_path, source):
+ """Line numbers mypy flags as deprecated in source, and its whole output."""
+ usage = tmp_path / "usage.py"
+ usage.write_text(source)
result = subprocess.run(
[
sys.executable,
@@ -108,4 +165,20 @@ def test_deprecated_forms_are_flagged(tmp_path):
rf"{re.escape(str(usage))}:(\d+): error: .*\[deprecated\]", result.stdout
)
}
- assert flagged == set(range(6, 19)), result.stdout
+ return flagged, result.stdout
+
+
+def test_deprecated_forms_are_flagged(tmp_path):
+ flagged, output = deprecated_lines(tmp_path, DEPRECATED_USAGE)
+ old_forms = set(range(7, 42))
+ # mypy 2.4 reports assignments to a deprecated settable property, not reads of
+ # it: the last three lines, which read QGKMeansParameters attributes, may go
+ # unreported. Each of those attributes is also assigned above.
+ settable_reads = {39, 40, 41}
+ assert old_forms - settable_reads <= flagged <= old_forms, output
+
+
+def test_current_forms_are_not_flagged(tmp_path):
+ flagged, output = deprecated_lines(tmp_path, CURRENT_USAGE)
+ assert not flagged, output
+ assert "Success: no issues found" in output, output