diff --git a/docs/development.md b/docs/development.md
index c1618824..fcc448d6 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -699,15 +699,14 @@ its upper and base layers use `upper_layer_max_degree_` and
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()` and `QGKMeansParameters::ef_build`
-retain their existing spellings, as do the Python vocabulary `random_seed`/`seed`,
-`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
+`Cluster::num()`, the protected `Initializer::num_cluster_` and QG's
+`degree_bound()`/`set_ef()` retain their existing spellings, as do the Python
+vocabulary `seed`, `train`, `obj`, `nsplit`, `final_obj` and `niter`. Since 0.9, Python
+spells each concept one way on the index and k-means classes: `ef_search`,
+`ef_construction`, `max_degree`, `nbits` (32 for raw storage), `routing` and `capacity`
+(#232, #233). `QGKMeansParameters` has the same field names in C++, converting
+`nbits == 32` to the 0 that `QGAssigner` and QG take as `quantization_bits`. 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.
Storage-mode parameters also retain their contracts: IVF/HNSW use `nbits()`
@@ -730,8 +729,9 @@ public and protected names, Python keywords, field order and numerical operation
integer accumulation outputs. Retain `lut` in compact local kernels where its
role is clear.
- Clustering's private state uses `dim_`, `num_points_`, `num_clusters_`,
- `num_workers_` and `data_`. Keep public `d`, `k`, `num_threads` and graph parameter
- names compatible. The private graph iteration count is `graph_build_iterations_`.
+ `num_workers_` and `data_`. Keep public `d`, `k`, `num_threads` and the graph parameter
+ names (`ef_search`, `graph_build_iterations` and, since 0.9, `max_degree`,
+ `ef_construction` and `nbits`) compatible. The private graph iteration count is `graph_build_iterations_`.
Per-point centroid IDs are `assignments` (arrays) and `cluster_id` (scalars);
`label` stays reserved for HNSW's caller-visible labels.
- FHT backend arguments use `rotated_data`, `padded_dim`, `trunc_dim` and
@@ -876,9 +876,8 @@ checked-bit manipulation independently.
### Ownership during construction
Some index builders retain non-owning access to input vectors only during synchronous construction.
-Do not extend such a pointer's lifetime without introducing explicit ownership. The HNSW Python
-wrapper copies cluster IDs before calling the mutable C++ construction API; preserve that boundary
-unless the C++ contract becomes const-correct.
+Do not extend such a pointer's lifetime without introducing explicit ownership. The Python
+wrappers pass `add` an owned, validated copy of the cluster IDs.
### Removal markers and search
diff --git a/docs/docs/clustering.md b/docs/docs/clustering.md
index 26f85ec7..dbc88202 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 > max_degree` (C++ `graph_degree`; default 32) |
+| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (default 32) |
## Python
@@ -164,15 +164,14 @@ 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 `nbits` (C++ `quantization_bits`) setting.
+it has no graph parameters or `nbits` setting.
### QGKMeans
QGKMeans builds a SymphonyQG graph over the centroids and uses previous
-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.
+assignments as search hints. Its additional parameters are below; C++ and Python use
+the same names. Before 0.9 the first three were `quantization_bits` (with `0` for raw
+storage), `graph_degree` and `ef_build`.
| Parameter | Default | Meaning |
| --- | --- | --- |
@@ -213,15 +212,15 @@ 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`.
+Python takes the strings `'approximate'` and `'exact'`, and `cp.final_assignment`
+reads back as one of them. 0.9 removed the `FinalAssignmentMode` enum from the Python
+package.
In C++, set `parameters.final_assignment` to
`rabitqlib::rabitqkmeans::FinalAssignmentMode::Exact` or
`rabitqlib::qgkmeans::FinalAssignmentMode::Exact`; both names refer to the same
-enum. Training still uses the selected approximate assignment algorithm.
+enum, whose values are `Approximate` and `Exact` (0.9 removed the alias
+`SymphonyQG`). Training still uses the selected approximate assignment algorithm.
Exact final assignment screens all centroids with blocked GEMM and refines
possible winners in float64; ties select the smallest centroid index. Returned
diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md
index 45660c59..d19ce90e 100644
--- a/docs/docs/index/hnsw.md
+++ b/docs/docs/index/hnsw.md
@@ -18,8 +18,8 @@ Run the [Quick start](../quick_start.md#build-and-search-an-ivf-index) to prepar
```python
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
+index = HnswIndex(data.shape[1], M=16, ef_construction=100, seed=7) # nbits=7 by default
+index.add(data, num_threads=1) # trains 16 centroids, then links; a seed and 1 thread are reproducible
ids, distances = index.search(queries, k=10) # ef_search defaults to max(k, 64)
index.save("hnsw.index")
loaded = HnswIndex.load("hnsw.index")
@@ -31,7 +31,7 @@ The first `add` trains an untrained index on the added vectors, as for
the row count. An empty first `add` raises `RuntimeError`.
`train` and `set_centroids` work as for [IVF-RaBitQ](ivf.md#training-centroids-in-python),
with `num_clusters` centroids (default 16) and always RaBitQKMeans; `index.cp`
-starts from the same defaults with `seed`'s low 32 bits. The first `add` into the
+starts from the same defaults with the index `seed`. The first `add` into the
empty index links vectors with their exact coordinates, like the 0.7 `build`;
later adds link through the stored codes (see [Recall after `add`](#recall-after-add)),
so add most vectors in the first call.
@@ -70,15 +70,16 @@ 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. 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. |
+| `metric`, `seed` | `metric` defaults to `"l2"` in Python; `"ip"` and [`"cosine"`](usage.md#the-cosine-metric) are also supported. `seed` is the graph and rotation seed in `[0, 2**32 - 1]` and the initial `cp.seed`. Python's default `None` draws one at random (it was 100 before 0.9); `index.seed` reports it. |
+| `capacity` (C++ `max_elements()`) | Python reports the current capacity, which `add` grows geometrically (at least doubling) and `reserve` can preallocate; they replace `max_elements` and `resize`, which 0.9 removed. 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 raises `ValueError`), a smaller value is raised to at least `k`, and a value above the stored point count is clamped to it. It replaces `ef`, which 0.9 removed. |
`seed` controls graph levels and the FHT/Kac rotation (using its low 32 bits).
With identical inputs and parameters, single-threaded construction is reproducible
-within the same build environment. Python `train` and `add` default to every
-available CPU, so **default builds are not reproducible**: pass `num_threads=1` to
-`add` when you need the same graph again. Different toolchains or SIMD backends can
+within the same build environment. Python draws a seed unless `seed=` is given, and
+`train` and `add` default to every available CPU, so **default builds are not
+reproducible**: pass `seed=` to the constructor and `num_threads=1` to `add` when you
+need the same graph again. Different toolchains or SIMD backends can
still change results. Loading restores the saved rotation.
Results use squared L2 or `1 - dot` estimates, ordered from smallest to largest.
@@ -234,8 +235,8 @@ 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` 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`.
+double it, and `reserve(num_points)` preallocates it; `reserve` never shrinks the
+capacity. 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.
@@ -282,7 +283,7 @@ exclusive access as other updates.
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_search` is omitted (it was named `ef` before 0.8.5); an explicit value is also raised to at least `k`,
+when `ef_search` is omitted; 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 3319bf28..29645b33 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). |
-| `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`. |
+| `routing` | Defaults to `"auto"`; see [centroid routing](#centroid-routing). It replaces `initializer`, which 0.9 removed. |
+| `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 raises `ValueError`); 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
@@ -230,8 +230,7 @@ index.add(vectors)
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_cluster` and
- `save` raise `RuntimeError`; `add` without `cluster_ids` trains first, except
- on an index created with `max_elements`, which `build` fills. If that
+ `save` raise `RuntimeError`; `add` without `cluster_ids` trains first. If that
first `add` fails, the index stays untrained and empty; an empty first `add`
raises `RuntimeError`. A trained index without
vectors cannot be saved, and its `search` returns only padded results; add
@@ -398,8 +397,7 @@ removed = index.remove(new_ids[:10])
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 names this method `reserve_cluster`; it replaces `reserve`, which 0.9 removed.
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
diff --git a/docs/docs/index/qg.md b/docs/docs/index/qg.md
index 4adab0cf..d2dc0933 100644
--- a/docs/docs/index/qg.md
+++ b/docs/docs/index/qg.md
@@ -71,13 +71,13 @@ qg.save("qg_example.index");
| Parameter | Contract |
| --- | --- |
| `dim` | Original input dimension; Python supports 64–65,536 and pads internally. |
-| `nbits` / C++ `quantization_bits` | Python keyword: 32 (default) for owned raw vectors, or 4/8 for quantized storage. C++ uses 0 for raw vectors, as Python's `quantization_bits` did before 0.8. |
+| `nbits` / C++ `quantization_bits` | Python keyword: 32 (default) for owned raw vectors, or 4/8 for quantized storage. C++ uses 0 for raw vectors. |
| `max_degree` | Python keyword, default 32: a positive multiple of 32, strictly smaller than the point count. It is a hard degree bound, unlike HNSW-RaBitQ's `M`. |
| `ef_construction` | Python keyword, default 200: positive construction search window used by `add`. |
| `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_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. |
+| `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 or `None` `ef_search` uses `max(k, 64)` in Python (0 raises `ValueError`), and smaller values are raised to `k`, as for HNSW-RaBitQ. It replaces `ef`, which 0.9 removed. |
| `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
@@ -183,8 +183,7 @@ Concurrent searches need separate outputs; do not modify the index or call
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`.
+available logical CPU count, capped by the number of queries.
Queries use the original dimension, including when the internal rotation pads it.
Python searches use per-call `ef_search` values. For access rules, see the
diff --git a/docs/docs/index/usage.md b/docs/docs/index/usage.md
index d09f2a60..462fd50e 100644
--- a/docs/docs/index/usage.md
+++ b/docs/docs/index/usage.md
@@ -68,11 +68,9 @@ three indexes):
| `capacity` (HNSW-RaBitQ only) | Logical record capacity, excluding SIMD padding |
`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
+HNSW-RaBitQ. Python's `max_elements` property, which 0.9 removed, was this capacity
+on `HnswIndex` and equal to `num_stored_points` on the other two classes. 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`,
the first `add`, or `load`), and is always `True` for SymphonyQG.
@@ -83,12 +81,12 @@ 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 `reserve` preallocates
-it (`resize` before 0.8.5). SymphonyQG has no incremental
+it. 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 routing strategy, and SymphonyQG includes its degree bound. The summary
+plus the training state for IVF/HNSW. IVF/HNSW also show stored count and centroid count; HNSW includes
+its capacity, IVF the resolved routing strategy, and SymphonyQG its degree bound. The summary
reads only metadata and follows the same concurrency rules as property reads.
## Estimate storage
@@ -147,8 +145,8 @@ 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`, `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 |
+| `search`, `save`, `repr`, and property reads | May run together |
+| `train`, `set_centroids`, `add`, `remove`, `reserve`, `reserve_cluster`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input, and an HNSW-RaBitQ `reserve` within the current capacity, which changes nothing; both may run with reads |
A conflicting call immediately raises
`RuntimeError("Index is busy: conflicting operation in progress")`.
@@ -174,12 +172,11 @@ example Faiss or PyTorch wheels) can crash when more than one of them starts
worker threads in the same process; set `OMP_NUM_THREADS=1` before the first
native call, or pass `num_threads=1`, in such processes.
`train` and `add` on every index, and IVF-RaBitQ `set_centroids`, default to all
-CPUs (`None` or `0`); the clustering classes default to `0`. `search` defaults to one thread (`None` or `1`),
-as do the deprecated `build`, which requires an integer, and `search_batch`.
+CPUs (`None` or `0`); the clustering classes default to `0`. `search` defaults to one thread (`None` or `1`).
Multithreaded HNSW-RaBitQ `add` links points in a nondeterministic order, and so
does a multithreaded build of IVF-RaBitQ's HNSW centroid routing by `train`,
-`set_centroids` or the first `add`; pass `num_threads=1` when a build must be
-reproducible.
+`set_centroids` or the first `add`; pass `num_threads=1`, and `seed=` to the
+constructor, when a build must be reproducible.
On Linux, CPU detection accounts for affinity and OpenMP binding. Apply binding
before starting the program.
diff --git a/docs/docs/modular_migration.md b/docs/docs/modular_migration.md
index 801282f9..e83e43cd 100644
--- a/docs/docs/modular_migration.md
+++ b/docs/docs/modular_migration.md
@@ -168,14 +168,15 @@ in C++ and Python.
Compared with the 0.6.0 Python API, IVF-RaBitQ adds `num_points` and `num_stored_points`,
HNSW-RaBitQ adds `num_stored_points`, and SymphonyQG adds `max_elements` and
-`num_stored_points`.
+`num_stored_points`. 0.9 removes the Python `max_elements` property; see the
+[migration guide](python_migration.md#from-08-to-09).
**HNSW-RaBitQ `num_points` now excludes removed records.** Use `num_stored_points` for
ID bounds, append offsets, and minimum resize capacity. Use `num_points` for a
live count, without subtracting a separate deletion counter.
The IVF-RaBitQ constructor keyword `max_elements` still specifies the required initial
-build size; 0.8 deprecates it (see [Migrating to 0.8](python_migration.md)). SymphonyQG's C++ `num_vertices()` still returns the configured graph
+build size; 0.8 deprecates it and 0.9 removes it (see the [migration guide](python_migration.md)). SymphonyQG's C++ `num_vertices()` still returns the configured graph
size for builders. Existing index files need no conversion: loading recovers
counts from their removal markers.
diff --git a/docs/docs/python_migration.md b/docs/docs/python_migration.md
index 3038f0b8..72c11840 100644
--- a/docs/docs/python_migration.md
+++ b/docs/docs/python_migration.md
@@ -1,31 +1,34 @@
-# Migrating Python code from 0.7 to 0.8
+# Migrating Python code to 0.9
-In 0.8, `IvfIndex`, `HnswIndex` and `SymqgIndex` follow a `train` → `add` →
+Since 0.8, `IvfIndex`, `HnswIndex` and `SymqgIndex` follow a `train` → `add` →
`search` workflow, as Faiss indexes do; since 0.8.2 the first `add` trains, so
construct → `add` → `search` is enough, and `train` remains for training on a
sample. IVF-RaBitQ and HNSW-RaBitQ learn their own centroids, so you no longer
run k-means and pass the centroids and assignments to `build`; SymphonyQG has
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**.
+still runs in 0.8, where each old form raises a `DeprecationWarning` at your call
+site. **0.9 removes those forms**: a removed call raises `TypeError`, and a removed
+attribute `AttributeError`.
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.
+[From 0.8 to 0.9](#from-08-to-09): 0.9 renames some of them. 0.8.5 accepts both
+spellings, so you can make every change on 0.8.5, with its warnings as a guide,
+before upgrading.
-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.
+The tables below give each replacement in its 0.9 spelling. In 0.8, a 0.7 call
+that raises a deprecation warning keeps its 0.7 behavior unless an item says
+otherwise, and calls that are valid in both versions, such as `add(x)` and
+`search`, follow the 0.8 rules.
## IVF-RaBitQ and HNSW-RaBitQ
### Old and new calls
-| 0.7 | 0.8 |
+| 0.7 | Since 0.8 |
| --- | --- |
| `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 `reserve(n)` preallocates it (`resize(n)` before 0.8.5) |
+| `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=None)` (`seed=100` in 0.8); 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)` |
@@ -33,8 +36,8 @@ warning keeps its 0.7 behavior. Calls that are valid in both versions, such as
| `index.is_built` | `index.is_trained`, or `len(index) > 0` for "holds vectors" |
Except for `dim` and IVF-RaBitQ's `num_clusters`, constructor arguments are
-keyword-only in 0.8. Since 0.8.2, `nbits` defaults to 7 (0.8.0 and 0.8.1 required
-it). HNSW-RaBitQ used to default to `nbits=8`; the old form keeps that default.
+keyword-only since 0.8. Since 0.8.2, `nbits` defaults to 7 (0.8.0 and 0.8.1 required
+it). HNSW-RaBitQ used to default to `nbits=8`.
`train` uses the settings in `index.cp`: 10 iterations (25 before 0.8.2), at most 256 sampled
vectors per centroid, spherical k-means for `metric="ip"` (and, from 0.9, `"cosine"`), and the index seed.
@@ -50,11 +53,10 @@ work if you want to run k-means yourself.
the same default and takes `num_threads`; before, it always used every CPU and
ignored `OMP_NUM_THREADS`. This applies to every `add` call that does not
pass `num_threads`, including 0.7 code such as `index.add(x)`, without a
- warning. `search` still defaults to one thread, and the deprecated `build`
- keeps its default of 1.
+ warning. `search` still defaults to one thread.
- **HNSW-RaBitQ builds are not reproducible by default.** With more than one
thread, `add` links points in a nondeterministic order. Pass `num_threads=1`
- to `add` for the same graph on every run. With one thread and the same seed,
+ to `add`, and since 0.9 a `seed`, for the same graph on every run. With one thread and the same seed,
`set_centroids` followed by `add` produces exactly the index that 0.7 `build`
produced from the same centroids and cluster IDs.
- **IVF-RaBitQ HNSW routing builds are not reproducible by default.** 0.7 `build`
@@ -68,9 +70,7 @@ work if you want to run k-means yourself.
slots with ID `2**32 - 1` (`-1` since 0.9) and distance `inf`; test
`np.isfinite(distances)`, which works in both.
- **HNSW-RaBitQ capacity grows.** `add` resizes the index, at least doubling it,
- instead of raising `ValueError` when the batch does not fit. This also applies
- to `add` on indexes created in the old form, and to the deprecated `build`,
- which no longer rejects more rows than `max_elements`.
+ instead of raising `ValueError` when the batch does not fit.
- **State errors.** Calling `add` with `cluster_ids`, `search`, `remove`,
`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,
@@ -78,49 +78,46 @@ work if you want to run k-means yourself.
cannot be saved. `repr` shows `is_trained` instead of `is_built`.
- **Seeds.** `IvfIndex` still draws a random rotation seed by default, and now
reports it as `index.seed`; pass it back as `seed=` to reproduce an index.
- Indexes loaded from files report `seed=None`.
+ Indexes loaded from files written by releases up to 0.8 report `seed=None`.
- **HNSW-RaBitQ `num_clusters`** reports the configured count (16 by default)
before training, where 0.7 reported 0 before `build`.
-- An `IvfIndex` created with `max_elements` is filled by `build`; `train` and
- `set_centroids` raise `RuntimeError` for it. Create the index in the 0.8 form
- to train it.
## SymphonyQG
-| 0.7 | 0.8 |
+| 0.7 | Since 0.8 |
| --- | --- |
| `SymqgIndex(dim, max_degree, metric, quantization_bits)` | `SymqgIndex(dim, max_degree=..., metric=..., nbits=...)`; every argument after `dim` is keyword-only |
| `quantization_bits=0` (raw vectors), `4`, `8` | `nbits=32` (raw vectors, the default), `4`, `8` |
| `index.build(x, ef_construction, num_threads, init)` | `SymqgIndex(dim, ef_construction=..., init=..., seed=...)`
`index.add(x, num_threads=...)` |
-| `index.search_batch(q, k, ef)` | `index.search(q, k, ef)`; `ef` is now optional |
+| `index.search_batch(q, k, ef)` | `index.search(q, k, ef_search)`; the breadth is now optional |
| `index.quantization_bits` | `index.nbits` (32 instead of 0 for raw vectors) |
| `index.is_built` | `len(index) > 0` |
`train(x)` exists for a uniform workflow but only checks `x` as `add` would,
and `is_trained` is always `True`. `add` builds the graph from all vectors and can run only once;
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.
+NSG index does; create a new index to rebuild, where 0.7 `build` replaced the
+existing graph.
`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`,
+`ValueError`. `add` uses every CPU by default, where `build` used one thread.
+The seed now also drives graph construction: without `seed`,
each index draws one random seed and reports it as `index.seed`; 0.7 drew
separate random seeds for the rotation and the graph. Before vectors are added,
`search` and `save` raise `RuntimeError("SymqgIndex has no vectors; ...")`.
## Files and C++
-Saved files are unchanged, and so is the `max_elements` property up to 0.8.4 (see
+Saved files are unchanged in 0.8, 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`.
-For C++, the existing constructors and `construct` are unchanged; see
+For C++, the existing index constructors and `construct` are unchanged; see
[IVF-RaBitQ](index/ivf.md#training-centroids-in-c) and
[HNSW-RaBitQ](index/hnsw.md#training-centroids-in-c) for the new training entry
points. C++ behavior changes: since 0.8.0, saving an index without stored points
@@ -133,11 +130,12 @@ iterations. See the [0.8.2 notes](releases/0.8.2.md#c-changes).
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.
+removes it. A removed name or call form then raises `AttributeError` or `TypeError`,
+and a zero breadth or an out-of-range seed raises `ValueError`.
| 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`. |
+| `IvfIndex.max_elements`, `SymqgIndex.max_elements` | `num_stored_points` | Every 0.8 release. The two are equal in 0.8, 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 |
@@ -176,10 +174,15 @@ 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.
+In C++, `QGKMeansParameters` takes the same three field renames in 0.9, without a
+transition release, and `FinalAssignmentMode::SymphonyQG` and the two statistics
+aliases are removed; see the [0.9 notes](releases/unreleased.md#c-changes).
+
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
+`capacity=` for `HnswIndex` and `routing=` for `IvfIndex` where it prints `max_elements=`
+and `initializer=`, and no longer prints `max_elements=` for `IvfIndex`. 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
diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md
index 8b795982..b1b7bd03 100644
--- a/docs/docs/releases/unreleased.md
+++ b/docs/docs/releases/unreleased.md
@@ -10,6 +10,37 @@
- `save` rejects IVF-RaBitQ indexes of more than 65,536 dimensions.
- A format-2 file that uses read-only-compatible features unknown to this release loads for search only: operations that change or save the index raise. Rebuilding with IVF-RaBitQ `construct`, or a new SymphonyQG build, makes it writable again.
+## Removed and renamed Python forms
+
+0.9 removes every Python form that 0.8 deprecated. The [migration guide](../python_migration.md) lists each replacement; all of them work in 0.8.5, where the old forms warn.
+
+- The 0.7 call forms, deprecated since 0.8.0 (#213):
+ - `IvfIndex(dim, max_elements, num_clusters, nbits, ...)`, `HnswIndex(dim, max_elements, ...)` and its `random_seed=`, and `SymqgIndex(dim, max_degree, metric, quantization_bits)` and its `quantization_bits=`;
+ - `build()` and `is_built` on every index, and `SymqgIndex.search_batch()` and `SymqgIndex.quantization_bits`;
+ - `cluster_ids`, `num_threads` and `fast_quantization` passed to `add` by position.
+- The 0.8 index spellings, deprecated since 0.8.5 (#232):
+ - `max_elements`: read `capacity` on `HnswIndex` and `num_stored_points` on `IvfIndex` and `SymqgIndex`;
+ - `HnswIndex.resize(n)`: call `reserve(n)`, which only grows the capacity;
+ - `IvfIndex.reserve(cluster_id, num_points)`: call `reserve_cluster`;
+ - `IvfIndex(initializer=...)` and `index.initializer`: use `routing`;
+ - `search(queries, k, ef=...)` on `HnswIndex` and `SymqgIndex`: use `ef_search=`;
+ - `high_accuracy` and `num_threads` passed to `search` by position: they are keyword-only, and only `nprobe` or `ef_search` stays positional;
+ - `nprobe=0` and `ef_search=0` for the default: they raise `ValueError`, and `None` selects the default. `num_threads=0` still means every available CPU;
+ - `HnswIndex` seeds above `2**32 - 1`: they raise `ValueError`, as on the other two classes.
+- The 0.8 k-means spellings, deprecated since 0.8.5 (#233):
+ - `QGKMeans` and `QGKMeansParameters` take `nbits` (32, 4 or 8), `max_degree` and `ef_construction` instead of `quantization_bits` (0, 4 or 8), `graph_degree` and `ef_build`;
+ - `final_assignment` is `'approximate'` or `'exact'`, also on `index.cp`, and reads back as that string. `FinalAssignmentMode` is no longer in the package;
+ - `KMeansIterationStats` is the only name of the statistics class; `QGKMeansIterationStats` and `RaBitQKMeansIterationStats` are no longer in the package.
+- A removed call form of an index raises `TypeError`, and a removed attribute or name `AttributeError` (`ImportError` when imported), as does a removed `QGKMeans` keyword, like any unknown keyword there; none is read as a different call. For example, `IvfIndex(dim, 1000, 64)` is an error, not an index with 1000 clusters.
+- Changes that 0.8.5 could not announce with a warning:
+ - `HnswIndex()` without `seed=` draws a seed, as `IvfIndex` and `SymqgIndex` do, instead of using 100. `index.seed` reports it; pass `seed=`, and `num_threads=1` to `add`, for a reproducible build.
+ - `repr(index)` prints `capacity=` for `HnswIndex` and `routing=` for `IvfIndex`, and no longer prints `max_elements=` for `IvfIndex`.
+- The index classes are now the extension's own, without replaced methods:
+ - A wrong argument raises pybind11's `TypeError`, which lists the supported signature. Messages such as `IvfIndex() got an unexpected keyword argument 'x'` are gone.
+ - `inspect.signature()` no longer works on the index constructors and methods; `help()` and the type stubs describe them.
+- k-means messages name the new parameters: `QGKMeans nbits must be 4, 8, or 32`, `QGKMeans max_degree must be a positive multiple of 32`, `QGKMeans requires more centroids than max_degree` and `QGKMeans ef_construction and ef_search must be positive`. As for the other parameters, `train` reports an invalid `nbits`; 0.8.5 rejected it when it was set.
+- txtai 9.14.0 and earlier use the 0.7 forms and fail with this release. They also filter results with `uid != 0xFFFFFFFF`, which no longer matches a missing result (see `int64` IDs below). See #213 for the first compatible txtai release.
+
## Python changes
- New `metric="cosine"` for `IvfIndex`, `HnswIndex` and `SymqgIndex` (#212). The index scales data and queries to unit length and returns `1 - cos`; results equal those of a `metric="ip"` index built from the scaled vectors. A zero vector stays zero, so its true distance to every vector is 1. The saved file records the metric, so a loaded index keeps scaling. `index.metric` can now return `"cosine"`, and an invalid metric raises `metric must be 'l2', 'ip' or 'cosine'`. See [the cosine metric](../index/usage.md#the-cosine-metric).
@@ -17,10 +48,9 @@
- `search` returns `int64` IDs, and slots without a neighbor hold `-1` instead of `2**32 - 1`; their distance is still `inf`. Code that compares IDs with `2**32 - 1`, `0xFFFFFFFF` or `np.iinfo(np.uint32).max` must change; `np.isfinite(distances)`, recommended since 0.8.2, works before and after.
- `add` returns `int64` IDs. `remove` already took any integer IDs and still rejects `-1` and other out-of-range values without removing anything.
- IDs remain the row numbers the index assigns, and C++ point IDs remain 32-bit `PID` values with `kPidMax` for a missing result.
- - txtai 9.14.0 and earlier filter results with `uid != 0xFFFFFFFF`, so with this release they return padded slots as ID `-1`; see #213 for the first compatible txtai release.
- Loading a format-2 file keeps the `seed` of every index, and `ef_construction` and `init` of SymphonyQG. They were `None` after `load`, and still are for files from releases up to 0.8.
-- With a recorded seed, `cp.seed` after `load` follows it as for a new index: the seed for IVF-RaBitQ, its low 32 bits for HNSW-RaBitQ. It was the k-means default.
+- With a recorded seed, `cp.seed` after `load` follows it as for a new index; for an HNSW-RaBitQ file whose seed exceeds 32 bits, which only C++ can write, it is the low 32 bits. It was the k-means default.
- A new exception, `rabitqlib.FormatError`, subclasses both `ValueError` and `RuntimeError`:
- Every index `load` raises it for a truncated, corrupt, mismatched or unsupported file, in format 2 and in every earlier layout. These were `RuntimeError`, which still catches them. A file that cannot be opened still raises a plain `RuntimeError`.
- `quant.FormatError` is now the same class. It was a subclass of `ValueError` only, which still catches it.
@@ -32,6 +62,11 @@
## C++ changes
+- `qgkmeans::QGKMeansParameters` uses the Python names (#233): `graph_degree` becomes `max_degree`, `ef_build` becomes `ef_construction`, and `quantization_bits` (0, 4 or 8) becomes `nbits` (32, 4 or 8, with 32 for raw float32). The fields keep their order and types. An `nbits` of 0 is rejected, so code that initialized the field positionally with 0 must pass 32. `QGAssigner` keeps its constructor, including `quantization_bits` with 0 for raw storage.
+- Messages follow the names: `QGKMeans nbits must be 4, 8, or 32`, `QGKMeans max_degree must be a positive multiple of 32`, `QGKMeans requires more centroids than max_degree` and `QGKMeans ef_construction and ef_search must be positive`.
+- `FinalAssignmentMode::SymphonyQG`, an alias of `Approximate`, is removed.
+- The aliases `qgkmeans::QGKMeansIterationStats` and `rabitqkmeans::RaBitQKMeansIterationStats` are removed; use `clustering::KMeansIterationStats`.
+
- `MetricType` gains `METRIC_COSINE`, which `IVF`, `HierarchicalNSW`, `QuantizedGraph` and `default_training_parameters` accept. The indexes normalize their inputs and store inner-product codes; `metric_type()` returns `METRIC_COSINE`. Entry points that validate the metric reject it with their existing messages: the stable core API v1, factor computation in the encoders, the query classes, FastScan queries, clustering and the IVF initializers. Code with an exhaustive `switch` over `MetricType` may warn about the new value.
- Loading an index throws `rabitqlib::FormatError`, a subclass of `std::runtime_error` in the new header `rabitqlib/index/format_error.hpp`, for a damaged, mismatched or unsupported file. Failing to open the file still throws `std::runtime_error`. Files of earlier layouts that threw other exceptions for invalid contents now throw `FormatError` too: an IVF-RaBitQ file with an invalid metric or a dimension its rotation does not support, which threw `std::invalid_argument`, and a SymphonyQG file with invalid settings or dimensions, which threw `std::invalid_argument` or `std::length_error`.
diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml
index b8c33f30..7fcb5822 100644
--- a/docs/mkdocs.yml
+++ b/docs/mkdocs.yml
@@ -9,7 +9,7 @@ copyright: Copyright © VectorDB Group, Nanyang Technological University
nav:
- Home: index.md
- Quick start: quick_start.md
- - Migrating to 0.8: python_migration.md
+ - Migrating to 0.9: python_migration.md
- Installation: installation.md
- C++ Integration: cpp_integration.md
# Group by minor version: nested groups stay collapsed except the current page's.
diff --git a/include/rabitqlib/clustering/detail/kmeans.hpp b/include/rabitqlib/clustering/detail/kmeans.hpp
index 809dc689..d243bdcf 100644
--- a/include/rabitqlib/clustering/detail/kmeans.hpp
+++ b/include/rabitqlib/clustering/detail/kmeans.hpp
@@ -32,7 +32,6 @@ namespace rabitqlib::clustering {
enum class FinalAssignmentMode : uint8_t {
Approximate = 0,
- SymphonyQG = Approximate, // Compatibility name for the graph assignment path.
Exact = 1,
};
diff --git a/include/rabitqlib/clustering/qgkmeans.hpp b/include/rabitqlib/clustering/qgkmeans.hpp
index 280c75f6..51916b18 100644
--- a/include/rabitqlib/clustering/qgkmeans.hpp
+++ b/include/rabitqlib/clustering/qgkmeans.hpp
@@ -29,7 +29,6 @@
namespace rabitqlib::qgkmeans {
using clustering::FinalAssignmentMode;
-using QGKMeansIterationStats = clustering::KMeansIterationStats;
namespace detail {
@@ -52,14 +51,14 @@ struct QGKMeansParameters {
FinalAssignmentMode final_assignment = FinalAssignmentMode::Approximate;
// SymphonyQG assignment parameters.
- uint32_t graph_degree = 32;
- uint32_t ef_build = 240;
+ uint32_t max_degree = 32;
+ uint32_t ef_construction = 240;
uint32_t ef_search = 16;
// Graph-building passes after PiPNN initialization; the last refines the graph.
uint32_t graph_build_iterations = 1;
uint32_t num_threads = 0;
- // Centroid storage in QG: 0 for raw float32, or 4/8-bit RaBitQ.
- uint32_t quantization_bits = 0;
+ // Centroid storage in QG: 32 for raw float32, or 4/8-bit RaBitQ.
+ uint32_t nbits = 32;
// When positive, train on a random sample of k * max_points_per_centroid
// vectors if there are more, then assign all vectors; 0 trains on all vectors.
size_t max_points_per_centroid = 0;
@@ -67,6 +66,11 @@ struct QGKMeansParameters {
namespace detail {
+// QG's own storage argument, which is 0 for raw float32.
+inline uint32_t qg_quantization_bits(const QGKMeansParameters& cp) {
+ return cp.nbits == 32 ? 0 : cp.nbits;
+}
+
// One training call owns the storage; the public assign adapter can instead
// borrow caller storage for one batch. State is read-only while workers run.
class QuerySumCache {
@@ -136,8 +140,8 @@ class QGAssigner {
QGAssigner(
size_t d,
size_t k,
- uint32_t graph_degree,
- uint32_t ef_build,
+ uint32_t max_degree,
+ uint32_t ef_construction,
uint32_t ef_search,
uint32_t graph_build_iterations,
uint32_t num_threads = 0,
@@ -147,8 +151,8 @@ class QGAssigner {
)
: dim_(d)
, num_clusters_(k)
- , graph_degree_(graph_degree)
- , ef_build_(ef_build)
+ , max_degree_(max_degree)
+ , ef_construction_(ef_construction)
, ef_search_(ef_search)
, graph_build_iterations_(graph_build_iterations)
, seed_(seed) {
@@ -158,7 +162,7 @@ class QGAssigner {
graph_ = std::make_unique>(
num_clusters_,
dim_,
- graph_degree_,
+ max_degree_,
metric_type,
RotatorType::FhtKacRotator,
quantization_bits,
@@ -170,7 +174,7 @@ class QGAssigner {
for (uint32_t thread = 0; thread < num_workers_; ++thread) {
scratch_.emplace_back(
std::make_unique(
- graph_->padded_dim(), graph_degree_, ef_search_, 1
+ graph_->padded_dim(), max_degree_, ef_search_, 1
)
);
}
@@ -207,7 +211,7 @@ class QGAssigner {
);
builder_ = std::make_unique(
*graph_,
- ef_build_,
+ ef_construction_,
centroids,
build_threads,
symqg::QGInitialization::PiPNN,
@@ -284,7 +288,7 @@ class QGAssigner {
for (uint32_t thread = 0; thread < num_workers_; ++thread) {
scratch.emplace_back(
std::make_unique(
- graph_->padded_dim(), graph_degree_, ef_search_, 1
+ graph_->padded_dim(), max_degree_, ef_search_, 1
)
);
}
@@ -367,19 +371,19 @@ class QGAssigner {
"QGKMeans currently requires dimensions in the range [64, 65536]"
);
}
- if (graph_degree_ == 0 || graph_degree_ % fastscan::kBatchSize != 0) {
+ if (max_degree_ == 0 || max_degree_ % fastscan::kBatchSize != 0) {
throw std::invalid_argument(
- "QGKMeans graph degree must be a positive multiple of 32"
+ "QGKMeans max_degree must be a positive multiple of 32"
);
}
- if (num_clusters_ <= graph_degree_) {
+ if (num_clusters_ <= max_degree_) {
+ throw std::invalid_argument("QGKMeans requires more centroids than max_degree");
+ }
+ if (ef_construction_ == 0 || ef_search_ == 0) {
throw std::invalid_argument(
- "QGKMeans requires more centroids than the graph degree"
+ "QGKMeans ef_construction and ef_search must be positive"
);
}
- if (ef_build_ == 0 || ef_search_ == 0) {
- throw std::invalid_argument("QGKMeans ef_build and ef_search must be positive");
- }
if (graph_build_iterations_ == 0) {
throw std::invalid_argument("QGKMeans graph_build_iterations must be positive");
}
@@ -387,8 +391,8 @@ class QGAssigner {
size_t dim_;
size_t num_clusters_;
- uint32_t graph_degree_;
- uint32_t ef_build_;
+ uint32_t max_degree_;
+ uint32_t ef_construction_;
uint32_t ef_search_;
uint32_t graph_build_iterations_;
uint32_t num_workers_ = 0;
@@ -416,14 +420,14 @@ class CentroidGraphCache {
, assigner(
d,
k,
- cp.graph_degree,
- cp.ef_build,
+ cp.max_degree,
+ cp.ef_construction,
cp.ef_search,
cp.graph_build_iterations,
cp.num_threads,
cp.seed,
cp.spherical ? METRIC_IP : METRIC_L2,
- cp.quantization_bits
+ qg_quantization_bits(cp)
) {
// The builder borrows this copy, which lives as long as the graph.
assigner.rebuild_centroid_graph(centroids.data());
@@ -436,11 +440,10 @@ class CentroidGraphCache {
return centroids.size() == k * d &&
std::equal(centroids.begin(), centroids.end(), source) &&
p.spherical == cp.spherical && p.seed == cp.seed &&
- p.graph_degree == cp.graph_degree && p.ef_build == cp.ef_build &&
- p.ef_search == cp.ef_search &&
+ p.max_degree == cp.max_degree &&
+ p.ef_construction == cp.ef_construction && p.ef_search == cp.ef_search &&
p.graph_build_iterations == cp.graph_build_iterations &&
- p.num_threads == cp.num_threads &&
- p.quantization_bits == cp.quantization_bits;
+ p.num_threads == cp.num_threads && p.nbits == cp.nbits;
}
};
@@ -513,9 +516,8 @@ class QGAssignment {
static constexpr const char* kName = "QGKMeans";
static void validate_parameters(size_t, const QGKMeansParameters& cp) {
- if (cp.quantization_bits != 0 && cp.quantization_bits != 4 &&
- cp.quantization_bits != 8) {
- throw std::invalid_argument("QGKMeans quantization_bits must be 0, 4, or 8");
+ if (cp.nbits != 4 && cp.nbits != 8 && cp.nbits != 32) {
+ throw std::invalid_argument("QGKMeans nbits must be 4, 8, or 32");
}
}
@@ -532,18 +534,18 @@ class QGAssignment {
, num_points_(n)
, num_workers_(num_workers)
, metric_type_(cp.spherical ? METRIC_IP : METRIC_L2)
- , quantized_(cp.quantization_bits != 0)
+ , quantized_(cp.nbits != 32)
, assigner_(
d,
k,
- cp.graph_degree,
- cp.ef_build,
+ cp.max_degree,
+ cp.ef_construction,
cp.ef_search,
cp.graph_build_iterations,
cp.num_threads,
cp.seed,
metric_type_,
- cp.quantization_bits
+ qg_quantization_bits(cp)
)
, query_sums_(assigner_.graph_->padded_dim(), cp) {}
diff --git a/include/rabitqlib/clustering/rabitqkmeans.hpp b/include/rabitqlib/clustering/rabitqkmeans.hpp
index 7550ed4d..a8d37e65 100644
--- a/include/rabitqlib/clustering/rabitqkmeans.hpp
+++ b/include/rabitqlib/clustering/rabitqkmeans.hpp
@@ -25,7 +25,6 @@
namespace rabitqlib::rabitqkmeans {
using clustering::FinalAssignmentMode;
-using RaBitQKMeansIterationStats = clustering::KMeansIterationStats;
struct RaBitQKMeansParameters {
// Number of clustering iterations.
diff --git a/python_bindings/__init__.py b/python_bindings/__init__.py
index a1057203..5364678c 100644
--- a/python_bindings/__init__.py
+++ b/python_bindings/__init__.py
@@ -4,904 +4,21 @@
and adds the clustering wrappers. Import public classes from ``rabitqlib``.
"""
-import inspect
-import operator
-import sys
-import warnings
-
-from ._rabitqlib import (
- FinalAssignmentMode as _FinalAssignmentMode,
-)
from ._rabitqlib import (
FormatError,
HnswIndex,
IvfIndex,
+ KMeansIterationStats,
QGKMeansParameters,
RaBitQKMeansParameters,
SymqgIndex,
_QGKMeans,
_RaBitQKMeans,
)
-from ._rabitqlib import (
- QGKMeansIterationStats as KMeansIterationStats,
-)
from ._rabitqlib import (
__version__ as __version__,
)
-# --- 0.8 compatibility layer; remove in 0.9 --------------------------------
-# The extension classes expose only the 0.8 API. As Faiss does for its SWIG
-# classes, the 0.7 call forms are restored by replacing methods on those classes
-# at import time, so the public types stay the native ones.
-
-_MIGRATION = (
- "see https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/; "
- "the old form will be removed in 0.9"
-)
-_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)
-
-
-def _bind(signature, name, args, kwargs, hint=""):
- try:
- bound = signature.bind(*args, **kwargs)
- except TypeError as error:
- raise TypeError(f"{name}() {error}{hint}") from None
- bound.apply_defaults()
- arguments = dict(bound.arguments)
- del arguments["self"]
- return arguments
-
-
-def _ivf_signature(
- self, dim, num_clusters, *, nbits=7, metric="l2", routing="auto", seed=None
-): ...
-
-
-def _ivf_legacy_signature(
- self, dim, max_elements, num_clusters, nbits, metric="l2", initializer="auto"
-): ...
-
-
-def _hnsw_signature(
- self,
- dim,
- *,
- nbits=7,
- num_clusters=16,
- M=16,
- ef_construction=200,
- metric="l2",
- seed=100,
-): ...
-
-
-def _hnsw_legacy_signature(
- self,
- dim,
- max_elements,
- M=16,
- ef_construction=200,
- nbits=8,
- metric="l2",
- random_seed=100,
-): ...
-
-
-def _add_signature(
- self, data, *, cluster_ids=None, num_threads=None, fast_quantization=False
-): ...
-
-
-def _patch_ivf_init(cls):
- native_init = cls.__init__
- signature = inspect.signature(_ivf_signature)
- legacy_signature = inspect.signature(_ivf_legacy_signature)
-
- def __init__(self, *args, **kwargs):
- # A third positional argument, max_elements, or num_clusters by keyword
- # after two positional arguments can only be the 0.7 form.
- if (
- len(args) > 2
- or "max_elements" in kwargs
- or (len(args) == 2 and "num_clusters" in kwargs)
- ):
- arguments = _bind(
- legacy_signature,
- "IvfIndex",
- (self, *args),
- kwargs,
- " (read as the 0.7 form IvfIndex(dim, max_elements, num_clusters, "
- "nbits, ...); the 0.8 form is IvfIndex(dim, num_clusters, nbits=...))",
- )
- _deprecated(
- "IvfIndex(dim, max_elements, num_clusters, nbits, ...) is deprecated; "
- "use IvfIndex(dim, num_clusters, nbits=...), whose first add() trains it"
- )
- native_init(
- self,
- arguments["dim"],
- arguments["num_clusters"],
- nbits=arguments["nbits"],
- metric=arguments["metric"],
- initializer=arguments["initializer"],
- _max_elements=arguments["max_elements"],
- )
- return
- # 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
- cls.__init__ = __init__
-
-
-def _patch_hnsw_init(cls):
- native_init = cls.__init__
- signature = inspect.signature(_hnsw_signature)
- legacy_signature = inspect.signature(_hnsw_legacy_signature)
-
- def __init__(self, *args, **kwargs):
- if len(args) > 1 or "max_elements" in kwargs:
- arguments = _bind(
- legacy_signature,
- "HnswIndex",
- (self, *args),
- kwargs,
- " (read as the 0.7 form HnswIndex(dim, max_elements, ...); "
- "the 0.8 form is HnswIndex(dim, nbits=...))",
- )
- _deprecated(
- "HnswIndex(dim, max_elements, ...) is deprecated; use "
- "HnswIndex(dim, nbits=...), whose capacity grows on add"
- )
- native_init(
- self,
- arguments["dim"],
- _max_elements=arguments["max_elements"],
- M=arguments["M"],
- ef_construction=arguments["ef_construction"],
- nbits=arguments["nbits"],
- metric=arguments["metric"],
- random_seed=arguments["random_seed"],
- )
- return
- random_seed = kwargs.pop("random_seed", _MISSING)
- if random_seed is not _MISSING:
- if "seed" in kwargs:
- raise TypeError(
- "HnswIndex() got both seed and its old name random_seed"
- )
- _deprecated("HnswIndex(random_seed=...) is deprecated; use seed=")
- kwargs["seed"] = random_seed
- 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
- cls.__init__ = __init__
-
-
-def _patch_add(cls):
- native_add = cls.add
- name = cls.__name__
- options = ("cluster_ids", "num_threads", "fast_quantization")
-
- def add(self, data, *args, **kwargs):
- if args:
- if len(args) > len(options):
- raise TypeError(
- f"{name}.add() takes at most {len(options) + 1} positional "
- f"arguments ({len(args) + 1} given)"
- )
- _deprecated(
- f"passing {', '.join(options[: len(args)])} to {name}.add() by "
- "position is deprecated; pass them by keyword"
- )
- for option, value in zip(options, args, strict=False):
- if option in kwargs:
- raise TypeError(
- f"{name}.add() got multiple values for argument {option!r}"
- )
- kwargs[option] = value
- return native_add(self, data, **kwargs)
-
- add.__doc__ = native_add.__doc__
- add.__signature__ = inspect.signature(_add_signature)
- cls.add = add
-
-
-def _patch_build(cls):
- name = cls.__name__
-
- def build(
- self, data, centroids, cluster_ids, num_threads=1, fast_quantization=False
- ):
- """Build the index from vectors and supplied centroid assignments.
-
- Deprecated since 0.8 and removed in 0.9: use set_centroids() (or
- train()) and then add(). The defaults match 0.7, including a single
- thread.
-
- Parameters
- ----------
- data : array_like of float, shape (n, dim)
- Vectors in the original, unpadded coordinates. Converted to
- contiguous float32; a copy may be made.
- centroids : array_like of float, shape (num_clusters, dim)
- Vectors in the original, unpadded coordinates. Converted to
- contiguous float32; a copy may be made.
- cluster_ids : array_like of int, shape (n,)
- Centroid ID per vector, in [0, num_clusters). Floating-point and
- boolean IDs are rejected.
- num_threads : int, optional
- Worker count. Default is 1; 0 selects the available CPU count,
- capped by OMP_NUM_THREADS.
- fast_quantization : bool, optional
- Use faster quantizer configuration. Default is False.
- """
- _deprecated(
- f"{name}.build() is deprecated; use set_centroids() or train(), then add()"
- )
- self._build(data, centroids, cluster_ids, num_threads, fast_quantization)
-
- def is_built(self):
- """Deprecated since 0.8: whether the index stores points; use len()."""
- _deprecated(f"{name}.is_built is deprecated; use is_trained or len()")
- return self.num_stored_points != 0
-
- cls.build = build
- cls.is_built = property(is_built, doc=is_built.__doc__)
-
-
-def _symqg_signature(
- self,
- dim,
- *,
- nbits=32,
- max_degree=32,
- ef_construction=200,
- init="pipnn",
- metric="l2",
- seed=None,
-): ...
-
-
-def _symqg_legacy_signature(
- self, dim, max_degree, metric="l2", quantization_bits=0
-): ...
-
-
-def _symqg_nbits(quantization_bits):
- # 0.7 stored raw vectors as 0 bits; 0.8 calls that 32.
- if isinstance(quantization_bits, bool) or quantization_bits not in (0, 4, 8):
- raise ValueError("quantization_bits must be 0, 4, or 8")
- return 32 if quantization_bits == 0 else 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)
-
- def __init__(self, *args, **kwargs):
- if len(args) > 1:
- arguments = _bind(
- legacy_signature,
- "SymqgIndex",
- (self, *args),
- kwargs,
- " (read as the 0.7 form SymqgIndex(dim, max_degree, metric, "
- "quantization_bits); the 0.8 form is SymqgIndex(dim, max_degree=...))",
- )
- _deprecated(
- "SymqgIndex(dim, max_degree, metric, quantization_bits) is deprecated; "
- "use SymqgIndex(dim, max_degree=..., metric=..., nbits=...)"
- )
- nbits = _symqg_nbits(arguments["quantization_bits"])
- native_init(
- self,
- arguments["dim"],
- nbits=nbits,
- max_degree=arguments["max_degree"],
- metric=arguments["metric"],
- )
- return
- quantization_bits = kwargs.pop("quantization_bits", _MISSING)
- if quantization_bits is not _MISSING:
- if "nbits" in kwargs:
- raise TypeError(
- "SymqgIndex() got both nbits and its old form quantization_bits"
- )
- _deprecated(
- "SymqgIndex(quantization_bits=...) is deprecated; use nbits=, with 32 "
- "instead of 0 for raw vectors"
- )
- kwargs["nbits"] = _symqg_nbits(quantization_bits)
- native_init(self, **_bind(signature, "SymqgIndex", (self, *args), kwargs))
-
- def build(self, data, ef_construction, num_threads=1, init="pipnn"):
- """Build the graph from input vectors, replacing any existing graph.
-
- Deprecated since 0.8 and removed in 0.9: pass ef_construction and init to
- the constructor, then call add() once. The defaults match 0.7, including
- a single thread.
-
- Parameters
- ----------
- data : array_like of float, shape (n, dim)
- Vectors in the original, unpadded coordinates, with n > max_degree.
- Converted to contiguous float32; a copy may be made.
- ef_construction : int
- Positive construction search breadth fitting uint32.
- num_threads : int, optional
- Worker count. Default is 1; 0 selects the available CPU count,
- capped by OMP_NUM_THREADS.
- init : {'pipnn', 'random'}, optional
- Graph initialization method. Default is 'pipnn'.
- """
- _deprecated(
- "SymqgIndex.build() is deprecated; pass ef_construction and init to "
- "SymqgIndex() and call add()"
- )
- self._build(data, ef_construction, num_threads, init)
-
- 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 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."""
- _deprecated(
- "SymqgIndex.quantization_bits is deprecated; use nbits, which is 32 "
- "instead of 0 for raw vectors"
- )
- return self._quantization_bits
-
- def is_built(self):
- """Deprecated since 0.8: whether the index holds a graph; use len()."""
- _deprecated("SymqgIndex.is_built is deprecated; use len()")
- return self.num_stored_points != 0
-
- __init__.__doc__ = cls.__doc__
- __init__.__signature__ = signature
- cls.__init__ = __init__
- cls.build = build
- cls.search_batch = search_batch
- cls.quantization_bits = property(quantization_bits, doc=quantization_bits.__doc__)
- cls.is_built = property(is_built, doc=is_built.__doc__)
-
-
-_patch_ivf_init(IvfIndex)
-_patch_hnsw_init(HnswIndex)
-for _cls in (IvfIndex, HnswIndex):
- _patch_add(_cls)
- _patch_build(_cls)
-del _cls
-_patch_symqg(SymqgIndex)
-# --- 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."""
@@ -910,36 +27,16 @@ 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:
- if renamed is not None:
- native.__set__(self.cp, value)
- else:
- setattr(self.cp, name, value)
+ getattr(self.cp, name)
+ except AttributeError:
+ raise AttributeError(
+ f"{type(self).__name__}() got an unexpected keyword argument "
+ f"{name!r}"
+ ) from None
+ try:
+ setattr(self.cp, name, value)
except TypeError as error:
raise TypeError(
f"{type(self).__name__}() could not convert parameter {name!r} "
@@ -968,19 +65,8 @@ def train(self, x):
A failed fit preserves the last successful results. Returned arrays are
copies.
"""
- 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
+ implementation = self._implementation_type(self.d, self.k, self.cp)
+ objective = implementation.train(x)
self._impl = implementation
return objective
@@ -1086,14 +172,11 @@ class QGKMeans(_KMeans):
capped by OMP_NUM_THREADS. Default is 0.
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.
+ assignment against final centroids. Default is 'approximate'.
max_degree : int, optional
- Centroid graph degree; a positive multiple of 32. Default is 32. Named
- graph_degree before 0.8.5.
+ Centroid graph degree; a positive multiple of 32. Default is 32.
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
@@ -1101,7 +184,7 @@ class QGKMeans(_KMeans):
is 1.
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.
+ 32.
Notes
-----
@@ -1118,7 +201,6 @@ class QGKMeans(_KMeans):
_parameters_type = QGKMeansParameters
_implementation_type = _QGKMeans
- _renamed_parameters = _QG_RENAMED
class RaBitQKMeans(_KMeans):
@@ -1154,8 +236,7 @@ class RaBitQKMeans(_KMeans):
capped by OMP_NUM_THREADS. Default is 0.
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.
+ assignment against final centroids. Default is 'approximate'.
Notes
-----
@@ -1182,20 +263,16 @@ class RaBitQKMeans(_KMeans):
_parameters_type = RaBitQKMeansParameters
_implementation_type = _RaBitQKMeans
- _renamed_parameters = {}
__all__ = [
- "FinalAssignmentMode",
"FormatError",
"HnswIndex",
"IvfIndex",
"KMeansIterationStats",
"QGKMeans",
- "QGKMeansIterationStats",
"QGKMeansParameters",
"RaBitQKMeans",
- "RaBitQKMeansIterationStats",
"RaBitQKMeansParameters",
"SymqgIndex",
]
diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi
index 6539dccd..6caf8071 100644
--- a/python_bindings/__init__.pyi
+++ b/python_bindings/__init__.pyi
@@ -5,25 +5,21 @@ Array shapes and numeric ranges are documented runtime constraints.
from collections.abc import Sequence
from os import PathLike
-from typing import Any, ClassVar, Literal, SupportsIndex, TypeAlias, overload
+from typing import Any, Literal, SupportsIndex, TypeAlias
import numpy as np
import numpy.typing as npt
-from typing_extensions import deprecated
__version__: str
__all__ = [
- "FinalAssignmentMode",
"FormatError",
"HnswIndex",
"IvfIndex",
"KMeansIterationStats",
"QGKMeans",
- "QGKMeansIterationStats",
"QGKMeansParameters",
"RaBitQKMeans",
- "RaBitQKMeansIterationStats",
"RaBitQKMeansParameters",
"SymqgIndex",
]
@@ -40,31 +36,6 @@ _IntegerIds: TypeAlias = npt.NDArray[np.integer[Any]] | Sequence[int | np.intege
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.
-
- Approximate uses the selected clustering algorithm. SymphonyQG is a
- compatibility alias for Approximate. Exact performs exhaustive assignment.
- """
-
- Approximate: ClassVar[FinalAssignmentMode]
- SymphonyQG: ClassVar[FinalAssignmentMode]
- Exact: ClassVar[FinalAssignmentMode]
- __members__: ClassVar[dict[str, FinalAssignmentMode]]
-
- def __init__(self, value: SupportsIndex) -> None: ...
- @property
- def name(self) -> str: ...
- @property
- def value(self) -> int: ...
- def __int__(self) -> int: ...
- def __index__(self) -> int: ...
-
class KMeansIterationStats:
"""Read-only statistics for one completed clustering iteration."""
@@ -81,10 +52,6 @@ class KMeansIterationStats:
def nsplit(self) -> int:
"""Number of empty centroids repaired by splitting."""
-# 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.
@@ -101,8 +68,7 @@ class IvfIndex:
Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine'
scales data and queries to unit length.
routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
- Centroid routing strategy. Default is 'auto'. Named initializer before
- 0.8.5.
+ Centroid routing strategy. Default is 'auto'.
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.
@@ -115,9 +81,6 @@ class IvfIndex:
supported; an overlapping mutation raises RuntimeError.
Data, centroids and queries must be finite float32 values within the index
coordinate range; other values raise ValueError.
- The 0.7 form IvfIndex(dim, max_elements, num_clusters, nbits, ...) and
- build() still work in 0.8, raise DeprecationWarning, and will be removed in
- 0.9.
Examples
--------
@@ -131,7 +94,6 @@ class IvfIndex:
((2, 3), (2, 3))
"""
- @overload
def __init__(
self,
dim: SupportsIndex,
@@ -157,8 +119,7 @@ class IvfIndex:
Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine'
scales data and queries to unit length.
routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
- Centroid routing strategy. Default is 'auto'. Named initializer before
- 0.8.5.
+ Centroid routing strategy. Default is 'auto'.
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.
@@ -171,36 +132,7 @@ class IvfIndex:
supported; an overlapping mutation raises RuntimeError.
Data, centroids and queries must be finite float32 values within the index
coordinate range; other values raise ValueError.
- The 0.7 form IvfIndex(dim, max_elements, num_clusters, nbits, ...) and
- build() still work in 0.8, raise DeprecationWarning, and will be removed in
- 0.9.
"""
- @overload
- @deprecated(
- "IvfIndex(dim, max_elements, num_clusters, nbits, ...) is deprecated since "
- "0.8; use IvfIndex(dim, num_clusters, nbits=...), whose first add() trains it"
- )
- def __init__(
- self,
- dim: SupportsIndex,
- max_elements: SupportsIndex,
- num_clusters: SupportsIndex,
- nbits: SupportsIndex,
- metric: _Metric = "l2",
- 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."""
@@ -211,13 +143,6 @@ class IvfIndex:
def dim(self) -> int:
"""Original vector dimension."""
- @property
- @deprecated(
- "IvfIndex.max_elements is deprecated since 0.8.5; use num_stored_points"
- )
- def max_elements(self) -> int:
- """Deprecated since 0.8.5: use num_stored_points."""
-
@property
def num_points(self) -> int:
"""Number of live, searchable points."""
@@ -228,16 +153,11 @@ class IvfIndex:
@property
def is_trained(self) -> bool:
- """Whether centroids are set, by train, set_centroids, the first add, build or load."""
-
- @property
- @deprecated("IvfIndex.is_built is deprecated since 0.8; use is_trained or len()")
- def is_built(self) -> bool:
- """Deprecated since 0.8: whether the index stores points; use len()."""
+ """Whether centroids are set, by train, set_centroids, the first add or load."""
@property
def seed(self) -> int | None:
- """Rotation seed, or None for an index loaded from a file from a release up to 0.8 or created in the 0.7 form."""
+ """Rotation seed, or None for an index loaded from a file from a release up to 0.8."""
@property
def cp(self) -> RaBitQKMeansParameters:
@@ -269,8 +189,7 @@ class IvfIndex:
n >= num_clusters. Converted to contiguous float32; a copy may be made.
num_threads : int, optional
Keyword-only. Worker count for this call. None (default) uses
- cp.num_threads; 0 selects the available CPU count,
- capped by OMP_NUM_THREADS.
+ cp.num_threads; 0 selects the available CPU count, capped by OMP_NUM_THREADS.
Notes
-----
@@ -304,43 +223,6 @@ class IvfIndex:
failed call leaves the index unchanged.
"""
- @deprecated(
- "IvfIndex.build() is deprecated since 0.8; use set_centroids() or "
- "train(), then add()"
- )
- def build(
- self,
- data: npt.ArrayLike,
- centroids: npt.ArrayLike,
- cluster_ids: _IntegerIds,
- num_threads: SupportsIndex = 1,
- fast_quantization: bool | np.bool_ = False,
- ) -> None:
- """Build the index from vectors and supplied centroid assignments.
-
- Deprecated since 0.8 and removed in 0.9: use set_centroids() (or
- train()) and then add(). The defaults match 0.7, including a single
- thread.
-
- Parameters
- ----------
- data : array_like of float, shape (n, dim)
- Vectors in the original, unpadded coordinates. Converted to
- contiguous float32; a copy may be made.
- centroids : array_like of float, shape (num_clusters, dim)
- Vectors in the original, unpadded coordinates. Converted to
- contiguous float32; a copy may be made.
- cluster_ids : array_like of int, shape (n,)
- Centroid ID per vector, in [0, num_clusters). Floating-point and
- boolean IDs are rejected.
- num_threads : int, optional
- Worker count. Default is 1; 0 selects the available CPU count,
- capped by OMP_NUM_THREADS.
- fast_quantization : bool, optional
- Use faster quantizer configuration. Default is False.
- """
-
- @overload
def add(
self,
data: npt.ArrayLike,
@@ -377,24 +259,10 @@ class IvfIndex:
as train(data) does, so data needs at least num_clusters rows, and an
empty first add raises RuntimeError; with
num_threads None, training uses cp.num_threads. Passing cluster_ids to an
- 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 index raises RuntimeError. If the call fails, the index stays
untrained and empty. Batch additions to reduce repeated cluster copying;
- reserve_cluster can preallocate room. Passing the options positionally is
- deprecated.
+ reserve_cluster can preallocate room.
"""
- @overload
- @deprecated(
- "Passing options to IvfIndex.add() by position is deprecated since 0.8; "
- "pass them by keyword"
- )
- def add(
- self,
- data: npt.ArrayLike,
- cluster_ids: _IntegerIds | None,
- num_threads: SupportsIndex = ...,
- fast_quantization: bool | np.bool_ = ...,
- ) -> npt.NDArray[np.int64]: ...
def remove(self, ids: _IntegerIds) -> int:
"""Exclude point IDs from subsequent search results.
@@ -414,7 +282,6 @@ class IvfIndex:
Removal does not reclaim storage and cannot be undone.
"""
- @overload
def search(
self,
queries: npt.ArrayLike,
@@ -435,17 +302,15 @@ 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)
- selects num_clusters / 16, rounded to the nearest integer and at least
- 1; 0 does the same and is deprecated since 0.8.5.
+ Number of clusters to probe, at least 1 and capped at num_clusters. None
+ (default) selects num_clusters / 16, rounded to the nearest integer and
+ at least 1.
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.
+ Keyword-only. Enable HACC. None (default) selects it for 4-9 bits and
+ standard FastScan otherwise. Raw storage uses standard FastScan.
num_threads : int, optional
- 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.
+ Keyword-only. Worker count. None (default) selects 1; 0 selects the
+ available CPU count, capped by OMP_NUM_THREADS.
Returns
-------
@@ -462,18 +327,6 @@ 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.
@@ -512,12 +365,7 @@ class IvfIndex:
@property
def routing(self) -> _Routing:
- """Resolved centroid routing strategy. Named initializer before 0.8.5."""
-
- @property
- @deprecated("IvfIndex.initializer is deprecated since 0.8.5; use routing")
- def initializer(self) -> _Routing:
- """Deprecated since 0.8.5: use routing."""
+ """Resolved centroid routing strategy, never 'auto'."""
def reserve_cluster(
self, cluster_id: SupportsIndex, num_points: SupportsIndex
@@ -529,19 +377,14 @@ class IvfIndex:
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.
+ 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.
+ Requires a trained or loaded index. Reserved room is not saved.
"""
- @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.
@@ -564,9 +407,8 @@ class HnswIndex:
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'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), in [0, 2**32 - 1]; larger values are deprecated since 0.8.5.
- Default is 100.
+ Keyword-only. Graph and rotation seed in [0, 2**32 - 1], also the initial
+ cp.seed. None (default) draws one at random; the seed property reports it.
Notes
-----
@@ -579,23 +421,20 @@ class HnswIndex:
Data, centroids and queries must be finite float32 values within the index
coordinate range; other values raise ValueError.
With more than one thread, add links points in a nondeterministic order;
- pass num_threads=1 for a reproducible graph.
- The 0.7 forms HnswIndex(dim, max_elements, ...), random_seed= and build()
- still work in 0.8, raise DeprecationWarning, and will be removed in 0.9.
+ pass num_threads=1 and a seed for a reproducible graph.
Examples
--------
>>> import numpy as np
>>> from rabitqlib import HnswIndex
>>> x = np.random.default_rng(42).normal(size=(80, 64)).astype(np.float32)
- >>> index = HnswIndex(64, num_clusters=2)
+ >>> index = HnswIndex(64, num_clusters=2, seed=7)
>>> ids = index.add(x, num_threads=1) # trains on x first
>>> ids, distances = index.search(x[:2], k=3)
>>> ids.shape, distances.shape
((2, 3), (2, 3))
"""
- @overload
def __init__(
self,
dim: SupportsIndex,
@@ -605,7 +444,7 @@ class HnswIndex:
M: SupportsIndex = 16,
ef_construction: SupportsIndex = 200,
metric: _Metric = "l2",
- seed: SupportsIndex = 100,
+ seed: SupportsIndex | None = None,
) -> None:
"""An approximate nearest-neighbor index using HNSW.
@@ -628,9 +467,8 @@ class HnswIndex:
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'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), in [0, 2**32 - 1]; larger values are deprecated since 0.8.5.
- Default is 100.
+ Keyword-only. Graph and rotation seed in [0, 2**32 - 1], also the initial
+ cp.seed. None (default) draws one at random; the seed property reports it.
Notes
-----
@@ -643,38 +481,8 @@ class HnswIndex:
Data, centroids and queries must be finite float32 values within the index
coordinate range; other values raise ValueError.
With more than one thread, add links points in a nondeterministic order;
- pass num_threads=1 for a reproducible graph.
- The 0.7 forms HnswIndex(dim, max_elements, ...), random_seed= and build()
- still work in 0.8, raise DeprecationWarning, and will be removed in 0.9.
+ pass num_threads=1 and a seed for a reproducible graph.
"""
- @overload
- @deprecated(
- "HnswIndex(dim, max_elements, ...) is deprecated since 0.8; use "
- "HnswIndex(dim, nbits=...), whose capacity grows on add"
- )
- def __init__(
- self,
- dim: SupportsIndex,
- max_elements: SupportsIndex,
- M: SupportsIndex = 16,
- ef_construction: SupportsIndex = 200,
- nbits: SupportsIndex = 8,
- metric: _Metric = "l2",
- random_seed: SupportsIndex = 100,
- ) -> None: ...
- @overload
- @deprecated("HnswIndex(random_seed=...) is deprecated since 0.8; use seed=")
- def __init__(
- self,
- dim: SupportsIndex,
- *,
- nbits: SupportsIndex = 7,
- num_clusters: SupportsIndex = 16,
- M: SupportsIndex = 16,
- ef_construction: SupportsIndex = 200,
- metric: _Metric = "l2",
- random_seed: SupportsIndex,
- ) -> None: ...
def __repr__(self) -> str:
"""Return a one-line summary of configuration, counts and training state."""
@@ -687,12 +495,7 @@ class HnswIndex:
@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:
- """Deprecated since 0.8.5: use capacity."""
+ """Current storage capacity, in stored points."""
@property
def num_points(self) -> int:
@@ -704,12 +507,7 @@ class HnswIndex:
@property
def is_trained(self) -> bool:
- """Whether centroids are set, by train, set_centroids, the first add, build or load."""
-
- @property
- @deprecated("HnswIndex.is_built is deprecated since 0.8; use is_trained or len()")
- def is_built(self) -> bool:
- """Deprecated since 0.8: whether the index stores points; use len()."""
+ """Whether centroids are set, by train, set_centroids, the first add or load."""
@property
def seed(self) -> int | None:
@@ -717,7 +515,7 @@ class HnswIndex:
@property
def cp(self) -> RaBitQKMeansParameters:
- """Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and cosine, and seed equal to the low 32 bits of the index seed."""
+ """Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and cosine, and seed equal to the index seed."""
@cp.setter
def cp(self, value: RaBitQKMeansParameters) -> None: ...
@@ -753,8 +551,7 @@ class HnswIndex:
n >= num_clusters. Converted to contiguous float32; a copy may be made.
num_threads : int, optional
Keyword-only. Worker count for this call. None (default) uses
- cp.num_threads; 0 selects the available CPU count,
- capped by OMP_NUM_THREADS.
+ cp.num_threads; 0 selects the available CPU count, capped by OMP_NUM_THREADS.
Notes
-----
@@ -780,43 +577,6 @@ class HnswIndex:
failed call leaves the index unchanged.
"""
- @deprecated(
- "HnswIndex.build() is deprecated since 0.8; use set_centroids() or "
- "train(), then add()"
- )
- def build(
- self,
- data: npt.ArrayLike,
- centroids: npt.ArrayLike,
- cluster_ids: _IntegerIds,
- num_threads: SupportsIndex = 1,
- fast_quantization: bool | np.bool_ = False,
- ) -> None:
- """Build the index from vectors and supplied centroid assignments.
-
- Deprecated since 0.8 and removed in 0.9: use set_centroids() (or
- train()) and then add(). The defaults match 0.7, including a single
- thread.
-
- Parameters
- ----------
- data : array_like of float, shape (n, dim)
- Vectors in the original, unpadded coordinates. Converted to
- contiguous float32; a copy may be made.
- centroids : array_like of float, shape (num_clusters, dim)
- Vectors in the original, unpadded coordinates. Converted to
- contiguous float32; a copy may be made.
- cluster_ids : array_like of int, shape (n,)
- Centroid ID per vector, in [0, num_clusters). Floating-point and
- boolean IDs are rejected.
- num_threads : int, optional
- Worker count. Default is 1; 0 selects the available CPU count,
- capped by OMP_NUM_THREADS.
- fast_quantization : bool, optional
- Use faster quantizer configuration. Default is False.
- """
-
- @overload
def add(
self,
data: npt.ArrayLike,
@@ -838,7 +598,8 @@ class HnswIndex:
num_threads : int, optional
Keyword-only. Worker count. None (default) and 0 select the available
CPU count, capped by OMP_NUM_THREADS; more than one thread links
- nondeterministically, so pass 1 for a reproducible graph.
+ nondeterministically, so pass 1, and a seed to the constructor, for a
+ reproducible graph.
fast_quantization : bool, optional
Keyword-only. Use faster quantizer configuration. Default is False.
@@ -855,24 +616,11 @@ class HnswIndex:
RuntimeError. With num_threads None, training
uses cp.num_threads. Passing cluster_ids to an untrained index raises
RuntimeError, as does add on an untrained index loaded from a 0.7 file;
- call train first. If the call fails, the index stays
- untrained and empty. The first add into an empty index links vectors with
- their exact coordinates; later adds link through the stored codes, so add
- most vectors in the first call. Capacity grows geometrically when needed.
- Removed IDs are not reused. Passing the options positionally is deprecated.
+ call train first. If the call fails, the index stays untrained and empty. The first
+ add into an empty index links vectors with their exact coordinates; later adds
+ link through the stored codes, so add most vectors in the first call. Capacity
+ grows geometrically when needed. Removed IDs are not reused.
"""
- @overload
- @deprecated(
- "Passing options to HnswIndex.add() by position is deprecated since 0.8; "
- "pass them by keyword"
- )
- def add(
- self,
- data: npt.ArrayLike,
- cluster_ids: _IntegerIds | None,
- num_threads: SupportsIndex = ...,
- fast_quantization: bool | np.bool_ = ...,
- ) -> npt.NDArray[np.int64]: ...
def remove(self, ids: _IntegerIds) -> int:
"""Exclude point IDs from subsequent search results.
@@ -892,7 +640,6 @@ class HnswIndex:
Removal does not reclaim storage and cannot be undone.
"""
- @overload
def search(
self,
queries: npt.ArrayLike,
@@ -912,13 +659,11 @@ class HnswIndex:
Number of neighbors requested, at least 1. It may exceed the number of
points; slots without a neighbor are padded as described below.
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.
+ Search breadth, at least 1. None (default) selects max(k, 64); values
+ above the stored point count are clamped.
num_threads : int, optional
- 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.
+ Keyword-only. Worker count. None (default) selects 1; 0 selects the
+ available CPU count, capped by OMP_NUM_THREADS.
Returns
-------
@@ -935,27 +680,6 @@ 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.
@@ -999,17 +723,10 @@ class HnswIndex:
Notes
-----
- Capacity only grows: a value at or below capacity changes nothing. add
- also grows the capacity when needed, so reserve is an optimization.
+ 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.
@@ -1044,9 +761,6 @@ class SymqgIndex:
overlapping mutation raises RuntimeError.
Data and queries must be finite float32 values within the index coordinate
range; other values raise ValueError.
- The 0.7 forms SymqgIndex(dim, max_degree, metric, quantization_bits),
- quantization_bits=, build() and search_batch() still work in 0.8, raise
- DeprecationWarning, and will be removed in 0.9.
Examples
--------
@@ -1060,7 +774,6 @@ class SymqgIndex:
((2, 3), (2, 3))
"""
- @overload
def __init__(
self,
dim: SupportsIndex,
@@ -1105,38 +818,7 @@ class SymqgIndex:
overlapping mutation raises RuntimeError.
Data and queries must be finite float32 values within the index coordinate
range; other values raise ValueError.
- The 0.7 forms SymqgIndex(dim, max_degree, metric, quantization_bits),
- quantization_bits=, build() and search_batch() still work in 0.8, raise
- DeprecationWarning, and will be removed in 0.9.
"""
- @overload
- @deprecated(
- "SymqgIndex(dim, max_degree, metric, quantization_bits) is deprecated since "
- "0.8; use SymqgIndex(dim, max_degree=..., metric=..., nbits=...)"
- )
- def __init__(
- self,
- dim: SupportsIndex,
- max_degree: SupportsIndex,
- metric: _Metric = "l2",
- quantization_bits: SupportsIndex = 0,
- ) -> None: ...
- @overload
- @deprecated(
- "SymqgIndex(quantization_bits=...) is deprecated since 0.8; use nbits=, "
- "with 32 instead of 0 for raw vectors"
- )
- def __init__(
- self,
- dim: SupportsIndex,
- *,
- quantization_bits: SupportsIndex,
- max_degree: SupportsIndex = 32,
- ef_construction: SupportsIndex = 200,
- init: _QGInit = "pipnn",
- metric: _Metric = "l2",
- seed: SupportsIndex | None = None,
- ) -> None: ...
def __repr__(self) -> str:
"""Return a one-line summary of configuration and counts."""
@@ -1147,13 +829,6 @@ class SymqgIndex:
def dim(self) -> int:
"""Original vector dimension."""
- @property
- @deprecated(
- "SymqgIndex.max_elements is deprecated since 0.8.5; use num_stored_points"
- )
- def max_elements(self) -> int:
- """Deprecated since 0.8.5: use num_stored_points."""
-
@property
def num_points(self) -> int:
"""Number of live, searchable points."""
@@ -1166,11 +841,6 @@ class SymqgIndex:
def is_trained(self) -> bool:
"""Always True: SymphonyQG needs no training."""
- @property
- @deprecated("SymqgIndex.is_built is deprecated since 0.8; use len()")
- def is_built(self) -> bool:
- """Deprecated since 0.8: whether the index holds a graph; use len()."""
-
@property
def metric(self) -> Literal["l2", "ip", "cosine"]:
"""Canonical metric name: 'l2', 'ip' or 'cosine'."""
@@ -1191,14 +861,6 @@ class SymqgIndex:
def nbits(self) -> int:
"""Storage bits: 32 for raw float32, or 4 or 8 for RaBitQ."""
- @property
- @deprecated(
- "SymqgIndex.quantization_bits is deprecated since 0.8; use nbits, which is "
- "32 instead of 0 for raw vectors"
- )
- def quantization_bits(self) -> int:
- """Deprecated since 0.8: storage bits with 0 for raw vectors; use nbits."""
-
@property
def seed(self) -> int | None:
"""Rotation and graph-construction seed, or None for an index loaded from a file from a release up to 0.8."""
@@ -1251,38 +913,6 @@ class SymqgIndex:
data. Input arrays need not be retained after this synchronous call.
"""
- @deprecated(
- "SymqgIndex.build() is deprecated since 0.8; pass ef_construction and init "
- "to SymqgIndex() and call add()"
- )
- def build(
- self,
- data: npt.ArrayLike,
- ef_construction: SupportsIndex,
- num_threads: SupportsIndex = 1,
- init: _QGInit = "pipnn",
- ) -> None:
- """Build the graph from input vectors, replacing any existing graph.
-
- Deprecated since 0.8 and removed in 0.9: pass ef_construction and init to
- the constructor, then call add() once. The defaults match 0.7, including
- a single thread.
-
- Parameters
- ----------
- data : array_like of float, shape (n, dim)
- Vectors in the original, unpadded coordinates, with n > max_degree.
- Converted to contiguous float32; a copy may be made.
- ef_construction : int
- Positive construction search breadth fitting uint32.
- num_threads : int, optional
- Worker count. Default is 1; 0 selects the available CPU count,
- capped by OMP_NUM_THREADS.
- init : {'pipnn', 'random'}, optional
- Graph initialization method. Default is 'pipnn'.
- """
-
- @overload
def search(
self,
queries: npt.ArrayLike,
@@ -1302,13 +932,11 @@ class SymqgIndex:
Number of neighbors requested, at least 1. It may exceed the number of
points; slots without a neighbor are padded as described below.
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.
+ Search breadth, at least 1. None (default) selects max(k, 64); smaller
+ values are raised to k.
num_threads : int, optional
- 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.
+ Keyword-only. Worker count. None (default) selects 1; 0 selects the
+ available CPU count, capped by OMP_NUM_THREADS.
Returns
-------
@@ -1325,36 +953,6 @@ 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,
- queries: npt.ArrayLike,
- k: SupportsIndex,
- ef: SupportsIndex,
- num_threads: SupportsIndex = 1,
- ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.float32]]:
- """Deprecated since 0.8: the same as search(); use search()."""
def save(self, path: _Path) -> None:
"""Save an index with vectors to disk.
@@ -1421,14 +1019,11 @@ class QGKMeans:
capped by OMP_NUM_THREADS. Default is 0.
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.
+ assignment against final centroids. Default is 'approximate'.
max_degree : int, optional
- Centroid graph degree; a positive multiple of 32. Default is 32. Named
- graph_degree before 0.8.5.
+ Centroid graph degree; a positive multiple of 32. Default is 32.
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
@@ -1436,7 +1031,7 @@ class QGKMeans:
is 1.
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.
+ 32.
Notes
-----
@@ -1455,7 +1050,6 @@ class QGKMeans:
k: int
cp: QGKMeansParameters
- @overload
def __init__(
self,
d: SupportsIndex,
@@ -1469,7 +1063,7 @@ class QGKMeans:
max_points_per_centroid: SupportsIndex = 0,
early_stop_threshold: float = 0.0,
num_threads: SupportsIndex = 0,
- final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate",
+ final_assignment: _FinalAssignment = "approximate",
max_degree: SupportsIndex = 32,
ef_construction: SupportsIndex = 240,
ef_search: SupportsIndex = 16,
@@ -1509,14 +1103,11 @@ class QGKMeans:
capped by OMP_NUM_THREADS. Default is 0.
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.
+ assignment against final centroids. Default is 'approximate'.
max_degree : int, optional
- Centroid graph degree; a positive multiple of 32. Default is 32. Named
- graph_degree before 0.8.5.
+ Centroid graph degree; a positive multiple of 32. Default is 32.
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
@@ -1524,7 +1115,7 @@ class QGKMeans:
is 1.
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.
+ 32.
Notes
-----
@@ -1539,79 +1130,6 @@ 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.
@@ -1743,45 +1261,21 @@ class QGKMeansParameters:
@num_threads.setter
def num_threads(self, value: SupportsIndex) -> None: ...
@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."""
+ def final_assignment(self) -> _FinalAssignment:
+ """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'."""
@final_assignment.setter
- def final_assignment(
- self, value: _FinalAssignment | FinalAssignmentMode
- ) -> None: ...
+ def final_assignment(self, value: _FinalAssignment) -> 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."""
+ """Centroid graph degree; a positive multiple of 32. Default is 32."""
@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:
- """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."""
+ """Positive centroid-graph construction search breadth. Default is 240."""
@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:
- """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:
"""Positive centroid-graph assignment search breadth. Default is 16."""
@ef_search.setter
@@ -1793,20 +1287,9 @@ class QGKMeansParameters:
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."""
+ """Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is 32."""
@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:
- """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."""
@@ -1843,8 +1326,7 @@ class RaBitQKMeans:
capped by OMP_NUM_THREADS. Default is 0.
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.
+ assignment against final centroids. Default is 'approximate'.
Notes
-----
@@ -1886,7 +1368,7 @@ class RaBitQKMeans:
max_points_per_centroid: SupportsIndex = 0,
early_stop_threshold: float = 0.0,
num_threads: SupportsIndex = 0,
- final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate",
+ final_assignment: _FinalAssignment = "approximate",
) -> None:
"""Cluster vectors using flat RaBitQ assignment.
@@ -1920,8 +1402,7 @@ class RaBitQKMeans:
capped by OMP_NUM_THREADS. Default is 0.
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.
+ assignment against final centroids. Default is 'approximate'.
Notes
-----
@@ -1934,16 +1415,6 @@ class RaBitQKMeans:
sample chosen by seed. obj and iteration_stats then describe the sample,
while assignments, distances and final_obj cover all n vectors, so the two
kinds of objective are not directly comparable.
-
- Examples
- --------
- >>> import numpy as np
- >>> from rabitqlib import RaBitQKMeans
- >>> x = np.random.default_rng(42).normal(size=(64, 64)).astype(np.float32)
- >>> model = RaBitQKMeans(64, 2, niter=2, num_threads=1)
- >>> objective = model.train(x)
- >>> model.centroids.shape
- (2, 64)
"""
def train(self, x: npt.ArrayLike) -> float:
@@ -2077,11 +1548,9 @@ class RaBitQKMeansParameters:
@num_threads.setter
def num_threads(self, value: SupportsIndex) -> None: ...
@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."""
+ def final_assignment(self) -> _FinalAssignment:
+ """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'."""
@final_assignment.setter
- def final_assignment(
- self, value: _FinalAssignment | FinalAssignmentMode
- ) -> None: ...
+ def final_assignment(self, value: _FinalAssignment) -> None: ...
def __init__(self) -> None:
"""Create parameters with their documented defaults."""
diff --git a/python_bindings/bindings_common.hpp b/python_bindings/bindings_common.hpp
index c8d58735..92bbceb7 100644
--- a/python_bindings/bindings_common.hpp
+++ b/python_bindings/bindings_common.hpp
@@ -401,6 +401,15 @@ inline void check_k(size_t k) {
}
}
+// A graph search breadth given explicitly is at least 1; None selects the default.
+inline void check_ef_search(std::optional ef_search) {
+ if (ef_search == size_t{0}) {
+ throw std::invalid_argument(
+ "ef_search must be at least 1; pass None for the default"
+ );
+ }
+}
+
inline SearchResults unfilled_search_results(size_t num_queries, size_t k) {
const auto shape = std::vector{
static_cast(num_queries), static_cast(k)};
@@ -459,10 +468,7 @@ inline std::vector checked_removal_ids(
// Validate before narrowing, and own the result for APIs that mutate assignments.
inline std::vector checked_cluster_ids(
- py::handle value,
- size_t rows,
- size_t clusters,
- const char* range_error = "cluster_ids must be in [0, num_clusters)"
+ py::handle value, size_t rows, size_t clusters
) {
const auto checked_copy = [&](const auto& ids) {
if (static_cast(ids.shape(0)) != rows) {
@@ -482,7 +488,7 @@ inline std::vector checked_cluster_ids(
if (id < 0 || static_cast(id) >= clusters ||
static_cast(id) > std::numeric_limits::max()) {
throw std::invalid_argument(
- std::string(range_error) + "; expected [0, " +
+ "cluster_ids must be in [0, num_clusters); expected [0, " +
std::to_string(clusters) + "), invalid entry at index " +
std::to_string(i)
);
diff --git a/python_bindings/hnsw_bindings.cpp b/python_bindings/hnsw_bindings.cpp
index 0768db73..6481e7a9 100644
--- a/python_bindings/hnsw_bindings.cpp
+++ b/python_bindings/hnsw_bindings.cpp
@@ -12,6 +12,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -47,38 +48,18 @@ class HnswIndex {
);
}
const auto metric_type = index_metric_from_string(metric);
- const auto graph_seed = checked_seed(seed, std::numeric_limits::max());
- // Capacity grows on add; resize preallocates.
+ const auto graph_seed =
+ seed.is_none() ? std::random_device{}()
+ : static_cast(
+ checked_seed(seed, std::numeric_limits::max())
+ );
+ // Capacity grows on add; reserve preallocates.
index_ = std::make_unique(
1, dim, nbits, M, ef_construction, graph_seed, metric_type
);
num_clusters_ = num_clusters;
seed_ = graph_seed;
- cp_ = default_training_parameters(metric_type, static_cast(graph_seed));
- }
-
- // The 0.7 form, whose max_elements becomes the initial capacity.
- static HnswIndex with_point_count(
- size_t dim,
- size_t max_elements,
- size_t M,
- size_t ef_construction,
- size_t nbits,
- const std::string& metric,
- const py::object& random_seed
- ) {
- const auto metric_type = index_metric_from_string(metric);
- const auto graph_seed =
- checked_seed(random_seed, std::numeric_limits::max());
- HnswIndex wrapper;
- wrapper.index_ = std::make_unique(
- max_elements, dim, nbits, M, ef_construction, graph_seed, metric_type
- );
- wrapper.num_clusters_ = kDefaultNumClusters;
- wrapper.seed_ = graph_seed;
- wrapper.cp_ =
- default_training_parameters(metric_type, static_cast(graph_seed));
- return wrapper;
+ cp_ = default_training_parameters(metric_type, graph_seed);
}
void train(py::handle x, std::optional num_threads) {
@@ -107,76 +88,6 @@ class HnswIndex {
index_->set_centroids(num_clusters, centroids_ptr);
}
- // Deprecated: the 0.7 build, which takes any number of centroids. An untrained
- // index is constructed; a trained one without points takes the centroids and
- // adds the data, which links it the same way.
- void build(
- py::handle data,
- py::handle centroids,
- py::handle cluster_ids,
- size_t num_threads,
- bool fast_quantization
- ) {
- const auto operation = access_.write();
- auto data_array = ensure_2d_array(data, "data");
- auto centroids_array = ensure_2d_array(centroids, "centroids");
-
- ensure_dimension(
- data_array, index_->dimension(), "data dimension does not match index dim"
- );
- if (data_array.shape(0) == 0) {
- throw std::invalid_argument(
- "number of data rows must be at least 1; got shape " +
- array_shape(data_array)
- );
- }
- ensure_dimension(
- centroids_array,
- index_->dimension(),
- "centroid dimension does not match index dim"
- );
- const size_t num_clusters = static_cast(centroids_array.shape(0));
- if (num_clusters == 0) {
- throw std::invalid_argument("at least one centroid is required");
- }
- const auto rows = static_cast(data_array.shape(0));
- auto cluster_ids_vec = checked_cluster_ids(
- cluster_ids, rows, num_clusters, "cluster_ids contains an out-of-range value"
- );
-
- const auto* data_ptr = data_array.data();
- const auto* centroids_ptr = centroids_array.data();
- const size_t dim = index_->dimension();
- {
- py::gil_scoped_release release;
- const bool empty = index_->num_stored_points() == 0;
- if (empty) {
- // Invalid centroids must not grow or retrain the index first.
- check_coordinates(
- centroids_ptr, num_clusters * dim, dim, "HNSW construction centroids"
- );
- grow_capacity(*index_, rows, data_ptr, "HNSW construction data");
- }
- if (empty && index_->is_trained()) {
- index_->set_centroids(num_clusters, centroids_ptr);
- index_->add(
- data_ptr, rows, cluster_ids_vec.data(), fast_quantization, num_threads
- );
- } else {
- index_->construct(
- num_clusters,
- centroids_ptr,
- rows,
- data_ptr,
- cluster_ids_vec.data(),
- num_threads,
- fast_quantization
- );
- }
- }
- num_clusters_ = num_clusters;
- }
-
py::array_t add(
py::handle data,
const py::object& cluster_ids,
@@ -246,10 +157,23 @@ class HnswIndex {
return ids;
}
- void resize(size_t new_max_elements) {
+ void reserve(int64_t num_points) {
+ if (num_points < 0) {
+ throw std::invalid_argument("num_points must be non-negative");
+ }
+ {
+ // Capacity only grows, and a request within it changes nothing, so it
+ // may run alongside searches.
+ const auto reading = access_.read();
+ if (static_cast(num_points) <= index_->max_elements()) {
+ return;
+ }
+ }
+ // The GIL is held from the check above to this guard, so no other call
+ // can change the capacity in between.
const auto operation = access_.write();
py::gil_scoped_release release;
- index_->resize(new_max_elements);
+ index_->resize(static_cast(num_points));
}
size_t remove(py::handle ids) {
@@ -273,7 +197,7 @@ class HnswIndex {
py::tuple search(
py::handle queries,
size_t k,
- std::optional ef,
+ std::optional ef_search,
std::optional num_threads
) {
const auto operation = access_.read();
@@ -283,8 +207,9 @@ class HnswIndex {
query_array, index_->dimension(), "query dimension does not match index dim"
);
check_k(k);
- // None and 0 select max(k, 64), as SymqgIndex does.
- const size_t ef_search = ef.value_or(0) == 0 ? std::max(k, 64) : *ef;
+ check_ef_search(ef_search);
+ // None selects max(k, 64), as in SymqgIndex.
+ const size_t search_breadth = ef_search.value_or(std::max(k, 64));
auto output = unfilled_search_results(static_cast(query_array.shape(0)), k);
auto distances_view = output.distances.mutable_unchecked<2>();
@@ -295,7 +220,7 @@ class HnswIndex {
{
py::gil_scoped_release release;
results = index_->search(
- queries_data, num_queries, k, ef_search, num_threads.value_or(1)
+ queries_data, num_queries, k, search_breadth, num_threads.value_or(1)
);
}
@@ -356,7 +281,7 @@ class HnswIndex {
"', nbits=" + std::to_string(index_->nbits()) +
", num_points=" + std::to_string(index_->num_points()) +
", num_stored_points=" + std::to_string(index_->num_stored_points()) +
- ", max_elements=" + std::to_string(index_->max_elements()) +
+ ", capacity=" + std::to_string(index_->max_elements()) +
", num_clusters=" + std::to_string(current_num_clusters()) +
", is_trained=" + (index_->is_trained() ? "True" : "False") + ")";
}
@@ -365,7 +290,7 @@ class HnswIndex {
const auto operation = access_.read();
return index_->dimension();
}
- [[nodiscard]] size_t max_elements() const {
+ [[nodiscard]] size_t capacity() const {
const auto operation = access_.read();
return index_->max_elements();
}
@@ -484,8 +409,8 @@ metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'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.
+ Keyword-only. Graph and rotation seed in [0, 2**32 - 1], also the initial
+ cp.seed. None (default) draws one at random; the seed property reports it.
Notes
-----
@@ -493,21 +418,19 @@ The first add trains an untrained index on the added vectors. Call train
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.
With more than one thread, add links points in a nondeterministic order;
-pass num_threads=1 for a reproducible graph.
-The 0.7 forms HnswIndex(dim, max_elements, ...), random_seed= and build()
-still work in 0.8, raise DeprecationWarning, and will be removed in 0.9.
+pass num_threads=1 and a seed for a reproducible graph.
Examples
--------
>>> import numpy as np
>>> from rabitqlib import HnswIndex
>>> x = np.random.default_rng(42).normal(size=(80, 64)).astype(np.float32)
->>> index = HnswIndex(64, num_clusters=2)
+>>> index = HnswIndex(64, num_clusters=2, seed=7)
>>> ids = index.add(x, num_threads=1) # trains on x first
>>> ids, distances = index.search(x[:2], k=3)
>>> ids.shape, distances.shape
@@ -526,7 +449,8 @@ cluster_ids : array_like of int, shape (n,), optional
num_threads : int, optional
Keyword-only. Worker count. None (default) and 0 select the available
CPU count, capped by OMP_NUM_THREADS; more than one thread links
- nondeterministically, so pass 1 for a reproducible graph.
+ nondeterministically, so pass 1, and a seed to the constructor, for a
+ reproducible graph.
fast_quantization : bool, optional
Keyword-only. Use faster quantizer configuration. Default is False.
@@ -546,8 +470,7 @@ RuntimeError, as does add on an untrained index loaded from a 0.7 file;
call train first. If the call fails, the index stays untrained and empty. The first
add into an empty index links vectors with their exact coordinates; later adds
link through the stored codes, so add most vectors in the first call. Capacity
-grows geometrically when needed. Removed IDs are not reused. Passing the options
-positionally is deprecated.)doc";
+grows geometrically when needed. Removed IDs are not reused.)doc";
py::class_(m, "HnswIndex", kIndexDoc)
.def(
@@ -566,21 +489,9 @@ positionally is deprecated.)doc";
py::arg("M") = 16,
py::arg("ef_construction") = 200,
py::arg("metric") = "l2",
- py::arg("seed") = 100,
+ py::arg("seed") = py::none(),
kIndexDoc
)
- // Private to the 0.8 compatibility layer in rabitqlib/__init__.py.
- .def(
- py::init(&HnswIndex::with_point_count),
- py::arg("dim"),
- py::kw_only(),
- py::arg("_max_elements"),
- py::arg("M"),
- py::arg("ef_construction"),
- py::arg("nbits"),
- py::arg("metric"),
- py::arg("random_seed")
- )
.def(
"train",
&HnswIndex::train,
@@ -623,21 +534,13 @@ The index counts as trained afterwards. Replacing centroids is allowed
while the index stores no vectors and raises RuntimeError afterwards. A
failed call leaves the index unchanged.)doc"
)
- .def(
- "_build",
- &HnswIndex::build,
- py::arg("data"),
- py::arg("centroids"),
- py::arg("cluster_ids"),
- py::arg("num_threads"),
- py::arg("fast_quantization")
- )
.def(
"search",
&HnswIndex::search,
py::arg("queries"),
py::arg("k"),
- py::arg("ef") = py::none(),
+ py::arg("ef_search") = py::none(),
+ py::kw_only(),
py::arg("num_threads") = py::none(),
R"doc(Search a batch of query vectors.
@@ -649,12 +552,12 @@ queries : array_like of float, shape (n_queries, dim)
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, at least 1. None (default) selects max(k, 64); values
+ above the stored point count are clamped.
num_threads : int, optional
- Worker count. None (default) selects 1; 0 selects the available CPU
- count, capped by OMP_NUM_THREADS.
+ Keyword-only. Worker count. None (default) selects 1; 0 selects the
+ available CPU count, capped by OMP_NUM_THREADS.
Returns
-------
@@ -682,15 +585,21 @@ and value ranges are checked at runtime, not by static type checkers.)doc"
kAddDoc
)
.def(
- "resize",
- &HnswIndex::resize,
- py::arg("max_elements"),
- R"doc(Change the storage capacity, for example to preallocate before add.
+ "reserve",
+ &HnswIndex::reserve,
+ py::arg("num_points"),
+ R"doc(Preallocate room for at least num_points stored points.
Parameters
----------
-max_elements : int
- New capacity; must be at least num_stored_points.)doc"
+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.)doc"
)
.def(
"remove",
@@ -762,7 +671,9 @@ index : HnswIndex
"dim", &HnswIndex::dim, R"doc(Original vector dimension.)doc"
)
.def_property_readonly(
- "max_elements", &HnswIndex::max_elements, R"doc(Current storage capacity.)doc"
+ "capacity",
+ &HnswIndex::capacity,
+ R"doc(Current storage capacity, in stored points.)doc"
)
.def_property_readonly(
"num_points",
@@ -795,7 +706,7 @@ index : HnswIndex
.def_property_readonly(
"is_trained",
&HnswIndex::is_trained,
- R"doc(Whether centroids are set, by train, set_centroids, the first add, build or load.)doc"
+ R"doc(Whether centroids are set, by train, set_centroids, the first add or load.)doc"
)
.def_property_readonly(
"seed",
@@ -807,7 +718,7 @@ index : HnswIndex
&HnswIndex::cp,
&HnswIndex::set_cp,
py::return_value_policy::reference_internal,
- R"doc(Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and cosine, and seed equal to the low 32 bits of the index seed.)doc"
+ R"doc(Clustering parameters train uses, a RaBitQKMeansParameters. Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and cosine, and seed equal to the index seed.)doc"
)
.def_property_readonly(
"metric",
diff --git a/python_bindings/ivf_bindings.cpp b/python_bindings/ivf_bindings.cpp
index 48d6c321..77e5dbaa 100644
--- a/python_bindings/ivf_bindings.cpp
+++ b/python_bindings/ivf_bindings.cpp
@@ -23,14 +23,13 @@
#include "rabitqlib/index/ivf/ivf.hpp"
#include "rabitqlib/index/training.hpp"
#include "rabitqlib/index/types.hpp"
-#include "rabitqlib/utils/input_checks.hpp"
namespace py = pybind11;
namespace rabitqlib::python_bindings {
namespace {
-ivf::InitializerType initializer_from_string(const std::string& value) {
+ivf::InitializerType routing_from_string(const std::string& value) {
if (value == "auto") {
return ivf::InitializerType::Auto;
}
@@ -43,12 +42,10 @@ ivf::InitializerType initializer_from_string(const std::string& value) {
if (value == "hnsw") {
return ivf::InitializerType::HNSW;
}
- throw std::invalid_argument(
- "initializer must be 'auto', 'flat', 'flat_rabitq', or 'hnsw'"
- );
+ throw std::invalid_argument("routing must be 'auto', 'flat', 'flat_rabitq', or 'hnsw'");
}
-std::string initializer_to_string(ivf::InitializerType type) {
+std::string routing_to_string(ivf::InitializerType type) {
switch (type) {
case ivf::InitializerType::Auto:
return "auto";
@@ -70,11 +67,11 @@ class IvfIndex {
size_t num_clusters,
size_t nbits,
const std::string& metric,
- const std::string& initializer,
+ const std::string& routing,
const py::object& seed
) {
const auto metric_type = index_metric_from_string(metric);
- const auto initializer_type = initializer_from_string(initializer);
+ const auto initializer_type = routing_from_string(routing);
const auto rotation_seed =
seed.is_none() ? std::random_device{}()
: static_cast(
@@ -93,31 +90,6 @@ class IvfIndex {
cp_ = default_training_parameters(metric_type, rotation_seed);
}
- // The 0.7 point-count form, which build fills with construct.
- static IvfIndex with_point_count(
- size_t dim,
- size_t max_elements,
- size_t num_clusters,
- size_t nbits,
- const std::string& metric,
- const std::string& initializer
- ) {
- const auto metric_type = index_metric_from_string(metric);
- IvfIndex wrapper;
- wrapper.index_ = std::make_unique(
- max_elements,
- dim,
- num_clusters,
- nbits,
- metric_type,
- RotatorType::FhtKacRotator,
- initializer_from_string(initializer)
- );
- wrapper.cp_ = untrainable_parameters(metric_type);
- wrapper.builds_by_construct_ = true;
- return wrapper;
- }
-
void train(py::handle x, std::optional num_threads) {
const auto operation = access_.write();
auto x_array = ensure_2d_array(x, "x");
@@ -142,67 +114,6 @@ class IvfIndex {
index_->set_centroids(centroids_ptr, num_threads.value_or(0));
}
- // Deprecated: the 0.7 build. A point-count index is constructed; any other
- // index sets the centroids and adds the data.
- void build(
- py::handle data,
- py::handle centroids,
- py::handle cluster_ids,
- size_t num_threads,
- bool fast_quantization
- ) {
- const auto operation = access_.write();
- auto data_array = ensure_2d_array(data, "data");
- auto centroids_array = ensure_2d_array(centroids, "centroids");
-
- ensure_dimension(
- data_array, index_->dimension(), "data dimension does not match index dim"
- );
- if (builds_by_construct_ &&
- static_cast(data_array.shape(0)) != index_->max_elements()) {
- throw std::invalid_argument(
- "number of data rows must match index max_elements; expected " +
- std::to_string(index_->max_elements()) + ", got shape " +
- array_shape(data_array)
- );
- }
- ensure_dimension(
- centroids_array,
- index_->dimension(),
- "centroid dimension does not match index dim"
- );
- if (static_cast(centroids_array.shape(0)) != index_->num_clusters()) {
- throw std::invalid_argument(
- "number of centroid rows must match index num_clusters; expected " +
- std::to_string(index_->num_clusters()) + ", got shape " +
- array_shape(centroids_array)
- );
- }
- const auto rows = static_cast(data_array.shape(0));
- auto cluster_ids_vec =
- checked_cluster_ids(cluster_ids, rows, index_->num_clusters());
- if (!builds_by_construct_) {
- check_trainable();
- }
-
- const auto* data_ptr = data_array.data();
- const auto* centroids_ptr = centroids_array.data();
- const auto* cluster_ids_ptr = cluster_ids_vec.data();
- py::gil_scoped_release release;
- if (builds_by_construct_) {
- index_->construct(
- data_ptr, centroids_ptr, cluster_ids_ptr, fast_quantization, num_threads
- );
- } else {
- // Check the data before replacing the centroids, so that invalid input
- // leaves the index unchanged; add repeats the check.
- const size_t dim = index_->dimension();
- check_coordinates(data_ptr, rows * dim, dim, "IVF add data");
- index_->set_centroids(centroids_ptr, num_threads);
- index_->add(data_ptr, rows, cluster_ids_ptr, fast_quantization, num_threads);
- }
- }
-
py::array_t add(
py::handle data,
const py::object& cluster_ids,
@@ -211,9 +122,10 @@ class IvfIndex {
) {
const auto operation = access_.write();
auto data_array = ensure_2d_array(data, "data");
- // The first add on an untrained 0.8-form index trains it on the same data.
- const bool trains = !index_->is_trained() && !builds_by_construct_ &&
- cluster_ids.is_none() && data_array.shape(0) > 0;
+ // The first add on an untrained index trains it on the same data. A loaded
+ // index is trained, so an untrained one knows its seed.
+ const bool trains =
+ !index_->is_trained() && cluster_ids.is_none() && data_array.shape(0) > 0;
if (!trains) {
check_trained("add");
}
@@ -279,9 +191,9 @@ class IvfIndex {
return ids;
}
- void reserve(int64_t cluster_id, int64_t num_points) {
+ void reserve_cluster(int64_t cluster_id, int64_t num_points) {
const auto operation = access_.write();
- check_trained("reserve");
+ check_trained("reserve_cluster");
if (cluster_id < 0 || static_cast(cluster_id) >= index_->num_clusters()) {
throw std::invalid_argument("cluster_id must be in [0, num_clusters)");
}
@@ -315,10 +227,14 @@ class IvfIndex {
query_array, index_->dimension(), "query dimension does not match index dim"
);
check_k(k);
- // None and 0 probe num_clusters / 16 clusters, rounded, and at least one.
+ if (nprobe == size_t{0}) {
+ throw std::invalid_argument(
+ "nprobe must be at least 1; pass None for the default"
+ );
+ }
+ // None probes num_clusters / 16 clusters, rounded, and at least one.
const size_t num_probes =
- nprobe.value_or(0) == 0 ? std::max(1, (index_->num_clusters() + 8) / 16)
- : *nprobe;
+ nprobe.value_or(std::max(1, (index_->num_clusters() + 8) / 16));
const size_t num_queries = static_cast(query_array.shape(0));
auto output = unfilled_search_results(num_queries, k);
@@ -362,7 +278,6 @@ class IvfIndex {
py::gil_scoped_release release;
wrapper.index_->load(filename.c_str());
}
- wrapper.builds_by_construct_ = true;
wrapper.seed_ = wrapper.index_->seed(); // recorded by format-2 files
wrapper.cp_ = default_training_parameters(
wrapper.index_->metric_type(),
@@ -378,9 +293,8 @@ class IvfIndex {
"', nbits=" + std::to_string(index_->nbits()) +
", num_points=" + std::to_string(index_->num_points()) +
", num_stored_points=" + std::to_string(index_->num_stored_points()) +
- ", max_elements=" + std::to_string(index_->max_elements()) +
- ", num_clusters=" + std::to_string(index_->num_clusters()) +
- ", initializer='" + initializer_to_string(index_->initializer_type()) +
+ ", num_clusters=" + std::to_string(index_->num_clusters()) + ", routing='" +
+ routing_to_string(index_->initializer_type()) +
"', is_trained=" + (index_->is_trained() ? "True" : "False") + ")";
}
@@ -388,10 +302,6 @@ class IvfIndex {
const auto operation = access_.read();
return index_->dimension();
}
- [[nodiscard]] size_t max_elements() const {
- const auto operation = access_.read();
- return index_->max_elements();
- }
[[nodiscard]] size_t num_points() const {
const auto operation = access_.read();
return index_->num_points();
@@ -416,9 +326,9 @@ class IvfIndex {
const auto operation = access_.read();
return seed_;
}
- [[nodiscard]] std::string initializer() const {
+ [[nodiscard]] std::string routing() const {
const auto operation = access_.read();
- return initializer_to_string(index_->initializer_type());
+ return routing_to_string(index_->initializer_type());
}
[[nodiscard]] std::string metric() const {
const auto operation = access_.read();
@@ -435,13 +345,6 @@ class IvfIndex {
private:
IvfIndex() = default;
- // Parameters of an index that cannot be trained; the k-means default seed.
- static rabitqkmeans::RaBitQKMeansParameters untrainable_parameters(MetricType metric) {
- return default_training_parameters(
- metric, rabitqkmeans::RaBitQKMeansParameters{}.seed
- );
- }
-
void check_trained(const char* operation) const {
if (!index_->is_trained()) {
throw std::runtime_error(
@@ -454,20 +357,12 @@ class IvfIndex {
if (index_->num_stored_points() != 0) {
throw std::runtime_error("IvfIndex cannot be trained once it stores points");
}
- if (builds_by_construct_) {
- throw std::runtime_error(
- "IvfIndex created with max_elements is filled by build; create "
- "IvfIndex(dim, num_clusters, nbits=...) to train or set centroids"
- );
- }
}
mutable IndexAccess access_;
std::unique_ptr index_;
rabitqkmeans::RaBitQKMeansParameters cp_;
- std::optional seed_; // Unknown for point-count indexes and 0.8 files.
- // Point-count and loaded indexes build by construct, never by training.
- bool builds_by_construct_ = false;
+ std::optional seed_; // Unknown for files from releases up to 0.8.
};
} // namespace rabitqlib::python_bindings
@@ -491,7 +386,7 @@ nbits : int, optional
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
+routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
Centroid routing strategy. Default is 'auto'.
seed : int, optional
Rotation seed in [0, 2**32 - 1], also the initial cp.seed. None
@@ -505,9 +400,6 @@ centroids. Loaded indexes are already trained. 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.
-The 0.7 form IvfIndex(dim, max_elements, num_clusters, nbits, ...) and
-build() still work in 0.8, raise DeprecationWarning, and will be removed in
-0.9.
Examples
--------
@@ -529,7 +421,7 @@ data : array_like of float, shape (n, dim)
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
@@ -548,11 +440,9 @@ On an untrained index, add first trains num_clusters centroids on data,
as train(data) does, so data needs at least num_clusters rows, and an
empty first add raises RuntimeError; with
num_threads None, training uses cp.num_threads. Passing cluster_ids to an
-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 index raises RuntimeError. 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
-deprecated.)doc";
+reserve_cluster can preallocate room.)doc";
py::class_(m, "IvfIndex", kIndexDoc)
.def(
@@ -568,30 +458,10 @@ deprecated.)doc";
py::kw_only(),
py::arg("nbits") = 7,
py::arg("metric") = "l2",
- py::arg("initializer") = "auto",
+ py::arg("routing") = "auto",
py::arg("seed") = py::none(),
kIndexDoc
)
- // Private to the 0.8 compatibility layer in rabitqlib/__init__.py.
- .def(
- py::init([](size_t dim,
- size_t num_clusters,
- size_t nbits,
- const std::string& metric,
- const std::string& initializer,
- size_t max_elements) {
- return IvfIndex::with_point_count(
- dim, max_elements, num_clusters, nbits, metric, initializer
- );
- }),
- py::arg("dim"),
- py::arg("num_clusters"),
- py::kw_only(),
- py::arg("nbits"),
- py::arg("metric"),
- py::arg("initializer"),
- py::arg("_max_elements")
- )
.def(
"train",
&IvfIndex::train,
@@ -642,15 +512,6 @@ The index counts as trained afterwards. Replacing centroids is allowed
while the index stores no vectors and raises RuntimeError afterwards. A
failed call leaves the index unchanged.)doc"
)
- .def(
- "_build",
- &IvfIndex::build,
- py::arg("data"),
- py::arg("centroids"),
- py::arg("cluster_ids"),
- py::arg("num_threads"),
- py::arg("fast_quantization")
- )
.def(
"add",
&IvfIndex::add,
@@ -662,8 +523,8 @@ failed call leaves the index unchanged.)doc"
kAddDoc
)
.def(
- "reserve",
- &IvfIndex::reserve,
+ "reserve_cluster",
+ &IvfIndex::reserve_cluster,
py::arg("cluster_id"),
py::arg("num_points"),
R"doc(Preallocate storage for a cluster.
@@ -673,7 +534,8 @@ Parameters
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
-----
@@ -706,6 +568,7 @@ Removal does not reclaim storage and cannot be undone.)doc"
py::arg("queries"),
py::arg("k"),
py::arg("nprobe") = py::none(),
+ py::kw_only(),
py::arg("high_accuracy") = py::none(),
py::arg("num_threads") = py::none(),
R"doc(Search a batch of query vectors.
@@ -719,14 +582,15 @@ 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.
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, at least 1 and capped at num_clusters. None
+ (default) selects num_clusters / 16, rounded to the nearest integer and
+ at least 1.
high_accuracy : bool, optional
- Enable HACC. None (default) selects it for 4-9 bits and standard
- FastScan otherwise. Raw storage uses standard FastScan.
+ Keyword-only. 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. Worker count. None (default) selects 1; 0 selects the
+ available CPU count, capped by OMP_NUM_THREADS.
Returns
-------
@@ -793,11 +657,6 @@ accompanying ``.hnsw`` file.)doc"
"Return the number of live, searchable points."
)
.def_property_readonly("dim", &IvfIndex::dim, R"doc(Original vector dimension.)doc")
- .def_property_readonly(
- "max_elements",
- &IvfIndex::max_elements,
- R"doc(Logical capacity: stored points, or the build row count of a 0.7-form index before build.)doc"
- )
.def_property_readonly(
"num_points",
&IvfIndex::num_points,
@@ -819,12 +678,12 @@ accompanying ``.hnsw`` file.)doc"
.def_property_readonly(
"is_trained",
&IvfIndex::is_trained,
- R"doc(Whether centroids are set, by train, set_centroids, the first add, build or load.)doc"
+ R"doc(Whether centroids are set, by train, set_centroids, the first add or load.)doc"
)
.def_property_readonly(
"seed",
&IvfIndex::seed,
- R"doc(Rotation seed, or None for an index loaded from a file from a release up to 0.8 or created in the 0.7 form.)doc"
+ R"doc(Rotation seed, or None for an index loaded from a file from a release up to 0.8.)doc"
)
.def_property(
"cp",
@@ -839,8 +698,8 @@ accompanying ``.hnsw`` file.)doc"
R"doc(Canonical metric name: 'l2', 'ip' or 'cosine'.)doc"
)
.def_property_readonly(
- "initializer",
- &IvfIndex::initializer,
- R"doc(Resolved centroid routing strategy.)doc"
+ "routing",
+ &IvfIndex::routing,
+ R"doc(Resolved centroid routing strategy, never 'auto'.)doc"
);
}
diff --git a/python_bindings/kmeans_bindings.cpp b/python_bindings/kmeans_bindings.cpp
index 16574b7d..79cca9b2 100644
--- a/python_bindings/kmeans_bindings.cpp
+++ b/python_bindings/kmeans_bindings.cpp
@@ -110,10 +110,28 @@ void bind_training_parameters(py::class_& binding) {
&Parameters::num_threads,
R"doc(Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0.)doc"
)
- .def_readwrite(
+ .def_property(
"final_assignment",
- &Parameters::final_assignment,
- R"doc(Approximate uses the training assignment method; Exact uses exhaustive assignment against final centroids. Default is FinalAssignmentMode.Approximate.)doc"
+ [](const Parameters& parameters) {
+ return std::string(
+ parameters.final_assignment == clustering::FinalAssignmentMode::Exact
+ ? "exact"
+ : "approximate"
+ );
+ },
+ [](Parameters& parameters, const std::string& value) {
+ if (value == "approximate") {
+ parameters.final_assignment =
+ clustering::FinalAssignmentMode::Approximate;
+ } else if (value == "exact") {
+ parameters.final_assignment = clustering::FinalAssignmentMode::Exact;
+ } else {
+ throw std::invalid_argument(
+ "final_assignment must be 'approximate' or 'exact'"
+ );
+ }
+ },
+ R"doc('approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'.)doc"
);
}
@@ -165,23 +183,12 @@ void bind_clustering(py::module_& m, const char* native_name, const char* public
void register_kmeans(py::module_& m) {
using namespace rabitqlib::python_bindings;
- using rabitqlib::qgkmeans::FinalAssignmentMode;
+ using rabitqlib::clustering::KMeansIterationStats;
using rabitqlib::qgkmeans::QGKMeans;
- using rabitqlib::qgkmeans::QGKMeansIterationStats;
using rabitqlib::qgkmeans::QGKMeansParameters;
using rabitqlib::rabitqkmeans::RaBitQKMeans;
using rabitqlib::rabitqkmeans::RaBitQKMeansParameters;
- py::enum_(
- m, "FinalAssignmentMode", R"doc(Final centroid assignment policy.
-
-Approximate uses the selected clustering algorithm. SymphonyQG is a
-compatibility alias for Approximate. Exact performs exhaustive assignment.)doc"
- )
- .value("Approximate", FinalAssignmentMode::Approximate)
- .value("SymphonyQG", FinalAssignmentMode::SymphonyQG)
- .value("Exact", FinalAssignmentMode::Exact);
-
py::class_ qg_parameters(
m, "QGKMeansParameters", R"doc(Mutable training settings for QGKMeans.
@@ -193,13 +200,13 @@ on QGKMeans.)doc"
bind_training_parameters(qg_parameters);
qg_parameters
.def_readwrite(
- "graph_degree",
- &QGKMeansParameters::graph_degree,
+ "max_degree",
+ &QGKMeansParameters::max_degree,
R"doc(Centroid graph degree; a positive multiple of 32. Default is 32.)doc"
)
.def_readwrite(
- "ef_build",
- &QGKMeansParameters::ef_build,
+ "ef_construction",
+ &QGKMeansParameters::ef_construction,
R"doc(Positive centroid-graph construction search breadth. Default is 240.)doc"
)
.def_readwrite(
@@ -213,9 +220,9 @@ on QGKMeans.)doc"
R"doc(Positive number of graph-building passes after initialization. Default is 1.)doc"
)
.def_readwrite(
- "quantization_bits",
- &QGKMeansParameters::quantization_bits,
- R"doc(Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is 0.)doc"
+ "nbits",
+ &QGKMeansParameters::nbits,
+ R"doc(Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is 32.)doc"
);
py::class_ flat_parameters(
@@ -228,32 +235,31 @@ on RaBitQKMeans.)doc"
);
bind_training_parameters(flat_parameters);
- py::class_(
+ py::class_(
m,
- "QGKMeansIterationStats",
+ "KMeansIterationStats",
R"doc(Read-only statistics for one completed clustering iteration.)doc"
)
.def_readonly(
"iteration",
- &QGKMeansIterationStats::iteration,
+ &KMeansIterationStats::iteration,
R"doc(Iteration number, starting at 1.)doc"
)
.def_readonly(
"obj",
- &QGKMeansIterationStats::obj,
+ &KMeansIterationStats::obj,
R"doc(Objective measured before the centroid update.)doc"
)
.def_readonly(
"shift",
- &QGKMeansIterationStats::shift,
+ &KMeansIterationStats::shift,
R"doc(Total squared centroid displacement during the update.)doc"
)
.def_readonly(
"nsplit",
- &QGKMeansIterationStats::nsplit,
+ &KMeansIterationStats::nsplit,
R"doc(Number of empty centroids repaired by splitting.)doc"
);
- m.attr("RaBitQKMeansIterationStats") = m.attr("QGKMeansIterationStats");
bind_clustering(m, "_QGKMeans", "QGKMeans");
bind_clustering(
diff --git a/python_bindings/symqg_bindings.cpp b/python_bindings/symqg_bindings.cpp
index c72e0a83..41bd368f 100644
--- a/python_bindings/symqg_bindings.cpp
+++ b/python_bindings/symqg_bindings.cpp
@@ -58,11 +58,10 @@ class SymqgIndex {
}
quantization_bits_ = nbits == 32 ? 0 : nbits;
check_construction(ef_construction, init);
- seed_given_ = !seed.is_none();
- seed_ = seed_given_ ? static_cast(
- checked_seed(seed, std::numeric_limits::max())
- )
- : random_seed();
+ seed_ = seed.is_none() ? std::random_device{}()
+ : static_cast(checked_seed(
+ seed, std::numeric_limits::max()
+ ));
}
// SymphonyQG learns nothing before add: train only checks x as add would, so
@@ -85,8 +84,7 @@ class SymqgIndex {
"and add all vectors at once"
);
}
- // Only a loaded index lacks these settings, and it is already built.
- build_graph(data, *ef_construction_, num_threads.value_or(0), *init_, *seed_);
+ build_graph(data, num_threads.value_or(0));
// Point IDs are the row numbers of data.
const size_t rows = index_->num_points();
auto ids = py::array_t(static_cast(rows));
@@ -94,34 +92,20 @@ class SymqgIndex {
return ids;
}
- // Deprecated: the 0.7 build, which replaces any existing graph. Without a
- // user seed, each build draws a new one, as 0.7 did.
- void build(
- py::handle data, size_t ef_construction, size_t num_threads, const std::string& init
- ) {
- const auto operation = access_.write();
- check_construction(ef_construction, init);
- const uint32_t seed = seed_given_ ? *seed_ : random_seed();
- build_graph(data, ef_construction, num_threads, init, seed);
- ef_construction_ = ef_construction;
- init_ = init;
- seed_ = seed;
- }
-
py::tuple search(
py::handle queries,
size_t k,
- std::optional ef,
+ std::optional ef_search,
std::optional num_threads
) {
const auto operation = access_.read();
auto query_array = ensure_2d_array(queries, "queries");
check_built("search");
- check_k(k);
- // As in HnswIndex: no or zero ef selects max(k, 64), and ef is at least k.
- const size_t ef_search =
- std::max(ef.value_or(0) == 0 ? std::max(k, 64) : *ef, k);
ensure_dimension(query_array, dim_, "query dimension does not match index dim");
+ check_k(k);
+ check_ef_search(ef_search);
+ // As in HnswIndex, None selects max(k, 64); a smaller breadth is raised to k.
+ const size_t search_breadth = std::max(ef_search.value_or(64), k);
const size_t num_queries = static_cast(query_array.shape(0));
auto output = unfilled_search_results(num_queries, k);
@@ -136,7 +120,7 @@ class SymqgIndex {
static_cast(k),
ids_data,
distances_data,
- ef_search,
+ search_breadth,
num_threads.value_or(1)
);
}
@@ -207,10 +191,6 @@ class SymqgIndex {
const auto operation = access_.read();
return built() ? index_->num_stored_points() : 0;
}
- [[nodiscard]] size_t max_elements() const {
- const auto operation = access_.read();
- return built() ? index_->max_elements() : 0;
- }
[[nodiscard]] std::string metric() const {
const auto operation = access_.read();
return metric_to_string(metric_type_);
@@ -219,10 +199,6 @@ class SymqgIndex {
const auto operation = access_.read();
return nbits();
}
- [[nodiscard]] size_t quantization_bits() const {
- const auto operation = access_.read();
- return quantization_bits_;
- }
[[nodiscard]] std::optional seed() const {
const auto operation = access_.read();
return seed_;
@@ -233,8 +209,6 @@ class SymqgIndex {
SymqgIndex() = default;
- static uint32_t random_seed() { return std::random_device{}(); }
-
static void check_max_degree(size_t max_degree) {
if (max_degree == 0 || max_degree % fastscan::kBatchSize != 0) {
throw std::invalid_argument("max_degree must be a positive multiple of 32");
@@ -262,15 +236,11 @@ class SymqgIndex {
}
}
- // Build a new graph from data; a failure keeps the previous one. Requires the
- // write guard.
- void build_graph(
- py::handle data,
- size_t ef_construction,
- size_t num_threads,
- const std::string& init,
- uint32_t seed
- ) {
+ // Build the graph from data with the constructor's settings; a failure leaves
+ // the index without one. Only a loaded index lacks those settings, and it
+ // already has a graph. Requires the write guard.
+ void build_graph(py::handle data, size_t num_threads) {
+ const uint32_t seed = *seed_;
auto data_array = ensure_2d_array(data, "data");
ensure_dimension(data_array, dim_, "data dimension does not match index dim");
@@ -285,14 +255,14 @@ class SymqgIndex {
seed
);
- const auto initialization = init == "pipnn" ? symqg::QGInitialization::PiPNN
- : symqg::QGInitialization::Random;
+ const auto initialization = *init_ == "pipnn" ? symqg::QGInitialization::PiPNN
+ : symqg::QGInitialization::Random;
const auto* data_ptr = data_array.data();
{
py::gil_scoped_release release;
symqg::QGBuilder builder(
*index,
- static_cast(ef_construction),
+ static_cast(*ef_construction_),
data_ptr,
num_threads,
initialization,
@@ -317,7 +287,6 @@ class SymqgIndex {
std::optional ef_construction_ = kDefaultEfConstruction;
std::optional init_ = "pipnn";
std::optional seed_; // Unknown for files from releases up to 0.8.
- bool seed_given_ = false; // The user chose the seed.
mutable IndexAccess access_;
std::unique_ptr> index_;
};
@@ -362,9 +331,6 @@ vectors before searching or saving. Concurrent reads are supported; an
overlapping mutation raises RuntimeError.
Data and queries must be finite float32 values within the index coordinate
range; other values raise ValueError.
-The 0.7 forms SymqgIndex(dim, max_degree, metric, quantization_bits),
-quantization_bits=, build() and search_batch() still work in 0.8, raise
-DeprecationWarning, and will be removed in 0.9.
Examples
--------
@@ -387,12 +353,12 @@ queries : array_like of float, shape (n_queries, dim)
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, at least 1. None (default) selects max(k, 64); smaller
+ values are raised to k.
num_threads : int, optional
- Worker count. None (default) selects 1; 0 selects the available CPU
- count, capped by OMP_NUM_THREADS.
+ Keyword-only. Worker count. None (default) selects 1; 0 selects the
+ available CPU count, capped by OMP_NUM_THREADS.
Returns
-------
@@ -481,20 +447,13 @@ extended: a second call raises RuntimeError, so add every vector in one
call, or create a new index to rebuild. Point IDs are the row numbers of
data. Input arrays need not be retained after this synchronous call.)doc"
)
- .def(
- "_build",
- &SymqgIndex::build,
- py::arg("data"),
- py::arg("ef_construction"),
- py::arg("num_threads"),
- py::arg("init")
- )
.def(
"search",
&SymqgIndex::search,
py::arg("queries"),
py::arg("k"),
- py::arg("ef") = py::none(),
+ py::arg("ef_search") = py::none(),
+ py::kw_only(),
py::arg("num_threads") = py::none(),
kSearchDoc
)
@@ -568,9 +527,6 @@ index : SymqgIndex
&SymqgIndex::num_stored_points,
R"doc(Number of stored points, including removed points.)doc"
)
- .def_property_readonly(
- "max_elements", &SymqgIndex::max_elements, R"doc(Current storage capacity.)doc"
- )
.def_property_readonly(
"is_trained",
[](const SymqgIndex&) { return true; },
@@ -586,7 +542,6 @@ index : SymqgIndex
&SymqgIndex::nbits_property,
R"doc(Storage bits: 32 for raw float32, or 4 or 8 for RaBitQ.)doc"
)
- .def_property_readonly("_quantization_bits", &SymqgIndex::quantization_bits)
.def_property_readonly(
"seed",
&SymqgIndex::seed,
diff --git a/sample/cpp/qgkmeans.cpp b/sample/cpp/qgkmeans.cpp
index fd84b5e3..473e4ffe 100644
--- a/sample/cpp/qgkmeans.cpp
+++ b/sample/cpp/qgkmeans.cpp
@@ -26,10 +26,10 @@ int run_demo() {
rabitqlib::qgkmeans::QGKMeansParameters parameters;
parameters.niter = 5;
- parameters.graph_degree = 32;
- parameters.ef_build = 64;
+ parameters.max_degree = 32;
+ parameters.ef_construction = 64;
parameters.ef_search = 32;
- parameters.quantization_bits = 8;
+ parameters.nbits = 8;
parameters.verbose = true;
rabitqlib::qgkmeans::QGKMeans clustering(kDimension, kNumClusters, parameters);
diff --git a/sample/python/README.md b/sample/python/README.md
index 20513d56..0c12a1e6 100644
--- a/sample/python/README.md
+++ b/sample/python/README.md
@@ -59,8 +59,9 @@ python sample/python/hnsw_rabitq_indexing.py --total-bits 5 --degree 16 \
It also accepts `--clusters` with a file from `kmeans_clustering.py`; use
`--method rabitq` there for a small cluster count. With more than one thread
-(`--num-threads`), the graph links vectors in a nondeterministic order; pass
-`--num-threads 1` for a reproducible index.
+(`--num-threads`), the graph links vectors in a nondeterministic order. The script
+draws a new seed on every run, so two runs give different indexes even with
+`--num-threads 1`; pass `seed=` to `HnswIndex` in your own code for a reproducible index.
Query with `hnsw_rabitq_querying.py`. SymphonyQG builds directly from vectors;
use `symqg_indexing.py` and `symqg_querying.py` without a clustering stage.
diff --git a/tests/consumer/main.cpp b/tests/consumer/main.cpp
index 13b8696d..8758be51 100644
--- a/tests/consumer/main.cpp
+++ b/tests/consumer/main.cpp
@@ -82,7 +82,7 @@ int main() {
rabitqlib::qgkmeans::QGKMeansParameters graph_parameters;
graph_parameters.niter = 2;
graph_parameters.num_threads = 2;
- graph_parameters.ef_build = 33;
+ graph_parameters.ef_construction = 33;
graph_parameters.ef_search = 33;
graph_parameters.final_assignment = rabitqlib::clustering::FinalAssignmentMode::Exact;
rabitqlib::qgkmeans::QGKMeans graph(kDimension, 33, graph_parameters);
diff --git a/tests/python/test_array_alignment.py b/tests/python/test_array_alignment.py
index 968df5bd..2a4e40cd 100644
--- a/tests/python/test_array_alignment.py
+++ b/tests/python/test_array_alignment.py
@@ -63,7 +63,7 @@ def fill(index, vectors, centers):
if kind == "ivf":
parameters = {"nprobe": 2}
else:
- parameters = {"ef": 65}
+ parameters = {"ef_search": 65}
# Explicit seeds and one build thread make every index reproducible.
reference = make_index()
diff --git a/tests/python/test_compat_08.py b/tests/python/test_compat_08.py
deleted file mode 100644
index b677431c..00000000
--- a/tests/python/test_compat_08.py
+++ /dev/null
@@ -1,476 +0,0 @@
-"""The 0.7 call forms the 0.8 compatibility layer keeps; removed in 0.9."""
-
-import inspect
-import warnings
-
-import numpy as np
-import pytest
-from conftest import DIM, N_CLUSTERS, N_VECTORS
-from rabitqlib import HnswIndex, IvfIndex, SymqgIndex
-
-
-def single_deprecation(call):
- """Run call and return its result and its one DeprecationWarning."""
- 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__
- assert "python_migration" in str(caught[0].message)
- return result, str(caught[0].message)
-
-
-def quietly(call):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", DeprecationWarning)
- return call()
-
-
-@pytest.mark.parametrize(
- "make",
- [
- lambda: IvfIndex(DIM, N_VECTORS, 4, 4),
- lambda: IvfIndex(DIM, N_VECTORS, 4, nbits=4),
- lambda: IvfIndex(DIM, N_VECTORS, num_clusters=4, nbits=4),
- lambda: IvfIndex(
- dim=DIM, max_elements=N_VECTORS, num_clusters=4, nbits=4, metric="ip"
- ),
- ],
-)
-def test_ivf_point_count_forms(make, base_data, clusters):
- index, message = single_deprecation(make)
- assert message.startswith(
- "IvfIndex(dim, max_elements, num_clusters, nbits, ...) is deprecated"
- )
- assert index.max_elements == N_VECTORS
- assert index.num_clusters == 4
- assert index.seed is None
- assert not index.is_trained
-
-
-@pytest.mark.parametrize(
- "make",
- [
- lambda: HnswIndex(DIM, N_VECTORS),
- lambda: HnswIndex(DIM, N_VECTORS, 8, 50, 4, "ip", 5),
- lambda: HnswIndex(dim=DIM, max_elements=N_VECTORS, M=8, nbits=4, random_seed=5),
- ],
-)
-def test_hnsw_max_elements_forms(make):
- index, message = single_deprecation(make)
- assert message.startswith("HnswIndex(dim, max_elements, ...) is deprecated")
- assert index.max_elements == N_VECTORS
-
-
-def test_old_forms_keep_old_defaults():
- hnsw = quietly(lambda: HnswIndex(DIM, N_VECTORS))
- assert hnsw.nbits == 8
- assert hnsw.seed == 100
- assert hnsw.num_clusters == 16
- build = inspect.signature(IvfIndex.build).parameters
- assert build["num_threads"].default == 1
- assert inspect.signature(HnswIndex.build).parameters["num_threads"].default == 1
-
-
-def test_random_seed_keyword():
- index, message = single_deprecation(lambda: HnswIndex(DIM, nbits=4, random_seed=7))
- assert message.startswith("HnswIndex(random_seed=...) is deprecated; use seed=")
- assert index.seed == 7
- with pytest.raises(
- TypeError, match="^HnswIndex\\(\\) got both seed and its old name random_seed$"
- ):
- HnswIndex(DIM, nbits=4, seed=1, random_seed=2)
-
-
-@pytest.mark.parametrize(
- "make,message",
- [
- # Mixing forms: the old form has no seed, and the new one no max_elements.
- (
- lambda: IvfIndex(DIM, N_VECTORS, 4, nbits=4, seed=1),
- "IvfIndex() got an unexpected keyword argument 'seed' (read as the 0.7 form",
- ),
- (
- lambda: IvfIndex(DIM, 4, nbits=4, max_elements=N_VECTORS),
- "IvfIndex() multiple values for argument 'max_elements' (read as the 0.7 form",
- ),
- (
- lambda: HnswIndex(DIM, max_elements=10, num_clusters=4),
- "HnswIndex() got an unexpected keyword argument 'num_clusters' (read as the 0.7 form",
- ),
- (
- lambda: HnswIndex(DIM, 10, seed=4),
- "HnswIndex() got an unexpected keyword argument 'seed' (read as the 0.7 form",
- ),
- ],
-)
-def test_mixed_forms_raise_instead_of_guessing(make, message):
- with warnings.catch_warnings():
- warnings.simplefilter("error", DeprecationWarning)
- with pytest.raises(TypeError) as error:
- make()
- assert str(error.value).startswith(message)
-
-
-@pytest.mark.parametrize("kind", ["ivf", "hnsw"])
-def test_build_and_is_built(kind, base_data, clusters):
- centroids, cluster_ids = clusters
- if kind == "ivf":
- index = quietly(lambda: IvfIndex(DIM, N_VECTORS, len(centroids), 4))
- else:
- index = quietly(lambda: HnswIndex(DIM, N_VECTORS, nbits=4))
- built, _ = single_deprecation(lambda: index.is_built)
- assert built is False
- _, message = single_deprecation(
- lambda: index.build(base_data, centroids, cluster_ids)
- )
- assert message.startswith(f"{type(index).__name__}.build() is deprecated")
- assert index.is_trained
- assert len(index) == N_VECTORS
- built, message = single_deprecation(lambda: index.is_built)
- assert built is True
- assert message.startswith(f"{type(index).__name__}.is_built is deprecated")
-
-
-def test_build_on_new_form_indexes(base_data, clusters, tmp_path):
- centroids, cluster_ids = clusters
- ivf = IvfIndex(DIM, len(centroids), nbits=4, seed=3)
- single_deprecation(lambda: ivf.build(base_data, centroids, cluster_ids))
- reference = IvfIndex(DIM, len(centroids), nbits=4, seed=3)
- reference.set_centroids(centroids)
- reference.add(base_data, cluster_ids=cluster_ids, num_threads=1)
- ivf.save(tmp_path / "a.index")
- reference.save(tmp_path / "b.index")
- assert (tmp_path / "a.index").read_bytes() == (tmp_path / "b.index").read_bytes()
-
- # HNSW build takes any number of centroids, as in 0.7.
- hnsw = HnswIndex(DIM, nbits=4)
- assert hnsw.num_clusters == 16
- single_deprecation(lambda: hnsw.build(base_data, centroids, cluster_ids))
- assert hnsw.num_clusters == len(centroids)
- assert hnsw.max_elements == N_VECTORS
-
-
-@pytest.mark.parametrize("kind", ["ivf", "hnsw"])
-def test_positional_add_options(kind, base_data):
- index = (
- IvfIndex(DIM, 2, nbits=4)
- if kind == "ivf"
- else HnswIndex(DIM, nbits=4, num_clusters=2)
- )
- index.set_centroids(base_data[:2])
- labels = np.zeros(10, dtype=np.uint32)
- ids, message = single_deprecation(lambda: index.add(base_data[:10], labels, 1))
- assert message.startswith(
- f"passing cluster_ids, num_threads to {type(index).__name__}.add() by position is deprecated"
- )
- np.testing.assert_array_equal(ids, np.arange(10))
- with pytest.raises(
- TypeError, match="got multiple values for argument 'cluster_ids'"
- ):
- quietly(lambda: index.add(base_data[:10], labels, cluster_ids=labels))
- with pytest.raises(
- TypeError, match=r"takes at most 4 positional arguments \(5 given\)"
- ):
- index.add(base_data[:10], labels, 1, False, 3)
- assert len(index) == 10
-
-
-def test_failed_build_leaves_a_new_form_index_unchanged(base_data, clusters):
- centroids, cluster_ids = clusters
- bad = base_data.copy()
- bad[7, 3] = np.nan
- ivf = IvfIndex(DIM, len(centroids), nbits=4)
- hnsw = HnswIndex(DIM, nbits=4)
- for index in (ivf, hnsw):
- with pytest.raises(ValueError, match="must contain only finite values"):
- quietly(lambda: index.build(bad, centroids, cluster_ids))
- assert not index.is_trained
- assert len(index) == 0
- assert hnsw.max_elements == 1
- bad_centroids = centroids.copy()
- bad_centroids[0, 0] = np.inf
- with pytest.raises(ValueError, match="must contain only finite values"):
- quietly(lambda: hnsw.build(base_data, bad_centroids, cluster_ids))
- assert hnsw.max_elements == 1
-
-
-def test_hnsw_build_on_a_trained_index_replaces_centroids(
- base_data, clusters, tmp_path
-):
- centroids, cluster_ids = clusters
- trained = HnswIndex(DIM, nbits=4, num_clusters=4)
- trained.train(base_data)
- single_deprecation(lambda: trained.build(base_data, centroids, cluster_ids))
- assert trained.num_clusters == len(centroids)
- # The same index the 0.7 form builds: both link with the exact vectors.
- built = quietly(lambda: HnswIndex(DIM, N_VECTORS, nbits=4))
- quietly(lambda: built.build(base_data, centroids, cluster_ids))
- trained.save(tmp_path / "a.index")
- built.save(tmp_path / "b.index")
- assert (tmp_path / "a.index").read_bytes() == (tmp_path / "b.index").read_bytes()
-
-
-@pytest.mark.parametrize(
- "make,bits",
- [
- (lambda: SymqgIndex(DIM, 32), 0),
- (lambda: SymqgIndex(DIM, 32, "ip", 4), 4),
- (lambda: SymqgIndex(DIM, 32, quantization_bits=8), 8),
- ],
-)
-def test_symqg_positional_form(make, bits):
- index, message = single_deprecation(make)
- assert message.startswith(
- "SymqgIndex(dim, max_degree, metric, quantization_bits) is deprecated"
- )
- assert index.nbits == (32 if bits == 0 else bits)
- assert index.max_degree == 32
- assert (index.ef_construction, index.init) == (200, "pipnn")
-
-
-@pytest.mark.parametrize("bits,nbits", [(0, 32), (4, 4), (8, 8)])
-def test_symqg_quantization_bits_keyword(bits, nbits, base_data, tmp_path):
- index, message = single_deprecation(
- lambda: SymqgIndex(dim=DIM, max_degree=32, quantization_bits=bits, seed=4)
- )
- assert message.startswith("SymqgIndex(quantization_bits=...) is deprecated")
- reference = SymqgIndex(DIM, nbits=nbits, seed=4)
- for graph in (index, reference):
- graph.add(base_data, num_threads=1)
- index.save(tmp_path / "a.index")
- reference.save(tmp_path / "b.index")
- assert (tmp_path / "a.index").read_bytes() == (tmp_path / "b.index").read_bytes()
- value, message = single_deprecation(lambda: index.quantization_bits)
- assert value == bits
- assert message.startswith("SymqgIndex.quantization_bits is deprecated")
-
-
-@pytest.mark.parametrize(
- "make,error,message",
- [
- (
- lambda: SymqgIndex(DIM, nbits=4, quantization_bits=4),
- TypeError,
- "^SymqgIndex\\(\\) got both nbits and its old form quantization_bits$",
- ),
- (
- lambda: SymqgIndex(DIM, quantization_bits=2),
- ValueError,
- "^quantization_bits must be 0, 4, or 8$",
- ),
- (
- lambda: SymqgIndex(DIM, 32, nbits=4),
- TypeError,
- "got an unexpected keyword argument 'nbits' \\(read as the 0.7 form",
- ),
- (
- lambda: SymqgIndex(DIM, 32, "l2", 3),
- ValueError,
- "^quantization_bits must be 0, 4, or 8$",
- ),
- ],
-)
-def test_symqg_mixed_or_invalid_old_forms(make, error, message):
- with pytest.raises(error, match=message):
- quietly(make)
-
-
-def test_symqg_build_search_batch_and_is_built(base_data, query_data):
- index = quietly(lambda: SymqgIndex(DIM, 32))
- built, _ = single_deprecation(lambda: index.is_built)
- assert built is False
- _, message = single_deprecation(lambda: index.build(base_data, 50))
- assert message.startswith("SymqgIndex.build() is deprecated")
- assert len(index) == N_VECTORS
- built, _ = single_deprecation(lambda: index.is_built)
- assert built is True
- batch, message = single_deprecation(lambda: index.search_batch(query_data, 5, 40))
- assert message.startswith("SymqgIndex.search_batch() is deprecated; use search()")
- expected = index.search(query_data, 5, 40)
- np.testing.assert_array_equal(batch[0], expected[0])
- np.testing.assert_array_equal(batch[1], expected[1])
- # As in 0.7, build replaces the graph, even after add or another build.
- quietly(lambda: index.build(base_data[:100], 50, 1, "random"))
- assert len(index) == 100
- added = SymqgIndex(DIM)
- added.add(base_data[:80])
- quietly(lambda: added.build(base_data, 50))
- assert len(added) == N_VECTORS
-
-
-def test_symqg_build_draws_a_new_seed_unless_one_was_given(base_data):
- unseeded = quietly(lambda: SymqgIndex(DIM, 32))
- seeds = set()
- for init in ("pipnn", "random"):
- quietly(lambda init=init: unseeded.build(base_data, 50, 1, init))
- seeds.add(unseeded.seed)
- # The settings of the current graph.
- assert (unseeded.ef_construction, unseeded.init) == (50, init)
- assert len(seeds) == 2
- seeded = SymqgIndex(DIM, seed=3)
- for _ in range(2):
- quietly(lambda: seeded.build(base_data, 50))
- assert seeded.seed == 3
-
-
-# Moved from test_input_boundaries.py (#214): build's row count has no 0.8 form.
-@pytest.mark.parametrize("index_kind,rows", [("ivf", 79), ("hnsw", 0)])
-def test_build_row_count_diagnostics(index_kind, rows):
- if index_kind == "ivf":
- index = quietly(lambda: IvfIndex(64, 80, 1, 4))
- expected = "number of data rows must match index max_elements; expected 80, got shape (79, 64)"
- else:
- # HNSW capacity grows, so only an empty build is rejected.
- index = quietly(lambda: HnswIndex(64, 80))
- expected = "number of data rows must be at least 1; got shape (0, 64)"
- with pytest.raises(ValueError) as error:
- quietly(
- lambda: index.build(
- np.zeros((rows, 64)),
- np.zeros((1, 64)),
- np.zeros(rows, dtype=np.uint32),
- )
- )
- assert str(error.value) == expected
-
-
-# Moved from test_symqg.py (#214): build replacing a graph has no 0.8 form.
-@pytest.mark.parametrize("bits", [0, 4, 8])
-@pytest.mark.parametrize("metric", ["l2", "ip"])
-@pytest.mark.parametrize("replacement_points", [0, 32])
-def test_symqg_failed_rebuild_preserves_index(
- base_data, query_data, tmp_path, bits, metric, replacement_points
-):
- data = base_data[:40]
- queries = query_data[:3]
- index = quietly(
- lambda: SymqgIndex(DIM, max_degree=32, metric=metric, quantization_bits=bits)
- )
- quietly(lambda: index.build(data, ef_construction=50))
- expected_ids, expected_distances = index.search(queries, k=5, ef=50)
- before_path = tmp_path / "before.index"
- index.save(str(before_path))
-
- with pytest.raises(
- ValueError,
- match="QuantizedGraph degree bound must be smaller than the number of points",
- ):
- quietly(lambda: index.build(data[:replacement_points], ef_construction=50))
-
- assert quietly(lambda: index.is_built)
- assert index.num_points == len(data)
- assert index.dim == DIM
- assert index.max_degree == 32
- assert index.metric == metric
- assert quietly(lambda: index.quantization_bits) == bits
- ids, distances = index.search(queries, k=5, ef=50)
- np.testing.assert_array_equal(ids, expected_ids)
- np.testing.assert_array_equal(distances, expected_distances)
-
- after_path = tmp_path / "after.index"
- index.save(str(after_path))
- assert after_path.read_bytes() == before_path.read_bytes()
- restored = SymqgIndex.load(str(after_path))
- assert restored.num_points == len(data)
- restored_ids, restored_distances = restored.search(queries, k=5, ef=50)
- np.testing.assert_array_equal(restored_ids, expected_ids)
- np.testing.assert_array_equal(restored_distances, expected_distances)
-
-
-# Moved from test_symqg.py (#214).
-@pytest.mark.parametrize("bits", [0, 4, 8])
-def test_symqg_successful_rebuild_replaces_index(base_data, tmp_path, bits):
- # Seeded, and build uses one thread, so every self-query below must succeed.
- index = quietly(
- lambda: SymqgIndex(DIM, max_degree=32, quantization_bits=bits, seed=42)
- )
- quietly(lambda: index.build(base_data[:40], ef_construction=50))
- replacement = base_data[40:88] + 10
- quietly(lambda: index.build(replacement, ef_construction=50))
-
- assert quietly(lambda: index.is_built)
- assert index.num_points == len(replacement)
- assert quietly(lambda: index.quantization_bits) == bits
- ids, distances = index.search(replacement[:3], k=1, ef=50)
- np.testing.assert_array_equal(ids[:, 0], np.arange(3))
-
- path = str(tmp_path / "rebuilt.index")
- index.save(path)
- restored = SymqgIndex.load(path)
- assert restored.num_points == len(replacement)
- restored_ids, restored_distances = restored.search(replacement[:3], k=1, ef=50)
- np.testing.assert_array_equal(restored_ids, ids)
- np.testing.assert_array_equal(restored_distances, distances)
-
-
-# Moved from test_symqg.py (#214).
-def test_symqg_build_defaults_to_pipnn():
- assert inspect.signature(SymqgIndex.build).parameters["init"].default == "pipnn"
-
-
-# Moved from test_hnsw.py (#214): build on a built index has no 0.8 form.
-@pytest.mark.parametrize("reload", [False, True])
-def test_hnsw_rejected_rebuild_preserves_index(base_data, clusters, tmp_path, reload):
- idx = quietly(lambda: HnswIndex(DIM, N_VECTORS, M=8, ef_construction=50, nbits=4))
- centroids, cluster_ids = clusters
- quietly(lambda: idx.build(base_data, centroids, cluster_ids))
- if reload:
- path = str(tmp_path / "hnsw.index")
- idx.save(path)
- idx = HnswIndex.load(path)
- before = idx.search(base_data[:10], k=3, ef=50)
- with pytest.raises(
- RuntimeError, match="^HNSW index is already trained, constructed or loaded$"
- ):
- quietly(
- lambda: idx.build(
- base_data, centroids[:1], np.zeros(N_VECTORS, dtype=np.uint32)
- )
- )
- assert quietly(lambda: idx.is_built)
- assert idx.num_clusters == N_CLUSTERS
- after = idx.search(base_data[:10], k=3, ef=50)
- for actual, expected in zip(after, before, strict=True):
- np.testing.assert_array_equal(actual, expected)
-
-
-# Moved from test_hnsw.py (#214): the 0.8 constructor takes no max_elements.
-def test_hnsw_zero_capacity_raises():
- with pytest.raises(
- ValueError, match="^HNSW max_elements must be greater than zero$"
- ):
- quietly(lambda: HnswIndex(max_elements=0, dim=64))
-
-
-# Moved from test_ivf.py (#214): build on a loaded index rebuilds it, which has no
-# 0.8 form. C++ IvfConstructionTest covers the same encoding.
-@pytest.mark.parametrize("bits", [1, 4, 32])
-@pytest.mark.parametrize("metric", ["l2", "ip"])
-def test_ivf_rebuild_matches_incremental_encoding_with_empty_clusters(
- tmp_path, bits, metric
-):
- rng = np.random.default_rng(731)
- data = rng.standard_normal((130, 65), dtype=np.float32)
- centers = rng.standard_normal((4, 65), dtype=np.float32)
- labels = np.full(130, 3, dtype=np.uint32)
- labels[0] = 1
- labels[1:33] = 2
- incremental = quietly(lambda: IvfIndex(65, 1, 4, nbits=bits, metric=metric))
- quietly(lambda: incremental.build(data[:1], centers, labels[:1], num_threads=1))
- incremental.add(data[1:], cluster_ids=labels[1:], num_threads=1)
- path = tmp_path / "incremental.index"
- incremental.save(str(path))
- expected_bytes = path.read_bytes()
- expected_ids, expected_distances = incremental.search(data[:3], k=10, nprobe=4)
- rebuilt = IvfIndex.load(str(path))
- for threads in (1, 4):
- quietly(lambda: rebuilt.build(data, centers, labels, num_threads=threads))
- rebuilt.save(str(path))
- assert path.read_bytes() == expected_bytes
- ids, distances = rebuilt.search(data[:3], k=10, nprobe=4)
- np.testing.assert_array_equal(ids, expected_ids)
- np.testing.assert_array_equal(distances, expected_distances)
diff --git a/tests/python/test_compat_09.py b/tests/python/test_compat_09.py
deleted file mode 100644
index d7f35596..00000000
--- a/tests/python/test_compat_09.py
+++ /dev/null
@@ -1,697 +0,0 @@
-"""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_concurrent_indexes.py b/tests/python/test_concurrent_indexes.py
index 787caf04..a5c53f28 100644
--- a/tests/python/test_concurrent_indexes.py
+++ b/tests/python/test_concurrent_indexes.py
@@ -31,7 +31,7 @@ def make_index(kind, bits=4, metric="l2", fill=True):
centroids = np.stack([data[labels == i].mean(axis=0) for i in range(5)])
if kind.startswith("ivf"):
initializer = kind.removeprefix("ivf_") if "_" in kind else "flat"
- index = IvfIndex(65, 5, nbits=bits, metric=metric, initializer=initializer)
+ index = IvfIndex(65, 5, nbits=bits, metric=metric, routing=initializer)
elif kind == "hnsw":
index = HnswIndex(
65,
@@ -58,7 +58,7 @@ def make_index(kind, bits=4, metric="l2", fill=True):
def parameters(kind, wide):
if kind.startswith("ivf"):
return {"nprobe": 5 if wide else 1, "high_accuracy": wide}
- return {"ef": 96 if wide else 5}
+ return {"ef_search": 96 if wide else 5}
@pytest.mark.parametrize("kind,bits", CASES)
@@ -127,7 +127,13 @@ def test_active_search_allows_reads_and_rejects_mutations(kind, tmp_path):
lambda: index.set_centroids(data[:5]),
]
if kind == "hnsw":
- mutations.append(lambda: index.resize(256))
+ # A reserve within the capacity changes nothing and is a read.
+ capacity = index.capacity
+ assert capacity < 256
+ for within in (0, capacity):
+ index.reserve(within)
+ assert index.capacity == capacity
+ mutations.append(lambda: index.reserve(256))
for mutate in mutations:
with pytest.raises(RuntimeError, match=f"^{BUSY}$"):
mutate()
@@ -136,7 +142,7 @@ def test_active_search_allows_reads_and_rejects_mutations(kind, tmp_path):
running.result(timeout=10)
# Failed conflicts must not leave the access state busy.
if kind == "hnsw":
- index.resize(256)
+ index.reserve(256)
elif kind == "qg":
# add takes write access before it rejects a second graph.
with pytest.raises(RuntimeError, match="does not support incremental addition"):
@@ -171,7 +177,7 @@ def test_active_mutation_rejects_reads_and_other_mutations(kind, tmp_path):
lambda: index.set_centroids(data[:5]),
]
if kind == "hnsw":
- calls.append(lambda: index.resize(256))
+ calls.append(lambda: index.reserve(256))
for call in calls:
with pytest.raises(RuntimeError, match=f"^{BUSY}$"):
call()
@@ -229,9 +235,9 @@ def test_native_exception_reacquires_gil_and_releases_access():
queries[1, 0] = np.nan
# The native search checks coordinates after releasing the GIL.
with pytest.raises(ValueError, match="must contain only finite values"):
- index.search(queries, 5, ef=64)
+ index.search(queries, 5, ef_search=64)
# add takes write access before it rejects a second graph.
with pytest.raises(RuntimeError, match="does not support incremental addition"):
index.add(data)
- ids, distances = index.search(data[:2], 5, ef=64)
+ ids, distances = index.search(data[:2], 5, ef_search=64)
assert ids.shape == distances.shape == (2, 5)
diff --git a/tests/python/test_cosine.py b/tests/python/test_cosine.py
index e0df141b..c731e313 100644
--- a/tests/python/test_cosine.py
+++ b/tests/python/test_cosine.py
@@ -78,7 +78,7 @@ def test_cosine_distance_of_a_zero_vector_is_one(kind, nbits, vectors):
index.add(data, num_threads=1)
_, distances = index.search(np.zeros((1, DIM), dtype=np.float32), 10)
np.testing.assert_array_equal(distances, np.ones((1, 10), dtype=np.float32))
- breadth = {"nprobe": 4} if kind == "ivf" else {"ef": COUNT}
+ breadth = {"nprobe": 4} if kind == "ivf" else {"ef_search": COUNT}
ids, distances = index.search(data[1:2], COUNT, **breadth)
assert distances[0, list(ids[0]).index(0)] == 1.0
diff --git a/tests/python/test_editor_support.py b/tests/python/test_editor_support.py
index 87b9830a..c00f751e 100644
--- a/tests/python/test_editor_support.py
+++ b/tests/python/test_editor_support.py
@@ -2,7 +2,6 @@
import ast
import doctest
-import inspect
import re
from pathlib import Path
@@ -54,9 +53,6 @@ def test_installed_public_declarations():
if isinstance(node, ast.AnnAssign):
assert isinstance(node.target, ast.Name)
members.add(node.target.id)
- if name == "FinalAssignmentMode":
- assert {"Approximate", "SymphonyQG", "Exact", "name", "value"} <= members
- continue
public = {key for key in vars(runtime) if not key.startswith("_")}
assert public <= members, (name, public - members)
for member in members - {"d", "k", "cp"}:
@@ -85,15 +81,6 @@ def test_editor_docs_match_runtime_help():
assert normalized(documentation) in normalized(actual), (name, node.name)
-def is_deprecated(node):
- return any(
- isinstance(d, ast.Call)
- and isinstance(d.func, ast.Name)
- and d.func.id == "deprecated"
- for d in node.decorator_list
- )
-
-
def stub_parameters(node):
"""Names, keyword-only names and literal defaults declared in the stub."""
args = node.args
@@ -114,14 +101,7 @@ def stub_parameters(node):
def runtime_parameters(member):
- """The same, from a Python replacement's signature or pybind11's first doc line."""
- if inspect.isfunction(member):
- parameters = inspect.signature(member).parameters.values()
- return (
- [p.name for p in parameters],
- [p.name for p in parameters if p.kind is inspect.Parameter.KEYWORD_ONLY],
- {p.name: p.default for p in parameters if p.default is not p.empty},
- )
+ """The same, from pybind11's first doc line."""
signature = member.__doc__.splitlines()[0]
names = re.findall(r"(?:\(|, )([A-Za-z_]\w*):", signature)
_, star, keyword_part = signature.partition(", *, ")
@@ -138,9 +118,7 @@ def test_native_signature_names_and_defaults(name):
cls = declarations()[name]
runtime = getattr(rabitqlib, name)
for node in cls.body:
- if not isinstance(node, ast.FunctionDef) or is_deprecated(node):
- # Deprecated overloads describe the 0.7 forms the compatibility layer
- # accepts; the runtime signature documents only the current form.
+ if not isinstance(node, ast.FunctionDef):
continue
if any(
(isinstance(d, ast.Name) and d.id == "property")
@@ -157,23 +135,13 @@ 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__"
- and not is_deprecated(n)
+ n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "__init__"
)
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)
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
+ assert getattr(instance.cp, arg.arg) == expected
for name in (
"centroids",
"assignments",
@@ -240,7 +208,7 @@ def test_documented_training_result_types(name):
assert isinstance(model.final_obj, float)
-def test_numpy_scalar_inputs_and_enum_members():
+def test_numpy_scalar_inputs():
import runpy
fixture = Path(__file__).parent / "typing" / "public_api.py"
diff --git a/tests/python/test_examples.py b/tests/python/test_examples.py
index b988eb28..8ee1849b 100644
--- a/tests/python/test_examples.py
+++ b/tests/python/test_examples.py
@@ -156,7 +156,6 @@ def search(prepared, *args, **kwargs):
return ids, np.zeros((2, 1))
index = SimpleNamespace(dim=2, num_clusters=2, search=search)
- index.search_batch = index.search
index_name = {"ivf": "IvfIndex", "hnsw": "HnswIndex", "symqg": "SymqgIndex"}[kind]
monkeypatch.setattr(module, index_name, SimpleNamespace(load=lambda path: index))
monkeypatch.setattr(module, "read_fvecs", lambda path: queries)
@@ -294,10 +293,8 @@ def test_separate_clustering_and_indexing(
@pytest.mark.parametrize("metric", ["l2", "ip"])
@pytest.mark.parametrize("kind", ["ivf", "hnsw"])
def test_indexing_trains_without_a_clustering_file(
- tmp_path, example_data, metric, kind, monkeypatch
+ tmp_path, example_data, metric, kind
):
- # The samples teach the 0.8 API, so they must not hit the compatibility layer.
- monkeypatch.setenv("PYTHONWARNINGS", "error::DeprecationWarning")
data_path, data = example_data
output = run_example(
f"{kind}_rabitq_indexing.py",
@@ -379,16 +376,12 @@ def test_clustering_default_requires_graph_compatible_cluster_count(monkeypatch)
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
- with pytest.raises(ValueError, match="more centroids than the graph degree"):
+ with pytest.raises(ValueError, match="more centroids than max_degree"):
module.cluster_data(np.zeros((65, 64), dtype=np.float32), 2, "l2", 1)
@pytest.mark.parametrize("metric", ["l2", "ip"])
-def test_symqg_examples_do_not_import_faiss(
- tmp_path, example_data, metric, monkeypatch
-):
- # The samples teach the 0.8 API, so they must not hit the compatibility layer.
- monkeypatch.setenv("PYTHONWARNINGS", "error::DeprecationWarning")
+def test_symqg_examples_do_not_import_faiss(tmp_path, example_data, metric):
data_path, data = example_data
run_example(
"symqg_indexing.py",
diff --git a/tests/python/test_historical_persistence.py b/tests/python/test_historical_persistence.py
index d6055841..5020207a 100644
--- a/tests/python/test_historical_persistence.py
+++ b/tests/python/test_historical_persistence.py
@@ -32,7 +32,7 @@ def reference(name):
if name.startswith("ivf")
else (HnswIndex if name.startswith("hnsw") else SymqgIndex)
)
- options = {"nprobe": 1} if name.startswith("ivf") else {"ef": 64}
+ options = {"nprobe": 1} if name.startswith("ivf") else {"ef_search": 64}
return path, cls, count, queries, ids, distances, options
@@ -67,7 +67,8 @@ def test_historical_load_search_and_resave(name, tmp_path):
assert index.metric == name.rsplit("_", 1)[1]
assert index.num_stored_points == count
assert index.num_points == count - (0 if cls is SymqgIndex else 1)
- assert index.max_elements >= index.num_stored_points
+ if cls is HnswIndex:
+ assert index.capacity >= index.num_stored_points
actual_ids, actual_distances = index.search(queries, 5, **options)
np.testing.assert_array_equal(actual_ids, ids)
# Distances may differ across AVX2, AVX-512, NEON, and compiler reductions.
@@ -108,10 +109,9 @@ def test_ivf_v1_header_uses_historical_payload_and_padding(name, tmp_path):
destination = tmp_path / "ivf-v1.index"
destination.write_bytes(header + payload)
index = cls.load(str(destination))
- assert index.initializer == "flat"
+ assert index.routing == "flat"
assert index.num_stored_points == count
assert index.num_points == count - 1
- assert index.max_elements == count
actual_ids, actual_distances = index.search(queries, 5, **options)
np.testing.assert_array_equal(actual_ids, ids)
np.testing.assert_allclose(actual_distances, distances, rtol=2e-4, atol=2e-4)
@@ -150,7 +150,7 @@ def test_v083_ivf_loads_and_migrates_without_loss(name, initializer, tmp_path):
distances = results[:, 1].astype(np.float32).reshape(nq, k)
index = IvfIndex.load(str(path))
- assert index.initializer == initializer
+ assert index.routing == initializer
assert index.num_stored_points == count
assert index.num_points == count - 1
destination = tmp_path / "migrated.index"
@@ -199,7 +199,7 @@ def test_v083_graphs_load_and_migrate(name, tmp_path):
assert index.num_stored_points == count
assert index.num_points == count - (1 if cls is HnswIndex else 0)
assert index.seed is None
- actual_ids, actual_distances = index.search(queries, k, ef=64)
+ actual_ids, actual_distances = index.search(queries, k, ef_search=64)
np.testing.assert_array_equal(actual_ids, ids)
np.testing.assert_allclose(actual_distances, distances, rtol=2e-4, atol=2e-4)
diff --git a/tests/python/test_hnsw.py b/tests/python/test_hnsw.py
index 73e1d1b9..4f7225a3 100644
--- a/tests/python/test_hnsw.py
+++ b/tests/python/test_hnsw.py
@@ -20,6 +20,8 @@ def _built(
data, centroids, cluster_ids, num_threads=1, fast_quantization=False, **options
):
"""An index over data with the given centroids; the first add links the points."""
+ # Seeded, so that a failure of a graph-dependent assertion can be replayed.
+ options.setdefault("seed", 100)
index = HnswIndex(data.shape[1], num_clusters=len(centroids), **options)
index.set_centroids(centroids)
index.add(
@@ -51,7 +53,7 @@ def test_properties(built_hnsw):
assert built_hnsw.dim == DIM
assert built_hnsw.nbits == 4
assert built_hnsw.metric == "l2"
- assert built_hnsw.max_elements == N_VECTORS
+ assert built_hnsw.capacity == N_VECTORS
assert built_hnsw.num_clusters == N_CLUSTERS
@@ -70,7 +72,7 @@ def test_seed_reproduces_serial_build_and_search(tmp_path):
path = tmp_path / f"seed-{run}.index"
index.save(str(path))
snapshots.append(path.read_bytes())
- results.append(index.search(queries, k=5, ef=65, num_threads=1))
+ results.append(index.search(queries, k=5, ef_search=65, num_threads=1))
assert snapshots[0] == snapshots[1]
assert snapshots[0] != snapshots[2]
for actual, expected in zip(results[1], results[0], strict=True):
@@ -91,7 +93,7 @@ def test_parallel_build_preserves_self_retrieval(base_data, clusters):
ef_construction=N_VECTORS,
nbits=4,
)
- ids, distances = idx.search(base_data, k=1, ef=N_VECTORS)
+ ids, distances = idx.search(base_data, k=1, ef_search=N_VECTORS)
np.testing.assert_array_equal(ids[:, 0], np.arange(N_VECTORS))
assert np.isfinite(distances).all()
@@ -101,7 +103,7 @@ def test_parallel_build_preserves_self_retrieval(base_data, clusters):
@pytest.mark.parametrize("nq,k", [(N_QUERIES, _TOPK), (1, 1)])
def test_search_output_contract(built_hnsw, query_data, nq, k):
- ids, dists = built_hnsw.search(query_data[:nq], k=k, ef=_EF)
+ ids, dists = built_hnsw.search(query_data[:nq], k=k, ef_search=_EF)
assert ids.shape == dists.shape == (nq, k)
assert ids.dtype == np.int64
assert dists.dtype == np.float32
@@ -112,12 +114,23 @@ def test_search_output_contract(built_hnsw, query_data, nq, k):
@pytest.mark.parametrize("k", [1, 10, 17])
def test_ef_default(built_hnsw, query_data, k):
- """None and 0 select the internal default, max(k, 64)."""
- expected_ids, expected_distances = built_hnsw.search(query_data, k=k, ef=max(k, 64))
- for kwargs in ({}, {"ef": None}, {"ef": 0}):
+ """None selects the internal default, max(k, 64); 0 is rejected."""
+ expected_ids, expected_distances = built_hnsw.search(
+ query_data, k=k, ef_search=max(k, 64)
+ )
+ for kwargs in ({}, {"ef_search": None}):
ids, distances = built_hnsw.search(query_data, k=k, **kwargs)
np.testing.assert_array_equal(ids, expected_ids)
np.testing.assert_array_equal(distances, expected_distances)
+ with pytest.raises(
+ ValueError, match="^ef_search must be at least 1; pass None for the default$"
+ ):
+ built_hnsw.search(query_data, k=k, ef_search=0)
+ # A breadth below k is raised to k.
+ at_k = built_hnsw.search(query_data, k=k, ef_search=k)
+ below_k = built_hnsw.search(query_data, k=k, ef_search=1)
+ np.testing.assert_array_equal(below_k[0], at_k[0])
+ np.testing.assert_array_equal(below_k[1], at_k[1])
# ── search correctness ────────────────────────────────────────────────────────
@@ -140,15 +153,15 @@ def test_self_retrieval(built_hnsw, base_data, clusters, fast_quantization):
)
assert len(idx) == N_VECTORS
probes = base_data[:10]
- ids, _ = idx.search(probes, k=1, ef=200)
+ ids, _ = idx.search(probes, k=1, ef_search=200)
for i in range(10):
assert i in ids[i], f"Vector {i} not found in its own top-1 result"
def test_recall_vs_brute_force(built_hnsw, base_data, query_data):
- """Approximate recall should exceed 0.5 at ef=50 on a small dataset."""
+ """Approximate recall should exceed 0.5 at ef_search=50 on a small dataset."""
k = 5
- approx_ids, _ = built_hnsw.search(query_data, k=k, ef=_EF)
+ approx_ids, _ = built_hnsw.search(query_data, k=k, ef_search=_EF)
exact_ids, _ = brute_force_knn(base_data, query_data, k)
r = recall_at_k(approx_ids, exact_ids, k)
assert r >= 0.5, f"Recall {r:.3f} too low"
@@ -230,8 +243,8 @@ def test_save_load_roundtrip(built_hnsw, query_data, tmp_path):
assert loaded.dim == built_hnsw.dim
assert loaded.nbits == built_hnsw.nbits
- ids_orig, dists_orig = built_hnsw.search(query_data, k=_TOPK, ef=_EF)
- ids_load, dists_load = loaded.search(query_data, k=_TOPK, ef=_EF)
+ ids_orig, dists_orig = built_hnsw.search(query_data, k=_TOPK, ef_search=_EF)
+ ids_load, dists_load = loaded.search(query_data, k=_TOPK, ef_search=_EF)
np.testing.assert_array_equal(ids_orig, ids_load)
np.testing.assert_allclose(dists_orig, dists_load, rtol=1e-5)
@@ -251,16 +264,18 @@ def test_load_rejects_count_larger_than_capacity(built_hnsw, tmp_path):
HnswIndex.load(str(path))
-# ── add and resize ────────────────────────────────────────────────────────────
+# ── add and reserve ───────────────────────────────────────────────────────────
@pytest.fixture
def partial_hnsw(base_data, clusters):
"""Built from the first 400 vectors, with room for the remaining 100."""
centroids, cluster_ids = clusters
- idx = HnswIndex(DIM, M=8, ef_construction=50, nbits=4, num_clusters=len(centroids))
+ idx = HnswIndex(
+ DIM, M=8, ef_construction=50, nbits=4, num_clusters=len(centroids), seed=100
+ )
idx.set_centroids(centroids)
- idx.resize(N_VECTORS)
+ idx.reserve(N_VECTORS)
idx.add(base_data[:400], cluster_ids=cluster_ids[:400], num_threads=1)
return idx
@@ -270,7 +285,7 @@ def test_add_returns_dense_labels_and_preserves_search(
):
_, cluster_ids = clusters
assert partial_hnsw.num_points == 400
- before, _ = partial_hnsw.search(base_data[:10], k=1, ef=N_VECTORS)
+ before, _ = partial_hnsw.search(base_data[:10], k=1, ef_search=N_VECTORS)
# One thread, as the build used, so the grown graph and `after` are reproducible.
ids = partial_hnsw.add(
base_data[400:], cluster_ids=cluster_ids[400:], num_threads=1
@@ -279,11 +294,11 @@ def test_add_returns_dense_labels_and_preserves_search(
assert partial_hnsw.num_points == N_VECTORS
# A sparse graph can isolate the odd point, as it can after build, so this
# asks for near-perfect self-retrieval rather than exact.
- ids, distances = partial_hnsw.search(base_data[400:], k=1, ef=N_VECTORS)
+ ids, distances = partial_hnsw.search(base_data[400:], k=1, ef_search=N_VECTORS)
found = np.count_nonzero(ids[:, 0] == np.arange(400, N_VECTORS))
assert found >= 0.95 * (N_VECTORS - 400)
assert np.isfinite(distances).all()
- after, _ = partial_hnsw.search(base_data[:10], k=1, ef=N_VECTORS)
+ after, _ = partial_hnsw.search(base_data[:10], k=1, ef_search=N_VECTORS)
np.testing.assert_array_equal(before[:, 0], after[:, 0])
@@ -300,7 +315,7 @@ def test_add_into_a_dense_graph_retrieves_every_point(base_data, clusters):
nbits=4,
)
idx.add(base_data[400:], cluster_ids=cluster_ids[400:])
- ids, _ = idx.search(base_data[400:], k=1, ef=N_VECTORS)
+ ids, _ = idx.search(base_data[400:], k=1, ef_search=N_VECTORS)
np.testing.assert_array_equal(ids[:, 0], np.arange(400, N_VECTORS))
@@ -309,16 +324,16 @@ def test_add_without_cluster_ids_preserves_self_retrieval(partial_hnsw, base_dat
np.testing.assert_array_equal(ids, np.arange(400, N_VECTORS))
# Automatically routed points must remain searchable even though nearest-centroid
# routing need not reproduce the round-robin assignments used during construction.
- found, _ = partial_hnsw.search(base_data[400:], k=1, ef=N_VECTORS)
+ found, _ = partial_hnsw.search(base_data[400:], k=1, ef_search=N_VECTORS)
assert np.count_nonzero(found[:, 0] == np.arange(400, N_VECTORS)) >= 0.95 * 100
def test_add_beyond_capacity_grows_it(partial_hnsw, base_data):
- capacity = partial_hnsw.max_elements
+ capacity = partial_hnsw.capacity
partial_hnsw.add(base_data)
assert partial_hnsw.num_points == 400 + N_VECTORS
# Geometric growth: at least double, so repeated small adds stay cheap.
- assert partial_hnsw.max_elements == max(400 + N_VECTORS, 2 * capacity)
+ assert partial_hnsw.capacity == max(400 + N_VECTORS, 2 * capacity)
def test_add_rejects_bad_cluster_ids(partial_hnsw, base_data):
@@ -350,32 +365,39 @@ def test_add_before_build_trains_first(base_data):
)
-def test_resize_grows_capacity_and_allows_more(base_data, clusters):
+def test_reserve_grows_capacity_and_allows_more(base_data, clusters):
centroids, cluster_ids = clusters
idx = _built(
base_data[:400], centroids, cluster_ids[:400], M=8, ef_construction=50, nbits=4
)
- assert idx.max_elements == 400 # the first add allocates exactly its rows
+ assert idx.capacity == 400 # the first add allocates exactly its rows
- idx.resize(N_VECTORS)
- assert idx.max_elements == N_VECTORS
+ idx.reserve(N_VECTORS)
+ assert idx.capacity == N_VECTORS
assert idx.num_points == 400
idx.add(base_data[400:], cluster_ids=cluster_ids[400:], num_threads=1)
assert idx.num_points == N_VECTORS
- ids, _ = idx.search(base_data[:10], k=1, ef=N_VECTORS)
+ ids, _ = idx.search(base_data[:10], k=1, ef_search=N_VECTORS)
np.testing.assert_array_equal(ids[:, 0], np.arange(10))
-def test_resize_below_element_count_raises(partial_hnsw):
- with pytest.raises(ValueError, match="element count"):
- partial_hnsw.resize(10)
- assert partial_hnsw.max_elements == N_VECTORS
+def test_reserve_never_shrinks(partial_hnsw):
+ # 450 lies between the 400 stored points and the capacity, where the
+ # resize of 0.8 shrank the index.
+ for smaller in (0, 10, 450, N_VECTORS):
+ partial_hnsw.reserve(smaller)
+ assert partial_hnsw.capacity == N_VECTORS
+ with pytest.raises(ValueError, match="^num_points must be non-negative$"):
+ partial_hnsw.reserve(-1)
+ with pytest.raises(TypeError):
+ partial_hnsw.reserve(1.5)
+ assert partial_hnsw.capacity == N_VECTORS
@pytest.mark.parametrize("nbits", [1, 9])
@pytest.mark.parametrize("metric", ["l2", "ip"])
-def test_resize_across_allocation_threshold_preserves_search(tmp_path, nbits, metric):
+def test_reserve_across_allocation_threshold_preserves_search(tmp_path, nbits, metric):
rng = np.random.default_rng(73)
data = rng.standard_normal((97, 65)).astype(np.float32)
queries = rng.standard_normal((7, 65)).astype(np.float32)
@@ -388,19 +410,19 @@ def test_resize_across_allocation_threshold_preserves_search(tmp_path, nbits, me
nbits=nbits,
metric=metric,
)
- expected_ids, expected_distances = index.search(queries, k=7, ef=97)
-
- # The level-0 allocation moves from below 2 MiB to above it and back.
- for capacity in [32768, len(data)]:
- index.resize(capacity)
- path = str(tmp_path / "resized.index")
- index.save(path)
- index = HnswIndex.load(path)
- assert index.max_elements == capacity
- assert index.num_points == len(data)
- ids, distances = index.search(queries, k=7, ef=97)
- np.testing.assert_array_equal(ids, expected_ids)
- np.testing.assert_array_equal(distances, expected_distances)
+ expected_ids, expected_distances = index.search(queries, k=7, ef_search=97)
+
+ # The level-0 allocation moves from below 2 MiB to above it.
+ capacity = 32768
+ index.reserve(capacity)
+ path = str(tmp_path / "reserved.index")
+ index.save(path)
+ index = HnswIndex.load(path)
+ assert index.capacity == capacity
+ assert index.num_points == len(data)
+ ids, distances = index.search(queries, k=7, ef_search=97)
+ np.testing.assert_array_equal(ids, expected_ids)
+ np.testing.assert_array_equal(distances, expected_distances)
def test_added_points_survive_save_and_load(
@@ -408,15 +430,15 @@ def test_added_points_survive_save_and_load(
):
_, cluster_ids = clusters
partial_hnsw.add(base_data[400:], cluster_ids=cluster_ids[400:])
- before_ids, before_dists = partial_hnsw.search(base_data, k=_TOPK, ef=_EF)
+ before_ids, before_dists = partial_hnsw.search(base_data, k=_TOPK, ef_search=_EF)
path = str(tmp_path / "hnsw-added.index")
partial_hnsw.save(path)
loaded = HnswIndex.load(path)
assert loaded.num_points == N_VECTORS
- assert loaded.max_elements == N_VECTORS
- after_ids, after_dists = loaded.search(base_data, k=_TOPK, ef=_EF)
+ assert loaded.capacity == N_VECTORS
+ after_ids, after_dists = loaded.search(base_data, k=_TOPK, ef_search=_EF)
np.testing.assert_array_equal(before_ids, after_ids)
np.testing.assert_allclose(before_dists, after_dists, rtol=1e-5)
@@ -445,7 +467,9 @@ def _removable(nbits=4, metric="l2", count=120, dim=64, seed=61):
def _everything(index, queries):
"""With k and ef at the point count, search visits every reachable point."""
- return index.search(queries, k=index.num_stored_points, ef=index.num_stored_points)
+ return index.search(
+ queries, k=index.num_stored_points, ef_search=index.num_stored_points
+ )
# C++ HnswRemoveTest covers intermediate widths; keep both storage endpoints here.
@@ -475,7 +499,7 @@ def check(index):
np.testing.assert_array_equal(dists[q, :alive], before_dists[q][keep])
assert np.all(ids[q, alive:] == _NO_ID)
assert np.all(np.isinf(dists[q, alive:]))
- top, top_dists = index.search(queries, k=10, ef=10)
+ top, top_dists = index.search(queries, k=10, ef_search=10)
assert not np.isin(top, removed).any()
assert np.isfinite(top_dists).all()
@@ -492,7 +516,7 @@ def check(index):
# graph, with a different set of reachable points.
plain = HnswIndex.load(str(plain_path))
for index in (idx, loaded, plain):
- index.resize(count + len(new))
+ index.reserve(count + len(new))
# One thread: graphs grown in parallel differ, and the searches compare them.
index.add(new, num_threads=1)
assert index.num_stored_points == count + len(new)
@@ -543,7 +567,7 @@ def test_remove_rejects_invalid_ids_without_removing_anything():
def test_removing_every_point_returns_only_sentinels():
idx, old, new = _removable()
assert idx.remove(np.arange(len(old))) == len(old)
- ids, dists = idx.search(new[:2], k=5, ef=10)
+ ids, dists = idx.search(new[:2], k=5, ef_search=10)
assert np.all(ids == _NO_ID)
assert np.all(np.isinf(dists))
@@ -582,12 +606,12 @@ def test_legacy_padding_round_trip_and_add(tmp_path):
fixture = Path(__file__).parent / "fixtures" / "hnsw_legacy_padding65_4bit.index"
index = HnswIndex.load(str(fixture))
query = np.zeros((1, 65), dtype=np.float32)
- ids, distances = index.search(query, k=3, ef=8)
+ ids, distances = index.search(query, k=3, ef_search=8)
np.testing.assert_array_equal(ids, [[0, 1, 2]])
np.testing.assert_allclose(distances, [[0, 14, 14]], atol=1e-5)
# Expected distances were recorded with the old 64-padding implementation.
nonzero_query = ((np.arange(65) % 9 - 4) / 4).astype(np.float32)[None, :]
- nonzero_ids, nonzero_distances = index.search(nonzero_query, k=3, ef=8)
+ nonzero_ids, nonzero_distances = index.search(nonzero_query, k=3, ef_search=8)
np.testing.assert_array_equal(nonzero_ids, [[0, 2, 1]])
np.testing.assert_allclose(
nonzero_distances, [[27.81249809, 33.36483002, 50.26016998]], rtol=2e-6
@@ -596,7 +620,7 @@ def test_legacy_padding_round_trip_and_add(tmp_path):
index.save(str(path))
assert format2_file.padded_dim(path.read_bytes()) == 128
loaded = HnswIndex.load(str(path))
- actual = loaded.search(query, k=3, ef=8)
+ actual = loaded.search(query, k=3, ef_search=8)
np.testing.assert_array_equal(actual[0], ids)
np.testing.assert_array_equal(actual[1], distances)
loaded.add(np.ones((1, 65), dtype=np.float32))
@@ -608,7 +632,7 @@ def test_huge_ef_is_clamped_to_the_stored_point_count():
index = _built(
data, data.mean(axis=0, keepdims=True), np.zeros(80, dtype=np.uint32), nbits=4
)
- exhaustive_ids, exhaustive_distances = index.search(data[:3], k=5, ef=80)
- ids, distances = index.search(data[:3], k=5, ef=2**40)
+ exhaustive_ids, exhaustive_distances = index.search(data[:3], k=5, ef_search=80)
+ ids, distances = index.search(data[:3], k=5, ef_search=2**40)
np.testing.assert_array_equal(ids, exhaustive_ids)
np.testing.assert_array_equal(distances, exhaustive_distances)
diff --git a/tests/python/test_index_counts.py b/tests/python/test_index_counts.py
index fcc3e366..71cae07d 100644
--- a/tests/python/test_index_counts.py
+++ b/tests/python/test_index_counts.py
@@ -1,4 +1,4 @@
-"""All index wrappers distinguish capacity, stored records and live points."""
+"""All index wrappers distinguish stored records and live points; HNSW adds capacity."""
import numpy as np
import pytest
@@ -6,12 +6,13 @@
def check_counts(index, capacity, stored, active):
- assert (index.max_elements, index.num_stored_points, index.num_points) == (
- capacity,
- stored,
- active,
- )
- assert 0 <= index.num_points <= index.num_stored_points <= index.max_elements
+ """capacity is None for the indexes without one."""
+ assert (index.num_stored_points, index.num_points) == (stored, active)
+ assert 0 <= index.num_points <= index.num_stored_points
+ assert getattr(index, "capacity", None) == capacity
+ assert not hasattr(index, "max_elements")
+ if capacity is not None:
+ assert index.num_stored_points <= capacity
# Metric forwarding is covered by portable-index tests; counts are metric-independent.
@@ -29,33 +30,30 @@ def test_count_contract_through_lifecycle(tmp_path, kind, bits):
assignments = np.zeros(count + 4, np.uint32)
if kind == "ivf":
index = IvfIndex(dim, 1, nbits=bits, metric=metric)
- capacity = 0
+ capacity = None
elif kind == "hnsw":
index = HnswIndex(
dim, num_clusters=1, M=8, ef_construction=40, nbits=bits, metric=metric
)
- index.resize(64)
+ index.reserve(64)
capacity = 64
else:
index = SymqgIndex(
dim, max_degree=32, ef_construction=40, nbits=bits, metric=metric
)
- capacity = 0
+ capacity = None
check_counts(index, capacity, 0, 0)
if kind == "symqg":
index.add(data[:count], num_threads=1)
- capacity = count
else:
index.set_centroids(centroid)
index.add(data[:count], cluster_ids=assignments[:count], num_threads=1)
- if kind == "ivf":
- capacity = count
check_counts(index, capacity, count, count)
path = tmp_path / "counts.index"
if kind == "symqg":
index.save(str(path))
- check_counts(SymqgIndex.load(str(path)), count, count, count)
+ check_counts(SymqgIndex.load(str(path)), None, count, count)
return
assert index.remove([0, 1, 0]) == 2
@@ -68,17 +66,15 @@ def test_count_contract_through_lifecycle(tmp_path, kind, bits):
index.remove([2, count])
check_counts(index, capacity, count, count - 3)
if kind == "hnsw":
- with pytest.raises(ValueError):
- index.resize(count - 3)
- index.resize(80)
+ index.reserve(count - 3) # never shrinks
+ check_counts(index, capacity, count, count - 3)
+ index.reserve(80)
capacity = 80
check_counts(index, capacity, count, count - 3)
ids = index.add(data[count : count + 3], cluster_ids=assignments[:3])
np.testing.assert_array_equal(ids, np.arange(count, count + 3))
stored = count + 3
- if kind == "ivf":
- capacity = stored
check_counts(index, capacity, stored, count)
index.save(str(path))
index = type(index).load(str(path))
@@ -91,7 +87,7 @@ def test_count_contract_through_lifecycle(tmp_path, kind, bits):
index.save(str(path))
index = type(index).load(str(path))
check_counts(index, capacity, stored, 0)
- args = {"nprobe": 1} if kind == "ivf" else {"ef": stored}
+ args = {"nprobe": 1} if kind == "ivf" else {"ef_search": stored}
hits, _ = index.search(data[:1], k=1, **args)
assert np.all(hits == -1)
@@ -99,8 +95,6 @@ def test_count_contract_through_lifecycle(tmp_path, kind, bits):
index.add(data[-1:], cluster_ids=assignments[:1]), [stored]
)
stored += 1
- if kind == "ivf":
- capacity = stored
check_counts(index, capacity, stored, 1)
index.save(str(path))
check_counts(type(index).load(str(path)), capacity, stored, 1)
diff --git a/tests/python/test_index_repr.py b/tests/python/test_index_repr.py
index cc7c32ac..6d8af005 100644
--- a/tests/python/test_index_repr.py
+++ b/tests/python/test_index_repr.py
@@ -7,12 +7,12 @@
SUMMARIES = {
"ivf": (
"IvfIndex(dim=64, metric='ip', nbits={bits}, num_points={live}, "
- "num_stored_points={stored}, max_elements={capacity}, "
- "num_clusters={clusters}, initializer='flat', is_trained={built})"
+ "num_stored_points={stored}, num_clusters={clusters}, routing='flat', "
+ "is_trained={built})"
),
"hnsw": (
"HnswIndex(dim=64, metric='ip', nbits={bits}, num_points={live}, "
- "num_stored_points={stored}, max_elements={capacity}, "
+ "num_stored_points={stored}, capacity={capacity}, "
"num_clusters={clusters}, is_trained={built})"
),
"symqg": (
@@ -33,7 +33,7 @@ def unbuilt_index(kind, bits):
if kind == "hnsw":
index = HnswIndex(64, nbits=bits, num_clusters=1, metric="innerproduct")
# Keep capacity distinct from the 80 stored points.
- index.resize(96)
+ index.reserve(96)
return index
return SymqgIndex(
64, max_degree=32, ef_construction=40, metric="innerproduct", nbits=bits
@@ -57,19 +57,18 @@ def test_repr_lifecycle(kind, bits, vectors, tmp_path):
bits=bits,
live=0,
stored=0,
- capacity=96 if kind == "hnsw" else 0,
+ capacity=96, # HnswIndex only
clusters=1,
built=False,
)
assert repr(index) == str(index) == before
build_index(index, vectors)
- capacity = 96 if kind == "hnsw" else 80
after = SUMMARIES[kind].format(
bits=bits,
live=80,
stored=80,
- capacity=capacity,
+ capacity=96,
clusters=1,
built=True,
)
@@ -92,19 +91,15 @@ def test_repr_tracks_live_stored_and_capacity(kind, vectors, tmp_path):
assert isinstance(index, (IvfIndex, HnswIndex))
build_index(index, vectors)
assert index.remove([0]) == 1
- capacity = 96 if kind == "hnsw" else 80
assert repr(index) == SUMMARIES[kind].format(
- bits=4, live=79, stored=80, capacity=capacity, clusters=1, built=True
+ bits=4, live=79, stored=80, capacity=96, clusters=1, built=True
)
index.add(vectors[:1])
if isinstance(index, HnswIndex):
- index.resize(128)
- capacity = 128
- else:
- capacity = 81
+ index.reserve(128)
expected = SUMMARIES[kind].format(
- bits=4, live=80, stored=81, capacity=capacity, clusters=1, built=True
+ bits=4, live=80, stored=81, capacity=128, clusters=1, built=True
)
assert repr(index) == expected
path = tmp_path / "updated.index"
diff --git a/tests/python/test_input_boundaries.py b/tests/python/test_input_boundaries.py
index ffe87df9..15650c94 100644
--- a/tests/python/test_input_boundaries.py
+++ b/tests/python/test_input_boundaries.py
@@ -28,7 +28,7 @@ def built_index(request):
else:
if request.param.startswith("ivf"):
initializer = "hnsw" if request.param == "ivf_hnsw" else "flat"
- index = IvfIndex(64, 1, nbits=4, initializer=initializer)
+ index = IvfIndex(64, 1, nbits=4, routing=initializer)
else:
index = HnswIndex(64, nbits=4, num_clusters=1)
index.set_centroids(data.mean(axis=0, keepdims=True))
@@ -70,7 +70,7 @@ def test_save_replaces_existing_files_without_leftovers(built_index, tmp_path):
filename = tmp_path / "replaced.index"
filename.write_bytes(b"stale")
expected_files = {filename.name}
- if isinstance(index, IvfIndex) and index.initializer == "hnsw":
+ if isinstance(index, IvfIndex) and index.routing == "hnsw":
Path(str(filename) + ".hnsw").write_bytes(b"stale")
expected_files.add(filename.name + ".hnsw")
for _ in range(2):
@@ -202,6 +202,32 @@ def test_query_rank_diagnostics(built_index, shape):
assert str(error.value) == f"queries must be a 2D NumPy array; got shape {shape}"
+def test_query_dimension_is_reported_before_k_and_breadth(built_index):
+ index, queries = built_index
+ narrow = queries[:, :-1]
+ for call in (
+ lambda: index.search(narrow, 0),
+ lambda: index.search(narrow, 1, 0),
+ ):
+ with pytest.raises(
+ ValueError, match="^query dimension does not match index dim"
+ ):
+ call()
+
+
+def test_negative_search_options_raise_type_error(built_index):
+ index, queries = built_index
+ breadth = "nprobe" if isinstance(index, IvfIndex) else "ef_search"
+ for call in (
+ lambda: index.search(queries, -1),
+ lambda: index.search(queries, 1, -1),
+ lambda: index.search(queries, 1, **{breadth: -1}),
+ lambda: index.search(queries, 1, num_threads=-1),
+ ):
+ with pytest.raises(TypeError, match="incompatible function arguments"):
+ call()
+
+
@pytest.mark.parametrize("built_index", ["ivf_hnsw", "hnsw", "symqg"], indirect=True)
def test_path_callback_runs_before_access_guard(built_index, tmp_path):
index, queries = built_index
@@ -209,9 +235,11 @@ def test_path_callback_runs_before_access_guard(built_index, tmp_path):
class UpdatingPath:
def __fspath__(self):
if isinstance(index, IvfIndex):
- index.reserve(0, index.num_stored_points)
+ index.reserve_cluster(0, index.num_stored_points)
elif isinstance(index, HnswIndex):
- index.resize(index.max_elements)
+ # An empty add still takes the write guard; a reserve within the
+ # capacity would only read.
+ index.add(np.empty((0, 64), dtype=np.float32))
else:
# add is SymphonyQG's only write. It takes the write guard and then
# refuses a built graph; a guard still held would raise "busy".
diff --git a/tests/python/test_ivf.py b/tests/python/test_ivf.py
index 1c24192c..1584fb08 100644
--- a/tests/python/test_ivf.py
+++ b/tests/python/test_ivf.py
@@ -53,7 +53,7 @@ def test_properties(built_ivf):
assert built_ivf.num_clusters == N_CLUSTERS
assert built_ivf.nbits == 4
assert built_ivf.metric == "l2"
- assert built_ivf.max_elements == N_VECTORS
+ assert built_ivf.num_stored_points == N_VECTORS
# ── search output shape and dtype ─────────────────────────────────────────────
@@ -323,8 +323,9 @@ def test_raw_reranking(metric, high_accuracy, fast_quantization, tmp_path):
assert loaded.dim == dim
assert loaded.metric == metric
for k in (5, len(data)):
- ids, distances = idx.search(queries, k, 3, high_accuracy, 2)
- loaded_ids, loaded_distances = loaded.search(queries, k, 3, high_accuracy, 2)
+ options = {"high_accuracy": high_accuracy, "num_threads": 2}
+ ids, distances = idx.search(queries, k, 3, **options)
+ loaded_ids, loaded_distances = loaded.search(queries, k, 3, **options)
np.testing.assert_array_equal(loaded_ids, ids)
np.testing.assert_array_equal(loaded_distances, distances)
np.testing.assert_allclose(
@@ -378,7 +379,13 @@ def test_raw_reranking(metric, high_accuracy, fast_quantization, tmp_path):
def test_legacy_ivf_fixture(tmp_path, filename, dim, bits, padded, nonzero_distances):
path = Path(__file__).parent / "fixtures" / filename
idx = IvfIndex.load(str(path))
- assert (idx.dim, idx.max_elements, idx.num_clusters, idx.nbits, idx.metric) == (
+ assert (
+ idx.dim,
+ idx.num_stored_points,
+ idx.num_clusters,
+ idx.nbits,
+ idx.metric,
+ ) == (
dim,
3,
1,
@@ -494,7 +501,7 @@ def test_save_failure_keeps_the_index(tmp_path, initializer):
data = np.zeros((2, 64), dtype=np.float32)
data[1, 0] = 1
idx = _built(
- data, data, np.arange(2, dtype=np.uint32), nbits=32, initializer=initializer
+ data, data, np.arange(2, dtype=np.uint32), nbits=32, routing=initializer
)
expected = idx.search(data, 1, 1)
# /dev/full is not a regular file, so save writes it in place and the write fails.
@@ -512,9 +519,7 @@ def test_save_failure_keeps_the_index(tmp_path, initializer):
def test_hnsw_routing_is_saved_inside_the_index_file(tmp_path):
data = np.zeros((2, 64), dtype=np.float32)
data[1, 0] = 1
- idx = _built(
- data, data, np.arange(2, dtype=np.uint32), nbits=32, initializer="hnsw"
- )
+ idx = _built(data, data, np.arange(2, dtype=np.uint32), nbits=32, routing="hnsw")
expected = idx.search(data, 1, 1)
path = tmp_path / "embedded.index"
# A path where releases up to 0.8 wrote the sidecar is neither used nor needed.
@@ -537,7 +542,7 @@ def test_hnsw_centroid_routing_roundtrip(tmp_path):
count, dim = 128, 64
centroids = rng.standard_normal((count, dim)).astype(np.float32)
labels = np.arange(count, dtype=np.uint32)
- idx = IvfIndex(dim, count, nbits=1, initializer="hnsw", seed=7)
+ idx = IvfIndex(dim, count, nbits=1, routing="hnsw", seed=7)
# A seeded single-thread routing build gives the same graph on every run; a
# parallel build may leave a centroid unreachable (#216).
idx.set_centroids(centroids, num_threads=1)
@@ -573,7 +578,7 @@ def test_hnsw_inner_product_routing_roundtrip(tmp_path):
nbits=32,
num_threads=4,
metric="ip",
- initializer="hnsw",
+ routing="hnsw",
)
path = str(tmp_path / "hnsw_ip_centroid.index")
@@ -610,7 +615,7 @@ def test_add_returns_ids_and_makes_points_searchable():
added = idx.add(new)
assert added.dtype == np.int64
np.testing.assert_array_equal(added, np.arange(len(old), len(old) + len(new)))
- assert idx.max_elements == len(old) + len(new)
+ assert idx.num_stored_points == len(old) + len(new)
# k may now exceed the original point count; raw storage makes the ranking exact.
ids, dists = idx.search(new[:3], k=len(old) + len(new), nprobe=3)
np.testing.assert_array_equal(ids[:, 0], added[:3])
@@ -666,7 +671,7 @@ def test_reserved_adds_match_a_single_add(tmp_path, nbits):
whole.add(new, cluster_ids=assigned)
parts = IvfIndex.load(str(base))
for cluster in range(parts.num_clusters):
- parts.reserve(cluster, len(old) + len(new))
+ parts.reserve_cluster(cluster, len(old) + len(new))
for chunk in np.array_split(np.arange(len(new)), [1, 33, 34, 90]):
parts.add(new[chunk], cluster_ids=assigned[chunk])
a, b = tmp_path / "a.index", tmp_path / "b.index"
@@ -675,29 +680,29 @@ def test_reserved_adds_match_a_single_add(tmp_path, nbits):
assert a.read_bytes() == b.read_bytes()
-def test_reserve_rejects_invalid_arguments():
+def test_reserve_cluster_rejects_invalid_arguments():
idx, old, _, _ = _dynamic_index()
for bad in (-1, 3, 2**32):
with pytest.raises(ValueError, match="cluster_id"):
- idx.reserve(bad, 10)
+ idx.reserve_cluster(bad, 10)
with pytest.raises(ValueError, match="num_points"):
- idx.reserve(0, -1)
+ idx.reserve_cluster(0, -1)
with pytest.raises(ValueError, match="supported ID range"):
- idx.reserve(0, 2**40)
- idx.reserve(0, 0)
- assert idx.max_elements == len(old)
+ idx.reserve_cluster(0, 2**40)
+ idx.reserve_cluster(0, 0)
+ assert idx.num_stored_points == len(old)
unbuilt = IvfIndex(65, 1, nbits=4)
with pytest.raises(RuntimeError, match="trained or loaded"):
- unbuilt.reserve(0, 1)
+ unbuilt.reserve_cluster(0, 1)
def test_add_accepts_fast_quantization_and_other_dtypes():
idx, _, new, _ = _dynamic_index()
idx.add(new[:10].astype(np.float64), fast_quantization=True)
- assert idx.max_elements == 130
+ assert idx.num_stored_points == 130
assert len(idx.add(new[:0])) == 0
- assert idx.max_elements == 130
+ assert idx.num_stored_points == 130
def test_add_rejects_invalid_arguments():
@@ -713,7 +718,7 @@ def test_add_rejects_invalid_arguments():
cluster_ids[0] = bad
with pytest.raises(ValueError, match="cluster_ids"):
idx.add(new, cluster_ids=cluster_ids)
- assert idx.max_elements == len(old)
+ assert idx.num_stored_points == len(old)
# Without cluster IDs, the first add trains the index; with them, it needs centroids.
unbuilt = IvfIndex(65, 1, nbits=4)
@@ -739,7 +744,7 @@ def test_remove_excludes_points_and_survives_reload(
assert idx.remove(removed) == 4
assert idx.remove(removed) == 0
assert idx.remove([]) == 0
- assert idx.max_elements == count
+ assert idx.num_stored_points == count
def check(index):
ids, dists = index.search(
@@ -832,7 +837,7 @@ def test_remove_and_add_refuse_non_integer_ids(bad):
idx.add(new[:2], cluster_ids=bad)
after = idx.search(new[:3], k=len(old), nprobe=3)
np.testing.assert_array_equal(before[0], after[0])
- assert idx.max_elements == len(old)
+ assert idx.num_stored_points == len(old)
def test_remove_and_add_accept_any_integer_dtype_and_empty_input():
diff --git a/tests/python/test_ivf_initializers.py b/tests/python/test_ivf_initializers.py
index db8b1d65..75e532d8 100644
--- a/tests/python/test_ivf_initializers.py
+++ b/tests/python/test_ivf_initializers.py
@@ -16,7 +16,7 @@ def test_hnsw_parallel_build_routes_and_reloads(tmp_path, metric, threads):
count, dim = 1024, 65
data = np.random.default_rng(42).standard_normal((count, dim)).astype(np.float32)
data /= np.linalg.norm(data, axis=1, keepdims=True)
- index = IvfIndex(dim, count, nbits=4, metric=metric, initializer="hnsw")
+ index = IvfIndex(dim, count, nbits=4, metric=metric, routing="hnsw")
index.set_centroids(data, num_threads=threads)
index.add(data, cluster_ids=np.arange(count, dtype=np.uint32), num_threads=threads)
# A parallel build may leave a centroid unreachable in the routing graph, so
@@ -42,7 +42,7 @@ def test_single_thread_set_centroids_builds_reproducible_hnsw_routing(tmp_path,
data = np.random.default_rng(42).standard_normal((count, dim)).astype(np.float32)
saved = []
for run in range(2):
- index = IvfIndex(dim, count, nbits=1, metric=metric, initializer="hnsw", seed=7)
+ index = IvfIndex(dim, count, nbits=1, metric=metric, routing="hnsw", seed=7)
index.set_centroids(data, num_threads=1)
index.add(data, cluster_ids=np.arange(count, dtype=np.uint32), num_threads=4)
path = tmp_path / f"run-{run}.index"
@@ -60,7 +60,7 @@ def test_hnsw_concurrent_routing_windows_match_serial(tmp_path, metric):
rng = np.random.default_rng(42)
data = rng.standard_normal((count, dim)).astype(np.float32)
queries = rng.standard_normal((4, dim)).astype(np.float32)
- index = IvfIndex(dim, count, nbits=1, metric=metric, initializer="hnsw")
+ index = IvfIndex(dim, count, nbits=1, metric=metric, routing="hnsw")
index.set_centroids(data)
index.add(data, cluster_ids=np.arange(count, dtype=np.uint32), num_threads=1)
probes = (1, 16, 400, 500)
@@ -83,7 +83,7 @@ def test_hnsw_concurrent_routing_windows_match_serial(tmp_path, metric):
def test_hnsw_rejects_corrupt_routing_graph(tmp_path, metric, damage):
count, dim = 64, 64
data = np.random.default_rng(42).standard_normal((count, dim)).astype(np.float32)
- index = IvfIndex(dim, count, nbits=4, metric=metric, initializer="hnsw")
+ index = IvfIndex(dim, count, nbits=4, metric=metric, routing="hnsw")
index.set_centroids(data)
index.add(data, cluster_ids=np.arange(count, dtype=np.uint32), num_threads=1)
expected = index.search(data[:2], 1, 4, num_threads=1)
@@ -139,9 +139,9 @@ def test_initializer_roundtrip_and_updates(tmp_path, metric, bits, initializer):
dim, count = 65, 33
data = rng.standard_normal((count + 1, dim)).astype(np.float32)
data /= np.linalg.norm(data, axis=1, keepdims=True)
- index = IvfIndex(dim, count, nbits=bits, metric=metric, initializer=initializer)
+ index = IvfIndex(dim, count, nbits=bits, metric=metric, routing=initializer)
resolved = "flat" if initializer == "auto" else initializer
- assert index.initializer == resolved
+ assert index.routing == resolved
index.set_centroids(data[:count])
index.add(
data[:count], cluster_ids=np.arange(count, dtype=np.uint32), num_threads=2
@@ -159,7 +159,7 @@ def test_initializer_roundtrip_and_updates(tmp_path, metric, bits, initializer):
assert format2_file.IVF_ROUTING[stored] in format2_file.sections(payload)
assert not Path(str(path) + ".hnsw").exists()
loaded = IvfIndex.load(str(path))
- assert loaded.initializer == resolved
+ assert loaded.routing == resolved
actual = loaded.search(queries, 3, 7, num_threads=2)
for left, right in zip(expected, actual):
np.testing.assert_array_equal(left, right)
@@ -168,11 +168,11 @@ def test_initializer_roundtrip_and_updates(tmp_path, metric, bits, initializer):
for obj in (index, loaded):
obj.add(data[count:], num_threads=2)
obj.remove(np.array([0], dtype=np.uint32))
- assert obj.initializer == resolved
+ assert obj.routing == resolved
for left, right in zip(index.search(queries, 3, 7), loaded.search(queries, 3, 7)):
np.testing.assert_array_equal(left, right)
loaded.save(str(path))
- assert IvfIndex.load(str(path)).initializer == resolved
+ assert IvfIndex.load(str(path)).routing == resolved
@pytest.mark.parametrize(
@@ -187,9 +187,9 @@ def test_initializer_roundtrip_and_updates(tmp_path, metric, bits, initializer):
],
)
def test_auto_initializer_thresholds(clusters, expected):
- assert IvfIndex(64, clusters, nbits=1).initializer == expected
+ assert IvfIndex(64, clusters, nbits=1).routing == expected
for mode in ("flat", "flat_rabitq", "hnsw"):
- assert IvfIndex(64, clusters, nbits=1, initializer=mode).initializer == mode
+ assert IvfIndex(64, clusters, nbits=1, routing=mode).routing == mode
# Historical routing depends only on the cluster count, and both storage widths'
@@ -213,7 +213,7 @@ def historical_ivf(request):
np.random.default_rng(43).standard_normal((clusters, 64)).astype(np.float32)
)
historical = "flat" if clusters < 20000 else "hnsw"
- index = IvfIndex(64, clusters, nbits=bits, initializer=historical)
+ index = IvfIndex(64, clusters, nbits=bits, routing=historical)
index.set_centroids(centroids)
index.add(centroids[:3], cluster_ids=np.arange(3, dtype=np.uint32), num_threads=2)
return index, centroids[:3].copy()
@@ -227,7 +227,7 @@ def test_legacy_formats_infer_historical_initializer(
path = tmp_path / "v1.index"
index.save(str(path))
# Format 2 honors the stored type even when today's Auto would choose differently.
- assert IvfIndex.load(str(path)).initializer == index.initializer
+ assert IvfIndex.load(str(path)).routing == index.routing
# Build the earlier layouts from the RABQIDX1 version 2 layout of 0.8. HNSW
# routing, chosen from 20000 clusters, lives in the sidecar of all three.
main, sidecar = format2_file.to_rabqidx1(path.read_bytes())
@@ -235,7 +235,7 @@ def test_legacy_formats_infer_historical_initializer(
Path(str(path) + ".hnsw").write_bytes(sidecar)
path.write_bytes(main)
# RABQIDX1 version 2 also records the routing type.
- assert IvfIndex.load(str(path)).initializer == index.initializer
+ assert IvfIndex.load(str(path)).routing == index.routing
payload = bytearray(main)
if format_version == "v1":
# v1 has the same payload but no initializer field after padded_dim.
@@ -248,7 +248,7 @@ def test_legacy_formats_infer_historical_initializer(
payload = b"RBFQRAW1" + (1).to_bytes(4, "little") + payload
path.write_bytes(payload)
loaded = IvfIndex.load(str(path))
- assert loaded.initializer == index.initializer
+ assert loaded.routing == index.routing
for left, right in zip(index.search(queries, 1, 2), loaded.search(queries, 1, 2)):
np.testing.assert_array_equal(left, right)
@@ -262,14 +262,14 @@ def test_initializer_rejects_invalid_argument():
def test_explicit_flat_routing_above_historical_threshold(tmp_path, initializer):
centroids = np.zeros((20000, 64), dtype=np.float32)
centroids[17, 0] = 1
- index = IvfIndex(64, len(centroids), nbits=32, initializer=initializer)
+ index = IvfIndex(64, len(centroids), nbits=32, routing=initializer)
index.set_centroids(centroids)
index.add(centroids[17:18], cluster_ids=np.array([17], np.uint32), num_threads=2)
path = tmp_path / "large.index"
index.save(str(path))
assert not Path(str(path) + ".hnsw").exists()
for obj in (index, IvfIndex.load(str(path))):
- assert obj.initializer == initializer
+ assert obj.routing == initializer
ids, distances = obj.search(centroids[17:18], 1, 1)
np.testing.assert_array_equal(ids, [[0]])
np.testing.assert_array_equal(distances, [[0]])
@@ -278,7 +278,7 @@ def test_explicit_flat_routing_above_historical_threshold(tmp_path, initializer)
@pytest.mark.parametrize("damage", ["auto", "unknown", "truncated_initializer"])
def test_initializer_rejects_invalid_persistence(tmp_path, damage):
data = np.zeros((3, 65), dtype=np.float32)
- index = IvfIndex(65, 1, nbits=1, initializer="flat_rabitq")
+ index = IvfIndex(65, 1, nbits=1, routing="flat_rabitq")
index.set_centroids(data[:1])
index.add(data, cluster_ids=np.zeros(3, dtype=np.uint32), num_threads=1)
path = tmp_path / "bad.index"
@@ -324,7 +324,7 @@ def test_auto_flat_rabitq_persists_actual_routing(tmp_path, clusters):
index.save(str(path))
assert not Path(str(path) + ".hnsw").exists()
for obj in (index, IvfIndex.load(str(path))):
- assert obj.initializer == "flat_rabitq"
+ assert obj.routing == "flat_rabitq"
ids, distances = obj.search(centroids[17:18], 1, 1)
np.testing.assert_array_equal(ids, [[0]])
np.testing.assert_array_equal(distances, [[0]])
diff --git a/tests/python/test_kmeans_sampling.py b/tests/python/test_kmeans_sampling.py
index 09c4de9c..adcbc4a9 100644
--- a/tests/python/test_kmeans_sampling.py
+++ b/tests/python/test_kmeans_sampling.py
@@ -3,7 +3,6 @@
import numpy as np
import pytest
from rabitqlib import (
- FinalAssignmentMode,
IvfIndex,
QGKMeans,
QGKMeansParameters,
@@ -14,7 +13,7 @@
DIM = 64
# QGKMeans requires more centroids than its default graph degree of 32.
CLUSTERS = {QGKMeans: 33, RaBitQKMeans: 4}
-MODES = [FinalAssignmentMode.Approximate, FinalAssignmentMode.Exact]
+MODES = ["approximate", "exact"]
def make_model(model_type, **kwargs):
@@ -129,7 +128,7 @@ def test_assign_returns_documented_types_for_new_vectors(model_type, mode):
rtol=1e-5,
atol=1e-5,
)
- if mode == FinalAssignmentMode.Exact:
+ if mode == "exact":
all_distances = np.stack(
[
selected_distances(queries, model.centroids, np.full(45, cluster))
@@ -165,9 +164,7 @@ def test_assign_on_training_data_matches_final_assignment(
)
model.train(x)
assignments, distances = model.assign(x)
- reproducible = (
- sampled or mode == FinalAssignmentMode.Exact or model_type is RaBitQKMeans
- )
+ reproducible = sampled or mode == "exact" or model_type is RaBitQKMeans
if reproducible:
np.testing.assert_array_equal(assignments, model.assignments)
np.testing.assert_array_equal(distances, model.distances)
diff --git a/tests/python/test_large_dimensions.py b/tests/python/test_large_dimensions.py
index 708680b2..90e954c1 100644
--- a/tests/python/test_large_dimensions.py
+++ b/tests/python/test_large_dimensions.py
@@ -24,13 +24,14 @@ def test_large_dimension_round_trip(tmp_path, dim, metric, kind):
ef_construction=count,
nbits=4,
metric=metric,
+ seed=42,
)
- search_args = {"ef": count}
+ search_args = {"ef_search": count}
else:
index = SymqgIndex(
dim, max_degree=32, ef_construction=count, nbits=4, metric=metric, seed=42
)
- search_args = {"ef": count}
+ search_args = {"ef_search": count}
# A seeded single-thread build is reproducible, so every self-query must succeed.
if kind == "qg":
diff --git a/tests/python/test_persistence_paths.py b/tests/python/test_persistence_paths.py
index b03a7923..5489afc3 100644
--- a/tests/python/test_persistence_paths.py
+++ b/tests/python/test_persistence_paths.py
@@ -19,11 +19,11 @@ def test_unicode_path_round_trip(tmp_path, kind, unicode_directory):
if kind.startswith("qg"):
index.add(data, num_threads=1)
- search_args = {"ef": 64}
+ search_args = {"ef_search": 64}
else:
index.set_centroids(data.mean(axis=0, keepdims=True))
index.add(data, cluster_ids=np.zeros(64, np.uint32), num_threads=1)
- search_args = {"nprobe": 1} if kind.startswith("ivf") else {"ef": 64}
+ search_args = {"nprobe": 1} if kind.startswith("ivf") else {"ef_search": 64}
directory = tmp_path / "\u6d4b\u8bd5_\U0001f680" if unicode_directory else tmp_path
directory.mkdir(exist_ok=True)
diff --git a/tests/python/test_portable_indexes.py b/tests/python/test_portable_indexes.py
index db88a109..a87339c9 100644
--- a/tests/python/test_portable_indexes.py
+++ b/tests/python/test_portable_indexes.py
@@ -24,7 +24,7 @@ def check_index_round_trip(tmp_path, metric, dim, kind, bits):
metric=metric,
seed=42,
)
- search_args = {"ef": 96}
+ search_args = {"ef_search": 96}
else:
# Seeded and single-threaded, so every self-query below must succeed (#216).
index = SymqgIndex(
@@ -35,7 +35,7 @@ def check_index_round_trip(tmp_path, metric, dim, kind, bits):
metric=metric,
seed=42,
)
- search_args = {"ef": 96}
+ search_args = {"ef_search": 96}
if kind == "qg":
index.add(data, num_threads=1)
else:
diff --git a/tests/python/test_qgkmeans.py b/tests/python/test_qgkmeans.py
index 25980235..02cbda0f 100644
--- a/tests/python/test_qgkmeans.py
+++ b/tests/python/test_qgkmeans.py
@@ -5,7 +5,7 @@
import numpy as np
import pytest
from conftest import DIM
-from rabitqlib import FinalAssignmentMode, QGKMeans, QGKMeansParameters, RaBitQKMeans
+from rabitqlib import QGKMeans, QGKMeansParameters, RaBitQKMeans
K = 33
@@ -26,7 +26,7 @@ def qgkmeans(**kwargs):
"niter": 2,
"num_threads": 1,
"min_points_per_centroid": 1,
- "ef_build": K,
+ "ef_construction": K,
"ef_search": K,
"graph_build_iterations": 2,
}
@@ -40,7 +40,7 @@ def test_parameters_use_faiss_names_and_defaults():
assert cp.graph_build_iterations == 1
assert cp.min_points_per_centroid == 39
assert cp.early_stop_threshold == 0.0
- assert cp.quantization_bits == 0
+ assert cp.nbits == 32
def test_constructor_accepts_faiss_style_keyword_parameters():
@@ -77,11 +77,9 @@ def test_parameters_can_be_changed_through_cp(base_data):
assert len(clustering.iteration_stats) == 1
-@pytest.mark.parametrize("bits", [0, 8])
+@pytest.mark.parametrize("bits", [32, 8])
def test_exact_final_assignment_has_no_nearest_centroid_violations(base_data, bits):
- clustering = qgkmeans(
- final_assignment=FinalAssignmentMode.Exact, quantization_bits=bits
- )
+ clustering = qgkmeans(final_assignment="exact", nbits=bits)
clustering.train(base_data)
differences = (
@@ -109,11 +107,11 @@ def test_exact_final_assignment_handles_matrix_tile_tails(spherical, threads):
niter=1,
num_threads=threads,
min_points_per_centroid=1,
- ef_build=40,
+ ef_construction=40,
ef_search=40,
graph_build_iterations=1,
spherical=spherical,
- final_assignment=FinalAssignmentMode.Exact,
+ final_assignment="exact",
)
clustering.train(x)
@@ -142,7 +140,7 @@ def test_exact_final_assignment_preserves_shifted_l2_accuracy():
niter=1,
num_threads=4,
min_points_per_centroid=1,
- final_assignment=FinalAssignmentMode.Exact,
+ final_assignment="exact",
)
clustering.train(x)
@@ -169,7 +167,7 @@ def test_exact_final_assignment_uses_first_duplicate_centroid(spherical, model_t
num_threads=4,
min_points_per_centroid=1,
spherical=spherical,
- final_assignment=FinalAssignmentMode.Exact,
+ final_assignment="exact",
)
clustering.train(x)
@@ -183,7 +181,7 @@ def test_spherical_mode_returns_normalized_centroids(base_data):
normalized = base_data / np.linalg.norm(base_data, axis=1, keepdims=True)
clustering = qgkmeans(
spherical=True,
- final_assignment=FinalAssignmentMode.Exact,
+ final_assignment="exact",
)
clustering.train(normalized)
@@ -202,7 +200,7 @@ def test_spherical_mode_returns_normalized_centroids(base_data):
np.testing.assert_allclose(clustering.distances, selected_distances, atol=1e-6)
-@pytest.mark.parametrize("bits", [0, 4, 8])
+@pytest.mark.parametrize("bits", [32, 4, 8])
@pytest.mark.parametrize("spherical", [False, True])
def test_graph_returns_exact_selected_distances(bits, spherical):
x = np.random.default_rng(42).standard_normal((100, 65)).astype(np.float32)
@@ -211,12 +209,12 @@ def test_graph_returns_exact_selected_distances(bits, spherical):
clustering = QGKMeans(
65,
K,
- quantization_bits=bits,
+ nbits=bits,
spherical=spherical,
niter=2,
num_threads=2,
min_points_per_centroid=1,
- ef_build=K,
+ ef_construction=K,
ef_search=K,
graph_build_iterations=2,
)
@@ -237,12 +235,10 @@ def test_graph_returns_exact_selected_distances(bits, spherical):
np.testing.assert_allclose(clustering.distances, expected, rtol=1e-6, atol=1e-6)
-@pytest.mark.parametrize("bits", [1, 7, 9, 32])
-def test_train_rejects_unsupported_quantization_bits(base_data, bits):
- clustering = qgkmeans(quantization_bits=bits)
- with pytest.raises(
- ValueError, match="^QGKMeans quantization_bits must be 0, 4, or 8$"
- ):
+@pytest.mark.parametrize("bits", [0, 1, 7, 9])
+def test_train_rejects_unsupported_nbits(base_data, bits):
+ clustering = qgkmeans(nbits=bits)
+ with pytest.raises(ValueError, match="^QGKMeans nbits must be 4, 8, or 32$"):
clustering.train(base_data)
@@ -305,9 +301,9 @@ def test_zero_input_converges_without_exhausting_iterations():
np.testing.assert_array_equal(clustering.distances, 0)
-@pytest.mark.parametrize("bits", [0, 4, 8])
+@pytest.mark.parametrize("bits", [32, 4, 8])
def test_final_objective_measures_returned_assignments(base_data, bits):
- clustering = qgkmeans(niter=1, quantization_bits=bits)
+ clustering = qgkmeans(niter=1, nbits=bits)
assert clustering.final_obj is None
returned = clustering.train(base_data)
assert returned == clustering.obj[-1]
@@ -334,7 +330,7 @@ def test_empty_cluster_recovery_preserves_constant_data(spherical):
np.testing.assert_array_equal(clustering.centroids, x[:K])
-@pytest.mark.parametrize("bits", [0, 4, 8])
+@pytest.mark.parametrize("bits", [32, 4, 8])
@pytest.mark.parametrize("threads", [1, 4])
def test_single_empty_cluster_preserves_duplicate_centroids(bits, threads):
# n == k includes every input row in initialization. Exactly one duplicate
@@ -344,8 +340,8 @@ def test_single_empty_cluster_preserves_duplicate_centroids(bits, threads):
clustering = qgkmeans(
niter=1,
num_threads=threads,
- quantization_bits=bits,
- final_assignment=FinalAssignmentMode.Exact,
+ nbits=bits,
+ final_assignment="exact",
)
clustering.train(x)
@@ -368,7 +364,7 @@ def test_final_objective_does_not_regress_after_last_update(spherical):
num_threads=2,
min_points_per_centroid=1,
# C++ checks every storage width with a genuinely approximate graph.
- quantization_bits=4,
+ nbits=4,
spherical=spherical,
)
clustering.train(x)
@@ -376,7 +372,7 @@ def test_final_objective_does_not_regress_after_last_update(spherical):
assert clustering.final_obj == clustering.distances.sum(dtype=np.float64)
-@pytest.mark.parametrize("bits", [0, 4, 8])
+@pytest.mark.parametrize("bits", [32, 4, 8])
@pytest.mark.parametrize("spherical", [False, True])
def test_pipnn_default_rebuilds_and_returns_exact_selected_distances(bits, spherical):
x = np.random.default_rng(73).standard_normal((100, 65)).astype(np.float32)
@@ -388,7 +384,7 @@ def test_pipnn_default_rebuilds_and_returns_exact_selected_distances(bits, spher
niter=3,
num_threads=2,
min_points_per_centroid=1,
- quantization_bits=bits,
+ nbits=bits,
spherical=spherical,
)
for shift in (0.0, 0.02):
@@ -407,9 +403,9 @@ def test_pipnn_default_rebuilds_and_returns_exact_selected_distances(bits, spher
np.testing.assert_allclose(model.final_obj, expected.sum(), rtol=1e-6)
-@pytest.mark.parametrize("bits", [0, 4, 8])
+@pytest.mark.parametrize("bits", [32, 4, 8])
def test_finite_out_of_range_input_preserves_previous_fit(base_data, bits):
- model = qgkmeans(quantization_bits=bits)
+ model = qgkmeans(nbits=bits)
model.train(base_data)
expected = model.centroids
with pytest.raises(
@@ -428,7 +424,7 @@ def test_training_size_warning_is_opt_in(capfd, verbose):
# C++ covers each dimension/storage layout; check binding outputs here.
-@pytest.mark.parametrize("dim,bits", [(4097, 0), (65535, 4), (65536, 8)])
+@pytest.mark.parametrize("dim,bits", [(4097, 32), (65535, 4), (65536, 8)])
def test_large_dimensions(dim, bits):
x = np.zeros((33, dim), dtype=np.float32)
x[np.arange(33), np.arange(33)] = 1
@@ -438,7 +434,7 @@ def test_large_dimensions(dim, bits):
33,
niter=1,
num_threads=2,
- quantization_bits=bits,
+ nbits=bits,
)
model.train(x)
assert model.centroids.shape == (33, dim)
@@ -446,7 +442,7 @@ def test_large_dimensions(dim, bits):
np.testing.assert_array_equal(x, model.centroids[model.assignments])
-@pytest.mark.parametrize("bits", [0, 4, 8])
+@pytest.mark.parametrize("bits", [32, 4, 8])
@pytest.mark.parametrize("threads", [1, 4])
def test_grouped_training_preserves_centroid_means_with_dimension_tail(bits, threads):
x = np.repeat(np.eye(K, 65, dtype=np.float32) * 16, 3, axis=0)
@@ -457,8 +453,8 @@ def test_grouped_training_preserves_centroid_means_with_dimension_tail(bits, thr
niter=8,
num_threads=threads,
min_points_per_centroid=1,
- quantization_bits=bits,
- ef_build=K,
+ nbits=bits,
+ ef_construction=K,
ef_search=K,
)
model.train(x)
@@ -472,7 +468,7 @@ def test_grouped_training_preserves_centroid_means_with_dimension_tail(bits, thr
np.testing.assert_array_equal(model.centroids, expected)
-@pytest.mark.parametrize("bits", [0, 4, 8])
+@pytest.mark.parametrize("bits", [32, 4, 8])
@pytest.mark.parametrize("spherical", [False, True])
@pytest.mark.parametrize("dim", [511, 960, 1024])
def test_refit_recomputes_sums_for_mutated_storage_seed_and_count(bits, spherical, dim):
@@ -489,9 +485,9 @@ def make_model(seed):
num_threads=1,
seed=seed,
min_points_per_centroid=1,
- ef_build=128,
+ ef_construction=128,
ef_search=1,
- quantization_bits=bits,
+ nbits=bits,
spherical=spherical,
)
@@ -523,9 +519,31 @@ def make_model(seed):
np.testing.assert_array_equal(data, before)
-def test_approximate_final_assignment_keeps_graph_mode_alias():
- assert FinalAssignmentMode.Approximate == FinalAssignmentMode.SymphonyQG
- assert QGKMeansParameters().final_assignment == FinalAssignmentMode.Approximate
+@pytest.mark.parametrize(
+ "parameters,message",
+ [
+ ({"max_degree": 48}, "QGKMeans max_degree must be a positive multiple of 32"),
+ ({"max_degree": 0}, "QGKMeans max_degree must be a positive multiple of 32"),
+ (
+ {"ef_construction": 0},
+ "QGKMeans ef_construction and ef_search must be positive",
+ ),
+ ({"ef_search": 0}, "QGKMeans ef_construction and ef_search must be positive"),
+ (
+ {"graph_build_iterations": 0},
+ "QGKMeans graph_build_iterations must be positive",
+ ),
+ ],
+)
+def test_train_rejects_invalid_graph_parameters(base_data, parameters, message):
+ model = QGKMeans(DIM, 80, niter=1, **parameters)
+ with pytest.raises(ValueError, match=f"^{message}$"):
+ model.train(base_data)
+ assert model.centroids is None
+
+
+def test_final_assignment_is_approximate_by_default():
+ assert QGKMeansParameters().final_assignment == "approximate"
@pytest.mark.parametrize(
@@ -534,14 +552,12 @@ def test_approximate_final_assignment_keeps_graph_mode_alias():
# and propagation of a non-default graph degree through Python.
[(1, 32), (32, 32), (64, 64)],
)
-@pytest.mark.parametrize(
- "mode", [FinalAssignmentMode.Approximate, FinalAssignmentMode.Exact]
-)
-def test_graph_rejects_clusters_at_or_below_graph_degree(clusters, degree, mode):
+@pytest.mark.parametrize("mode", ["approximate", "exact"])
+def test_graph_rejects_clusters_at_or_below_max_degree(clusters, degree, mode):
model = QGKMeans(
- 64, clusters, niter=1, num_threads=1, graph_degree=degree, final_assignment=mode
+ 64, clusters, niter=1, num_threads=1, max_degree=degree, final_assignment=mode
)
with pytest.raises(
- ValueError, match="^QGKMeans requires more centroids than the graph degree$"
+ ValueError, match="^QGKMeans requires more centroids than max_degree$"
):
model.train(np.zeros((65, 64), dtype=np.float32))
diff --git a/tests/python/test_rabitqkmeans.py b/tests/python/test_rabitqkmeans.py
index ab1c198f..d34395c4 100644
--- a/tests/python/test_rabitqkmeans.py
+++ b/tests/python/test_rabitqkmeans.py
@@ -3,11 +3,10 @@
import numpy as np
import pytest
from rabitqlib import (
- FinalAssignmentMode,
+ KMeansIterationStats,
QGKMeans,
QGKMeansParameters,
RaBitQKMeans,
- RaBitQKMeansIterationStats,
RaBitQKMeansParameters,
)
@@ -19,7 +18,7 @@ def test_flat_parameters_and_outputs():
assert parameters.niter == 25
assert parameters.min_points_per_centroid == 39
assert parameters.early_stop_threshold == 0.0
- assert parameters.final_assignment == FinalAssignmentMode.Approximate
+ assert parameters.final_assignment == "approximate"
model = RaBitQKMeans(65, 33, niter=2, num_threads=1, seed=123)
assert model.cp.seed == 123
assert model.centroids is None
@@ -35,17 +34,17 @@ def test_flat_parameters_and_outputs():
assert model.obj.shape == (1,)
assert objective == model.obj[-1]
assert model.final_obj == model.distances.sum(dtype=np.float64)
- assert isinstance(model.iteration_stats[0], RaBitQKMeansIterationStats)
+ assert isinstance(model.iteration_stats[0], KMeansIterationStats)
@pytest.mark.parametrize(
"parameter",
[
- "graph_degree",
- "ef_build",
+ "max_degree",
+ "ef_construction",
"ef_search",
"graph_build_iterations",
- "quantization_bits",
+ "nbits",
],
)
def test_flat_rejects_graph_only_parameters(parameter):
@@ -80,7 +79,7 @@ def test_flat_train_refit_and_return_exact_selected_distances(
):
rng = np.random.default_rng(573)
x = rng.standard_normal((97, 65), dtype=np.float32)
- mode = FinalAssignmentMode.Exact if exact else FinalAssignmentMode.Approximate
+ mode = "exact" if exact else "approximate"
parameters = dict(
niter=3,
num_threads=2,
@@ -133,7 +132,7 @@ def test_flat_duplicates_and_zero(clusters, spherical):
num_threads=2,
spherical=spherical,
min_points_per_centroid=1,
- final_assignment=FinalAssignmentMode.Approximate,
+ final_assignment="approximate",
)
model.train(x)
np.testing.assert_array_equal(model.centroids, x[:clusters])
diff --git a/tests/python/test_remove_arrays.py b/tests/python/test_remove_arrays.py
index e746561b..e817cce1 100644
--- a/tests/python/test_remove_arrays.py
+++ b/tests/python/test_remove_arrays.py
@@ -20,7 +20,7 @@ def test_remove_integer_views_preserve_input_and_validate_atomically(
)
index.set_centroids(np.zeros((1, dim), np.float32))
index.add(data, cluster_ids=np.zeros(count, np.uint32), num_threads=1)
- search_args = {"nprobe": 1} if kind == "ivf" else {"ef": count}
+ search_args = {"nprobe": 1} if kind == "ivf" else {"ef_search": count}
before = index.search(data, k=1, **search_args)
def make_ids(values):
diff --git a/tests/python/test_removed_forms.py b/tests/python/test_removed_forms.py
new file mode 100644
index 00000000..bf1d86d4
--- /dev/null
+++ b/tests/python/test_removed_forms.py
@@ -0,0 +1,309 @@
+"""The call forms that 0.9 removed fail plainly; none is read as something else.
+
+Covers the 0.7 forms (issue #213), the 0.8 index spellings (#232) and the 0.8
+k-means spellings (#233).
+"""
+
+import pickle
+
+import numpy as np
+import pytest
+import rabitqlib
+from conftest import DIM, N_VECTORS
+from rabitqlib import (
+ HnswIndex,
+ IvfIndex,
+ QGKMeans,
+ QGKMeansParameters,
+ RaBitQKMeans,
+ RaBitQKMeansParameters,
+ SymqgIndex,
+)
+
+
+@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
+
+
+@pytest.mark.parametrize(
+ "make",
+ [
+ # IvfIndex(dim, max_elements, num_clusters, nbits, metric, initializer)
+ lambda: IvfIndex(DIM, 1000, 64),
+ lambda: IvfIndex(DIM, N_VECTORS, 4, 4),
+ lambda: IvfIndex(DIM, N_VECTORS, 4, 4, "l2", "flat"),
+ lambda: IvfIndex(dim=DIM, max_elements=N_VECTORS, num_clusters=4, nbits=4),
+ lambda: IvfIndex(DIM, N_VECTORS, num_clusters=4, nbits=4),
+ lambda: IvfIndex(DIM, 4, initializer="flat"),
+ # HnswIndex(dim, max_elements, M, ef_construction, nbits, metric, random_seed)
+ lambda: HnswIndex(DIM, N_VECTORS),
+ lambda: HnswIndex(DIM, N_VECTORS, 16, 200, 4, "l2", 100),
+ lambda: HnswIndex(DIM, max_elements=N_VECTORS),
+ lambda: HnswIndex(DIM, random_seed=5),
+ # SymqgIndex(dim, max_degree, metric, quantization_bits)
+ lambda: SymqgIndex(DIM, 32),
+ lambda: SymqgIndex(DIM, 32, "l2", 4),
+ lambda: SymqgIndex(DIM, quantization_bits=0),
+ ],
+)
+def test_removed_constructor_forms_raise_type_error(make):
+ with pytest.raises(TypeError, match="incompatible constructor arguments") as error:
+ make()
+ # Only the public constructor is offered as the alternative.
+ assert "\n 1. " in str(error.value)
+ assert "\n 2. " not in str(error.value)
+
+
+@pytest.mark.parametrize("kind", ["ivf", "hnsw"])
+def test_add_options_are_keyword_only(kind, request, base_data):
+ index = request.getfixturevalue(kind)
+ cluster_ids = np.zeros(4, dtype=np.uint32)
+ stored = index.num_stored_points
+ for call in (
+ lambda: index.add(base_data[:4], cluster_ids),
+ lambda: index.add(base_data[:4], cluster_ids, 1),
+ lambda: index.add(base_data[:4], cluster_ids, 1, False),
+ ):
+ with pytest.raises(TypeError, match="incompatible function arguments"):
+ call()
+ assert index.num_stored_points == stored
+
+
+def test_ivf_search_keeps_only_nprobe_positional(ivf, query_data):
+ expected = ivf.search(query_data, 3, 4, high_accuracy=False, num_threads=1)
+ # Four probes find other neighbors than the default of one, so a dropped
+ # argument would fail the comparison below.
+ assert not np.array_equal(
+ expected[0], ivf.search(query_data, 3, high_accuracy=False)[0]
+ )
+ for call in (
+ lambda: ivf.search(query_data, 3, 4, False),
+ lambda: ivf.search(query_data, 3, 4, False, 1),
+ ):
+ with pytest.raises(TypeError, match="incompatible function arguments"):
+ call()
+ actual = ivf.search(query_data, 3, nprobe=4, high_accuracy=False)
+ np.testing.assert_array_equal(actual[0], expected[0])
+ np.testing.assert_array_equal(actual[1], expected[1])
+
+
+@pytest.mark.parametrize("kind", ["hnsw", "symqg"])
+def test_graph_search_takes_ef_search_and_keyword_threads(kind, request, query_data):
+ index = request.getfixturevalue(kind)
+ # A breadth of k finds other neighbors than the default of max(k, 64), so a
+ # dropped argument would fail the comparison below.
+ expected = index.search(query_data, 3, ef_search=3)
+ assert not np.array_equal(expected[0], index.search(query_data, 3)[0])
+ for call in (
+ lambda: index.search(query_data, 3, ef=3),
+ lambda: index.search(query_data, 3, 3, 1),
+ lambda: index.search(query_data, 3, 3, ef=3),
+ ):
+ with pytest.raises(TypeError, match="incompatible function arguments"):
+ call()
+ actual = index.search(query_data, 3, 3, num_threads=1)
+ np.testing.assert_array_equal(actual[0], expected[0])
+ np.testing.assert_array_equal(actual[1], expected[1])
+
+
+@pytest.mark.parametrize("zero", [0, np.int64(0), False, np.float32(0)])
+def test_zero_breadth_is_rejected(zero, ivf, hnsw, symqg, query_data):
+ message = "^nprobe must be at least 1; pass None for the default$"
+ for call in (
+ lambda: ivf.search(query_data, 3, zero),
+ lambda: ivf.search(query_data, 3, nprobe=zero),
+ ):
+ with pytest.raises(ValueError, match=message):
+ call()
+ message = "^ef_search must be at least 1; pass None for the default$"
+ for index in (hnsw, symqg):
+ for call in (
+ lambda index=index: index.search(query_data, 3, zero),
+ lambda index=index: index.search(query_data, 3, ef_search=zero),
+ ):
+ with pytest.raises(ValueError, match=message):
+ call()
+
+
+def test_none_and_zero_threads_are_still_accepted(ivf, hnsw, symqg, query_data):
+ for index in (ivf, hnsw, symqg):
+ expected = index.search(query_data, 3)
+ for options in ({"num_threads": None}, {"num_threads": 0}):
+ actual = index.search(query_data, 3, None, **options)
+ np.testing.assert_array_equal(actual[0], expected[0])
+
+
+REMOVED_MEMBERS = {
+ "ivf": [
+ "build",
+ "_build",
+ "is_built",
+ "max_elements",
+ "capacity",
+ "initializer",
+ "reserve",
+ ],
+ "hnsw": ["build", "_build", "is_built", "max_elements", "resize"],
+ "symqg": [
+ "build",
+ "_build",
+ "search_batch",
+ "quantization_bits",
+ "_quantization_bits",
+ "is_built",
+ "max_elements",
+ "capacity",
+ ],
+}
+
+
+@pytest.mark.parametrize(
+ "kind,name",
+ [(kind, name) for kind, names in REMOVED_MEMBERS.items() for name in names],
+)
+def test_removed_index_members_raise_attribute_error(kind, name, request):
+ index = request.getfixturevalue(kind)
+ assert not hasattr(type(index), name)
+ with pytest.raises(AttributeError, match=f"has no attribute '{name}'"):
+ getattr(index, name)
+ # An assignment must not create the attribute either.
+ with pytest.raises(AttributeError):
+ setattr(index, name, 1)
+
+
+def test_renamed_index_members(ivf, hnsw):
+ assert ivf.routing == "flat"
+ assert hnsw.capacity >= hnsw.num_stored_points == N_VECTORS
+ for index, name in ((ivf, "routing"), (hnsw, "capacity")):
+ with pytest.raises(AttributeError):
+ setattr(index, name, getattr(index, name))
+ assert f"capacity={hnsw.capacity}" in repr(hnsw)
+ assert "routing='flat'" in repr(ivf)
+ for index in (ivf, hnsw):
+ assert "max_elements" not in repr(index)
+ assert "initializer" not in repr(index)
+ with pytest.raises(ValueError, match="^routing must be 'auto', 'flat'"):
+ IvfIndex(DIM, 8, routing="unknown")
+ untrained = IvfIndex(DIM, 4)
+ with pytest.raises(
+ RuntimeError,
+ match="^IvfIndex must be trained or loaded before reserve_cluster$",
+ ):
+ untrained.reserve_cluster(0, 1)
+
+
+@pytest.mark.parametrize("name", ["quantization_bits", "graph_degree", "ef_build"])
+def test_removed_kmeans_parameters(name):
+ with pytest.raises(
+ AttributeError,
+ match=f"^QGKMeans\\(\\) got an unexpected keyword argument '{name}'$",
+ ):
+ QGKMeans(DIM, 80, **{name: 32})
+ cp = QGKMeansParameters()
+ with pytest.raises(AttributeError):
+ getattr(cp, name)
+ with pytest.raises(AttributeError):
+ setattr(cp, name, 32)
+
+
+def test_qgkmeans_parameters_use_the_index_names(base_data):
+ cp = QGKMeansParameters()
+ assert (cp.nbits, cp.max_degree, cp.ef_construction) == (32, 32, 240)
+ model = QGKMeans(DIM, 80, nbits=4, max_degree=64, ef_construction=100)
+ assert (model.cp.nbits, model.cp.max_degree, model.cp.ef_construction) == (
+ 4,
+ 64,
+ 100,
+ )
+ for name in ("nbits", "max_degree", "ef_construction"):
+ with pytest.raises(AttributeError, match="unexpected keyword argument"):
+ RaBitQKMeans(DIM, 4, **{name: 32})
+ # 0 was raw storage in 0.8; it is not read as 32.
+ with pytest.raises(ValueError, match="^QGKMeans nbits must be 4, 8, or 32$"):
+ QGKMeans(DIM, 80, niter=1, nbits=0).train(base_data)
+ 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)
+
+
+@pytest.mark.parametrize("cls", [QGKMeans, RaBitQKMeans])
+def test_final_assignment_is_a_string(cls, base_data):
+ assert cls(DIM, 80).cp.final_assignment == "approximate"
+ for mode in ("exact", "approximate"):
+ model = cls(DIM, 80, niter=2, num_threads=1, seed=1, final_assignment=mode)
+ assert model.cp.final_assignment == mode
+ model.train(base_data)
+ cp = cls(DIM, 80).cp
+ 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(
+ ValueError, match="^final_assignment must be 'approximate' or 'exact'$"
+ ):
+ cp.final_assignment = invalid
+ # The 0.8 enum members were integers underneath.
+ with pytest.raises(
+ TypeError, match="could not convert parameter 'final_assignment' from int"
+ ):
+ cls(DIM, 80, final_assignment=1)
+ with pytest.raises(TypeError):
+ cp.final_assignment = 1
+ assert cp.final_assignment == "approximate"
+
+
+def test_index_training_parameters_take_the_string(base_data):
+ for index in (IvfIndex(DIM, 8, seed=3), HnswIndex(DIM, num_clusters=8, seed=3)):
+ assert isinstance(index.cp, RaBitQKMeansParameters)
+ index.cp.final_assignment = "exact"
+ assert index.cp.final_assignment == "exact"
+ with pytest.raises(ValueError, match="^final_assignment must be"):
+ index.cp.final_assignment = "Exact"
+ with pytest.raises(TypeError):
+ index.cp.final_assignment = 1
+ assert index.cp.final_assignment == "exact" # unchanged by the failures
+ index.train(base_data, num_threads=1)
+ assert index.is_trained
+
+
+@pytest.mark.parametrize(
+ "name",
+ ["FinalAssignmentMode", "QGKMeansIterationStats", "RaBitQKMeansIterationStats"],
+)
+def test_names_that_left_the_package(name):
+ assert name not in rabitqlib.__all__
+ assert not hasattr(rabitqlib, name)
+ with pytest.raises(ImportError):
+ exec(f"from rabitqlib import {name}")
+
+
+def test_kmeans_iteration_stats_is_one_class(base_data):
+ stats = rabitqlib.KMeansIterationStats
+ assert stats.__name__ == stats.__qualname__ == "KMeansIterationStats"
+ for cls in (QGKMeans, RaBitQKMeans):
+ model = cls(DIM, 80, niter=2, num_threads=1, seed=1)
+ model.train(base_data)
+ assert len(model.iteration_stats) == 2
+ assert all(type(item) is stats for item in model.iteration_stats)
+ # Pickle and pydoc find the class by this name in its module.
+ assert stats.__module__ == "rabitqlib._rabitqlib"
+ assert pickle.loads(pickle.dumps(stats)) is stats
diff --git a/tests/python/test_symqg.py b/tests/python/test_symqg.py
index 54ab007d..a8d2524b 100644
--- a/tests/python/test_symqg.py
+++ b/tests/python/test_symqg.py
@@ -1,6 +1,5 @@
"""Tests for SymqgIndex: construction, search, properties, error handling, save/load."""
-import inspect
import os
import re
@@ -45,7 +44,7 @@ def test_properties(built_symqg):
@pytest.mark.parametrize("nq,k", [(N_QUERIES, _TOPK), (1, 1)])
def test_search_output_contract(built_symqg, query_data, nq, k):
- ids, dists = built_symqg.search(query_data[:nq], k=k, ef=_EF)
+ ids, dists = built_symqg.search(query_data[:nq], k=k, ef_search=_EF)
assert ids.shape == dists.shape == (nq, k)
assert ids.dtype == np.int64
assert dists.dtype == np.float32
@@ -82,31 +81,33 @@ def test_batch_search_matches_individual_queries(tmp_path, bits, metric):
(1, 64, 8),
]:
individual = [
- index.search(query.copy()[None, :], k=k, ef=ef) for query in queries
+ index.search(query.copy()[None, :], k=k, ef_search=ef) for query in queries
]
expected_ids = np.concatenate([result[0] for result in individual])
expected_distances = np.concatenate([result[1] for result in individual])
- ids, distances = restored.search(queries, k=k, ef=ef, num_threads=threads)
+ ids, distances = restored.search(
+ queries, k=k, ef_search=ef, num_threads=threads
+ )
np.testing.assert_array_equal(ids, expected_ids)
np.testing.assert_array_equal(
distances.view(np.uint32), expected_distances.view(np.uint32)
)
empty_ids, empty_distances = restored.search(
- queries[:0], k=k, ef=ef, num_threads=threads
+ queries[:0], k=k, ef_search=ef, num_threads=threads
)
assert empty_ids.shape == empty_distances.shape == (0, k)
def test_search_validates_inputs(built_symqg, query_data):
with pytest.raises(ValueError, match="queries must be a 2D NumPy array"):
- built_symqg.search(query_data[0], k=1, ef=_EF)
+ built_symqg.search(query_data[0], k=1, ef_search=_EF)
with pytest.raises(ValueError, match="query dimension does not match index dim"):
- built_symqg.search(query_data[:, :-1], k=1, ef=_EF)
+ built_symqg.search(query_data[:, :-1], k=1, ef_search=_EF)
with pytest.raises(ValueError, match=r"k must be between 1 and 2\*\*31"):
- built_symqg.search(query_data, k=0, ef=_EF)
+ built_symqg.search(query_data, k=0, ef_search=_EF)
unbuilt = SymqgIndex(DIM, max_degree=_MAX_DEGREE)
with pytest.raises(RuntimeError, match="add them or load an index before search"):
- unbuilt.search(query_data, k=1, ef=_EF)
+ unbuilt.search(query_data, k=1, ef_search=_EF)
# ── search correctness ────────────────────────────────────────────────────────
@@ -115,15 +116,15 @@ def test_search_validates_inputs(built_symqg, query_data):
def test_self_retrieval(built_symqg, base_data):
"""Each database vector must be its own nearest neighbor at high ef."""
probes = base_data[:10]
- ids, _ = built_symqg.search(probes, k=1, ef=200)
+ ids, _ = built_symqg.search(probes, k=1, ef_search=200)
for i in range(10):
assert i in ids[i], f"Vector {i} not found in its own top-1 result"
def test_recall_vs_brute_force(built_symqg, base_data, query_data):
- """Approximate recall should exceed 0.5 at ef=50 on a small dataset."""
+ """Approximate recall should exceed 0.5 at ef_search=50 on a small dataset."""
k = 5
- approx_ids, _ = built_symqg.search(query_data, k=k, ef=_EF)
+ approx_ids, _ = built_symqg.search(query_data, k=k, ef_search=_EF)
exact_ids, _ = brute_force_knn(base_data, query_data, k)
r = recall_at_k(approx_ids, exact_ids, k)
assert r >= 0.5, f"Recall {r:.3f} too low"
@@ -156,7 +157,7 @@ def test_wrong_query_dim_raises(built_symqg):
)
+ "$",
):
- built_symqg.search(bad_queries, k=1, ef=_EF)
+ built_symqg.search(bad_queries, k=1, ef_search=_EF)
def test_save_before_build_raises(tmp_path):
@@ -175,21 +176,24 @@ def test_search_before_build_raises():
RuntimeError,
match="^SymqgIndex has no vectors; add them or load an index before search$",
):
- idx.search(queries, k=1, ef=_EF)
+ idx.search(queries, k=1, ef_search=_EF)
def test_search_raises_ef_to_k_and_defaults_it(built_symqg, query_data):
- # As in HnswIndex: no or zero ef selects max(k, 64), and ef is at least k.
- at_k = built_symqg.search(query_data, k=10, ef=10)
+ # As in HnswIndex: no ef_search selects max(k, 64), and it is at least k.
+ at_k = built_symqg.search(query_data, k=10, ef_search=10)
for ef in (9, 1):
- raised = built_symqg.search(query_data, k=10, ef=ef)
+ raised = built_symqg.search(query_data, k=10, ef_search=ef)
np.testing.assert_array_equal(raised[0], at_k[0])
- default = built_symqg.search(query_data, k=3, ef=64)
- for ef in (None, 0):
- np.testing.assert_array_equal(
- built_symqg.search(query_data, 3, ef)[0], default[0]
- )
+ default = built_symqg.search(query_data, k=3, ef_search=64)
+ np.testing.assert_array_equal(
+ built_symqg.search(query_data, 3, None)[0], default[0]
+ )
np.testing.assert_array_equal(built_symqg.search(query_data, 3)[0], default[0])
+ with pytest.raises(
+ ValueError, match="^ef_search must be at least 1; pass None for the default$"
+ ):
+ built_symqg.search(query_data, 3, 0)
def test_invalid_degree_raises():
@@ -212,7 +216,7 @@ def test_qg_quant_build_search_and_roundtrip(bits, base_data, query_data, tmp_pa
idx.add(base_data, num_threads=1)
assert idx.nbits == bits
- ids, dists = idx.search(query_data, k=5, ef=_EF)
+ ids, dists = idx.search(query_data, k=5, ef_search=_EF)
assert np.all(ids < N_VECTORS)
assert np.all(np.isfinite(dists))
@@ -220,7 +224,7 @@ def test_qg_quant_build_search_and_roundtrip(bits, base_data, query_data, tmp_pa
idx.save(path)
loaded = SymqgIndex.load(path)
assert loaded.nbits == bits
- loaded_ids, loaded_dists = loaded.search(query_data, k=5, ef=_EF)
+ loaded_ids, loaded_dists = loaded.search(query_data, k=5, ef_search=_EF)
np.testing.assert_array_equal(loaded_ids, ids)
np.testing.assert_allclose(loaded_dists, dists, rtol=1e-5)
@@ -238,8 +242,8 @@ def test_save_load_roundtrip(built_symqg, query_data, tmp_path):
assert loaded.max_degree == built_symqg.max_degree
assert loaded.num_points == built_symqg.num_points
- ids_orig, dists_orig = built_symqg.search(query_data, k=_TOPK, ef=_EF)
- ids_load, dists_load = loaded.search(query_data, k=_TOPK, ef=_EF)
+ ids_orig, dists_orig = built_symqg.search(query_data, k=_TOPK, ef_search=_EF)
+ ids_load, dists_load = loaded.search(query_data, k=_TOPK, ef_search=_EF)
np.testing.assert_array_equal(ids_orig, ids_load)
np.testing.assert_allclose(dists_orig, dists_load, rtol=1e-5)
@@ -285,13 +289,15 @@ def test_constant_vectors_preserve_returned_distance(metric, tmp_path):
queries = np.full((2, 64), 0.0625, dtype=np.float32)
index = SymqgIndex(64, max_degree=32, metric=metric, ef_construction=64)
index.add(data, num_threads=1)
- ids, distances = index.search(queries, k=5, ef=64)
+ ids, distances = index.search(queries, k=5, ef_search=64)
expected = 0.5 if metric == "ip" else 0.25
np.testing.assert_allclose(distances, expected, rtol=0, atol=1e-6)
assert np.all(ids < len(data))
path = str(tmp_path / "constant.symqg")
index.save(path)
- loaded_ids, loaded_distances = SymqgIndex.load(path).search(queries, k=5, ef=64)
+ loaded_ids, loaded_distances = SymqgIndex.load(path).search(
+ queries, k=5, ef_search=64
+ )
np.testing.assert_array_equal(loaded_ids, ids)
np.testing.assert_allclose(loaded_distances, expected, rtol=0, atol=1e-6)
@@ -314,7 +320,7 @@ def test_initialization_and_roundtrip(tmp_path, bits, metric, init):
)
index.add(data, num_threads=2)
assert len(index) == len(data)
- ids, distances = index.search(queries, k=10, ef=160, num_threads=2)
+ ids, distances = index.search(queries, k=10, ef_search=160, num_threads=2)
assert np.all(ids < len(data))
assert np.isfinite(distances).all()
assert all(len(set(row)) == 10 for row in ids)
@@ -334,7 +340,7 @@ def test_initialization_and_roundtrip(tmp_path, bits, metric, init):
path = str(tmp_path / "native_pipnn.index")
index.save(path)
restored = SymqgIndex.load(path)
- restored_ids, restored_distances = restored.search(queries, k=10, ef=160)
+ restored_ids, restored_distances = restored.search(queries, k=10, ef_search=160)
np.testing.assert_array_equal(ids, restored_ids)
np.testing.assert_array_equal(distances, restored_distances)
@@ -349,5 +355,4 @@ def test_native_pipnn_rejects_invalid_build_arguments():
def test_default_initialization_is_pipnn():
- assert inspect.signature(SymqgIndex.__init__).parameters["init"].default == "pipnn"
assert SymqgIndex(DIM).init == "pipnn"
diff --git a/tests/python/test_symqg_api.py b/tests/python/test_symqg_api.py
index 253c8df3..0053af9b 100644
--- a/tests/python/test_symqg_api.py
+++ b/tests/python/test_symqg_api.py
@@ -1,7 +1,4 @@
-"""The 0.8 train / add / search workflow of SymqgIndex."""
-
-import inspect
-import warnings
+"""The train / add / search workflow of SymqgIndex."""
import numpy as np
import pytest
@@ -9,43 +6,22 @@
from rabitqlib import SymqgIndex
-@pytest.fixture(autouse=True)
-def no_deprecations():
- # The 0.8 API must never go through the compatibility layer.
- with warnings.catch_warnings():
- warnings.simplefilter("error", DeprecationWarning)
- yield
-
-
def saved_bytes(index, path):
index.save(path)
return path.read_bytes()
def test_constructor_options_are_keyword_only_with_defaults():
- parameters = inspect.signature(SymqgIndex.__init__).parameters
- keyword = inspect.Parameter.KEYWORD_ONLY
- assert [p for p in parameters if parameters[p].kind is not keyword] == [
- "self",
- "dim",
- ]
- defaults = {name: p.default for name, p in parameters.items() if name != "self"}
- assert defaults == {
- "dim": inspect.Parameter.empty,
- "nbits": 32,
- "max_degree": 32,
- "ef_construction": 200,
- "init": "pipnn",
- "metric": "l2",
- "seed": None,
- }
+ with pytest.raises(TypeError, match="incompatible constructor arguments"):
+ SymqgIndex(DIM, 32)
index = SymqgIndex(DIM)
- assert (index.nbits, index.max_degree, index.ef_construction, index.init) == (
- 32,
- 32,
- 200,
- "pipnn",
- )
+ assert (
+ index.nbits,
+ index.max_degree,
+ index.ef_construction,
+ index.init,
+ index.metric,
+ ) == (32, 32, 200, "pipnn", "l2")
assert index.is_trained
assert len(index) == 0
@@ -85,10 +61,8 @@ def test_constructor_options_are_keyword_only_with_defaults():
],
)
def test_constructor_argument_errors(make, error, message):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", DeprecationWarning)
- with pytest.raises(error, match=message):
- make()
+ with pytest.raises(error, match=message):
+ make()
def test_seed_is_drawn_once_and_reproduces_the_index(base_data, tmp_path):
@@ -144,15 +118,39 @@ def test_add_builds_once_and_search_finds_the_vectors(nbits, base_data, tmp_path
def test_add_uses_the_constructor_settings(base_data, tmp_path):
- for init in ("pipnn", "random"):
- added = SymqgIndex(DIM, ef_construction=60, init=init, seed=9)
- added.add(base_data, num_threads=1)
- with pytest.warns(DeprecationWarning):
- built = SymqgIndex(DIM, seed=9)
- built.build(base_data, 60, 1, init)
- assert saved_bytes(added, tmp_path / "a.index") == saved_bytes(
- built, tmp_path / "b.index"
+ # The file records both settings, so compare what the graphs return, not bytes.
+ found = {}
+ for init, ef_construction in (("pipnn", 33), ("pipnn", 400), ("random", 33)):
+ index = SymqgIndex(DIM, ef_construction=ef_construction, init=init, seed=9)
+ index.add(base_data, num_threads=1)
+ found[init, ef_construction] = index.search(base_data, 10, 10)[0]
+ index.save(tmp_path / "graph.index")
+ loaded = SymqgIndex.load(tmp_path / "graph.index")
+ assert (loaded.ef_construction, loaded.init, loaded.seed) == (
+ ef_construction,
+ init,
+ 9,
)
+ assert not np.array_equal(found["pipnn", 33], found["pipnn", 400])
+ assert not np.array_equal(found["pipnn", 33], found["random", 33])
+
+
+def test_failed_add_leaves_the_index_empty(base_data):
+ index = SymqgIndex(DIM, max_degree=32, ef_construction=60, seed=9)
+ with pytest.raises(
+ ValueError,
+ match="^QuantizedGraph degree bound must be smaller than the number of points$",
+ ):
+ index.add(base_data[:32])
+ assert len(index) == index.num_stored_points == 0
+ # A later failure, raised after the graph object exists.
+ bad = base_data.copy()
+ bad[7, 1] = np.nan
+ with pytest.raises(ValueError, match="finite"):
+ index.add(bad)
+ assert len(index) == index.num_stored_points == 0
+ np.testing.assert_array_equal(index.add(base_data), np.arange(N_VECTORS))
+ assert len(index) == N_VECTORS
def test_search_ef_defaults_to_max_of_k_and_64_and_is_raised_to_k(base_data):
@@ -186,7 +184,8 @@ def test_operations_before_add_raise(tmp_path, base_data):
def test_type_errors_list_only_the_public_constructor():
with pytest.raises(TypeError) as error:
SymqgIndex(DIM, nbits="four")
- assert "_quantization_bits" not in str(error.value)
+ assert "\n 1. " in str(error.value)
+ assert "\n 2. " not in str(error.value)
def test_search_pads_k_beyond_the_points(base_data):
diff --git a/tests/python/test_thread_counts.py b/tests/python/test_thread_counts.py
index a530523c..22ef675a 100644
--- a/tests/python/test_thread_counts.py
+++ b/tests/python/test_thread_counts.py
@@ -25,10 +25,10 @@ def test_build_and_search_thread_counts(kind, metric, build_threads):
index = HnswIndex(
64, num_clusters=1, M=16, ef_construction=96, nbits=8, metric=metric
)
- search_args = {"ef": 96}
+ search_args = {"ef_search": 96}
else:
index = SymqgIndex(64, max_degree=32, ef_construction=96, metric=metric)
- search_args = {"ef": 96}
+ search_args = {"ef_search": 96}
if kind == "qg":
index.add(data, num_threads=build_threads)
else:
@@ -96,7 +96,7 @@ def test_default_set_centroids_respects_omp_num_threads(tmp_path):
data = np.random.default_rng(42).standard_normal((1024, 64)).astype(np.float32)
saved = []
for run in range(2):
- index = IvfIndex(64, 1024, nbits=1, initializer="hnsw", seed=7)
+ index = IvfIndex(64, 1024, nbits=1, routing="hnsw", seed=7)
index.set_centroids(data)
index.add(data[:1], cluster_ids=[0], num_threads=1)
path = Path(sys.argv[1]) / f"run-{run}.index"
diff --git a/tests/python/test_train_api.py b/tests/python/test_train_api.py
index cefcc53a..ae26bbe5 100644
--- a/tests/python/test_train_api.py
+++ b/tests/python/test_train_api.py
@@ -1,7 +1,4 @@
-"""The 0.8 train / set_centroids / add / search workflow of IvfIndex and HnswIndex."""
-
-import inspect
-import warnings
+"""The train / set_centroids / add / search workflow of IvfIndex and HnswIndex."""
import format2_file
import numpy as np
@@ -13,8 +10,8 @@
def new_index(kind, metric="l2", **kwargs):
+ kwargs.setdefault("seed", 7)
if kind == "ivf":
- kwargs.setdefault("seed", 7)
return IvfIndex(
DIM, kwargs.pop("num_clusters", 4), nbits=4, metric=metric, **kwargs
)
@@ -38,58 +35,37 @@ def saved_bytes(index, path):
return path.read_bytes()
-@pytest.fixture(autouse=True)
-def no_deprecations():
- # The 0.8 API must never go through the compatibility layer.
- with warnings.catch_warnings():
- warnings.simplefilter("error", DeprecationWarning)
- yield
-
-
def test_constructor_options_are_keyword_only():
- ivf = inspect.signature(IvfIndex.__init__).parameters
- hnsw = inspect.signature(HnswIndex.__init__).parameters
- keyword = inspect.Parameter.KEYWORD_ONLY
- assert [p for p in ivf if ivf[p].kind is not keyword] == [
- "self",
- "dim",
- "num_clusters",
- ]
- assert [p for p in hnsw if hnsw[p].kind is not keyword] == ["self", "dim"]
- assert ivf["nbits"].default == 7
- assert hnsw["nbits"].default == 7
- assert IvfIndex(DIM, 4).nbits == HnswIndex(DIM).nbits == 7
- assert ivf["seed"].default is None
- assert hnsw["seed"].default == 100
- assert hnsw["num_clusters"].default == 16
+ with pytest.raises(TypeError, match="incompatible constructor arguments"):
+ IvfIndex(DIM, 4, 4)
+ with pytest.raises(TypeError, match="incompatible constructor arguments"):
+ HnswIndex(DIM, 4)
+ ivf, hnsw = IvfIndex(DIM, 4), HnswIndex(DIM)
+ assert ivf.nbits == hnsw.nbits == 7
+ assert hnsw.num_clusters == 16
for cls in (IvfIndex, HnswIndex):
- add = inspect.signature(cls.add).parameters
- assert [p for p in add if add[p].kind is not keyword] == ["self", "data"]
- assert add["num_threads"].default is None
- # train is native; pybind11 documents its signature on the first line.
+ # pybind11 documents each signature on the first line.
+ assert ", data: object, *, cluster_ids:" in cls.add.__doc__.splitlines()[0]
assert ", x: object, *, num_threads:" in cls.train.__doc__.splitlines()[0]
assert cls.train.__doc__.splitlines()[0].endswith("= None) -> None")
-@pytest.mark.parametrize(
- "make,message",
- [
- (
- lambda: IvfIndex(DIM, 4, nbits=4, max_degree=8),
- r"^IvfIndex\(\) got an unexpected keyword argument 'max_degree'$",
- ),
- ],
-)
-def test_constructor_argument_errors(make, message):
- with pytest.raises(TypeError, match=message):
- make()
+def test_unknown_constructor_keyword_raises_type_error():
+ with pytest.raises(TypeError, match="incompatible constructor arguments"):
+ IvfIndex(DIM, 4, nbits=4, max_degree=8)
-def test_positional_nbits_is_read_as_the_old_form_and_explained():
+def test_hnsw_seed_is_drawn_like_the_other_indexes():
+ drawn = [HnswIndex(DIM).seed for _ in range(4)]
+ assert all(isinstance(seed, int) and 0 <= seed < 2**32 for seed in drawn)
+ assert len(set(drawn)) > 1
+ for accepted in (0, 2**32 - 1, np.uint32(7)):
+ index = HnswIndex(DIM, seed=accepted)
+ assert index.seed == index.cp.seed == accepted
with pytest.raises(
- TypeError, match=r"missing a required argument: 'nbits' \(read as the 0\.7 form"
+ ValueError, match=r"^seed must be an integer in \[0, 4294967295\]$"
):
- IvfIndex(DIM, 4, 4)
+ HnswIndex(DIM, seed=2**32)
@pytest.mark.parametrize("cls", [IvfIndex, HnswIndex])
@@ -337,19 +313,6 @@ def test_same_seed_reproduces_an_ivf_index(base_data, tmp_path):
)
-def test_ivf_point_count_index_cannot_be_trained(base_data):
- with pytest.warns(DeprecationWarning):
- index = IvfIndex(DIM, N_VECTORS, 4, 4)
- message = r"^IvfIndex created with max_elements is filled by build; create IvfIndex\(dim, num_clusters, nbits=\.\.\.\) to train or set centroids$"
- with pytest.raises(RuntimeError, match=message):
- index.train(base_data)
- with pytest.raises(RuntimeError, match=message):
- index.set_centroids(base_data[:4])
- 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_reserve_preallocates(base_data):
index = HnswIndex(DIM, nbits=4, num_clusters=4)
assert index.capacity == 1
@@ -395,23 +358,6 @@ def test_hnsw_num_clusters_is_validated():
HnswIndex(DIM, nbits=4, num_clusters=0)
-def test_hnsw_first_add_matches_deprecated_build(base_data, clusters, tmp_path):
- # The first add into an empty index links like the 0.7 build, so the two
- # paths give the same bytes when single-threaded.
- centroids, cluster_ids = clusters
- added = HnswIndex(
- DIM, nbits=4, num_clusters=len(centroids), M=8, ef_construction=50
- )
- added.set_centroids(centroids)
- added.add(base_data, cluster_ids=cluster_ids, num_threads=1)
- with pytest.warns(DeprecationWarning):
- built = HnswIndex(DIM, N_VECTORS, M=8, ef_construction=50, nbits=4)
- built.build(base_data, centroids, cluster_ids)
- assert saved_bytes(added, tmp_path / "a.index") == saved_bytes(
- built, tmp_path / "b.index"
- )
-
-
@pytest.mark.parametrize("kind", KINDS)
def test_add_without_cluster_ids_routes_to_trained_centroids(kind, base_data):
index = new_index(kind)
@@ -539,12 +485,25 @@ 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):
+def test_hnsw_first_add_uses_the_drawn_seed(base_data, tmp_path):
implicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50)
+ seed = implicit.seed
+ implicit.add(base_data, num_threads=1)
+ assert implicit.seed == implicit.cp.seed == seed
+ explicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50, seed=seed)
+ explicit.train(base_data)
+ explicit.add(base_data, num_threads=1)
+ assert saved_bytes(implicit, tmp_path / "implicit.index") == saved_bytes(
+ explicit, tmp_path / "explicit.index"
+ )
+
+
+def test_hnsw_first_add_keeps_a_preallocated_capacity(base_data, tmp_path):
+ implicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50, seed=7)
implicit.reserve(2 * N_VECTORS)
implicit.add(base_data, num_threads=1)
assert implicit.capacity == 2 * N_VECTORS
- explicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50)
+ explicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50, seed=7)
explicit.reserve(2 * N_VECTORS)
explicit.train(base_data)
explicit.add(base_data, num_threads=1)
diff --git a/tests/python/test_txtai_compat.py b/tests/python/test_txtai_compat.py
index 089fba84..bff702f7 100644
--- a/tests/python/test_txtai_compat.py
+++ b/tests/python/test_txtai_compat.py
@@ -1,9 +1,12 @@
-"""txtai's rabitqlib backend, call for call, must keep working in 0.8.
-
-Mirrors txtai.ann.dense.rabitq.RabitQ at neuml/txtai 4d5e05f (index, append,
-delete, search, count, save, load). txtai trains centroids with scikit-learn;
-any centroids exercise the same calls, so these come from the data. The only
-warnings allowed are the compatibility layer's DeprecationWarnings.
+"""The calls a 0.9-compatible txtai backend makes (issue #213).
+
+Follows txtai.ann.dense.rabitq.RabitQ (index, append, delete, search, count,
+save, load) with the four changes 0.9 needs: set_centroids() and
+add(cluster_ids=...) instead of build(), no max_elements or random_seed,
+np.isfinite(distances) to find missing results, and None instead of 0 for an
+unset ef. The same calls run without warnings on 0.8.5. txtai trains centroids with
+scikit-learn; any centroids exercise the same calls, so these come from the
+data. No call may warn.
"""
import math
@@ -13,11 +16,6 @@
import pytest
from rabitqlib import HnswIndex, IvfIndex
-# txtai's filter for missing results. Since 0.9 a missing result is -1, which this no
-# longer matches; these searches never leave slots unfilled. Follow txtai's filter once
-# its first compatible release exists (#213).
-SENTINEL = 0xFFFFFFFF
-
@pytest.fixture
def embeddings():
@@ -34,20 +32,19 @@ def index_like_txtai(mode, vectors):
)
dim = vectors.shape[1]
if mode == "ivf":
- backend = IvfIndex(
- dim=dim, max_elements=rows, num_clusters=clusters, nbits=1, metric="ip"
- )
+ backend = IvfIndex(dim=dim, num_clusters=clusters, nbits=1, metric="ip")
else:
backend = HnswIndex(
dim=dim,
- max_elements=rows,
+ num_clusters=clusters,
M=16,
ef_construction=200,
nbits=1,
metric="ip",
- random_seed=100,
+ seed=100,
)
- backend.build(vectors, centroids, clusterids)
+ backend.set_centroids(centroids)
+ backend.add(vectors, cluster_ids=clusterids)
return backend
@@ -71,14 +68,15 @@ def search_like_txtai(backend, mode, queries, limit):
nprobe = max(1, round(backend.num_clusters / 16))
ids, distances = backend.search(queries, k, nprobe)
else:
- ids, distances = backend.search(queries, k, None or 0)
+ ids, distances = backend.search(queries, k, None)
+ found = np.isfinite(distances)
return [
[
(int(uid), float(1.0 - dist))
- for uid, dist in zip(uids, dists)
- if uid != SENTINEL
+ for uid, dist, hit in zip(uids, dists, hits)
+ if hit
]
- for uids, dists in zip(ids.tolist(), distances.tolist())
+ for uids, dists, hits in zip(ids.tolist(), distances.tolist(), found.tolist())
]
@@ -104,5 +102,4 @@ def test_txtai_calls(mode, embeddings, tmp_path):
assert search_like_txtai(loaded, mode, embeddings[:5], 3) == (
search_like_txtai(backend, mode, embeddings[:5], 3)
)
- categories = {w.category for w in caught}
- assert categories == {DeprecationWarning}, [str(w.message) for w in caught]
+ assert not caught, [str(w.message) for w in caught]
diff --git a/tests/python/typing/public_api.py b/tests/python/typing/public_api.py
index 97c733e3..cb4981ed 100644
--- a/tests/python/typing/public_api.py
+++ b/tests/python/typing/public_api.py
@@ -8,15 +8,12 @@
import numpy.typing as npt
import rabitqlib
from rabitqlib import (
- FinalAssignmentMode,
HnswIndex,
IvfIndex,
KMeansIterationStats,
QGKMeans,
- QGKMeansIterationStats,
QGKMeansParameters,
RaBitQKMeans,
- RaBitQKMeansIterationStats,
RaBitQKMeansParameters,
SymqgIndex,
quant,
@@ -62,8 +59,15 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None:
assert_type(SymqgIndex.load("index.bin"), SymqgIndex)
ivf.reserve_cluster(0, 128)
hnsw.reserve(256)
- qg = QGKMeans(64, 40, niter=2, nbits=4)
+ assert_type(hnsw.capacity, int)
+ assert_type(ivf.num_stored_points, int)
+ ivf.search(x, 5, 1, high_accuracy=None, num_threads=1)
+ hnsw.search(x, 5, 32, num_threads=1)
+ graph.search(x, 5, ef_search=32, num_threads=1)
+ qg = QGKMeans(64, 40, niter=2, nbits=4, max_degree=32, ef_construction=100)
flat = RaBitQKMeans(64, 2, final_assignment="exact")
+ assert_type(qg.cp.nbits, int)
+ assert_type(flat.cp.final_assignment, Literal["approximate", "exact"])
assert_type(qg.cp, QGKMeansParameters)
assert_type(flat.cp, RaBitQKMeansParameters)
for model in (qg, flat):
@@ -80,33 +84,63 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None:
if model.iteration_stats is not None:
assert_type(model.iteration_stats[0], KMeansIterationStats)
qg.cp.final_assignment = "approximate"
- ivf.search(x, "five", 2) # type: ignore[call-overload]
+ ivf.search(x, "five", 2) # type: ignore[arg-type]
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-overload]
- IvfIndex(64, 2, 4) # type: ignore[call-overload]
+ hnsw.search(x, 5, nprobe=2) # type: ignore[call-arg]
+ IvfIndex(64, 2, 4) # type: ignore[call-arg]
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]
+ QGKMeans(64, 40, ef_build=1, bogus=1) # type: ignore[call-arg]
-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 reject_removed_forms(
+ ivf: IvfIndex,
+ hnsw: HnswIndex,
+ graph: SymqgIndex,
+ qg: QGKMeans,
+ x: npt.NDArray[np.float32],
+ labels: npt.NDArray[np.uint32],
+) -> None:
+ # The 0.7 call forms and the 0.8 spellings that 0.9 removed.
+ IvfIndex(64, 80, 1, 4) # type: ignore[arg-type, call-arg]
+ IvfIndex(dim=64, max_elements=80, num_clusters=1, nbits=4) # type: ignore[call-arg]
+ IvfIndex(64, 1, initializer="flat") # type: ignore[call-arg]
+ HnswIndex(64, 80) # type: ignore[call-arg]
+ HnswIndex(64, max_elements=80) # type: ignore[call-arg]
+ HnswIndex(64, random_seed=5) # type: ignore[call-arg]
+ SymqgIndex(64, 32, "l2", 4) # type: ignore[arg-type, call-arg]
+ SymqgIndex(64, quantization_bits=0) # type: ignore[call-arg]
+ ivf.build(x, x[:1], labels) # type: ignore[attr-defined]
+ hnsw.build(x, x[:1], labels) # type: ignore[attr-defined]
+ graph.build(x, 40) # type: ignore[attr-defined]
+ ivf.add(x, labels) # type: ignore[call-arg]
+ hnsw.add(x, labels) # type: ignore[call-arg]
+ ivf.is_built # type: ignore[attr-defined]
+ graph.is_built # type: ignore[attr-defined]
+ ivf.max_elements # type: ignore[attr-defined]
+ hnsw.max_elements # type: ignore[attr-defined]
+ graph.max_elements # type: ignore[attr-defined]
+ ivf.initializer # type: ignore[attr-defined]
+ ivf.reserve(0, 8) # type: ignore[attr-defined]
+ hnsw.resize(128) # type: ignore[attr-defined]
+ graph.quantization_bits # type: ignore[attr-defined]
+ graph.search_batch(x, 5, 32) # type: ignore[attr-defined]
+ ivf.search(x, 5, 1, None) # type: ignore[call-arg]
+ hnsw.search(x, 5, ef=32) # type: ignore[call-arg]
+ hnsw.search(x, 5, 32, 1) # type: ignore[call-arg]
+ graph.search(x, 5, ef=32) # type: ignore[call-arg]
+ graph.search(x, 5, 32, 1) # type: ignore[call-arg]
+ QGKMeans(64, 40, quantization_bits=4) # type: ignore[call-arg]
+ QGKMeans(64, 40, graph_degree=32) # type: ignore[call-arg]
+ QGKMeans(64, 40, ef_build=100) # type: ignore[call-arg]
+ qg.cp.quantization_bits = 4 # type: ignore[attr-defined]
+ qg.cp.graph_degree = 32 # type: ignore[attr-defined]
+ qg.cp.ef_build = 100 # type: ignore[attr-defined]
+ rabitqlib.FinalAssignmentMode # type: ignore[attr-defined]
+ rabitqlib.QGKMeansIterationStats # type: ignore[attr-defined]
+ rabitqlib.RaBitQKMeansIterationStats # type: ignore[attr-defined]
def check_parameter_reads(
@@ -189,12 +223,9 @@ def check_numpy_scalars() -> None:
qg.cp.ef_search = np.int64(16)
qg.cp.graph_build_iterations = np.int64(1)
qg.cp.nbits = np.int64(4)
- members = FinalAssignmentMode.__members__
- assert_type(members, dict[str, FinalAssignmentMode])
- assert_type(members["Exact"], FinalAssignmentMode)
- assert members["Exact"] == FinalAssignmentMode.Exact
- assert members["SymphonyQG"] == members["Approximate"]
- assert FinalAssignmentMode(np.int64(1)) == members["Exact"]
+ for mode in ("approximate", "exact"):
+ qg.cp.final_assignment = mode
+ assert qg.cp.final_assignment == mode
def check_input_contracts() -> None:
@@ -255,11 +286,11 @@ def reject_invalid_inputs(x: npt.NDArray[np.float32]) -> None:
ivf = IvfIndex(64, 1, nbits=4)
hnsw = HnswIndex(64, nbits=4)
graph = SymqgIndex(64)
- 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, routing="flat_rabit") # type: ignore[call-overload]
- SymqgIndex(64, init="pippn") # type: ignore[call-overload]
+ IvfIndex(64, 1, nbits=4, metric="cos") # type: ignore[arg-type]
+ HnswIndex(64, nbits=4, metric="L2") # type: ignore[arg-type]
+ SymqgIndex(64, metric="inner_product") # type: ignore[arg-type]
+ IvfIndex(64, 1, nbits=4, routing="flat_rabit") # type: ignore[arg-type]
+ SymqgIndex(64, init="pippn") # type: ignore[arg-type]
graph.add(x, 1) # type: ignore[call-arg]
ivf.add(x, cluster_ids=[0.0] * 80) # type: ignore[list-item]
hnsw.add(x, cluster_ids=float_ids) # type: ignore[arg-type]
@@ -355,18 +386,3 @@ 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 3ab2d3eb..224de9a0 100644
--- a/tests/test_mypy.py
+++ b/tests/test_mypy.py
@@ -56,129 +56,3 @@ def test_static_public_usage(tmp_path):
)
}
assert error_lines == expected_lines, result.stdout
-
-
-# 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
-import rabitqlib
-from rabitqlib import HnswIndex, IvfIndex, QGKMeans, SymqgIndex
-
-x = np.zeros((80, 64), dtype=np.float32)
-labels = np.zeros(80, dtype=np.uint32)
-ivf = IvfIndex(dim=64, max_elements=80, num_clusters=1, nbits=4, metric="ip")
-hnsw = HnswIndex(dim=64, max_elements=80, M=16, ef_construction=200, nbits=4)
-seeded = HnswIndex(64, nbits=4, random_seed=5)
-ivf.build(x, x[:1], labels)
-hnsw.build(x, x[:1], labels)
-ivf.add(x, labels)
-flag = ivf.is_built
-graph = SymqgIndex(64, 32, "l2", 4)
-alias = SymqgIndex(64, quantization_bits=0)
-graph.build(x, 40)
-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
-
-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,
- "-m",
- "mypy",
- "--strict",
- "--enable-error-code",
- "deprecated",
- "--no-incremental",
- "--cache-dir",
- str(tmp_path / "cache"),
- str(usage),
- ],
- text=True,
- capture_output=True,
- check=False,
- )
- flagged = {
- int(number)
- for number in re.findall(
- rf"{re.escape(str(usage))}:(\d+): error: .*\[deprecated\]", 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
diff --git a/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp b/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp
index 93b73fb5..c40c31f0 100644
--- a/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp
+++ b/tests/unit/rabitqlib/clustering/kmeans_sampling_test.cpp
@@ -57,7 +57,7 @@ qgkmeans::QGKMeansParameters test_parameters(const qgkmeans::QGKMeans*) {
parameters.niter = 4;
parameters.num_threads = 1;
parameters.min_points_per_centroid = 1;
- parameters.ef_build = 64;
+ parameters.ef_construction = 64;
parameters.ef_search = 16;
return parameters;
}
@@ -244,7 +244,7 @@ void check_assign_matches_final_training_assignment() {
constexpr size_t kMaxPoints = 2;
for (const uint32_t threads : {1U, 4U}) {
for (const uint32_t bits :
- kGraph ? std::vector{0, 4, 8} : std::vector{0}) {
+ kGraph ? std::vector{32, 4, 8} : std::vector{32}) {
for (const size_t num_points :
{kClusterCount * kMaxPoints, 3 * kClusterCount * kMaxPoints + 1}) {
const auto points = clustered_points(num_points, 67);
@@ -257,7 +257,7 @@ void check_assign_matches_final_training_assignment() {
auto parameters = test_parameters();
parameters.num_threads = threads;
if constexpr (kGraph) {
- parameters.quantization_bits = bits;
+ parameters.nbits = bits;
}
parameters.final_assignment = mode;
parameters.max_points_per_centroid = kMaxPoints;
@@ -323,10 +323,10 @@ void check_graph_cache_follows_centroids_and_settings() {
constexpr size_t kClusterCount = kClusters;
const auto points = clustered_points(6 * kClusterCount, 83);
const auto queries = clustered_points(60, 89);
- for (const uint32_t bits : {0U, 4U}) {
+ for (const uint32_t bits : {32U, 4U}) {
SCOPED_TRACE(bits);
auto parameters = test_parameters();
- parameters.quantization_bits = bits;
+ parameters.nbits = bits;
QGKMeans clustering(kDim, kClusterCount, parameters);
clustering.train(6 * kClusterCount, points.data());
QGKMeans fresh = clustering; // Copied before any graph is cached.
@@ -693,11 +693,11 @@ TEST(KMeansParametersTest, CopySharedParametersCopiesOnlySharedFields) {
from.spherical = true;
from.verbose = true;
qgkmeans::QGKMeansParameters to;
- to.graph_degree = 64;
- to.ef_build = 99;
+ to.max_degree = 64;
+ to.ef_construction = 99;
to.ef_search = 33;
to.graph_build_iterations = 2;
- to.quantization_bits = 4;
+ to.nbits = 4;
clustering::detail::copy_shared_parameters(from, to);
EXPECT_EQ(to.early_stop_threshold, from.early_stop_threshold);
@@ -709,11 +709,11 @@ TEST(KMeansParametersTest, CopySharedParametersCopiesOnlySharedFields) {
EXPECT_EQ(to.seed, from.seed);
EXPECT_EQ(to.spherical, from.spherical);
EXPECT_EQ(to.verbose, from.verbose);
- EXPECT_EQ(to.graph_degree, 64U);
- EXPECT_EQ(to.ef_build, 99U);
+ EXPECT_EQ(to.max_degree, 64U);
+ EXPECT_EQ(to.ef_construction, 99U);
EXPECT_EQ(to.ef_search, 33U);
EXPECT_EQ(to.graph_build_iterations, 2U);
- EXPECT_EQ(to.quantization_bits, 4U);
+ EXPECT_EQ(to.nbits, 4U);
}
TEST(KMeansTrainCentroidsTest, RaBitQSkipsFinalAssignment) {
diff --git a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp
index a529b9c1..9ce6f1c4 100644
--- a/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp
+++ b/tests/unit/rabitqlib/clustering/qgkmeans_test.cpp
@@ -134,15 +134,15 @@ TEST(QGKMeansTest, UsesTwentyFiveIterationsByDefault) {
}
TEST(QGKMeansTest, UsesRawGraphStorageByDefaultAndRejectsUnsupportedBits) {
- EXPECT_EQ(QGKMeansParameters{}.quantization_bits, 0U);
- for (const uint32_t bits : {1U, 7U, 9U, 32U}) {
+ EXPECT_EQ(QGKMeansParameters{}.nbits, 32U);
+ for (const uint32_t bits : {0U, 1U, 7U, 9U}) {
QGKMeansParameters parameters;
- parameters.quantization_bits = bits;
+ parameters.nbits = bits;
try {
QGKMeans clustering(65, 33, parameters);
- FAIL() << "Accepted unsupported quantization bits " << bits;
+ FAIL() << "Accepted unsupported nbits " << bits;
} catch (const std::invalid_argument& error) {
- EXPECT_STREQ(error.what(), "QGKMeans quantization_bits must be 0, 4, or 8");
+ EXPECT_STREQ(error.what(), "QGKMeans nbits must be 4, 8, or 32");
}
}
}
@@ -294,8 +294,8 @@ TEST(QGAssignerTest, GroupedQueriesPreserveIndependentSearchHintsAcrossRebuilds)
}
}
-TEST(QGKMeansTest, UsesSymphonyQGForFinalAssignmentByDefault) {
- EXPECT_EQ(QGKMeansParameters{}.final_assignment, FinalAssignmentMode::SymphonyQG);
+TEST(QGKMeansTest, UsesApproximateFinalAssignmentByDefault) {
+ EXPECT_EQ(QGKMeansParameters{}.final_assignment, FinalAssignmentMode::Approximate);
}
TEST(QGKMeansTest, UsesFaissTrainingSizeWarningThresholdByDefault) {
@@ -305,8 +305,8 @@ TEST(QGKMeansTest, UsesFaissTrainingSizeWarningThresholdByDefault) {
QGKMeansParameters exact_search_parameters() {
QGKMeansParameters parameters;
parameters.niter = 4;
- parameters.graph_degree = 32;
- parameters.ef_build = 33;
+ parameters.max_degree = 32;
+ parameters.ef_construction = 33;
parameters.ef_search = 33;
parameters.graph_build_iterations = 2;
parameters.num_threads = 1;
@@ -791,9 +791,9 @@ TEST(QGKMeansTest, TrainsAndReturnsAssignmentsForFinalCentroids) {
TEST(QGKMeansTest, RetrainsOnOwnedCentroidsLikeAnIndependentCopy) {
constexpr size_t kDim = 65, kInitialClusters = 35, kClusters = 33;
const auto data = separated_points(kInitialClusters, kDim);
- for (const uint32_t bits : {0U, 4U, 8U}) {
+ for (const uint32_t bits : {32U, 4U, 8U}) {
for (const auto mode :
- {FinalAssignmentMode::SymphonyQG, FinalAssignmentMode::Exact}) {
+ {FinalAssignmentMode::Approximate, FinalAssignmentMode::Exact}) {
for (const size_t offset : {0U, 1U}) {
SCOPED_TRACE(
::testing::Message()
@@ -801,7 +801,7 @@ TEST(QGKMeansTest, RetrainsOnOwnedCentroidsLikeAnIndependentCopy) {
);
auto parameters = exact_search_parameters();
parameters.niter = 2;
- parameters.quantization_bits = bits;
+ parameters.nbits = bits;
parameters.final_assignment = mode;
QGKMeans clustering(kDim, kInitialClusters, parameters);
clustering.train(kInitialClusters, data.data());
@@ -1163,7 +1163,7 @@ TEST(QGKMeansTest, FinalAssignmentsRetainACloserPreviousCluster) {
parameters.num_threads = 1;
parameters.min_points_per_centroid = 1;
parameters.spherical = spherical;
- parameters.quantization_bits = bits;
+ parameters.nbits = bits == 0 ? 32 : bits;
QGKMeans clustering(kDim, kClusters, parameters);
clustering.train(kPoints, data.data());
const auto distance = spherical ? dot_product_dis : euclidean_sqr;
@@ -1209,20 +1209,20 @@ TEST(QGKMeansTest, TrainsWithMovingCentroidsAndAnApproximateGraph) {
}
}
}
- for (uint32_t bits : {0U, 4U, 8U}) {
+ for (uint32_t bits : {32U, 4U, 8U}) {
SCOPED_TRACE(::testing::Message() << spherical << "/" << bits);
QGKMeansParameters parameters;
parameters.niter = 5;
parameters.num_threads = 2;
parameters.min_points_per_centroid = 1;
parameters.spherical = spherical;
- parameters.quantization_bits = bits;
+ parameters.nbits = bits;
QGKMeans clustering(kDim, kClusters, parameters);
clustering.train(kCount, data.data());
double previous = std::numeric_limits::infinity();
for (const auto& stats : clustering.iteration_stats) {
EXPECT_TRUE(std::isfinite(stats.obj));
- if (bits == 0) {
+ if (bits == 32) {
EXPECT_LE(stats.obj, previous + 1e-6 * std::abs(previous));
}
previous = stats.obj;
@@ -1248,7 +1248,7 @@ TEST(QGKMeansTest, RejectsTooFewClustersForGraphDegreeInBothFinalModes) {
QGKMeansParameters parameters;
parameters.niter = 1;
parameters.num_threads = 1;
- parameters.graph_degree = degree;
+ parameters.max_degree = degree;
parameters.final_assignment = mode;
try {
QGKMeans model(kDim, clusters, parameters);
@@ -1256,8 +1256,7 @@ TEST(QGKMeansTest, RejectsTooFewClustersForGraphDegreeInBothFinalModes) {
FAIL() << "Accepted k=" << clusters << " for degree=" << degree;
} catch (const std::invalid_argument& error) {
EXPECT_STREQ(
- error.what(),
- "QGKMeans requires more centroids than the graph degree"
+ error.what(), "QGKMeans requires more centroids than max_degree"
);
}
}
@@ -1312,11 +1311,11 @@ TEST(QGAssignerTest, PropagatesSearchFailureFromWorkers) {
}
TEST(QGKMeansTest, RejectsFiniteOutOfRangeInputBeforeConstruction) {
- for (uint32_t bits : {0U, 4U, 8U}) {
+ for (uint32_t bits : {32U, 4U, 8U}) {
QGKMeansParameters parameters;
parameters.niter = 1;
parameters.num_threads = 2;
- parameters.quantization_bits = bits;
+ parameters.nbits = bits;
QGKMeans model(64, 33, parameters);
const std::vector data(66 * 64, 1e19F);
EXPECT_THROW(model.train(66, data.data()), std::invalid_argument);
@@ -1335,16 +1334,16 @@ TEST(QGKMeansTest, SupportsLargerPaddedDimensions) {
data[i * d + i] = 1.0F;
data[i * d + d - 1] = static_cast(i) / 64.0F;
}
- for (uint32_t bits : {0U, 4U, 8U}) {
+ for (uint32_t bits : {32U, 4U, 8U}) {
// Quantized rows of 65535 and 65536 inputs share the 65536-wide padded
// layout; the exact maximum only adds unpadded raw storage.
- if (d == 65536 && bits != 0) {
+ if (d == 65536 && bits != 32) {
continue;
}
QGKMeansParameters parameters;
parameters.niter = 1;
parameters.num_threads = 2;
- parameters.quantization_bits = bits;
+ parameters.nbits = bits;
QGKMeans model(d, kClusters, parameters);
model.train(kClusters, data.data());
EXPECT_DOUBLE_EQ(model.final_obj, 0.0);
@@ -1396,9 +1395,9 @@ void check_uncached_reference(size_t clusters, uint32_t ef_search, size_t intrin
parameters.num_threads = threads;
parameters.seed = 42;
parameters.min_points_per_centroid = 1;
- parameters.quantization_bits = bits;
+ parameters.nbits = bits == 0 ? 32 : bits;
parameters.spherical = spherical;
- parameters.ef_build = 128;
+ parameters.ef_construction = 128;
parameters.ef_search = ef_search;
QGKMeans model(kDim, clusters, parameters);
model.train(kPoints, x.data());
@@ -1423,7 +1422,7 @@ void check_uncached_reference(size_t clusters, uint32_t ef_search, size_t intrin
kDim,
clusters,
32,
- parameters.ef_build,
+ parameters.ef_construction,
ef_search,
1,
threads,
diff --git a/tests/unit/rabitqlib/index/hnsw_test.cpp b/tests/unit/rabitqlib/index/hnsw_test.cpp
index 54e5637e..b0f61b13 100644
--- a/tests/unit/rabitqlib/index/hnsw_test.cpp
+++ b/tests/unit/rabitqlib/index/hnsw_test.cpp
@@ -681,6 +681,33 @@ TEST(HnswResizeTest, GrowsCapacityAndKeepsTheGraph) {
}
}
+TEST(HnswResizeTest, ShrinksUnusedCapacityAndKeepsSearchResults) {
+ constexpr size_t kBuilt = 128;
+ AddFixture fixture(kBuilt, 37);
+
+ HierarchicalNSW index(kBuilt, AddFixture::kDim, 4, 8, 50);
+ index.construct(
+ 1,
+ fixture.centroid.data(),
+ kBuilt,
+ fixture.data.data(),
+ fixture.cluster_ids.data(),
+ 1,
+ false
+ );
+ const auto expected = index.search(fixture.data.data(), kBuilt, 4, kBuilt, 1);
+
+ // Grow past the 2 MiB level-0 allocation threshold, then shrink back to the
+ // stored count.
+ for (const size_t capacity : {size_t{32768}, kBuilt + 1, kBuilt}) {
+ SCOPED_TRACE(capacity);
+ index.resize(capacity);
+ EXPECT_EQ(index.max_elements(), capacity);
+ EXPECT_EQ(index.num_points(), kBuilt);
+ EXPECT_EQ(index.search(fixture.data.data(), kBuilt, 4, kBuilt, 1), expected);
+ }
+}
+
TEST(HnswResizeTest, SurvivesSaveAndLoad) {
constexpr size_t kBuilt = 64;
constexpr size_t kTotal = 96;