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 @@ -257,6 +257,7 @@ if(RABITQ_BUILD_INDEX)
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
Expand Down
10 changes: 6 additions & 4 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ factors estimate L2 distance or inner product.
| `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<float>` 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 |
Expand Down Expand Up @@ -576,10 +577,11 @@ 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` 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`.
`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.

Expand Down
13 changes: 9 additions & 4 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` and `HnswIndex` use 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`, `HnswIndex` and `SymqgIndex` use 64-bit IDs, as Python does.

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

- 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 Down Expand Up @@ -80,7 +80,12 @@
- `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.
- 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.
- `ivf::IVF`, `hnsw::HierarchicalNSW`, `symqg::QuantizedGraph` and `symqg::QGBuilder` are otherwise 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 All @@ -98,5 +103,5 @@
- `IVF::seed()`;
- `HierarchicalNSW::seed()`;
- `QuantizedGraph<float>::seed()`, `ef_construction()` and `initialization()`.
- `symqg::QGInitialization` moves from `qg_builder.hpp` to `qg.hpp`, which `qg_builder.hpp` includes.
- `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.
4 changes: 1 addition & 3 deletions include/rabitqlib/index/symqg/qg.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#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"
Expand All @@ -28,9 +29,6 @@ class SearchBuffer;

namespace rabitqlib::symqg {

// How a builder initializes the graph before refinement.
enum class QGInitialization { PiPNN, Random };

class QuantizedQuery {
private:
const float* rotated_query_;
Expand Down
6 changes: 6 additions & 0 deletions include/rabitqlib/index/symqg/types.hpp
Original file line number Diff line number Diff line change
@@ -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
140 changes: 140 additions & 0 deletions include/rabitqlib/index/symqg_index.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
#pragma once

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

#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 <typename T>
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<uint32_t> 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<size_t> ef_construction() const;
[[nodiscard]] std::optional<symqg::QGInitialization> init() const;
[[nodiscard]] std::optional<uint32_t> 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<symqg::QuantizedGraph<float>> 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<size_t> ef_construction_;
std::optional<symqg::QGInitialization> init_;
std::optional<uint32_t> seed_;
std::unique_ptr<symqg::QuantizedGraph<float>> graph_; // null until add or load
};

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

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

// Settings of a graph index search (HnswIndex).
// 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<size_t> ef_search;
Expand Down
37 changes: 0 additions & 37 deletions python_bindings/bindings_common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -385,30 +385,6 @@ RowView<T> checked_output_rows(
return make_row_view<T>(std::move(array));
}

// Point IDs as Python sees them: int64, with -1 where the index reports kPidMax.
inline py::array_t<int64_t> python_ids(const PID* ids, std::vector<py::ssize_t> shape) {
py::array_t<int64_t> result(std::move(shape));
int64_t* out = result.mutable_data();
for (py::ssize_t i = 0; i < result.size(); ++i) {
out[i] = ids[i] == kPidMax ? int64_t{-1} : static_cast<int64_t>(ids[i]);
}
return result;
}

// (num_queries, k) outputs. The index writes row numbers into ids; slots without a
// neighbor keep kPidMax and +inf. Searches pad slots without a result, so k may exceed
// the number of points.
struct SearchResults {
std::vector<py::ssize_t> shape;
std::vector<PID> ids;
py::array_t<float> distances;

// (ids, distances) for Python, with int64 IDs and -1 for a missing neighbor.
[[nodiscard]] py::tuple to_python() const {
return py::make_tuple(python_ids(ids.data(), shape), distances);
}
};

inline void check_k(size_t k) {
if (k == 0 || k > buffer::kSearchBufferMaxPointCount) {
throw std::invalid_argument("k must be between 1 and 2**31");
Expand All @@ -424,19 +400,6 @@ inline void check_ef_search(std::optional<size_t> ef_search) {
}
}

inline SearchResults unfilled_search_results(size_t num_queries, size_t k) {
const auto shape = std::vector<py::ssize_t>{
static_cast<py::ssize_t>(num_queries), static_cast<py::ssize_t>(k)};
SearchResults results{
shape, std::vector<PID>(num_queries * k, kPidMax), py::array_t<float>(shape)};
std::fill(
results.distances.mutable_data(),
results.distances.mutable_data() + results.distances.size(),
std::numeric_limits<float>::infinity()
);
return results;
}

// Like ensure_1d_array<int64_t>, but refuses input whose dtype is not an integer. forcecast
// would otherwise truncate floats and turn booleans or numeric strings into ids, and
// callers use these ids to remove points permanently. An empty sequence has no dtype to
Expand Down
Loading
Loading