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
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ if(RABITQ_BUILD_INDEX)
src/index/format2.cpp
src/index/hnsw.cpp
src/index/ivf.cpp
src/index/ivf_index.cpp
src/index/ivf_initializer.cpp
src/index/ivf_search.cpp
src/index/qg.cpp
Expand Down
16 changes: 13 additions & 3 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ 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 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/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 @@ -573,13 +574,19 @@ a new format, freeze the last files of the old writer as release-produced fixtur
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`, 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`.
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
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
dereferencing a possibly misaligned typed pointer. Removal IDs are checked against
stored count, including removed records, rather than live count.

Expand All @@ -590,6 +597,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.

Expand Down
13 changes: 12 additions & 1 deletion docs/docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,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, and C++ point IDs remain 32-bit `PID` values with `kPidMax` for a missing result.
- 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.

- 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`.

- 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 @@ -62,6 +64,15 @@

## 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`.
- `ivf::IVF` is 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`.
- `FinalAssignmentMode::SymphonyQG`, an alias of `Approximate`, is removed.
Expand Down
2 changes: 2 additions & 0 deletions include/rabitqlib/index/ivf/types.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
195 changes: 195 additions & 0 deletions include/rabitqlib/index/ivf_index.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
#pragma once

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

#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<uint32_t> 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<size_t> 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<bool> 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<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
* @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<uint32_t> 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<ivf::IVF> index,
std::unique_ptr<rabitqkmeans::RaBitQKMeansParameters> cp
);

void check_trained(const char* operation) const;
void check_trainable() const;
[[nodiscard]] rabitqkmeans::RaBitQKMeansParameters training_parameters(
std::optional<size_t> num_threads
) const;

std::unique_ptr<ivf::IVF> index_;
std::unique_ptr<rabitqkmeans::RaBitQKMeansParameters> cp_;
};

} // namespace rabitqlib
20 changes: 20 additions & 0 deletions include/rabitqlib/index/types.hpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,32 @@
#pragma once

#include <cstddef>
#include <cstdint>
#include <limits>
#include <optional>

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.
using Id = int64_t;
// A search result slot without a point.
inline constexpr Id kNoId = -1;

// Settings of IvfIndex::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<size_t> num_threads;
// Fixed-scale extra-bit quantization: faster, possibly less accurate. No effect on
// one-bit or raw storage.
bool fast_quantization = false;
};

template <typename T, typename TP = PID>
struct AnnCandidate {
TP id = 0;
Expand Down
15 changes: 15 additions & 0 deletions python_bindings/bindings_common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,21 @@ inline std::vector<PID> checked_removal_ids(
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(
const py::array_t<int64_t, py::array::c_style | py::array::forcecast>& ids
) {
std::vector<Id> result(static_cast<size_t>(ids.shape(0)));
const detail::ConstPackedArrayView<int64_t> values(
reinterpret_cast<const char*>(ids.data())
);
for (size_t i = 0; i < result.size(); ++i) {
result[i] = values[i];
}
return result;
}

// Validate before narrowing, and own the result for APIs that mutate assignments.
inline std::vector<PID> checked_cluster_ids(
py::handle value, size_t rows, size_t clusters
Expand Down
Loading
Loading