diff --git a/.clang-tidy b/.clang-tidy
index 6ec0d237..63dd90a9 100644
--- a/.clang-tidy
+++ b/.clang-tidy
@@ -54,6 +54,8 @@ CheckOptions:
readability-identifier-naming.ProtectedMemberCase: lower_case
readability-identifier-naming.ProtectedMemberSuffix: '_'
readability-identifier-naming.PublicMemberCase: lower_case
+ # HnswOptions::M, the same HNSW graph-degree setting.
+ readability-identifier-naming.PublicMemberIgnoredRegexp: '^M$'
# Functions, types, namespaces, constants and macros follow AGENTS.md. The
# ignored names are retained public API or names the standard library requires.
readability-identifier-naming.FunctionCase: lower_case
@@ -65,7 +67,7 @@ CheckOptions:
readability-identifier-naming.StructIgnoredRegexp: '^rebind$'
readability-identifier-naming.EnumCase: CamelCase
readability-identifier-naming.EnumConstantCase: CamelCase
- readability-identifier-naming.EnumConstantIgnoredRegexp: '^(METRIC_L2|METRIC_IP|RECONSTRUCTION|UNBIASED_ESTIMATION|PLAIN)$'
+ readability-identifier-naming.EnumConstantIgnoredRegexp: '^(METRIC_L2|METRIC_IP|METRIC_COSINE|RECONSTRUCTION|UNBIASED_ESTIMATION|PLAIN)$'
readability-identifier-naming.TypeAliasCase: CamelCase
readability-identifier-naming.TypeAliasIgnoredRegexp: '^(value_type|pointer|reference|difference_type|iterator_category|is_always_equal|other|maxheap|minheap|ex_ipfunc)$'
readability-identifier-naming.TypedefCase: CamelCase
diff --git a/.github/release.yml b/.github/release.yml
index 98db5107..a393bb93 100644
--- a/.github/release.yml
+++ b/.github/release.yml
@@ -5,6 +5,10 @@ changelog:
- invalid
categories:
+ - title: Breaking changes
+ labels:
+ - release:breaking
+
- title: Added
labels:
- release:added
diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml
index b2526230..2e6f10ea 100644
--- a/.github/workflows/python.yml
+++ b/.github/workflows/python.yml
@@ -4,7 +4,7 @@ on:
push:
branches: ["main", "master"]
pull_request:
- branches: ["main", "master"]
+ branches: ["main", "master", "dev/0.9"]
concurrency:
group: ${{ github.event.pull_request.number || github.sha }}-${{ github.workflow }}
diff --git a/CMakeLists.txt b/CMakeLists.txt
index eb24ddd3..35f155e6 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.20)
-project(RaBitQLib VERSION 0.8.5 LANGUAGES CXX)
+project(RaBitQLib VERSION 0.9.0 LANGUAGES CXX)
include(CMakePackageConfigHelpers)
include(GNUInstallDirs)
@@ -84,6 +84,7 @@ endfunction()
set(RABITQ_CORE_SOURCES
src/core/api.cpp
+ src/core/blob.cpp
src/core/fast_scale_table.cpp
src/core/provisional.cpp
src/utils/cpu_features.cpp
@@ -247,12 +248,16 @@ if(RABITQ_BUILD_FASTSCAN)
endif()
if(RABITQ_BUILD_INDEX)
add_library(rabitq_index STATIC
+ src/index/format2.cpp
src/index/hnsw.cpp
+ src/index/hnsw_index.cpp
src/index/ivf.cpp
+ src/index/ivf_index.cpp
src/index/ivf_initializer.cpp
src/index/ivf_search.cpp
src/index/qg.cpp
src/index/qg_builder.cpp
+ src/index/symqg_index.cpp
src/index/pipnn.cpp
src/index/hnsw_dispatch.cpp
src/index/hnsw_search_generic.cpp
@@ -261,6 +266,10 @@ if(RABITQ_BUILD_INDEX)
)
add_library(rabitqlib::index ALIAS rabitq_index)
target_link_libraries(rabitq_index PUBLIC rabitq_fastscan)
+ # Index files record the library version that wrote them.
+ target_compile_definitions(rabitq_index PRIVATE
+ RABITQ_LIBRARY_VERSION="${PROJECT_VERSION}"
+ )
set_target_properties(rabitq_index PROPERTIES
EXPORT_NAME index
POSITION_INDEPENDENT_CODE ON
@@ -317,7 +326,8 @@ configure_package_config_file(
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/rabitqlibConfigVersion.cmake"
VERSION "${PROJECT_VERSION}"
- COMPATIBILITY SameMajorVersion
+ # Before 1.0 a minor release may break the API.
+ COMPATIBILITY SameMinorVersion
)
install(EXPORT rabitqlibTargets
FILE rabitqlibTargets.cmake
diff --git a/README.md b/README.md
index 5dffb2e7..5eef47fd 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
-
+
@@ -27,28 +27,28 @@ approximate nearest-neighbor search. See the [research papers](https://vectordb-
## News
+- **v0.9.0:** removes the Python forms 0.8 deprecated, saves index format 2, and adds
+ the cosine metric, `int64` IDs and C++ index classes that match the Python API
+ ([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.9.0/)).
- **v0.8.5:** accepts the names 0.9 will use (`capacity`, `routing`, `ef_search`,
k-means `nbits`) and deprecates the 0.8 spellings they replace
([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.5/)).
- **v0.8.4:** input validation reads each batch once instead of twice
([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.4/)).
-- **v0.8.3:** provisional `rabitqlib.quant` module: rotate, quantize, pack and score
- RaBitQ codes stored outside an index
- ([notes](https://vectordb-ntu.github.io/RaBitQ-Library/releases/0.8.3/)).
Earlier versions: [all releases](https://github.com/VectorDB-NTU/RaBitQ-Library/releases).
## Vector indexes
Use the included indexes when you want construction, search, and save/load in one
-library. All three support L2 and inner product; normalize vectors for cosine
-search. Their structures, storage costs, and search parameters offer different
+library. All three support L2, inner product and cosine, which normalizes vectors
+for you. Their structures, storage costs, and search parameters offer different
QPS–recall tradeoffs.
| Index | Search approach | Storage and updates |
| --- | --- | --- |
| [IVF-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/ivf/) | Partitioned search with batch scoring. | 1–9-bit codes or raw-vector reranking; add/remove. |
-| [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/) | Graph traversal over quantized vectors. | 1–9-bit codes plus graph edges; add/remove and resize. |
+| [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/) | Graph traversal over quantized vectors. | 1–9-bit codes plus graph edges; add/remove and reserve. |
| [SymphonyQG](https://vectordb-ntu.github.io/RaBitQ-Library/index/qg/) | Graph search with batched distance estimation. | Raw or 4/8-bit storage; updates require rebuilding. |
[Native clustering methods](https://vectordb-ntu.github.io/RaBitQ-Library/clustering/) prepare centroids and
@@ -62,7 +62,7 @@ settings, and limitations.
### Python
```bash
-python -m pip install --upgrade "rabitqlib>=0.8.5"
+python -m pip install --upgrade "rabitqlib>=0.9.0"
```
Wheels support CPython 3.11–3.14 on Linux x86-64/ARM64, Windows x86-64,
@@ -93,8 +93,8 @@ distance, with smaller values first. Without `nprobe`, search probes
Quantization remains approximate even when all clusters are probed.
The [complete quick start](https://vectordb-ntu.github.io/RaBitQ-Library/quick_start/) explains result handling,
measures recall while varying `nprobe`, and shows save/load. Code written for
-0.7 still runs in 0.8 with deprecation warnings; see the
-[migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/).
+0.8 may need changes for 0.9; see the
+[migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/#from-08-to-09).
For other indexes, see the [HNSW-RaBitQ](https://vectordb-ntu.github.io/RaBitQ-Library/index/hnsw/#minimal-workflow) and
[SymphonyQG](https://vectordb-ntu.github.io/RaBitQ-Library/index/qg/#minimal-workflow) examples.
@@ -159,7 +159,7 @@ listed above.
-  LanceDB
+  LanceDB
|
 Databricks
|
-  ClickHouse
+  ClickHouse
|
 Qdrant
@@ -208,7 +208,7 @@ listed above.
- [Documentation](https://vectordb-ntu.github.io/RaBitQ-Library/) and [algorithm overview](https://vectordb-ntu.github.io/RaBitQ-Library/rabitq/rabitq/).
- [Papers and citations](https://vectordb-ntu.github.io/RaBitQ-Library/papers/) for the research behind the library.
-- [Release notes](https://github.com/VectorDB-NTU/RaBitQ-Library/releases) and [0.7 migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/modular_migration/).
+- [Release notes](https://github.com/VectorDB-NTU/RaBitQ-Library/releases), the [Python migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/python_migration/) and the [0.7 migration guide](https://vectordb-ntu.github.io/RaBitQ-Library/modular_migration/).
- [GPU implementation](https://github.com/Stardust-SJF/cuvs_rabitq/tree/cuvs_ivf_rabitq) in cuVS.
## Contributing
diff --git a/benchmarks/hotpaths/README.md b/benchmarks/hotpaths/README.md
index 7b7a4bd4..0ffbf635 100644
--- a/benchmarks/hotpaths/README.md
+++ b/benchmarks/hotpaths/README.md
@@ -11,7 +11,7 @@ Enable `RABITQ_BUILD_BENCHMARKS=ON` in a Release build. Targets follow enabled c
| `rabitq_core_hotpaths` | core only | One-bit compact encoding or raw L2 calls |
| `rabitq_fastscan_hotpaths` | FastScan | Cached standard/HACC batch scoring |
| `rabitq_load_hotpaths` | index | HNSW centroid-sidecar load and validation |
-| `rabitq_ivf_add_hotpaths` | index | One IVF `add` call on a freshly loaded index |
+| `rabitq_ivf_add_hotpaths` | index | One `IvfIndex::add` call on a freshly loaded index |
| `rabitq_ids_benchmark` module + `ids.py` | Python bindings | Production cluster-ID conversion helper |
No additional production dependencies are introduced. Core/FastScan benchmarks support
@@ -66,7 +66,8 @@ the deterministic input. Original production indexes are not benchmark fixtures.
- IVF add verifies the expected point counts and samples new points' self-neighbors
outside the timed call, in addition to comparing output hashes across repetitions.
- Inputs use an LCG with seed 42 (query/centroid seed 91 where applicable; IVF add uses
- seed 91 for added points and seed 7 for centroids), metric L2.
+ seed 91 for added points and seed 7 for centroids), metric L2. IVF add fixes the
+ rotation seed at 42, so its hashes match across processes.
Dimensions for encoding/scoring are multiples of 32. Use 64, 128 and 960 dimensions;
encoding rows 32/4096 and threads 1/4 retain the cases from the original investigation.
- Core encoding times the existing serial template at one thread and OpenMP template
diff --git a/benchmarks/hotpaths/ivf_add.cpp b/benchmarks/hotpaths/ivf_add.cpp
index de99b388..a0d1c690 100644
--- a/benchmarks/hotpaths/ivf_add.cpp
+++ b/benchmarks/hotpaths/ivf_add.cpp
@@ -1,4 +1,5 @@
-// Times one IVF::add() per repetition, each on a freshly loaded copy of the base index.
+// Times one IvfIndex::add() per repetition, each on a freshly loaded copy of the base
+// index.
#include
#include
#include
@@ -12,7 +13,7 @@
#include "common.hpp"
#include "rabitqlib/core/metric.hpp"
-#include "rabitqlib/index/ivf/ivf.hpp"
+#include "rabitqlib/index/ivf_index.hpp"
#include "rabitqlib/index/types.hpp"
namespace {
@@ -49,47 +50,58 @@ void run(int argc, char** argv) {
const std::vector single_ids(add_n, rabitqlib::PID{0});
const rabitqlib::PID* add_cluster_ids = mode == "single" ? single_ids.data() : nullptr;
+ rabitqlib::AddOptions add_options;
+ add_options.num_threads = 1;
{
- rabitqlib::ivf::IVF base(base_n, dim, clusters, 4, rabitqlib::METRIC_L2);
- base.construct(base_data.data(), centroids.data(), base_assigned.data(), false, 1);
+ rabitqlib::IvfOptions options;
+ options.nbits = 4;
+ options.seed = 42; // a fixed rotation keeps hashes comparable across processes
+ rabitqlib::IvfIndex base(dim, clusters, options);
+ base.set_centroids(centroids.data(), 1);
+ add_options.cluster_ids = base_assigned.data();
+ base.add(base_data.data(), base_n, add_options);
base.save(path.c_str());
}
+ add_options.cluster_ids = add_cluster_ids;
+ rabitqlib::IvfSearchOptions search_options;
+ search_options.nprobe = clusters;
bench::metadata(dim, base_n, 1);
const char* name = mode == "single" ? "add_single_cluster" : "add_routed";
uint64_t expected = 0;
for (size_t rep = 0; rep <= reps; ++rep) {
- rabitqlib::ivf::IVF index;
- index.load(path.c_str());
+ auto index = rabitqlib::IvfIndex::load(path.c_str());
const auto start = bench::Clock::now();
- index.add(add_data.data(), add_n, add_cluster_ids, false, 1);
+ index.add(add_data.data(), add_n, add_options);
const double seconds =
std::chrono::duration(bench::Clock::now() - start).count();
if (index.num_stored_points() != base_n + add_n ||
- index.num_points() != base_n + add_n ||
- index.max_elements() != base_n + add_n) {
+ index.num_points() != base_n + add_n) {
throw std::runtime_error("add() did not append the requested points");
}
// Validate known self-neighbors outside timing, independently of prior runs.
for (size_t row = 0; row < std::min(add_n, size_t{3}); ++row) {
- rabitqlib::PID id = rabitqlib::kPidMax;
+ rabitqlib::Id id = rabitqlib::kNoId;
float distance = 0;
- index.search(add_data.data() + row * dim, 1, clusters, &id, &distance);
- if (id != base_n + row || !std::isfinite(distance)) {
+ index.search(add_data.data() + row * dim, 1, 1, &id, &distance, search_options);
+ if (id != static_cast(base_n + row) ||
+ !std::isfinite(distance)) {
throw std::runtime_error("Added point is not searchable with its new ID");
}
}
uint64_t h = 14695981039346656037ULL;
- const size_t total = index.max_elements();
+ const size_t total = index.num_stored_points();
h = bench::hash(&total, sizeof(total), h);
const size_t k = std::min(size_t{10}, index.num_points());
- std::vector ids(k);
+ std::vector ids(k);
std::vector distances(k);
- index.search(base_data.data(), ids.size(), clusters, ids.data(), distances.data());
- h = bench::hash(ids.data(), ids.size() * sizeof(rabitqlib::PID), h);
+ index.search(
+ base_data.data(), 1, ids.size(), ids.data(), distances.data(), search_options
+ );
+ h = bench::hash(ids.data(), ids.size() * sizeof(rabitqlib::Id), h);
h = bench::hash(distances.data(), distances.size() * sizeof(float), h);
if (rep == 0) {
diff --git a/benchmarks/hotpaths/load.cpp b/benchmarks/hotpaths/load.cpp
index 8e4d0de2..dc1c6c84 100644
--- a/benchmarks/hotpaths/load.cpp
+++ b/benchmarks/hotpaths/load.cpp
@@ -37,8 +37,11 @@ void run(int argc, char** argv) {
if (!std::filesystem::exists(rabitqlib::io_impl::filesystem_path(path + ".hnsw"))) {
rabitqlib::ivf::HNSWInitializer index(dim, count);
index.add_vectors(data.data(), 1);
- std::ofstream unused;
- index.save(unused, path.c_str());
+ std::ofstream output(
+ rabitqlib::io_impl::filesystem_path(path + ".hnsw"), std::ios::binary
+ );
+ output.exceptions(std::ios::failbit | std::ios::badbit);
+ index.write(output);
return;
}
}
@@ -46,9 +49,19 @@ void run(int argc, char** argv) {
uint64_t expected = 0;
for (size_t rep = 0; rep <= reps; ++rep) {
rabitqlib::ivf::HNSWInitializer index(dim, count);
- std::ifstream unused;
const auto start = bench::Clock::now();
- index.load(unused, path.c_str());
+ // Open the graph file inside the timing, as loading an index does.
+ std::ifstream input(
+ rabitqlib::io_impl::filesystem_path(path + ".hnsw"),
+ std::ios::binary | std::ios::ate
+ );
+ if (!input) {
+ throw std::runtime_error("Cannot open the HNSW centroid graph file");
+ }
+ const auto bytes =
+ static_cast(static_cast(input.tellg()));
+ input.seekg(0);
+ index.read(input, bytes);
const double seconds =
std::chrono::duration(bench::Clock::now() - start).count();
uint64_t h = 14695981039346656037ULL;
diff --git a/docs/development.md b/docs/development.md
index 7bf6b9c2..983a9051 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -45,7 +45,10 @@ factors estimate L2 distance or inner product.
| `include/rabitqlib/core/` | Per-vector encoding, query/estimation, rotation and per-vector byte layouts |
| `include/rabitqlib/fastscan/` | All 32-vector batch layouts, encoding adapters, packing, LUT/estimation and FastScan/HACC |
| `include/rabitqlib/core/types.hpp`, `core/detail/eigen.hpp` | Numerical configuration/types and internal Eigen aliases, respectively |
-| `include/rabitqlib/index/types.hpp` | Point IDs and ANN candidate values; no Eigen dependency |
+| `include/rabitqlib/index/types.hpp` | Point IDs, add and graph search options, and ANN candidate values; no Eigen dependency |
+| `include/rabitqlib/index/ivf_index.hpp` | `IvfIndex`, the supported C++ IVF API: the Python workflow over `ivf::IVF` |
+| `include/rabitqlib/index/hnsw_index.hpp` | `HnswIndex`, the supported C++ HNSW API: the Python workflow over `hnsw::HierarchicalNSW` |
+| `include/rabitqlib/index/symqg_index.hpp` | `SymqgIndex`, the supported C++ SymphonyQG API: the Python workflow over `symqg::QuantizedGraph` and `QGBuilder` |
| `include/rabitqlib/clustering/` | RaBitQKMeans flat assignment, QGKMeans graph assignment, and shared Lloyd training |
| `include/rabitqlib/index/{ivf,hnsw,symqg}/` | Index construction, persistence, and search |
| `include/rabitqlib/{core,fastscan,index}/detail/` | Module-owned implementation headers; no public stability promise |
@@ -462,7 +465,9 @@ parity against a saved pre-change build when changing those shared implementatio
Keep `tests/fixtures/core_api_v1/consumer.cpp` unchanged when extending v1; add tests.
Changes to v1 names, signatures, aggregate fields, enum values, buffer/code semantics
-or allocation guarantees require an explicit API-major decision. The stable header
+or allocation guarantees require an explicit API-major decision. Adding a `MetricType`
+value that v1 rejects, as `METRIC_COSINE` does, is not such a change; keep v1's rejection
+covered by `core_api_test.cpp`. The stable header
must not expose Eigen, record maps, ANN or ISA-specific types. Workspace APIs must
never silently allocate on the heap or spawn worker threads.
@@ -505,12 +510,13 @@ in place of extra-bit codes.
#### IVF formats and initialization
-New IVF files have a magic/version header, an explicit padded dimension, and a resolved initializer type (v2); v1 files infer the historical
-Flat/HNSW choice at 20,000 clusters, independently of current auto selection.
-New IVF auto routing uses Flat below 5,000 clusters, Flat RaBitQ below 60,000,
-and HNSW otherwise. Flat RaBitQ persists its mean and codes in the main file;
-HNSW retains its sidecar. Legacy quantized files and raw v1 files infer
-64-dimension padding.
+New IVF files use index format 2 (`docs/formats.md`): the resolved initializer type
+is in `ivf_params`, and the routing data, including the HNSW graph, is a section of
+the one file. Earlier `RABQIDX1` v2 files store the initializer type; v1 files infer
+the historical Flat/HNSW choice at 20,000 clusters, independently of current auto
+selection. Those layouts keep HNSW routing in the `.hnsw` sidecar. New IVF auto
+routing uses Flat below 5,000 clusters, Flat RaBitQ below 60,000, and HNSW otherwise.
+Legacy quantized files and raw v1 files infer 64-dimension padding.
#### Search defaults
@@ -518,10 +524,18 @@ IVF search defaults to HACC for 4–9 bits and standard FastScan for 1–3 bits
#### SymphonyQG storage
-SymphonyQG supports raw storage (`quantization_bits == 0`) and quantized storage at 4 or 8 bits.
+SymphonyQG supports raw storage (`quantization_bits == 0` in `QuantizedGraph`, `nbits == 32` in
+`SymqgIndex` and Python) and quantized storage at 4 or 8 bits.
### Change an index API
+The supported C++ index API is `IvfIndex`, `HnswIndex` and `SymqgIndex` in
+`include/rabitqlib/index/*_index.hpp`, with the names, defaults and behaviour of the Python
+classes, and their messages where those do not name Python values; the bindings wrap them.
+`ivf::IVF`, `hnsw::HierarchicalNSW`, `symqg::QuantizedGraph` and `QGBuilder` stay installed for
+these classes and for `QGAssigner`, without documentation or a compatibility promise. Samples and
+docs use the supported classes.
+
Update the C++ declaration/implementation, the corresponding file in `python_bindings/`, Python
type stubs, tests, samples, and the relevant page under `docs/docs/index/`. Preserve public signatures where
possible; add a forwarding overload when evolving an API compatibly. Index construction
@@ -532,7 +546,7 @@ and buffer changes must also preserve the [ID marker](#search-buffer-id-marker)
Filesystem path strings are UTF-8 on Windows and native path bytes on POSIX. Use
`io_impl::filesystem_path` from `utils/path.hpp` before opening files or querying
-filesystem metadata, including IVF's HNSW sidecar. It converts UTF-8 to native Unicode
+filesystem metadata, including the HNSW sidecar of earlier IVF files. It converts UTF-8 to native Unicode
on Windows and preserves existing path bytes on Linux/macOS.
For path-only changes, check path conversion and the affected I/O operations; the
@@ -550,28 +564,40 @@ keep their provenance and hashes, and do not regenerate them with the current wr
Index files are trusted input (see the usage guide): validate structure and sizes so
that corrupt or mismatched files are reported before allocation, without treating a
crafted file as a supported input.
+Readers throw `rabitqlib::FormatError` (`include/rabitqlib/index/format_error.hpp`) for
+any truncated, corrupt, mismatched or unsupported content, including errors raised by
+shared validators while loading; only a file that cannot be opened throws a plain
+`std::runtime_error`. Python maps it to `rabitqlib.FormatError`; rejection tests assert it.
Do not silently reinterpret an old file. Add a magic/version discriminator, use fixed-width
-serialized fields for new formats (the current IVF, HNSW and QG bodies still store several
-`size_t` fields; change those only with a format version bump), validate sizes before
-allocation, check every read, and retain a
-compatibility test fixture or an explicit rejection path. Review each affected format;
-changes to shared serialization helpers require auditing every format using them.
-IVF-RaBitQ, HNSW-RaBitQ, and SymphonyQG have separate formats. SymphonyQG includes a versioned quantized format plus a legacy
-raw-format fallback; preserve both unless a breaking change is explicitly requested.
+serialized fields for new formats (earlier layouts store several `size_t` fields; keep their readers unchanged), validate sizes before allocation, check every
+read, and retain a compatibility test fixture or an explicit rejection path. Review each affected
+format; changes to shared serialization helpers require auditing every format using them.
+Every index writes index format 2 ([`docs/formats.md`](formats.md#index-format-2), container in
+`src/index/format2.*`) and still reads its earlier layouts: IVF-RaBitQ's `RABQIDX1` versions and
+unversioned files, HNSW-RaBitQ's unversioned layout, and SymphonyQG's versioned quantized layout
+and raw fallback. Preserve those readers unless a breaking change is explicitly requested. When a writer moves to
+a new format, freeze the last files of the old writer as release-produced fixtures first.
### Change Python bindings
Shared NumPy and string conversion helpers live in `python_bindings/bindings_common.hpp`. Register
index-specific APIs in their own binding file and export public classes from
`python_bindings/__init__.py`. Validate rank, dimensionality, state, and parameter ranges before
-entering the core. Be deliberate about `py::array::forcecast`: it permits dtype/layout copies and
+entering the core. A binding over a class that implements the Python workflow in C++, such as
+`IvfIndex`, `HnswIndex` or `SymqgIndex`, leaves the state checks and the removal-ID range to
+that class, and for IVF the `reserve_cluster` cluster-ID range. It keeps the conversions and
+shape checks, the `add` cluster-ID range and the `num_points` sign checked before narrowing, the
+`k` range checked before allocating outputs, and checks whose messages name Python values such as
+`None`.
+Be deliberate about `py::array::forcecast`: it permits dtype/layout copies and
must not be used where callers expect in-place mutation or pointer identity.
C-contiguous NumPy storage is not necessarily aligned even to `alignof(T)`.
`ensure_2d_array` copies misaligned inputs into an aligned owner; one-dimensional
-ID conversion uses packed reads in `checked_cluster_ids` and `checked_removal_ids`
-before narrowing to owned PID storage. Reuse these helpers rather than directly
+ID conversion uses packed reads in `checked_cluster_ids`, which validates cluster IDs
+before narrowing them to owned PID storage, and in `copied_ids`, which makes an aligned
+`Id` copy whose range the index checks. Reuse these helpers rather than directly
dereferencing a possibly misaligned typed pointer. Removal IDs are checked against
stored count, including removed records, rather than live count.
@@ -582,6 +608,9 @@ conversion. Acquire and destroy guards with the GIL held, release the GIL only i
their lifetime, and keep converted owners alive until reacquisition.
Python wrappers use `IndexAccess` for concurrent reads and fail-fast exclusive updates.
+Settings that Python changes through a returned reference, such as `cp`, take no guard: keep
+them in the wrapper and copy them into the native index or the call's parameters with the GIL
+and the write guard held before releasing the GIL.
Extract native pointers before releasing the GIL and keep search parameters local to
each call. C++ callers synchronize index mutations themselves.
@@ -691,22 +720,24 @@ its upper and base layers use `upper_layer_max_degree_` and
of 32. These settings are not interchangeable.
Public names and Python keywords are compatibility contracts. For example,
-`Cluster::num()`, the protected `Initializer::num_cluster_`, QG's
-`degree_bound()`/`set_ef()` and `QGKMeansParameters::ef_build`
-retain their existing spellings, as do the Python vocabulary `random_seed`/`seed`,
-`train`/`build`, `obj`, `nsplit`, `final_obj` and `niter`. Python's search breadth is
-`ef_search` since 0.8.5; `ef` is deprecated and removed in 0.9 (#232). Python's `QGKMeans`
-and `QGKMeansParameters` take `nbits`, `max_degree` and `ef_construction` since 0.8.5;
-`quantization_bits`, `graph_degree` and `ef_build` are deprecated there and removed in
-0.9 (#233), while the C++ struct keeps them until 0.9. C++ parameter names may be clarified without
-changing types, order or defaults. Keep declarations, definitions and comments
-in agreement; do not rename methods or literals by textual substitution.
+`Cluster::num()`, the protected `Initializer::num_cluster_`, QG's `degree_bound()` and its
+`set_ef()`, which the installed `QGAssigner` calls, retain their existing spellings, as do the
+Python vocabulary `seed`, `train`, `obj`, `nsplit`, `final_obj` and `niter`. Since 0.9, Python
+spells each concept one way on the index and k-means classes: `ef_search`,
+`ef_construction`, `max_degree`, `nbits` (32 for raw storage), `routing` and `capacity`
+(#232, #233). The C++ index classes and `QGKMeansParameters` use the same names; the index
+classes also take `Id` (`int64_t`) IDs with `kNoId` for an empty result slot, and
+`num_threads == 0` for every available CPU, capped by `OMP_NUM_THREADS`.
+`QGKMeansParameters` and `SymqgIndex` convert `nbits == 32` to the 0 that `QGAssigner` and
+QG take as `quantization_bits`. C++ parameter names may be clarified without changing types,
+order or defaults. Keep declarations, definitions and comments in agreement; do not rename
+methods or literals by textual substitution.
Storage-mode parameters also retain their contracts: IVF/HNSW use `nbits()`
with separate internal `ex_bits_`; IVF additionally accepts 32 for raw-vector
reranking. QG uses `quantization_bits()` with 0 for raw storage and 4/8 for packed
-vectors. Naming work does not change these values, allocation sizes, numeric
-operations, serialized field order, or ownership.
+vectors; `SymqgIndex::nbits()` reports 32 for raw storage. Naming work does not change
+these values, allocation sizes, numeric operations, serialized field order, or ownership.
### Numerical module variable names
@@ -722,8 +753,9 @@ public and protected names, Python keywords, field order and numerical operation
integer accumulation outputs. Retain `lut` in compact local kernels where its
role is clear.
- Clustering's private state uses `dim_`, `num_points_`, `num_clusters_`,
- `num_workers_` and `data_`. Keep public `d`, `k`, `num_threads` and graph parameter
- names compatible. The private graph iteration count is `graph_build_iterations_`.
+ `num_workers_` and `data_`. Keep public `d`, `k`, `num_threads` and the graph parameter
+ names (`ef_search`, `graph_build_iterations` and, since 0.9, `max_degree`,
+ `ef_construction` and `nbits`) compatible. The private graph iteration count is `graph_build_iterations_`.
Per-point centroid IDs are `assignments` (arrays) and `cluster_id` (scalars);
`label` stays reserved for HNSW's caller-visible labels.
- FHT backend arguments use `rotated_data`, `padded_dim`, `trunc_dim` and
@@ -844,15 +876,18 @@ Centroids, data, and queries compared by the same estimator must be in the same
Rotator state is part of persisted index state. Loading an index must restore the exact rotation
used at construction; generating a new random rotator produces silently incorrect distances.
-Honor stored padded dimensions instead of recomputing them from current defaults. IVF `RABQIDX1`
-v1 and v2 files explicitly store this field; preserve it for both versions. Only legacy unversioned
+Honor stored padded dimensions instead of recomputing them from current defaults. Index format 2
+and IVF `RABQIDX1` v1 and v2 files explicitly store this field; preserve it. Only legacy unversioned
quantized IVF files and old raw v1 files omit it and infer historical 64-dimension padding.
Unreleased pad16 files whose stored dimension is not divisible by 32 are rejected.
### Distance conventions
The library supports `METRIC_L2` and `METRIC_IP`. Some internal helpers represent inner-product
-distance as `1 - dot_product`, and estimator correction terms differ between metrics. Do not reuse
+distance as `1 - dot_product`, and estimator correction terms differ between metrics.
+`METRIC_COSINE` exists only at the ANN index boundary: an index stores `METRIC_IP` internally,
+normalizes inputs where they enter (`src/index/cosine.hpp`), and records the metric in its file.
+Quantizers, FastScan, clustering and the IVF initializers keep rejecting it. Do not reuse
an L2 norm/correction formula for IP merely because both paths compile. Test ordering and returned
distance semantics separately.
@@ -865,9 +900,8 @@ checked-bit manipulation independently.
### Ownership during construction
Some index builders retain non-owning access to input vectors only during synchronous construction.
-Do not extend such a pointer's lifetime without introducing explicit ownership. The HNSW Python
-wrapper copies cluster IDs before calling the mutable C++ construction API; preserve that boundary
-unless the C++ contract becomes const-correct.
+Do not extend such a pointer's lifetime without introducing explicit ownership. The Python
+wrappers pass `add` an owned, validated copy of the cluster IDs.
### Removal markers and search
@@ -879,9 +913,9 @@ updates or persistence. These markers affect live search as well as saved files.
IVF-RaBitQ `remove` stores a removed point as `f_add = +inf` inside the existing batch data, so it needs no
discriminator. No index written before `remove` existed has an infinite `f_add`, so nothing in an old
file is reinterpreted. In the legacy file formats readable by release 0.5.0, that reader also
-excludes removed points. This compatibility of the removal marker does not extend to the current
-writer's `RABQIDX1` v2 format: older releases cannot read current saves, even when resaving a loaded
-legacy index. Keep this convention when touching IVF-RaBitQ code:
+excludes removed points. This compatibility of the removal marker does not extend to index
+format 2, which the current writer uses: releases up to 0.8 cannot read current saves, even when
+resaving a loaded legacy index. Keep this convention when touching IVF-RaBitQ code:
- Every estimator and scan path must turn `f_add = +inf` into an infinite estimated distance and an
infinite lower bound, and never into NaN. A NaN distance would enter the result buffer.
diff --git a/docs/docs/clustering.md b/docs/docs/clustering.md
index 26f85ec7..ec3bbfe3 100644
--- a/docs/docs/clustering.md
+++ b/docs/docs/clustering.md
@@ -20,11 +20,12 @@ per centroid; the classes below default to training on every vector.
| Class | Assignment | Recommended use | Cluster count |
| --- | --- | --- | --- |
| [RaBitQKMeans](#rabitqkmeans) | Flat RaBitQ scan | Small cluster counts | `n >= k >= 1` |
-| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (C++ `graph_degree`; default 32) |
+| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (default 32) |
## Python
-Both classes have the same training and result interface:
+Both classes have the same training and result interface. Here `x` is a float32
+array of shape `(n, d)` and `queries` one of shape `(m, d)`:
```python
from rabitqlib import QGKMeans, RaBitQKMeans
@@ -164,15 +165,14 @@ encodes new vectors around it.
Each iteration compares every training point with every centroid. The batch size of 32
is not a cluster-count limit. This method uses one-bit point codes throughout;
-it has no graph parameters or `nbits` (C++ `quantization_bits`) setting.
+it has no graph parameters or `nbits` setting.
### QGKMeans
QGKMeans builds a SymphonyQG graph over the centroids and uses previous
-assignments as search hints. Its additional parameters are below, under their Python
-names since 0.8.5. C++ and Python before 0.8.5 name the first three
-`quantization_bits` (with `0` for raw storage), `graph_degree` and `ef_build`; in
-Python those names still work, with a `DeprecationWarning`, until 0.9.
+assignments as search hints. Its additional parameters are below; C++ and Python use
+the same names. Before 0.9 the first three were `quantization_bits` (with `0` for raw
+storage), `graph_degree` and `ef_build`.
| Parameter | Default | Meaning |
| --- | --- | --- |
@@ -213,15 +213,15 @@ kmeans = RaBitQKMeans(d, 16, final_assignment="exact")
kmeans.train(x)
```
-Python takes the strings `'approximate'` and `'exact'` since 0.8.5. The
-`FinalAssignmentMode` members `Approximate`, `Exact` and the legacy alias `SymphonyQG`
-are still accepted until 0.9, and `cp.final_assignment` reads back as a member
-until then; importing `FinalAssignmentMode` raises a `DeprecationWarning`.
+Python takes the strings `'approximate'` and `'exact'`, and `cp.final_assignment`
+reads back as one of them. 0.9 removed the `FinalAssignmentMode` enum from the Python
+package.
In C++, set `parameters.final_assignment` to
`rabitqlib::rabitqkmeans::FinalAssignmentMode::Exact` or
`rabitqlib::qgkmeans::FinalAssignmentMode::Exact`; both names refer to the same
-enum. Training still uses the selected approximate assignment algorithm.
+enum, whose values are `Approximate` and `Exact` (0.9 removed the alias
+`SymphonyQG`). Training still uses the selected approximate assignment algorithm.
Exact final assignment screens all centroids with blocked GEMM and refines
possible winners in float64; ties select the smallest centroid index. Returned
diff --git a/docs/docs/cpp_integration.md b/docs/docs/cpp_integration.md
index 686a490d..5d5cccdd 100644
--- a/docs/docs/cpp_integration.md
+++ b/docs/docs/cpp_integration.md
@@ -44,7 +44,9 @@ for Linux ARM64, Windows, and Apple Silicon.
## C++ examples
ANN example executables are written to `bin/`. Their source demonstrates complete
-indexing and querying workflows:
+indexing and querying workflows with the index classes `IvfIndex`, `HnswIndex` and
+`SymqgIndex` from `rabitqlib/index/ivf_index.hpp`, `hnsw_index.hpp` and
+`symqg_index.hpp`, which `rabitqlib::index` provides:
- [IVF-RaBitQ](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/ivf_rabitq_indexing.cpp)
- [HNSW-RaBitQ](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/hnsw_rabitq_indexing.cpp)
@@ -58,12 +60,12 @@ The core example is built as the `core_example` CMake target. For the GIST bench
The [core quantization v1 API](rabitq/core_api.md) has a C++ source-compatibility contract.
Other C++ APIs may evolve, and no cross-version C++ binary ABI is promised.
-Pin the `v0.8.5` release and include RaBitQ-Library as a Git submodule:
+Pin the `v0.9.0` release and include RaBitQ-Library as a Git submodule:
```bash
git submodule add https://github.com/VectorDB-NTU/RaBitQ-Library.git third_party/rabitqlib
git submodule update --init --recursive
-git -C third_party/rabitqlib checkout v0.8.5
+git -C third_party/rabitqlib checkout v0.9.0
git add third_party/rabitqlib
```
@@ -105,6 +107,12 @@ find_package(rabitqlib CONFIG REQUIRED)
target_link_libraries(my_program PRIVATE rabitqlib::index)
```
+To require a release, pass its version, for example
+`find_package(rabitqlib 0.9 CONFIG REQUIRED)`. Before 1.0 a minor release may break the
+API, so only the same minor release, at or above a requested patch, satisfies the request:
+0.9.x does, 0.8 and 0.10 do not. A version range must stay within one minor release, for
+example `0.9...<0.10`.
+
For a non-system prefix, point CMake to the installation:
```bash
diff --git a/docs/docs/index.md b/docs/docs/index.md
index 71a74a18..5546b06c 100644
--- a/docs/docs/index.md
+++ b/docs/docs/index.md
@@ -26,7 +26,7 @@ estimation into your own C++ search engine.
```bash
-python -m pip install "rabitqlib>=0.8.5"
+python -m pip install "rabitqlib>=0.9.0"
```
[Installation and supported platforms](installation.md) ·
@@ -36,7 +36,7 @@ python -m pip install "rabitqlib>=0.8.5"
## Choose your index
-All three indexes support L2 and inner-product search, with save/load support.
+All three indexes support L2, inner-product and cosine search, with save/load support.
Start with IVF-RaBitQ for the complete introductory example, then compare on your own data.
@@ -112,5 +112,5 @@ on your own dataset when choosing an index.
## Explore further
- [Algorithm overview](rabitq/rabitq.md) for the rotation, encoding, and scoring workflow.
-- [RaBitQ Library 0.8.5 release notes](releases/0.8.5.md) for the latest changes and upgrade guidance.
+- [RaBitQ Library 0.9.0 release notes](releases/0.9.0.md) for the latest changes and upgrade guidance.
- [Papers and citations](papers.md) for the original RaBitQ method, its multi-bit extension, and SymphonyQG.
diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md
index 10a93afa..5f5fe86c 100644
--- a/docs/docs/index/hnsw.md
+++ b/docs/docs/index/hnsw.md
@@ -1,6 +1,6 @@
# HNSW-RaBitQ
-C++ callers include `rabitqlib/index/hnsw/hnsw.hpp` and link `rabitqlib::index`.
+C++ callers include `rabitqlib/index/hnsw_index.hpp` and link `rabitqlib::index`.
[HNSW](https://arxiv.org/abs/1603.09320) is a popular graph-based index.
HNSW-RaBitQ combines HNSW graph traversal with RaBitQ quantization. Under
comparable quantization settings, HNSW-RaBitQ typically uses more memory
@@ -18,8 +18,8 @@ Run the [Quick start](../quick_start.md#build-and-search-an-ivf-index) to prepar
```python
from rabitqlib import HnswIndex
-index = HnswIndex(data.shape[1], M=16, ef_construction=100) # nbits=7 by default
-index.add(data, num_threads=1) # trains 16 centroids, then links; 1 thread is reproducible
+index = HnswIndex(data.shape[1], M=16, ef_construction=100, seed=7) # nbits=7 by default
+index.add(data, num_threads=1) # trains 16 centroids, then links; a seed and 1 thread are reproducible
ids, distances = index.search(queries, k=10) # ef_search defaults to max(k, 64)
index.save("hnsw.index")
loaded = HnswIndex.load("hnsw.index")
@@ -30,60 +30,67 @@ The first `add` trains an untrained index on the added vectors, as for
`num_clusters`, it trains one centroid per row, and `num_clusters` then reports
the row count. An empty first `add` raises `RuntimeError`.
`train` and `set_centroids` work as for [IVF-RaBitQ](ivf.md#training-centroids-in-python),
-with `num_clusters` centroids (default 16) and always RaBitQKMeans; `index.cp`
-starts from the same defaults with `seed`'s low 32 bits. The first `add` into the
+with `num_clusters` centroids (default 16) and always RaBitQKMeans, but
+`set_centroids` takes no `num_threads`; `index.cp`
+starts from the same defaults with the index `seed`. The first `add` into the
empty index links vectors with their exact coordinates, like the 0.7 `build`;
later adds link through the stored codes (see [Recall after `add`](#recall-after-add)),
so add most vectors in the first call.
### C++
-Link `rabitqlib::index`. Here `data`, `centroids` and `queries` are row-major
-`std::vector ` buffers with original dimension `dim`; `cluster_ids` is a
-`std::vector` with one centroid ID per data row. Supply at least
-ten points for this example.
+`rabitqlib::HnswIndex` has the names, defaults and behaviour of the Python class.
+Here `data` and `queries` are row-major `std::vector` buffers with
+dimension `dim`.
```cpp
#include
-#include
-
-// Constructor order: capacity, dimension, total bits, M, ef_construction.
-rabitqlib::hnsw::HierarchicalNSW index(data.size() / dim, dim, 4, 16, 100);
-index.construct(
- centroids.size() / dim, centroids.data(), data.size() / dim, data.data(),
- cluster_ids.data(), 1
-);
-auto results = index.search(queries.data(), queries.size() / dim, 10, 100, 1);
+#include
+
+rabitqlib::HnswOptions options; // set the fields by name; nbits is 7 by default
+options.ef_construction = 100;
+options.seed = 7;
+rabitqlib::HnswIndex index(dim, options);
+rabitqlib::AddOptions add_options;
+add_options.num_threads = 1; // with the seed, a reproducible graph
+index.add(data.data(), data.size() / dim, add_options); // trains 16 centroids, then links
+
+const size_t num_queries = queries.size() / dim;
+std::vector ids(num_queries * 10);
+std::vector distances(num_queries * 10);
+index.search(queries.data(), num_queries, 10, ids.data(), distances.data());
index.save("hnsw.index");
-rabitqlib::hnsw::HierarchicalNSW loaded;
-loaded.load("hnsw.index");
+auto loaded = rabitqlib::HnswIndex::load("hnsw.index");
```
-C++ results are per-query vectors of `(distance, ID)` pairs. For build setup,
-see [C++ integration](../cpp_integration.md).
+For build setup, see [C++ integration](../cpp_integration.md).
## Parameters and limits
| Parameter | Contract |
| --- | --- |
-| `dim` | Original input dimension; Python supports 64–65,536 and pads internally. |
-| `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. 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. |
+| `dim` | Original input dimension, 64–65,536; the index pads internally. |
+| `nbits` | 1–9 total bits including the sign bit; defaults to 7. Raw-vector storage is not supported. |
+| `num_clusters` | 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; defaults are 16 and 200, and the index reports both. `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` | `metric` defaults to L2 (Python `"l2"`); inner product and [cosine](usage.md#the-cosine-metric) are also supported. `seed` is the graph and rotation seed in `[0, 2**32 - 1]` and the initial `cp.seed`. The default (Python `None`, an empty C++ `std::optional`) draws one at random (it was 100 before 0.9); `seed` reports it. |
+| `capacity` | The current capacity, which `add` grows geometrically (at least doubling) and `reserve` can preallocate; in Python they replace `max_elements` and `resize`, which 0.9 removed. |
+| `k`, `ef_search` | Result count, from 1 to 2^31, and search window. `k` may exceed the stored point count; missing results are padded with ID `-1` (C++ `kNoId`) and `+inf`. An omitted `ef_search` (Python `None`) uses `max(k, 64)`, an explicit 0 raises `ValueError` (C++ `std::invalid_argument`), a smaller value is raised to at least `k`, and a value above the stored point count is clamped to it. It replaces `ef`, which 0.9 removed. |
+
+In C++, the construction settings are fields of `HnswOptions`, and `ef_search`
+and `num_threads` fields of `GraphSearchOptions`.
`seed` controls graph levels and the FHT/Kac rotation (using its low 32 bits).
With identical inputs and parameters, single-threaded construction is reproducible
-within the same build environment. Python `train` and `add` default to every
-available CPU, so **default builds are not reproducible**: pass `num_threads=1` to
-`add` when you need the same graph again. Different toolchains or SIMD backends can
+within the same build environment. A seed is drawn unless one is given, and
+`train` and `add` default to every available CPU, so **default builds are not
+reproducible**: pass a seed to the constructor and one thread to `add` when you
+need the same graph again. Different toolchains or SIMD backends can
still change results. Loading restores the saved rotation.
Results use squared L2 or `1 - dot` estimates, ordered from smallest to largest.
-Python fills missing results with ID `2**32 - 1` and distance `+inf`; C++ returns
-only the available pairs. See [result handling](../quick_start.md#read-the-results)
+IDs are `int64` (C++ `rabitqlib::Id`), and missing results hold ID `-1` and distance
+`+inf`. See [result handling](../quick_start.md#read-the-results)
and the shared [input, count and concurrency contracts](usage.md).
## Index construction
@@ -94,121 +101,110 @@ the links, centroids, cluster IDs, labels, RaBitQ codes, and factors rather
than a copy of the raw dataset. Total bit widths from 1 through 9 are
supported.
-`construct()` is synchronous. Keep its input buffers valid for the entire call;
-the index retains no pointers to them after it returns or throws. The borrowed
-input pointer and search candidate helpers are private implementation details;
-see the [C++ migration guide](../modular_migration.md#public-and-implementation-interfaces).
+`add` is synchronous. Keep its input buffers valid for the entire call; the
+index retains no pointers to them after it returns or throws.
+
+To build from centroids computed elsewhere, for example by
+[RaBitQKMeans](../clustering.md#rabitqkmeans), set them and pass each vector's
+cluster:
```cpp
-void HierarchicalNSW::construct(
- size_t num_clusters,
- const float* centroids,
- size_t num_points,
- const float* data,
- PID* cluster_ids,
- size_t num_threads = std::numeric_limits::max(),
- bool fast_quantization = false
-);
+rabitqlib::HnswOptions options;
+options.num_clusters = num_clusters;
+rabitqlib::HnswIndex index(dim, options);
+index.set_centroids(centroids.data());
+rabitqlib::AddOptions add_options;
+add_options.cluster_ids = cluster_ids.data();
+index.add(data.data(), num_points, add_options);
```
-- **data**: Vectors in the original input coordinates.
-- **num_points**: The number of data vectors.
-- **centroids**: Centroids computed by [RaBitQKMeans](../clustering.md#rabitqkmeans); the examples use `num_clusters = 16`.
-- **cluster_ids**: Array of length `num_points`; every entry must be in the range `[0, num_clusters)`.
-- **num_threads**: Number of threads to use (default: every available thread; `0` also auto-selects).
+- **centroids**: `num_clusters` centroids in the original input coordinates; the examples use 16.
+- **cluster_ids**: One entry per vector, each in `[0, num_clusters)`.
+- **num_threads**: Worker count; no value, the default, uses every available CPU, and `0` also auto-selects.
- **fast_quantization**: Use calibrated scaling instead of per-vector scale search; see [encoding paths](../rabitq/quantizer.md#implementations).
### Training centroids in C++
-Instead of passing centroids to `construct`, train or set them on an empty
-index, then add the points:
+`HnswIndex` trains as the Python class does. `cp()` returns the training
+settings; include `rabitqlib/clustering/rabitqkmeans.hpp` to change them:
```cpp
-#include
-#include
+#include
+#include
-rabitqlib::hnsw::HierarchicalNSW index(max_elements, dim, 4, 16, 200);
-index.train(16, num_points, data.data(),
- rabitqlib::default_training_parameters(rabitqlib::METRIC_L2, 100));
-// Or supply centroids: index.set_centroids(num_clusters, centroids.data());
+rabitqlib::HnswIndex index(dim);
+index.cp().niter = 20;
+index.train(sample.data(), num_samples); // no thread count: cp().num_threads
+// Or supply centroids: index.set_centroids(centroids.data());
index.add(data.data(), num_points);
```
-- `train(num_clusters, num_points, data, cp)` trains centroids with
- [RaBitQKMeans](../clustering.md#rabitqkmeans); `num_points` must be at least
- `num_clusters`. Points are assigned by `add`, not by training. See the
- [IVF-RaBitQ defaults](ivf.md#training-centroids-in-c) for
- `default_training_parameters`.
-- The first `add` into an empty graph links points with their exact vectors, as
- `construct` does; with one thread it produces the same index as `construct`
- with the same centroids and cluster IDs. If it fails, the graph is left empty
- and the centroids are kept. Later adds link through the stored codes; see
+- `train`, `set_centroids` and the first `add` follow the Python rules above.
+ Training always uses [RaBitQKMeans](../clustering.md#rabitqkmeans); points are
+ assigned by `add`, not by training.
+- The first `add` into an empty graph links points with their exact vectors. If
+ it fails, the graph is left empty. Centroids set by `train` or `set_centroids`
+ are kept, and a first `add` that trained leaves the index untrained. Later adds link
+ through the stored codes; see
[how added points are linked](#how-added-points-are-linked).
-- `train` and `set_centroids` replace the centroids only while the index stores
- no points, removed ones included; otherwise they throw `std::logic_error`.
- A failed call leaves the index unchanged. `construct` needs an untrained index,
- so after either call it throws `std::logic_error`; use `add` instead.
-- `is_trained()` reports whether centroids are set. Before that, `add` throws
- `std::logic_error`; searching an empty index, trained or not, returns no results.
-- `save` throws `std::logic_error` for an index without stored points, trained
- or not. Earlier releases saved an untrained empty index; such files still load.
+- Arguments outside their range throw `std::invalid_argument` (Python
+ `ValueError`), and a call in the wrong state throws `std::logic_error` (Python
+ `RuntimeError`), with the Python messages except where those name Python values
+ such as `None`.
+- `is_trained()` reports whether centroids are set. A trained index without
+ points pads every `search` result slot with `kNoId` and `+inf`; `save` throws
+ `std::logic_error` until the index stores at least one point. Earlier
+ releases saved an untrained empty index; such files still load, and without a
+ recorded seed they need `train` or `set_centroids` before `add`.
## Querying
```cpp
-std::vector>> HierarchicalNSW::search(
+void HnswIndex::search(
const float* queries,
size_t num_queries,
size_t k,
- size_t ef_search,
- size_t num_threads
-);
+ Id* ids,
+ float* distances,
+ const GraphSearchOptions& options = {}
+) const;
```
-- **queries**: Query vectors in the original input coordinates.
-- **num_queries**: The number of query vectors.
+- **queries**: `num_queries` query vectors in the original input coordinates.
- **k**: The number of nearest neighbors to search.
-- **ef_search**: The size of the candidate set for searching HNSW-RaBitQ base layer.
-- **num_threads**: Number of threads to use. Each query is processed by one thread.
+- **ids**, **distances**: Output buffers of `num_queries * k` values; `distances` may be `nullptr`.
+- **options.ef_search**: The size of the candidate set for searching the base layer.
+- **options.num_threads**: Number of threads to use (default 1). Each query is processed by one thread.
-The search window belongs to each call, so concurrent C++ searches can use
+The search window belongs to each call, so concurrent searches can use
different `ef_search` values and separate outputs while the index is unchanged.
-Python follows the shared [concurrency contract](usage.md#threading-and-file-paths).
+See the shared [concurrency contract](usage.md#threading-and-file-paths).
## Updating an index
-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
-[compatibility restrictions](#how-removal-is-stored).
+A trained index supports `add()`, `reserve()` and `remove()` without the original
+data. Every loaded index is trained, except one loaded from a file saved before
+training (see below). `save` always writes index format 2; see
+[persistence](#persistence).
```c++
-std::vector HierarchicalNSW::add(
- const float* data,
- size_t num_points,
- const PID* cluster_ids = nullptr,
- bool fast_quantization = false,
- size_t num_threads = 1
-);
-
-void HierarchicalNSW::resize(size_t new_max_elements);
+Id HnswIndex::add(const float* data, size_t num_points, const AddOptions& options = {});
+
+void HnswIndex::reserve(size_t num_points);
```
- **data**, **num_points**: `num_points` new vectors in the original coordinates. Vector `i` receives
- the label `num_stored_points() + i`, so labels stay dense, and `add` returns them.
-- **cluster_ids**: The cluster of each new vector, in `[0, num_clusters)`. When it
+ the ID `num_stored_points() + i`, so IDs stay dense; `add` returns the first.
+- **options.cluster_ids**: The cluster of each new vector, in `[0, num_clusters)`. When it
is `nullptr`, each vector goes to its nearest centroid, chosen the same way a
query is routed.
-- **fast_quantization**, **num_threads**: Same meaning as in `construct`, but `add` defaults
- to one thread, which keeps the resulting links deterministic; pass `0` to auto-select. A point keeps the label
- `num_stored_points() + i` whatever order the threads finish in, because the slots are
- reserved as one block before the inserts start.
-- **new_max_elements**: The new capacity. It must be at least `num_stored_points()`.
- In C++, initialize the index through its parameterized constructor or `load`
- before calling `resize`.
+- **options.fast_quantization**, **options.num_threads**: As in [index construction](#index-construction).
+ With more than one thread the links vary between runs; one thread keeps them
+ deterministic. A point keeps the ID `num_stored_points() + i` whatever order the
+ threads finish in, because the slots are reserved as one block before the inserts start.
+- **num_points** of `reserve`: The capacity to preallocate; a smaller value changes nothing.
-In Python, `add` grows the capacity when needed:
+In Python, with `vectors` a float32 array of new vectors of shape `(n, index.dim)`:
```python
new_ids = index.add(vectors) # route to the nearest centroids
@@ -221,7 +217,7 @@ Updates require exclusive access; see the
`add` prepares the result IDs, quantized vectors, and link-list allocations before
changing the graph or point count. A failure during preparation leaves those
-unchanged. A failure during graph linking can leave the batch counted in
+unchanged. A failure while linking a later batch can leave it counted in
`num_stored_points()` with only some points reachable through the graph. The index
remains safe to search, save, load, and destroy; inspect `num_stored_points()` before
retrying, or rebuild to restore full reachability.
@@ -231,15 +227,13 @@ retrying, or rebuild to restore full reachability.
See the shared [index count contract](usage.md#index-counts). Removed
records still occupy capacity.
-C++ `add` never grows the index: it rejects a whole batch whose size exceeds
-`max_elements() - num_stored_points()`, and `resize` is the only way to raise
-that. Python `add` grows the capacity first when the batch does not fit, to at least
-double it, and `reserve(num_points)` preallocates it (since 0.8.5; `resize` still works,
-with a `DeprecationWarning`, until 0.9, and `capacity` replaces `max_elements`). Reserving capacity avoids reallocating and copying the whole base-layer record storage during `add`.
+`add` grows the capacity first when the batch does not fit, to at least
+double it, and `reserve(num_points)` preallocates it; `reserve` never shrinks the
+capacity. Reserving capacity avoids reallocating and copying the whole base-layer record storage during `add`.
It does not make insertion allocation-free: batch scratch, upper-layer link lists,
and label-map entries still require allocations, and the label map may rehash.
-`resize` rebuilds the base-layer storage and copies it, so it needs memory for
+Growing the capacity rebuilds the base-layer storage and copies it, so it needs memory for
both copies while it runs and costs time proportional to the whole index. It
invalidates every pointer into the index. The per-node upper-layer link lists are
not copied, only their pointer table.
@@ -255,12 +249,12 @@ of a rebuild.
### Removing points
```c++
-size_t HierarchicalNSW::remove(const PID* labels, size_t num_points);
+size_t HnswIndex::remove(const Id* ids, size_t num_ids);
```
-- **labels**, **num_points**: `num_points` labels of the points to remove, as returned by `add` and
- `search`. Every label must be in the index; nothing is removed if one is not.
- `remove` returns how many points were newly removed, so repeating a label or a
+- **ids**, **num_ids**: IDs of the points to remove, as returned by `add` and
+ `search`. Every ID must be in `[0, num_stored_points())`; nothing is removed if one is not.
+ `remove` returns how many points were newly removed, so repeating an ID or a
call is safe.
In Python:
@@ -272,18 +266,17 @@ removed = index.remove(new_ids[:10]) # IDs in [0, num_stored_points)
A removed point keeps its codes, its links, and its place in the graph. Search
still walks through it and `add` may link new points to it, which keeps the graph
connected, as in hnswlib. Search never returns it, so a query can get fewer than
-`k` results once points are removed: in Python the missing slots hold `kPidMax`
-(`2**32 - 1`) with an infinite distance. Removed points still count in
+`k` results once points are removed: the missing slots hold ID `-1` (C++ `kNoId`)
+with an infinite distance. Removed points still count in
`num_stored_points()` and cannot be restored. Removal requires the same
exclusive access as other updates.
#### Choosing `ef_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_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.
+`ef_search` close to `k` finds fewer live points as removals accumulate. Search uses
+`max(k, 64)` when `ef_search` is omitted; an explicit value is 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
`num_stored_points()`):
@@ -298,29 +291,28 @@ Callers that track how many points they removed can apply this directly.
### How removal is stored
-`remove` sets the high bit of the point's stored cluster ID. `construct` and `load`
-limit the number of clusters to 2^31, so no real cluster ID has that bit, and
+`remove` sets the high bit of the point's stored cluster ID. Setting centroids and
+`load` limit the number of clusters to 2^31, so no real cluster ID has that bit, and
every reader of the cluster ID masks it off. The mark lives in the base layer, so
-it survives `save`, `load`, and `resize`, and a file without removals is
-unchanged.
-
-In C++, `cluster_id_of(internal_id)` returns a stored record's cluster with the
-mark masked off; removed points keep their cluster. It takes an internal ID from 0
-through `num_stored_points() - 1`, which matches the label only for points added
-in order. It throws `std::logic_error` on a default-constructed index that has
-not been loaded, and `std::invalid_argument` for an ID not below
-`num_stored_points()`, including any ID before `construct`. Python does not
-expose it.
-
-A file that has removals cannot be read by earlier releases. Releases 0.3.7
+it survives `save`, `load`, and capacity growth, and a file without removals
+carries no marks.
+
+In the layout written before 0.9, a file that has removals cannot be read by
+releases before 0.5.2. Releases 0.3.7
through 0.5.1 check every cluster ID on `load` and reject the file as invalid
instead of returning removed points. Releases before 0.3.7 do not check cluster
IDs, so do not open such a file with them.
+`save` writes [index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2), which also records the construction seed, so
+`seed` survives a reload. Releases up to 0.8 cannot read these files; every earlier
+file still loads, without a recorded seed, and saving it writes format 2.
+The C++ API of earlier releases could also save an index before training it. Such a
+file loads untrained, with `num_clusters` 16; without a recorded seed its first `add`
+cannot train it, so call `train` or `set_centroids` before `add`.
+
New HNSW-RaBitQ indexes pad dimensions to multiples of 32 for all supported bit widths.
Loading preserves the saved padded dimension and rotation, so older indexes
-using multiples of 64 remain readable. Older library versions cannot load new
-files whose padded dimension is not a multiple of 64.
+using multiples of 64 remain readable.
## Implementation details
@@ -396,11 +388,12 @@ is not refined and uses its 1-bit estimate for window admission.
### How added points are linked
-`construct` borrows the caller's vectors and links points using exact distances
-between them. That pointer is not retained, so `add` cannot use it, and instead
-scores candidates with the estimator the search already uses: the vector being
-compared against is rebuilt from its stored RaBitQ code, sign bit and extra bits
-together, and the other side is scored straight from its codes. This is the same
+The first `add` into an empty graph borrows the caller's vectors and links points
+using exact distances between them. That pointer is not retained, so later adds
+cannot use it, and instead score candidates with the estimator the search already
+uses: the vector being compared against is rebuilt from its stored RaBitQ code,
+sign bit and extra bits together, and the other side is scored straight from its
+codes. This is the same
approach quantized SymphonyQG construction takes.
Graph quality therefore depends on how a point arrived.
diff --git a/docs/docs/index/ivf.md b/docs/docs/index/ivf.md
index aa346060..7a377fd5 100644
--- a/docs/docs/index/ivf.md
+++ b/docs/docs/index/ivf.md
@@ -1,6 +1,6 @@
# IVF-RaBitQ
-C++ callers include `rabitqlib/index/ivf/ivf.hpp` and link `rabitqlib::index`.
+C++ callers include `rabitqlib/index/ivf_index.hpp` and link `rabitqlib::index`.
[IVF](https://doi.org/10.1109/TPAMI.2010.57) is a classical
clustering-based ANN method. IVF-RaBitQ stores RaBitQ codes and
@@ -20,44 +20,52 @@ clustering options, and the update examples below reuse the Quick Start's `index
### C++
-Link `rabitqlib::index`. In this snippet, `data`, `centroids` and `queries` are
-row-major `std::vector` buffers with original dimension `dim`;
-`cluster_ids` is a `std::vector` with one centroid ID per data row.
-The example requests ten neighbors from five clusters, so supply at least ten
-points and five centroids.
+`rabitqlib::IvfIndex` has the names, defaults and behaviour of the Python class.
+In this snippet, `data` and `queries` are row-major `std::vector` buffers
+with dimension `dim`. As in Python, the first `add` trains the 1,024 centroids on
+the added vectors, so supply at least 1,024 of them.
```cpp
#include
-#include
+#include
+
+rabitqlib::IvfOptions options; // set the fields by name
+options.nbits = 4;
+rabitqlib::IvfIndex index(dim, 1024, options);
+index.add(data.data(), data.size() / dim);
-rabitqlib::ivf::IVF index(data.size() / dim, dim, centroids.size() / dim, 4);
-index.construct(data.data(), centroids.data(), cluster_ids.data(), false, 1);
const size_t num_queries = queries.size() / dim;
-std::vector ids(num_queries * 10);
+std::vector ids(num_queries * 10);
std::vector distances(num_queries * 10);
-index.search_batch(queries.data(), num_queries, 10, 5, ids.data(), distances.data());
+index.search(queries.data(), num_queries, 10, ids.data(), distances.data());
index.save("ivf.index");
+auto loaded = rabitqlib::IvfIndex::load("ivf.index");
```
See [C++ integration](../cpp_integration.md) for build setup and
-[Index Construction](#index-construction) for loading `.fvecs` inputs.
+[Index Construction](#index-construction) for building from precomputed
+centroids and cluster IDs.
## Parameters and limits
| Parameter | Contract |
| --- | --- |
-| `dim` | Original input dimension; Python supports 64–65,536 and pads internally. |
+| `dim` | Original input dimension, 64–65,536; the index pads internally. |
| `num_clusters` | Number of centroids `train` or the first `add` learns, or `set_centroids` supplies; every cluster ID must be in `[0, num_clusters)`. |
-| `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"`. |
-| `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. |
+| `nbits` | 1–9 total bits including the sign bit, or 32 for owned raw-vector reranking. Defaults to 7. |
+| `seed` | Rotation seed in `[0, 2**32 - 1]` and the initial `cp.seed`. The default (Python `None`, an empty C++ `std::optional`) draws one at random; `seed` reports it, and passing it back reproduces the index. |
+| `metric` | Python `"l2"`, `"ip"` or `"cosine"` (C++ `METRIC_L2`, `METRIC_IP` or `METRIC_COSINE`); defaults to L2. See [the cosine metric](usage.md#the-cosine-metric). |
+| `routing` | Defaults to `"auto"` (C++ `ivf::Routing::Auto`); see [centroid routing](#centroid-routing). It replaces `initializer`, which 0.9 removed. |
+| `k`, `nprobe` | Result count, from 1 to 2^31, and positive cluster probe count. `k` may exceed the stored point count; missing results are padded with ID `-1` (C++ `kNoId`) and `+inf`. `nprobe` defaults to `num_clusters / 16`, rounded and at least 1, when omitted (Python `None`); an explicit 0 raises `ValueError` (C++ `std::invalid_argument`). |
+| `high_accuracy` | Defaults to automatic selection (Python `None`): HACC for 4–9 bits, standard FastScan otherwise. |
+
+In C++, `nbits`, `seed`, `metric` and `routing` are fields of `IvfOptions`, and
+`nprobe`, `high_accuracy` and `num_threads` fields of `IvfSearchOptions`.
Results contain IDs and squared L2 or `1 - dot` distances, ordered from smallest
-to largest. Quantized distances are estimates. Unfilled slots use ID `2**32 - 1`
-and distance `+inf`; see [result handling](../quick_start.md#read-the-results).
+to largest. Quantized distances are estimates. IDs are `int64` in Python and
+`rabitqlib::Id` (`int64_t`) in C++. Unfilled slots use ID `-1` and distance `+inf`;
+see [result handling](../quick_start.md#read-the-results).
See the shared [input and concurrency contracts](usage.md).
## Index construction
@@ -80,11 +88,11 @@ For example, split SIFT into 4,096 clusters using squared L2 distance:
After files are prepared, load them into memory. The snippet below uses
`const char*` paths `data_file`, `centroids_file`, and `cluster_ids_file`. Include the
-Eigen aliases and I/O helpers explicitly; `ivf.hpp` does not import them.
+Eigen aliases and I/O helpers explicitly; `ivf_index.hpp` does not import them.
```c++
#include
-#include
+#include
#include
#include
@@ -104,42 +112,40 @@ rabitqlib::load_vecs(cluster_ids_file, cluster_ids);
See the [complete indexing example](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/sample/cpp/ivf_rabitq_indexing.cpp)
for argument parsing and the surrounding program.
-Then initialize an IVF-RaBitQ object with the number of data points, vector
-dimension, number of clusters, and total bits per dimension. The C++ index
-accepts total quantized bit widths from 1 through 9, or `total_bits=32`
-(Python `nbits=32`) to store raw float32 vectors for reranking.
+Then create the index with the vector dimension, the number of clusters and the
+total bits per dimension: 1 through 9, or 32 to store raw float32 vectors for
+reranking.
```c++
-using index_type = rabitqlib::ivf::IVF;
-
size_t num_points = data.rows();
size_t dim = data.cols();
size_t num_clusters = centroids.rows();
-index_type ivf(num_points, dim, num_clusters, total_bits);
+rabitqlib::IvfOptions options;
+options.nbits = total_bits;
+rabitqlib::IvfIndex ivf(dim, num_clusters, options);
```
### Centroid routing
-The optional final C++ constructor argument selects `InitializerType::Auto`,
-`Flat`, `FlatRaBitQ`, or `HNSW` from the `rabitqlib::ivf` namespace. Python accepts
-`routing="auto"`, `"flat"`, `"flat_rabitq"`, or `"hnsw"`:
+`IvfOptions::routing` selects `ivf::Routing::Auto`, `Flat`, `FlatRaBitQ`, or
+`HNSW`. Python accepts `routing="auto"`, `"flat"`, `"flat_rabitq"`, or `"hnsw"`; here
+`dim` and `num_clusters` are the vector dimension and the number of clusters:
```python
-index = IvfIndex(dim, num_clusters, nbits=4, routing="flat_rabitq")
-print(index.routing) # resolved routing type
+routed = IvfIndex(dim, num_clusters, nbits=4, routing="flat_rabitq")
+print(routed.routing) # resolved routing type
```
```c++
-index_type ivf(num_points, dim, num_clusters, total_bits, rabitqlib::METRIC_L2,
- rabitqlib::RotatorType::FhtKacRotator,
- rabitqlib::ivf::InitializerType::FlatRaBitQ);
-auto routing = ivf.initializer_type();
+options.routing = rabitqlib::ivf::Routing::FlatRaBitQ;
+rabitqlib::IvfIndex ivf(dim, num_clusters, options);
+auto routing = ivf.routing(); // resolved routing type
```
- `auto` selects `flat` below 5,000 clusters, `flat_rabitq` from 5,000 through
59,999 clusters, and `hnsw` from 60,000 clusters onward. These defaults are
- practical thresholds; explicitly select a different initializer when it better
+ practical thresholds; explicitly select a different routing when it better
suits your workload.
- `flat` computes exact distances to every centroid.
- `flat_rabitq` scans one-bit centroid codes with FastScan, prunes candidates
@@ -153,17 +159,13 @@ auto routing = ivf.initializer_type();
error instead of probing every cluster. Use `flat` or `flat_rabitq` when a
query should probe most clusters.
-All choices support L2 and inner product. Flat RaBitQ uses the IVF-RaBitQ rotation and
+All choices support every metric. Flat RaBitQ uses the IVF-RaBitQ rotation and
padded domain, retains float32 centroids for refinement, and stores its mean and
codes in the main index file. Its code precision is independent of the index's
`nbits`. It trades additional code storage and an O(cluster count) query work
buffer for fewer full-vector distance evaluations. Performance depends on
cluster count, dimension, `nprobe`, and data distribution. Measure recall and
-latency on your workload, and use an explicit initializer to override `auto`.
-
-The optional routing argument introduced in 0.6.0 preserves existing constructor
-call forms; this does not imply compatibility with all 0.7.0 C++ changes. See the
-[migration guide](../modular_migration.md) and rebuild with matching headers and libraries.
+latency on your workload, and use an explicit routing to override `auto`.
Compared with releases before 0.6.0, `auto` changes routing for 5,000–59,999
clusters. The 5,000–19,999 range changes from exact to approximate selection.
@@ -171,33 +173,24 @@ 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 `routing`) reports the resolved type,
+omitted. `routing()` (Python `routing`) reports the resolved type,
including after loading; loading never re-runs the current `auto` policy for a
new-format file.
-Finally, call the construct API:
+Finally, set the centroids and add the vectors with their cluster IDs:
```c++
-void IVF::construct(
- const float* data,
- const float* centroids,
- const PID* cluster_ids,
- bool fast_quantization = false,
- size_t num_threads = std::numeric_limits::max()
-);
+ivf.set_centroids(centroids.data());
+rabitqlib::AddOptions add_options;
+add_options.cluster_ids = cluster_ids.data();
+add_options.fast_quantization = true;
+ivf.add(data.data(), num_points, add_options);
```
-- **data**: Vectors in the original input coordinates.
- **centroids**: One centroid per configured cluster, in the original input coordinates.
- **cluster_ids**: One ID per input vector, in `[0, num_clusters())`.
- **fast_quantization**: Use a calibrated scaling factor instead of per-vector scale search; defaults to `false`. See [encoding paths](../rabitq/quantizer.md#implementations).
-- **num_threads**: Maximum number of OpenMP threads used to quantize clusters.
-
-For example:
-
-```c++
-ivf.construct(data.data(), centroids.data(), cluster_ids.data(), true);
-```
+- **num_threads**: Worker count; no value, the default, uses every available CPU.
### Training centroids in Python
@@ -208,14 +201,16 @@ and quantizes vectors. On an untrained index, the first `add` without
to train on a different sample. Training uses the settings in `index.cp`, a
[`RaBitQKMeansParameters`](../clustering.md#rabitqkmeans) whose defaults differ
from the k-means classes: 10 iterations, at most 256 sampled vectors per
-centroid (`max_points_per_centroid`), spherical k-means for `metric="ip"`, and
-`seed` equal to the index seed. Change fields before training:
+centroid (`max_points_per_centroid`), spherical k-means for `metric="ip"` and `"cosine"`, and
+`seed` equal to the index seed. Change fields before training; in this example
+`sample` and `vectors` are float32 arrays of shape `(n, dim)`, and `sample` needs at
+least 1024 rows:
```python
-index = IvfIndex(dim, 1024, nbits=4, metric="ip")
-index.cp.niter = 20
-index.train(sample) # num_threads=None uses index.cp.num_threads (0: all CPUs)
-index.add(vectors)
+ip_index = IvfIndex(dim, 1024, nbits=4, metric="ip")
+ip_index.cp.niter = 20
+ip_index.train(sample) # num_threads=None uses ip_index.cp.num_threads (0: all CPUs)
+ip_index.add(vectors)
```
- Up to 2,000 clusters, training uses RaBitQKMeans; above that it uses
@@ -230,165 +225,136 @@ index.add(vectors)
vectors; once it stores any (including removed ones), both raise
`RuntimeError`. A failed call leaves the index unchanged.
- Before training, `add` with `cluster_ids`, `search`, `remove`, `reserve_cluster` and
- `save` raise `RuntimeError`; `add` without `cluster_ids` trains first, except
- on an index created with `max_elements`, which `build` fills. If that
+ `save` raise `RuntimeError`; `add` without `cluster_ids` trains first. If that
first `add` fails, the index stays untrained and empty; an empty first `add`
raises `RuntimeError`. A trained index without
vectors cannot be saved, and its `search` returns only padded results; add
- vectors first. Loaded indexes are trained, and their `seed` is `None`.
+ vectors first. Loaded indexes are trained; `seed` is `None` for files without
+ a recorded seed, such as those from releases up to 0.8.
- `train` and `add` default to every available CPU; `search` defaults to one
thread.
### Training centroids in C++
-Instead of passing centroids to `construct`, create an index without a point
-count, train or set its centroids, then add the points:
+`IvfIndex` trains as the Python class does. `cp()` returns the training
+settings; include `rabitqlib/clustering/rabitqkmeans.hpp` to change them:
```c++
-#include
-#include
-
-rabitqlib::ivf::IVF index(dim, num_clusters, 4, rabitqlib::METRIC_L2, /*seed=*/42);
-index.train(num_points, data.data(),
- rabitqlib::default_training_parameters(rabitqlib::METRIC_L2, 42));
+#include
+#include
+
+rabitqlib::IvfOptions options;
+options.metric = rabitqlib::METRIC_IP;
+options.nbits = 4;
+rabitqlib::IvfIndex index(dim, 1024, options);
+index.cp().niter = 20;
+index.train(sample.data(), num_samples); // no thread count: cp().num_threads
// Or supply centroids: index.set_centroids(centroids.data());
index.add(data.data(), num_points);
```
-- The constructor takes `dim`, `num_clusters`, `total_bits`, the metric and the
- rotation seed, followed by the optional rotator and initializer types. Pass
- the seed: without it, four arguments such as `IVF(dim, num_clusters, 4,
- METRIC_IP)` select the point-count constructor instead, reading them as
- `(num_points, dim, num_clusters, total_bits)` with the metric converted to a
- bit count, which may compile and run without an error. The
- index starts with no point storage. `construct` rebuilds an index from
- `max_elements()` rows, so it fails on this index until `add` has stored points.
-- An index created with a point count is built by `construct`: `train` and
- `set_centroids` throw `std::logic_error` for it.
-- `train` uses [RaBitQKMeans](../clustering.md#rabitqkmeans) for up to
- `kMaxRaBitQKMeansClusters` (2,000) clusters and
- [QGKMeans](../clustering.md#qgkmeans) above that, copying the fields the two
- parameter types share and keeping QGKMeans' default graph settings. The
- threshold is provisional and has not been measured. Only centroids are
- trained; `add` assigns the points. `cp.num_threads` also limits building the
- centroid routing.
-- `default_training_parameters(metric, seed)` runs 10 iterations on at most
- 256 sampled points per centroid and selects spherical k-means for inner
- product. The k-means classes keep their own defaults, which train on every point.
-- `train` and `set_centroids` replace the centroids only while the index stores
- no points, removed ones included; otherwise they throw `std::logic_error`.
- A failed call leaves the index unchanged.
-- `is_trained()` reports whether centroids are set. Before that, `add` and
- `search` throw `std::logic_error`. A trained index without points pads every
- `search` result slot with `kPidMax` and `+inf`; `save` throws
+- `train`, `set_centroids` and the first `add` follow the Python rules above,
+ including the thresholds, the defaults of `cp()` and the state checks.
+- Arguments outside their range throw `std::invalid_argument` (Python
+ `ValueError`), and a call in the wrong state throws `std::logic_error` (Python
+ `RuntimeError`), with the Python messages except where those name Python values
+ such as `None`.
+- `is_trained()` reports whether centroids are set. A trained index without
+ points pads every `search` result slot with `kNoId` and `+inf`; `save` throws
`std::logic_error` until the index stores at least one point.
+- `train` without a thread count and the first `add` without
+ `AddOptions::num_threads` train, and build the centroid routing, with
+ `cp().num_threads`; `add` quantizes with every available CPU unless
+ `num_threads` is set.
## Querying
To search a saved index, load it first:
```c++
-using index_type = rabitqlib::ivf::IVF;
-index_type ivf;
-ivf.load(index_file);
+auto ivf = rabitqlib::IvfIndex::load(index_file);
```
-Search a constructed or loaded index with:
+Search a trained or loaded index with:
```c++
-void IVF::search(
- const float* query,
+void IvfIndex::search(
+ const float* queries,
+ size_t num_queries,
size_t k,
- size_t nprobe,
- PID* result_ids,
- float* distances = nullptr
+ Id* ids,
+ float* distances,
+ const IvfSearchOptions& options = {}
) const;
```
-- **query**: Query vector.
-- **k**: Top-k.
-- **nprobe**: The number of closest clusters to search.
-- **result_ids**: Output ID buffer, size of `k`.
-- **distances**: Optional distance buffer, size of `k`.
+- **queries**: `num_queries` contiguous row-major float32 vectors of dimension `dim()`.
+- **k**: Results per query.
+- **ids**, **distances**: Output buffers of `num_queries * k` values; `distances` may be `nullptr`.
+- **options**: `nprobe`, `high_accuracy` and `num_threads`; see below.
FastScan precision is selected automatically: HACC for 4–9 quantized bits, and
standard FastScan for 1–3 bits or raw vectors (`32`). HACC reduces lookup-table
error carried into extra-bit distance estimation; raw reranking computes its
-final distances directly from floats. Existing C++ overloads with `use_hacc`
-and Python's `high_accuracy=True/False` still allow explicit overrides. Python
-uses automatic selection when `high_accuracy` is omitted or `None`.
+final distances directly from floats. `IvfSearchOptions::high_accuracy` (Python
+`high_accuracy=True/False`) overrides the selection; no value (Python `None`)
+selects automatically.
```cpp
-ivf.search(query, k, nprobe, ids, distances); // Automatic
-ivf.search(query, k, nprobe, ids, distances, true); // Force HACC
-ivf.search(query, k, nprobe, ids, distances, false); // Force standard FastScan
+rabitqlib::IvfSearchOptions options;
+options.nprobe = 64;
+ivf.search(queries, num_queries, k, ids, distances, options); // Automatic
+options.high_accuracy = true; // Force HACC
+ivf.search(queries, num_queries, k, ids, distances, options);
+options.high_accuracy = false; // Force standard FastScan
+ivf.search(queries, num_queries, k, ids, distances, options);
```
-The IDs-only overloads accept the same override without the `distances`
-argument. In Python, call `index.search(queries, k, nprobe)` for automatic
+In Python, call `index.search(queries, k, nprobe)` for automatic
selection, or pass `high_accuracy=True` / `False` to force either mode.
The querying examples also default to automatic selection; Python's
`--use-hacc` flag forces HACC, and the C++ example accepts an optional final
`true` or `false` argument.
-C++ `search_batch` distributes queries across workers.
-Input queries are contiguous row-major float32
-vectors with shape `(num_queries, dimension())`; output buffers have shape
-`(num_queries, k)`.
-
-```cpp
-ivf.search_batch(queries, num_queries, k, nprobe, ids, distances,
- std::nullopt, 4); // Automatic precision, up to four workers
-```
-
-The last two arguments are `std::optional use_hacc` (default
-`std::nullopt`) and `size_t num_threads` (default `1`, using OpenMP for parallel
-batches). Pass `true` or `false`
-for an explicit precision override. Distances may be `nullptr`. An empty batch
-does no work. Input and output buffers must not overlap. Simultaneous searches
-need separate output buffers, and must not overlap index updates.
-Python's existing `index.search(queries, k, nprobe, num_threads=4)` uses this
-batch path with the same output and precision rules.
+`num_threads` (default 1; 0 selects every available CPU) distributes the
+queries across OpenMP workers. An empty batch does no work. Input and output
+buffers must not overlap. Simultaneous searches need separate output buffers,
+and must not overlap index updates. Python's
+`index.search(queries, k, nprobe, num_threads=4)` takes the same settings.
Concurrent Python searches may use independent `nprobe`, `high_accuracy`, and
`num_threads` values. See the [concurrency contract](usage.md#threading-and-file-paths).
## Updating an index
-C++ `IVF` and Python `IvfIndex` support `add()` and `remove()` on a constructed
-or loaded index without the original dataset; C++ also adds to a
-[trained](#training-centroids-in-c) index. Updates preserve the file format.
+`IvfIndex` supports `add()` and `remove()` on a trained or loaded index without
+the original dataset. `save` always writes index format 2; see
+[how removal is stored](#how-removal-is-stored).
```c++
-void IVF::add(
- const float* data,
- size_t num_points,
- const PID* cluster_ids = nullptr,
- bool fast_quantization = false,
- size_t num_threads = std::numeric_limits::max()
-);
+Id IvfIndex::add(const float* data, size_t num_points, const AddOptions& options = {});
-size_t IVF::remove(const PID* ids_to_remove, size_t num_points);
+size_t IvfIndex::remove(const Id* ids, size_t num_ids);
-void IVF::reserve(PID cluster_id, size_t num_points);
+void IvfIndex::reserve_cluster(size_t cluster_id, size_t num_points);
```
-- **data**, **num_points**: `num_points` new vectors, quantized like `construct` does. Vector `i`
- receives the PID `num_stored_points() + i`, using the count before the call. Existing
- IDs stay unchanged, and removed IDs are never reused.
-- **cluster_ids**: The cluster of each new vector, in `[0, num_clusters)`. When
+- **data**, **num_points**: `num_points` new vectors. Vector `i` receives the ID
+ `num_stored_points() + i`, using the count before the call; `add` returns the
+ first. Existing IDs stay unchanged, and removed IDs are never reused.
+- **options.cluster_ids**: The cluster of each new vector, in `[0, num_clusters)`. When
it is `nullptr`, each vector goes to its nearest centroid under the index's
- routing type, the initializer selected at construction or restored from the
+ routing type, the one selected at creation or restored from the
index file. With Flat routing, `add` assigns exactly and queries scan in float,
so near-ties may resolve differently.
-- **fast_quantization**, **num_threads**: Same as in `construct`.
-- **ids_to_remove**: `num_points` PIDs to remove. Every PID must be below `num_stored_points()`; nothing is
+- **options.fast_quantization**, **options.num_threads**: As in [index construction](#index-construction).
+- **ids**, **num_ids**: IDs to remove. Every ID must be in `[0, num_stored_points())`; nothing is
removed if one is not. `remove` returns how many were newly removed and can be
repeated safely.
-- **cluster_id**, **num_points**: `reserve` preallocates room for cluster `cluster_id`
+- **cluster_id**, **num_points**: `reserve_cluster` preallocates room for cluster `cluster_id`
to hold `num_points` vectors in total, counting the ones it already holds. It does
nothing if the cluster already has that room. See [Cost of `add`](#cost-of-add).
-In Python:
+In Python, with `vectors` a float32 array of new vectors:
```python
new_ids = index.add(vectors, num_threads=1, fast_quantization=False)
@@ -398,20 +364,17 @@ removed = index.remove(new_ids[:10])
index.reserve_cluster(cluster_id, num_points)
```
-Python names this method `reserve_cluster` since 0.8.5; `reserve` still works, with a
-`DeprecationWarning`, until 0.9.
+In Python, `reserve_cluster` replaces `reserve`, which 0.9 removed.
Python `vectors` has shape `(n, index.dim)` and is converted to contiguous float32.
-`add()` returns a uint32 array of the new IDs. Optional `cluster_ids` must be a
+`add()` returns an int64 array of the new IDs. Optional `cluster_ids` must be a
one-dimensional integer array or sequence with one valid cluster ID per vector;
`remove()` likewise accepts a one-dimensional integer array or sequence of point
IDs and returns the number newly removed. Duplicate IDs count once. Python
`num_threads` defaults to `None` (every available CPU) and `fast_quantization` to
`False`; pass both by keyword.
-After appending, rebuilding with C++ `construct` requires `num_stored_points`
-rows, including removed records. Updates require exclusive
-access; see the
+Updates require exclusive access; see the
[concurrency contract](usage.md#threading-and-file-paths).
### Cost of `add`
@@ -427,7 +390,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` (Python `reserve_cluster`) first: later `add` calls then write into the reserved
+copying it, call `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.
@@ -455,37 +418,41 @@ enters the result buffer and never triggers reranking. Any code that estimates
IVF-RaBitQ distances must keep this behavior and must never turn `+inf` into NaN.
Search may return fewer than `k` results once points are removed: the missing slots
-hold `kPidMax` (`2**32 - 1` in Python) with an infinite distance, as when the probed
+hold ID `-1` (C++ `kNoId`) with an infinite distance, as when the probed
clusters hold fewer than `k` points.
The removal marker lives in the ordinary batch data and needs no additional
format change; removal survives `save` and `load`. No file written before
`remove` existed has an infinite `f_add`, so nothing in an old file is
reinterpreted. Release 0.5.0 also excludes removed points when reading its
-supported legacy formats. However, current saves always use `RABQIDX1` v2,
-including when resaving a loaded legacy index. Older releases cannot read these
+supported legacy formats. However, current saves always use index format 2,
+including when resaving a loaded legacy index. Releases up to 0.8 cannot read these
files, regardless of whether they contain removals.
## Persistence
-Save a constructed index with:
+Save an index that stores at least one point with:
```c++
ivf.save(output_index_file);
```
-New files use the `RABQIDX1` magic, version 2, storage flags, an explicit
-padded dimension, and a uint32 initializer type (1 = Flat, 2 = Flat RaBitQ,
-3 = HNSW) before the index metadata. `Auto` is resolved before saving. Loading
-restores the routing type, storage mode, rotation state, and padded dimension.
-Raw files also contain the original vectors, so querying does not require an external dataset.
-
-Version-1 `RABQIDX1` files remain readable with their stored padding. Legacy
-unversioned quantized files and raw v1 files retain their original 64-dimension
-padding. All three historical formats infer routing with the original 20,000
-cluster threshold. HNSW routing still requires the accompanying `.hnsw` file.
-Flat RaBitQ loads its saved codes without random re-quantization. Saving a loaded
-legacy index writes the new header without changing its padded dimension or encoded data. Older library
-versions cannot read the new format.
+Files are written in
+[index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2):
+one file with a header, a section table, and sections for the rotation, the routing
+data, the codes and the IDs. HNSW routing is a section of that file, so there is no
+separate sidecar. `Auto` is resolved before saving. Loading restores the routing type,
+storage mode, rotation state, and padded dimension. Raw files also contain the original
+vectors, so querying does not require an external dataset. Releases up to 0.8 cannot
+read format 2. Indexes of more than 65,536 dimensions cannot be saved.
+
+Files from earlier releases remain readable. `RABQIDX1` version 2 files store their
+routing type; version-1 `RABQIDX1` files keep their stored padding; legacy unversioned
+quantized files and raw v1 files retain their original 64-dimension padding. These three
+older layouts infer routing with the original 20,000 cluster threshold. All of these
+layouts keep HNSW routing in the accompanying `.hnsw` file, which loading reads.
+Flat RaBitQ loads its saved codes without random re-quantization. Saving a loaded file
+writes format 2 without changing its padded dimension or encoded data; a `.hnsw` file
+left beside it is not removed and is no longer used.
## Implementation details
@@ -493,7 +460,7 @@ versions cannot read the new format.
During construction, we process clusters in parallel, rotate their centroids and
vectors, and compute one-bit codes and factors. Quantized mode also computes
-`total_bits - 1` extra-bit codes and factors; raw mode stores the original
+`nbits - 1` extra-bit codes and factors; raw mode stores the original
float32 vectors instead. In raw mode, the index owns a copy of the input, so
the original data can be released after construction.
diff --git a/docs/docs/index/qg.md b/docs/docs/index/qg.md
index 76649734..3c054ea5 100644
--- a/docs/docs/index/qg.md
+++ b/docs/docs/index/qg.md
@@ -2,7 +2,7 @@
[SymphonyQG](https://dl.acm.org/doi/abs/10.1145/3709730) combines the graph search
of [QG](https://medium.com/@masajiro.iwasaki/fusion-of-graph-based-indexing-and-product-quantization-for-ann-search-7d1f0336d0d0),
-from [NGT](https://github.com/yahoojapan/NGT), with batched RaBitQ distance estimation.
+from [NGT](https://github.com/NGT-labs/NGT), with batched RaBitQ distance estimation.
FastScan estimates neighbor distances; visited vertices are scored using stored
raw vectors or quantized codes.
@@ -36,183 +36,140 @@ indexes, but has nothing to train: `train(x)` only checks `x` as `add` would,
and `is_trained` is always `True`. `add` builds the graph from every vector at once
and can be called only once, as in Faiss's NSG index; a second call, or `add` on
a loaded index, raises `RuntimeError`. To index more vectors, create a new index
-and add all of them. Point IDs are the row numbers of the added data. Files do
-not store the construction settings, so a loaded index reports
-`ef_construction`, `init` and `seed` as `None`.
+and add all of them. Point IDs are the row numbers of the added data. Files
+from releases up to 0.8 do not store the construction settings, so an index
+loaded from one reports `ef_construction`, `init` and `seed` as `None`.
### C++
-Link `rabitqlib::index`. Here `data` is a row-major `std::vector` with
-`rows * cols` values, and `query` contains `cols` values; use at least 33 rows.
-See [C++ integration](../cpp_integration.md) for build setup.
+`rabitqlib::SymqgIndex` has the names, defaults and behaviour of the Python
+class. Here `data` and `queries` are row-major `std::vector` buffers with
+dimension `dim`; use at least 33 data rows. See
+[C++ integration](../cpp_integration.md) for build setup.
```cpp
#include
-#include
-#include
-
-using namespace rabitqlib::symqg;
-
-// data contains rows * cols floats.
-QuantizedGraph qg(rows, cols, 32);
-{
- QGBuilder builder(qg, 200, data.data(), 1, QGInitialization::PiPNN);
- builder.build();
-} // release builder scratch before saving
-qg.set_ef(100);
-std::vector ids(10);
-std::vector distances(10);
-qg.search(query.data(), 10, ids.data(), distances.data());
-qg.save("qg_example.index");
+#include
+
+rabitqlib::SymqgIndex index(dim); // max_degree 32, ef_construction 200, PiPNN
+index.add(data.data(), data.size() / dim); // builds the whole graph
+index.save("qg_example.index");
+
+auto loaded = rabitqlib::SymqgIndex::load("qg_example.index");
+const size_t num_queries = queries.size() / dim;
+std::vector ids(num_queries * 10);
+std::vector distances(num_queries * 10);
+rabitqlib::GraphSearchOptions options;
+options.ef_search = 100;
+loaded.search(queries.data(), num_queries, 10, ids.data(), distances.data(), options);
```
+`add` throws `std::logic_error` (Python `RuntimeError`) on a built or loaded
+index, and `train` only checks its input.
+
## Parameters and limits
| Parameter | Contract |
| --- | --- |
-| `dim` | Original input dimension; Python supports 64–65,536 and pads internally. |
-| `nbits` / C++ `quantization_bits` | Python keyword: 32 (default) for owned raw vectors, or 4/8 for quantized storage. C++ uses 0 for raw vectors, as Python's `quantization_bits` did before 0.8. |
-| `max_degree` | Python keyword, default 32: a positive multiple of 32, strictly smaller than the point count. It is a hard degree bound, unlike HNSW-RaBitQ's `M`. |
-| `ef_construction` | Python keyword, default 200: positive construction search window used by `add`. |
-| `init` | Python keyword: `"pipnn"` (default) or `"random"`. |
-| `metric` | Python keyword: `"l2"` (default) 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_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
+| `dim` | Original input dimension, 64–65,536; the index pads internally. |
+| `nbits` | 32 (default) for owned raw vectors, or 4/8 for quantized storage. |
+| `max_degree` | Default 32: a positive multiple of 32, strictly smaller than the point count. It is a hard degree bound, unlike HNSW-RaBitQ's `M`. |
+| `ef_construction` | Default 200: positive construction search window used by `add`. |
+| `init` | `"pipnn"` (default) or `"random"`; C++ `symqg::QGInitialization::PiPNN` or `Random`. |
+| `metric` | L2 (default), inner product or [cosine](usage.md#the-cosine-metric): Python `"l2"`, `"ip"` or `"cosine"`. |
+| `seed` | Rotation and graph-construction seed in `[0, 2**32 - 1]`. The default (Python `None`, an empty C++ `std::optional`) draws one at random; `seed` reports it, and passing it back with one thread rebuilds the same graph from the same data. |
+| `k`, `ef_search` | `k` is from 1 to 2^31 and may exceed the point count; slots the graph cannot fill are padded with ID `-1` (C++ `kNoId`) and distance `+inf`. An omitted `ef_search` (Python `None`) uses `max(k, 64)`, an explicit 0 raises `ValueError` (C++ `std::invalid_argument`), and smaller values are raised to `k`, as for HNSW-RaBitQ. It replaces `ef`, which 0.9 removed. |
+| `num_threads` | `add` defaults to every available logical CPU, capped by `OMP_NUM_THREADS`, and `search` to 1; Python `None` and C++ 0 for `add` select the available CPUs. |
+
+In C++, the construction settings are fields of `SymqgOptions`, and `ef_search`
+and `num_threads` fields of `GraphSearchOptions`; `add` takes the thread count.
+Search returns IDs and distances (Python `(ids, distances)` arrays). Distances are squared
L2 or `1 - dot`, ordered from smallest to largest; quantized storage returns
estimates. SymphonyQG has no incremental add/remove API. See shared
[input, count and concurrency contracts](usage.md).
## Index construction
-See the shared [index count contract](usage.md#index-counts). C++
-`num_vertices()` returns the configured graph size, even before building.
+See the shared [index count contract](usage.md#index-counts). `num_points()` is 0
+until `add` builds the graph.
[PiPNN](https://dl.acm.org/doi/abs/10.1145/3770855.3817891) is the default initializer
for fast indexing, followed by one SymphonyQG refinement iteration. Random
initialization remains available and uses three iterations by default.
-Include `rabitqlib/index/symqg/qg.hpp` and `qg_builder.hpp` from the same directory,
-and link `rabitqlib::index`. The C++ API provides
-`rabitqlib::symqg::QuantizedGraph` and `QGBuilder`.
-Only float vectors are supported; C++17 declarations may omit `` through
-class template argument deduction:
+Include `rabitqlib/index/symqg_index.hpp` and link `rabitqlib::index`:
```cpp
-QuantizedGraph(
- size_t max_elements, size_t dim, size_t max_degree,
- MetricType metric_type = METRIC_L2,
- RotatorType rotator_type = RotatorType::FhtKacRotator,
- size_t quantization_bits = 0, uint32_t seed = std::random_device{}()
-);
-QGBuilder(
- QuantizedGraph& index, uint32_t ef_construction, const float* data,
- size_t num_threads = std::numeric_limits::max(),
- QGInitialization init = QGInitialization::PiPNN,
- uint32_t seed = std::random_device{}(), bool cache_vectors = false
-);
+rabitqlib::SymqgOptions options; // set the fields by name
+options.nbits = 4;
+options.init = rabitqlib::symqg::QGInitialization::Random;
+options.seed = 42;
+rabitqlib::SymqgIndex index(dim, options);
+index.add(data.data(), num_points, /*num_threads=*/1);
```
-`data` contains `max_elements * dim` floats. This is the configured point count;
-QG has no spare capacity for later appends. `max_degree` has the same constraints
-as Python's parameter. C++ defaults to all available threads. `build()` runs one refinement
-for PiPNN or three passes for `QGInitialization::Random`; `build(n)` requests
-`n >= 2` passes. The older overload with a numeric fifth argument uses that value
-as the random-initialization seed.
-
-### Input lifetime and rebuilds
-
-The caller can release input vectors after the `QGBuilder` constructor returns.
-Python retains the caller's array during `add`. Complete construction before
-querying or saving.
-
-`builder.reset(data)` reinitializes vectors of the same shape and reuses workspace.
-Input may be released after reset returns; rebuild before querying or saving.
-
-### Vector cache
-
-`cache_vectors=true` retains transformed vectors and query factors
-(`4 * max_elements * padded_dim` bytes plus factors). [QGKMeans](../clustering.md#qgkmeans) enables
-this for its centroid graph; the cache is not persisted.
+`add` builds a graph of exactly `num_points` vertices, so `data` contains
+`num_points * dim` floats; there is no spare capacity for later appends. It
+runs one refinement for PiPNN or three passes for random initialization. If
+`add` throws, the index stays without a graph and a later `add` can build one.
+The input may be released after `add` returns.
### Random seeds
-The graph seed controls the rotation. An FHT/Kac seed gives the same rotation on
-every platform; a MatrixRotator seed reproduces the matrix only with the same
-standard library and build, so rely on the saved index rather than the seed.
-The builder seed controls random initialization and fallback edges. PiPNN uses
-fixed internal seeds. Python's `seed` sets both the graph seed and the builder seed.
+The seed controls the FHT/Kac rotation, which is the same on every platform, and
+random initialization and fallback edges. PiPNN uses fixed internal seeds.
## Querying
-C++ search accepts one vector in the original input dimension and writes `k` IDs
-and distances:
+C++ search accepts contiguous row-major queries in the original input dimension
+and writes `num_queries * k` IDs and distances:
```cpp
-QuantizedGraph qg;
-qg.load("qg_example.index");
-qg.set_ef(100);
-
-std::vector ids(10);
-std::vector distances(10);
-qg.search(query.data(), 10, ids.data(), distances.data());
+void SymqgIndex::search(
+ const float* queries,
+ size_t num_queries,
+ size_t k,
+ Id* ids,
+ float* distances,
+ const GraphSearchOptions& options = {}
+) const;
```
-C++ `search_batch()` accepts contiguous row-major batches
-and reuses scratch storage within each worker, preserving the results of
-independent `search()` calls:
-
```cpp
-// queries contains num_queries * qg.dimension() floats in the original dimension.
-std::vector batch_ids(num_queries * 10);
-std::vector batch_distances(num_queries * 10);
-qg.search_batch(
- queries.data(), num_queries, 10, batch_ids.data(), batch_distances.data(), 4
-);
+auto qg = rabitqlib::SymqgIndex::load("qg_example.index");
+rabitqlib::GraphSearchOptions options;
+options.ef_search = 100;
+options.num_threads = 4;
+std::vector ids(num_queries * 10);
+std::vector distances(num_queries * 10);
+qg.search(queries.data(), num_queries, 10, ids.data(), distances.data(), options);
```
-The C++ signature is `search_batch(queries, num_queries, k, result_ids, distances,
-num_threads=1)`. Set `ef_search >= k` with `set_ef()` before searching. Both output
-buffers are required and contain `num_queries * k` elements. Empty C++ batches
-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.
+`distances` may be `nullptr`. Workers reuse scratch storage across their
+queries. Empty batches do no work. Inputs and outputs must not overlap.
+Concurrent searches may use different `ef_search` values but need separate
+outputs and an unchanged index.
Python `search(queries, k, ef_search=None, *, num_threads=None)` accepts a two-dimensional
query array and returns `(ids, distances)` arrays of shape `(num_queries, k)`,
including empty batches. It defaults to one worker; `num_threads=0` selects the
-available logical CPU count, capped by the number of queries. The 0.7 name
-`search_batch` still works in 0.8 with a `DeprecationWarning`.
+available logical CPU count, capped by `OMP_NUM_THREADS` and by the number of queries.
Queries use the original dimension, including when the internal rotation pads it.
-Python searches use per-call `ef_search` values. For access rules, see the
+Python searches also use per-call `ef_search` values. For access rules, see the
[concurrency contract](usage.md#threading-and-file-paths).
-For C++, use
-`search_batch_with_ef(queries, num_queries, k, result_ids, distances, ef_search, num_threads=1)`
-to run concurrent calls with independent windows:
-
-```cpp
-qg.search_batch_with_ef(
- queries.data(), num_queries, 10, batch_ids.data(), batch_distances.data(), 100, 4
-);
-```
-
-This method does not read or change the default set by `set_ef()`. The existing
-`search()`, `search_batch()`, and `search_with_scratch()` retain that default.
-All concurrent searches require separate outputs and an unchanged index.
-
See `sample/cpp/symqg_indexing.cpp`, `sample/cpp/symqg_querying.cpp`, and their
Python counterparts for complete examples.
## Persistence
+`save` writes [index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2), which also records the seed, `ef_construction`
+and `init`, so they survive a reload. Releases up to 0.8 cannot read these files; every
+earlier file still loads, without these settings, and saving it writes format 2.
+
All three modes pad the rotated domain to a multiple of 32. Loading an older
index preserves its saved padded dimension, including historical multiples of 64.
-Older library versions that enforce 64-dimension padding cannot load new files
-whose padded dimension is not a multiple of 64.
## Implementation details
diff --git a/docs/docs/index/usage.md b/docs/docs/index/usage.md
index 2afe6391..ada320ce 100644
--- a/docs/docs/index/usage.md
+++ b/docs/docs/index/usage.md
@@ -6,7 +6,8 @@ SymphonyQG. Start with the [Python quick start](../quick_start.md) for a complet
## Input requirements
`IvfIndex`, `HnswIndex`, and `SymqgIndex` accept data and query arrays with shape
-`(count, dim)`, converted to contiguous float32. Their FHT/Kac rotation requires
+`(count, dim)`, converted to contiguous float32; the C++ classes of the same names
+take row-major float32 buffers. Their FHT/Kac rotation requires
`64 <= dim <= 65536`. Supply the original dimension; the indexes pad internally
to a multiple of 32. Queries and centroids must have the same original dimension
as the indexed data.
@@ -22,20 +23,48 @@ float32. `train`, `set_centroids`, `add` and `search` raise `ValueError` (C++:
the index. The C++ `quantize_*` encoders in `core/encoder.hpp` assume their
callers have validated the input.
-These limits apply to the Python indexes. The C++ [stable core API](../rabitq/core_api.md)
+These limits apply to the index classes in both languages. The C++ [stable core API](../rabitq/core_api.md)
accepts working dimensions from 2, with multiples of 32 required for `SplitPacked`.
C++ [MatrixRotator](../rabitq/rotator.md) has separate dimension and storage requirements;
-the Python indexes do not expose a rotator choice.
+the index classes do not expose a rotator choice.
+
+## The cosine metric
+
+With `metric="cosine"` (C++ `METRIC_COSINE`), every index scales data and queries to
+unit length, stores the inner-product codes of the scaled vectors, and returns
+`1 - cos` as the distance, the inner-product distance `1 - dot` of unit vectors.
+Centroids passed to `set_centroids` are scaled the same way, because the codes are
+residuals against them: centroids far from the unit sphere, such as the means of
+unscaled data, would ruin the estimates. `train`, and the first `add` that trains,
+compute centroids from the scaled vectors with spherical k-means and use them as
+computed. Results equal those of a `metric="ip"` index built from the same vectors,
+and given the same centroids, after this scaling. A zero vector stays zero, as in
+hnswlib and Faiss: its true distance to every vector is 1, which quantized storage
+estimates like any other distance.
+
+The index checks the original coordinates first, as above. Because it then trains on
+scaled copies, invalid training data is reported as `IVF training data ...` or
+`HNSW training data ...` rather than with the k-means message of the other metrics.
+`train`, `add` and construction scale a copy of their whole input, so they briefly
+need memory for one more float32 copy of it. To bound that for very large data, call
+`train` on a sample and `add` the data in several calls. Queries are scaled one at a
+time.
+
+The metric is stored in the [index file](#index-file-compatibility), so a loaded index
+keeps scaling its inputs. Releases up to 0.8 have no cosine metric: there, normalize
+vectors yourself and use `metric="ip"`. The core quantization APIs, FastScan queries
+and clustering reject `METRIC_COSINE`.
## Index counts
-The unified count properties below are introduced in **0.7.0**. In particular,
-HNSW-RaBitQ's `num_points` now excludes removed records; see the
-[count migration guide](../modular_migration.md#unified-index-counts) when upgrading.
+`num_points` and `num_stored_points` were unified in **0.7.0**, when HNSW-RaBitQ's
+`num_points` started to exclude removed records; see the
+[count migration guide](../modular_migration.md#unified-index-counts) when upgrading
+from an earlier release. `capacity` is the property 0.7.0 called `max_elements`:
+Python renamed it in 0.8.5, and the C++ `HnswIndex` provides `capacity()` from 0.9.
IVF-RaBitQ, HNSW-RaBitQ, and SymphonyQG expose these read-only Python properties
-(C++ uses the same names with `()`, and `max_elements()` for the capacity of all
-three indexes):
+(the C++ classes use the same names with `()`):
| Property | Meaning |
| --- | --- |
@@ -44,11 +73,9 @@ three indexes):
| `capacity` (HNSW-RaBitQ only) | Logical record capacity, excluding SIMD padding |
`0 <= num_points <= num_stored_points`, and `num_stored_points <= capacity` for
-HNSW-RaBitQ. Before 0.8.5 Python named the capacity `max_elements` on all three
-classes; that property is deprecated and is removed in 0.9. On `IvfIndex` and
-`SymqgIndex` it equals `num_stored_points`, except on an `IvfIndex` created in the
-0.7 form before `build`, where it is the declared row count. Before vectors are
-added, both point counts are zero; configured capacity may be nonzero. For
+HNSW-RaBitQ. Python's `max_elements` property, which 0.9 removed, was this capacity
+on `HnswIndex` and equal to `num_stored_points` on the other two classes. Before
+vectors are added, both point counts are zero; configured capacity may be nonzero. For
all three indexes, `len(index)` equals `num_points`. `is_trained` reports
whether IVF-RaBitQ or HNSW-RaBitQ centroids are set (by `train`, `set_centroids`,
the first `add`, or `load`), and is always `True` for SymphonyQG.
@@ -58,13 +85,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 `reserve` preallocates
-it (`resize` before 0.8.5). SymphonyQG has no incremental
+HNSW-RaBitQ's `add` grows its capacity geometrically, and `reserve` preallocates
+it. SymphonyQG has no incremental
updates: `add` builds the graph once, and both counts are equal afterwards.
`repr(index)` shows dimension, metric, quantization bits and live point count,
-plus the training state for IVF/HNSW. IVF/HNSW also show stored count, capacity and centroid count; IVF includes
-the resolved routing strategy, and SymphonyQG includes its degree bound. The summary
+plus the training state for IVF/HNSW. IVF/HNSW also show stored count and centroid count; HNSW includes
+its capacity, IVF the resolved routing strategy, and SymphonyQG its degree bound. The summary
reads only metadata and follows the same concurrency rules as property reads.
## Estimate storage
@@ -93,7 +120,7 @@ IVF-RaBitQ allocates one-bit codes and their three factors in full batches of 32
use the stored point count. Small clusters therefore increase padding overhead.
Centroids, routing structures and cluster metadata are additional.
-HNSW-RaBitQ allocates base-layer records for `max_elements`, including unused capacity.
+HNSW-RaBitQ allocates base-layer records for its whole `capacity`, including unused capacity.
Upper-layer edges, label maps, locks, visited lists and other bookkeeping are
additional. Removing points does not reclaim their storage in either IVF-RaBitQ or HNSW-RaBitQ.
@@ -123,15 +150,15 @@ construction, updates, and file I/O. The following contract applies to
| Operation on the same index | Concurrent access |
| --- | --- |
-| `search`, `search_batch`, `save`, `repr`, and property reads | May run together |
-| `train`, `set_centroids`, `build`, `add`, `remove`, `reserve`, `reserve_cluster`, `resize`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input and may run with reads |
+| `search`, `save`, `repr`, and property reads | May run together |
+| `train`, `set_centroids`, `add`, `remove`, `reserve`, `reserve_cluster`, and setting `cp`, where available | Require exclusive access, except SymphonyQG's `train`, which only checks its input, and an HNSW-RaBitQ `reserve` within the current capacity, which changes nothing; both may run with reads |
A conflicting call immediately raises
`RuntimeError("Index is busy: conflicting operation in progress")`.
It does not wait or queue an update. Access protection includes Python input
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.
+different output paths.
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
@@ -150,12 +177,11 @@ example Faiss or PyTorch wheels) can crash when more than one of them starts
worker threads in the same process; set `OMP_NUM_THREADS=1` before the first
native call, or pass `num_threads=1`, in such processes.
`train` and `add` on every index, and IVF-RaBitQ `set_centroids`, default to all
-CPUs (`None` or `0`); the clustering classes default to `0`. `search` defaults to one thread (`None` or `1`),
-as do the deprecated `build`, which requires an integer, and `search_batch`.
+CPUs (`None` or `0`); the clustering classes default to `0`. `search` defaults to one thread (`None` or `1`).
Multithreaded HNSW-RaBitQ `add` links points in a nondeterministic order, and so
does a multithreaded build of IVF-RaBitQ's HNSW centroid routing by `train`,
-`set_centroids` or the first `add`; pass `num_threads=1` when a build must be
-reproducible.
+`set_centroids` or the first `add`; pass `num_threads=1`, and `seed=` to the
+constructor, when a build must be reproducible.
On Linux, CPU detection accounts for affinity and OpenMP binding. Apply binding
before starting the program.
@@ -163,25 +189,34 @@ C++ paths use UTF-8 on Windows and native path bytes on POSIX.
Python `save`/`load` accept strings, `pathlib.Path` and `os.PathLike` objects;
existing `bytes` and `bytearray` paths remain supported. POSIX paths preserve native
bytes, but non-UTF-8 filenames require filesystem support. Windows byte paths use
-UTF-8. Embedded null characters are rejected before file access. IVF HNSW sidecars
-use the same path conversion.
+UTF-8. Embedded null characters are rejected before file access. The HNSW sidecars
+of IVF files from earlier releases use the same path conversion.
`save` writes a temporary file beside the destination and renames it into place, so a
failed save leaves an existing index unchanged. A replaced file keeps its permission
bits, but not its owner or other hard links. Symbolic links and other non-regular
-destinations are written in place. IVF renames its HNSW sidecar before the index file;
-a failure between the two renames can leave a new sidecar beside the old index.
+destinations are written in place. IVF-RaBitQ writes one file that includes its HNSW
+routing graph.
## Index file compatibility
-The compatibility suite loads frozen files written by v0.5.2, compares search
-IDs and distances, and verifies save/load migration and rejection of truncated
-or unsupported versions. See the
+The compatibility suite loads frozen files written by v0.5.2, v0.8.3 and v0.9.0, compares
+search IDs and distances, and verifies save/load migration and rejection of truncated
+or unsupported versions. Every index saves in
+[index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2),
+which releases up to 0.8 cannot read, and which records the construction seed. See the
[fixture provenance and coverage](https://github.com/VectorDB-NTU/RaBitQ-Library/tree/main/tests/fixtures/persistence).
Compatibility is format-specific; preserving old readers' ability to open new
files is not guaranteed. Consult each index's format documentation before
downgrading the library.
+A truncated, corrupt, mismatched or unsupported file raises `rabitqlib.FormatError`,
+a subclass of both `ValueError` and `RuntimeError`, so `except RuntimeError`
+handlers still catch it. A file that cannot be opened raises a plain `RuntimeError`;
+a read that fails after opening looks like truncation and raises `FormatError`.
+C++ loaders throw `rabitqlib::FormatError` from `rabitqlib/index/format_error.hpp`,
+a subclass of `std::runtime_error`.
+
Index files are trusted input. Loaders validate structure and reject truncated,
inconsistent, or unsupported files so that mistakes are reported, but they are
not a security boundary: a crafted file can make `load` allocate its stored
diff --git a/docs/docs/installation.md b/docs/docs/installation.md
index d907f92f..d365d95e 100644
--- a/docs/docs/installation.md
+++ b/docs/docs/installation.md
@@ -1,6 +1,6 @@
# Installation
-Platform requirements and source installation for RaBitQ Library **0.8.5**.
+Platform requirements and source installation for RaBitQ Library **0.9.0**.
For the first Python example, see [Quick Start](quick_start.md).
## Requirements
@@ -40,10 +40,12 @@ build can use scalar kernels without the FastScan CPU baseline.
## Python wheels
```bash
-python -m pip install "rabitqlib>=0.8.5"
+python -m pip install "rabitqlib>=0.9.0"
```
-For changes from 0.6.0, see the [0.7.0 upgrade notes](releases/0.7.0.md).
+To upgrade from 0.8, see the [migration guide](python_migration.md#from-08-to-09) and the
+[0.9.0 release notes](releases/0.9.0.md). For changes from 0.6.0, see the
+[0.7.0 upgrade notes](releases/0.7.0.md).
Wheels target the platforms above and require no compiler or CMake.
Every wheel bundles its OpenMP runtime (GNU OpenMP on Linux, LLVM OpenMP on
@@ -61,11 +63,11 @@ importing those classes. Array shapes and parameter ranges are still checked at
## Get the source
-For Python source builds or C++ use, obtain the 0.8.5 checkout once. With Git
+For Python source builds or C++ use, obtain the 0.9.0 checkout once. With Git
installed, run:
```bash
-git clone --branch v0.8.5 --depth 1 https://github.com/VectorDB-NTU/RaBitQ-Library.git
+git clone --branch v0.9.0 --depth 1 https://github.com/VectorDB-NTU/RaBitQ-Library.git
cd RaBitQ-Library
```
diff --git a/docs/docs/integrations/txtai.md b/docs/docs/integrations/txtai.md
index 000abe6c..a2ed6e97 100644
--- a/docs/docs/integrations/txtai.md
+++ b/docs/docs/integrations/txtai.md
@@ -5,10 +5,17 @@
embedding-search workflow, while txtai handles the surrounding application API
and result conversion.
-This walkthrough was checked on October 21, 2026 against txtai commit
-[`0ea7cb0d8234`][snapshot]. It describes the downstream adapter at that revision;
-it is a source snapshot, not a verification of every published txtai package.
-Consult the [current configuration reference][current-config] for later changes.
+This walkthrough was checked on November 20, 2026 against txtai commit
+[`86f3bad`][snapshot], which moved the adapter to forms that rabitqlib 0.8.5 and 0.9
+accept ([neuml/txtai#1616](https://github.com/neuml/txtai/pull/1616)). It describes
+the downstream adapter at that revision; it is a source snapshot, not a verification
+of every published txtai package. Consult the [current configuration reference][current-config]
+for later changes.
+
+rabitqlib 0.9 needs txtai 9.15.0 or later. txtai 9.14.0, the first release with
+the backend, uses call forms that 0.9 removes and fails with it; rabitqlib 0.8
+still accepts them, with deprecation warnings. Its `ann` extra only declares
+`rabitqlib>=0.5.1`, so with txtai 9.14.0 keep `rabitqlib<0.9`.
## Select the backend
@@ -25,7 +32,7 @@ rabitq:
Keep your existing embedding model and other application settings. Install
optional dependencies according to [txtai's installation guide][install]; its
adapter imports both `rabitqlib` and scikit-learn. The inspected
-[package configuration][dependencies] declares `rabitqlib>=0.7.0` in its `ann` extra. The fragment above selects
+[package configuration][dependencies] declares `rabitqlib>=0.8.5` in its `ann` extra. The fragment above selects
the backend, rather than providing a complete model-and-data example.
`clusters` controls the KMeans centroid count in both modes: IVF-RaBitQ uses these
@@ -41,8 +48,8 @@ The [adapter source][adapter] shows the boundary between the projects:
| Stage | txtai's role | RaBitQ-Library's role |
| --- | --- | --- |
-| Build | Converts embeddings to contiguous float32 and uses scikit-learn KMeans to produce centroids and assignments. | Builds `IvfIndex` or `HnswIndex` with the inner-product metric. |
-| Search | Selects `nprobe` or `ef`, drops missing-result IDs, and converts returned distances to scores with `1 - distance`. | Searches the native index and returns IDs and distances; quantized modes return estimates, while IVF-RaBitQ raw mode uses original-vector reranking. |
+| Build | Converts embeddings to contiguous float32 and uses scikit-learn KMeans to produce centroids and assignments. | Creates `IvfIndex` or `HnswIndex` with the inner-product metric, takes the centroids with `set_centroids`, and adds the embeddings with `add(cluster_ids=...)`. |
+| Search | Selects `nprobe` or `efsearch`, drops unfilled result slots by their infinite distance, and converts returned distances to scores with `1 - distance`. | Searches the native index and returns IDs and distances; quantized modes return estimates, while IVF-RaBitQ raw mode uses original-vector reranking. |
| Persistence | Calls the backend's save/load methods. | Stores and restores the native index state. |
| Updates | Routes IVF-RaBitQ append/delete requests to the backend. | Adds vectors or removes them from search. |
@@ -62,9 +69,14 @@ The adapter requests inner-product search and converts its `1 - dot` distance
convention back to scores. For normalized database and query embeddings, these are cosine-similarity
estimates in quantized modes; normalization does not remove quantization error.
-The source inspection establishes the integration path. It does not establish
-production deployment scale or a performance gain, and this configuration has
-not been exercised end to end in this documentation update.
+The first build adds with every available CPU, capped by `OMP_NUM_THREADS`, so an
+HNSW-RaBitQ graph built with several threads differs between runs even with the same
+`randomseed`. An index saved with rabitqlib 0.9 uses index format 2, which rabitqlib 0.8
+cannot read.
+
+txtai's RaBitQ tests pass with this adapter on rabitqlib 0.8.5 and on a 0.9 build.
+That establishes the integration path, not production deployment scale or a
+performance gain.
For maintainer checks against future library versions, see the
[downstream compatibility procedure](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/development.md#downstream-compatibility-validation).
@@ -73,11 +85,11 @@ To use the same indexes directly, follow the library's [Python quick start](../q
and [HNSW-RaBitQ guide](../index/hnsw.md). To integrate only quantization into your own
index, see the [zvec walkthrough](zvec.md).
-[snapshot]: https://github.com/neuml/txtai/tree/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b
-[adapter]: https://github.com/neuml/txtai/blob/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b/src/python/txtai/ann/dense/rabitq.py
-[config]: https://github.com/neuml/txtai/blob/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b/docs/embeddings/configuration/ann.md#rabitq
+[snapshot]: https://github.com/neuml/txtai/tree/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b
+[adapter]: https://github.com/neuml/txtai/blob/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b/src/python/txtai/ann/dense/rabitq.py
+[config]: https://github.com/neuml/txtai/blob/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b/docs/embeddings/configuration/ann.md#rabitq
[current-config]: https://github.com/neuml/txtai/blob/master/docs/embeddings/configuration/ann.md#rabitq
[install]: https://neuml.github.io/txtai/install/#ann
-[dependencies]: https://github.com/neuml/txtai/blob/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b/setup.py
-[base]: https://github.com/neuml/txtai/blob/0ea7cb0d8234497e8ea9ed1a0f2f58492e00460b/src/python/txtai/ann/base.py
+[dependencies]: https://github.com/neuml/txtai/blob/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b/setup.py
+[base]: https://github.com/neuml/txtai/blob/86f3bad49de8fe3f1b2cb4b0f3e3166afb84820b/src/python/txtai/ann/base.py
diff --git a/docs/docs/modular_migration.md b/docs/docs/modular_migration.md
index 801282f9..d6cd5d7e 100644
--- a/docs/docs/modular_migration.md
+++ b/docs/docs/modular_migration.md
@@ -168,14 +168,15 @@ in C++ and Python.
Compared with the 0.6.0 Python API, IVF-RaBitQ adds `num_points` and `num_stored_points`,
HNSW-RaBitQ adds `num_stored_points`, and SymphonyQG adds `max_elements` and
-`num_stored_points`.
+`num_stored_points`. 0.9 removes the Python `max_elements` property; see the
+[migration guide](python_migration.md#from-08-to-09).
**HNSW-RaBitQ `num_points` now excludes removed records.** Use `num_stored_points` for
ID bounds, append offsets, and minimum resize capacity. Use `num_points` for a
live count, without subtracting a separate deletion counter.
-The IVF-RaBitQ constructor keyword `max_elements` still specifies the required initial
-build size; 0.8 deprecates it (see [Migrating to 0.8](python_migration.md)). SymphonyQG's C++ `num_vertices()` still returns the configured graph
+In 0.7, the IVF-RaBitQ constructor keyword `max_elements` still specified the required
+initial build size; 0.8 deprecated it and 0.9 removed it (see the [migration guide](python_migration.md)). SymphonyQG's C++ `num_vertices()` still returns the configured graph
size for builders. Existing index files need no conversion: loading recovers
counts from their removal markers.
diff --git a/docs/docs/python_migration.md b/docs/docs/python_migration.md
index aa0e72a2..4ad9721f 100644
--- a/docs/docs/python_migration.md
+++ b/docs/docs/python_migration.md
@@ -1,31 +1,34 @@
-# Migrating Python code from 0.7 to 0.8
+# Migrating Python code to 0.9
-In 0.8, `IvfIndex`, `HnswIndex` and `SymqgIndex` follow a `train` → `add` →
+Since 0.8, `IvfIndex`, `HnswIndex` and `SymqgIndex` follow a `train` → `add` →
`search` workflow, as Faiss indexes do; since 0.8.2 the first `add` trains, so
construct → `add` → `search` is enough, and `train` remains for training on a
sample. IVF-RaBitQ and HNSW-RaBitQ learn their own centroids, so you no longer
run k-means and pass the centroids and assignments to `build`; SymphonyQG has
nothing to train and builds its graph in `add`. Code written for 0.7
-still runs in 0.8. Each old form raises a `DeprecationWarning` at your call site
-and will be removed in **0.9**.
+still runs in 0.8, where each old form raises a `DeprecationWarning` at your call
+site. **0.9 removes those forms**: a removed call raises `TypeError`, and a removed
+attribute `AttributeError`.
If your code already uses the 0.8 forms, go to
-[From 0.8 to 0.9](#from-08-to-09): 0.9 renames some of them, and 0.8.5 accepts
-the new names.
+[From 0.8 to 0.9](#from-08-to-09): 0.9 renames some of them. 0.8.5 accepts both
+spellings, so you can make every change on 0.8.5, with its warnings as a guide,
+before upgrading.
-Unless an item below says otherwise, a 0.7 call that raises a deprecation
-warning keeps its 0.7 behavior. Calls that are valid in both versions, such as
-`add(x)` and `search`, follow the 0.8 rules.
+The tables below give each replacement in its 0.9 spelling. In 0.8, a 0.7 call
+that raises a deprecation warning keeps its 0.7 behavior unless an item says
+otherwise, and calls that are valid in both versions, such as `add(x)` and
+`search`, follow the 0.8 rules.
## IVF-RaBitQ and HNSW-RaBitQ
### Old and new calls
-| 0.7 | 0.8 |
+| 0.7 | Since 0.8 |
| --- | --- |
| `IvfIndex(dim, max_elements, num_clusters, nbits, metric, initializer)` | `IvfIndex(dim, num_clusters, nbits=..., metric=..., routing=..., seed=None)` (`initializer=` before 0.8.5); storage grows on `add` |
| `IvfIndex(dim=..., max_elements=..., num_clusters=..., nbits=...)` | the same, without `max_elements` |
-| `HnswIndex(dim, max_elements, M=16, ef_construction=200, nbits=8, metric="l2", random_seed=100)` | `HnswIndex(dim, nbits=..., num_clusters=16, M=16, ef_construction=200, metric="l2", seed=100)`; capacity grows on `add`, and `reserve(n)` preallocates it (`resize(n)` before 0.8.5) |
+| `HnswIndex(dim, max_elements, M=16, ef_construction=200, nbits=8, metric="l2", random_seed=100)` | `HnswIndex(dim, nbits=..., num_clusters=16, M=16, ef_construction=200, metric="l2", seed=None)` (`seed=100` in 0.8); capacity grows on `add`, and `reserve(n)` preallocates it (`resize(n)` before 0.8.5) |
| `HnswIndex(..., random_seed=s)` | `HnswIndex(..., seed=s)` |
| `kmeans = RaBitQKMeans(dim, k)` `kmeans.train(x)` `index.build(x, kmeans.centroids, kmeans.assignments)` | `index.add(x)`, which trains on `x` first (since 0.8.2; in 0.8.0 and 0.8.1, call `index.train(x)` first) |
| `index.build(x, centroids, cluster_ids)` | `index.set_centroids(centroids)` `index.add(x, cluster_ids=cluster_ids)` |
@@ -33,11 +36,11 @@ warning keeps its 0.7 behavior. Calls that are valid in both versions, such as
| `index.is_built` | `index.is_trained`, or `len(index) > 0` for "holds vectors" |
Except for `dim` and IVF-RaBitQ's `num_clusters`, constructor arguments are
-keyword-only in 0.8. Since 0.8.2, `nbits` defaults to 7 (0.8.0 and 0.8.1 required
-it). HNSW-RaBitQ used to default to `nbits=8`; the old form keeps that default.
+keyword-only since 0.8. Since 0.8.2, `nbits` defaults to 7 (0.8.0 and 0.8.1 required
+it). HNSW-RaBitQ used to default to `nbits=8`.
`train` uses the settings in `index.cp`: 10 iterations (25 before 0.8.2), at most 256 sampled
-vectors per centroid, spherical k-means for `metric="ip"`, and the index seed.
+vectors per centroid, spherical k-means for `metric="ip"` (and, from 0.9, `"cosine"`), and the index seed.
See [IVF-RaBitQ training](index/ivf.md#training-centroids-in-python) for the
details and for `set_centroids`. The [clustering classes](clustering.md) still
work if you want to run k-means yourself.
@@ -50,11 +53,10 @@ work if you want to run k-means yourself.
the same default and takes `num_threads`; before, it always used every CPU and
ignored `OMP_NUM_THREADS`. This applies to every `add` call that does not
pass `num_threads`, including 0.7 code such as `index.add(x)`, without a
- warning. `search` still defaults to one thread, and the deprecated `build`
- keeps its default of 1.
+ warning. `search` still defaults to one thread.
- **HNSW-RaBitQ builds are not reproducible by default.** With more than one
thread, `add` links points in a nondeterministic order. Pass `num_threads=1`
- to `add` for the same graph on every run. With one thread and the same seed,
+ to `add`, and since 0.9 a `seed`, for the same graph on every run. With one thread and the same seed,
`set_centroids` followed by `add` produces exactly the index that 0.7 `build`
produced from the same centroids and cluster IDs.
- **IVF-RaBitQ HNSW routing builds are not reproducible by default.** 0.7 `build`
@@ -65,11 +67,10 @@ work if you want to run k-means yourself.
- **`k` above the point count.** 0.8.0 and 0.8.1 raised `ValueError` when `k`
exceeded `num_stored_points` (HNSW-RaBitQ) or the point count (IVF-RaBitQ,
SymphonyQG). Since 0.8.2, every index accepts any `k >= 1` and fills missing
- slots with ID `2**32 - 1` and distance `inf`; test `np.isfinite(distances)`.
+ slots with ID `2**32 - 1` (`-1` since 0.9) and distance `inf`; test
+ `np.isfinite(distances)`, which works in both.
- **HNSW-RaBitQ capacity grows.** `add` resizes the index, at least doubling it,
- instead of raising `ValueError` when the batch does not fit. This also applies
- to `add` on indexes created in the old form, and to the deprecated `build`,
- which no longer rejects more rows than `max_elements`.
+ instead of raising `ValueError` when the batch does not fit.
- **State errors.** Calling `add` with `cluster_ids`, `search`, `remove`,
`reserve_cluster` (`reserve` before 0.8.5) or `save` before training raises `RuntimeError("IvfIndex must be
trained or loaded before ...")`; the 0.7 message said "built". Since 0.8.2,
@@ -77,52 +78,51 @@ work if you want to run k-means yourself.
cannot be saved. `repr` shows `is_trained` instead of `is_built`.
- **Seeds.** `IvfIndex` still draws a random rotation seed by default, and now
reports it as `index.seed`; pass it back as `seed=` to reproduce an index.
- Indexes loaded from files report `seed=None`.
+ Indexes loaded from files written by releases up to 0.8 report `seed=None`.
- **HNSW-RaBitQ `num_clusters`** reports the configured count (16 by default)
before training, where 0.7 reported 0 before `build`.
-- An `IvfIndex` created with `max_elements` is filled by `build`; `train` and
- `set_centroids` raise `RuntimeError` for it. Create the index in the 0.8 form
- to train it.
## SymphonyQG
-| 0.7 | 0.8 |
+| 0.7 | Since 0.8 |
| --- | --- |
| `SymqgIndex(dim, max_degree, metric, quantization_bits)` | `SymqgIndex(dim, max_degree=..., metric=..., nbits=...)`; every argument after `dim` is keyword-only |
| `quantization_bits=0` (raw vectors), `4`, `8` | `nbits=32` (raw vectors, the default), `4`, `8` |
| `index.build(x, ef_construction, num_threads, init)` | `SymqgIndex(dim, ef_construction=..., init=..., seed=...)` `index.add(x, num_threads=...)` |
-| `index.search_batch(q, k, ef)` | `index.search(q, k, ef)`; `ef` is now optional |
+| `index.search_batch(q, k, ef)` | `index.search(q, k, ef_search)`; the breadth is now optional |
| `index.quantization_bits` | `index.nbits` (32 instead of 0 for raw vectors) |
| `index.is_built` | `len(index) > 0` |
`train(x)` exists for a uniform workflow but only checks `x` as `add` would,
and `is_trained` is always `True`. `add` builds the graph from all vectors and can run only once;
a second `add`, or `add` on a loaded index, raises `RuntimeError`, as Faiss's
-NSG index does. The deprecated `build` keeps its 0.7 behavior: it replaces any
-existing graph and, unless you passed `seed`, draws a new random seed each time.
+NSG index does; create a new index to rebuild, where 0.7 `build` replaced the
+existing graph.
`search` now treats its breadth (`ef_search`; `ef` before 0.8.5) like HNSW-RaBitQ:
omitted, it uses
`max(k, 64)` (`max(k, 10)` before 0.8.2), and a smaller one is raised to `k`. In 0.7, both raised
-`ValueError`. `add` uses every CPU by default, while the deprecated `build`
-keeps one thread. The seed now also drives graph construction: without `seed`,
+`ValueError`. `add` uses every CPU by default, where `build` used one thread.
+The seed now also drives graph construction: without `seed`,
each index draws one random seed and reports it as `index.seed`; 0.7 drew
separate random seeds for the rotation and the graph. Before vectors are added,
`search` and `save` raise `RuntimeError("SymqgIndex has no vectors; ...")`.
## Files and C++
-Saved files are unchanged, and so is the `max_elements` property up to 0.8.4 (see
+Saved files are unchanged in 0.8, and so is the `max_elements` property up to 0.8.4 (see
[From 0.8 to 0.9](#from-08-to-09)). `HnswIndex.search`
without a search breadth uses `max(k, 64)` since 0.8.2 (`max(k, 10)` before), which changes
its results and latency; pass the breadth as the third argument to keep the old window. Files written by 0.7
load as trained indexes, except empty, untrained HNSW-RaBitQ files, which need
`train` before `add`.
-For C++, the existing constructors and `construct` are unchanged; see
-[IVF-RaBitQ](index/ivf.md#training-centroids-in-c) and
-[HNSW-RaBitQ](index/hnsw.md#training-centroids-in-c) for the new training entry
-points. C++ behavior changes: since 0.8.0, saving an index without stored points
+For C++ in 0.8, the existing index constructors and `construct` are unchanged, and
+`IVF::train` and `HierarchicalNSW::train` are the new training entry points; from
+0.9 the [IVF-RaBitQ](index/ivf.md#training-centroids-in-c) and
+[HNSW-RaBitQ](index/hnsw.md#training-centroids-in-c) pages describe `IvfIndex` and
+`HnswIndex` instead, and the [release notes](releases/0.9.0.md#c-changes) map the
+0.8 classes to `IvfIndex`, `HnswIndex` and `SymqgIndex`. 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).
@@ -132,11 +132,12 @@ iterations. See the [0.8.2 notes](releases/0.8.2.md#c-changes).
0.9 gives the three index classes one name for each concept
([#232](https://github.com/VectorDB-NTU/RaBitQ-Library/issues/232)). Since 0.8.5 the
0.8 form in the first column raises a `DeprecationWarning` at your call site; 0.9
-removes it.
+removes it. A removed name or call form then raises `AttributeError` or `TypeError`,
+and a zero breadth or an out-of-range seed raises `ValueError`.
| 0.8 | Use instead | Works since |
| --- | --- | --- |
-| `IvfIndex.max_elements`, `SymqgIndex.max_elements` | `num_stored_points` | Every 0.8 release. The two are equal, except on an `IvfIndex` created in the 0.7 form before `build`. |
+| `IvfIndex.max_elements`, `SymqgIndex.max_elements` | `num_stored_points` | Every 0.8 release. The two are equal in 0.8, except on an `IvfIndex` created in the 0.7 form before `build`. |
| `HnswIndex.max_elements` | `HnswIndex.capacity` | 0.8.5 |
| `HnswIndex.resize(n)` | `HnswIndex.reserve(n)`, which only grows the capacity; `resize` could also shrink it | 0.8.5 |
| `IvfIndex.reserve(cluster_id, num_points)` | `IvfIndex.reserve_cluster(cluster_id, num_points)` | 0.8.5 |
@@ -175,8 +176,42 @@ mode = mode if isinstance(mode, str) else mode.name.lower()
Code that must also run on releases before 0.8.5 needs a version check for the rows
marked 0.8.5; the other replacements work on every release named.
-Three changes come without a warning in 0.9. `HnswIndex()` without `seed=` draws a seed,
+In C++, `QGKMeansParameters` takes the same three field renames in 0.9, without a
+transition release, and `FinalAssignmentMode::SymphonyQG` and the two statistics
+aliases are removed; see the [0.9 notes](releases/0.9.0.md#c-changes).
+
+Four changes come without a warning in 0.9. `HnswIndex()` without `seed=` draws a seed,
as `IvfIndex` and `SymqgIndex` already do, instead of using 100: pass `seed=` (and
`num_threads=1` to `add`) if you rely on a reproducible build. `repr(index)` prints
-`capacity=` and `routing=` where it prints `max_elements=` and `initializer=`. And
-`cp.final_assignment` reads back as a string, as described above.
+`capacity=` for `HnswIndex` and `routing=` for `IvfIndex` where it prints `max_elements=`
+and `initializer=`, and no longer prints `max_elements=` for `IvfIndex`. The metric
+spelling `"innerproduct"` raises `ValueError` on the index classes and in
+`rabitqlib.quant`: use `"ip"`, which every release accepts and the `metric` properties
+return. And `cp.final_assignment` reads back as a string, as described above.
+
+0.9 also changes behavior that no warning can announce:
+
+- `search` and `add` return `int64` IDs, with `-1` instead of `2**32 - 1` for a missing
+ result.
+- `save` writes index format 2, which releases up to 0.8 cannot read, and `load`
+ restores the seed of such a file. Files from earlier releases still load, without a
+ recorded seed.
+- An `IvfIndex` with HNSW routing stores the routing graph in the index file, so `save`
+ no longer writes a `.hnsw` sidecar. A sidecar left by an earlier save is not
+ removed; the new file does not use it.
+- `load` raises the new `rabitqlib.FormatError` for a truncated, corrupt, mismatched or
+ unsupported file. It subclasses `RuntimeError`, which these errors raised before, and
+ `ValueError`; `rabitqlib.quant.FormatError` is now the same class. A file that cannot
+ be opened, or the missing sidecar of an earlier file, still raises a plain
+ `RuntimeError`. The messages for damaged files change, so match the exception class
+ rather than its text.
+- The index classes are the extension's own classes, without Python wrappers. A wrong
+ argument raises pybind11's `TypeError`, which lists the supported signatures, instead
+ of messages such as `IvfIndex() got an unexpected keyword argument 'x'`, and
+ `inspect.signature()` no longer works on their constructors and methods; `help()` and
+ the type stubs describe them.
+- A call with both an invalid argument and the wrong state may report the argument
+ first, for example `ValueError` instead of `RuntimeError` for `nprobe=0` on an
+ untrained index.
+
+See the [0.9 notes](releases/0.9.0.md) for every change.
diff --git a/docs/docs/quick_start.md b/docs/docs/quick_start.md
index c4ea730c..a7235284 100644
--- a/docs/docs/quick_start.md
+++ b/docs/docs/quick_start.md
@@ -1,14 +1,14 @@
# Quick start
Build, search, save and reload a small IVF-RaBitQ index with Python. This guide describes
-**0.8.5** and uses synthetic data, so no dataset download is required. Coming from 0.7?
+**0.9.0** and uses synthetic data, so no dataset download is required. Coming from 0.8 or 0.7?
See the [migration guide](python_migration.md).
For C++, go directly to [C++ integration](cpp_integration.md).
## Install
```bash
-python -m pip install "rabitqlib>=0.8.5"
+python -m pip install "rabitqlib>=0.9.0"
```
Wheels support CPython 3.11–3.14 on Linux x86-64/ARM64, Windows x86-64 and
@@ -45,7 +45,7 @@ print(ids[0])
The first `add` on an untrained index trains it on the added vectors, as
`index.train(data)` would, then adds them. Training uses the settings in
`index.cp`: 10 k-means iterations on at most 256 sampled vectors per centroid,
-spherical k-means for `metric="ip"`, and the index `seed`. Change `index.cp`
+spherical k-means for `metric="ip"` and `"cosine"`, and the index `seed`. Change `index.cp`
before the first `add` to tune them, call `index.train(sample)` first to train on a
sample, or call `index.set_centroids(centroids)` to use centroids you computed
elsewhere. `train` and `add` use every available CPU by default, capped by
@@ -66,11 +66,12 @@ not exact distances to the original vectors.
A search may return fewer than `k` valid neighbors, for example when `k` exceeds the
number of points, after removals, or when the probed IVF-RaBitQ clusters contain too
-few points. Unfilled slots contain ID `2**32 - 1` and distance `+inf`. Filter them with
+few points. IDs are `int64`; unfilled slots contain ID `-1` and distance `+inf`. Filter them with
`valid = np.isfinite(distances)` before using IDs to index your data.
-The `metric` argument accepts `"l2"` and `"ip"` (also `"innerproduct"`). For
-cosine search, normalize database and query vectors first and use `metric="ip"`.
+The `metric` argument accepts `"l2"`, `"ip"` and `"cosine"`.
+`metric="cosine"` scales database and query vectors to unit length and returns
+`1 - cos`; the saved file records it, so a loaded index keeps normalizing.
## Measure recall
@@ -122,9 +123,9 @@ with TemporaryDirectory() as directory:
np.testing.assert_allclose(loaded_distances, distances)
```
-The loaded index owns its data and restores the saved rotation. IVF-RaBitQ indexes using
-HNSW centroid routing also need the accompanying `.hnsw` file; keep it with the
-main index. This small example uses Flat routing and has no sidecar.
+The loaded index owns its data and restores the saved rotation. IVF-RaBitQ saves one
+file, including its HNSW centroid routing; files from releases up to 0.8 with HNSW
+routing also need the accompanying `.hnsw` file.
See [file compatibility](index/usage.md#index-file-compatibility) before downgrading.
## Next steps
diff --git a/docs/docs/rabitq/core_api.md b/docs/docs/rabitq/core_api.md
index 9de9cb9f..192d5ac9 100644
--- a/docs/docs/rabitq/core_api.md
+++ b/docs/docs/rabitq/core_api.md
@@ -119,7 +119,10 @@ and do not persist or hardcode them. Compiler warnings from future compilers are
part of the compatibility guarantee.
The stable surface is the v1 namespace, its version macros, and the existing
-`MetricType` / `METRIC_L2` / `METRIC_IP` values used by it. Other core templates,
+`MetricType` / `METRIC_L2` / `METRIC_IP` values used by it. `MetricType` may gain
+values that only other modules accept, such as `METRIC_COSINE` for the ANN indexes
+from 0.9. v1 rejects them as invalid metrics, so adding one does not change v1 or its
+version; a `switch` over `MetricType` without a `default` may warn about the new value. Other core templates,
`detail/`, SIMD entry points, rotator implementations, FastScan and ANN
interfaces are not implicitly frozen by including this header. Existing interfaces
remain available through canonical module headers; old forwarding paths are removed as
@@ -135,7 +138,7 @@ automatically apply to them.
| --- | --- |
| `dim` | Number of coordinates actually supplied, at least 2; no implicit padding |
| `total_bits` | 1 through 9, including the sign bit |
-| `metric` | `METRIC_L2` or `METRIC_IP` |
+| `metric` | `METRIC_L2` or `METRIC_IP`; `METRIC_COSINE`, which only the ANN indexes accept, is rejected like any other value |
| `t_const` | Finite, at most `INT_MAX / 2`; nonpositive selects the existing exact search, positive selects the existing fast scaling algorithm |
Inputs and a non-null centroid contain at least `dim` aligned float32 values. Pass
diff --git a/docs/docs/rabitq/estimator.md b/docs/docs/rabitq/estimator.md
index 54817aa9..f7f06596 100644
--- a/docs/docs/rabitq/estimator.md
+++ b/docs/docs/rabitq/estimator.md
@@ -48,9 +48,9 @@ $$
## Estimator
The following derivation covers squared Euclidean distance and inner product.
-The public metric choices are `METRIC_L2` and `METRIC_IP`; there is no separate
-cosine metric. For cosine search, normalize both data and query vectors, then
-use inner product. The implementation represents inner-product distance as
+The estimator supports `METRIC_L2` and `METRIC_IP` and has no cosine metric. For
+cosine search, normalize both data and query vectors, then use inner product;
+the ANN indexes' `METRIC_COSINE` does this for you. The implementation represents inner-product distance as
$1-\langle\mathbf{o}_r,\mathbf{q}_r\rangle$, which preserves the same ranking while
keeping the nearest-neighbor convention that smaller values are better.
diff --git a/docs/docs/rabitq/quant_python.md b/docs/docs/rabitq/quant_python.md
index 12df7922..0716cc8c 100644
--- a/docs/docs/rabitq/quant_python.md
+++ b/docs/docs/rabitq/quant_python.md
@@ -1,7 +1,7 @@
# Python quantization building blocks
!!! warning "Provisional"
- `rabitqlib.quant` is provisional in the sense of [PEP 411](https://peps.python.org/pep-0411/): any minor release may change or remove part of its API, with a note in the release notes, until it is declared stable. Byte formats are versioned from the first release, and bytes of an unknown version raise `quant.FormatError` instead of giving wrong results.
+ `rabitqlib.quant` is provisional in the sense of [PEP 411](https://peps.python.org/pep-0411/): any minor release may change or remove part of its API, with a note in the release notes, until it is declared stable. Byte formats are versioned from the first release, and bytes of an unknown version raise `quant.FormatError` instead of giving wrong results. It is `rabitqlib.FormatError`, which index loads also raise, a subclass of both `ValueError` and `RuntimeError`.
`rabitqlib.quant` exposes the pieces the indexes are built from: rotation, quantization, correction factors, packed codes and distance estimation. Use it to store RaBitQ codes in your own database or file format and to score them with your own selection logic. For a ready-made index, use [IVF-RaBitQ](../index/ivf.md), [HNSW-RaBitQ](../index/hnsw.md) or [SymphonyQG](../index/qg.md) instead.
diff --git a/docs/docs/rabitq/rabitq.md b/docs/docs/rabitq/rabitq.md
index 47c5c355..012a0d8a 100644
--- a/docs/docs/rabitq/rabitq.md
+++ b/docs/docs/rabitq/rabitq.md
@@ -14,7 +14,8 @@ with a low-bit unsigned integer and store per-vector factors for distance estima
3. **Estimate.** Combine the codes, factors and rotated query to estimate squared
L2 or inner-product distance (`1 - dot`). See [Estimation](estimator.md).
-For cosine search, normalize data and queries before rotation and use inner product.
+For cosine search, normalize data and queries before rotation and use inner product;
+the indexes' [cosine metric](../index/usage.md#the-cosine-metric) does this for you.
The probabilistic error intervals can guide [reranking](reranking.md), but do not
make approximate search exact. Recall depends on the data and search settings.
diff --git a/docs/docs/rabitq/rotator.md b/docs/docs/rabitq/rotator.md
index ec684581..2c134c1d 100644
--- a/docs/docs/rabitq/rotator.md
+++ b/docs/docs/rabitq/rotator.md
@@ -92,6 +92,9 @@ This implementation is based on the [FFHT library](https://github.com/FALCONN-LI
## Random orthogonal transformation
This method samples a Gaussian matrix and orthogonalizes it with QR decomposition.
+Each column of the orthogonal factor takes the sign of the matching diagonal entry
+of the triangular factor, which makes the transform Haar distributed, that is,
+uniform over orthogonal matrices ([Mezzadri, 2007](https://arxiv.org/abs/math-ph/0609050), Section 5).
It then multiplies each vector by the stored transform. The table describes stored
space and per-vector rotation work when input and output dimensions are both $D$;
QR construction is separate setup work.
diff --git a/docs/docs/releases/0.9.0.md b/docs/docs/releases/0.9.0.md
new file mode 100644
index 00000000..929e923c
--- /dev/null
+++ b/docs/docs/releases/0.9.0.md
@@ -0,0 +1,152 @@
+# RaBitQ Library 0.9.0
+
+This release removes the Python forms that 0.8 deprecated, saves every index in index
+format 2, adds the cosine metric and 64-bit IDs, and adds C++ index classes that match
+the Python API. Index files from every earlier release still load; files saved by 0.9
+need 0.9 or later.
+
+## Index files
+
+- IVF-RaBitQ, HNSW-RaBitQ and SymphonyQG `save` write [index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2), a single file with a header, a section table and checksummed metadata.
+- Releases up to 0.8 cannot read these files. Keep a copy saved by 0.8 if you may downgrade.
+- Files written by every earlier release still load, including the `.hnsw` sidecars of HNSW-routed IVF files. Saving one writes format 2 with the same rotation, codes and results.
+- IVF-RaBitQ stores HNSW centroid routing inside the file, so `save` no longer writes a `.hnsw` sidecar. A sidecar left by an earlier save is not removed.
+- The saved bytes now include that routing graph. It is reproducible only when `train`, `set_centroids` or the first `add` builds it with `num_threads=1`. Saving the same index twice still gives identical files.
+- `save` rejects IVF-RaBitQ indexes of more than 65,536 dimensions.
+- A format-2 file that uses read-only-compatible features unknown to this release loads for search only: operations that change or save the index raise. A new index built from the original data is writable.
+
+## Removed and renamed Python forms
+
+0.9 removes every Python form that 0.8 deprecated. The [migration guide](../python_migration.md) lists each replacement; all of them work in 0.8.5, where the old forms warn.
+
+- The 0.7 call forms, deprecated since 0.8.0 (#213):
+ - `IvfIndex(dim, max_elements, num_clusters, nbits, ...)`, `HnswIndex(dim, max_elements, ...)` and its `random_seed=`, and `SymqgIndex(dim, max_degree, metric, quantization_bits)` and its `quantization_bits=`;
+ - `build()` and `is_built` on every index, and `SymqgIndex.search_batch()` and `SymqgIndex.quantization_bits`;
+ - `cluster_ids`, `num_threads` and `fast_quantization` passed to `add` by position.
+- The 0.8 index spellings, deprecated since 0.8.5 (#232):
+ - `max_elements`: read `capacity` on `HnswIndex` and `num_stored_points` on `IvfIndex` and `SymqgIndex`;
+ - `HnswIndex.resize(n)`: call `reserve(n)`, which only grows the capacity;
+ - `IvfIndex.reserve(cluster_id, num_points)`: call `reserve_cluster`;
+ - `IvfIndex(initializer=...)` and `index.initializer`: use `routing`;
+ - `search(queries, k, ef=...)` on `HnswIndex` and `SymqgIndex`: use `ef_search=`;
+ - `high_accuracy` and `num_threads` passed to `search` by position: they are keyword-only, and only `nprobe` or `ef_search` stays positional;
+ - `nprobe=0` and `ef_search=0` for the default: they raise `ValueError`, and `None` selects the default. `num_threads=0` still means every available CPU;
+ - `HnswIndex` seeds above `2**32 - 1`: they raise `ValueError`, as on the other two classes.
+- The 0.8 k-means spellings, deprecated since 0.8.5 (#233):
+ - `QGKMeans` and `QGKMeansParameters` take `nbits` (32, 4 or 8), `max_degree` and `ef_construction` instead of `quantization_bits` (0, 4 or 8), `graph_degree` and `ef_build`;
+ - `final_assignment` is `'approximate'` or `'exact'`, also on `index.cp`, and reads back as that string. `FinalAssignmentMode` is no longer in the package;
+ - `KMeansIterationStats` is the only name of the statistics class; `QGKMeansIterationStats` and `RaBitQKMeansIterationStats` are no longer in the package.
+- A removed call form of an index raises `TypeError`, and a removed attribute or name `AttributeError` (`ImportError` when imported), as does a removed `QGKMeans` keyword, like any unknown keyword there; none is read as a different call. For example, `IvfIndex(dim, 1000, 64)` is an error, not an index with 1000 clusters.
+- Changes that 0.8.5 could not announce with a warning:
+ - `metric="innerproduct"` raises `ValueError` on the index classes and in `rabitqlib.quant`. Use `"ip"`, which every release accepts and the `metric` properties return.
+ - `HnswIndex()` without `seed=` draws a seed, as `IvfIndex` and `SymqgIndex` do, instead of using 100. `index.seed` reports it; pass `seed=`, and `num_threads=1` to `add`, for a reproducible build.
+ - `repr(index)` prints `capacity=` for `HnswIndex` and `routing=` for `IvfIndex`, and no longer prints `max_elements=` for `IvfIndex`.
+- The index classes are now the extension's own, without replaced methods:
+ - A wrong argument raises pybind11's `TypeError`, which lists the supported signature. Messages such as `IvfIndex() got an unexpected keyword argument 'x'` are gone.
+ - `inspect.signature()` no longer works on the index constructors and methods; `help()` and the type stubs describe them.
+- k-means messages name the new parameters: `QGKMeans nbits must be 4, 8, or 32`, `QGKMeans max_degree must be a positive multiple of 32`, `QGKMeans requires more centroids than max_degree` and `QGKMeans ef_construction and ef_search must be positive`. As for the other parameters, `train` reports an invalid `nbits`; 0.8.5 rejected it when it was set.
+- txtai 9.14.0, the first txtai release with a RaBitQ backend, uses the 0.7 forms and fails with this release. It also filters results with `uid != 0xFFFFFFFF`, which no longer matches a missing result (see `int64` IDs below). txtai 9.15.0, the first release with [neuml/txtai#1616](https://github.com/neuml/txtai/pull/1616), works with this release and with 0.8.5 (#213). With txtai 9.14.0, keep `rabitqlib<0.9`.
+
+## Python changes
+
+- New `metric="cosine"` for `IvfIndex`, `HnswIndex` and `SymqgIndex` (#212). The index scales data, queries and centroids passed to `set_centroids` to unit length and returns `1 - cos`; results equal those of a `metric="ip"` index built from the scaled vectors and given the scaled centroids (#259). A zero vector stays zero, so its true distance to every vector is 1. The saved file records the metric, so a loaded index keeps scaling. `index.metric` can now return `"cosine"`, and an invalid metric raises `metric must be 'l2', 'ip' or 'cosine'`. See [the cosine metric](../index/usage.md#the-cosine-metric).
+- Point IDs are `int64` at the Python boundary (#211):
+ - `search` returns `int64` IDs, and slots without a neighbor hold `-1` instead of `2**32 - 1`; their distance is still `inf`. Code that compares IDs with `2**32 - 1`, `0xFFFFFFFF` or `np.iinfo(np.uint32).max` must change; `np.isfinite(distances)`, recommended since 0.8.2, works before and after.
+ - `add` returns `int64` IDs. `remove` already took any integer IDs and still rejects `-1` and other out-of-range values without removing anything.
+ - IDs remain the row numbers the index assigns. The C++ `IvfIndex`, `HnswIndex` and `SymqgIndex` use 64-bit `rabitqlib::Id` values with `kNoId` (-1) for a missing result, as Python does. The indexes still hold 32-bit row numbers inside, so they keep their limit of 2^31 points; the unsupported `ivf::IVF`, `hnsw::HierarchicalNSW` and `symqg::QuantizedGraph` keep `PID` and `kPidMax`.
+
+- An `IvfIndex`, `HnswIndex` or `SymqgIndex` call with both an invalid argument and the wrong state may now report the argument first, for example `ValueError` for `nprobe=0` on an untrained index, which raised `RuntimeError`, or for data of the wrong dimension passed to `SymqgIndex.add` after the graph is built. `HnswIndex()` with an invalid `metric` or `seed` and an out-of-range `num_clusters` now reports the metric or seed. `SymqgIndex()` with an invalid `init` and an invalid `dim`, `nbits` or `max_degree` now reports the `init`, and with an invalid `seed` and an invalid `dim`, `nbits`, `max_degree` or `ef_construction` the seed.
+- k-means training accepts every coordinate that `add` and `search` accept. For many dimensions, including 64, 100, 256, 960 and 1024, `train` and `assign` of `QGKMeans` and `RaBitQKMeans`, and `train` and the first `add`, which trains, of `IvfIndex` and `HnswIndex` rejected a coordinate whose magnitude equals the float32 coordinate bound with `exceeds the safe float32 coordinate range`, although a trained index accepted it. The C++ `rabitqkmeans::RaBitQKMeans` and `qgkmeans::QGKMeans` change the same way.
+
+- Loading a format-2 file keeps the `seed` of every index, and `ef_construction` and `init` of SymphonyQG. They were `None` after `load`, and still are for files from releases up to 0.8.
+- With a recorded seed, `cp.seed` after `load` follows it as for a new index; for an HNSW-RaBitQ file whose seed exceeds 32 bits, which only C++ can write, it is the low 32 bits. It was the k-means default.
+- An HNSW-RaBitQ file saved before training, which the C++ API of earlier releases allowed, loads untrained, with `num_clusters` 16. Without a recorded seed its first `add` cannot train it, so `add`, `search`, `remove` and `save` raise `RuntimeError: HnswIndex loaded from an untrained file must be trained before add; call train or set_centroids` (naming the operation) until `train` or `set_centroids` runs.
+- A new exception, `rabitqlib.FormatError`, subclasses both `ValueError` and `RuntimeError`:
+ - Every index `load` raises it for a truncated, corrupt, mismatched or unsupported file, in format 2 and in every earlier layout. These were `RuntimeError`, which still catches them. A file that cannot be opened still raises a plain `RuntimeError`.
+ - `quant.FormatError` is now the same class. It was a subclass of `ValueError` only, which still catches it.
+- Messages for damaged or mismatched files change:
+ - A format-2 file names the problem, for example `IVF index file is 6916 bytes, but its sections end at 6852` for trailing bytes.
+ - Errors in an HNSW routing graph name the graph rather than the sidecar: `Truncated HNSW centroid graph` and `HNSW centroid graph changed while loading` replace their `sidecar` forms.
+ - A missing sidecar of an earlier file still raises `Cannot open HNSW centroid sidecar`.
+ - A failed HNSW-RaBitQ write raises `HNSW index file cannot be written` instead of `HNSW failed to write index file`.
+- `pickle.dumps(obj, protocol=0)` or `protocol=1` on a `rabitqlib` object no longer aborts the Python process. `quant.Rotator` and `quant.Query` now pickle with every protocol; the index, k-means, parameter and iteration-statistics classes raise `TypeError: cannot pickle ...`, as they already did with protocol 2 and higher, which include the default. Protocols 0 and 1 cannot reduce pybind11 objects ([pybind11#3745](https://github.com/pybind/pybind11/issues/3745)), so they now use the protocol-2 reduction.
+- `quant.Rotator(method="matrix")` now draws a Haar-distributed rotation, uniform over orthogonal matrices. It used the orthogonal factor of a Householder QR factorization as returned, whose determinant is fixed and whose first entry is always negative; each column now takes the sign of the matching diagonal entry of the triangular factor. RaBitQ's codes and estimator do not change when the same rotated coordinate changes sign in every vector and query, and the old rotation was Haar distributed up to such sign changes, so accuracy is not expected to change. A given `seed` now produces a different matrix; rotators saved with `to_bytes()` and saved indexes keep theirs.
+
+## C++ changes
+
+- New `rabitqlib::IvfIndex` in `rabitqlib/index/ivf_index.hpp` (#234), with the workflow and defaults of the Python class, which now wraps it, and its messages where they do not name Python values:
+ - `IvfIndex(dim, num_clusters, options)` takes an `IvfOptions` struct with an `ivf::Routing`, an alias of `ivf::InitializerType`. A static `load` returns a trained index, and `train`, `set_centroids`, `add`, `remove`, `reserve_cluster`, `search` and `save` follow the Python methods.
+ - The first `add` trains an untrained index and leaves it untrained and empty if it fails. `add` takes an `AddOptions` struct and returns the first new ID.
+ - IDs are `rabitqlib::Id` (`int64_t`). A missing search result is `kNoId` (-1) with distance `+inf`.
+ - `search` takes a batch of queries and an `IvfSearchOptions` struct. Without an `nprobe` it probes `num_clusters / 16` clusters, rounded and at least 1, and an explicit 0 throws.
+ - A seed is drawn unless given, and `num_threads == 0` means every available CPU, capped by `OMP_NUM_THREADS`.
+ - Arguments out of range throw `std::invalid_argument`, and calls in the wrong state `std::logic_error`.
+- New `rabitqlib::HnswIndex` in `rabitqlib/index/hnsw_index.hpp` (#234), built the same way, which the Python `HnswIndex` now wraps:
+ - `HnswIndex(dim, options)` takes an `HnswOptions` struct (metric, `nbits`, `num_clusters`, `M`, `ef_construction`, seed). `train`, `set_centroids`, `add`, `remove`, `reserve`, `search`, `save` and the static `load` follow the Python methods.
+ - The first `add` trains `min(num_clusters, number of points)` centroids and leaves the index untrained, empty and with its capacity if it fails.
+ - Capacity starts at one point and grows on `add`, at least doubling, after the points and cluster IDs are checked; `reserve` only grows it.
+ - `add` uses every available CPU unless `num_threads` is set, whereas `hnsw::HierarchicalNSW::add` uses one; pass `num_threads = 1` and a seed for a reproducible graph.
+ - `search` takes a `GraphSearchOptions` struct. Without an `ef_search` it uses `max(k, 64)`, and an explicit 0 throws.
+ - `seed()` is a `std::optional`, because a file written by `hnsw::HierarchicalNSW` may record a seed above 32 bits.
+- New `rabitqlib::SymqgIndex` in `rabitqlib/index/symqg_index.hpp` (#234), which the Python `SymqgIndex` now wraps:
+ - `SymqgIndex(dim, options)` takes a `SymqgOptions` struct (metric, `nbits` of 32, 4 or 8 with 32 for raw float32, `max_degree`, `ef_construction`, `init`, seed). `add` builds the graph from every vector, once, and a built or loaded index throws `std::logic_error` on `add`. `train` only checks its input. `search`, `save` and the static `load` follow the Python methods.
+ - A failed `add` leaves the index without a graph. `add` takes a worker count, with 0, the default, for every available CPU.
+ - `search` takes a `GraphSearchOptions` struct. Without an `ef_search` it uses `max(k, 64)`, a smaller value is raised to `k`, and an explicit 0 throws; `symqg::QuantizedGraph` rejects an `ef_search` below `k`.
+ - `seed()`, `ef_construction()` and `init()` have no value for a file of a release up to 0.8.
+- `IvfIndex`, `HnswIndex` and `SymqgIndex` are the supported and documented C++ index API from 0.9. `ivf::IVF`, `hnsw::HierarchicalNSW`, `symqg::QuantizedGraph` and `symqg::QGBuilder` stay installed at their paths and keep their interfaces apart from the changes listed below, but they leave the documentation and carry no compatibility promise.
+
+Move to the new classes as follows:
+
+| 0.8 | 0.9 |
+| --- | --- |
+| `IVF(num_points, dim, num_clusters, bits, ...)`, then `construct(data, centroids, cluster_ids)` | `IvfIndex(dim, num_clusters, options)`, `set_centroids(centroids)`, then `add(data, num_points, add_options)` with `add_options.cluster_ids` |
+| `HierarchicalNSW(max_elements, dim, bits, M, ef_construction, seed, metric)`, then `construct(...)` | `HnswIndex(dim, options)` with `options.num_clusters`, then the same two calls; capacity grows on `add` |
+| `QuantizedGraph(num_points, dim, max_degree, ...)` with `quantization_bits` 0 for raw vectors, then `QGBuilder(graph, ef_construction, data).build()` | `SymqgIndex(dim, options)` with `options.nbits` 32 for raw vectors, then `add(data, num_points)` |
+| `IVF::search`, `IVF::search_batch`, `HierarchicalNSW::search` (nested vectors), `set_ef` with `QuantizedGraph::search_batch` | `search(queries, num_queries, k, ids, distances, search_options)` |
+| `Index index; index.load(filename);` | `auto index = IvfIndex::load(filename);`, and likewise `HnswIndex::load` and `SymqgIndex::load` |
+| `PID` results, `kPidMax` for a missing IVF or SymphonyQG result | `Id` results, `kNoId` for a missing result |
+| `dimension()`, `metric_type()`, `initializer_type()`, `max_elements()` (HNSW), `degree_bound()`, `quantization_bits()` (0 for raw), `num_vertices()`; `IVF::reserve`, `HierarchicalNSW::resize` | `dim()`, `metric()`, `routing()`, `capacity()`, `max_degree()`, `nbits()` (32 for raw), `num_points()`; `reserve_cluster`, `reserve` |
+| `IVF::train(num_points, data, cp)`, `HierarchicalNSW::train(num_clusters, num_points, data, cp)`, `HierarchicalNSW::set_centroids(num_clusters, centroids)`; `add` returning `void` or every label | `train(data, num_points)` with `cp()`, `set_centroids(centroids)`, `add` returning the first `Id` |
+
+Four differences are not renames: `HnswIndex::add` uses every CPU unless `num_threads` is set; `HnswIndex::search` writes all `k` slots, padding with `kNoId` and `+inf`, where `HierarchicalNSW::search` returns only the pairs found; a seed is drawn unless given, where `HierarchicalNSW` defaults to 100; and default thread counts are capped by `OMP_NUM_THREADS`. The new classes do not offer the matrix rotator, rebuilding with `IVF::construct`, shrinking with `HierarchicalNSW::resize`, `HierarchicalNSW::cluster_id_of`, `QuantizedGraph::search_with_scratch` with its warm-start hint, `QGBuilder`'s multi-pass `build(n)`, `reset`, `refine`, `avg_degree`, `check_dup` and `cache_vectors`, or `padded_dim()`; use the existing classes for them.
+
+- The C++ examples in `sample/cpp` and the IVF `add` hot-path benchmark use the new classes. `symqg_indexing` takes `nbits` (32 for raw vectors, 4 or 8, default 32) and still reads 0 as raw vectors; it no longer prints stage times or the average degree. Its optional thread count 0 selects every available CPU. The default thread counts of `symqg_indexing` and `ivf_rabitq_indexing` are now capped by `OMP_NUM_THREADS`, which they ignored. `ivf_rabitq_indexing`, `hnsw_rabitq_indexing` and `symqg_indexing` accept `cosine` as the metric and reject unknown metric names; all three used to build an L2 index silently.
+
+- `qgkmeans::QGKMeansParameters` uses the Python names (#233): `graph_degree` becomes `max_degree`, `ef_build` becomes `ef_construction`, and `quantization_bits` (0, 4 or 8) becomes `nbits` (32, 4 or 8, with 32 for raw float32). The fields keep their order and types. An `nbits` of 0 is rejected, so code that initialized the field positionally with 0 must pass 32. `QGAssigner` keeps its constructor, including `quantization_bits` with 0 for raw storage.
+- Messages follow the names: `QGKMeans nbits must be 4, 8, or 32`, `QGKMeans max_degree must be a positive multiple of 32`, `QGKMeans requires more centroids than max_degree` and `QGKMeans ef_construction and ef_search must be positive`.
+- `FinalAssignmentMode::SymphonyQG`, an alias of `Approximate`, is removed.
+- The aliases `qgkmeans::QGKMeansIterationStats` and `rabitqkmeans::RaBitQKMeansIterationStats` are removed; use `clustering::KMeansIterationStats`.
+
+- `MetricType` gains `METRIC_COSINE`, which `IVF`, `HierarchicalNSW`, `QuantizedGraph` and `default_training_parameters` accept. The indexes normalize their inputs and store inner-product codes; `metric_type()` returns `METRIC_COSINE`. Entry points that validate the metric reject it with their existing messages: the stable core API v1, factor computation in the encoders, the query classes, FastScan queries, clustering and the IVF initializers. Code with an exhaustive `switch` over `MetricType` may warn about the new value.
+
+- Loading an index throws `rabitqlib::FormatError`, a subclass of `std::runtime_error` in the new header `rabitqlib/index/format_error.hpp`, for a damaged, mismatched or unsupported file. Failing to open the file still throws `std::runtime_error`. Files of earlier layouts that threw other exceptions for invalid contents now throw `FormatError` too: an IVF-RaBitQ file with an invalid metric or a dimension its rotation does not support, which threw `std::invalid_argument`, and a SymphonyQG file with invalid settings or dimensions, which threw `std::invalid_argument` or `std::length_error`.
+
+- `ivf::Initializer` and its subclasses:
+ - `save(std::ofstream&, const char*)` becomes `write(std::ostream&)`, and `load(std::ifstream&, const char*)` becomes `read(std::istream&, uint64_t bytes)`.
+ - The HNSW initializer no longer writes a sidecar itself.
+- New accessors report what format-2 files record, or no value when unknown:
+ - `IVF::seed()`;
+ - `HierarchicalNSW::seed()`;
+ - `QuantizedGraph::seed()`, `ef_construction()` and `initialization()`.
+- `symqg::QGInitialization` moves from `qg_builder.hpp` to `rabitqlib/index/symqg/types.hpp`, which `qg.hpp`, and through it `qg_builder.hpp`, includes.
+- The vendored hnswlib adds `saveIndex(std::ostream&)` and `loadIndex(std::istream&, size_t bytes, ...)`; the path overloads are unchanged.
+
+- `rabitqlib::ceil_log2` in `rabitqlib/utils/tools.hpp` shifts a `size_t`, so an input of 2^32 or more is no longer undefined on 64-bit Windows, where `unsigned long` has 32 bits (#247). The library does not call it.
+- `rabitqlib::distance_ratio` and `rabitqlib::horizontal_avg` are removed from `rabitqlib/utils/tools.hpp` (#262). They were evaluation helpers for the C++ samples, and the library does not call them. `distance_ratio` read out of bounds for a missing result ID (`kNoId` or `kPidMax`), and `horizontal_avg` read out of bounds for empty or ragged input and averaged negative integer columns wrongly, for example `horizontal_avg` gave 1431655764 for three rows of -1. Code that uses them needs its own version that handles these inputs; the samples now average their measurements with a local helper. `tools.hpp` no longer includes ``, so code that used `std::priority_queue` through RaBitQ headers must include `` itself.
+
+- `MatrixRotator`, which `choose_rotator` returns for `RotatorType::MatrixRotator` and `IVF` and `QuantizedGraph` use when given it, draws a Haar-distributed rotation, as described for `quant.Rotator` above. A given seed now produces a different matrix; saved rotators and indexes keep theirs.
+
+- The installed CMake package satisfies `find_package(rabitqlib X.Y[.Z])` only when the major and minor versions match: `find_package(rabitqlib 0.8)` no longer finds 0.9, which `SameMajorVersion` compatibility allowed, and a version range must stay within one minor release, such as `0.9...<0.10`. Before 1.0 a minor release may break the API.
+
+## Upgrading
+
+From 0.8, first run your code on 0.8.5 and replace every form that raises a
+`DeprecationWarning`, using the [migration guide](../python_migration.md#from-08-to-09);
+each replacement also works in 0.9. The same section lists the changes that come without
+a warning, including `int64` IDs and index format 2. Files saved by every earlier release
+load in 0.9, but releases up to 0.8 cannot read files that 0.9 saves, so keep a copy
+saved by 0.8 if you may downgrade. Rebuild C++ consumers with matching headers and
+libraries; no cross-version C++ binary ABI is promised.
+
+When upgrading from 0.7, follow the [0.8.0 release notes](0.8.0.md) and the
+[migration guide](../python_migration.md).
diff --git a/docs/formats.md b/docs/formats.md
index 7aa60efb..09fbc9d0 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -1,6 +1,6 @@
# Byte formats
-This is the specification of the byte formats `rabitqlib.quant` reads and writes. It is shared with the planned index format revision, which will add its own blob kinds. While `rabitqlib.quant` is provisional, a release may stop reading an old format version; reading it then raises `quant.FormatError` instead of returning wrong results. A promise that every released version stays readable comes with stabilisation.
+This is the specification of the byte formats `rabitqlib.quant` reads and writes. Index files ([format 2](#index-format-2)) use their own container and nest blobs in its sections. While `rabitqlib.quant` is provisional, a release may stop reading an old format version; reading it then raises `rabitqlib.FormatError` (also `quant.FormatError`) instead of returning wrong results. A promise that every released version stays readable comes with stabilisation.
Every format has a version. A change to any layout is a new version, never an edit of an existing one. The golden files in `tests/python/fixtures/quant/` freeze each version and are never regenerated.
@@ -59,7 +59,7 @@ A blob is a self-describing byte string, such as `Rotator.to_bytes()`. It starts
| Offset | Size | Type | Field | Rule |
| --- | --- | --- | --- | --- |
| 0 | 8 | ASCII | `magic` = `"RABQBLOB"` | Anything else raises `FormatError` |
-| 8 | 4 | u32 | `kind` | 1 = rotator; 2 = codec (reserved); 3 and up reserved for index formats. A kind the reader does not expect raises `FormatError` |
+| 8 | 4 | u32 | `kind` | 1 = rotator; 2 = codec (reserved); 3 and up reserved. A kind the reader does not expect raises `FormatError` |
| 12 | 4 | u32 | `version` | Layout version of this kind; an unknown version raises `FormatError` |
| 16 | 4 | u32 | `header_bytes` | Common header plus kind fields, a multiple of 8; it must equal the size the kind and version define |
| 20 | 4 | u32 | `flags` | Kind-specific; unknown bits raise `FormatError` |
@@ -92,3 +92,283 @@ The body is what `Rotator::save()` writes, and `body_bytes` must equal it
| Matrix | The rotation matrix as row-major float32 | `4 * dim * padded_dim` |
The body defines the rotation; `seed` only records where it came from. A seeded FHT/Kac rotation is identical on every platform, while a matrix drawn from a seed is reproducible only with the same standard library and build, which is why the matrix itself is stored.
+
+
+
+## Index files, format 2
+
+> **Status:** 0.9 is the first release that writes format 2 (#211, #212). IVF-RaBitQ, HNSW-RaBitQ and SymphonyQG read and write it, including the cosine metric; the container is `src/index/format2.*`. IVF-SSD and companion files are not implemented, and their parts of this specification may change until a release writes them.
+
+Format 2 is one container for IVF-RaBitQ, HNSW-RaBitQ and SymphonyQG, and later for the SSD-resident IVF index from RaBitQ-SSD. It replaces the per-index layouts: IVF-RaBitQ `RABQIDX1` version 2 (readers also accept version 1, which no release wrote), its raw-vector layout `RBFQRAW1` and its unversioned layout, the unversioned HNSW-RaBitQ layout, SymphonyQG's quantized version 1 and its raw layout, and the unversioned hnswlib sidecar `.hnsw` of IVF-RaBitQ. Every released layout stays readable (see [Earlier layouts](#earlier-layouts)); `save` always writes format 2.
+
+The number continues the name used in #212. An index file is told apart from earlier layouts by its magic, not by the version, so the unrelated IVF-RaBitQ `RABQIDX1` version 2 does not clash. The header is not a [blob](#blobs): a blob checksums its whole body, which is too costly for large index files, so index files have their own container and nest blobs in sections.
+
+Unlike the provisional `rabitqlib.quant` formats above, index files carry the library's full compatibility promise: every format-2 file written by a release stays readable by every later release.
+
+### Conventions
+
+- Multi-byte fields are little-endian; types are fixed-width (`u32`, `u64`, `i32`, `f32`, `f64`). No field is `size_t`.
+- Offsets are absolute byte offsets from the start of the file.
+- The section table starts at a multiple of 8, and every section starts at a multiple of 64, so a reader can map the file and read sections in place. Writers fill gaps with zero bytes, and readers do not inspect them.
+- Reserved fields and undefined flag bits are written as zero. A reader rejects a nonzero value unless a rule below says otherwise.
+- Enumerations start at 1, so zero always means unset; their values are never reused or renumbered.
+- Checksums are CRC-32 as `zlib.crc32` computes it, the same as in [blobs](#blobs).
+
+### Layout
+
+| Part | Position |
+| --- | --- |
+| Header | Offset 0, `header_bytes` long |
+| Section table | `section_table_offset`, `section_count` entries of 32 bytes |
+| Sections | Anywhere after the header, each at a multiple of 64 |
+
+Each section starts at or after `header_bytes` and at or after the end (`offset + size`) of the previous table entry, so the table lists sections in file order and no two overlap. An empty section takes no bytes: several may share an offset, and the next section may start at it. Non-empty sections do not overlap the section table; an empty section's offset may fall inside it. The file ends exactly where the table or the last section ends, whichever is later; an empty section still has an aligned offset, so writers pad up to it.
+
+### Header
+
+The fields below take 128 bytes. `header_bytes` is a multiple of 8 and at least 128; a later release may append fields without changing `version`, and a reader skips the bytes past the fields it knows, which `header_crc32` still covers (see [Compatibility rules](#compatibility-rules)).
+
+| Offset | Size | Type | Field | Rule |
+| --- | --- | --- | --- | --- |
+| 0 | 8 | ASCII | `magic` = `"RABQINDX"` | Anything else is not a format-2 file; the reader tries [earlier layouts](#earlier-layouts) |
+| 8 | 4 | u32 | `version` = 2 | Any other value is rejected |
+| 12 | 4 | u32 | `header_bytes` | See above |
+| 16 | 8 | u64 | `incompat_features` | See [Feature flags](#feature-flags) |
+| 24 | 8 | u64 | `ro_compat_features` | |
+| 32 | 8 | u64 | `compat_features` | |
+| 40 | 4 | u32 | `index_kind` | 1 = IVF-RaBitQ, 2 = HNSW-RaBitQ, 3 = SymphonyQG; 4 = IVF-SSD (reserved). Unknown values are rejected |
+| 44 | 4 | u32 | `metric` | 1 = L2, 2 = inner product, 3 = cosine. See [Metrics](#metrics) |
+| 48 | 8 | u64 | `dim` | Original dimension, at least 1 |
+| 56 | 8 | u64 | `padded_dim` | Working dimension; a multiple of 32, at least `dim` and at most 65,536 (the rotator's limit). Readers use the stored value and never recompute it |
+| 64 | 4 | u32 | `code_bits` | Bits per coordinate of the stored quantized code, 1–9; 0 when the index stores no quantized code of its points |
+| 68 | 4 | u32 | `raw_type` | Element type of stored raw vectors: 0 = none, 1 = float32, 2 = uint8 |
+| 72 | 4 | u32 | `id_bits` | Width of the point IDs stored in the file: 32 or 64 |
+| 76 | 4 | u32 | `flags` | Bit 0, `seed_known`: `seed` is valid |
+| 80 | 8 | u64 | `seed` | The index's construction seed. Zero when `seed_known` is clear, which a file migrated from an earlier layout has. IVF-RaBitQ: the rotation and training seed, at most 2^32 − 1. HNSW-RaBitQ: the graph-level and training seed, whose low 32 bits seeded the rotation. SymphonyQG: the rotation seed, at most 2^32 − 1, which Python also uses for graph construction. The rotator blob records the rotation seed again |
+| 88 | 8 | u64 | `num_points` | Stored points, including removed ones |
+| 96 | 8 | u64 | `section_table_offset` | A multiple of 8, at least `header_bytes` |
+| 104 | 4 | u32 | `section_count` | At least 1 |
+| 108 | 4 | u32 | `header_crc32` | Over the header with this field taken as zero, followed by the section table |
+| 112 | 16 | ASCII | `writer_version` | Library version that wrote the file, printable ASCII, NUL-padded. For error messages only: readers neither branch on it nor validate it, and messages show the bytes before the first NUL, with backslashes and bytes outside printable ASCII as `\xNN` |
+
+The Python `nbits` maps to these fields as follows. IVF-RaBitQ `nbits` 1–9 is `code_bits`. IVF-RaBitQ `nbits = 32` is `code_bits = 1` with `raw_type = float32`, because it keeps 1-bit FastScan codes and reranks with raw vectors. SymphonyQG `nbits = 32` is `code_bits = 0` with `raw_type = float32`.
+
+### Section table
+
+| Offset | Size | Type | Field | Rule |
+| --- | --- | --- | --- | --- |
+| 0 | 4 | u32 | `kind` | See [Section kinds](#section-kinds) |
+| 4 | 4 | u32 | `flags` | Bit 0, `required`; bit 1, `checksummed` |
+| 8 | 8 | u64 | `offset` | A multiple of 64 |
+| 16 | 8 | u64 | `size` | Bytes; may be 0 |
+| 24 | 4 | u32 | `crc32` | Over the section's bytes when `checksummed` is set; zero otherwise |
+| 28 | 4 | — | reserved | |
+
+Kind 0 is reserved, and a kind appears at most once. Section flags other than the two above are rejected; a later version cannot add a section flag without a new `version`. Writers checksum the header-like sections (parameters, cluster sizes, companions), whose values size later allocations, and leave bulk data unchecksummed, so that loading a large index does not read it twice. A reader verifies the checksum of a section it knows exactly when `checksummed` is set. Per-point arrays such as `hnsw_levels` count as bulk data: the header fixes their size, and readers check every value against its limit.
+
+A section the reader does not know is handled by its `required` bit: a required one rejects the file, and an optional one is skipped without reading it, so its checksum is not verified. A writer marks a section optional only if dropping it leaves a correct index, for example a cache that can be recomputed. `save` drops optional sections it does not know.
+
+### Feature flags
+
+The three masks follow the ext4 superblock: they say what an older reader may do with a file that uses something newer than itself.
+
+| Mask | A reader that does not know a set bit |
+| --- | --- |
+| `incompat_features` | Rejects the file; reading it would give wrong results |
+| `ro_compat_features` | May load and search; operations that change or save the index (`add`, `reserve`, `remove`, `save`) raise, because they would leave the unknown data stale. Rebuilding replaces that data and makes the index writable again: IVF-RaBitQ `construct`, or a new SymphonyQG build; HNSW-RaBitQ cannot be rebuilt in place |
+| `compat_features` | Ignores the bit; `save` clears it |
+
+The error names the unknown bits and `writer_version`, such as "index file uses incompatible features 0x4 that this release does not know; written by rabitqlib 0.10.0".
+
+A writer sets only the bits it knows. Resaving a file therefore drops the unknown `compat` bits, together with the unknown optional sections and header fields past the writer's `header_bytes`. A `compat` bit may describe only data whose loss on such a resave is harmless.
+
+No bit is defined in version 2. Bits are assigned when a feature needs one. Examples:
+
+| Possible feature | Mask | Why |
+| --- | --- | --- |
+| Caller-provided IDs (`add(x, ids=...)`), an external-ID section | `incompat` | An older reader would return row numbers instead of the caller's IDs |
+| A per-cluster statistics section that `add` updates | `ro_compat` | An older reader can search, but its `add` would not update the section |
+| A new code layout of an existing section | `incompat`, or a new section kind | The bytes mean something else |
+
+### Metrics
+
+L2 and inner product are as in [Distance conventions](development.md#distance-conventions). Cosine stores the codes and factors of inner product over L2-normalized vectors. The index normalizes data on `train`, `add` and construction, centroids given to `set_centroids` or construction, and queries on `search`, and reports `1 - cos` as the distance. It is a stored metric, not a flag of the caller, so a reloaded index keeps normalizing.
+
+Normalization computes `scale = 1 / sqrt(s)` in double precision, where `s` is the sum of the squared coordinates added in coordinate order in double precision; each coordinate is multiplied by `scale` in double precision and rounded once to float32. The product of two float32 values is exact in double precision, so the sum does not depend on whether a compiler fuses multiply and add. A zero vector stays zero, so its true distance to every vector is 1. Every vector section (codes, raw float32 vectors and the IVF rerank vectors) holds the normalized vectors, so a cosine file equals the inner-product file of the normalized vectors except for `metric`. Centroids are stored as trained, or normalized as above when they were given.
+
+### Point IDs
+
+Python `search`, `add` and `remove` use `int64` IDs, and a missing search result is `-1` (#211). `id_bits` records what the file stores. The in-memory indexes keep 32-bit row numbers internally and write `id_bits = 32`; their upper limit stays below 2^31 points (the search-buffer marker bit). IVF-SSD writes `id_bits = 64`. A reader rejects an `id_bits` its index kind does not support.
+
+### Section kinds
+
+Kinds 1–255 are shared, 256–511 are IVF-RaBitQ, 512–767 HNSW-RaBitQ, 768–1023 SymphonyQG and 1024–1279 IVF-SSD. Writers mark every section listed here `required`. A reader that knows a kind reads the section whatever its `required` bit says; the bit governs only kinds the reader does not know.
+
+| Kind | Name | Used by | Content |
+| --- | --- | --- | --- |
+| 1 | `rotator` | All | A [rotator blob](#rotator-kind-1-version-1), byte for byte what `Rotator.to_bytes()` writes. Its `dim` and `padded_dim` must equal the header's. Not checksummed by the container: the blob carries its own CRC-32 |
+| 2 | `companions` | IVF-SSD | The [companion table](#companion-files) |
+| 256 | `ivf_params` | IVF | `num_clusters` u64; `initializer` u32 (1 = flat, 2 = FlatRaBitQ, 3 = HNSW); reserved u32 |
+| 257 | `ivf_cluster_sizes` | IVF | `num_clusters` × u64; the sum equals `num_points` |
+| 258 | `ivf_flat_routing` | IVF, flat | The rotated centroids, `num_clusters × padded_dim` f32 |
+| 259 | `ivf_flat_rabitq_routing` | IVF, FlatRaBitQ | The rotated centroids as above, the global centroid (their mean, `padded_dim` f32), then `ceil(num_clusters / 32)` [FastScan blocks](#fastscan-blocks-version-1) of the centroids, quantized against the global centroid under the index metric |
+| 260 | `ivf_hnsw_routing` | IVF, HNSW | The [HNSW routing graph](#hnsw-routing-graph), byte for byte the `.hnsw` sidecar of earlier releases |
+| 261 | `ivf_codes` | IVF | Per cluster in cluster order, `ceil(size / 32)` [FastScan blocks](#fastscan-blocks-version-1). Removed points have `add = +inf` |
+| 262 | `ivf_rerank` | IVF, `code_bits > 1` or raw | Per point in cluster order: a [single-code record](#single-code-record) with `b = code_bits - 1`, or `dim` raw values of `raw_type` |
+| 263 | `ivf_ids` | IVF | Per point in cluster order, `id_bits`-wide IDs |
+| 512 | `hnsw_params` | HNSW | `max_elements`, `num_clusters`, `M`, `upper_max_degree`, `base_max_degree`, `ef_construction` as u64; `level_multiplier` f64; `max_level` i32; reserved u32; `entry_point` u64. Record sizes are derived, not stored (see [HNSW-RaBitQ records](#hnsw-rabitq-records)) |
+| 513 | `hnsw_centroids` | HNSW | `num_clusters × padded_dim` f32 |
+| 514 | `hnsw_records` | HNSW | `num_points` [base-layer records](#hnsw-rabitq-records) |
+| 515 | `hnsw_levels` | HNSW | `num_points` × u32 levels |
+| 516 | `hnsw_upper_links` | HNSW | The upper-layer link lists of points with level > 0 in point order; each is `level × upper_links_bytes` |
+| 768 | `qg_params` | SymphonyQG | `max_degree` u64; `entry_point` u64; `ef_construction` u64 (0 = unknown); `init` u32 (0 = unknown, 1 = PiPNN, 2 = random); reserved u32 |
+| 769 | `qg_centroid` | SymphonyQG, `code_bits > 0` | `padded_dim` f32 |
+| 770 | `qg_records` | SymphonyQG | `num_points` [records](#symphonyqg-records) |
+
+An IVF file has exactly one routing section, the one that `ivf_params` names; a rerank section exactly when `code_bits > 1` or raw vectors are stored.
+
+`hnsw_levels` replaces the per-point length prefix of the earlier HNSW-RaBitQ layout, so a reader knows every size before reading the link lists.
+
+### Record layouts
+
+These are the in-memory layouts the indexes use today, written as is, so that `load` copies sections without converting them. Record sizes follow from the header and parameter sections; readers derive them and compare them with the section sizes. Floats inside records are not aligned. Reserved bytes inside bulk data are written as zero and ignored by readers, which do not scan bulk data for them.
+
+The tables use `id_bits = 32`, so an ID takes 4 bytes; this is the only value the in-memory indexes write.
+
+#### Single-code record
+
+One vector's `b`-bit code with its two factors. IVF-RaBitQ and HNSW-RaBitQ use it for the extra bits (`b = code_bits - 1`), SymphonyQG for its whole code (`b = code_bits`).
+
+| Offset | Size | Content |
+| --- | --- | --- |
+| 0 | `padded_dim * b / 8` | The codes as [packed codes](#packed-codes-version-1) of width `b` |
+| `padded_dim * b / 8` | 4 | `add`, f32 |
+| `padded_dim * b / 8 + 4` | 4 | `rescale`, f32 |
+
+The record has no `error` factor.
+
+#### HNSW sign code
+
+HNSW-RaBitQ stores the 1-bit code in a different bit order from the `rabitqlib.quant` bitset. Split the `padded_dim` coordinates into groups of 64, where the last group has 32 coordinates when `padded_dim` is not a multiple of 64. A group of `G` bytes, read as a little-endian integer, stores coordinate `t` of the group in bit `8G - 1 - t`. This is what `pack_binary_to_bytes` writes (checked against it for `padded_dim` 32, 64, 96, 160 and 1024); the `PackBinaryTest` cases in `tests/unit/rabitqlib/utils/space_test.cpp` check this bit order.
+
+#### HNSW-RaBitQ records
+
+Let `L = 4 * (base_max_degree + 1)` and `U = 4 * (upper_max_degree + 1)`.
+
+| Offset | Size | Content |
+| --- | --- | --- |
+| 0 | 2 | Base-layer neighbor count, u16 |
+| 2 | 2 | Reserved |
+| 4 | `4 * base_max_degree` | Base-layer neighbor IDs; entries past the count are unspecified |
+| `L` | 4 | Cluster ID, u32; bit 31 is the removal mark (see [HNSW removal](development.md#hnsw-removal)) |
+| `L + 4` | 4 | Row ID of the point, u32 |
+| `L + 8` | `padded_dim / 8` | [Sign code](#hnsw-sign-code) |
+| `L + 8 + padded_dim / 8` | 12 | `add`, `rescale` and `error`, f32 |
+| `L + 20 + padded_dim / 8` | | When `code_bits > 1`, a [single-code record](#single-code-record) with `b = code_bits - 1` |
+
+A point at level `l > 0` has `l` upper-layer link lists in `hnsw_upper_links`, for levels 1 to `l`, each `U` bytes: a u16 count, 2 reserved bytes, then `upper_max_degree` neighbor IDs.
+
+#### HNSW routing graph
+
+The centroid graph of IVF-RaBitQ's HNSW routing is the layout hnswlib's `saveIndex` writes. Unlike the rest of format 2 it is not defined field by field by this library, so it is fixed here as written on the supported 64-bit little-endian platforms (`size_t` is 8 bytes, `int` and `unsigned` 4):
+
+| Offset | Size | Type | Field | Rule |
+| --- | --- | --- | --- | --- |
+| 0 | 8 | u64 | `offset_level0` | 0 |
+| 8 | 8 | u64 | `max_elements` | At least `count` |
+| 16 | 8 | u64 | `count` | `num_clusters` |
+| 24 | 8 | u64 | `record_bytes` | `label_offset + 8` |
+| 32 | 8 | u64 | `label_offset` | `data_offset + 4 * padded_dim` |
+| 40 | 8 | u64 | `data_offset` | `4 + 4 * max_m0` |
+| 48 | 4 | i32 | `max_level` | The entry point's level, at least 0 |
+| 52 | 4 | u32 | `entry_point` | Below `count` |
+| 56 | 8 | u64 | `max_m` | `m` |
+| 64 | 8 | u64 | `max_m0` | `2 * m` |
+| 72 | 8 | u64 | `m` | 2 to 10,000 |
+| 80 | 8 | f64 | `level_multiplier` | Finite and positive |
+| 88 | 8 | u64 | `ef_construction` | At least `m` |
+
+Then `count` base records of `record_bytes`: a u16 neighbor count of at most `max_m0`, a flags byte whose bit 0 (hnswlib's deletion mark) must be clear, a reserved byte, `max_m0` u32 neighbor IDs, the rotated centroid (`padded_dim` f32) and its label (u64). Then, per point in order, a u32 byte length followed by that many bytes of upper-layer link lists: `level` lists of `4 + 4 * max_m` bytes each, laid out as in the base record. Every neighbor ID is below `count` and has at least the level of the list that holds it.
+
+#### SymphonyQG records
+
+Every vertex has `max_degree` neighbor slots, a multiple of 32. Let `V` be the size of the vector part: `4 * dim` for raw vectors, or the [single-code record](#single-code-record) size with `b = code_bits` otherwise.
+
+| Offset | Size | Content |
+| --- | --- | --- |
+| 0 | `V` | The vector: `dim` float32 values (`raw_type = float32`, `code_bits = 0`), or a single-code record |
+| `V` | `(max_degree / 32) * (padded_dim * 4 + 256)` | The neighbors' 1-bit codes, quantized against this vertex, as [FastScan blocks](#fastscan-blocks-version-1) without the `error` factor: sign codes, then 32 `add` and 32 `rescale` values |
+| `V + (max_degree / 32) * (padded_dim * 4 + 256)` | `4 * max_degree` | Neighbor IDs |
+
+Unused lanes of a partial neighbor block have zero factors. Their IDs are left over from construction, but like every ID slot they are below `num_points`, which readers check.
+
+### IVF-RaBitQ files
+
+Besides the rules above, an IVF-RaBitQ reader requires:
+
+- `num_points` from 1 to 2^31, and every stored ID below it;
+- `code_bits` from 1 to 9, with `raw_type = float32` only when `code_bits = 1`, and `raw_type` none or float32;
+- `id_bits = 32`;
+- in `ivf_params`, `num_clusters` from 1 to 2^31, `initializer` 1 to 3, and the reserved field zero;
+- cluster sizes that add up to `num_points`;
+- a seed, when known, of at most 2^32 − 1.
+
+### HNSW-RaBitQ files
+
+An HNSW-RaBitQ reader requires `num_points` from 1 to 2^31, `code_bits` from 1 to 9, `raw_type` none, `id_bits = 32`, `dim` at least 64, and an FHT/Kac rotator. In `hnsw_params`: `max_elements` from `num_points` to 2^31; `num_clusters` from 1 to 2^31; `M` from 2 to 10,000, with `upper_max_degree = M` and `base_max_degree = 2 * M`; `ef_construction` at least `M`; a finite positive `level_multiplier`; `max_level` at least 0; `entry_point` below `num_points`; and the reserved field zero. Every level in `hnsw_levels` is at most `max_level`, and the entry point's level equals it. Every record's cluster ID (without the removal mark) is below `num_clusters`, its labels are distinct, its base-layer neighbor count is at most `base_max_degree` and each upper-layer count at most `M`, and every neighbor ID is below `num_points` with at least the level of the list that holds it.
+
+### SymphonyQG files
+
+A SymphonyQG reader requires `id_bits = 32` and either raw vectors (`code_bits = 0`, `raw_type = float32`) or `code_bits` 4 or 8 with `raw_type` none; a seed, when known, of at most 2^32 − 1; `num_points` up to 2^31; in `qg_params`, a `max_degree` that is a positive multiple of 32 and below `num_points`, `entry_point` below `num_points`, `init` 0 to 2 and the reserved field zero; `qg_centroid` exactly when the codes are quantized; and every neighbor ID below `num_points`.
+
+### Companion files
+
+Only IVF-SSD uses them. `.ssd` holds the page-packed inverted lists, read with `O_DIRECT` and too large to keep in the main file. The `companions` section lists each one:
+
+| Offset | Size | Type | Field |
+| --- | --- | --- | --- |
+| 0 | 4 | u32 | `role`: 1 = SSD inverted lists |
+| 4 | 4 | u32 | reserved |
+| 8 | 32 | ASCII | `suffix` appended to the main file's path, such as `".ssd"`, NUL-padded; no path separators |
+| 40 | 8 | u64 | `size` in bytes |
+| 48 | 8 | u64 | `fingerprint` |
+
+`fingerprint` is the 64-bit FNV-1a hash that RaBitQ-SSD already uses (offset basis 1469598103934665603, prime 1099511628211) over the rotated centroids as f32 bytes. It is deterministic, so saving the same index twice gives identical files.
+
+A companion starts with a 4,096-byte header page: magic `"RABQSSD\0"`, version, `fingerprint`, `num_points` and `code_bits`, then zeros, with a CRC-32 over the page. Data pages follow at offset 4,096, keeping the 4,096-byte alignment that `O_DIRECT` needs. Loading rejects a missing companion, or one whose size, fingerprint or header does not match the main file.
+
+RaBitQ-SSD's swappable coarse quantizer is not a companion: the base does not pin one. A coarse-quantizer file is its own file and records the base's fingerprint, so the pairing is checked from the coarse side. Its layout is specified when IVF-SSD moves into the library.
+
+### Reading
+
+A reader checks, in order, and validates every size before allocating. The loader of each index knows the index kind it expects, so a file of another kind is reported as such before any section is checked:
+
+1. The file is at least 128 bytes long, and the magic, `version` and `header_bytes` are valid.
+2. The section table is non-empty and lies within the file, and `header_crc32` matches.
+3. Feature flags, as in the table above.
+4. `index_kind` is the expected one; the fields that every kind shares are valid; then the expecting index's own header rules hold.
+5. Each table entry, in order: a nonzero kind, its flags and reserved field, a zero `crc32` unless `checksummed` is set, alignment, bounds, the [layout](#layout) rules (order and overlap) and repetition, then whether its kind is known. An unknown required kind rejects the file here.
+6. The file ends where the table or the last section ends.
+7. Each known checksummed section matches its `crc32`.
+8. The index's required sections are present, and each section's size equals what the header and parameter sections imply, before its content is read.
+
+Steps 1–7 belong to the container; step 8 and the index's header rules in step 4 belong to each index. Readers read through the stream buffer, so the stream's exception mask does not matter, and need seekable input.
+
+A file that fails any of these checks, or a damaged file of an [earlier layout](#earlier-layouts), raises `rabitqlib::FormatError` in C++, a subclass of `std::runtime_error`, and `rabitqlib.FormatError` in Python, a subclass of both `ValueError` and `RuntimeError`. `rabitqlib.quant` raises the same class for blobs. A file that cannot be opened raises a plain `std::runtime_error` (Python `RuntimeError`). A read that fails after opening cannot be told from a truncated file, so it raises `FormatError`.
+
+Index files remain trusted input (see [Index file compatibility](docs/index/usage.md#index-file-compatibility)). These checks report truncated, corrupt or mismatched files; they do not make crafted files safe.
+
+### Writing
+
+A writer writes the file once, front to back, so it does not need seekable output (`save` writes devices and FIFOs in place): it buffers the checksummed sections, which are small, to know their checksums before the table. `save` writes to a temporary file and renames it into place, as today. With the routing graph inside the main file, IVF-RaBitQ no longer has a second rename that can leave a new sidecar beside an old index. Resaving a file loaded from an earlier layout writes format 2. IVF-SSD companion files are written before the main file, so a failed save never leaves a main file that points to a missing companion.
+
+### Earlier layouts
+
+Readers dispatch on the leading bytes: `"RABQINDX"`, then each index's legacy magic (IVF `RABQIDX1` and `RBFQRAW1`, SymphonyQG quantized), then the unversioned fallbacks the readers accept today. Legacy files have no cosine metric, seed or 64-bit IDs; they load as `seed_known = false` with 32-bit IDs, as they do in 0.8. The frozen fixtures in `tests/fixtures/persistence/` keep covering every layout.
+
+### Compatibility rules
+
+- A new release reads every earlier released index file.
+- An older release reads a newer format-2 file or rejects it with an error naming the problem; it never misreads it. Older releases reject `version` values other than 2, unknown `index_kind`, `metric` or `id_bits` values, unknown required sections and unknown `incompat` bits.
+- An additive change appends header fields (raising `header_bytes`), adds sections, or adds feature bits, chosen by the table in [Feature flags](#feature-flags). A change that an older reader cannot detect from these is not allowed; it needs `version = 3`.
+- Every released change adds a frozen fixture. Synthetic "future" fixtures check the rules above: an unknown optional section loads; an unknown required section, an `incompat` bit or a larger `version` is rejected with its message; a `ro_compat` bit loads read-only; a longer header loads.
diff --git a/docs/maintaining.md b/docs/maintaining.md
index ff9dc959..38aa468f 100644
--- a/docs/maintaining.md
+++ b/docs/maintaining.md
@@ -229,6 +229,9 @@ Use lowercase prefixes, a space after the colon and a nonempty summary, for exam
`fix(ivf): update only affected clusters`. A scope and a `!` marker before the
colon are optional. The marker does not change the category or authorize a
breaking change; compatibility decisions still follow the project rules.
+Add the manual label `release:breaking` to a merged breaking change: its category,
+Breaking changes, comes first, so the PR is listed there instead of under its
+automatic category.
For dependency-only changes, use `deps:` rather than `chore(deps):`.
The workflow creates its repository labels as needed and updates only the
diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml
index 65679d7e..fbaf0e3c 100644
--- a/docs/mkdocs.yml
+++ b/docs/mkdocs.yml
@@ -9,11 +9,13 @@ copyright: Copyright © VectorDB Group, Nanyang Technological University
nav:
- Home: index.md
- Quick start: quick_start.md
- - Migrating to 0.8: python_migration.md
+ - Migrating to 0.9: python_migration.md
- Installation: installation.md
- C++ Integration: cpp_integration.md
# Group by minor version: nested groups stay collapsed except the current page's.
- Release notes:
+ - "0.9":
+ - "0.9.0": releases/0.9.0.md
- "0.8":
- "0.8.5": releases/0.8.5.md
- "0.8.4": releases/0.8.4.md
diff --git a/include/rabitqlib/clustering/detail/kmeans.hpp b/include/rabitqlib/clustering/detail/kmeans.hpp
index 809dc689..9257ef39 100644
--- a/include/rabitqlib/clustering/detail/kmeans.hpp
+++ b/include/rabitqlib/clustering/detail/kmeans.hpp
@@ -25,6 +25,7 @@
#include "rabitqlib/index/detail/parallel_exception.hpp"
#include "rabitqlib/index/types.hpp"
#include "rabitqlib/utils/cpu_features.hpp"
+#include "rabitqlib/utils/input_checks.hpp"
#include "rabitqlib/utils/space.hpp"
#include "rabitqlib/utils/tools.hpp"
@@ -32,7 +33,6 @@ namespace rabitqlib::clustering {
enum class FinalAssignmentMode : uint8_t {
Approximate = 0,
- SymphonyQG = Approximate, // Compatibility name for the graph assignment path.
Exact = 1,
};
@@ -535,12 +535,8 @@ class LloydKMeans : public Parameters {
std::string(Assignment::kName) + " input dimensions overflow ptrdiff_t"
);
}
- // Leave headroom for products of squared distances in graph pruning,
- // as well as quantized reconstruction and rotated residuals.
- const double max_coordinate = std::sqrt(
- std::sqrt(static_cast(std::numeric_limits::max())) /
- (64.0 * static_cast(d))
- );
+ // The index bound, so training accepts every point the indexes accept.
+ const float max_coordinate = max_coordinate_magnitude(d);
bool in_range = true;
bool finite = true;
#pragma omp parallel for num_threads(num_workers) reduction(&& : finite, in_range) \
@@ -549,7 +545,7 @@ class LloydKMeans : public Parameters {
++index) {
const size_t i = static_cast(index);
finite = finite && std::isfinite(x[i]);
- in_range = in_range && std::abs(static_cast(x[i])) <= max_coordinate;
+ in_range = in_range && std::abs(x[i]) <= max_coordinate;
}
if (!finite) {
throw std::invalid_argument(
diff --git a/include/rabitqlib/clustering/qgkmeans.hpp b/include/rabitqlib/clustering/qgkmeans.hpp
index 280c75f6..96f112c2 100644
--- a/include/rabitqlib/clustering/qgkmeans.hpp
+++ b/include/rabitqlib/clustering/qgkmeans.hpp
@@ -29,7 +29,6 @@
namespace rabitqlib::qgkmeans {
using clustering::FinalAssignmentMode;
-using QGKMeansIterationStats = clustering::KMeansIterationStats;
namespace detail {
@@ -52,14 +51,14 @@ struct QGKMeansParameters {
FinalAssignmentMode final_assignment = FinalAssignmentMode::Approximate;
// SymphonyQG assignment parameters.
- uint32_t graph_degree = 32;
- uint32_t ef_build = 240;
+ uint32_t max_degree = 32;
+ uint32_t ef_construction = 240;
uint32_t ef_search = 16;
// Graph-building passes after PiPNN initialization; the last refines the graph.
uint32_t graph_build_iterations = 1;
uint32_t num_threads = 0;
- // Centroid storage in QG: 0 for raw float32, or 4/8-bit RaBitQ.
- uint32_t quantization_bits = 0;
+ // Centroid storage in QG: 32 for raw float32, or 4/8-bit RaBitQ.
+ uint32_t nbits = 32;
// When positive, train on a random sample of k * max_points_per_centroid
// vectors if there are more, then assign all vectors; 0 trains on all vectors.
size_t max_points_per_centroid = 0;
@@ -67,6 +66,11 @@ struct QGKMeansParameters {
namespace detail {
+// QG's own storage argument, which is 0 for raw float32.
+inline uint32_t qg_quantization_bits(const QGKMeansParameters& cp) {
+ return cp.nbits == 32 ? 0 : cp.nbits;
+}
+
// One training call owns the storage; the public assign adapter can instead
// borrow caller storage for one batch. State is read-only while workers run.
class QuerySumCache {
@@ -136,8 +140,8 @@ class QGAssigner {
QGAssigner(
size_t d,
size_t k,
- uint32_t graph_degree,
- uint32_t ef_build,
+ uint32_t max_degree,
+ uint32_t ef_construction,
uint32_t ef_search,
uint32_t graph_build_iterations,
uint32_t num_threads = 0,
@@ -147,18 +151,21 @@ class QGAssigner {
)
: dim_(d)
, num_clusters_(k)
- , graph_degree_(graph_degree)
- , ef_build_(ef_build)
+ , max_degree_(max_degree)
+ , ef_construction_(ef_construction)
, ef_search_(ef_search)
, graph_build_iterations_(graph_build_iterations)
, seed_(seed) {
validate_configuration(num_threads);
+ // Cosine belongs to the indexes, which normalize vectors; the assigner's exact
+ // distances are raw L2 or inner product.
+ validate_metric_type(metric_type);
num_workers_ = static_cast(resolve_num_threads(num_threads));
graph_ = std::make_unique>(
num_clusters_,
dim_,
- graph_degree_,
+ max_degree_,
metric_type,
RotatorType::FhtKacRotator,
quantization_bits,
@@ -170,7 +177,7 @@ class QGAssigner {
for (uint32_t thread = 0; thread < num_workers_; ++thread) {
scratch_.emplace_back(
std::make_unique(
- graph_->padded_dim(), graph_degree_, ef_search_, 1
+ graph_->padded_dim(), max_degree_, ef_search_, 1
)
);
}
@@ -207,7 +214,7 @@ class QGAssigner {
);
builder_ = std::make_unique(
*graph_,
- ef_build_,
+ ef_construction_,
centroids,
build_threads,
symqg::QGInitialization::PiPNN,
@@ -284,7 +291,7 @@ class QGAssigner {
for (uint32_t thread = 0; thread < num_workers_; ++thread) {
scratch.emplace_back(
std::make_unique(
- graph_->padded_dim(), graph_degree_, ef_search_, 1
+ graph_->padded_dim(), max_degree_, ef_search_, 1
)
);
}
@@ -367,19 +374,19 @@ class QGAssigner {
"QGKMeans currently requires dimensions in the range [64, 65536]"
);
}
- if (graph_degree_ == 0 || graph_degree_ % fastscan::kBatchSize != 0) {
+ if (max_degree_ == 0 || max_degree_ % fastscan::kBatchSize != 0) {
throw std::invalid_argument(
- "QGKMeans graph degree must be a positive multiple of 32"
+ "QGKMeans max_degree must be a positive multiple of 32"
);
}
- if (num_clusters_ <= graph_degree_) {
+ if (num_clusters_ <= max_degree_) {
+ throw std::invalid_argument("QGKMeans requires more centroids than max_degree");
+ }
+ if (ef_construction_ == 0 || ef_search_ == 0) {
throw std::invalid_argument(
- "QGKMeans requires more centroids than the graph degree"
+ "QGKMeans ef_construction and ef_search must be positive"
);
}
- if (ef_build_ == 0 || ef_search_ == 0) {
- throw std::invalid_argument("QGKMeans ef_build and ef_search must be positive");
- }
if (graph_build_iterations_ == 0) {
throw std::invalid_argument("QGKMeans graph_build_iterations must be positive");
}
@@ -387,8 +394,8 @@ class QGAssigner {
size_t dim_;
size_t num_clusters_;
- uint32_t graph_degree_;
- uint32_t ef_build_;
+ uint32_t max_degree_;
+ uint32_t ef_construction_;
uint32_t ef_search_;
uint32_t graph_build_iterations_;
uint32_t num_workers_ = 0;
@@ -416,14 +423,14 @@ class CentroidGraphCache {
, assigner(
d,
k,
- cp.graph_degree,
- cp.ef_build,
+ cp.max_degree,
+ cp.ef_construction,
cp.ef_search,
cp.graph_build_iterations,
cp.num_threads,
cp.seed,
cp.spherical ? METRIC_IP : METRIC_L2,
- cp.quantization_bits
+ qg_quantization_bits(cp)
) {
// The builder borrows this copy, which lives as long as the graph.
assigner.rebuild_centroid_graph(centroids.data());
@@ -436,11 +443,10 @@ class CentroidGraphCache {
return centroids.size() == k * d &&
std::equal(centroids.begin(), centroids.end(), source) &&
p.spherical == cp.spherical && p.seed == cp.seed &&
- p.graph_degree == cp.graph_degree && p.ef_build == cp.ef_build &&
- p.ef_search == cp.ef_search &&
+ p.max_degree == cp.max_degree &&
+ p.ef_construction == cp.ef_construction && p.ef_search == cp.ef_search &&
p.graph_build_iterations == cp.graph_build_iterations &&
- p.num_threads == cp.num_threads &&
- p.quantization_bits == cp.quantization_bits;
+ p.num_threads == cp.num_threads && p.nbits == cp.nbits;
}
};
@@ -513,9 +519,8 @@ class QGAssignment {
static constexpr const char* kName = "QGKMeans";
static void validate_parameters(size_t, const QGKMeansParameters& cp) {
- if (cp.quantization_bits != 0 && cp.quantization_bits != 4 &&
- cp.quantization_bits != 8) {
- throw std::invalid_argument("QGKMeans quantization_bits must be 0, 4, or 8");
+ if (cp.nbits != 4 && cp.nbits != 8 && cp.nbits != 32) {
+ throw std::invalid_argument("QGKMeans nbits must be 4, 8, or 32");
}
}
@@ -532,18 +537,18 @@ class QGAssignment {
, num_points_(n)
, num_workers_(num_workers)
, metric_type_(cp.spherical ? METRIC_IP : METRIC_L2)
- , quantized_(cp.quantization_bits != 0)
+ , quantized_(cp.nbits != 32)
, assigner_(
d,
k,
- cp.graph_degree,
- cp.ef_build,
+ cp.max_degree,
+ cp.ef_construction,
cp.ef_search,
cp.graph_build_iterations,
cp.num_threads,
cp.seed,
metric_type_,
- cp.quantization_bits
+ qg_quantization_bits(cp)
)
, query_sums_(assigner_.graph_->padded_dim(), cp) {}
diff --git a/include/rabitqlib/clustering/rabitqkmeans.hpp b/include/rabitqlib/clustering/rabitqkmeans.hpp
index 7550ed4d..a8d37e65 100644
--- a/include/rabitqlib/clustering/rabitqkmeans.hpp
+++ b/include/rabitqlib/clustering/rabitqkmeans.hpp
@@ -25,7 +25,6 @@
namespace rabitqlib::rabitqkmeans {
using clustering::FinalAssignmentMode;
-using RaBitQKMeansIterationStats = clustering::KMeansIterationStats;
struct RaBitQKMeansParameters {
// Number of clustering iterations.
diff --git a/include/rabitqlib/core/metric.hpp b/include/rabitqlib/core/metric.hpp
index b65a6f08..bb0f49bc 100644
--- a/include/rabitqlib/core/metric.hpp
+++ b/include/rabitqlib/core/metric.hpp
@@ -4,7 +4,9 @@
#include
namespace rabitqlib {
-enum MetricType : uint8_t { METRIC_L2, METRIC_IP };
+// METRIC_COSINE is accepted only by the ANN indexes, which normalize vectors and
+// store inner-product codes; quantizers, FastScan and clustering reject it.
+enum MetricType : uint8_t { METRIC_L2, METRIC_IP, METRIC_COSINE };
inline void validate_metric_type(MetricType metric_type) {
if (metric_type != METRIC_L2 && metric_type != METRIC_IP) {
diff --git a/include/rabitqlib/core/rotator.hpp b/include/rabitqlib/core/rotator.hpp
index 789ba4e0..fc277b05 100644
--- a/include/rabitqlib/core/rotator.hpp
+++ b/include/rabitqlib/core/rotator.hpp
@@ -101,6 +101,16 @@ class MatrixRotator : public Rotator {
qr.householderQ()
.transpose(); // The inverse of an orthogonal matrix is its transpose.
+ // Householder Q alone is not Haar distributed (its determinant is fixed). Giving
+ // column i of Q, row i of q_inv, the sign of R(i, i) makes it Haar (Mezzadri,
+ // Notices AMS 2007, Section 5); only the copied rows matter.
+ const auto r_diag = qr.matrixQR().diagonal();
+ for (Eigen::Index i = 0; i < static_cast(dim); ++i) {
+ if (r_diag(i) < T(0)) {
+ q_inv.row(i) *= T(-1);
+ }
+ }
+
// the random matrix only need the first dim rows, since we just pad zeros for
// the vector to be rotated to padded dimension
std::memcpy(&rand_mat_(0, 0), &q_inv(0, 0), sizeof(T) * dim * padded_dim);
diff --git a/include/rabitqlib/index/format_error.hpp b/include/rabitqlib/index/format_error.hpp
new file mode 100644
index 00000000..104a7374
--- /dev/null
+++ b/include/rabitqlib/index/format_error.hpp
@@ -0,0 +1,19 @@
+#pragma once
+
+#include
+
+namespace rabitqlib {
+
+/**
+ * @brief An index file whose contents are invalid, or which this release cannot read.
+ *
+ * Loading any index throws it for a damaged, mismatched or unsupported file in every
+ * layout; failing to open the file is a plain std::runtime_error. Python raises it as
+ * rabitqlib.FormatError, a subclass of both ValueError and RuntimeError.
+ */
+class FormatError : public std::runtime_error {
+ public:
+ using std::runtime_error::runtime_error;
+};
+
+} // namespace rabitqlib
diff --git a/include/rabitqlib/index/hnsw/hnsw.hpp b/include/rabitqlib/index/hnsw/hnsw.hpp
index 001ffc65..b5c6debb 100644
--- a/include/rabitqlib/index/hnsw/hnsw.hpp
+++ b/include/rabitqlib/index/hnsw/hnsw.hpp
@@ -7,9 +7,11 @@
#include
#include
#include
+#include
#include
#include
#include
+#include
#include
#include
#include
@@ -69,7 +71,12 @@ class HierarchicalNSW {
[[nodiscard]] size_t nbits() const { return ex_bits_ + 1; }
[[nodiscard]] size_t M() const { return M_; }
[[nodiscard]] size_t ef_construction() const { return ef_construction_; }
- [[nodiscard]] MetricType metric_type() const { return metric_type_; }
+ [[nodiscard]] MetricType metric_type() const {
+ return cosine_ ? METRIC_COSINE : metric_type_;
+ }
+ // The construction seed, or no value for an index loaded from a file that does not
+ // record it (files from releases up to 0.8).
+ [[nodiscard]] std::optional seed() const { return seed_; }
// Logical capacity, nonremoved points, and stored records (including removals).
[[nodiscard]] size_t max_elements() const { return max_elements_; }
[[nodiscard]] size_t num_points() const {
@@ -105,7 +112,8 @@ class HierarchicalNSW {
* these centroids; the first add into the empty graph links like construct.
*
* @param num_clusters Number of centroids, from 1 through 2^31
- * @param centroids Centroid vectors (num_clusters * dim) in the original coordinates
+ * @param centroids Centroid vectors (num_clusters * dim) in the original coordinates;
+ * a cosine index scales them to unit length, as it does data
*/
void set_centroids(size_t num_clusters, const float* centroids);
@@ -128,6 +136,7 @@ class HierarchicalNSW {
);
// Centroids and data use the original dimension; cluster_ids has num_points entries.
+ // A cosine index scales the data and the centroids to unit length.
// Input buffers must remain valid until this synchronous call returns or throws;
// the index retains no pointers to them afterward.
// fast_quantization selects fixed-scale extra-bit quantization instead of exact scale
@@ -205,7 +214,8 @@ class HierarchicalNSW {
size_t remove(const PID* labels, size_t num_points);
// Queries use the original dimension. Each result is (distance, external label),
- // where distance estimates squared L2 or 1 - dot according to the index metric.
+ // where distance estimates squared L2, 1 - dot or 1 - cos according to the index
+ // metric.
// ef_search is raised to k and clamped to the stored point count. An empty index,
// trained or not, returns no results.
std::vector>> search(
@@ -220,6 +230,10 @@ class HierarchicalNSW {
// Borrows construct() input only while its workers run; cleared on success or failure.
const float* construction_data_{nullptr};
+ // set_centroids with given = true scales the centroids of a cosine index to unit
+ // length, as data and queries are; train passes centroids trained on scaled data.
+ void set_centroids_impl(size_t num_clusters, const float* centroids, bool given);
+
friend struct HnswTestAccess;
friend struct detail::HnswSearchAccess;
@@ -239,7 +253,8 @@ class HierarchicalNSW {
size_t upper_layer_max_degree_{0};
size_t base_layer_max_degree_{0};
size_t ef_construction_{0};
- MetricType metric_type_{METRIC_L2};
+ MetricType metric_type_{METRIC_L2}; // METRIC_IP for the cosine metric
+ bool cosine_{false}; // normalize data, queries, given centroids; metric_type_ is IP
double level_multiplier_{0.0};
// max_level_ == -1 and entry_point_id_ == kPidMax mark an empty graph.
@@ -284,6 +299,10 @@ class HierarchicalNSW {
std::unordered_map label_lookup_;
std::default_random_engine level_generator_;
+ std::optional seed_; // the construction seed, when known
+ // Loaded from a file with read-only-compatible features this release does not know:
+ // search works, but add, resize, remove and save refuse the index.
+ bool read_only_ = false;
std::unique_ptr visited_set_pool_{nullptr};
@@ -381,9 +400,20 @@ class HierarchicalNSW {
int random_level(double multiplier);
- // Write the index file at exactly this path.
+ // Write the index file in format 2 at exactly this path.
void write_file(const char* filename) const;
+ // Read a file into this freshly created index: format 2, or the earlier layout.
+ void read_format2(std::istream& input);
+ void read_legacy(std::ifstream& input);
+
+ // Check the loaded records and link lists, and rebuild what they imply: the label
+ // lookup and the removed-point count.
+ void validate_graph();
+
+ // Refuse an operation that would modify or save a read-only index.
+ void check_writable(const char* operation) const;
+
// A link list is a count header followed by neighbor IDs.
[[nodiscard]] PID* upper_layer_links(PID internal_id, int level) {
return reinterpret_cast(
diff --git a/include/rabitqlib/index/hnsw_index.hpp b/include/rabitqlib/index/hnsw_index.hpp
new file mode 100644
index 00000000..e8cf5103
--- /dev/null
+++ b/include/rabitqlib/index/hnsw_index.hpp
@@ -0,0 +1,199 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+
+#include "rabitqlib/core/metric.hpp" // IWYU pragma: export
+#include "rabitqlib/index/types.hpp" // IWYU pragma: export
+
+namespace rabitqlib {
+namespace hnsw {
+class HierarchicalNSW;
+}
+namespace rabitqkmeans {
+struct RaBitQKMeansParameters;
+}
+
+// Settings of a new HnswIndex; set the fields by name. The metric comes first, so a lone
+// positional value must be a metric: {4} does not compile.
+struct HnswOptions {
+ MetricType metric = METRIC_L2; // METRIC_L2, METRIC_IP or METRIC_COSINE
+ size_t nbits = 7; // 1-9 quantization bits
+ // Centroids from train, set_centroids or the first add, which caps the count at its
+ // number of points. From 1 to 2^31.
+ size_t num_clusters = 16;
+ size_t M =
+ 16; // graph connectivity, at least 2; the base layer keeps up to 2 * M edges
+ size_t ef_construction = 200; // construction search breadth
+ std::optional seed; // graph and rotation seed; no value draws one
+};
+
+/**
+ * @brief An HNSW-RaBitQ index with the workflow of the Python HnswIndex.
+ *
+ * Create it, then add vectors: the first add trains an untrained index on them. Call
+ * train on a sample, or set_centroids, first to choose the training data or the
+ * centroids. Search, remove and save need a trained index. Capacity grows on add, at
+ * least doubling; reserve preallocates it.
+ *
+ * IDs are the row numbers the index assigns, consecutive from 0 in the order points are
+ * added. Removed points keep their IDs.
+ *
+ * Const members may run concurrently; a call that changes the index needs exclusive
+ * access. Arguments outside their documented range throw std::invalid_argument, a call
+ * in the wrong state std::logic_error, and load rabitqlib::FormatError for a damaged or
+ * unsupported file. The index is movable and not copyable; a moved-from index may only be
+ * destroyed or assigned to.
+ */
+class HnswIndex {
+ public:
+ /**
+ * @param dim Vector dimension
+ * @param options Metric, bits, cluster count, graph settings and seed
+ */
+ explicit HnswIndex(size_t dim, const HnswOptions& options = {});
+
+ HnswIndex(HnswIndex&& other) noexcept;
+ HnswIndex& operator=(HnswIndex&& other) noexcept;
+ HnswIndex(const HnswIndex&) = delete;
+ HnswIndex& operator=(const HnswIndex&) = delete;
+ ~HnswIndex();
+
+ // Load an index saved by any release. A file saved before training loads untrained,
+ // with 16 clusters to train; without a recorded seed, it needs train or set_centroids
+ // before add.
+ static HnswIndex load(const char* filename);
+
+ // Requires at least one stored point. Releases up to 0.8 cannot read the file.
+ void save(const char* filename) const;
+
+ /**
+ * @brief Clustering parameters of train and of the first add.
+ *
+ * Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and
+ * cosine, and seed equal to the low 32 bits of the index seed, or the k-means default
+ * for a file without one. Include rabitqlib/clustering/rabitqkmeans.hpp to read or
+ * change the fields.
+ */
+ rabitqkmeans::RaBitQKMeansParameters& cp();
+ [[nodiscard]] const rabitqkmeans::RaBitQKMeansParameters& cp() const;
+
+ /**
+ * @brief Train num_clusters() centroids on `data` and set them.
+ *
+ * Only centroids are trained; add assigns points. Retraining is allowed while the
+ * index stores no points. The index is unchanged if this throws.
+ *
+ * @param data Training points (num_points * dim)
+ * @param num_points At least num_clusters()
+ * @param num_threads Worker count for this call; no value uses cp().num_threads
+ */
+ void train(
+ const float* data,
+ size_t num_points,
+ std::optional num_threads = std::nullopt
+ );
+
+ /**
+ * @brief Use the given centroids instead of training.
+ *
+ * Allowed while the index stores no points. The index is unchanged if this throws.
+ * A cosine index scales the centroids to unit length, as it does data.
+ *
+ * @param centroids num_clusters() * dim values
+ */
+ void set_centroids(const float* centroids);
+
+ /**
+ * @brief Add points, training an untrained index on them first.
+ *
+ * The first add trains min(num_clusters(), num_points) centroids on `data` as train
+ * does, so it needs no cluster_ids; if it throws, the index stays untrained and
+ * empty, with its capacity. On a trained index the points are quantized against the
+ * existing centroids, which do not move. Capacity grows to fit the points, at least
+ * doubling, after the points and cluster IDs are checked. A failure while linking may
+ * leave part of the batch in the index, which stays safe to search, save and destroy.
+ * An index loaded from a file saved before training has no seed, so add does not
+ * train it; call train or set_centroids first.
+ *
+ * @param data New points (num_points * dim)
+ * @param num_points Number of new points
+ * @param options Cluster IDs, worker count and quantization speed. With more than one
+ * worker the graph links vary between runs; use one, and a seed, for a reproducible
+ * graph.
+ * @return ID of the first new point; the batch has consecutive IDs
+ */
+ Id add(const float* data, size_t num_points, const AddOptions& options = {});
+
+ /**
+ * @brief Exclude points from later search results.
+ *
+ * Removed points keep their IDs, storage and place in the graph, and removal cannot
+ * be undone.
+ *
+ * @param ids IDs in [0, num_stored_points()); repeats count once
+ * @param num_ids Number of IDs
+ * @return Number of points newly removed
+ */
+ size_t remove(const Id* ids, size_t num_ids);
+
+ // Grow the capacity to num_points; a smaller value changes nothing.
+ void reserve(size_t num_points);
+
+ /**
+ * @brief Search a batch of queries.
+ *
+ * Slots without a result get kNoId and +inf. Distances estimate squared L2, 1 - dot
+ * or 1 - cos according to the metric; lower is better.
+ *
+ * @param queries num_queries * dim values
+ * @param k Results per query, from 1 to 2^31; may exceed the number of points
+ * @param ids num_queries * k results
+ * @param distances num_queries * k results, or nullptr
+ */
+ void search(
+ const float* queries,
+ size_t num_queries,
+ size_t k,
+ Id* ids,
+ float* distances,
+ const GraphSearchOptions& options = {}
+ ) const;
+
+ [[nodiscard]] size_t dim() const;
+ // The configured count until centroids are set, then the trained count.
+ [[nodiscard]] size_t num_clusters() const;
+ [[nodiscard]] size_t nbits() const;
+ [[nodiscard]] MetricType metric() const;
+ [[nodiscard]] size_t M() const;
+ [[nodiscard]] size_t ef_construction() const;
+ // No value for an index loaded from a file of a release up to 0.8. A file written by
+ // the C++ HierarchicalNSW class may hold a seed above 32 bits.
+ [[nodiscard]] std::optional seed() const;
+ // Points the index can hold before it grows, including removed ones.
+ [[nodiscard]] size_t capacity() const;
+ // Live, searchable points.
+ [[nodiscard]] size_t num_points() const;
+ // Stored points, including removed ones.
+ [[nodiscard]] size_t num_stored_points() const;
+ // Whether centroids are set, by train, set_centroids, the first add or load.
+ [[nodiscard]] bool is_trained() const;
+
+ private:
+ HnswIndex(
+ std::unique_ptr index,
+ std::unique_ptr cp,
+ size_t num_clusters
+ );
+
+ void check_trained(const char* operation) const;
+ void check_trainable() const;
+
+ std::unique_ptr index_;
+ std::unique_ptr cp_;
+ size_t num_clusters_; // centroid count train and set_centroids expect when untrained
+};
+
+} // namespace rabitqlib
diff --git a/include/rabitqlib/index/ivf/detail/hnsw_sidecar.hpp b/include/rabitqlib/index/ivf/detail/hnsw_sidecar.hpp
index 32bde339..080a42ef 100644
--- a/include/rabitqlib/index/ivf/detail/hnsw_sidecar.hpp
+++ b/include/rabitqlib/index/ivf/detail/hnsw_sidecar.hpp
@@ -5,37 +5,40 @@
#include
#include
#include
-#include
#include
+#include
#include
#include
-#include
+#include "rabitqlib/index/format_error.hpp"
#include "rabitqlib/third/hnswlib/hnswlib.h"
-#include "rabitqlib/utils/path.hpp"
namespace rabitqlib::ivf::detail {
-// The HNSW initializer stores its graph at the index path plus this suffix. Saving,
-// loading and atomic replacement must all agree on it.
+// Releases before index format 2 stored the HNSW routing graph at the index path plus
+// this suffix; loading those files reads it from there.
inline constexpr char kHnswSidecarSuffix[] = ".hnsw";
-// hnswlib's native sidecar has no version tag. Check the existing writer's
-// header and record lengths before its loader uses offsets or allocates links.
-// As with the main index file, callers must not mutate the file during loading.
-inline void validate_hnsw_sidecar_file(
- const std::string& path, size_t expected_count, size_t vector_bytes
+// hnswlib's native layout has no version tag. Check the header and record lengths of
+// the `bytes` bytes at the current position of `input` before hnswlib's loader uses
+// offsets or allocates links, then restore the position. As with the index file,
+// callers must not mutate the data during loading.
+inline void validate_hnsw_graph(
+ std::istream& input, uint64_t bytes, size_t expected_count, size_t vector_bytes
) {
- std::ifstream input(io_impl::filesystem_path(path), std::ios::binary | std::ios::ate);
- if (!input) {
- throw std::runtime_error("Cannot open HNSW centroid sidecar");
+ const std::streampos begin = input.tellg();
+ if (begin == std::streampos(std::streamoff(-1))) {
+ throw FormatError("Cannot read HNSW centroid graph");
}
- const auto end = input.tellg();
- input.seekg(0);
+ // Stay within the graph's bytes, as a budget rather than by querying the position:
+ // in an index file, other data follows them.
+ auto remaining = static_cast(bytes);
const auto read = [&](auto& value) {
- if (!input.read(reinterpret_cast(&value), sizeof(value))) {
- throw std::runtime_error("Truncated HNSW centroid sidecar");
+ if (remaining < static_cast(sizeof(value)) ||
+ !input.read(reinterpret_cast(&value), sizeof(value))) {
+ throw FormatError("Truncated HNSW centroid graph");
}
+ remaining -= static_cast(sizeof(value));
};
size_t level0_offset = 0, capacity = 0, count = 0, level0_record_bytes = 0;
size_t label_offset = 0, data_offset = 0;
@@ -58,12 +61,12 @@ inline void validate_hnsw_sidecar_file(
read(ef_construction);
if (count != expected_count || count == 0 || capacity < count ||
count > std::numeric_limits::max()) {
- throw std::runtime_error("HNSW centroid count does not match IVF cluster count");
+ throw FormatError("HNSW centroid count does not match IVF cluster count");
}
constexpr size_t kMaxM = 10000; // hnswlib caps M at this value.
if (m < 2 || m > kMaxM || max_m != m || max_m0 != 2 * m || !std::isfinite(mult) ||
mult <= 0 || ef_construction < m) {
- throw std::runtime_error("Invalid HNSW centroid graph parameters");
+ throw FormatError("Invalid HNSW centroid graph parameters");
}
const size_t upper_layer_links_bytes =
sizeof(hnswlib::linklistsizeint) + max_m * sizeof(hnswlib::tableint);
@@ -73,14 +76,13 @@ inline void validate_hnsw_sidecar_file(
data_offset > label_offset || label_offset > level0_record_bytes ||
label_offset - data_offset != vector_bytes ||
level0_record_bytes - label_offset != sizeof(hnswlib::labeltype)) {
- throw std::runtime_error("HNSW centroid layout does not match IVF dimension");
+ throw FormatError("HNSW centroid layout does not match IVF dimension");
}
if (max_level < 0 || entry >= count) {
- throw std::runtime_error("Invalid HNSW centroid entry point or maximum level");
+ throw FormatError("Invalid HNSW centroid entry point or maximum level");
}
- auto remaining = end - input.tellg();
- if (remaining < 0 || count > static_cast(remaining) / level0_record_bytes) {
- throw std::runtime_error("Truncated HNSW centroid base records");
+ if (count > static_cast(remaining) / level0_record_bytes) {
+ throw FormatError("Truncated HNSW centroid base records");
}
const auto level0_records_bytes =
static_cast(count * level0_record_bytes);
@@ -89,14 +91,10 @@ inline void validate_hnsw_sidecar_file(
size_t highest_level = 0, entry_level = 0;
for (size_t i = 0; i < count; ++i) {
unsigned int link_bytes = 0; // Native type written by hnswlib::saveIndex.
- if (remaining < static_cast(sizeof(link_bytes))) {
- throw std::runtime_error("Truncated HNSW centroid sidecar");
- }
read(link_bytes);
- remaining -= static_cast(sizeof(link_bytes));
if (link_bytes % upper_layer_links_bytes != 0 ||
link_bytes > static_cast(remaining)) {
- throw std::runtime_error("Invalid HNSW centroid upper-link length");
+ throw FormatError("Invalid HNSW centroid upper-link length");
}
const size_t levels = link_bytes / upper_layer_links_bytes;
highest_level = std::max(highest_level, levels);
@@ -112,8 +110,10 @@ inline void validate_hnsw_sidecar_file(
}
if (!input || remaining != 0 || highest_level != static_cast(max_level) ||
entry_level != highest_level) {
- throw std::runtime_error("Invalid HNSW centroid level structure");
+ throw FormatError("Invalid HNSW centroid level structure");
}
+ input.clear();
+ input.seekg(begin);
}
inline void validate_hnsw_centroid_graph(const hnswlib::HierarchicalNSW& graph) {
@@ -121,11 +121,11 @@ inline void validate_hnsw_centroid_graph(const hnswlib::HierarchicalNSW&
if (graph.enterpoint_node_ >= count || graph.maxlevel_ < 0 ||
graph.element_levels_[graph.enterpoint_node_] != graph.maxlevel_ ||
graph.num_deleted_ != 0) {
- throw std::runtime_error("Invalid HNSW centroid entry point or deletion state");
+ throw FormatError("Invalid HNSW centroid entry point or deletion state");
}
for (size_t i = 0; i < count; ++i) {
if (graph.element_levels_[i] < 0 || graph.element_levels_[i] > graph.maxlevel_) {
- throw std::runtime_error("Invalid HNSW centroid node level");
+ throw FormatError("Invalid HNSW centroid node level");
}
for (int level = 0; level <= graph.element_levels_[i]; ++level) {
const char* links =
@@ -136,7 +136,7 @@ inline void validate_hnsw_centroid_graph(const hnswlib::HierarchicalNSW&
uint16_t degree = 0; // The high two bytes hold flags, not the degree.
std::memcpy(°ree, links, sizeof(degree));
if (degree > (level == 0 ? graph.maxM0_ : graph.maxM_)) {
- throw std::runtime_error("Invalid HNSW centroid neighbor count");
+ throw FormatError("Invalid HNSW centroid neighbor count");
}
for (size_t j = 0; j < degree; ++j) {
hnswlib::tableint neighbor = 0;
@@ -146,9 +146,7 @@ inline void validate_hnsw_centroid_graph(const hnswlib::HierarchicalNSW&
sizeof(neighbor)
);
if (neighbor >= count || graph.element_levels_[neighbor] < level) {
- throw std::runtime_error(
- "Invalid HNSW centroid neighbor or target level"
- );
+ throw FormatError("Invalid HNSW centroid neighbor or target level");
}
}
}
diff --git a/include/rabitqlib/index/ivf/initializer.hpp b/include/rabitqlib/index/ivf/initializer.hpp
index 618d6731..1104965a 100644
--- a/include/rabitqlib/index/ivf/initializer.hpp
+++ b/include/rabitqlib/index/ivf/initializer.hpp
@@ -3,10 +3,12 @@
#include
#include
#include
+#include
#include
-#include
#include
+#include
#include
+#include
#include
#include
#include
@@ -15,6 +17,7 @@
#include "rabitqlib/core/metric.hpp"
#include "rabitqlib/index/detail/parallel_for.hpp"
+#include "rabitqlib/index/format_error.hpp"
#include "rabitqlib/index/ivf/detail/hnsw_sidecar.hpp"
#include "rabitqlib/index/ivf/types.hpp" // IWYU pragma: export
#include "rabitqlib/index/types.hpp"
@@ -61,8 +64,11 @@ class Initializer {
virtual void centroids_distances(
const float* query, size_t nprobe, std::vector>& candidates
) const = 0;
- virtual void load(std::ifstream& input, const char* filename) = 0;
- virtual void save(std::ofstream& output, const char* filename) const = 0;
+ // Write the routing data that read() restores.
+ virtual void write(std::ostream& output) const = 0;
+ // Read `bytes` bytes that write() wrote, from the current position of `input`.
+ // Data that does not fit this initializer raises FormatError.
+ virtual void read(std::istream& input, uint64_t bytes) = 0;
};
inline Initializer::~Initializer() = default;
@@ -113,8 +119,8 @@ class FlatInitializer : public Initializer {
std::copy_n(centroid_candidates.begin(), num_probes, candidates.begin());
}
- // The flat initializer stores its centroids inline in the index file stream.
- void save(std::ofstream& output, const char* /*filename*/) const override {
+ // The flat initializer stores only its centroids.
+ void write(std::ostream& output) const override {
output.write(
reinterpret_cast(centroids_.data()),
static_cast(sizeof(float) * dim_ * num_cluster_)
@@ -124,13 +130,15 @@ class FlatInitializer : public Initializer {
}
}
- void load(std::ifstream& input, const char* /*filename*/) override {
+ void read(std::istream& input, uint64_t bytes) override {
+ if (bytes != sizeof(float) * dim_ * num_cluster_) {
+ throw FormatError("IVF Flat initializer data has the wrong size");
+ }
input.read(
- reinterpret_cast(centroids_.data()),
- static_cast(sizeof(float) * dim_ * num_cluster_)
+ reinterpret_cast(centroids_.data()), static_cast(bytes)
);
if (!input) {
- throw std::runtime_error("IVF Flat initializer cannot be read");
+ throw FormatError("IVF Flat initializer cannot be read");
}
}
};
@@ -153,8 +161,8 @@ class FlatRaBitQInitializer : public Initializer {
void centroids_distances(
const float* query, size_t nprobe, std::vector>& candidates
) const override;
- void save(std::ofstream& output, const char* filename) const override;
- void load(std::ifstream& input, const char* filename) override;
+ void write(std::ostream& output) const override;
+ void read(std::istream& input, uint64_t bytes) override;
};
// Keep centroid routing on the same runtime-selected distance kernels as flat IVF.
@@ -291,28 +299,30 @@ class HNSWInitializer : public Initializer {
}
}
- // The HNSW initializer stores its graph in a separate hnswlib sidecar file.
- void save(std::ofstream& /*output*/, const char* filename) const override {
- alg_hnsw_->saveIndex(std::string(filename) + detail::kHnswSidecarSuffix);
- }
+ // The HNSW initializer stores its graph in hnswlib's own layout, which earlier
+ // releases wrote to the sidecar file .hnsw.
+ void write(std::ostream& output) const override { alg_hnsw_->saveIndex(output); }
- void load(std::ifstream& /*input*/, const char* filename) override {
- const std::string sidecar = std::string(filename) + detail::kHnswSidecarSuffix;
- detail::validate_hnsw_sidecar_file(sidecar, num_cluster_, space_->get_data_size());
- alg_hnsw_->loadIndex(sidecar, space_, num_cluster_);
+ void read(std::istream& input, uint64_t bytes) override {
+ detail::validate_hnsw_graph(input, bytes, num_cluster_, space_->get_data_size());
+ alg_hnsw_->loadIndex(input, static_cast(bytes), space_, num_cluster_);
const auto& graph = *alg_hnsw_;
- // validate_hnsw_sidecar_file already checked these header fields, and loadIndex
- // reads them again from a second open of the file. Recheck the loaded values so
- // a sidecar replaced in between cannot give centroid() an out-of-record offset.
+ // validate_hnsw_graph already checked these header fields, and loadIndex reads
+ // them again. Recheck the loaded values so that data changed in between cannot
+ // give centroid() an out-of-record offset.
if (graph.offsetData_ > graph.label_offset_ ||
graph.label_offset_ > graph.size_data_per_element_ ||
graph.label_offset_ - graph.offsetData_ != space_->get_data_size() ||
graph.size_data_per_element_ - graph.label_offset_ !=
sizeof(hnswlib::labeltype)) {
- throw std::runtime_error("HNSW centroid sidecar changed while loading");
+ throw FormatError("HNSW centroid graph changed while loading");
}
detail::validate_hnsw_centroid_graph(graph);
- rebuild_label_lookup();
+ try {
+ rebuild_label_lookup();
+ } catch (const std::runtime_error& error) {
+ throw FormatError(error.what()); // stored labels that do not fit
+ }
}
~HNSWInitializer() override = default;
diff --git a/include/rabitqlib/index/ivf/ivf.hpp b/include/rabitqlib/index/ivf/ivf.hpp
index 745ed983..f1f16f91 100644
--- a/include/rabitqlib/index/ivf/ivf.hpp
+++ b/include/rabitqlib/index/ivf/ivf.hpp
@@ -2,6 +2,7 @@
#include
#include
+#include
#include
#include
#include
@@ -90,11 +91,16 @@ class IVF {
size_t num_clusters_ = 0;
bool raw_reranking_ = false; // raw vectors replace extra-bit codes
bool ready_ = false; // centroids set, construction or loading completed
- size_t ex_bits_ = 0; // total bits = ex_bits_ + 1; 0 with raw reranking
+ // Loaded from a file with read-only-compatible features this release does not know:
+ // search works, but add, reserve, remove and save refuse the index.
+ bool read_only_ = false;
+ std::optional seed_; // the construction seed, when known
+ size_t ex_bits_ = 0; // total bits = ex_bits_ + 1; 0 with raw reranking
RotatorType rotator_type_ = RotatorType::FhtKacRotator;
std::unique_ptr> rotator_;
std::vector clusters_;
- MetricType metric_type_ = METRIC_L2;
+ MetricType metric_type_ = METRIC_L2; // METRIC_IP for the cosine metric
+ bool cosine_ = false; // normalize data, queries, given centroids; metric_type_ is IP
float (*ip_func_)(const float*, const uint8_t*, size_t) = nullptr;
static constexpr uint64_t kRawFormatMagic = 0x3157415251464252ULL;
@@ -157,6 +163,10 @@ class IVF {
[[nodiscard]] std::unique_ptr make_initializer() const;
+ // set_centroids with given = true scales the centroids of a cosine index to unit
+ // length, as data and queries are; train passes centroids trained on scaled data.
+ void set_centroids_impl(const float* centroids, size_t num_threads, bool given);
+
// Reset the index and allocate a new initializer and per-cluster storage
void allocate_storage(const std::vector& cluster_sizes);
@@ -190,9 +200,22 @@ class IVF {
const float* query, size_t k, size_t nprobe, const PID* result_ids
) const;
- // Write the index file, and any initializer sidecar, at exactly this path.
+ // Write the index file in format 2 at exactly this path.
void write_file(const char* filename) const;
+ // Load a format-2 file into this freshly created index.
+ void read_format2(std::istream& input);
+
+ // Bytes of Flat or FlatRaBitQ routing data; HNSW routing has no fixed size.
+ [[nodiscard]] size_t flat_routing_bytes() const;
+
+ // Check the stored IDs, create the cluster views, count removed points and mark the
+ // index ready: the end of loading in every format.
+ void complete_load(const std::vector& cluster_sizes);
+
+ // Refuse an operation that would modify or save a read-only index.
+ void check_writable(const char* operation) const;
+
public:
explicit IVF() noexcept;
// dim is the original input dimension; total_bits is 1-9 for quantized
@@ -246,7 +269,12 @@ class IVF {
[[nodiscard]] size_t num_stored_points() const { return ready_ ? max_elements_ : 0; }
[[nodiscard]] size_t dimension() const { return dim_; }
[[nodiscard]] size_t nbits() const { return raw_reranking_ ? 32 : ex_bits_ + 1; }
- [[nodiscard]] MetricType metric_type() const { return metric_type_; }
+ [[nodiscard]] MetricType metric_type() const {
+ return cosine_ ? METRIC_COSINE : metric_type_;
+ }
+ // The rotation seed of the seeded constructor, or no value when it is unknown: the
+ // point-count constructor draws one, and files from releases up to 0.8 omit it.
+ [[nodiscard]] std::optional seed() const { return seed_; }
[[nodiscard]] RotatorType rotator_type() const { return rotator_type_; }
[[nodiscard]] InitializerType initializer_type() const { return initializer_type_; }
// Centroids are set, by train, set_centroids, construct or load.
@@ -275,7 +303,8 @@ class IVF {
*
* Builds the centroid initializer and empty clusters, so the index can add points.
* An index created with a point count is built by construct instead, so this
- * throws std::logic_error for it. The index is unchanged if this throws.
+ * throws std::logic_error for it. The index is unchanged if this throws. A cosine
+ * index scales the centroids to unit length, as it does data.
*
* @param centroids Centroid vectors (num_clusters() * dim)
* @param num_threads Threads used to build the centroid initializer
@@ -287,7 +316,8 @@ class IVF {
/**
* @brief Quantize every point into its cluster and build the centroid initializer.
*
- * Replaces any existing contents of the index.
+ * Replaces any existing contents of the index. A cosine index scales the data and
+ * the centroids to unit length.
*
* @param data Data points (max_elements() * dim)
* @param centroids Centroid vectors (num_clusters() * dim)
@@ -372,7 +402,7 @@ class IVF {
void load(const char* filename);
// Automatically use HACC for 4-9 quantized bits; use standard FastScan otherwise.
- // Distances estimate squared L2 or 1 - dot according to the index metric.
+ // Distances estimate squared L2, 1 - dot or 1 - cos according to the index metric.
// k may exceed the point count; slots without a result get kPidMax and +inf.
void search(
const float* query,
diff --git a/include/rabitqlib/index/ivf/types.hpp b/include/rabitqlib/index/ivf/types.hpp
index f487e693..e1a93f28 100644
--- a/include/rabitqlib/index/ivf/types.hpp
+++ b/include/rabitqlib/index/ivf/types.hpp
@@ -4,4 +4,6 @@
namespace rabitqlib::ivf {
enum class InitializerType : uint32_t { Auto = 0, Flat = 1, FlatRaBitQ = 2, HNSW = 3 };
+// Centroid routing of IvfIndex. Auto resolves by cluster count when the index is created.
+using Routing = InitializerType;
} // namespace rabitqlib::ivf
diff --git a/include/rabitqlib/index/ivf_index.hpp b/include/rabitqlib/index/ivf_index.hpp
new file mode 100644
index 00000000..0a132d9f
--- /dev/null
+++ b/include/rabitqlib/index/ivf_index.hpp
@@ -0,0 +1,196 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+
+#include "rabitqlib/core/metric.hpp" // IWYU pragma: export
+#include "rabitqlib/index/ivf/types.hpp" // IWYU pragma: export
+#include "rabitqlib/index/types.hpp" // IWYU pragma: export
+
+namespace rabitqlib {
+namespace ivf {
+class IVF;
+}
+namespace rabitqkmeans {
+struct RaBitQKMeansParameters;
+}
+
+// Settings of a new IvfIndex; set the fields by name. The metric comes first, so a lone
+// positional value must be a metric: {4} does not compile.
+struct IvfOptions {
+ MetricType metric = METRIC_L2; // METRIC_L2, METRIC_IP or METRIC_COSINE
+ size_t nbits = 7; // 1-9 quantization bits, or 32 for raw vectors
+ ivf::Routing routing = ivf::Routing::Auto;
+ std::optional seed; // rotation seed; no value draws one
+};
+
+// Settings of IvfIndex::search.
+struct IvfSearchOptions {
+ // Clusters to probe; a value above num_clusters() probes every cluster. No value
+ // probes num_clusters() / 16, rounded, and at least 1; 0 throws.
+ std::optional nprobe;
+ // Worker count; 0 selects every available CPU, capped by OMP_NUM_THREADS.
+ size_t num_threads = 1;
+ // HACC reranking. No value selects it for 4-9 bits and standard FastScan otherwise.
+ std::optional high_accuracy;
+};
+
+/**
+ * @brief An IVF-RaBitQ index with the workflow of the Python IvfIndex.
+ *
+ * Create it, then add vectors: the first add trains an untrained index on them. Call
+ * train on a sample, or set_centroids, first to choose the training data or the
+ * centroids. Search, remove, reserve_cluster and save need a trained index.
+ *
+ * IDs are the row numbers the index assigns, consecutive from 0 in the order points are
+ * added. Removed points keep their IDs.
+ *
+ * Const members may run concurrently; a call that changes the index needs exclusive
+ * access. Arguments outside their documented range throw std::invalid_argument, a call
+ * in the wrong state std::logic_error, and load rabitqlib::FormatError for a damaged or
+ * unsupported file. The index is movable and not copyable; a moved-from index may only be
+ * destroyed or assigned to.
+ */
+class IvfIndex {
+ public:
+ /**
+ * @param dim Vector dimension
+ * @param num_clusters Number of centroids, from train, set_centroids or the first add
+ * @param options Metric, bits, routing and seed
+ */
+ explicit IvfIndex(size_t dim, size_t num_clusters, const IvfOptions& options = {});
+
+ IvfIndex(IvfIndex&& other) noexcept;
+ IvfIndex& operator=(IvfIndex&& other) noexcept;
+ IvfIndex(const IvfIndex&) = delete;
+ IvfIndex& operator=(const IvfIndex&) = delete;
+ ~IvfIndex();
+
+ // Load an index saved by any release, with its rotation; the result is trained.
+ static IvfIndex load(const char* filename);
+
+ // Requires at least one stored point. Releases up to 0.8 cannot read the file.
+ void save(const char* filename) const;
+
+ /**
+ * @brief Clustering parameters of train and of the first add.
+ *
+ * Defaults: niter 10, max_points_per_centroid 256, spherical for inner product and
+ * cosine, and seed equal to the index seed, or the k-means default for a file
+ * without one. Include rabitqlib/clustering/rabitqkmeans.hpp to read or change the
+ * fields.
+ */
+ rabitqkmeans::RaBitQKMeansParameters& cp();
+ [[nodiscard]] const rabitqkmeans::RaBitQKMeansParameters& cp() const;
+
+ /**
+ * @brief Train num_clusters() centroids on `data` and set them.
+ *
+ * Only centroids are trained; add assigns points. Retraining is allowed while the
+ * index stores no points. The index is unchanged if this throws.
+ *
+ * @param data Training points (num_points * dim)
+ * @param num_points At least num_clusters()
+ * @param num_threads Worker count for this call; no value uses cp().num_threads
+ */
+ void train(
+ const float* data,
+ size_t num_points,
+ std::optional num_threads = std::nullopt
+ );
+
+ /**
+ * @brief Use the given centroids instead of training.
+ *
+ * Allowed while the index stores no points. The index is unchanged if this throws.
+ * A cosine index scales the centroids to unit length, as it does data.
+ *
+ * @param centroids num_clusters() * dim values
+ * @param num_threads Worker count for building the centroid routing
+ */
+ void set_centroids(const float* centroids, size_t num_threads = 0);
+
+ /**
+ * @brief Add points, training an untrained index on them first.
+ *
+ * The first add trains num_clusters() centroids on `data` as train does, so it needs
+ * at least num_clusters() points and no cluster_ids; if it throws, the index stays
+ * untrained and empty. On a trained index the points are quantized against the
+ * existing centroids, which do not move, and the index is unchanged if this throws.
+ *
+ * @param data New points (num_points * dim)
+ * @param num_points Number of new points
+ * @param options Cluster IDs, worker count and quantization speed
+ * @return ID of the first new point; the batch has consecutive IDs
+ */
+ Id add(const float* data, size_t num_points, const AddOptions& options = {});
+
+ /**
+ * @brief Exclude points from later search results.
+ *
+ * Removed points keep their IDs and storage, and removal cannot be undone.
+ *
+ * @param ids IDs in [0, num_stored_points()); repeats count once
+ * @param num_ids Number of IDs
+ * @return Number of points newly removed
+ */
+ size_t remove(const Id* ids, size_t num_ids);
+
+ // Preallocate room for cluster_id to hold num_points points in total, so that later
+ // adds grow it in place. Reserved room is not saved.
+ void reserve_cluster(size_t cluster_id, size_t num_points);
+
+ /**
+ * @brief Search a batch of queries.
+ *
+ * Slots without a result get kNoId and +inf. Distances estimate squared L2, 1 - dot
+ * or 1 - cos according to the metric; lower is better.
+ *
+ * @param queries num_queries * dim values
+ * @param k Results per query, from 1 to 2^31; may exceed the number of points
+ * @param ids num_queries * k results
+ * @param distances num_queries * k results, or nullptr
+ */
+ void search(
+ const float* queries,
+ size_t num_queries,
+ size_t k,
+ Id* ids,
+ float* distances,
+ const IvfSearchOptions& options = {}
+ ) const;
+
+ [[nodiscard]] size_t dim() const;
+ [[nodiscard]] size_t num_clusters() const;
+ [[nodiscard]] size_t nbits() const;
+ [[nodiscard]] MetricType metric() const;
+ // Never Auto: the routing Auto resolved to.
+ [[nodiscard]] ivf::Routing routing() const;
+ // No value for an index loaded from a file of a release up to 0.8.
+ [[nodiscard]] std::optional seed() const;
+ // Live, searchable points.
+ [[nodiscard]] size_t num_points() const;
+ // Stored points, including removed ones.
+ [[nodiscard]] size_t num_stored_points() const;
+ // Whether centroids are set, by train, set_centroids, the first add or load.
+ [[nodiscard]] bool is_trained() const;
+
+ private:
+ IvfIndex(
+ std::unique_ptr index,
+ std::unique_ptr cp
+ );
+
+ void check_trained(const char* operation) const;
+ void check_trainable() const;
+ [[nodiscard]] rabitqkmeans::RaBitQKMeansParameters training_parameters(
+ std::optional num_threads
+ ) const;
+
+ std::unique_ptr index_;
+ std::unique_ptr cp_;
+};
+
+} // namespace rabitqlib
diff --git a/include/rabitqlib/index/symqg/qg.hpp b/include/rabitqlib/index/symqg/qg.hpp
index 1e82f6d0..b414fba2 100644
--- a/include/rabitqlib/index/symqg/qg.hpp
+++ b/include/rabitqlib/index/symqg/qg.hpp
@@ -2,13 +2,16 @@
#include
#include
+#include
#include
+#include
#include
#include
#include "rabitqlib/core/metric.hpp" // IWYU pragma: export
#include "rabitqlib/core/types.hpp" // IWYU pragma: export
#include "rabitqlib/index/detail/visited_set_fwd.hpp" // IWYU pragma: export
+#include "rabitqlib/index/symqg/types.hpp" // IWYU pragma: export
#include "rabitqlib/index/types.hpp" // IWYU pragma: export
#include "rabitqlib/utils/memory.hpp"
#include "rabitqlib/utils/packed.hpp"
@@ -88,7 +91,8 @@ class QuantizedGraph {
size_t padded_dim_ = 0;
float (*raw_dist_func_)(const float*, const float*, size_t) = nullptr;
PID entry_point_id_ = 0;
- MetricType metric_type_ = METRIC_L2;
+ MetricType metric_type_ = METRIC_L2; // METRIC_IP for the cosine metric
+ bool cosine_ = false; // normalize data and queries; metric_type_ is METRIC_IP
RotatorType rotator_type_ = RotatorType::FhtKacRotator;
size_t quantization_bits_ = 0; // 0: raw vectors, 4/8: packed RaBitQ vectors
std::vector centroid_; // rotated global centroid for qg-quant
@@ -114,6 +118,13 @@ class QuantizedGraph {
size_t default_ef_search_ = 0;
bool ready_ = false;
uint32_t seed_ = 42;
+ bool seed_known_ = false; // false for files that do not record the seed
+ // Construction settings a builder records; unknown (0 and no value) otherwise.
+ size_t ef_construction_ = 0;
+ std::optional initialization_;
+ // Loaded from a file with read-only-compatible features this release does not know:
+ // search works, but save refuses the graph until a builder rebuilds it.
+ bool read_only_ = false;
[[nodiscard]] static size_t checked_add(size_t lhs, size_t rhs);
@@ -127,9 +138,12 @@ class QuantizedGraph {
void initialize(bool randomize_rotation = true);
- // Write the graph file at exactly this path.
+ // Write the graph file in index format 2 at exactly this path.
void write_file(const char* filename) const;
+ // Load a format-2 file into this freshly created graph.
+ void read_format2(std::istream& input);
+
void copy_vectors(const float* data, size_t num_workers);
void set_quantization_centroid(const float* centroid);
@@ -279,6 +293,14 @@ class QuantizedGraph {
[[nodiscard]] size_t quantization_bits() const;
+ // The rotation seed, or no value for a graph loaded from a file that does not
+ // record it (files from releases up to 0.8).
+ [[nodiscard]] std::optional seed() const;
+
+ // The settings the builder used, or no value when they are unknown.
+ [[nodiscard]] std::optional ef_construction() const;
+ [[nodiscard]] std::optional initialization() const;
+
[[nodiscard]] bool is_quantized() const;
void set_ep(PID entry);
@@ -343,7 +365,8 @@ class QuantizedGraph {
* buffers, including visited sets.
*
* An optional g_k1xsumq must come from BatchQuery::g_k1xsumq() for the same
- * query and this graph's rotation. A null pointer recomputes the sum.
+ * query and this graph's rotation; with the cosine metric, for the query scaled to
+ * unit norm. A null pointer recomputes the sum.
*/
void search_with_scratch(
const float* __restrict__ query,
diff --git a/include/rabitqlib/index/symqg/qg_builder.hpp b/include/rabitqlib/index/symqg/qg_builder.hpp
index e2bf47e7..70e5f4b3 100644
--- a/include/rabitqlib/index/symqg/qg_builder.hpp
+++ b/include/rabitqlib/index/symqg/qg_builder.hpp
@@ -14,8 +14,6 @@
namespace rabitqlib::symqg {
inline constexpr size_t kMaxBsIter = 5; // max iter for binary search of pruning bar
using CandidateList = std::vector>;
-enum class QGInitialization { PiPNN, Random };
-
// Owns temporary state for SymphonyQG initialization and refinement.
class QGBuilder {
friend struct QGConstructionTestAccess;
diff --git a/include/rabitqlib/index/symqg/types.hpp b/include/rabitqlib/index/symqg/types.hpp
new file mode 100644
index 00000000..479dad56
--- /dev/null
+++ b/include/rabitqlib/index/symqg/types.hpp
@@ -0,0 +1,6 @@
+#pragma once
+
+namespace rabitqlib::symqg {
+// How a builder initializes the graph before refinement.
+enum class QGInitialization { PiPNN, Random };
+} // namespace rabitqlib::symqg
diff --git a/include/rabitqlib/index/symqg_index.hpp b/include/rabitqlib/index/symqg_index.hpp
new file mode 100644
index 00000000..a076ce90
--- /dev/null
+++ b/include/rabitqlib/index/symqg_index.hpp
@@ -0,0 +1,140 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+
+#include "rabitqlib/core/metric.hpp" // IWYU pragma: export
+#include "rabitqlib/index/symqg/types.hpp" // IWYU pragma: export
+#include "rabitqlib/index/types.hpp" // IWYU pragma: export
+
+namespace rabitqlib {
+namespace symqg {
+template
+class QuantizedGraph;
+}
+
+// Settings of a new SymqgIndex; set the fields by name. The metric comes first, so a lone
+// positional value must be a metric: {4} does not compile.
+struct SymqgOptions {
+ MetricType metric = METRIC_L2; // METRIC_L2, METRIC_IP or METRIC_COSINE
+ size_t nbits = 32; // 32 keeps raw float32 vectors; 4 or 8 RaBitQ bits
+ size_t max_degree = 32; // graph degree bound, a positive multiple of 32
+ size_t ef_construction = 200; // construction search breadth, from 1 to 2^32 - 1
+ symqg::QGInitialization init = symqg::QGInitialization::PiPNN;
+ std::optional seed; // rotation and construction seed; no value draws one
+};
+
+/**
+ * @brief A SymphonyQG index with the workflow of the Python SymqgIndex.
+ *
+ * Create it, then add every vector in one call: add builds the graph, and a built
+ * graph cannot be extended. Search and save need a built or loaded index. There is
+ * nothing to train; train only checks its input.
+ *
+ * IDs are the row numbers of the added data, from 0.
+ *
+ * Const members may run concurrently; a call that changes the index needs exclusive
+ * access. Arguments outside their documented range throw std::invalid_argument, a call
+ * in the wrong state std::logic_error, and load rabitqlib::FormatError for a damaged or
+ * unsupported file. The index is movable and not copyable; a moved-from index may only be
+ * destroyed or assigned to.
+ */
+class SymqgIndex {
+ public:
+ /**
+ * @param dim Vector dimension, from 64 to 65536
+ * @param options Metric, bits, graph settings and seed
+ */
+ explicit SymqgIndex(size_t dim, const SymqgOptions& options = {});
+
+ SymqgIndex(SymqgIndex&& other) noexcept;
+ SymqgIndex& operator=(SymqgIndex&& other) noexcept;
+ SymqgIndex(const SymqgIndex&) = delete;
+ SymqgIndex& operator=(const SymqgIndex&) = delete;
+ ~SymqgIndex();
+
+ // Load an index saved by any release; it is built, so add throws.
+ static SymqgIndex load(const char* filename);
+
+ // Requires a built or loaded index. Releases up to 0.8 cannot read the file.
+ void save(const char* filename) const;
+
+ /**
+ * @brief Check that the vectors are finite and within the coordinate range, as add
+ * does; the index does not change. The point count is not checked.
+ *
+ * @param data num_points * dim values
+ */
+ void train(const float* data, size_t num_points) const;
+
+ /**
+ * @brief Build the graph from all vectors, once.
+ *
+ * Uses the constructor's metric, bits, max_degree, ef_construction, init and seed.
+ * If it throws, the index stays without a graph. A built or loaded index throws
+ * std::logic_error; create a new index to rebuild.
+ *
+ * @param data num_points * dim values
+ * @param num_points More than max_degree()
+ * @param num_threads Worker count; 0 selects every available CPU, capped by
+ * OMP_NUM_THREADS
+ * @return ID of the first point, 0; the points have consecutive IDs
+ */
+ Id add(const float* data, size_t num_points, size_t num_threads = 0);
+
+ /**
+ * @brief Search a batch of queries.
+ *
+ * Slots without a result get kNoId and +inf. Distances are squared L2, 1 - dot or
+ * 1 - cos according to the metric, exact for raw vectors and estimated with 4 or 8
+ * bits; lower is better.
+ *
+ * @param queries num_queries * dim values
+ * @param k Results per query, from 1 to 2^31; may exceed the number of points
+ * @param ids num_queries * k results
+ * @param distances num_queries * k results, or nullptr
+ */
+ void search(
+ const float* queries,
+ size_t num_queries,
+ size_t k,
+ Id* ids,
+ float* distances,
+ const GraphSearchOptions& options = {}
+ ) const;
+
+ [[nodiscard]] size_t dim() const;
+ // 32 for raw float32 vectors, or 4 or 8.
+ [[nodiscard]] size_t nbits() const;
+ [[nodiscard]] MetricType metric() const;
+ [[nodiscard]] size_t max_degree() const;
+ // No value for an index loaded from a file of a release up to 0.8.
+ [[nodiscard]] std::optional ef_construction() const;
+ [[nodiscard]] std::optional init() const;
+ [[nodiscard]] std::optional seed() const;
+ // Searchable points: 0 until add.
+ [[nodiscard]] size_t num_points() const;
+ // Stored points, equal to num_points(); SymphonyQG has no removal.
+ [[nodiscard]] size_t num_stored_points() const;
+ // Always true: SymphonyQG needs no training.
+ [[nodiscard]] bool is_trained() const;
+
+ private:
+ explicit SymqgIndex(std::unique_ptr> graph);
+
+ void check_built(const char* operation) const;
+
+ size_t dim_;
+ MetricType metric_;
+ size_t nbits_;
+ size_t max_degree_;
+ // Settings of the current graph or of add; unknown for a file of a release up to 0.8.
+ std::optional ef_construction_;
+ std::optional init_;
+ std::optional seed_;
+ std::unique_ptr> graph_; // null until add or load
+};
+
+} // namespace rabitqlib
diff --git a/include/rabitqlib/index/training.hpp b/include/rabitqlib/index/training.hpp
index 5f3a65a9..82eb4106 100644
--- a/include/rabitqlib/index/training.hpp
+++ b/include/rabitqlib/index/training.hpp
@@ -11,17 +11,19 @@ namespace rabitqlib {
/**
* Centroid training parameters for IVF::train and HierarchicalNSW::train: 10
* iterations, as in Faiss IVF, on a sample of at most 256 points per centroid, spherical
- * k-means for inner product, and the given seed. The k-means classes keep their own
- * defaults, which train on all points.
+ * k-means for inner product and cosine, and the given seed. The k-means classes keep
+ * their own defaults, which train on all points.
*/
inline rabitqkmeans::RaBitQKMeansParameters default_training_parameters(
MetricType metric_type, uint32_t seed
) {
- validate_metric_type(metric_type);
+ if (metric_type != METRIC_COSINE) {
+ validate_metric_type(metric_type);
+ }
rabitqkmeans::RaBitQKMeansParameters cp;
cp.niter = 10;
cp.max_points_per_centroid = 256;
- cp.spherical = metric_type == METRIC_IP;
+ cp.spherical = metric_type != METRIC_L2;
cp.seed = seed;
return cp;
}
diff --git a/include/rabitqlib/index/types.hpp b/include/rabitqlib/index/types.hpp
index cc94266c..003b7e81 100644
--- a/include/rabitqlib/index/types.hpp
+++ b/include/rabitqlib/index/types.hpp
@@ -1,12 +1,41 @@
#pragma once
+#include
#include
#include
+#include
namespace rabitqlib {
using PID = uint32_t;
inline constexpr PID kPidMax = 0xFFFFFFFF;
+// A point ID at the IvfIndex, HnswIndex and SymqgIndex API: the row number the index
+// assigned to the point.
+using Id = int64_t;
+// A search result slot without a point.
+inline constexpr Id kNoId = -1;
+
+// Settings of IvfIndex::add and HnswIndex::add.
+struct AddOptions {
+ // Cluster of each point, or nullptr to route each point with the index's routing,
+ // which may be approximate.
+ const PID* cluster_ids = nullptr;
+ // Worker count. No value trains an untrained index with cp().num_threads and adds
+ // with every available CPU; 0 selects every available CPU, capped by OMP_NUM_THREADS.
+ std::optional num_threads;
+ // Fixed-scale extra-bit quantization: faster, possibly less accurate. No effect on
+ // one-bit or raw storage.
+ bool fast_quantization = false;
+};
+
+// Settings of a graph index search (HnswIndex and SymqgIndex).
+struct GraphSearchOptions {
+ // Search breadth, raised to k. No value selects max(k, 64); 0 throws.
+ std::optional ef_search;
+ // Worker count; 0 selects every available CPU, capped by OMP_NUM_THREADS.
+ size_t num_threads = 1;
+};
+
template
struct AnnCandidate {
TP id = 0;
diff --git a/include/rabitqlib/third/hnswlib/hnswalg.h b/include/rabitqlib/third/hnswlib/hnswalg.h
index c8ff85d1..d6ccf26a 100644
--- a/include/rabitqlib/third/hnswlib/hnswalg.h
+++ b/include/rabitqlib/third/hnswlib/hnswalg.h
@@ -688,8 +688,14 @@ class HierarchicalNSW : public AlgorithmInterface {
if (!output.is_open())
throw std::runtime_error("Cannot open HNSW index file for writing");
output.exceptions(std::ios::failbit | std::ios::badbit);
- std::streampos position;
+ saveIndex(output);
+ output.close();
+ }
+
+ // RaBitQ: the stream overloads let an index embed the graph in a section of its own
+ // file. The bytes are those of the path overload, which delegates to them.
+ void saveIndex(std::ostream &output) {
writeBinaryPOD(output, offsetLevel0_);
writeBinaryPOD(output, max_elements_);
writeBinaryPOD(output, cur_element_count);
@@ -713,7 +719,6 @@ class HierarchicalNSW : public AlgorithmInterface {
if (linkListSize)
output.write(linkLists_[i], linkListSize);
}
- output.close();
}
@@ -723,11 +728,20 @@ class HierarchicalNSW : public AlgorithmInterface {
if (!input.is_open())
throw std::runtime_error("Cannot open file");
- clear();
// get file size:
input.seekg(0, input.end);
- std::streampos total_filesize = input.tellg();
+ const std::streamoff total_filesize = input.tellg();
input.seekg(0, input.beg);
+ loadIndex(input, static_cast(total_filesize), s, max_elements_i);
+ input.close();
+ }
+
+
+ // RaBitQ: read a graph of `total_bytes` bytes that starts at the current position.
+ void loadIndex(std::istream &input, size_t total_bytes, SpaceInterface *s, size_t max_elements_i = 0) {
+ clear();
+ const std::streampos begin = input.tellg();
+ const std::streampos end = begin + static_cast(total_bytes);
readBinaryPOD(input, offsetLevel0_);
readBinaryPOD(input, max_elements_);
@@ -758,7 +772,7 @@ class HierarchicalNSW : public AlgorithmInterface {
/// Optional - check if index is ok:
input.seekg(cur_element_count * size_data_per_element_, input.cur);
for (size_t i = 0; i < cur_element_count; i++) {
- if (input.tellg() < 0 || input.tellg() >= total_filesize) {
+ if (input.tellg() < begin || input.tellg() >= end) {
throw std::runtime_error("Index seems to be corrupted or unsupported");
}
@@ -770,13 +784,13 @@ class HierarchicalNSW : public AlgorithmInterface {
}
// throw exception if it either corrupted or old index
- if (input.tellg() != total_filesize)
+ if (input.tellg() != end)
throw std::runtime_error("Index seems to be corrupted or unsupported");
input.clear();
/// Optional check end
- input.seekg(pos, input.beg);
+ input.seekg(pos);
data_level0_memory_ = (char *) malloc(max_elements * size_data_per_element_);
if (data_level0_memory_ == nullptr)
@@ -819,10 +833,6 @@ class HierarchicalNSW : public AlgorithmInterface |