diff --git a/docs/docs/python_migration.md b/docs/docs/python_migration.md index 72c11840..b9ed55d3 100644 --- a/docs/docs/python_migration.md +++ b/docs/docs/python_migration.md @@ -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 diff --git a/docs/docs/quick_start.md b/docs/docs/quick_start.md index 83f55e68..35ca9f69 100644 --- a/docs/docs/quick_start.md +++ b/docs/docs/quick_start.md @@ -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. diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index f28c28f8..1da1577f 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -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: diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi index 6caf8071..370f424e 100644 --- a/python_bindings/__init__.pyi +++ b/python_bindings/__init__.pyi @@ -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"] @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 diff --git a/python_bindings/bindings_common.hpp b/python_bindings/bindings_common.hpp index 17592aaf..d17d98c0 100644 --- a/python_bindings/bindings_common.hpp +++ b/python_bindings/bindings_common.hpp @@ -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'"); @@ -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'"); diff --git a/python_bindings/hnsw_bindings.cpp b/python_bindings/hnsw_bindings.cpp index 6481e7a9..9b41b6d2 100644 --- a/python_bindings/hnsw_bindings.cpp +++ b/python_bindings/hnsw_bindings.cpp @@ -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 diff --git a/python_bindings/ivf_bindings.cpp b/python_bindings/ivf_bindings.cpp index 7531364f..2f95616c 100644 --- a/python_bindings/ivf_bindings.cpp +++ b/python_bindings/ivf_bindings.cpp @@ -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 diff --git a/python_bindings/quant.pyi b/python_bindings/quant.pyi index b50851b6..44e88e8e 100644 --- a/python_bindings/quant.pyi +++ b/python_bindings/quant.pyi @@ -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.""" diff --git a/python_bindings/quant_bindings.cpp b/python_bindings/quant_bindings.cpp index a364262c..b1b3a551 100644 --- a/python_bindings/quant_bindings.cpp +++ b/python_bindings/quant_bindings.cpp @@ -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. @@ -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. diff --git a/python_bindings/symqg_bindings.cpp b/python_bindings/symqg_bindings.cpp index 41bd368f..3ddd9244 100644 --- a/python_bindings/symqg_bindings.cpp +++ b/python_bindings/symqg_bindings.cpp @@ -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 diff --git a/sample/python/clustering_cli/ivf.py b/sample/python/clustering_cli/ivf.py index bd20f4b4..62f1aefc 100644 --- a/sample/python/clustering_cli/ivf.py +++ b/sample/python/clustering_cli/ivf.py @@ -17,7 +17,7 @@ nargs="?", default="l2", type=str.lower, - choices=["l2", "ip", "innerproduct"], + choices=["l2", "ip"], ) parser.add_argument( "--method", @@ -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__}") diff --git a/tests/python/test_examples.py b/tests/python/test_examples.py index 8ee1849b..f1931639 100644 --- a/tests/python/test_examples.py +++ b/tests/python/test_examples.py @@ -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" @@ -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) diff --git a/tests/python/test_index_repr.py b/tests/python/test_index_repr.py index 6d8af005..7118902b 100644 --- a/tests/python/test_index_repr.py +++ b/tests/python/test_index_repr.py @@ -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): diff --git a/tests/python/test_removed_forms.py b/tests/python/test_removed_forms.py index bf1d86d4..3501479f 100644 --- a/tests/python/test_removed_forms.py +++ b/tests/python/test_removed_forms.py @@ -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 @@ -18,6 +18,7 @@ RaBitQKMeans, RaBitQKMeansParameters, SymqgIndex, + quant, ) @@ -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" diff --git a/tests/python/typing/public_api.py b/tests/python/typing/public_api.py index cb4981ed..80a29039 100644 --- a/tests/python/typing/public_api.py +++ b/tests/python/typing/public_api.py @@ -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] @@ -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)