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
13 changes: 8 additions & 5 deletions docs/docs/index/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,14 @@ the index classes do not expose a rotator choice.
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.
Results equal those of a `metric="ip"` index built from the same vectors 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. Centroids
passed to `set_centroids` are used as given; `train`, and the first
`add` that trains, compute them from the scaled vectors with spherical k-means.
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
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

## Python changes

- New `metric="cosine"` for `IvfIndex`, `HnswIndex` and `SymqgIndex` (#212). The index scales data and queries to unit length and returns `1 - cos`; results equal those of a `metric="ip"` index built from the scaled vectors. 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).
- 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.
Expand Down
4 changes: 2 additions & 2 deletions docs/formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,9 @@ No bit is defined in version 2. Bits are assigned when a feature needs one. Exam

### 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, 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.
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 the index was given or trained them.
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

Expand Down
10 changes: 8 additions & 2 deletions include/rabitqlib/index/hnsw/hnsw.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,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);

Expand All @@ -135,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
Expand Down Expand Up @@ -228,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;

Expand All @@ -248,7 +254,7 @@ class HierarchicalNSW {
size_t base_layer_max_degree_{0};
size_t ef_construction_{0};
MetricType metric_type_{METRIC_L2}; // METRIC_IP for the cosine metric
bool cosine_{false}; // normalize data and queries; metric_type_ is METRIC_IP
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.
Expand Down
1 change: 1 addition & 0 deletions include/rabitqlib/index/hnsw_index.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ class HnswIndex {
* @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
*/
Expand Down
12 changes: 9 additions & 3 deletions include/rabitqlib/index/ivf/ivf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class IVF {
std::unique_ptr<Rotator<float>> rotator_;
std::vector<Cluster> clusters_;
MetricType metric_type_ = METRIC_L2; // METRIC_IP for the cosine metric
bool cosine_ = false; // normalize data and queries; metric_type_ is METRIC_IP
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;
Expand Down Expand Up @@ -163,6 +163,10 @@ class IVF {

[[nodiscard]] std::unique_ptr<Initializer> 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<size_t>& cluster_sizes);

Expand Down Expand Up @@ -299,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
Expand All @@ -311,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)
Expand Down
1 change: 1 addition & 0 deletions include/rabitqlib/index/ivf_index.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ class IvfIndex {
* @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
Expand Down
6 changes: 4 additions & 2 deletions python_bindings/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,8 @@ class IvfIndex:
----------
centroids : array_like of float, shape (num_clusters, dim)
Centroids in the original, unpadded coordinates. Converted to
contiguous float32; a copy may be made.
contiguous float32; a copy may be made. A cosine index scales them
to unit length, as it does data.
num_threads : int, optional
Keyword-only. Worker count for rotating the centroids and building the
centroid routing. None (default) and 0 select the available CPU count,
Expand Down Expand Up @@ -568,7 +569,8 @@ class HnswIndex:
----------
centroids : array_like of float, shape (num_clusters, dim)
Centroids in the original, unpadded coordinates. Converted to
contiguous float32; a copy may be made.
contiguous float32; a copy may be made. A cosine index scales them
to unit length, as it does data.

Notes
-----
Expand Down
3 changes: 2 additions & 1 deletion python_bindings/hnsw_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,8 @@ Parameters
----------
centroids : array_like of float, shape (num_clusters, dim)
Centroids in the original, unpadded coordinates. Converted to
contiguous float32; a copy may be made.
contiguous float32; a copy may be made. A cosine index scales them
to unit length, as it does data.

Notes
-----
Expand Down
3 changes: 2 additions & 1 deletion python_bindings/ivf_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,8 @@ Parameters
----------
centroids : array_like of float, shape (num_clusters, dim)
Centroids in the original, unpadded coordinates. Converted to
contiguous float32; a copy may be made.
contiguous float32; a copy may be made. A cosine index scales them
to unit length, as it does data.
num_threads : int, optional
Keyword-only. Worker count for rotating the centroids and building the
centroid routing. None (default) and 0 select the available CPU count,
Expand Down
17 changes: 16 additions & 1 deletion src/index/hnsw.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -753,9 +753,13 @@ void HierarchicalNSW::construct(
check_coordinates(data, num_points * dim_, dim_, "HNSW construction data");
check_coordinates(centroids, num_clusters * dim_, dim_, "HNSW construction centroids");
std::vector<float> normalized;
std::vector<float> scaled_centroids;
if (cosine_) {
normalized = index_detail::normalized_rows(data, num_points, dim_, num_threads);
data = normalized.data();
scaled_centroids =
index_detail::normalized_rows(centroids, num_clusters, dim_, num_threads);
centroids = scaled_centroids.data();
}

try {
Expand Down Expand Up @@ -815,6 +819,12 @@ void HierarchicalNSW::link_exact(
}

void HierarchicalNSW::set_centroids(size_t num_clusters, const float* centroids) {
set_centroids_impl(num_clusters, centroids, /*given=*/true);
}

void HierarchicalNSW::set_centroids_impl(
size_t num_clusters, const float* centroids, bool given
) {
if (level0_record_bytes_ == 0) {
throw std::logic_error("HNSW index must be initialized before setting centroids");
}
Expand All @@ -831,6 +841,11 @@ void HierarchicalNSW::set_centroids(size_t num_clusters, const float* centroids)
throw std::invalid_argument("HNSW centroids exceed addressable storage");
}
check_coordinates(centroids, num_clusters * dim_, dim_, "HNSW centroids");
std::vector<float> scaled;
if (cosine_ && given) {
scaled = index_detail::normalized_rows(centroids, num_clusters, dim_, 1);
centroids = scaled.data();
}

// construct rotates centroids the same way, so both paths quantize identically.
AlignedStorage rotated(
Expand Down Expand Up @@ -881,7 +896,7 @@ void HierarchicalNSW::train(
}
rabitqkmeans::RaBitQKMeans kmeans(dim_, num_clusters, cp);
kmeans.train_centroids(num_points, data);
set_centroids(num_clusters, kmeans.centroids.data());
set_centroids_impl(num_clusters, kmeans.centroids.data(), /*given=*/false);
}

template <class Distance>
Expand Down
15 changes: 14 additions & 1 deletion src/index/ivf.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,10 @@ std::unique_ptr<Initializer> IVF::make_initializer() const {
}

void IVF::set_centroids(const float* centroids, size_t num_threads) {
set_centroids_impl(centroids, num_threads, /*given=*/true);
}

void IVF::set_centroids_impl(const float* centroids, size_t num_threads, bool given) {
if (rotator_ == nullptr) {
throw std::logic_error("IVF must be configured before setting centroids");
}
Expand All @@ -290,6 +294,11 @@ void IVF::set_centroids(const float* centroids, size_t num_threads) {
throw std::invalid_argument("IVF centroids must not be null");
}
check_coordinates(centroids, num_clusters_ * dim_, dim_, "IVF centroids");
std::vector<float> scaled;
if (cosine_ && given) {
scaled = index_detail::normalized_rows(centroids, num_clusters_, dim_, num_threads);
centroids = scaled.data();
}

// construct rotates centroids the same way, so both paths route identically.
std::vector<float> rotated_centroids(num_clusters_ * padded_dim_);
Expand Down Expand Up @@ -369,7 +378,7 @@ void IVF::train(
kmeans.train_centroids(num_points, data);
centroids = std::move(kmeans.centroids);
}
set_centroids(centroids.data(), cp.num_threads);
set_centroids_impl(centroids.data(), cp.num_threads, /*given=*/false);
}

void IVF::construct(
Expand Down Expand Up @@ -400,9 +409,13 @@ void IVF::construct(
check_coordinates(data, max_elements_ * dim_, dim_, "IVF construction data");
check_coordinates(centroids, num_clusters_ * dim_, dim_, "IVF construction centroids");
std::vector<float> normalized;
std::vector<float> scaled_centroids;
if (cosine_) {
normalized = index_detail::normalized_rows(data, max_elements_, dim_, num_threads);
data = normalized.data();
scaled_centroids =
index_detail::normalized_rows(centroids, num_clusters_, dim_, num_threads);
centroids = scaled_centroids.data();
}

allocate_storage(cluster_sizes);
Expand Down
7 changes: 4 additions & 3 deletions tests/python/test_cosine.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,11 @@ def test_cosine_trained_or_given_centroids_match_inner_product(kind, setup, vect
cosine.train(data[:200], num_threads=1)
ip.train(normalized(data[:200]), num_threads=1)
else:
# Centroids are used as given.
centroids = normalized(data[:4])
# Given centroids are scaled to unit length, as the data is, so centroids far
# from the unit sphere match their scaled copies.
centroids = data[:4] * np.float32(50)
cosine.set_centroids(centroids)
ip.set_centroids(centroids)
ip.set_centroids(normalized(centroids))
cosine.add(data, num_threads=1)
ip.add(normalized(data), num_threads=1)
ids, distances = cosine.search(queries, 10)
Expand Down
45 changes: 37 additions & 8 deletions tests/unit/rabitqlib/index/hnsw_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1203,17 +1203,46 @@ TEST(HnswCosineTest, MatchesInnerProductOverNormalizedVectors) {
);
}

// construct normalizes its data too; the centroids are used as given.
std::vector<PID> cosine_ids(kCount, 0);
std::vector<PID> ip_ids(kCount, 0);
const std::vector<float> centroids(unit_points.begin(), unit_points.begin() + kDim);
// construct and set_centroids scale given centroids to unit length, as the data is,
// so centroids far from the unit sphere match their scaled copies.
std::vector<float> centroids(points.begin(), points.begin() + (kClusters * kDim));
for (auto& value : centroids) {
value *= 100.0F; // like cluster means of unscaled data
}
const auto unit_centroids = rabitq_test::normalized_rows(centroids, kDim);
std::vector<PID> cosine_ids(kCount);
for (size_t i = 0; i < kCount; ++i) {
cosine_ids[i] = static_cast<PID>(i % kClusters);
}
std::vector<PID> ip_ids = cosine_ids;
HierarchicalNSW cosine(kCount, kDim, 5, 8, 50, 7, METRIC_COSINE);
cosine.construct(1, centroids.data(), kCount, points.data(), cosine_ids.data(), 1);
cosine.construct(
kClusters, centroids.data(), kCount, points.data(), cosine_ids.data(), 1
);
HierarchicalNSW ip(kCount, kDim, 5, 8, 50, 7, METRIC_IP);
ip.construct(1, centroids.data(), kCount, unit_points.data(), ip_ids.data(), 1);
ip.construct(
kClusters, unit_centroids.data(), kCount, unit_points.data(), ip_ids.data(), 1
);
const auto expected = ip.search(unit_queries.data(), kQueries, 10, 64, 1);
EXPECT_EQ(cosine.search(queries.data(), kQueries, 10, 64, 1), expected);

HierarchicalNSW given(kCount, kDim, 5, 8, 50, 7, METRIC_COSINE);
given.set_centroids(kClusters, centroids.data());
given.add(points.data(), kCount, cosine_ids.data(), false, 1);
HierarchicalNSW given_ip(kCount, kDim, 5, 8, 50, 7, METRIC_IP);
given_ip.set_centroids(kClusters, unit_centroids.data());
given_ip.add(unit_points.data(), kCount, ip_ids.data(), false, 1);
given.save(cosine_file.path().c_str());
given_ip.save(ip_file.path().c_str());
rabitq_test::expect_same_sections_except_metric(
cosine_file.path(),
ip_file.path(),
rabitq_test::format2::IndexKind::Hnsw,
rabitq_test::kHnswSections
);
EXPECT_EQ(
cosine.search(queries.data(), kQueries, 10, 64, 1),
ip.search(unit_queries.data(), kQueries, 10, 64, 1)
given.search(queries.data(), kQueries, 10, 64, 1),
given_ip.search(unit_queries.data(), kQueries, 10, 64, 1)
);
}

Expand Down
Loading
Loading