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
8 changes: 5 additions & 3 deletions docs/docs/python_migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,14 @@ In C++, `QGKMeansParameters` takes the same three field renames in 0.9, without
transition release, and `FinalAssignmentMode::SymphonyQG` and the two statistics
aliases are removed; see the [0.9 notes](releases/unreleased.md#c-changes).

Three of these changes come without a warning in 0.9. `HnswIndex()` without `seed=` draws a seed,
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=` for `HnswIndex` and `routing=` for `IvfIndex` where it prints `max_elements=`
and `initializer=`, and no longer prints `max_elements=` for `IvfIndex`. And
`cp.final_assignment` reads back as a string, as described above.
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
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/quick_start.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ number of points, after removals, or when the probed IVF-RaBitQ clusters contain
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"`, `"ip"` (also `"innerproduct"`) and `"cosine"`.
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.

Expand Down
1 change: 1 addition & 0 deletions docs/docs/releases/unreleased.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
- `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:
Expand Down
14 changes: 7 additions & 7 deletions python_bindings/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ __all__ = [

_Path: TypeAlias = str | bytes | bytearray | PathLike[str] | PathLike[bytes]

_Metric: TypeAlias = Literal["l2", "ip", "innerproduct", "cosine"]
_Metric: TypeAlias = Literal["l2", "ip", "cosine"]
_Routing: TypeAlias = Literal["auto", "flat", "flat_rabitq", "hnsw"]
_QGInit: TypeAlias = Literal["pipnn", "random"]
_FinalAssignment: TypeAlias = Literal["approximate", "exact"]
Expand Down Expand Up @@ -64,7 +64,7 @@ class IvfIndex:
nbits : int, optional
Keyword-only. Total quantization bits, 1 through 9, or 32 for owned
float32 vectors with one-bit filtering and raw reranking. Default is 7.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine'
scales data and queries to unit length.
routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
Expand Down Expand Up @@ -115,7 +115,7 @@ class IvfIndex:
nbits : int, optional
Keyword-only. Total quantization bits, 1 through 9, or 32 for owned
float32 vectors with one-bit filtering and raw reranking. Default is 7.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine'
scales data and queries to unit length.
routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
Expand Down Expand Up @@ -403,7 +403,7 @@ class HnswIndex:
2 * M edges. Default is 16.
ef_construction : int, optional
Keyword-only. Construction search breadth. Default is 200.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'l2'. 'cosine' scales data and queries to unit length.
seed : int, optional
Expand Down Expand Up @@ -463,7 +463,7 @@ class HnswIndex:
2 * M edges. Default is 16.
ef_construction : int, optional
Keyword-only. Construction search breadth. Default is 200.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'l2'. 'cosine' scales data and queries to unit length.
seed : int, optional
Expand Down Expand Up @@ -745,7 +745,7 @@ class SymqgIndex:
Default is 200.
init : {'pipnn', 'random'}, optional
Keyword-only. Graph initialization method. Default is 'pipnn'.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'l2'. 'cosine' scales data and queries to unit length.
seed : int, optional
Expand Down Expand Up @@ -802,7 +802,7 @@ class SymqgIndex:
Default is 200.
init : {'pipnn', 'random'}, optional
Keyword-only. Graph initialization method. Default is 'pipnn'.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'l2'. 'cosine' scales data and queries to unit length.
seed : int, optional
Expand Down
4 changes: 2 additions & 2 deletions python_bindings/bindings_common.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ inline MetricType metric_from_string(const std::string& metric) {
if (metric == "l2") {
return METRIC_L2;
}
if (metric == "ip" || metric == "innerproduct") {
if (metric == "ip") {
return METRIC_IP;
}
throw std::invalid_argument("metric must be 'l2' or 'ip'");
Expand All @@ -216,7 +216,7 @@ inline MetricType index_metric_from_string(const std::string& metric) {
if (metric == "cosine") {
return METRIC_COSINE;
}
if (metric == "l2" || metric == "ip" || metric == "innerproduct") {
if (metric == "l2" || metric == "ip") {
return metric_from_string(metric);
}
throw std::invalid_argument("metric must be 'l2', 'ip' or 'cosine'");
Expand Down
2 changes: 1 addition & 1 deletion python_bindings/hnsw_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ M : int, optional
2 * M edges. Default is 16.
ef_construction : int, optional
Keyword-only. Construction search breadth. Default is 200.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'l2'. 'cosine' scales data and queries to unit length.
seed : int, optional
Expand Down
2 changes: 1 addition & 1 deletion python_bindings/ivf_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ num_clusters : int
nbits : int, optional
Keyword-only. Total quantization bits, 1 through 9, or 32 for owned
float32 vectors with one-bit filtering and raw reranking. Default is 7.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Squared L2, inner-product or cosine distance. Default is 'l2'. 'cosine'
scales data and queries to unit length.
routing : {'auto', 'flat', 'flat_rabitq', 'hnsw'}, optional
Expand Down
2 changes: 1 addition & 1 deletion python_bindings/quant.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class Rotator:
def __deepcopy__(self, memo: Any) -> Rotator:
"""Return self; rotators are immutable."""

_Metric = Literal["l2", "ip", "innerproduct"]
_Metric = Literal["l2", "ip"]

class Query:
"""A rotated, padded query for scoring codes in the working space."""
Expand Down
4 changes: 2 additions & 2 deletions python_bindings/quant_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2164,7 +2164,7 @@ Parameters
----------
rotated_query : array_like of float32, shape (d,)
A rotated, padded query; d is a positive multiple of 32.
metric : {'l2', 'ip', 'innerproduct'}
metric : {'l2', 'ip'}
The metric the factors were computed for.
centroid : array_like of float32, shape (d,), optional
The working-space centroid the factors were computed with; None is zero.
Expand Down Expand Up @@ -2251,7 +2251,7 @@ Parameters
----------
rotated_query : array_like of float32, shape (d,)
A rotated, padded query; d is a positive multiple of 32.
metric : {'l2', 'ip', 'innerproduct'}
metric : {'l2', 'ip'}
The metric the factors were computed for.
centroid : array_like of float32, shape (d,), optional
The working-space centroid the factors were computed with; None is zero.
Expand Down
2 changes: 1 addition & 1 deletion python_bindings/symqg_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ ef_construction : int, optional
Default is 200.
init : {'pipnn', 'random'}, optional
Keyword-only. Graph initialization method. Default is 'pipnn'.
metric : {'l2', 'ip', 'innerproduct', 'cosine'}, optional
metric : {'l2', 'ip', 'cosine'}, optional
Keyword-only. Squared L2, inner-product or cosine distance. Default is
'l2'. 'cosine' scales data and queries to unit length.
seed : int, optional
Expand Down
4 changes: 2 additions & 2 deletions sample/python/clustering_cli/ivf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
nargs="?",
default="l2",
type=str.lower,
choices=["l2", "ip", "innerproduct"],
choices=["l2", "ip"],
)
parser.add_argument(
"--method",
Expand All @@ -30,7 +30,7 @@
K = args.num_clusters
centroids_path = args.centroids_path
cluster_id_path = args.cluster_id_path
metric = "l2" if args.metric == "l2" else "ip"
metric = args.metric
clustering_type = RaBitQKMeans if args.method == "rabitq" else QGKMeans
print(f"Using {metric.upper()} metric with {clustering_type.__name__}")

Expand Down
4 changes: 2 additions & 2 deletions tests/python/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ def check_exact_cluster_labels(data, centroids, labels, metric):
np.testing.assert_array_equal(labels, np.argmin(distances, axis=1))


@pytest.mark.parametrize("argument", [None, "l2", "ip", "innerproduct"])
@pytest.mark.parametrize("argument", [None, "l2", "ip"])
def test_legacy_clustering_formats_without_faiss(tmp_path, example_data, argument):
data_path, data = example_data
centroids_path = tmp_path / "centroids.fvecs"
Expand All @@ -349,7 +349,7 @@ def test_legacy_clustering_formats_without_faiss(tmp_path, example_data, argumen
labels = label_words[:, 1]
assert np.isfinite(centroids).all()
assert ((0 <= labels) & (labels < 16)).all()
metric = "ip" if argument in ("ip", "innerproduct") else "l2"
metric = argument or "l2"
check_exact_cluster_labels(data, centroids, labels, metric)


Expand Down
8 changes: 3 additions & 5 deletions tests/python/test_index_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,13 @@ def vectors():

def unbuilt_index(kind, bits):
if kind == "ivf":
return IvfIndex(64, 1, nbits=bits, metric="innerproduct")
return IvfIndex(64, 1, nbits=bits, metric="ip")
if kind == "hnsw":
index = HnswIndex(64, nbits=bits, num_clusters=1, metric="innerproduct")
index = HnswIndex(64, nbits=bits, num_clusters=1, metric="ip")
# Keep capacity distinct from the 80 stored points.
index.reserve(96)
return index
return SymqgIndex(
64, max_degree=32, ef_construction=40, metric="innerproduct", nbits=bits
)
return SymqgIndex(64, max_degree=32, ef_construction=40, metric="ip", nbits=bits)


def build_index(index, vectors):
Expand Down
29 changes: 27 additions & 2 deletions tests/python/test_removed_forms.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""The call forms that 0.9 removed fail plainly; none is read as something else.

Covers the 0.7 forms (issue #213), the 0.8 index spellings (#232) and the 0.8
k-means spellings (#233).
Covers the 0.7 forms (issue #213), the 0.8 index spellings (#232), including the
"innerproduct" metric spelling, and the 0.8 k-means spellings (#233).
"""

import pickle
Expand All @@ -18,6 +18,7 @@
RaBitQKMeans,
RaBitQKMeansParameters,
SymqgIndex,
quant,
)


Expand Down Expand Up @@ -307,3 +308,27 @@ def test_kmeans_iteration_stats_is_one_class(base_data):
# Pickle and pydoc find the class by this name in its module.
assert stats.__module__ == "rabitqlib._rabitqlib"
assert pickle.loads(pickle.dumps(stats)) is stats


def test_innerproduct_is_no_longer_a_metric_name():
# The inner-product metric is spelled "ip" only, as index.metric reports it.
index_message = r"^metric must be 'l2', 'ip' or 'cosine'$"
for make in (
lambda: IvfIndex(DIM, 8, metric="innerproduct"),
lambda: HnswIndex(DIM, metric="innerproduct"),
lambda: SymqgIndex(DIM, metric="innerproduct"),
):
with pytest.raises(ValueError, match=index_message):
make()
query = np.zeros(DIM, dtype=np.float32)
codes = np.zeros((0, DIM), dtype=np.uint8)
for call in (
lambda: quant.Query(query, metric="innerproduct"),
lambda: quant.query_terms(query, metric="innerproduct"),
lambda: quant.code_factors(
codes.astype(np.float32), codes, nbits=4, metric="innerproduct"
),
):
with pytest.raises(ValueError, match=r"^metric must be 'l2' or 'ip'$"):
call()
assert IvfIndex(DIM, 8, metric="ip").metric == "ip"
8 changes: 2 additions & 6 deletions tests/python/typing/public_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def reject_removed_forms(
IvfIndex(64, 80, 1, 4) # type: ignore[arg-type, call-arg]
IvfIndex(dim=64, max_elements=80, num_clusters=1, nbits=4) # type: ignore[call-arg]
IvfIndex(64, 1, initializer="flat") # type: ignore[call-arg]
IvfIndex(64, 1, metric="innerproduct") # type: ignore[arg-type]
HnswIndex(64, 80) # type: ignore[call-arg]
HnswIndex(64, max_elements=80) # type: ignore[call-arg]
HnswIndex(64, random_seed=5) # type: ignore[call-arg]
Expand Down Expand Up @@ -234,12 +235,7 @@ def check_input_contracts() -> None:
centroids = x.mean(axis=0, keepdims=True)
signed = np.zeros(80, dtype=np.int64)
unsigned = np.zeros(80, dtype=np.uint32)
metrics: tuple[Literal["l2", "ip", "innerproduct", "cosine"], ...] = (
"l2",
"ip",
"innerproduct",
"cosine",
)
metrics: tuple[Literal["l2", "ip", "cosine"], ...] = ("l2", "ip", "cosine")
for metric in metrics:
ivf = IvfIndex(64, 1, nbits=4, metric=metric)
HnswIndex(64, nbits=4, metric=metric)
Expand Down
Loading