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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions benchmarks/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}")


Expand Down
5 changes: 3 additions & 2 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
19 changes: 10 additions & 9 deletions docs/docs/index/hnsw.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
```
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down
21 changes: 12 additions & 9 deletions docs/docs/index/ivf.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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++
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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;
Expand All @@ -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.

Expand Down
8 changes: 4 additions & 4 deletions docs/docs/index/qg.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
23 changes: 14 additions & 9 deletions docs/docs/index/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand All @@ -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
Expand Down Expand Up @@ -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")`.
Expand All @@ -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
Expand Down
Loading
Loading