From 411a30b2f91bddf6dc8c61e2de16347cb07a9b37 Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Sat, 14 Nov 2026 11:52:00 +0800 Subject: [PATCH 1/2] feat(python): accept the 0.9 names and deprecate the 0.8 spellings 0.9 gives the three index classes one name for each concept (#232). This release accepts both spellings and raises a DeprecationWarning, at the caller's line, for the 0.8 one: - HnswIndex.capacity and reserve(num_points) for max_elements and resize; max_elements is deprecated on IvfIndex and SymqgIndex. - IvfIndex.reserve_cluster for reserve. - IvfIndex(routing=...) and the routing property for initializer. - search(queries, k, ef_search=...) for ef= on HnswIndex and SymqgIndex. - Search options after the breadth are keyword-only; positions warn. - nprobe=0 and ef_search=0 for the default warn; None selects it. - HnswIndex seeds above 2**32 - 1 warn. The extension keeps the 0.8 names, so the new ones are added in the Python layer, which 0.9 deletes when the extension itself is renamed. No 0.8 call changes its result or its exception type. The HnswIndex default seed and repr() are unchanged here; the 0.9 changes to them are announced in the new 0.8.5 release notes page, which also records #231. --- benchmarks/run.py | 8 +- docs/development.md | 5 +- docs/docs/index/hnsw.md | 19 +- docs/docs/index/ivf.md | 21 +- docs/docs/index/qg.md | 8 +- docs/docs/index/usage.md | 23 +- docs/docs/python_migration.md | 47 +++- docs/docs/releases/0.8.5.md | 37 +++ docs/mkdocs.yml | 1 + python_bindings/__init__.py | 359 ++++++++++++++++++++++++- python_bindings/__init__.pyi | 205 +++++++++++---- sample/python/hnsw_rabitq_querying.py | 2 +- sample/python/symqg_querying.py | 2 +- tests/python/test_compat_09.py | 362 ++++++++++++++++++++++++++ tests/python/test_editor_support.py | 4 +- tests/python/test_examples.py | 2 +- tests/python/test_ivf_initializers.py | 4 +- tests/python/test_symqg_api.py | 3 +- tests/python/test_train_api.py | 39 +-- tests/python/typing/public_api.py | 24 +- tests/test_mypy.py | 20 +- 21 files changed, 1061 insertions(+), 134 deletions(-) create mode 100644 docs/docs/releases/0.8.5.md create mode 100644 tests/python/test_compat_09.py diff --git a/benchmarks/run.py b/benchmarks/run.py index ee770e59..2ba302cd 100644 --- a/benchmarks/run.py +++ b/benchmarks/run.py @@ -120,7 +120,7 @@ def build_index(cfg, base, path): from rabitqlib import IvfIndex # The library's default training: QGKMeans above 2,000 clusters, then add - # routes each vector with the index's centroid initializer. + # routes each vector with the index's routing strategy. index = IvfIndex( dim, cfg["nlist"], nbits=cfg["bits"], metric=cfg["metric"], seed=42 ) @@ -167,7 +167,7 @@ def build_index(cfg, base, path): metric=cfg["metric"], seed=42, ) - index.resize(n) + index.reserve(n) index.set_centroids(kmeans.centroids) index.add(base, cluster_ids=kmeans.assignments, num_threads=cfg["threads"]) indexing_s = time.perf_counter() - stage_start @@ -259,7 +259,9 @@ def search(index, cfg, queries, threads): if method == "rabitq-ivf": return index.search(queries, k=k, nprobe=cfg["nprobe"], num_threads=threads) if method in ("rabitq-hnsw", "rabitq-symqg"): - return index.search(queries, k=k, ef=cfg["ef_search"], num_threads=threads) + return index.search( + queries, k=k, ef_search=cfg["ef_search"], num_threads=threads + ) raise ValueError(f"unsupported benchmark method: {method}") diff --git a/docs/development.md b/docs/development.md index 5800fe56..9b516649 100644 --- a/docs/development.md +++ b/docs/development.md @@ -692,9 +692,10 @@ of 32. These settings are not interchangeable. Public names and Python keywords are compatibility contracts. For example, `Cluster::num()`, the protected `Initializer::num_cluster_`, QG's -`degree_bound()`/`set_ef()`, Python's `ef`, and `QGKMeansParameters::ef_build` +`degree_bound()`/`set_ef()` and `QGKMeansParameters::ef_build` retain their existing spellings, as do the Python vocabulary `random_seed`/`seed`, -`train`/`build`, `obj`, `nsplit`, `final_obj` and `niter`. C++ parameter names may be clarified without +`train`/`build`, `obj`, `nsplit`, `final_obj` and `niter`. Python's search breadth is +`ef_search` since 0.8.5; `ef` is deprecated and removed in 0.9 (#232). C++ parameter names may be clarified without changing types, order or defaults. Keep declarations, definitions and comments in agreement; do not rename methods or literals by textual substitution. diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md index a846c58d..10a93afa 100644 --- a/docs/docs/index/hnsw.md +++ b/docs/docs/index/hnsw.md @@ -20,7 +20,7 @@ from rabitqlib import HnswIndex index = HnswIndex(data.shape[1], M=16, ef_construction=100) # nbits=7 by default index.add(data, num_threads=1) # trains 16 centroids, then links; 1 thread is reproducible -ids, distances = index.search(queries, k=10) # ef defaults to max(k, 64) +ids, distances = index.search(queries, k=10) # ef_search defaults to max(k, 64) index.save("hnsw.index") loaded = HnswIndex.load("hnsw.index") ``` @@ -70,9 +70,9 @@ see [C++ integration](../cpp_integration.md). | `nbits` / C++ `total_bits` | 1–9 total bits including the sign bit. Python's keyword-only `nbits` defaults to 7; C++ requires it. Raw-vector storage is not supported. | | `num_clusters` | Python keyword, default 16: centroids `train` or the first `add` learns, or `set_centroids` supplies; the first `add` caps it at its row count. | | `M`, `ef_construction` | Graph connectivity and construction search budget; Python defaults are 16 and 200, and the index reports both as properties. `M` must be at least 2 and is capped at 10,000; `ef_construction` is raised to at least `M`. The base layer keeps up to `2 * M` edges per node. | -| `metric`, `seed` | Python defaults are `"l2"` and 100; `"ip"` is also supported. `seed` was called `random_seed` before 0.8. | -| `max_elements` | Python reports the current capacity, which `add` grows geometrically (at least doubling) and `resize` can preallocate. C++ `add` never grows it. | -| `k`, `ef` | Positive result count and search window. `k` may exceed the stored point count; Python pads missing results, while C++ returns fewer pairs. Omitted, `None` or zero `ef` uses `max(k, 64)` in Python, positive `ef` is raised to at least `k`, and `ef` above the stored point count is clamped to it. | +| `metric`, `seed` | Python defaults are `"l2"` and 100; `"ip"` is also supported. `seed` was called `random_seed` before 0.8. A seed is in `[0, 2**32 - 1]`; larger values are deprecated since 0.8.5, and 0.9 draws a seed when it is omitted. | +| `capacity` (C++ `max_elements()`) | Python reports the current capacity, which `add` grows geometrically (at least doubling) and `reserve` can preallocate; they were named `max_elements` and `resize` before 0.8.5. C++ `add` never grows it. | +| `k`, `ef_search` | Positive result count and search window. `k` may exceed the stored point count; Python pads missing results, while C++ returns fewer pairs. An omitted or `None` `ef_search` uses `max(k, 64)` in Python (0 does the same and is deprecated since 0.8.5), a smaller value is raised to at least `k`, and a value above the stored point count is clamped to it. Python named it `ef` before 0.8.5. | `seed` controls graph levels and the FHT/Kac rotation (using its low 32 bits). With identical inputs and parameters, single-threaded construction is reproducible @@ -177,7 +177,7 @@ Python follows the shared [concurrency contract](usage.md#threading-and-file-pat ## Updating an index -A constructed or loaded index supports `add()`, `resize()`, +A constructed or loaded index supports `add()`, `resize()` (Python `reserve`), and `remove()` without the original data; C++ also adds to a [trained](#training-centroids-in-c) index. Adding points and resizing preserve the index file format; files with removals have @@ -233,8 +233,9 @@ records still occupy capacity. C++ `add` never grows the index: it rejects a whole batch whose size exceeds `max_elements() - num_stored_points()`, and `resize` is the only way to raise -that. Python `add` calls `resize` first when the batch does not fit, to at least -double the capacity. Reserving capacity avoids reallocating and copying the whole base-layer record storage during `add`. +that. Python `add` grows the capacity first when the batch does not fit, to at least +double it, and `reserve(num_points)` preallocates it (since 0.8.5; `resize` still works, +with a `DeprecationWarning`, until 0.9, and `capacity` replaces `max_elements`). Reserving capacity avoids reallocating and copying the whole base-layer record storage during `add`. It does not make insertion allocation-free: batch scratch, upper-layer link lists, and label-map entries still require allocations, and the label map may rehash. @@ -276,12 +277,12 @@ connected, as in hnswlib. Search never returns it, so a query can get fewer than `num_stored_points()` and cannot be restored. Removal requires the same exclusive access as other updates. -#### Choosing `ef` after removals +#### Choosing `ef_search` after removals Removed points still take slots in the `ef_search` candidate set, so a search with `ef_search` close to `k` finds fewer live points as removals accumulate. C++ search uses `max(ef_search, k)`, clamped to `num_stored_points()`. Python uses `max(k, 64)` -when `ef` is omitted or zero; an explicit positive `ef` is also raised to at least `k`, +when `ef_search` is omitted (it was named `ef` before 0.8.5); an explicit value is also raised to at least `k`, and both are clamped to the stored point count. To keep about the same number of live candidates as before the removals, scale the effective window by the share of live points (search clamps the result to diff --git a/docs/docs/index/ivf.md b/docs/docs/index/ivf.md index 1ac96b07..aa346060 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"` or `"ip"`; defaults to `"l2"`. | -| `initializer` | Defaults to `"auto"`; see [centroid routing](#centroid-routing). | -| `k`, `nprobe` | Positive result count and cluster probe count. `k` may exceed the stored point count; missing results are padded with `kPidMax` (`2**32 - 1` in Python) and `+inf`. Python's `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted, `None` or 0; C++ requires a positive `nprobe`. | +| `routing` | Defaults to `"auto"`; see [centroid routing](#centroid-routing). Named `initializer` before 0.8.5; the old name still works, with a `DeprecationWarning`, until 0.9. | +| `k`, `nprobe` | Positive result count and cluster probe count. `k` may exceed the stored point count; missing results are padded with `kPidMax` (`2**32 - 1` in Python) and `+inf`. Python's `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted or `None` (0 does the same and is deprecated since 0.8.5); C++ requires a positive `nprobe`. | | `high_accuracy` | Python defaults to `None`: HACC for 4–9 bits, standard FastScan otherwise. | Results contain IDs and squared L2 or `1 - dot` distances, ordered from smallest @@ -123,11 +123,11 @@ index_type ivf(num_points, dim, num_clusters, total_bits); The optional final C++ constructor argument selects `InitializerType::Auto`, `Flat`, `FlatRaBitQ`, or `HNSW` from the `rabitqlib::ivf` namespace. Python accepts -`initializer="auto"`, `"flat"`, `"flat_rabitq"`, or `"hnsw"`: +`routing="auto"`, `"flat"`, `"flat_rabitq"`, or `"hnsw"`: ```python -index = IvfIndex(dim, num_clusters, nbits=4, initializer="flat_rabitq") -print(index.initializer) # resolved routing type +index = IvfIndex(dim, num_clusters, nbits=4, routing="flat_rabitq") +print(index.routing) # resolved routing type ``` ```c++ @@ -171,7 +171,7 @@ To retain the earlier policy when rebuilding, choose `flat` below 20,000 cluster and `hnsw` otherwise. Loading an old index preserves its historical routing. Routing is fixed for an index and is also used by `add` when cluster IDs are -omitted. `initializer_type()` (Python `initializer`) reports the resolved type, +omitted. `initializer_type()` (Python `routing`) reports the resolved type, including after loading; loading never re-runs the current `auto` policy for a new-format file. @@ -229,7 +229,7 @@ index.add(vectors) - Training or setting centroids again replaces them while the index stores no vectors; once it stores any (including removed ones), both raise `RuntimeError`. A failed call leaves the index unchanged. -- Before training, `add` with `cluster_ids`, `search`, `remove`, `reserve` and +- Before training, `add` with `cluster_ids`, `search`, `remove`, `reserve_cluster` and `save` raise `RuntimeError`; `add` without `cluster_ids` trains first, except on an index created with `max_elements`, which `build` fills. If that first `add` fails, the index stays untrained and empty; an empty first `add` @@ -395,9 +395,12 @@ new_ids = index.add(vectors, num_threads=1, fast_quantization=False) # To choose clusters explicitly, use this instead of the call above: # new_ids = index.add(vectors, cluster_ids=labels) removed = index.remove(new_ids[:10]) -index.reserve(cluster_id, num_points) +index.reserve_cluster(cluster_id, num_points) ``` +Python names this method `reserve_cluster` since 0.8.5; `reserve` still works, with a +`DeprecationWarning`, until 0.9. + Python `vectors` has shape `(n, index.dim)` and is converted to contiguous float32. `add()` returns a uint32 array of the new IDs. Optional `cluster_ids` must be a one-dimensional integer array or sequence with one valid cluster ID per vector; @@ -424,7 +427,7 @@ index is unchanged if `add` throws. As a result: time.** A rebuilt cluster gets exactly the room it needs. To grow a cluster without -copying it, call `reserve` first: later `add` calls then write into the reserved +copying it, call `reserve` (Python `reserve_cluster`) first: later `add` calls then write into the reserved room in place until the cluster outgrows it. The reserved room is memory the index holds but does not use yet. It is not saved, so a loaded index has none. diff --git a/docs/docs/index/qg.md b/docs/docs/index/qg.md index cbab008b..76649734 100644 --- a/docs/docs/index/qg.md +++ b/docs/docs/index/qg.md @@ -28,7 +28,7 @@ ids = index.add(data) # builds the whole graph; ids are the row numbers index.save("qg_example.index") loaded = SymqgIndex.load("qg_example.index") -ids, distances = loaded.search(queries, k=10, ef=100) +ids, distances = loaded.search(queries, k=10, ef_search=100) ``` SymphonyQG follows the same `train` → `add` → `search` workflow as the other @@ -77,7 +77,7 @@ qg.save("qg_example.index"); | `init` | Python keyword: `"pipnn"` (default) or `"random"`. | | `metric` | Python keyword: `"l2"` (default) or `"ip"`. | | `seed` | Python keyword: rotation and graph-construction seed in `[0, 2**32 - 1]`. The default `None` draws one at random; `index.seed` reports it, and passing it back with `num_threads=1` rebuilds the same graph from the same data. | -| `k`, `ef` | `k` is at least 1 and may exceed the point count; slots the graph cannot fill are padded with ID `2**32 - 1` and distance `+inf`. Omitted or zero `ef` uses `max(k, 64)` in Python, and smaller values are raised to `k`, as for HNSW-RaBitQ. | +| `k`, `ef_search` | `k` is at least 1 and may exceed the point count; slots the graph cannot fill are padded with ID `2**32 - 1` and distance `+inf`. An omitted `ef_search` uses `max(k, 64)` in Python, and smaller values are raised to `k`, as for HNSW-RaBitQ. Python named it `ef` before 0.8.5. | | `num_threads` | Python `add` defaults to every available logical CPU, capped by `OMP_NUM_THREADS`, and `search` to 1; `None` selects these defaults. | Python search returns `(ids, distances)` arrays. Distances are squared @@ -180,14 +180,14 @@ do no work and may use null buffers. Inputs and outputs must not overlap. Concurrent searches need separate outputs; do not modify the index or call `set_ef()` while searches are running. -Python `search(queries, k, ef=None, num_threads=None)` accepts a two-dimensional +Python `search(queries, k, ef_search=None, *, num_threads=None)` accepts a two-dimensional query array and returns `(ids, distances)` arrays of shape `(num_queries, k)`, including empty batches. It defaults to one worker; `num_threads=0` selects the available logical CPU count, capped by the number of queries. The 0.7 name `search_batch` still works in 0.8 with a `DeprecationWarning`. Queries use the original dimension, including when the internal rotation pads it. -Python searches use per-call `ef` values. For access rules, see the +Python searches use per-call `ef_search` values. For access rules, see the [concurrency contract](usage.md#threading-and-file-paths). For C++, use diff --git a/docs/docs/index/usage.md b/docs/docs/index/usage.md index 113c443f..2afe6391 100644 --- a/docs/docs/index/usage.md +++ b/docs/docs/index/usage.md @@ -34,15 +34,20 @@ HNSW-RaBitQ's `num_points` now excludes removed records; see the [count migration guide](../modular_migration.md#unified-index-counts) when upgrading. IVF-RaBitQ, HNSW-RaBitQ, and SymphonyQG expose these read-only Python properties -(C++ uses the same names with `()`): +(C++ uses the same names with `()`, and `max_elements()` for the capacity of all +three indexes): | Property | Meaning | | --- | --- | -| `max_elements` | Logical record capacity, excluding SIMD padding | | `num_points` | Nonremoved points | | `num_stored_points` | Stored records, including removed ones | +| `capacity` (HNSW-RaBitQ only) | Logical record capacity, excluding SIMD padding | -`0 <= num_points <= num_stored_points <= max_elements`. Before vectors are +`0 <= num_points <= num_stored_points`, and `num_stored_points <= capacity` for +HNSW-RaBitQ. Before 0.8.5 Python named the capacity `max_elements` on all three +classes; that property is deprecated and is removed in 0.9. On `IvfIndex` and +`SymqgIndex` it equals `num_stored_points`, except on an `IvfIndex` created in the +0.7 form before `build`, where it is the declared row count. Before vectors are added, both point counts are zero; configured capacity may be nonzero. For all three indexes, `len(index)` equals `num_points`. `is_trained` reports whether IVF-RaBitQ or HNSW-RaBitQ centroids are set (by `train`, `set_centroids`, @@ -53,13 +58,13 @@ start at the previous `num_stored_points`. Use this stored count for ID bounds, and `num_points` for a live count. Counts survive save/load. IVF-RaBitQ grows automatically and has no spare logical capacity after an append. -HNSW-RaBitQ's Python `add` grows its capacity geometrically, and `resize` changes -only capacity, for example to preallocate it. SymphonyQG has no incremental -updates: `add` builds the graph once, and all three counts are equal afterwards. +HNSW-RaBitQ's Python `add` grows its capacity geometrically, and `reserve` preallocates +it (`resize` before 0.8.5). SymphonyQG has no incremental +updates: `add` builds the graph once, and both counts are equal afterwards. `repr(index)` shows dimension, metric, quantization bits and live point count, plus the training state for IVF/HNSW. IVF/HNSW also show stored count, capacity and centroid count; IVF includes -the resolved initializer, and SymphonyQG includes its degree bound. The summary +the resolved routing strategy, and SymphonyQG includes its degree bound. The summary reads only metadata and follows the same concurrency rules as property reads. ## Estimate storage @@ -119,7 +124,7 @@ construction, updates, and file I/O. The following contract applies to | Operation on the same index | Concurrent access | | --- | --- | | `search`, `search_batch`, `save`, `repr`, and property reads | May run together | -| `train`, `set_centroids`, `build`, `add`, `remove`, `reserve`, `resize`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input and may run with reads | +| `train`, `set_centroids`, `build`, `add`, `remove`, `reserve`, `reserve_cluster`, `resize`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input and may run with reads | A conflicting call immediately raises `RuntimeError("Index is busy: conflicting operation in progress")`. @@ -128,7 +133,7 @@ conversion and is released when the operation returns or raises an exception. Different index objects can operate independently. Concurrent saves must use different output paths, including any sidecar files. -Search parameters such as `ef`, `nprobe`, precision, and `num_threads` belong to +Search parameters such as `ef_search`, `nprobe`, precision, and `num_threads` belong to each call. When using a Python thread pool, consider `num_threads=1` to avoid starting multiple native worker pools. Keep input arrays and any shared backing storage unchanged for the entire call; do not resize or modify them from another diff --git a/docs/docs/python_migration.md b/docs/docs/python_migration.md index c14a1bc6..4d2e32a9 100644 --- a/docs/docs/python_migration.md +++ b/docs/docs/python_migration.md @@ -9,6 +9,10 @@ nothing to train and builds its graph in `add`. Code written for 0.7 still runs in 0.8. Each old form raises a `DeprecationWarning` at your call site and will be removed in **0.9**. +If your code already uses the 0.8 forms, go to +[From 0.8 to 0.9](#from-08-to-09): 0.9 renames some of them, and 0.8.5 accepts +the new names. + Unless an item below says otherwise, a 0.7 call that raises a deprecation warning keeps its 0.7 behavior. Calls that are valid in both versions, such as `add(x)` and `search`, follow the 0.8 rules. @@ -19,9 +23,9 @@ warning keeps its 0.7 behavior. Calls that are valid in both versions, such as | 0.7 | 0.8 | | --- | --- | -| `IvfIndex(dim, max_elements, num_clusters, nbits, metric, initializer)` | `IvfIndex(dim, num_clusters, nbits=..., metric=..., initializer=..., seed=None)`; storage grows on `add` | +| `IvfIndex(dim, max_elements, num_clusters, nbits, metric, initializer)` | `IvfIndex(dim, num_clusters, nbits=..., metric=..., routing=..., seed=None)` (`initializer=` before 0.8.5); storage grows on `add` | | `IvfIndex(dim=..., max_elements=..., num_clusters=..., nbits=...)` | the same, without `max_elements` | -| `HnswIndex(dim, max_elements, M=16, ef_construction=200, nbits=8, metric="l2", random_seed=100)` | `HnswIndex(dim, nbits=..., num_clusters=16, M=16, ef_construction=200, metric="l2", seed=100)`; capacity grows on `add`, and `resize(n)` preallocates it | +| `HnswIndex(dim, max_elements, M=16, ef_construction=200, nbits=8, metric="l2", random_seed=100)` | `HnswIndex(dim, nbits=..., num_clusters=16, M=16, ef_construction=200, metric="l2", seed=100)`; capacity grows on `add`, and `reserve(n)` preallocates it (`resize(n)` before 0.8.5) | | `HnswIndex(..., random_seed=s)` | `HnswIndex(..., seed=s)` | | `kmeans = RaBitQKMeans(dim, k)`
`kmeans.train(x)`
`index.build(x, kmeans.centroids, kmeans.assignments)` | `index.add(x)`, which trains on `x` first (since 0.8.2; in 0.8.0 and 0.8.1, call `index.train(x)` first) | | `index.build(x, centroids, cluster_ids)` | `index.set_centroids(centroids)`
`index.add(x, cluster_ids=cluster_ids)` | @@ -67,7 +71,7 @@ work if you want to run k-means yourself. to `add` on indexes created in the old form, and to the deprecated `build`, which no longer rejects more rows than `max_elements`. - **State errors.** Calling `add` with `cluster_ids`, `search`, `remove`, - `reserve` or `save` before training raises `RuntimeError("IvfIndex must be + `reserve_cluster` (`reserve` before 0.8.5) or `save` before training raises `RuntimeError("IvfIndex must be trained or loaded before ...")`; the 0.7 message said "built". Since 0.8.2, `add` without `cluster_ids` trains first. A trained index without vectors cannot be saved. `repr` shows `is_trained` instead of `is_built`. @@ -97,7 +101,8 @@ a second `add`, or `add` on a loaded index, raises `RuntimeError`, as Faiss's NSG index does. The deprecated `build` keeps its 0.7 behavior: it replaces any existing graph and, unless you passed `seed`, draws a new random seed each time. -`search` now treats `ef` like HNSW-RaBitQ: an omitted or zero `ef` uses +`search` now treats its breadth (`ef_search`; `ef` before 0.8.5) like HNSW-RaBitQ: +omitted, it uses `max(k, 64)` (`max(k, 10)` before 0.8.2), and a smaller one is raised to `k`. In 0.7, both raised `ValueError`. `add` uses every CPU by default, while the deprecated `build` keeps one thread. The seed now also drives graph construction: without `seed`, @@ -107,9 +112,10 @@ separate random seeds for the rotation and the graph. Before vectors are added, ## Files and C++ -Saved files and the `max_elements` property are unchanged. `HnswIndex.search` -without `ef` uses `max(k, 64)` since 0.8.2 (`max(k, 10)` before), which changes -its results and latency; pass `ef=` to keep the old window. Files written by 0.7 +Saved files are unchanged, and so is the `max_elements` property up to 0.8.4 (see +[From 0.8 to 0.9](#from-08-to-09)). `HnswIndex.search` +without a search breadth uses `max(k, 64)` since 0.8.2 (`max(k, 10)` before), which changes +its results and latency; pass the breadth as the third argument to keep the old window. Files written by 0.7 load as trained indexes, except empty, untrained HNSW-RaBitQ files, which need `train` before `add`. @@ -120,3 +126,30 @@ points. C++ behavior changes: since 0.8.0, saving an index without stored points throws `std::logic_error`; since 0.8.2, IVF and SymphonyQG searches pad `k` above the point count instead of throwing, and `default_training_parameters` runs 10 iterations. See the [0.8.2 notes](releases/0.8.2.md#c-changes). + +## From 0.8 to 0.9 + +0.9 gives the three index classes one name for each concept +([#232](https://github.com/VectorDB-NTU/RaBitQ-Library/issues/232)). Since 0.8.5 the +0.8 form in the first column raises a `DeprecationWarning` at your call site; 0.9 +removes it. + +| 0.8 | Use instead | Works since | +| --- | --- | --- | +| `IvfIndex.max_elements`, `SymqgIndex.max_elements` | `num_stored_points` | Every 0.8 release. The two are equal, except on an `IvfIndex` created in the 0.7 form before `build`. | +| `HnswIndex.max_elements` | `HnswIndex.capacity` | 0.8.5 | +| `HnswIndex.resize(n)` | `HnswIndex.reserve(n)`, which only grows the capacity; `resize` could also shrink it | 0.8.5 | +| `IvfIndex.reserve(cluster_id, num_points)` | `IvfIndex.reserve_cluster(cluster_id, num_points)` | 0.8.5 | +| `IvfIndex(initializer=...)`, `index.initializer` | `IvfIndex(routing=...)`, `index.routing`, with the same values | 0.8.5 | +| `search(queries, k, ef=...)` on `HnswIndex` and `SymqgIndex` | `search(queries, k, ef_search=...)` | 0.8.5; passing the breadth by position works in every release | +| `search(queries, k, nprobe, high_accuracy, num_threads)`, `search(queries, k, ef, num_threads)` | `high_accuracy=` and `num_threads=` by keyword; only `nprobe` or `ef_search` stays positional | Every 0.8 release | +| `nprobe=0`, `ef=0` for the default | `None`, or omit the argument; 0.9 raises `ValueError` for 0, while `num_threads=0` keeps meaning every available CPU | 0.8.2 | +| `HnswIndex(seed=s)` with `s` above `2**32 - 1` | A seed in `[0, 2**32 - 1]`, the range of the other two classes | Every 0.8 release | + +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. + +Two 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. And `repr(index)` prints +`capacity=` and `routing=` where it prints `max_elements=` and `initializer=`. diff --git a/docs/docs/releases/0.8.5.md b/docs/docs/releases/0.8.5.md new file mode 100644 index 00000000..e98ed564 --- /dev/null +++ b/docs/docs/releases/0.8.5.md @@ -0,0 +1,37 @@ +# RaBitQ Library 0.8.5 (unreleased) + +These notes collect what is on `main` for the next 0.8 release. It adds the names that +0.9 will use and deprecates the 0.8 spellings they replace. Every 0.8 call keeps +working, with the same results; index files are unchanged. + +## Python: names that change in 0.9 + +0.9 gives the three index classes one name for each concept (#232). This release +accepts both spellings and raises a `DeprecationWarning` for the old one, at your call +site. The [migration guide](../python_migration.md#from-08-to-09) lists each change. + +- `HnswIndex.capacity` replaces `max_elements`, and `HnswIndex.reserve(num_points)` + replaces `resize`. `reserve` only grows the capacity. +- `max_elements` is deprecated on `IvfIndex` and `SymqgIndex`; use `num_stored_points`. +- `IvfIndex.reserve_cluster(cluster_id, num_points)` replaces `reserve`. +- `IvfIndex(routing=...)` and `index.routing` replace `initializer`. +- `HnswIndex.search` and `SymqgIndex.search` take `ef_search=` instead of `ef=`. Passing + the breadth by position is unaffected. +- The `search` options after the breadth (`high_accuracy`, `num_threads`) are + keyword-only; passing them by position is deprecated. +- `nprobe=0` and `ef_search=0` for the default are deprecated; pass `None` or omit the + argument. `num_threads=0` keeps meaning every available CPU. +- `HnswIndex` seeds above `2**32 - 1` are deprecated. + +## Python: other changes + +- `IvfIndex.set_centroids` takes `num_threads` (#231). Its default follows + `OMP_NUM_THREADS`; before, building HNSW centroid routing always used every CPU. + +## Coming in 0.9 without a warning + +- `HnswIndex()` without `seed=` will draw a seed, as `IvfIndex` and `SymqgIndex` do, + instead of using 100. Pass `seed=`, and `num_threads=1` to `add`, for a reproducible + build. +- `repr(index)` will print `capacity=` and `routing=` where it prints `max_elements=` + and `initializer=`. diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index f9a7dba3..38799f7a 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -15,6 +15,7 @@ nav: # Group by minor version: nested groups stay collapsed except the current page's. - Release notes: - "0.8": + - "0.8.5 (unreleased)": releases/0.8.5.md - "0.8.4": releases/0.8.4.md - "0.8.3": releases/0.8.3.md - "0.8.2": releases/0.8.2.md diff --git a/python_bindings/__init__.py b/python_bindings/__init__.py index b84c57a5..019a1d4e 100644 --- a/python_bindings/__init__.py +++ b/python_bindings/__init__.py @@ -5,6 +5,7 @@ """ import inspect +import operator import warnings from ._rabitqlib import ( @@ -35,6 +36,29 @@ _MISSING = object() +def _is_zero(value): + """Whether an optional integer argument is one the extension reads as 0.""" + if value is None or isinstance(value, (float, str, bytes)): + return False + try: + return operator.index(value) == 0 + except TypeError: + pass + try: + # pybind11 also converts objects that only define __int__, such as + # numpy floating scalars. + return int(value) == 0 + except (TypeError, ValueError, OverflowError): + return False + + +def _exceeds_32_bits(value): + try: + return operator.index(value) > 0xFFFFFFFF + except TypeError: + return False + + def _deprecated(message): # Called from a replacement method, so the caller of that method is two up. warnings.warn(f"{message}; {_MIGRATION}", DeprecationWarning, stacklevel=3) @@ -52,7 +76,7 @@ def _bind(signature, name, args, kwargs, hint=""): def _ivf_signature( - self, dim, num_clusters, *, nbits=7, metric="l2", initializer="auto", seed=None + self, dim, num_clusters, *, nbits=7, metric="l2", routing="auto", seed=None ): ... @@ -126,7 +150,28 @@ def __init__(self, *args, **kwargs): _max_elements=arguments["max_elements"], ) return - native_init(self, **_bind(signature, "IvfIndex", (self, *args), kwargs)) + # 0.9 names the routing strategy routing; initializer is its 0.8 spelling. + initializer = kwargs.pop("initializer", _MISSING) + if initializer is not _MISSING: + if "routing" in kwargs: + raise TypeError( + "IvfIndex() got both routing and its old name initializer" + ) + _deprecated("IvfIndex(initializer=...) is deprecated; use routing=") + kwargs["routing"] = initializer + arguments = _bind(signature, "IvfIndex", (self, *args), kwargs) + arguments["initializer"] = arguments.pop("routing") + try: + native_init(self, **arguments) + except ValueError as error: + # The extension names the argument initializer; a caller who wrote + # routing= gets that name back. + message = str(error) + if initializer is not _MISSING or not message.startswith( + "initializer must be" + ): + raise + raise ValueError("routing" + message[len("initializer") :]) from None __init__.__doc__ = cls.__doc__ __init__.__signature__ = signature @@ -171,7 +216,13 @@ def __init__(self, *args, **kwargs): ) _deprecated("HnswIndex(random_seed=...) is deprecated; use seed=") kwargs["seed"] = random_seed - native_init(self, **_bind(signature, "HnswIndex", (self, *args), kwargs)) + arguments = _bind(signature, "HnswIndex", (self, *args), kwargs) + if _exceeds_32_bits(arguments["seed"]): + _deprecated( + "HnswIndex seeds above 2**32 - 1 are deprecated; 0.9 accepts " + "[0, 2**32 - 1], as the other indexes do" + ) + native_init(self, **arguments) __init__.__doc__ = cls.__doc__ __init__.__signature__ = signature @@ -277,6 +328,7 @@ def _symqg_nbits(quantization_bits): def _patch_symqg(cls): native_init = cls.__init__ + native_search = cls.search signature = inspect.signature(_symqg_signature) legacy_signature = inspect.signature(_symqg_legacy_signature) @@ -345,7 +397,7 @@ def build(self, data, ef_construction, num_threads=1, init="pipnn"): def search_batch(self, queries, k, ef, num_threads=1): """Deprecated since 0.8: the same as search(); use search().""" _deprecated("SymqgIndex.search_batch() is deprecated; use search()") - return self.search(queries, k, ef, num_threads) + return native_search(self, queries, k, ef, num_threads) def quantization_bits(self): """Deprecated since 0.8: storage bits with 0 for raw vectors; use nbits.""" @@ -379,6 +431,305 @@ def is_built(self): # --- end of the 0.8 compatibility layer ------------------------------------- +# --- 0.9 names; the 0.8 spellings they replace are removed in 0.9 ----------- +# 0.9 renames these members and arguments (issue #232). This release accepts both +# spellings and warns on the old one. The extension classes still carry the 0.8 +# names, so the new ones are added here, again by replacing members on the classes. + + +def _member(cls, function, name=None): + """function named as a member of cls, so errors and help() show the class.""" + if name is not None: + function.__name__ = name + function.__qualname__ = f"{cls.__name__}.{function.__name__}" + function.__module__ = cls.__module__ + return function + + +def _renamed_property(cls, old, new, new_doc, replacement): + """Add property new for the native property old, which then warns.""" + native = vars(cls)[old] + name = cls.__name__ + + def current(self): + return native.__get__(self, cls) + + def former(self): + _deprecated(f"{name}.{old} is deprecated; use {replacement}") + return native.__get__(self, cls) + + _member(cls, former, old) + if new is not None: + _member(cls, current, new) + setattr(cls, new, property(current, doc=new_doc)) + setattr( + cls, + old, + property(former, doc=f"Deprecated since 0.8.5: use {replacement}."), + ) + + +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.", + ), +) +# --- end of the 0.9 names ---------------------------------------------------- + + class _KMeans: """Shared result handling for the two clustering methods.""" diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi index fe59efbd..a97df638 100644 --- a/python_bindings/__init__.pyi +++ b/python_bindings/__init__.pyi @@ -29,7 +29,7 @@ __all__ = [ _Path: TypeAlias = str | bytes | bytearray | PathLike[str] | PathLike[bytes] _Metric: TypeAlias = Literal["l2", "ip", "innerproduct"] -_Initializer: TypeAlias = Literal["auto", "flat", "flat_rabitq", "hnsw"] +_Routing: TypeAlias = Literal["auto", "flat", "flat_rabitq", "hnsw"] _QGInit: TypeAlias = Literal["pipnn", "random"] # Rank, ID ranges and Python bool (an int subtype) are validated at runtime. _IntegerIds: TypeAlias = npt.NDArray[np.integer[Any]] | Sequence[int | np.integer[Any]] @@ -88,8 +88,9 @@ class IvfIndex: metric : {'l2', 'ip', 'innerproduct'}, optional Squared L2 or inner-product distance. Default is 'l2'. Vectors are not automatically normalized for cosine similarity. - initializer : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional - Centroid routing strategy. Default is 'auto'. + routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional + Centroid routing strategy. Default is 'auto'. Named initializer before + 0.8.5. seed : int, optional Rotation seed in [0, 2**32 - 1], also the initial cp.seed. None (default) draws one at random; the seed property reports it. @@ -126,7 +127,7 @@ class IvfIndex: *, nbits: SupportsIndex = 7, metric: _Metric = "l2", - initializer: _Initializer = "auto", + routing: _Routing = "auto", seed: SupportsIndex | None = None, ) -> None: """An approximate nearest-neighbor index using IVF. @@ -143,8 +144,9 @@ class IvfIndex: metric : {'l2', 'ip', 'innerproduct'}, optional Squared L2 or inner-product distance. Default is 'l2'. Vectors are not automatically normalized for cosine similarity. - initializer : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional - Centroid routing strategy. Default is 'auto'. + routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional + Centroid routing strategy. Default is 'auto'. Named initializer before + 0.8.5. seed : int, optional Rotation seed in [0, 2**32 - 1], also the initial cp.seed. None (default) draws one at random; the seed property reports it. @@ -173,7 +175,19 @@ class IvfIndex: num_clusters: SupportsIndex, nbits: SupportsIndex, metric: _Metric = "l2", - initializer: _Initializer = "auto", + initializer: _Routing = "auto", + ) -> None: ... + @overload + @deprecated("IvfIndex(initializer=...) is deprecated since 0.8.5; use routing=") + def __init__( + self, + dim: SupportsIndex, + num_clusters: SupportsIndex, + *, + nbits: SupportsIndex = 7, + metric: _Metric = "l2", + initializer: _Routing, + seed: SupportsIndex | None = None, ) -> None: ... def __repr__(self) -> str: """Return a one-line summary of configuration, counts and training state.""" @@ -186,8 +200,11 @@ class IvfIndex: """Original vector dimension.""" @property + @deprecated( + "IvfIndex.max_elements is deprecated since 0.8.5; use num_stored_points" + ) def max_elements(self) -> int: - """Logical capacity: stored points, or the build row count of a 0.7-form index before build.""" + """Deprecated since 0.8.5: use num_stored_points.""" @property def num_points(self) -> int: @@ -329,7 +346,7 @@ class IvfIndex: float32; a copy may be made. cluster_ids : array_like of int, shape (n,), optional Keyword-only. Existing centroid IDs. None routes each vector using the - index's configured centroid initializer; routing may be approximate. + index's configured routing strategy, which may be approximate. Centroids do not move. num_threads : int, optional Keyword-only. Worker count. None (default) and 0 select the available @@ -351,7 +368,7 @@ class IvfIndex: untrained index raises RuntimeError, as does add on an index created with max_elements, which build fills. If the call fails, the index stays untrained and empty. Batch additions to reduce repeated cluster copying; - reserve can preallocate room. Passing the options positionally is + reserve_cluster can preallocate room. Passing the options positionally is deprecated. """ @overload @@ -385,11 +402,13 @@ class IvfIndex: Removal does not reclaim storage and cannot be undone. """ + @overload def search( self, queries: npt.ArrayLike, k: SupportsIndex, nprobe: SupportsIndex | None = None, + *, high_accuracy: bool | np.bool_ | None = None, num_threads: SupportsIndex | None = None, ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: @@ -404,14 +423,17 @@ class IvfIndex: Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. nprobe : int, optional - Number of clusters to probe, capped at num_clusters. None (default) and - 0 select num_clusters / 16, rounded to the nearest integer and at least 1. + Number of clusters to probe, capped at num_clusters. None (default) + selects num_clusters / 16, rounded to the nearest integer and at least + 1; 0 does the same and is deprecated since 0.8.5. high_accuracy : bool, optional + Keyword-only; passing it by position is deprecated since 0.8.5. Enable HACC. None (default) selects it for 4-9 bits and standard FastScan otherwise. Raw storage uses standard FastScan. num_threads : int, optional - Worker count. None (default) selects 1; 0 selects the available CPU - count, capped by OMP_NUM_THREADS. + Keyword-only; passing it by position is deprecated since 0.8.5. Worker + count. None (default) selects 1; 0 selects the available CPU count, + capped by OMP_NUM_THREADS. Returns ------- @@ -428,7 +450,18 @@ class IvfIndex: np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers. """ - + @overload + @deprecated( + "Passing high_accuracy or num_threads to IvfIndex.search() by position is deprecated since 0.8.5; use keywords" + ) + def search( + self, + queries: npt.ArrayLike, + k: SupportsIndex, + nprobe: SupportsIndex | None, + high_accuracy: bool | np.bool_ | None, + num_threads: SupportsIndex | None = ..., + ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: ... def save(self, path: _Path) -> None: """Save an index with stored vectors to disk. @@ -461,10 +494,17 @@ class IvfIndex: """ @property - def initializer(self) -> _Initializer: - """Resolved centroid routing strategy.""" + def routing(self) -> _Routing: + """Resolved centroid routing strategy. Named initializer before 0.8.5.""" - def reserve(self, cluster_id: SupportsIndex, num_points: SupportsIndex) -> None: + @property + @deprecated("IvfIndex.initializer is deprecated since 0.8.5; use routing") + def initializer(self) -> _Routing: + """Deprecated since 0.8.5: use routing.""" + + def reserve_cluster( + self, cluster_id: SupportsIndex, num_points: SupportsIndex + ) -> None: """Preallocate storage for a cluster. Parameters @@ -472,13 +512,19 @@ class IvfIndex: cluster_id : int Cluster ID in [0, num_clusters). num_points : int - Nonnegative capacity to reserve for this cluster. + Nonnegative capacity to reserve for this cluster: the total number + of points it can hold, including its current ones. Notes ----- - Requires a trained or loaded index. Reserved room is not saved. + Requires a trained or loaded index. Reserved room is not saved. Named + reserve before 0.8.5. """ + @deprecated("IvfIndex.reserve() is deprecated since 0.8.5; use reserve_cluster()") + def reserve(self, cluster_id: SupportsIndex, num_points: SupportsIndex) -> None: + """Deprecated since 0.8.5: the same as reserve_cluster(); use reserve_cluster().""" + class HnswIndex: """An approximate nearest-neighbor index using HNSW. @@ -502,7 +548,8 @@ class HnswIndex: Vectors are not automatically normalized for cosine similarity. seed : int, optional Keyword-only. Graph and rotation seed, also the initial cp.seed (its low - 32 bits). Default is 100. + 32 bits), in [0, 2**32 - 1]; larger values are deprecated since 0.8.5. + Default is 100. Notes ----- @@ -510,7 +557,7 @@ class HnswIndex: on a sample, or set_centroids, first to choose the training data or the centroids. Loaded indexes are trained, except empty files saved untrained by 0.7. Capacity grows automatically - on add; resize can preallocate it. Concurrent reads are supported; an + on add; reserve can preallocate it. Concurrent reads are supported; an overlapping mutation raises RuntimeError. Data, centroids and queries must be finite float32 values within the index coordinate range; other values raise ValueError. @@ -565,7 +612,8 @@ class HnswIndex: Vectors are not automatically normalized for cosine similarity. seed : int, optional Keyword-only. Graph and rotation seed, also the initial cp.seed (its low - 32 bits). Default is 100. + 32 bits), in [0, 2**32 - 1]; larger values are deprecated since 0.8.5. + Default is 100. Notes ----- @@ -573,7 +621,7 @@ class HnswIndex: on a sample, or set_centroids, first to choose the training data or the centroids. Loaded indexes are trained, except empty files saved untrained by 0.7. Capacity grows automatically - on add; resize can preallocate it. Concurrent reads are supported; an + on add; reserve can preallocate it. Concurrent reads are supported; an overlapping mutation raises RuntimeError. Data, centroids and queries must be finite float32 values within the index coordinate range; other values raise ValueError. @@ -621,8 +669,13 @@ class HnswIndex: """Original vector dimension.""" @property + def capacity(self) -> int: + """Current storage capacity, in stored points. Named max_elements before 0.8.5.""" + + @property + @deprecated("HnswIndex.max_elements is deprecated since 0.8.5; use capacity") def max_elements(self) -> int: - """Current storage capacity.""" + """Deprecated since 0.8.5: use capacity.""" @property def num_points(self) -> int: @@ -822,11 +875,13 @@ class HnswIndex: Removal does not reclaim storage and cannot be undone. """ + @overload def search( self, queries: npt.ArrayLike, k: SupportsIndex, - ef: SupportsIndex | None = None, + ef_search: SupportsIndex | None = None, + *, num_threads: SupportsIndex | None = None, ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: """Search a batch of query vectors. @@ -839,12 +894,14 @@ class HnswIndex: k : int Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. - ef : int, optional - Search breadth. None or 0 (default) selects max(k, 64); values above the stored - point count are clamped. + ef_search : int, optional + Search breadth. None (default) selects max(k, 64); values above the stored + point count are clamped. 0 selects the default and is deprecated since + 0.8.5. Named ef before 0.8.5. num_threads : int, optional - Worker count. None (default) selects 1; 0 selects the available CPU - count, capped by OMP_NUM_THREADS. + Keyword-only; passing it by position is deprecated since 0.8.5. Worker + count. None (default) selects 1; 0 selects the available CPU count, + capped by OMP_NUM_THREADS. Returns ------- @@ -861,7 +918,27 @@ class HnswIndex: np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers. """ - + @overload + @deprecated("HnswIndex.search(ef=...) is deprecated since 0.8.5; use ef_search=") + def search( + self, + queries: npt.ArrayLike, + k: SupportsIndex, + *, + ef: SupportsIndex | None, + num_threads: SupportsIndex | None = None, + ) -> tuple[npt.NDArray[np.uint32], 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.uint32], npt.NDArray[np.float32]]: ... def save(self, path: _Path) -> None: """Save an index with stored vectors to disk. @@ -893,15 +970,28 @@ class HnswIndex: A trained index ready for search. """ - def resize(self, max_elements: SupportsIndex) -> None: - """Change the storage capacity, for example to preallocate before add. + def reserve(self, num_points: SupportsIndex) -> None: + """Preallocate room for at least num_points stored points. Parameters ---------- - max_elements : int - New capacity; must be at least num_stored_points. + num_points : int + Nonnegative number of stored points to make room for, including the + current ones. + + Notes + ----- + Capacity only grows: a value at or below capacity changes nothing. add + also grows the capacity when needed, so reserve is an optimization. """ + @deprecated( + "HnswIndex.resize() is deprecated since 0.8.5; use reserve(), which only " + "grows the capacity" + ) + def resize(self, max_elements: SupportsIndex) -> None: + """Deprecated since 0.8.5: change the capacity; use reserve(), which only grows it.""" + class SymqgIndex: """An approximate nearest-neighbor index using SymphonyQG. @@ -1040,8 +1130,11 @@ class SymqgIndex: """Original vector dimension.""" @property + @deprecated( + "SymqgIndex.max_elements is deprecated since 0.8.5; use num_stored_points" + ) def max_elements(self) -> int: - """Current storage capacity.""" + """Deprecated since 0.8.5: use num_stored_points.""" @property def num_points(self) -> int: @@ -1171,11 +1264,13 @@ class SymqgIndex: Graph initialization method. Default is 'pipnn'. """ + @overload def search( self, queries: npt.ArrayLike, k: SupportsIndex, - ef: SupportsIndex | None = None, + ef_search: SupportsIndex | None = None, + *, num_threads: SupportsIndex | None = None, ) -> tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]]: """Search a batch of query vectors. @@ -1188,12 +1283,14 @@ class SymqgIndex: k : int Number of neighbors requested, at least 1. It may exceed the number of points; slots without a neighbor are padded as described below. - ef : int, optional - Search breadth. None or 0 (default) selects max(k, 64); smaller values - are raised to k. + ef_search : int, optional + Search breadth. None (default) selects max(k, 64); smaller values + are raised to k. 0 selects the default and is deprecated since 0.8.5. + Named ef before 0.8.5. num_threads : int, optional - Worker count. None (default) selects 1; 0 selects the available CPU - count, capped by OMP_NUM_THREADS. + Keyword-only; passing it by position is deprecated since 0.8.5. Worker + count. None (default) selects 1; 0 selects the available CPU count, + capped by OMP_NUM_THREADS. Returns ------- @@ -1210,7 +1307,27 @@ class SymqgIndex: np.isfinite(distances) to find them. Array shapes and value ranges are checked at runtime, not by static type checkers. """ - + @overload + @deprecated("SymqgIndex.search(ef=...) is deprecated since 0.8.5; use ef_search=") + def search( + self, + queries: npt.ArrayLike, + k: SupportsIndex, + *, + ef: SupportsIndex | None, + num_threads: SupportsIndex | None = None, + ) -> tuple[npt.NDArray[np.uint32], 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.uint32], npt.NDArray[np.float32]]: ... @deprecated("SymqgIndex.search_batch() is deprecated since 0.8; use search()") def search_batch( self, diff --git a/sample/python/hnsw_rabitq_querying.py b/sample/python/hnsw_rabitq_querying.py index 7f276c1c..f8132140 100644 --- a/sample/python/hnsw_rabitq_querying.py +++ b/sample/python/hnsw_rabitq_querying.py @@ -37,7 +37,7 @@ def main(args=None) -> None: for r in range(args.test_rounds): t0 = perf_counter() ids, _ = idx.search( - queries, k=args.topk, ef=ef, num_threads=args.num_threads + queries, k=args.topk, ef_search=ef, num_threads=args.num_threads ) elapsed = perf_counter() - t0 # seconds diff --git a/sample/python/symqg_querying.py b/sample/python/symqg_querying.py index 035282a4..91750333 100644 --- a/sample/python/symqg_querying.py +++ b/sample/python/symqg_querying.py @@ -38,7 +38,7 @@ def main(args=None) -> None: for r in range(args.test_rounds): t0 = perf_counter() ids, _ = idx.search( - queries, k=args.topk, ef=ef, num_threads=args.num_threads + queries, k=args.topk, ef_search=ef, num_threads=args.num_threads ) elapsed = perf_counter() - t0 # seconds diff --git a/tests/python/test_compat_09.py b/tests/python/test_compat_09.py new file mode 100644 index 00000000..9907523f --- /dev/null +++ b/tests/python/test_compat_09.py @@ -0,0 +1,362 @@ +"""The 0.8 spellings that 0.9 renames: both work in 0.8.5, and the old one warns.""" + +import inspect +import warnings + +import numpy as np +import pytest +from conftest import DIM +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 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__ diff --git a/tests/python/test_editor_support.py b/tests/python/test_editor_support.py index eb14d8c4..4d937fb7 100644 --- a/tests/python/test_editor_support.py +++ b/tests/python/test_editor_support.py @@ -198,7 +198,7 @@ def test_documented_search_result_types(kind): if kind == "symqg": index = rabitqlib.SymqgIndex(64, ef_construction=40) index.add(data) - result = index.search(data[:2], 3, ef=20) + result = index.search(data[:2], 3, ef_search=20) else: if kind == "ivf": index = rabitqlib.IvfIndex(64, 2, nbits=4) @@ -209,7 +209,7 @@ def test_documented_search_result_types(kind): if isinstance(index, rabitqlib.IvfIndex): result = index.search(data[:2], 3, nprobe=2) else: - result = index.search(data[:2], 3, ef=20) + result = index.search(data[:2], 3, ef_search=20) ids, distances = result assert ids.shape == distances.shape == (2, 3) assert ids.dtype == np.uint32 diff --git a/tests/python/test_examples.py b/tests/python/test_examples.py index a66655ac..b988eb28 100644 --- a/tests/python/test_examples.py +++ b/tests/python/test_examples.py @@ -197,7 +197,7 @@ def check_saved_index_and_query(tmp_path, kind, metric, data): index_type = {"ivf": IvfIndex, "hnsw": HnswIndex, "symqg": SymqgIndex}[kind] index = index_type.load(str(index_path)) queries = data[:4].copy() - search_args = {"nprobe": 2} if kind == "ivf" else {"ef": len(data)} + search_args = {"nprobe": 2} if kind == "ivf" else {"ef_search": len(data)} ids, distances = index.search(queries, k=5, num_threads=2, **search_args) assert index.metric == metric if kind == "ivf": diff --git a/tests/python/test_ivf_initializers.py b/tests/python/test_ivf_initializers.py index 1afdf8b0..09c45ff8 100644 --- a/tests/python/test_ivf_initializers.py +++ b/tests/python/test_ivf_initializers.py @@ -245,8 +245,8 @@ def test_legacy_formats_infer_historical_initializer( def test_initializer_rejects_invalid_argument(): - with pytest.raises(ValueError, match="initializer must be"): - IvfIndex(64, 1, nbits=1, initializer="unknown") + with pytest.raises(ValueError, match="^routing must be"): + IvfIndex(64, 1, nbits=1, routing="unknown") @pytest.mark.parametrize("initializer", ["flat", "flat_rabitq"]) diff --git a/tests/python/test_symqg_api.py b/tests/python/test_symqg_api.py index 769cbe42..dbb1f2c5 100644 --- a/tests/python/test_symqg_api.py +++ b/tests/python/test_symqg_api.py @@ -161,8 +161,7 @@ def test_search_ef_defaults_to_max_of_k_and_64_and_is_raised_to_k(base_data): queries = base_data[:10] for k, implied_ef in ((3, 64), (80, 80)): expected = index.search(queries, k, implied_ef) - for ef in (None, 0): - actual = index.search(queries, k, ef) + for actual in (index.search(queries, k), index.search(queries, k, None)): np.testing.assert_array_equal(actual[0], expected[0]) np.testing.assert_array_equal(actual[1], expected[1]) np.testing.assert_array_equal( diff --git a/tests/python/test_train_api.py b/tests/python/test_train_api.py index f80e062b..476b627f 100644 --- a/tests/python/test_train_api.py +++ b/tests/python/test_train_api.py @@ -119,14 +119,14 @@ def test_ivf_seed_range_and_random_default(): @pytest.mark.parametrize("metric", ["l2", "ip"]) def test_cp_defaults_follow_metric_and_seed(metric): ivf = IvfIndex(DIM, 4, nbits=4, metric=metric, seed=11) - hnsw = HnswIndex(DIM, nbits=4, metric=metric, seed=2**40 + 5) + hnsw = HnswIndex(DIM, nbits=4, metric=metric, seed=5) for index, seed in ((ivf, 11), (hnsw, 5)): assert index.cp.niter == 10 assert index.cp.max_points_per_centroid == 256 assert index.cp.spherical is (metric == "ip") assert index.cp.seed == seed assert index.cp.num_threads == 0 - assert hnsw.seed == 2**40 + 5 + assert hnsw.seed == 5 # cp is the index's own object: changes persist, and assignment copies. ivf.cp.niter = 3 assert ivf.cp.niter == 3 @@ -252,7 +252,7 @@ def test_operations_before_training_raise_and_change_nothing(kind, base_data, tm "save": lambda: index.save(tmp_path / "untrained.index"), } if kind == "ivf": - operations["reserve"] = lambda: index.reserve(0, 10) + operations["reserve_cluster"] = lambda: index.reserve_cluster(0, 10) for operation, call in operations.items(): with pytest.raises( RuntimeError, match=f"^{name} must be trained or loaded before {operation}$" @@ -327,29 +327,31 @@ def test_ivf_point_count_index_cannot_be_trained(base_data): index.train(base_data) with pytest.raises(RuntimeError, match=message): index.set_centroids(base_data[:4]) - assert index.max_elements == N_VECTORS + assert index.num_stored_points == 0 + with pytest.warns(DeprecationWarning): + assert index.max_elements == N_VECTORS # the declared row count is kept -def test_hnsw_capacity_grows_and_resize_preallocates(base_data): +def test_hnsw_capacity_grows_and_reserve_preallocates(base_data): index = HnswIndex(DIM, nbits=4, num_clusters=4) - assert index.max_elements == 1 + assert index.capacity == 1 index.train(base_data) index.add(base_data[:100]) - assert index.max_elements == 100 + assert index.capacity == 100 index.add(base_data[100:110]) - assert index.max_elements == 200 # doubled + assert index.capacity == 200 # doubled preallocated = HnswIndex(DIM, nbits=4, num_clusters=4) - preallocated.resize(1000) + preallocated.reserve(1000) preallocated.train(base_data) preallocated.add(base_data) - assert preallocated.max_elements == 1000 + assert preallocated.capacity == 1000 def test_hnsw_search_ef_none_means_the_default(base_data): index = HnswIndex(DIM, nbits=4, num_clusters=4) index.train(base_data) index.add(base_data, num_threads=1) - expected = index.search(base_data[:10], 5, 0) + expected = index.search(base_data[:10], 5, 64) for found in ( index.search(base_data[:10], 5, None), index.search(base_data[:10], 5), @@ -366,7 +368,7 @@ def test_hnsw_failed_add_keeps_the_capacity(base_data): bad[150, 0] = np.nan with pytest.raises(ValueError, match="must contain only finite values"): index.add(bad) - assert index.max_elements == 100 + assert index.capacity == 100 assert len(index) == 100 @@ -443,7 +445,6 @@ def test_ivf_nprobe_defaults_to_a_sixteenth_of_the_clusters(base_data): for found in (index.search(queries, 5), index.search(queries, 5, None)): np.testing.assert_array_equal(found[0], expected[0]) np.testing.assert_array_equal(found[1], expected[1]) - np.testing.assert_array_equal(index.search(queries, 5, 0)[0], expected[0]) small = IvfIndex(DIM, 4, nbits=4, seed=3) small.add(base_data) np.testing.assert_array_equal( @@ -458,7 +459,7 @@ def test_num_threads_none_selects_the_defaults(kind, base_data): found = ( index.search(base_data[:5], 3, None, num_threads=None) if kind == "hnsw" - else index.search(base_data[:5], 3, None, None, None) + else index.search(base_data[:5], 3, None, high_accuracy=None, num_threads=None) ) assert found[0].shape == (5, 3) @@ -480,8 +481,8 @@ def test_package_reports_its_version(): "options", [ {"nbits": 32}, - {"initializer": "flat_rabitq"}, - {"initializer": "hnsw"}, + {"routing": "flat_rabitq"}, + {"routing": "hnsw"}, {"niter": 3, "max_points_per_centroid": 64}, ], ) @@ -520,11 +521,11 @@ def test_ivf_first_add_uses_the_drawn_seed(base_data, tmp_path): def test_hnsw_first_add_keeps_a_preallocated_capacity(base_data, tmp_path): implicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50) - implicit.resize(2 * N_VECTORS) + implicit.reserve(2 * N_VECTORS) implicit.add(base_data, num_threads=1) - assert implicit.max_elements == 2 * N_VECTORS + assert implicit.capacity == 2 * N_VECTORS explicit = HnswIndex(DIM, num_clusters=4, M=8, ef_construction=50) - explicit.resize(2 * N_VECTORS) + explicit.reserve(2 * N_VECTORS) explicit.train(base_data) explicit.add(base_data, num_threads=1) assert saved_bytes(implicit, tmp_path / "implicit.index") == saved_bytes( diff --git a/tests/python/typing/public_api.py b/tests/python/typing/public_api.py index 4d2a05cd..ad080254 100644 --- a/tests/python/typing/public_api.py +++ b/tests/python/typing/public_api.py @@ -59,8 +59,8 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: assert_type(IvfIndex.load("index.bin"), IvfIndex) assert_type(HnswIndex.load("index.bin"), HnswIndex) assert_type(SymqgIndex.load("index.bin"), SymqgIndex) - ivf.reserve(0, 128) - hnsw.resize(256) + ivf.reserve_cluster(0, 128) + hnsw.reserve(256) qg = QGKMeans(64, 40, niter=2, quantization_bits=4) flat = RaBitQKMeans(64, 2, final_assignment=FinalAssignmentMode.Exact) assert_type(qg.cp, QGKMeansParameters) @@ -79,11 +79,11 @@ 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], QGKMeansIterationStats) qg.cp.final_assignment = FinalAssignmentMode.Approximate - ivf.search(x, "five", 2) # type: ignore[arg-type] + ivf.search(x, "five", 2) # type: ignore[call-overload] ivf.dim = 16 # type: ignore[misc] qg.cp.niter = "two" # type: ignore[assignment] RaBitQKMeans(64, 2, graph_degree=32) # type: ignore[call-arg] - hnsw.search(x, 5, nprobe=2) # type: ignore[call-arg] + hnsw.search(x, 5, nprobe=2) # type: ignore[call-overload] IvfIndex(64, 2, 4) # type: ignore[call-overload] hnsw.train(x, 1) # type: ignore[call-arg] @@ -131,14 +131,14 @@ def check_numpy_scalars() -> None: ) assert_type(index.dim, int) assert type(index.dim) is int - ivf.reserve(np.uint32(0), np.int64(100)) + ivf.reserve_cluster(np.uint32(0), np.int64(100)) ids, distances = ivf.search( x[:2], k=np.int64(3), nprobe=np.int64(1), high_accuracy=np.bool_(True) ) assert_type(ids, npt.NDArray[np.uint32]) assert_type(distances, npt.NDArray[np.float32]) - hnsw.resize(np.int64(100)) - hnsw.search(x[:2], np.int64(3), ef=np.int64(10)) + hnsw.reserve(np.int64(100)) + hnsw.search(x[:2], np.int64(3), ef_search=np.int64(10)) graph.add(x, num_threads=np.int64(1)) graph.search(x[:2], np.int64(3), np.int64(10)) flat = RaBitQKMeans( @@ -195,14 +195,14 @@ def check_input_contracts() -> None: ivf = IvfIndex(64, 1, nbits=4, metric=metric) HnswIndex(64, nbits=4, metric=metric) SymqgIndex(64, metric=metric) - initializers: tuple[Literal["auto", "flat", "flat_rabitq", "hnsw"], ...] = ( + routings: tuple[Literal["auto", "flat", "flat_rabitq", "hnsw"], ...] = ( "auto", "flat", "flat_rabitq", "hnsw", ) - for initializer in initializers: - IvfIndex(64, 1, nbits=4, initializer=initializer) + for routing in routings: + IvfIndex(64, 1, nbits=4, routing=routing) for ids in (signed, unsigned, [0] * 80, (0,) * 80): ivf = IvfIndex(64, 1, nbits=4) ivf.set_centroids(centroids, num_threads=1) @@ -226,7 +226,7 @@ def check_input_contracts() -> None: graph = SymqgIndex(64, ef_construction=40, init=init) graph.add(x) # Returned option values must be usable as inputs without casts. - IvfIndex(64, 1, nbits=4, metric=ivf.metric, initializer=ivf.initializer) + IvfIndex(64, 1, nbits=4, metric=ivf.metric, routing=ivf.routing) def reject_invalid_inputs(x: npt.NDArray[np.float32]) -> None: @@ -239,7 +239,7 @@ def reject_invalid_inputs(x: npt.NDArray[np.float32]) -> None: IvfIndex(64, 1, nbits=4, metric="cosine") # type: ignore[call-overload] HnswIndex(64, nbits=4, metric="L2") # type: ignore[call-overload] SymqgIndex(64, metric="inner_product") # type: ignore[call-overload] - IvfIndex(64, 1, nbits=4, initializer="flat_rabit") # type: ignore[call-overload] + IvfIndex(64, 1, nbits=4, routing="flat_rabit") # type: ignore[call-overload] SymqgIndex(64, init="pippn") # type: ignore[call-overload] graph.add(x, 1) # type: ignore[call-arg] ivf.add(x, cluster_ids=[0.0] * 80) # type: ignore[list-item] diff --git a/tests/test_mypy.py b/tests/test_mypy.py index 430f2322..d4914806 100644 --- a/tests/test_mypy.py +++ b/tests/test_mypy.py @@ -58,8 +58,10 @@ def test_static_public_usage(tmp_path): assert error_lines == expected_lines, result.stdout -# Each 0.7 call form the compatibility layer accepts is marked deprecated in the -# stubs, so editors flag it while it still type-checks. +# Each 0.7 call form the compatibility layer accepts, and each 0.8 spelling that 0.9 +# renames, is marked deprecated in the stubs, so editors flag it while it still +# type-checks. Deprecations that depend on a value (a breadth of 0, a seed above +# 2**32 - 1) cannot be declared and are documented in the docstrings only. DEPRECATED_USAGE = """\ import numpy as np from rabitqlib import HnswIndex, IvfIndex, SymqgIndex @@ -79,6 +81,18 @@ def test_static_public_usage(tmp_path): graph.search_batch(x, 5, 32) bits = graph.quantization_bits built = graph.is_built +routed = IvfIndex(64, 1, initializer="flat") +strategy = routed.initializer +stored = routed.max_elements +routed.reserve(0, 8) +routed.search(x, 5, 1, None) +capacity = seeded.max_elements +seeded.resize(128) +seeded.search(x, 5, ef=32) +seeded.search(x, 5, 32, 1) +count = graph.max_elements +graph.search(x, 5, ef=32) +graph.search(x, 5, 32, 1) """ @@ -108,4 +122,4 @@ def test_deprecated_forms_are_flagged(tmp_path): rf"{re.escape(str(usage))}:(\d+): error: .*\[deprecated\]", result.stdout ) } - assert flagged == set(range(6, 19)), result.stdout + assert flagged == set(range(6, 31)), result.stdout From 421cf2caa41e74ea398b9695b6ca92067e164b3e Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Sat, 14 Nov 2026 12:01:06 +0800 Subject: [PATCH 2/2] fix(python): name the renamed properties on Python 3.11 and 3.12 A property assigned to a class after its creation does not get __set_name__, and before Python 3.13 it then reports errors without its name: assigning to the read-only routing property raised "property of 'IvfIndex' object has no setter". CI's wheel tests on CPython 3.11 caught this through test_new_members_are_named_after_their_class; the local environment is 3.13, where the name falls back to the getter's name. Call __set_name__ when adding the properties, so every supported Python names them. --- python_bindings/__init__.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/python_bindings/__init__.py b/python_bindings/__init__.py index 019a1d4e..cb76d254 100644 --- a/python_bindings/__init__.py +++ b/python_bindings/__init__.py @@ -461,12 +461,17 @@ def former(self): _member(cls, former, old) if new is not None: _member(cls, current, new) - setattr(cls, new, property(current, doc=new_doc)) - setattr( - cls, - old, - property(former, doc=f"Deprecated since 0.8.5: use {replacement}."), - ) + _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): + """Assign a read-only property, named as a class body would name it.""" + member = property(getter, 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):