diff --git a/benchmarks/run.py b/benchmarks/run.py index 2ba302cd..d7565be5 100644 --- a/benchmarks/run.py +++ b/benchmarks/run.py @@ -141,7 +141,7 @@ def build_index(cfg, base, path): "assignment": "add routing", } elif method == "rabitq-hnsw": - from rabitqlib import FinalAssignmentMode, HnswIndex, RaBitQKMeans + from rabitqlib import HnswIndex, RaBitQKMeans cluster_count = cfg["hnsw_clusters"] kmeans = RaBitQKMeans( @@ -152,7 +152,7 @@ def build_index(cfg, base, path): spherical=cfg["metric"] == "ip", seed=42, min_points_per_centroid=1, - final_assignment=FinalAssignmentMode.Exact, + final_assignment="exact", ) stage_start = time.perf_counter() kmeans.train(base) diff --git a/benchmarks/run_kmeans.py b/benchmarks/run_kmeans.py index f956f7f6..3a3c775d 100644 --- a/benchmarks/run_kmeans.py +++ b/benchmarks/run_kmeans.py @@ -64,7 +64,7 @@ def load_base(cfg): def train_python(method, x, k, threads, seed): if method == "qgkmeans": - from rabitqlib import FinalAssignmentMode, QGKMeans + from rabitqlib import QGKMeans start = time.perf_counter() model = QGKMeans( @@ -74,13 +74,13 @@ def train_python(method, x, k, threads, seed): num_threads=threads, seed=seed, spherical=False, - quantization_bits=0, - graph_degree=32, - ef_build=240, + nbits=32, + max_degree=32, + ef_construction=240, ef_search=16, graph_build_iterations=1, early_stop_threshold=0.0, - final_assignment=FinalAssignmentMode.Exact, + final_assignment="exact", ) model.train(x) total = time.perf_counter() - start diff --git a/docs/development.md b/docs/development.md index 9b516649..7bf6b9c2 100644 --- a/docs/development.md +++ b/docs/development.md @@ -695,7 +695,10 @@ Public names and Python keywords are compatibility contracts. For example, `degree_bound()`/`set_ef()` and `QGKMeansParameters::ef_build` retain their existing spellings, as do the Python vocabulary `random_seed`/`seed`, `train`/`build`, `obj`, `nsplit`, `final_obj` and `niter`. Python's search breadth is -`ef_search` since 0.8.5; `ef` is deprecated and removed in 0.9 (#232). C++ parameter names may be clarified without +`ef_search` since 0.8.5; `ef` is deprecated and removed in 0.9 (#232). Python's `QGKMeans` +and `QGKMeansParameters` take `nbits`, `max_degree` and `ef_construction` since 0.8.5; +`quantization_bits`, `graph_degree` and `ef_build` are deprecated there and removed in +0.9 (#233), while the C++ struct keeps them until 0.9. C++ parameter names may be clarified without changing types, order or defaults. Keep declarations, definitions and comments in agreement; do not rename methods or literals by textual substitution. diff --git a/docs/docs/benchmarks/kmeans.md b/docs/docs/benchmarks/kmeans.md index 189e4340..0afd9bad 100644 --- a/docs/docs/benchmarks/kmeans.md +++ b/docs/docs/benchmarks/kmeans.md @@ -49,7 +49,7 @@ search. Centroids are not normalized. | Method | Additional settings | | --- | --- | -| `rabitqlib.QGKMeans` | `quantization_bits=0`, degree 32, `ef_build=240`, `ef_search=16`, one graph refinement, `early_stop_threshold=0`, `FinalAssignmentMode.Exact` | +| `rabitqlib.QGKMeans` | raw centroid storage (`nbits=32`; `quantization_bits=0` before 0.8.5), degree 32, `ef_construction=240` (`ef_build` before 0.8.5), `ef_search=16`, one graph refinement, `early_stop_threshold=0`, exact final assignment | | `faiss.Kmeans` | CPU, `nredo=1`, `max_points_per_centroid=N`, `spherical=False`, `early_stop_threshold=0`; exact final `index.search(x, 1)` | | `superkmeans.SuperKMeans` | v0.2.0, `quantizer="f32"`, `hierarchical=False`, `sampling_fraction=1`, `angular=False`, `use_blas_only=False`, `early_termination=True`, `tol=1e-4`; exact final `assign(x, centroids)` | diff --git a/docs/docs/clustering.md b/docs/docs/clustering.md index 9c7b162e..26f85ec7 100644 --- a/docs/docs/clustering.md +++ b/docs/docs/clustering.md @@ -20,7 +20,7 @@ per centroid; the classes below default to training on every vector. | Class | Assignment | Recommended use | Cluster count | | --- | --- | --- | --- | | [RaBitQKMeans](#rabitqkmeans) | Flat RaBitQ scan | Small cluster counts | `n >= k >= 1` | -| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > graph_degree` (default 32) | +| [QGKMeans](#qgkmeans) | SymphonyQG centroid graph | Larger cluster counts | `n >= k > max_degree` (C++ `graph_degree`; default 32) | ## Python @@ -101,7 +101,7 @@ Set Python keyword arguments or fields of the corresponding C++ parameter type: | `min_points_per_centroid` | `39` | Warn below this training-points-per-centroid ratio when verbose. | | `max_points_per_centroid` | `0` | When positive, train on a random sample above `k * max_points_per_centroid` vectors; `0` trains on all vectors. See [sampling](#training-set-sampling). | | `verbose` | `false` | Print training progress and warnings. | -| `final_assignment` | `Approximate` | Use the selected method for final labels, or `Exact` for nearest-centroid labels. | +| `final_assignment` | `'approximate'` (C++ `Approximate`) | Use the selected method for final labels, or `'exact'` (C++ `Exact`) for nearest-centroid labels. | `num_threads` sets an upper limit, not a fixed worker count for every stage. QGKMeans may use fewer workers to build small centroid graphs. That additional @@ -164,18 +164,21 @@ encodes new vectors around it. Each iteration compares every training point with every centroid. The batch size of 32 is not a cluster-count limit. This method uses one-bit point codes throughout; -it has no graph parameters or `quantization_bits` setting. +it has no graph parameters or `nbits` (C++ `quantization_bits`) setting. ### QGKMeans QGKMeans builds a SymphonyQG graph over the centroids and uses previous -assignments as search hints. Its additional parameters are: +assignments as search hints. Its additional parameters are below, under their Python +names since 0.8.5. C++ and Python before 0.8.5 name the first three +`quantization_bits` (with `0` for raw storage), `graph_degree` and `ef_build`; in +Python those names still work, with a `DeprecationWarning`, until 0.9. | Parameter | Default | Meaning | | --- | --- | --- | -| `quantization_bits` | `0` | Graph centroid storage: raw, or `4`/`8` bits. | -| `graph_degree` | `32` | A positive multiple of 32, strictly smaller than `k`. | -| `ef_build`, `ef_search` | `240`, `16` | Positive graph construction and search window sizes. | +| `nbits` | `32` | Graph centroid storage: `32` for raw vectors, or `4`/`8` bits. | +| `max_degree` | `32` | A positive multiple of 32, strictly smaller than `k`. | +| `ef_construction`, `ef_search` | `240`, `16` | Positive graph construction and search window sizes. | | `graph_build_iterations` | `1` | PiPNN initialization followed by one refinement; values ≥2 request that many graph passes, ending in refinement. Independent of `niter`. | The seed also controls fallback neighbors; PiPNN uses fixed internal seeds. @@ -194,9 +197,8 @@ their sum (WCSS); spherical mode sums `1 - inner_product`. `obj` and `iteration_stats` record objectives before each centroid update; Python `train()` returns the last such objective. -`FinalAssignmentMode.Approximate` (default) uses the selected class's assignment -algorithm. The legacy name `FinalAssignmentMode.SymphonyQG` remains an alias for -`Approximate`. Labels need not identify the exact nearest centroids, but reported +`final_assignment='approximate'` (default) uses the selected class's assignment +algorithm. Labels need not identify the exact nearest centroids, but reported distances and WCSS remain exact for those labels. Without sampling, quantized QGKMeans final assignment retains a point's last-iteration label when it is closer. After sampling, most points have no such label, so every point uses the @@ -205,12 +207,17 @@ same graph search. Approximate training objectives need not decrease monotonical To require exact nearest-centroid **final** assignments with either class: ```python -from rabitqlib import FinalAssignmentMode, RaBitQKMeans +from rabitqlib import RaBitQKMeans -kmeans = RaBitQKMeans(d, 16, final_assignment=FinalAssignmentMode.Exact) +kmeans = RaBitQKMeans(d, 16, final_assignment="exact") kmeans.train(x) ``` +Python takes the strings `'approximate'` and `'exact'` since 0.8.5. The +`FinalAssignmentMode` members `Approximate`, `Exact` and the legacy alias `SymphonyQG` +are still accepted until 0.9, and `cp.final_assignment` reads back as a member +until then; importing `FinalAssignmentMode` raises a `DeprecationWarning`. + In C++, set `parameters.final_assignment` to `rabitqlib::rabitqkmeans::FinalAssignmentMode::Exact` or `rabitqlib::qgkmeans::FinalAssignmentMode::Exact`; both names refer to the same @@ -240,7 +247,7 @@ C++ callers that change `centroids` or graph parameters cause one rebuild on the next call. Each call still validates the `k * d` centroid coordinates. For the training vectors, `assign` reproduces `assignments` and `distances` -with `FinalAssignmentMode.Exact`, for RaBitQKMeans, and whenever training +with exact final assignment, for RaBitQKMeans, and whenever training sampled the input, because the sampled final pass is the same assignment. Unsampled approximate QGKMeans training also uses previous labels as graph search hints, so its final labels can differ. diff --git a/docs/docs/python_migration.md b/docs/docs/python_migration.md index 4d2e32a9..aa0e72a2 100644 --- a/docs/docs/python_migration.md +++ b/docs/docs/python_migration.md @@ -146,10 +146,37 @@ removes it. | `nprobe=0`, `ef=0` for the default | `None`, or omit the argument; 0.9 raises `ValueError` for 0, while `num_threads=0` keeps meaning every available CPU | 0.8.2 | | `HnswIndex(seed=s)` with `s` above `2**32 - 1` | A seed in `[0, 2**32 - 1]`, the range of the other two classes | Every 0.8 release | +The k-means classes take the names of the index parameters +([#233](https://github.com/VectorDB-NTU/RaBitQ-Library/issues/233)), as keywords and as +attributes of `cp`: + +| 0.8 | Use instead | Works since | +| --- | --- | --- | +| `QGKMeans(quantization_bits=0 \| 4 \| 8)` | `nbits=32 \| 4 \| 8`: 32, not 0, keeps raw vectors | 0.8.5 | +| `QGKMeans(graph_degree=...)` | `max_degree=...` | 0.8.5 | +| `QGKMeans(ef_build=...)` | `ef_construction=...` | 0.8.5 | +| `final_assignment=FinalAssignmentMode.Approximate \| .Exact`, also as `index.cp.final_assignment` on `IvfIndex` and `HnswIndex` | `final_assignment='approximate' \| 'exact'`; `'approximate'` also replaces the alias `FinalAssignmentMode.SymphonyQG` | 0.8.5 | +| `QGKMeansIterationStats`, `RaBitQKMeansIterationStats` | `KMeansIterationStats`, the one class both always were; since 0.8.5 it also reports that name | 0.8.5 | + +Passing a `FinalAssignmentMode` member does not warn by itself; the warning comes where +one of the three old names is imported or read from `rabitqlib`, including through +`from rabitqlib import *`. + +Until 0.9, `cp.final_assignment` still reads back as a `FinalAssignmentMode` member, +whose `.name` is `'Approximate'` or `'Exact'`; 0.9 returns `'approximate'` or +`'exact'`. Reading it does not warn. Code that reads it on both releases can +normalize the value: + +```python +mode = cp.final_assignment +mode = mode if isinstance(mode, str) else mode.name.lower() +``` + Code that must also run on releases before 0.8.5 needs a version check for the rows marked 0.8.5; the other replacements work on every release named. -Two changes come without a warning in 0.9. `HnswIndex()` without `seed=` draws a seed, +Three 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. And `repr(index)` prints -`capacity=` and `routing=` where it prints `max_elements=` and `initializer=`. +`num_threads=1` to `add`) if you rely on a reproducible build. `repr(index)` prints +`capacity=` and `routing=` where it prints `max_elements=` and `initializer=`. And +`cp.final_assignment` reads back as a string, as described above. diff --git a/docs/docs/releases/0.8.5.md b/docs/docs/releases/0.8.5.md index e98ed564..fddd31f0 100644 --- a/docs/docs/releases/0.8.5.md +++ b/docs/docs/releases/0.8.5.md @@ -23,6 +23,18 @@ site. The [migration guide](../python_migration.md#from-08-to-09) lists each cha argument. `num_threads=0` keeps meaning every available CPU. - `HnswIndex` seeds above `2**32 - 1` are deprecated. +The k-means classes take the names of the index parameters (#233): + +- `QGKMeans` and `QGKMeansParameters` take `nbits` (32, 4 or 8), `max_degree` and + `ef_construction` for `quantization_bits` (0, 4 or 8), `graph_degree` and `ef_build`. +- `final_assignment` takes `'approximate'` or `'exact'`, also as + `index.cp.final_assignment` on `IvfIndex` and `HnswIndex`. `FinalAssignmentMode` + members are still accepted, and the attribute still reads back as a member until 0.9. +- `KMeansIterationStats` is the one name of the statistics class. + `QGKMeansIterationStats`, `RaBitQKMeansIterationStats` and `FinalAssignmentMode` warn + when imported or read from the package. The class now reports its name as + `KMeansIterationStats`. + ## Python: other changes - `IvfIndex.set_centroids` takes `num_threads` (#231). Its default follows @@ -35,3 +47,5 @@ site. The [migration guide](../python_migration.md#from-08-to-09) lists each cha build. - `repr(index)` will print `capacity=` and `routing=` where it prints `max_elements=` and `initializer=`. +- `cp.final_assignment` will read back as `'approximate'` or `'exact'` instead of a + `FinalAssignmentMode` member. diff --git a/python_bindings/__init__.py b/python_bindings/__init__.py index cb76d254..45aea066 100644 --- a/python_bindings/__init__.py +++ b/python_bindings/__init__.py @@ -6,20 +6,24 @@ import inspect import operator +import sys import warnings from ._rabitqlib import ( - FinalAssignmentMode, + FinalAssignmentMode as _FinalAssignmentMode, +) +from ._rabitqlib import ( HnswIndex, IvfIndex, - QGKMeansIterationStats, QGKMeansParameters, - RaBitQKMeansIterationStats, RaBitQKMeansParameters, SymqgIndex, _QGKMeans, _RaBitQKMeans, ) +from ._rabitqlib import ( + QGKMeansIterationStats as KMeansIterationStats, +) from ._rabitqlib import ( __version__ as __version__, ) @@ -465,9 +469,9 @@ def former(self): _set_property(cls, old, former, f"Deprecated since 0.8.5: use {replacement}.") -def _set_property(cls, name, getter, documentation): - """Assign a read-only property, named as a class body would name it.""" - member = property(getter, doc=documentation) +def _set_property(cls, name, getter, documentation, setter=None): + """Assign a property, named as a class body would name it.""" + member = property(getter, setter, doc=documentation) setattr(cls, name, member) # Assignment after class creation skips __set_name__, and before Python 3.13 # a property without it reports errors without its name. @@ -732,6 +736,169 @@ def resize(self, max_elements): " Named ef before 0.8.5.", ), ) +# k-means (issue #233): the graph parameters take the index names, final_assignment +# takes a string, and the two statistics class names become one. + +KMeansIterationStats.__name__ = KMeansIterationStats.__qualname__ = ( + "KMeansIterationStats" +) +# Pickle and pydoc find a class by its name in its module, which is the extension. +sys.modules[KMeansIterationStats.__module__].KMeansIterationStats = KMeansIterationStats + +_FINAL_ASSIGNMENTS = { + "approximate": _FinalAssignmentMode.Approximate, + "exact": _FinalAssignmentMode.Exact, +} + + +def _patch_final_assignment(cls): + native = vars(cls)["final_assignment"] + + def final_assignment(self): + return native.__get__(self, cls) + + def set_final_assignment(self, value): + if isinstance(value, str): + try: + value = _FINAL_ASSIGNMENTS[value] + except KeyError: + raise ValueError( + "final_assignment must be 'approximate' or 'exact'" + ) from None + elif not isinstance(value, _FinalAssignmentMode): + raise TypeError( + "final_assignment must be 'approximate' or 'exact', not " + f"{type(value).__name__}" + ) + native.__set__(self, value) + + _set_property( + cls, + "final_assignment", + _member(cls, final_assignment), + "'approximate' uses the training assignment method; 'exact' uses exhaustive " + "assignment against final centroids. Default is 'approximate'. Until 0.9 it " + "reads back as the FinalAssignmentMode member, which is still accepted.", + _member(cls, set_final_assignment, "final_assignment"), + ) + + +def _qg_nbits_to_native(value): + bits = operator.index(value) + if bits not in (4, 8, 32): + raise ValueError("nbits must be 4, 8, or 32") + return 0 if bits == 32 else bits + + +def _qg_nbits_from_native(value): + return 32 if value == 0 else value + + +def _rename_parameter(cls, old, new, documentation, to_native=None, from_native=None): + """Add attribute new for the native attribute old, which then warns.""" + native = vars(cls)[old] + name = cls.__name__ + + def current(self): + value = native.__get__(self, cls) + return value if from_native is None else from_native(value) + + def set_current(self, value): + native.__set__(self, value if to_native is None else to_native(value)) + + def former(self): + _deprecated(f"{name}.{old} is deprecated; use {new}") + return native.__get__(self, cls) + + def set_former(self, value): + _deprecated(f"{name}.{old} is deprecated; use {new}") + native.__set__(self, value) + + _set_property( + cls, + new, + _member(cls, current, new), + documentation, + _member(cls, set_current, new), + ) + _set_property( + cls, + old, + _member(cls, former, old), + f"Deprecated since 0.8.5: use {new}.", + _member(cls, set_former, old), + ) + return native + + +# Old keyword and attribute name -> (new name, the native attribute behind both). +_QG_RENAMED = { + "graph_degree": ( + "max_degree", + _rename_parameter( + QGKMeansParameters, + "graph_degree", + "max_degree", + "Centroid graph degree; a positive multiple of 32. Default is 32. Named " + "graph_degree before 0.8.5.", + ), + ), + "ef_build": ( + "ef_construction", + _rename_parameter( + QGKMeansParameters, + "ef_build", + "ef_construction", + "Positive centroid-graph construction search breadth. Default is 240. " + "Named ef_build before 0.8.5.", + ), + ), + "quantization_bits": ( + "nbits", + _rename_parameter( + QGKMeansParameters, + "quantization_bits", + "nbits", + "Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is " + "32. Named quantization_bits, with 0 for raw float32, before 0.8.5.", + _qg_nbits_to_native, + _qg_nbits_from_native, + ), + ), +} +_patch_final_assignment(QGKMeansParameters) +_patch_final_assignment(RaBitQKMeansParameters) + +_RENAMED_EXPORTS = { + "FinalAssignmentMode": ( + _FinalAssignmentMode, + "FinalAssignmentMode is deprecated; pass 'approximate' or 'exact' as " + "final_assignment", + ), + "QGKMeansIterationStats": ( + KMeansIterationStats, + "QGKMeansIterationStats is deprecated; use KMeansIterationStats", + ), + "RaBitQKMeansIterationStats": ( + KMeansIterationStats, + "RaBitQKMeansIterationStats is deprecated; use KMeansIterationStats", + ), +} + + +def __getattr__(name): + try: + value, message = _RENAMED_EXPORTS[name] + except KeyError: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None + # "from rabitqlib import " asks twice: importlib checks the name before + # the import statement reads it. Warn for the statement only, at its line. + caller = sys._getframe().f_back # None when no Python code is calling + if caller is None or caller.f_code.co_name != "_handle_fromlist": + warnings.warn(f"{message}; {_MIGRATION}", DeprecationWarning, stacklevel=2) + return value + + # --- end of the 0.9 names ---------------------------------------------------- @@ -742,15 +909,36 @@ def __init__(self, d, k, **kwargs): self.d = int(d) self.k = int(k) self.cp = self._parameters_type() + self._keywords = frozenset(kwargs) for name, value in kwargs.items(): + renamed = self._renamed_parameters.get(name) + if renamed is not None: + new, native = renamed + if new in kwargs: + raise TypeError( + f"{type(self).__name__}() got both {new} and its old name {name}" + ) + _deprecated( + f"{type(self).__name__}({name}=...) is deprecated; use {new}=" + + ( + ", with 32 instead of 0 for raw vectors" + if new == "nbits" + else "" + ) + ) + else: + try: + getattr(self.cp, name) + except AttributeError: + raise AttributeError( + f"{type(self).__name__}() got an unexpected keyword argument " + f"{name!r}" + ) from None try: - getattr(self.cp, name) - except AttributeError: - raise AttributeError( - f"{type(self).__name__}() got an unexpected keyword argument {name!r}" - ) from None - try: - setattr(self.cp, name, value) + if renamed is not None: + native.__set__(self.cp, value) + else: + setattr(self.cp, name, value) except TypeError as error: raise TypeError( f"{type(self).__name__}() could not convert parameter {name!r} " @@ -779,8 +967,19 @@ def train(self, x): A failed fit preserves the last successful results. Returned arrays are copies. """ - implementation = self._implementation_type(self.d, self.k, self.cp) - objective = implementation.train(x) + try: + implementation = self._implementation_type(self.d, self.k, self.cp) + objective = implementation.train(x) + except ValueError as error: + # The extension names the 0.8 setting. A caller who wrote the 0.9 + # keyword gets that name back; every 0.8 call keeps its message. A + # subclass may not have run __init__, hence the getattr. + message = str(error) + if "ef_build" not in message or "ef_construction" not in getattr( + self, "_keywords", () + ): + raise + raise ValueError(message.replace("ef_build", "ef_construction")) from None self._impl = implementation return objective @@ -860,7 +1059,7 @@ class QGKMeans(_KMeans): d : int Original vector dimension, from 64 through 65536. k : int - Number of centroids; greater than graph_degree and no more than the + Number of centroids; greater than max_degree and no more than the number of training vectors. niter : int, optional Maximum number of clustering iterations. Default is 25. @@ -884,22 +1083,24 @@ class QGKMeans(_KMeans): num_threads : int, optional Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0. - final_assignment : FinalAssignmentMode, optional - Approximate uses the training assignment method; Exact uses exhaustive - assignment against final centroids. Default is - FinalAssignmentMode.Approximate. - graph_degree : int, optional - Centroid graph degree; a positive multiple of 32. Default is 32. - ef_build : int, optional + final_assignment : {'approximate', 'exact'}, optional + 'approximate' uses the training assignment method; 'exact' uses exhaustive + assignment against final centroids. Default is 'approximate'. A + FinalAssignmentMode member is still accepted until 0.9. + max_degree : int, optional + Centroid graph degree; a positive multiple of 32. Default is 32. Named + graph_degree before 0.8.5. + ef_construction : int, optional Positive centroid-graph construction search breadth. Default is 240. + Named ef_build before 0.8.5. ef_search : int, optional Positive centroid-graph assignment search breadth. Default is 16. graph_build_iterations : int, optional Positive number of graph-building passes after initialization. Default is 1. - quantization_bits : int, optional - Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is - 0. + nbits : int, optional + Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is + 32. Named quantization_bits, with 0 for raw float32, before 0.8.5. Notes ----- @@ -916,6 +1117,7 @@ class QGKMeans(_KMeans): _parameters_type = QGKMeansParameters _implementation_type = _QGKMeans + _renamed_parameters = _QG_RENAMED class RaBitQKMeans(_KMeans): @@ -949,10 +1151,10 @@ class RaBitQKMeans(_KMeans): num_threads : int, optional Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0. - final_assignment : FinalAssignmentMode, optional - Approximate uses the training assignment method; Exact uses exhaustive - assignment against final centroids. Default is - FinalAssignmentMode.Approximate. + final_assignment : {'approximate', 'exact'}, optional + 'approximate' uses the training assignment method; 'exact' uses exhaustive + assignment against final centroids. Default is 'approximate'. A + FinalAssignmentMode member is still accepted until 0.9. Notes ----- @@ -979,12 +1181,14 @@ class RaBitQKMeans(_KMeans): _parameters_type = RaBitQKMeansParameters _implementation_type = _RaBitQKMeans + _renamed_parameters = {} __all__ = [ "FinalAssignmentMode", "HnswIndex", "IvfIndex", + "KMeansIterationStats", "QGKMeans", "QGKMeansIterationStats", "QGKMeansParameters", diff --git a/python_bindings/__init__.pyi b/python_bindings/__init__.pyi index a97df638..f53d8d07 100644 --- a/python_bindings/__init__.pyi +++ b/python_bindings/__init__.pyi @@ -17,6 +17,7 @@ __all__ = [ "FinalAssignmentMode", "HnswIndex", "IvfIndex", + "KMeansIterationStats", "QGKMeans", "QGKMeansIterationStats", "QGKMeansParameters", @@ -31,10 +32,15 @@ _Path: TypeAlias = str | bytes | bytearray | PathLike[str] | PathLike[bytes] _Metric: TypeAlias = Literal["l2", "ip", "innerproduct"] _Routing: TypeAlias = Literal["auto", "flat", "flat_rabitq", "hnsw"] _QGInit: TypeAlias = Literal["pipnn", "random"] +_FinalAssignment: TypeAlias = Literal["approximate", "exact"] # Rank, ID ranges and Python bool (an int subtype) are validated at runtime. _IntegerIds: TypeAlias = npt.NDArray[np.integer[Any]] | Sequence[int | np.integer[Any]] # pybind11 enums are not subclasses of enum.Enum. +@deprecated( + "FinalAssignmentMode is deprecated since 0.8.5; pass 'approximate' or 'exact' " + "as final_assignment" +) class FinalAssignmentMode: """Final centroid assignment policy. @@ -55,7 +61,7 @@ class FinalAssignmentMode: def __int__(self) -> int: ... def __index__(self) -> int: ... -class QGKMeansIterationStats: +class KMeansIterationStats: """Read-only statistics for one completed clustering iteration.""" @property @@ -71,7 +77,9 @@ class QGKMeansIterationStats: def nsplit(self) -> int: """Number of empty centroids repaired by splitting.""" -RaBitQKMeansIterationStats = QGKMeansIterationStats +# The two 0.8 names of KMeansIterationStats; deprecated since 0.8.5. +QGKMeansIterationStats = KMeansIterationStats +RaBitQKMeansIterationStats = KMeansIterationStats class IvfIndex: """An approximate nearest-neighbor index using IVF. @@ -1376,7 +1384,7 @@ class QGKMeans: d : int Original vector dimension, from 64 through 65536. k : int - Number of centroids; greater than graph_degree and no more than the + Number of centroids; greater than max_degree and no more than the number of training vectors. niter : int, optional Maximum number of clustering iterations. Default is 25. @@ -1400,22 +1408,24 @@ class QGKMeans: num_threads : int, optional Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0. - final_assignment : FinalAssignmentMode, optional - Approximate uses the training assignment method; Exact uses exhaustive - assignment against final centroids. Default is - FinalAssignmentMode.Approximate. - graph_degree : int, optional - Centroid graph degree; a positive multiple of 32. Default is 32. - ef_build : int, optional + final_assignment : {'approximate', 'exact'}, optional + 'approximate' uses the training assignment method; 'exact' uses exhaustive + assignment against final centroids. Default is 'approximate'. A + FinalAssignmentMode member is still accepted until 0.9. + max_degree : int, optional + Centroid graph degree; a positive multiple of 32. Default is 32. Named + graph_degree before 0.8.5. + ef_construction : int, optional Positive centroid-graph construction search breadth. Default is 240. + Named ef_build before 0.8.5. ef_search : int, optional Positive centroid-graph assignment search breadth. Default is 16. graph_build_iterations : int, optional Positive number of graph-building passes after initialization. Default is 1. - quantization_bits : int, optional - Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is - 0. + nbits : int, optional + Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is + 32. Named quantization_bits, with 0 for raw float32, before 0.8.5. Notes ----- @@ -1434,6 +1444,7 @@ class QGKMeans: k: int cp: QGKMeansParameters + @overload def __init__( self, d: SupportsIndex, @@ -1447,12 +1458,12 @@ class QGKMeans: max_points_per_centroid: SupportsIndex = 0, early_stop_threshold: float = 0.0, num_threads: SupportsIndex = 0, - final_assignment: FinalAssignmentMode = FinalAssignmentMode.Approximate, - graph_degree: SupportsIndex = 32, - ef_build: SupportsIndex = 240, + final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", + max_degree: SupportsIndex = 32, + ef_construction: SupportsIndex = 240, ef_search: SupportsIndex = 16, graph_build_iterations: SupportsIndex = 1, - quantization_bits: SupportsIndex = 0, + nbits: SupportsIndex = 32, ) -> None: """Cluster vectors using SymphonyQG graph assignment. @@ -1461,7 +1472,7 @@ class QGKMeans: d : int Original vector dimension, from 64 through 65536. k : int - Number of centroids; greater than graph_degree and no more than the + Number of centroids; greater than max_degree and no more than the number of training vectors. niter : int, optional Maximum number of clustering iterations. Default is 25. @@ -1485,22 +1496,24 @@ class QGKMeans: num_threads : int, optional Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0. - final_assignment : FinalAssignmentMode, optional - Approximate uses the training assignment method; Exact uses exhaustive - assignment against final centroids. Default is - FinalAssignmentMode.Approximate. - graph_degree : int, optional - Centroid graph degree; a positive multiple of 32. Default is 32. - ef_build : int, optional + final_assignment : {'approximate', 'exact'}, optional + 'approximate' uses the training assignment method; 'exact' uses exhaustive + assignment against final centroids. Default is 'approximate'. A + FinalAssignmentMode member is still accepted until 0.9. + max_degree : int, optional + Centroid graph degree; a positive multiple of 32. Default is 32. Named + graph_degree before 0.8.5. + ef_construction : int, optional Positive centroid-graph construction search breadth. Default is 240. + Named ef_build before 0.8.5. ef_search : int, optional Positive centroid-graph assignment search breadth. Default is 16. graph_build_iterations : int, optional Positive number of graph-building passes after initialization. Default is 1. - quantization_bits : int, optional - Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is - 0. + nbits : int, optional + Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is + 32. Named quantization_bits, with 0 for raw float32, before 0.8.5. Notes ----- @@ -1515,6 +1528,79 @@ class QGKMeans: kinds of objective are not directly comparable. """ + @overload + @deprecated( + "QGKMeans(quantization_bits=...) is deprecated since 0.8.5; use nbits=, with 32 instead of 0 for raw vectors" + ) + def __init__( + self, + d: SupportsIndex, + k: SupportsIndex, + *, + quantization_bits: SupportsIndex, + niter: SupportsIndex = 25, + verbose: bool | np.bool_ = False, + spherical: bool | np.bool_ = False, + seed: SupportsIndex = 42, + min_points_per_centroid: SupportsIndex = 39, + max_points_per_centroid: SupportsIndex = 0, + early_stop_threshold: float = 0.0, + num_threads: SupportsIndex = 0, + final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", + ef_search: SupportsIndex = 16, + graph_build_iterations: SupportsIndex = 1, + graph_degree: SupportsIndex = ..., + ef_build: SupportsIndex = ..., + max_degree: SupportsIndex = 32, + ef_construction: SupportsIndex = 240, + ) -> None: ... + @overload + @deprecated("QGKMeans(graph_degree=...) is deprecated since 0.8.5; use max_degree=") + def __init__( + self, + d: SupportsIndex, + k: SupportsIndex, + *, + graph_degree: SupportsIndex, + niter: SupportsIndex = 25, + verbose: bool | np.bool_ = False, + spherical: bool | np.bool_ = False, + seed: SupportsIndex = 42, + min_points_per_centroid: SupportsIndex = 39, + max_points_per_centroid: SupportsIndex = 0, + early_stop_threshold: float = 0.0, + num_threads: SupportsIndex = 0, + final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", + ef_search: SupportsIndex = 16, + graph_build_iterations: SupportsIndex = 1, + ef_build: SupportsIndex = ..., + ef_construction: SupportsIndex = 240, + nbits: SupportsIndex = 32, + ) -> None: ... + @overload + @deprecated( + "QGKMeans(ef_build=...) is deprecated since 0.8.5; use ef_construction=" + ) + def __init__( + self, + d: SupportsIndex, + k: SupportsIndex, + *, + ef_build: SupportsIndex, + niter: SupportsIndex = 25, + verbose: bool | np.bool_ = False, + spherical: bool | np.bool_ = False, + seed: SupportsIndex = 42, + min_points_per_centroid: SupportsIndex = 39, + max_points_per_centroid: SupportsIndex = 0, + early_stop_threshold: float = 0.0, + num_threads: SupportsIndex = 0, + final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", + ef_search: SupportsIndex = 16, + graph_build_iterations: SupportsIndex = 1, + max_degree: SupportsIndex = 32, + nbits: SupportsIndex = 32, + ) -> None: ... def train(self, x: npt.ArrayLike) -> float: """Train centroids and retain the final assignments. @@ -1594,7 +1680,7 @@ class QGKMeans: """Objective for the final assignments of all n vectors, or None before training.""" @property - def iteration_stats(self) -> list[QGKMeansIterationStats] | None: + def iteration_stats(self) -> list[KMeansIterationStats] | None: """Per-iteration statistics over the vectors used for iterations, or None before training.""" class QGKMeansParameters: @@ -1645,19 +1731,44 @@ class QGKMeansParameters: """Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0.""" @num_threads.setter def num_threads(self, value: SupportsIndex) -> None: ... - - final_assignment: FinalAssignmentMode - """Approximate uses the training assignment method; Exact uses exhaustive assignment against final centroids. Default is FinalAssignmentMode.Approximate.""" - @property + def final_assignment(self) -> FinalAssignmentMode: + """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'. Until 0.9 it reads back as the FinalAssignmentMode member, which is still accepted.""" + @final_assignment.setter + def final_assignment( + self, value: _FinalAssignment | FinalAssignmentMode + ) -> None: ... + @property + def max_degree(self) -> int: + """Centroid graph degree; a positive multiple of 32. Default is 32. Named graph_degree before 0.8.5.""" + @max_degree.setter + def max_degree(self, value: SupportsIndex) -> None: ... + @property + @deprecated( + "QGKMeansParameters.graph_degree is deprecated since 0.8.5; use max_degree" + ) def graph_degree(self) -> int: - """Centroid graph degree; a positive multiple of 32. Default is 32.""" + """Deprecated since 0.8.5: use max_degree.""" @graph_degree.setter + @deprecated( + "QGKMeansParameters.graph_degree is deprecated since 0.8.5; use max_degree" + ) def graph_degree(self, value: SupportsIndex) -> None: ... @property + def ef_construction(self) -> int: + """Positive centroid-graph construction search breadth. Default is 240. Named ef_build before 0.8.5.""" + @ef_construction.setter + def ef_construction(self, value: SupportsIndex) -> None: ... + @property + @deprecated( + "QGKMeansParameters.ef_build is deprecated since 0.8.5; use ef_construction" + ) def ef_build(self) -> int: - """Positive centroid-graph construction search breadth. Default is 240.""" + """Deprecated since 0.8.5: use ef_construction.""" @ef_build.setter + @deprecated( + "QGKMeansParameters.ef_build is deprecated since 0.8.5; use ef_construction" + ) def ef_build(self, value: SupportsIndex) -> None: ... @property def ef_search(self) -> int: @@ -1670,9 +1781,20 @@ class QGKMeansParameters: @graph_build_iterations.setter def graph_build_iterations(self, value: SupportsIndex) -> None: ... @property + def nbits(self) -> int: + """Centroid storage: 32 for raw float32, or 4 or 8 for RaBitQ. Default is 32. Named quantization_bits, with 0 for raw float32, before 0.8.5.""" + @nbits.setter + def nbits(self, value: SupportsIndex) -> None: ... + @property + @deprecated( + "QGKMeansParameters.quantization_bits is deprecated since 0.8.5; use nbits" + ) def quantization_bits(self) -> int: - """Centroid storage: 0 for raw float32, or 4 or 8 for RaBitQ. Default is 0.""" + """Deprecated since 0.8.5: use nbits.""" @quantization_bits.setter + @deprecated( + "QGKMeansParameters.quantization_bits is deprecated since 0.8.5; use nbits" + ) def quantization_bits(self, value: SupportsIndex) -> None: ... def __init__(self) -> None: """Create parameters with their documented defaults.""" @@ -1708,10 +1830,10 @@ class RaBitQKMeans: num_threads : int, optional Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0. - final_assignment : FinalAssignmentMode, optional - Approximate uses the training assignment method; Exact uses exhaustive - assignment against final centroids. Default is - FinalAssignmentMode.Approximate. + final_assignment : {'approximate', 'exact'}, optional + 'approximate' uses the training assignment method; 'exact' uses exhaustive + assignment against final centroids. Default is 'approximate'. A + FinalAssignmentMode member is still accepted until 0.9. Notes ----- @@ -1753,7 +1875,7 @@ class RaBitQKMeans: max_points_per_centroid: SupportsIndex = 0, early_stop_threshold: float = 0.0, num_threads: SupportsIndex = 0, - final_assignment: FinalAssignmentMode = FinalAssignmentMode.Approximate, + final_assignment: _FinalAssignment | FinalAssignmentMode = "approximate", ) -> None: """Cluster vectors using flat RaBitQ assignment. @@ -1785,10 +1907,10 @@ class RaBitQKMeans: num_threads : int, optional Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0. - final_assignment : FinalAssignmentMode, optional - Approximate uses the training assignment method; Exact uses exhaustive - assignment against final centroids. Default is - FinalAssignmentMode.Approximate. + final_assignment : {'approximate', 'exact'}, optional + 'approximate' uses the training assignment method; 'exact' uses exhaustive + assignment against final centroids. Default is 'approximate'. A + FinalAssignmentMode member is still accepted until 0.9. Notes ----- @@ -1892,7 +2014,7 @@ class RaBitQKMeans: """Objective for the final assignments of all n vectors, or None before training.""" @property - def iteration_stats(self) -> list[QGKMeansIterationStats] | None: + def iteration_stats(self) -> list[KMeansIterationStats] | None: """Per-iteration statistics over the vectors used for iterations, or None before training.""" class RaBitQKMeansParameters: @@ -1943,9 +2065,12 @@ class RaBitQKMeansParameters: """Worker count; 0 selects the available CPU count, capped by OMP_NUM_THREADS. Default is 0.""" @num_threads.setter def num_threads(self, value: SupportsIndex) -> None: ... - - final_assignment: FinalAssignmentMode - """Approximate uses the training assignment method; Exact uses exhaustive assignment against final centroids. Default is FinalAssignmentMode.Approximate.""" - + @property + def final_assignment(self) -> FinalAssignmentMode: + """'approximate' uses the training assignment method; 'exact' uses exhaustive assignment against final centroids. Default is 'approximate'. Until 0.9 it reads back as the FinalAssignmentMode member, which is still accepted.""" + @final_assignment.setter + def final_assignment( + self, value: _FinalAssignment | FinalAssignmentMode + ) -> None: ... def __init__(self) -> None: """Create parameters with their documented defaults.""" diff --git a/sample/python/clustering_cli/ivf.py b/sample/python/clustering_cli/ivf.py index 5bb589d4..bd20f4b4 100644 --- a/sample/python/clustering_cli/ivf.py +++ b/sample/python/clustering_cli/ivf.py @@ -1,7 +1,7 @@ import argparse from time import time -from rabitqlib import FinalAssignmentMode, QGKMeans, RaBitQKMeans +from rabitqlib import QGKMeans, RaBitQKMeans from utils.io import read_fvecs, write_fvecs, write_ivecs if __name__ == "__main__": @@ -45,7 +45,7 @@ dim, K, spherical=metric == "ip", - final_assignment=FinalAssignmentMode.Exact, + final_assignment="exact", verbose=True, ) kmeans.train(X) diff --git a/sample/python/kmeans_clustering.py b/sample/python/kmeans_clustering.py index 79b99e6d..ddd20ade 100644 --- a/sample/python/kmeans_clustering.py +++ b/sample/python/kmeans_clustering.py @@ -4,7 +4,7 @@ from time import time import numpy as np -from rabitqlib import FinalAssignmentMode, QGKMeans, RaBitQKMeans +from rabitqlib import QGKMeans, RaBitQKMeans from rabitqlib._rabitqlib import _available_cpu_count, _default_thread_count from utils import read_fvecs @@ -37,7 +37,7 @@ def cluster_data( num_clusters, spherical=metric == "ip", num_threads=threads, - final_assignment=FinalAssignmentMode.Exact, + final_assignment="exact", verbose=True, ) start = time() @@ -71,7 +71,7 @@ def main(args) -> None: "--method", choices=["rabitq", "qg"], default="qg", - help="rabitq for few centroids; qg for many (requires k > graph_degree)", + help="rabitq for few centroids; qg for many (requires k > max_degree)", ) parser.add_argument( "--num-threads", diff --git a/tests/python/test_compat_09.py b/tests/python/test_compat_09.py index 9907523f..d7f35596 100644 --- a/tests/python/test_compat_09.py +++ b/tests/python/test_compat_09.py @@ -1,16 +1,25 @@ """The 0.8 spellings that 0.9 renames: both work in 0.8.5, and the old one warns.""" +import _thread import inspect +import pickle +import sys +import time import warnings import numpy as np import pytest +import rabitqlib from conftest import DIM -from rabitqlib import HnswIndex, IvfIndex, SymqgIndex +from rabitqlib import HnswIndex, IvfIndex, QGKMeans, RaBitQKMeans, SymqgIndex -def single_deprecation(call): - """Run call and return its result and its one DeprecationWarning.""" +def single_deprecation(call, at=None): + """Run call and return its result and its one DeprecationWarning. + + The warning must point at the code that used the old form: the lines of call, + or of the helper function at when call reaches the old form through it. + """ with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") result = call() @@ -19,6 +28,10 @@ def single_deprecation(call): ] # Attributed to the caller, so users see their own line. assert caught[0].filename == __file__ + lines = [ + line for _, _, line in (at or call).__code__.co_lines() if line is not None + ] + assert min(lines) <= caught[0].lineno <= max(lines), (caught[0].lineno, lines) assert "python_migration" in str(caught[0].message) return result, str(caught[0].message) @@ -360,3 +373,325 @@ def test_new_members_are_documented(): assert "reserve can preallocate it" in HnswIndex.__doc__ assert "reserve_cluster can preallocate room" in IvfIndex.add.__doc__ assert "centroid initializer" not in IvfIndex.add.__doc__ + + +# --- k-means: the names of issue #233 ----------------------------------------- + + +def qg_kmeans(**parameters): + return QGKMeans(DIM, 80, niter=2, num_threads=1, seed=1, **parameters) + + +def test_qgkmeans_takes_the_index_parameter_names(base_data): + new = silently(lambda: qg_kmeans(nbits=4, max_degree=64, ef_construction=100)) + assert (new.cp.nbits, new.cp.max_degree, new.cp.ef_construction) == (4, 64, 100) + for keyword, value, hint, current in ( + ("quantization_bits", 4, "use nbits=, with 32 instead of 0", "nbits"), + ("graph_degree", 64, "use max_degree=", "max_degree"), + ("ef_build", 100, "use ef_construction=", "ef_construction"), + ): + model, message = single_deprecation( + lambda keyword=keyword, value=value: qg_kmeans(**{keyword: value}), + at=qg_kmeans, + ) + assert message.startswith(f"QGKMeans({keyword}=...) is deprecated; {hint}") + # The old keyword reaches the same setting, which differs from its default. + assert ( + getattr(model.cp, current) + == value + != getattr(QGKMeans(DIM, 80).cp, current) + ) + with pytest.raises( + TypeError, + match=f"^QGKMeans\\(\\) got both {current} and its old name {keyword}$", + ): + silently( + lambda keyword=keyword, value=value, current=current: qg_kmeans( + **{keyword: value, current: value} + ) + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + old = qg_kmeans(quantization_bits=4, graph_degree=64, ef_build=100) + new.train(base_data) + old.train(base_data) + np.testing.assert_array_equal(new.centroids, old.centroids) + np.testing.assert_array_equal(new.assignments, old.assignments) + + +def test_qgkmeans_nbits_uses_32_for_raw_vectors(): + assert silently(lambda: QGKMeans(DIM, 80).cp.nbits) == 32 + for nbits, stored in ((32, 0), (4, 4), (8, 8), (np.int64(32), 0)): + model = silently(lambda nbits=nbits: qg_kmeans(nbits=nbits)) + assert model.cp.nbits == nbits + with pytest.warns(DeprecationWarning, match="use nbits"): + assert model.cp.quantization_bits == stored + raw, _ = single_deprecation(lambda: qg_kmeans(quantization_bits=0), at=qg_kmeans) + assert raw.cp.nbits == 32 + for invalid in (0, 16, 33, True): + with pytest.raises(ValueError, match="^nbits must be 4, 8, or 32$"): + qg_kmeans(nbits=invalid) + with pytest.raises(ValueError, match="^nbits must be 4, 8, or 32$"): + QGKMeans(DIM, 80).cp.nbits = invalid + with pytest.raises(TypeError, match="could not convert parameter 'nbits'"): + qg_kmeans(nbits="4") + + +def test_qgkmeans_parameter_attributes_are_renamed(): + cp = QGKMeans(DIM, 80).cp + for old, new, value in ( + ("graph_degree", "max_degree", 64), + ("ef_build", "ef_construction", 100), + ("quantization_bits", "nbits", 8), + ): + silently(lambda new=new, value=value: setattr(cp, new, value)) + assert silently(lambda new=new: getattr(cp, new)) == value + read, message = single_deprecation(lambda old=old: getattr(cp, old)) + assert read == value + assert message.startswith(f"QGKMeansParameters.{old} is deprecated; use {new}") + _, message = single_deprecation( + lambda old=old: setattr(cp, old, 4 if new == "nbits" else 32) + ) + assert message.startswith(f"QGKMeansParameters.{old} is deprecated; use {new}") + assert getattr(cp, new) == (4 if new == "nbits" else 32) + for name in ("nbits", "max_degree", "ef_construction", "graph_degree"): + with pytest.raises(AttributeError, match="unexpected keyword argument"): + RaBitQKMeans(DIM, 4, **{name: 32}) + + +@pytest.mark.parametrize("cls", [QGKMeans, RaBitQKMeans]) +def test_final_assignment_takes_a_string(cls, base_data): + def trained(final_assignment): + model = cls( + DIM, 80, niter=2, num_threads=1, seed=1, final_assignment=final_assignment + ) + model.train(base_data) + return model + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + modes = rabitqlib.FinalAssignmentMode + for text, member in (("exact", modes.Exact), ("approximate", modes.Approximate)): + by_text = silently(lambda text=text: trained(text)) + # A member is still accepted, silently: its name warned where it was read. + by_member = silently(lambda member=member: trained(member)) + assert by_text.cp.final_assignment == member # reads back as the member + np.testing.assert_array_equal(by_text.assignments, by_member.assignments) + np.testing.assert_array_equal(by_text.distances, by_member.distances) + cp = cls(DIM, 80).cp + silently(lambda cp=cp, text=text: setattr(cp, "final_assignment", text)) + assert cp.final_assignment == member + for invalid in ("Exact", "EXACT", "", "symphonyqg"): + with pytest.raises( + ValueError, match="^final_assignment must be 'approximate' or 'exact'$" + ): + cls(DIM, 80, final_assignment=invalid) + with pytest.raises( + TypeError, match="could not convert parameter 'final_assignment'" + ): + cls(DIM, 80, final_assignment=1) + + +def test_index_training_parameters_take_the_string(base_data): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + modes = rabitqlib.FinalAssignmentMode + for index in (IvfIndex(DIM, 8, seed=3), HnswIndex(DIM, num_clusters=8, seed=3)): + for value, member in ( + ("exact", modes.Exact), + ("approximate", modes.Approximate), + (modes.Exact, modes.Exact), + (modes.SymphonyQG, modes.Approximate), + ): + silently( + lambda index=index, value=value: setattr( + index.cp, "final_assignment", value + ) + ) + assert index.cp.final_assignment == member + with pytest.raises( + ValueError, match="^final_assignment must be 'approximate' or 'exact'$" + ): + index.cp.final_assignment = "Exact" + with pytest.raises( + TypeError, + match="^final_assignment must be 'approximate' or 'exact', not int$", + ): + index.cp.final_assignment = 1 + assert index.cp.final_assignment == modes.Approximate # unchanged by failures + silently(lambda index=index: index.train(base_data, num_threads=1)) + assert index.is_trained + + +def _import_final_assignment_mode(): + from rabitqlib import FinalAssignmentMode + + return FinalAssignmentMode + + +def _import_qg_stats(): + from rabitqlib import QGKMeansIterationStats + + return QGKMeansIterationStats + + +def _import_rabitq_stats(): + from rabitqlib import RaBitQKMeansIterationStats + + return RaBitQKMeansIterationStats + + +@pytest.mark.parametrize( + "name,importer,message", + [ + ( + "FinalAssignmentMode", + _import_final_assignment_mode, + "FinalAssignmentMode is deprecated; pass 'approximate'", + ), + ( + "QGKMeansIterationStats", + _import_qg_stats, + "QGKMeansIterationStats is deprecated; use KMeansIterationStats", + ), + ( + "RaBitQKMeansIterationStats", + _import_rabitq_stats, + "RaBitQKMeansIterationStats is deprecated; use KMeansIterationStats", + ), + ], +) +def test_names_that_leave_the_package_warn_once(name, importer, message): + value, text = single_deprecation(lambda: getattr(rabitqlib, name)) + assert text.startswith(message) + imported, text = single_deprecation(importer, at=importer) + assert text.startswith(message) + assert imported is value + assert name in rabitqlib.__all__ + # hasattr reads the name too. + found, text = single_deprecation(lambda: hasattr(rabitqlib, name)) + assert found and text.startswith(message) + + +def test_old_names_can_be_read_without_a_python_caller(): + # A thread whose entry point is a builtin has no Python frame for the warning + # to point at; the read must still succeed. list.extend and map are builtins, + # so getattr runs in the new thread with no Python code calling it. + read = [] + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + expected = rabitqlib.FinalAssignmentMode + _thread.start_new_thread( + read.extend, (map(getattr, [rabitqlib], ["FinalAssignmentMode"]),) + ) + # A failed read leaves the list empty, so this waits out the deadline. + deadline = time.monotonic() + 5 + while not read and time.monotonic() < deadline: + time.sleep(0.01) + assert read == [expected] + + +def test_kmeans_iteration_stats_is_one_class(base_data): + stats = silently(lambda: rabitqlib.KMeansIterationStats) + assert stats.__name__ == stats.__qualname__ == "KMeansIterationStats" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + assert rabitqlib.QGKMeansIterationStats is stats + assert rabitqlib.RaBitQKMeansIterationStats is stats + for cls in (QGKMeans, RaBitQKMeans): + model = cls(DIM, 80, niter=2, num_threads=1, seed=1) + model.train(base_data) + assert all(type(item) is stats for item in model.iteration_stats) + with pytest.raises( + AttributeError, match="^module 'rabitqlib' has no attribute 'missing'$" + ): + rabitqlib.missing + + +def test_star_import_still_provides_the_old_names(): + namespace = {} + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + exec("from rabitqlib import *", namespace) + assert set(rabitqlib.__all__) <= set(namespace) + assert [w.category for w in caught] == [DeprecationWarning] * 3 + + +def test_old_attribute_keeps_the_08_encoding(): + cp = QGKMeans(DIM, 80).cp + cp.nbits = 8 + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + cp.quantization_bits = 0 # raw vectors in the 0.8 encoding + assert cp.quantization_bits == 0 + assert cp.nbits == 32 + + +def test_subclass_warnings_name_the_subclass(): + class Clustering(QGKMeans): + pass + + def make(): + return Clustering(DIM, 80, graph_degree=64) + + model, message = single_deprecation(make, at=make) + assert message.startswith( + "Clustering(graph_degree=...) is deprecated; use max_degree=" + ) + assert model.cp.max_degree == 64 + + +@pytest.mark.parametrize("cls", [QGKMeans, RaBitQKMeans]) +@pytest.mark.parametrize("name", ["unknown", "mro", "__dict__"]) +def test_unknown_kmeans_keyword_message_is_unchanged(cls, name): + with pytest.raises( + AttributeError, + match=f"^{cls.__name__}\\(\\) got an unexpected keyword argument '{name}'$", + ): + cls(DIM, 80, **{name: 1}) + + +def test_train_error_names_the_keyword_the_caller_used(base_data): + old_message = "^QGKMeans ef_build and ef_search must be positive$" + with pytest.raises( + ValueError, match="^QGKMeans ef_construction and ef_search must be positive$" + ): + QGKMeans(DIM, 80, niter=1, ef_construction=0).train(base_data) + # Every call that 0.8 accepts keeps the message 0.8 gave it. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + old = QGKMeans(DIM, 80, niter=1, ef_build=0) + with pytest.raises(ValueError, match=old_message): + old.train(base_data) + with pytest.raises(ValueError, match=old_message): + QGKMeans(DIM, 80, niter=1, ef_search=0).train(base_data) + + class WithoutInit(QGKMeans): + def __init__(self): + self.d, self.k, self._impl = DIM, 80, None + self.cp = rabitqlib.QGKMeansParameters() + self.cp.ef_search = 0 + + with pytest.raises(ValueError, match=old_message): + WithoutInit().train(base_data) + # Other errors pass through as the extension raised them. + with pytest.raises( + ValueError, match="^QGKMeans graph_build_iterations must be positive$" + ) as raised: + QGKMeans(DIM, 80, niter=1, ef_construction=100, graph_build_iterations=0).train( + base_data + ) + assert raised.value.__context__ is None # not re-raised as a new object + # The 0.8 name with a value only nbits would accept is still rejected at train. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + wrong = QGKMeans(DIM, 80, niter=1, quantization_bits=32) + with pytest.raises(ValueError, match="quantization_bits must be 0, 4, or 8"): + wrong.train(base_data) + + +def test_statistics_class_pickles_by_reference(): + stats = rabitqlib.KMeansIterationStats + assert pickle.loads(pickle.dumps(stats)) is stats + assert stats.__module__ == "rabitqlib._rabitqlib" + assert getattr(sys.modules[stats.__module__], "KMeansIterationStats") is stats diff --git a/tests/python/test_editor_support.py b/tests/python/test_editor_support.py index 4d937fb7..64098788 100644 --- a/tests/python/test_editor_support.py +++ b/tests/python/test_editor_support.py @@ -157,16 +157,23 @@ def test_native_signature_names_and_defaults(name): def test_clustering_keyword_defaults(name): cls = declarations()[name] init = next( - n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "__init__" + n + for n in cls.body + if isinstance(n, ast.FunctionDef) + and n.name == "__init__" + and not is_deprecated(n) ) instance = getattr(rabitqlib, name)(64, 40) for arg, default in zip(init.args.kwonlyargs, init.args.kw_defaults): assert default is not None, (name, arg.arg) - if isinstance(default, ast.Attribute): - expected = getattr(rabitqlib.FinalAssignmentMode, default.attr) - else: - expected = ast.literal_eval(default) - assert getattr(instance.cp, arg.arg) == expected + expected = ast.literal_eval(default) + actual = getattr(instance.cp, arg.arg) + if arg.arg == "final_assignment": + # Reads back as the enum member until 0.9: compare with what passing + # the declared default explicitly gives. + explicit = getattr(rabitqlib, name)(64, 40, final_assignment=expected) + expected = explicit.cp.final_assignment + assert actual == expected for name in ( "centroids", "assignments", diff --git a/tests/python/typing/public_api.py b/tests/python/typing/public_api.py index ad080254..6cab83a4 100644 --- a/tests/python/typing/public_api.py +++ b/tests/python/typing/public_api.py @@ -11,6 +11,7 @@ FinalAssignmentMode, HnswIndex, IvfIndex, + KMeansIterationStats, QGKMeans, QGKMeansIterationStats, QGKMeansParameters, @@ -61,8 +62,8 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: assert_type(SymqgIndex.load("index.bin"), SymqgIndex) ivf.reserve_cluster(0, 128) hnsw.reserve(256) - qg = QGKMeans(64, 40, niter=2, quantization_bits=4) - flat = RaBitQKMeans(64, 2, final_assignment=FinalAssignmentMode.Exact) + qg = QGKMeans(64, 40, niter=2, nbits=4) + flat = RaBitQKMeans(64, 2, final_assignment="exact") assert_type(qg.cp, QGKMeansParameters) assert_type(flat.cp, RaBitQKMeansParameters) for model in (qg, flat): @@ -77,8 +78,8 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: tuple[npt.NDArray[np.uint32], npt.NDArray[np.float32]], ) if model.iteration_stats is not None: - assert_type(model.iteration_stats[0], QGKMeansIterationStats) - qg.cp.final_assignment = FinalAssignmentMode.Approximate + assert_type(model.iteration_stats[0], KMeansIterationStats) + qg.cp.final_assignment = "approximate" ivf.search(x, "five", 2) # type: ignore[call-overload] ivf.dim = 16 # type: ignore[misc] qg.cp.niter = "two" # type: ignore[assignment] @@ -86,12 +87,28 @@ def check(x: npt.NDArray[np.float32], labels: npt.NDArray[np.uint32]) -> None: hnsw.search(x, 5, nprobe=2) # type: ignore[call-overload] IvfIndex(64, 2, 4) # type: ignore[call-overload] hnsw.train(x, 1) # type: ignore[call-arg] + qg.cp.final_assignment = "Exact" # type: ignore[assignment] + QGKMeans(64, 40, ef_build=1, bogus=1) # type: ignore[call-overload] + + +def deprecated_forms_still_type_check(qg: QGKMeans, flat: RaBitQKMeans) -> None: + # Accepted until 0.9; the stubs mark them deprecated without rejecting them. + RaBitQKMeans(64, 2, final_assignment=FinalAssignmentMode.Exact) + QGKMeans(64, 40, final_assignment=FinalAssignmentMode.Approximate) + qg.cp.final_assignment = FinalAssignmentMode.Exact + assert_type(flat.cp.final_assignment, FinalAssignmentMode) + QGKMeans(64, 40, quantization_bits=4, niter=2) + QGKMeans(64, 40, graph_degree=32, ef_build=100) def stats_alias(stats: RaBitQKMeansIterationStats) -> QGKMeansIterationStats: return stats +def stats_name(stats: QGKMeansIterationStats) -> KMeansIterationStats: + return stats + + def check_parameter_reads( parameters: QGKMeansParameters | RaBitQKMeansParameters, ) -> None: @@ -152,7 +169,7 @@ def check_numpy_scalars() -> None: np.int64(64), np.int64(40), niter=np.int64(1), - graph_degree=np.int64(32), + max_degree=np.int64(32), num_threads=np.int64(1), ) for model in (flat, qg): @@ -167,11 +184,11 @@ def check_numpy_scalars() -> None: assert_type(model.train(x), float) assignments, distances = model.assign(x[:3]) assert assignments.shape == distances.shape == (3,) - qg.cp.graph_degree = np.int64(32) - qg.cp.ef_build = np.int64(40) + qg.cp.max_degree = np.int64(32) + qg.cp.ef_construction = np.int64(40) qg.cp.ef_search = np.int64(16) qg.cp.graph_build_iterations = np.int64(1) - qg.cp.quantization_bits = np.int64(4) + qg.cp.nbits = np.int64(4) members = FinalAssignmentMode.__members__ assert_type(members, dict[str, FinalAssignmentMode]) assert_type(members["Exact"], FinalAssignmentMode) diff --git a/tests/test_mypy.py b/tests/test_mypy.py index d4914806..3ab2d3eb 100644 --- a/tests/test_mypy.py +++ b/tests/test_mypy.py @@ -61,10 +61,13 @@ def test_static_public_usage(tmp_path): # Each 0.7 call form the compatibility layer accepts, and each 0.8 spelling that 0.9 # renames, is marked deprecated in the stubs, so editors flag it while it still # type-checks. Deprecations that depend on a value (a breadth of 0, a seed above -# 2**32 - 1) cannot be declared and are documented in the docstrings only. +# 2**32 - 1) cannot be declared and are documented in the docstrings only. The two +# old statistics class names are plain aliases, which PEP 702 cannot mark; only the +# runtime warns for them. DEPRECATED_USAGE = """\ import numpy as np -from rabitqlib import HnswIndex, IvfIndex, SymqgIndex +import rabitqlib +from rabitqlib import HnswIndex, IvfIndex, QGKMeans, SymqgIndex x = np.zeros((80, 64), dtype=np.float32) labels = np.zeros(80, dtype=np.uint32) @@ -93,12 +96,52 @@ def test_static_public_usage(tmp_path): count = graph.max_elements graph.search(x, 5, ef=32) graph.search(x, 5, 32, 1) +kmeans = QGKMeans(64, 40, quantization_bits=4) +kmeans = QGKMeans(64, 40, graph_degree=32) +kmeans = QGKMeans(64, 40, ef_build=100) +kmeans.cp.quantization_bits = 4 +kmeans.cp.graph_degree = 32 +kmeans.cp.ef_build = 100 +mode = rabitqlib.FinalAssignmentMode.Exact +storage = kmeans.cp.quantization_bits +degree = kmeans.cp.graph_degree +breadth = kmeans.cp.ef_build """ +# The forms 0.9 keeps: none may be flagged as deprecated. +CURRENT_USAGE = """\ +import numpy as np +from rabitqlib import HnswIndex, IvfIndex, QGKMeans, RaBitQKMeans, SymqgIndex -def test_deprecated_forms_are_flagged(tmp_path): - usage = tmp_path / "deprecated_usage.py" - usage.write_text(DEPRECATED_USAGE) +x = np.zeros((80, 64), dtype=np.float32) +ivf = IvfIndex(64, 1, nbits=4, routing="flat") +strategy = ivf.routing +stored = ivf.num_stored_points +ivf.reserve_cluster(0, 8) +ivf.search(x, 5, 1, high_accuracy=None, num_threads=1) +hnsw = HnswIndex(64, nbits=4, seed=5) +capacity = hnsw.capacity +hnsw.reserve(128) +hnsw.search(x, 5, 32, num_threads=1) +hnsw.search(x, 5, ef_search=32) +graph = SymqgIndex(64) +graph.search(x, 5, ef_search=32, num_threads=1) +kmeans = QGKMeans( + 64, 40, nbits=4, max_degree=32, ef_construction=100, final_assignment="exact" +) +kmeans.cp.nbits = 8 +kmeans.cp.max_degree = 32 +kmeans.cp.ef_construction = 100 +kmeans.cp.final_assignment = "approximate" +width = kmeans.cp.nbits +flat = RaBitQKMeans(64, 2, final_assignment="exact") +""" + + +def deprecated_lines(tmp_path, source): + """Line numbers mypy flags as deprecated in source, and its whole output.""" + usage = tmp_path / "usage.py" + usage.write_text(source) result = subprocess.run( [ sys.executable, @@ -122,4 +165,20 @@ def test_deprecated_forms_are_flagged(tmp_path): rf"{re.escape(str(usage))}:(\d+): error: .*\[deprecated\]", result.stdout ) } - assert flagged == set(range(6, 31)), result.stdout + return flagged, result.stdout + + +def test_deprecated_forms_are_flagged(tmp_path): + flagged, output = deprecated_lines(tmp_path, DEPRECATED_USAGE) + old_forms = set(range(7, 42)) + # mypy 2.4 reports assignments to a deprecated settable property, not reads of + # it: the last three lines, which read QGKMeansParameters attributes, may go + # unreported. Each of those attributes is also assigned above. + settable_reads = {39, 40, 41} + assert old_forms - settable_reads <= flagged <= old_forms, output + + +def test_current_forms_are_not_flagged(tmp_path): + flagged, output = deprecated_lines(tmp_path, CURRENT_USAGE) + assert not flagged, output + assert "Success: no issues found" in output, output