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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .clang-tidy
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ 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
Expand Down
17 changes: 9 additions & 8 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ 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, add options 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/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 |
Expand Down Expand Up @@ -575,18 +576,18 @@ Shared NumPy and string conversion helpers live in `python_bindings/bindings_com
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. A binding over a class that implements the Python workflow in C++, such as
`IvfIndex`, leaves the state checks and the removal-ID and `reserve_cluster` cluster-ID ranges
to that class. 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`.
`IvfIndex` or `HnswIndex`, 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, and in `copied_ids` for an aligned `Id` copy
whose range the index checks. 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.

Expand Down
13 changes: 10 additions & 3 deletions docs/docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@
- 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 existing C++ index classes keep 32-bit `PID` values with `kPidMax` for a missing result; the new C++ `IvfIndex` uses 64-bit IDs, as Python does.
- IDs remain the row numbers the index assigns. The existing C++ index classes keep 32-bit `PID` values with `kPidMax` for a missing result; the new C++ `IvfIndex` and `HnswIndex` use 64-bit IDs, as Python does.

- An `IvfIndex` 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`.
- An `IvfIndex` or `HnswIndex` 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`. `HnswIndex()` with an invalid `metric` or `seed` and an out-of-range `num_clusters` now reports the metric or seed.

- 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.
Expand All @@ -73,7 +73,14 @@
- `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`.
- `ivf::IVF` is unchanged.
- 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<uint64_t>`, because a file written by `hnsw::HierarchicalNSW` may record a seed above 32 bits.
- `ivf::IVF` and `hnsw::HierarchicalNSW` are unchanged.

- `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`.
Expand Down
196 changes: 196 additions & 0 deletions include/rabitqlib/index/hnsw_index.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
#pragma once

#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>

#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<uint32_t> 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. An empty, untrained file saved by 0.7 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<size_t> 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.
*
* @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.
*
* @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<uint64_t> 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<hnsw::HierarchicalNSW> index,
std::unique_ptr<rabitqkmeans::RaBitQKMeansParameters> cp,
size_t num_clusters
);

void check_trained(const char* operation) const;
void check_trainable() const;

std::unique_ptr<hnsw::HierarchicalNSW> index_;
std::unique_ptr<rabitqkmeans::RaBitQKMeansParameters> cp_;
size_t num_clusters_; // centroid count train and set_centroids expect when untrained
};

} // namespace rabitqlib
13 changes: 11 additions & 2 deletions include/rabitqlib/index/types.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ namespace rabitqlib {
using PID = uint32_t;
inline constexpr PID kPidMax = 0xFFFFFFFF;

// A point ID at the IvfIndex API: the row number the index assigned to the point.
// A point ID at the IvfIndex and HnswIndex 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.
// 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.
Expand All @@ -27,6 +28,14 @@ struct AddOptions {
bool fast_quantization = false;
};

// Settings of a graph index search (HnswIndex).
struct GraphSearchOptions {
// Search breadth, raised to k. No value selects max(k, 64); 0 throws.
std::optional<size_t> ef_search;
// Worker count; 0 selects every available CPU, capped by OMP_NUM_THREADS.
size_t num_threads = 1;
};

template <typename T, typename TP = PID>
struct AnnCandidate {
TP id = 0;
Expand Down
20 changes: 0 additions & 20 deletions python_bindings/bindings_common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -460,26 +460,6 @@ ensure_1d_integer_array(py::handle value, const char* name) {
return ensure_1d_array<int64_t>(value, name);
}

// The caller has already validated rank/dtype. Removed points still occupy IDs.
inline std::vector<PID> checked_removal_ids(
const py::array_t<int64_t, py::array::c_style | py::array::forcecast>& ids,
size_t num_stored_points
) {
std::vector<PID> result;
result.reserve(static_cast<size_t>(ids.shape(0)));
const detail::ConstPackedArrayView<int64_t> values(
reinterpret_cast<const char*>(ids.data())
);
for (py::ssize_t i = 0; i < ids.shape(0); ++i) {
const int64_t id = values[static_cast<size_t>(i)];
if (id < 0 || static_cast<uint64_t>(id) >= num_stored_points) {
throw std::invalid_argument("ids must be in [0, num_stored_points)");
}
result.push_back(static_cast<PID>(id));
}
return result;
}

// An aligned copy of IDs whose rank and dtype the caller has validated; the index checks
// their range.
inline std::vector<Id> copied_ids(
Expand Down
Loading
Loading