diff --git a/README.md b/README.md index ff4b9d8b..1b8e9684 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ -Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 500 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-32M) is the most performant static embedding model in the world. See our [results](results/README.md), read our [docs](https://minish.ai/packages/model2vec/introduction), or dive in to see how it works. +Model2Vec is a technique to turn any sentence transformer into a small, fast static embedding model. Model2Vec reduces model size by a factor up to 50 and makes models up to 30000 times faster, with a small drop in performance. Our [best model](https://huggingface.co/minishlab/potion-base-32M) is the most performant static embedding model in the world. See our [results](results/README.md), read our [docs](https://minish.ai/packages/model2vec/introduction), or dive in to see how it works. ## Quickstart @@ -107,7 +107,7 @@ For advanced usage, see our [training docs](https://minish.ai/packages/model2vec - **State-of-the-Art Performance**: Model2Vec models outperform any other static embeddings (such as GLoVe and BPEmb) by a large margin, as can be seen in our [results](results/README.md). - **Small**: Model2Vec reduces the size of a Sentence Transformer model by a factor of up to 50. Our [best model](https://huggingface.co/minishlab/potion-base-8M) is just ~30 MB on disk, and our smallest model just ~8 MB (making it the smallest model on [MTEB](https://huggingface.co/spaces/mteb/leaderboard)!). - **Lightweight Dependencies**: the base package's only major dependency is `numpy`. -- **Lightning-fast Inference**: up to 500 times faster on CPU than the original model. +- **Lightning-fast Inference**: up to 30000 times faster on CPU than the original model. - **Fast, Dataset-free Distillation**: distill your own model in 30 seconds on a CPU, without a dataset. - **Fine-tuning**: fine-tune Model2Vec models for classification, similarity, regression, or pair similarity, and run them without `torch`. - **Integrated in many popular libraries**: Model2Vec is integrated direclty into popular libraries such as [Sentence Transformers](https://github.com/UKPLab/sentence-transformers) and [LangChain](https://github.com/langchain-ai/langchain). For more information, see our [integrations documentation](https://minish.ai/packages/model2vec/integrations). @@ -147,7 +147,6 @@ We have performed extensive experiments to evaluate the performance of Model2Vec - [MMTEB Results](results/README.md#mmteb-results) - [Retrieval Results](results/README.md#retrieval-results) - [Training Results](results/README.md#training-results) -- [Ablations](results/README.md#ablations) ## Acknowledgements diff --git a/assets/images/speed_vs_mteb_plot.png b/assets/images/speed_vs_mteb_plot.png deleted file mode 100644 index 9911c42e..00000000 Binary files a/assets/images/speed_vs_mteb_plot.png and /dev/null differ diff --git a/assets/images/speed_vs_mteb_plot.svg b/assets/images/speed_vs_mteb_plot.svg new file mode 100644 index 00000000..2ed1a858 --- /dev/null +++ b/assets/images/speed_vs_mteb_plot.svg @@ -0,0 +1,2430 @@ + + + + + + + + 2026-11-25T14:47:08.005787 + image/svg+xml + + + Matplotlib v3.11.2, https://matplotlib.org/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/model2vec/inference/README.md b/model2vec/inference/README.md index 1a81099e..e90042c9 100644 --- a/model2vec/inference/README.md +++ b/model2vec/inference/README.md @@ -70,7 +70,7 @@ The report has the same format as the dictionary returned by scikit-learn's `cla `predict_proba` and `evaluate` raise an error for pipelines that predict vectors. -`predict` and `predict_proba` take the same encoding options as `StaticModel.encode`: `batch_size`, `max_length`, `show_progress_bar`, `use_multiprocessing` and `multiprocessing_threshold`. If `max_length` is not passed, the model's own `max_length` is used. Pass `max_length=None` to disable truncation. +`predict` and `predict_proba` take `max_length`, like `StaticModel.encode`. If `max_length` is not passed, the model's own `max_length` is used. Pass `max_length=None` to disable truncation. The underlying `StaticModel` is available as `pipeline.model`, and the head as `pipeline.head`. diff --git a/model2vec/inference/model.py b/model2vec/inference/model.py index eed28f7c..db2daa6b 100644 --- a/model2vec/inference/model.py +++ b/model2vec/inference/model.py @@ -4,7 +4,7 @@ from collections.abc import Sequence from pathlib import Path from tempfile import TemporaryDirectory -from typing import TypeVar, cast +from typing import Any, TypeVar, cast import huggingface_hub import numpy as np @@ -13,7 +13,7 @@ from model2vec.inference.evaluation import evaluate_single_or_multi_label from model2vec.inference.mlp import Activation, Layer, MLPHead -from model2vec.model import PathLike, StaticModel +from model2vec.model import PathLike, StaticModel, _warn_removed_arguments from model2vec.persistence import save_pretrained from model2vec.types import _UNSET, StaticModelConfig, _UnsetType @@ -71,24 +71,9 @@ def push_to_hub( _save_pipeline(self, temp_dir) push_folder_to_hub(Path(temp_dir), subfolder, repo_id, private, token) - def _encode_and_coerce_to_2d( - self, - X: Sequence[str], - show_progress_bar: bool, - max_length: int | None | _UnsetType, - batch_size: int, - use_multiprocessing: bool, - multiprocessing_threshold: int, - ) -> np.ndarray: + def _encode_and_coerce_to_2d(self, X: str | Sequence[str], max_length: int | None | _UnsetType) -> np.ndarray: """Encode the instances and coerce the output to a matrix.""" - encoded = self.model.encode( - X, - show_progress_bar=show_progress_bar, - max_length=max_length, - batch_size=batch_size, - use_multiprocessing=use_multiprocessing, - multiprocessing_threshold=multiprocessing_threshold, - ) + encoded = self.model.encode(X, max_length=max_length) if np.ndim(encoded) == 1: encoded = encoded[None, :] @@ -96,34 +81,24 @@ def _encode_and_coerce_to_2d( def predict( self, - X: Sequence[str], - show_progress_bar: bool = False, + X: str | Sequence[str], + *, max_length: int | None | _UnsetType = _UNSET, - batch_size: int = 1024, - use_multiprocessing: bool = True, - multiprocessing_threshold: int = 10_000, threshold: float = 0.5, + **kwargs: Any, ) -> np.ndarray: """Predict the labels of the input. :param X: The input data to predict. Can be a list of strings or a single string. - :param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False. :param max_length: The maximum length of the input sequences. If not passed, the encoder model's `max_length` is used. Pass `max_length=None` to disable truncation. - :param batch_size: The batch size for prediction. Defaults to 1024. - :param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True. - :param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000. :param threshold: The threshold for multilabel classification. Defaults to 0.5. Ignored if not multilabel. + :param **kwargs: Any additional arguments. These are ignored. The removed `batch_size`, + `show_progress_bar`, `use_multiprocessing` and `multiprocessing_threshold` raise a DeprecationWarning. :return: The predicted labels or probabilities. """ - encoded = self._encode_and_coerce_to_2d( - X, - show_progress_bar=show_progress_bar, - max_length=max_length, - batch_size=batch_size, - use_multiprocessing=use_multiprocessing, - multiprocessing_threshold=multiprocessing_threshold, - ) + _warn_removed_arguments(kwargs) + encoded = self._encode_and_coerce_to_2d(X, max_length=max_length) if self.head.activation == Activation.IDENTITY: return self.head.predict_regression(encoded) @@ -139,53 +114,45 @@ def predict( def predict_proba( self, - X: Sequence[str], - show_progress_bar: bool = False, + X: str | Sequence[str], + *, max_length: int | None | _UnsetType = _UNSET, - batch_size: int = 1024, - use_multiprocessing: bool = True, - multiprocessing_threshold: int = 10_000, + **kwargs: Any, ) -> np.ndarray: """Predict the labels of the input. :param X: The input data to predict. Can be a list of strings or a single string. - :param show_progress_bar: Whether to display a progress bar during prediction. Defaults to False. :param max_length: The maximum length of the input sequences. If not passed, the encoder model's `max_length` is used. Pass `max_length=None` to disable truncation. - :param batch_size: The batch size for prediction. Defaults to 1024. - :param use_multiprocessing: Whether to use multiprocessing for encoding. Defaults to True. - :param multiprocessing_threshold: The threshold for the number of samples to use multiprocessing. Defaults to 10,000. + :param **kwargs: Any additional arguments. These are ignored. The removed `batch_size`, + `show_progress_bar`, `use_multiprocessing` and `multiprocessing_threshold` raise a DeprecationWarning. :return: The predicted labels or probabilities. :raises ValueError: If the classifier type is projector. """ + _warn_removed_arguments(kwargs) if self.head.activation == Activation.IDENTITY: raise ValueError("You are using predict_proba on a projector model. This is not supported.") - encoded = self._encode_and_coerce_to_2d( - X, - show_progress_bar=show_progress_bar, - max_length=max_length, - batch_size=batch_size, - use_multiprocessing=use_multiprocessing, - multiprocessing_threshold=multiprocessing_threshold, - ) + encoded = self._encode_and_coerce_to_2d(X, max_length=max_length) return self.head.predict_proba(encoded) def evaluate( - self, X: Sequence[str], y: LabelType, batch_size: int = 1024, threshold: float = 0.5 + self, X: Sequence[str], y: LabelType, *, threshold: float = 0.5, **kwargs: Any ) -> dict[str, dict[str, float]]: """Evaluate the classifier on a given dataset using a classification report. :param X: The texts to predict on. :param y: The ground truth labels. - :param batch_size: The batch size. :param threshold: The threshold for multilabel classification. + :param **kwargs: Any additional arguments. These are ignored. The removed `batch_size`, + `show_progress_bar`, `use_multiprocessing` and `multiprocessing_threshold` raise a DeprecationWarning. :return: A classification report, as a dictionary. :raises ValueError: If the classifier type is projector. """ + _warn_removed_arguments(kwargs) if self.head.activation == Activation.IDENTITY: raise ValueError("You are using evaluate on a projector model. This is not supported.") - predictions = self.predict(X, show_progress_bar=True, batch_size=batch_size, threshold=threshold) + predictions = self.predict(X, threshold=threshold) return evaluate_single_or_multi_label(predictions=predictions, y=y) diff --git a/model2vec/model.py b/model2vec/model.py index 6f430984..f9a4304a 100644 --- a/model2vec/model.py +++ b/model2vec/model.py @@ -2,23 +2,20 @@ import copy import json -import math -import os -from collections import defaultdict -from collections.abc import Iterator, Sequence +import warnings +from collections.abc import Sequence from logging import getLogger from pathlib import Path from tempfile import TemporaryDirectory from typing import Any, Mapping, TypeVar, cast, overload +import model2vec_rs import numpy as np -from joblib import delayed +import numpy.typing as npt from tokenizers import Encoding, Tokenizer -from tqdm import tqdm from model2vec.quantization import DType, quantize_and_reduce_dim from model2vec.types import _UNSET, StaticModelConfig, _UnsetType -from model2vec.utils import ProgressParallel PathLike = Path | str @@ -43,8 +40,10 @@ def __init__( ) -> None: """Initialize the StaticModel. - :param vectors: The vectors to use. - :param tokenizer: The Transformers tokenizer to use. + :param vectors: The vectors to use. The model stores read-only views of `vectors`, `weights` and + `token_mapping`; assign new arrays to `embedding`, `weights` or `token_mapping` to change them. + :param tokenizer: The Transformers tokenizer to use. Stored as a copy. If you change `model.tokenizer` + in place, assign it again (`model.tokenizer = model.tokenizer`) for `encode` to use the changes. :param config: Any metadata config. Stored as a copy, so mutating it afterwards does not affect the model, and vice versa. :param normalize: Whether to normalize the embeddings. Defaults to False. This value is authoritative: @@ -75,9 +74,7 @@ def __init__( self.embedding = vectors self.weights = weights - # Convert to an array for fast lookups - # We can't use or short circuit here because np.ndarray as booleans are ambiguous. - self.token_mapping: np.ndarray | None = token_mapping + self.token_mapping = token_mapping self.tokenizer = copy.deepcopy(tokenizer) _disable_padding(self.tokenizer) @@ -90,6 +87,90 @@ def __init__( self.max_length = max_length self.normalize = normalize + def __getstate__(self) -> dict[str, Any]: + """Get the state for pickling, without the Rust backend.""" + state = self.__dict__.copy() + state.pop("_rust_backend", None) + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + """Restore the state from pickling, keeping the arrays read-only.""" + for name in ("embedding", "weights", "token_mapping"): + state[f"_{name}"] = _read_only(state.pop(f"_{name}", state.pop(name, None))) + state["_tokenizer"] = state.pop("_tokenizer", state.pop("tokenizer", None)) + self.__dict__.update(state) + + @property + def tokenizer(self) -> Tokenizer: + """The tokenizer. Assign it again after changing it in place, so that `encode` uses the changes.""" + return self._tokenizer + + @tokenizer.setter + def tokenizer(self, value: Tokenizer) -> None: + self._tokenizer = value + self.__dict__.pop("_rust_backend", None) + + @property + def embedding(self) -> np.ndarray: + """The read-only embedding matrix.""" + return self._embedding + + @embedding.setter + def embedding(self, value: np.ndarray) -> None: + self._embedding = _read_only(value) + + @property + def weights(self) -> np.ndarray | None: + """The read-only token weights, or None.""" + return self._weights + + @weights.setter + def weights(self, value: np.ndarray | None) -> None: + self._weights = _read_only(value) + + @property + def token_mapping(self) -> np.ndarray | None: + """The read-only mapping from token ids to rows of `embedding`, or None.""" + return self._token_mapping + + @token_mapping.setter + def token_mapping(self, value: np.ndarray | None) -> None: + self._token_mapping = _read_only(value) + + def _get_rust_backend(self) -> model2vec_rs.StaticModel: + """Get the Rust backend used by `encode`, rebuilding it if the vectors or tokenizer were assigned. + + Building the backend replaces `embedding` and `weights` with read-only views of the backend's memory + when their dtypes match. + + :return: The Rust backend. + """ + key = (self.embedding, self.weights, self.token_mapping) + cached = self.__dict__.get("_rust_backend") + if cached is not None and all(old is new for old, new in zip(cached[0], key)): + return cached[1] + embedding: npt.NDArray[np.float32] | npt.NDArray[np.int8] + if self.embedding.dtype == np.int8: + embedding = np.ascontiguousarray(self.embedding, dtype=np.int8) + else: + embedding = np.ascontiguousarray(self.embedding, dtype=np.float32) + backend = model2vec_rs.StaticModel.from_arrays( + self.tokenizer.to_str(), + embedding, + normalize=False, + weights=None if self.weights is None else np.ascontiguousarray(self.weights, dtype=np.float32), + token_mapping=( + None if self.token_mapping is None else np.ascontiguousarray(self.token_mapping, dtype=np.int64) + ), + ) + shared_embedding, shared_weights = backend.embeddings, backend.weights + if shared_embedding is not None and shared_embedding.dtype == self.embedding.dtype: + self.embedding = shared_embedding + if shared_weights is not None and self.weights is not None and self.weights.dtype == shared_weights.dtype: + self.weights = shared_weights + self._rust_backend = ((self.embedding, self.weights, self.token_mapping), backend) + return backend + @property def dim(self) -> int: """Get the dimension of the model.""" @@ -240,105 +321,22 @@ def _set_max_length_in_tokenizer(self, max_length: int | None) -> None: else: self.tokenizer.enable_truncation(max_length) - def _encode_dispatch( - self, - sentences: str | Sequence[str], - *, - max_length: int | None, - batch_size: int, - show_progress_bar: bool, - use_multiprocessing: bool, - multiprocessing_threshold: int, - batch_fn: Any, - batch_args: tuple[Any, ...] = (), - ) -> tuple[list[Any], bool]: - """Shared truncation, batching, and multiprocessing dispatch logic for `encode` and `encode_as_sequence`. - - :param sentences: The sentence or sentences to encode. - :param max_length: The maximum length of the sentences. Any tokens beyond this length are truncated. - :param batch_size: The batch size to use. - :param show_progress_bar: Whether to show the progress bar. - :param use_multiprocessing: Whether to use multiprocessing. - :param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing. - :param batch_fn: The function to apply to each batch of sentences. - :param batch_args: Additional positional arguments passed to `batch_fn` after the batch. - :return: A tuple of the per-batch results and whether the input was a single sentence. - """ - was_single = False - if isinstance(sentences, str): - sentences = [sentences] - was_single = True - if max_length is not None: - m = max_length * self.median_token_length - sentences = [sentence[:m] for sentence in sentences] - - sentence_batches = list(self._batch(sentences, batch_size)) - total_batches = math.ceil(len(sentences) / batch_size) - - self._set_max_length_in_tokenizer(max_length) - previous_parallelism = os.environ.get("TOKENIZERS_PARALLELISM") - try: - if use_multiprocessing and len(sentences) > multiprocessing_threshold: - # Disable parallelism for tokenizers - os.environ["TOKENIZERS_PARALLELISM"] = "false" - - results = ProgressParallel( - n_jobs=-1, backend="threading", use_tqdm=show_progress_bar, total=total_batches - )(delayed(batch_fn)(batch, *batch_args) for batch in sentence_batches) - else: - results = [ - batch_fn(batch, *batch_args) - for batch in tqdm(sentence_batches, total=total_batches, disable=not show_progress_bar) - ] - finally: - self._set_max_length_in_tokenizer(self.max_length) - if previous_parallelism is None: - os.environ.pop("TOKENIZERS_PARALLELISM", None) - else: - os.environ["TOKENIZERS_PARALLELISM"] = previous_parallelism - - return results, was_single - @overload - def encode_as_sequence( - self, - sentences: str, - *, - max_length: int | None = None, - batch_size: int = 1024, - show_progress_bar: bool = False, - use_multiprocessing: bool = True, - multiprocessing_threshold: int = 10_000, - ) -> np.ndarray: ... + def encode_as_sequence(self, sentences: str, *, max_length: int | None = None, **kwargs: Any) -> np.ndarray: ... @overload def encode_as_sequence( - self, - sentences: list[str], - *, - max_length: int | None = None, - batch_size: int = 1024, - show_progress_bar: bool = False, - use_multiprocessing: bool = True, - multiprocessing_threshold: int = 10_000, + self, sentences: list[str], *, max_length: int | None = None, **kwargs: Any ) -> list[np.ndarray]: ... def encode_as_sequence( - self, - sentences: str | list[str], - *, - max_length: int | None = None, - batch_size: int = 1024, - show_progress_bar: bool = False, - use_multiprocessing: bool = True, - multiprocessing_threshold: int = 10_000, + self, sentences: str | list[str], *, max_length: int | None = None, **kwargs: Any ) -> list[np.ndarray] | np.ndarray: """Encode a list of sentences as a list of numpy arrays of tokens. This is useful if you want to use the tokens for further processing, or if you want to do sequence modeling. - Note that if you just want the mean, you should use the `encode` method. - This is about twice as slow. + Note that if you just want the mean, you should use the `encode` method, which is much faster. Sentences that do not contain any tokens will be turned into an empty array. Unlike `encode`, this method ignores the model's `max_length`: truncation is only applied if you explicitly pass `max_length` here. @@ -349,100 +347,66 @@ def encode_as_sequence( :param sentences: The list of sentences to encode. :param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated. If this is None, no truncation is done. Note that this is independent of the model's `max_length`. - :param batch_size: The batch size to use. - :param show_progress_bar: Whether to show the progress bar. - :param use_multiprocessing: Whether to use multiprocessing. - By default, this is enabled for inputs > multiprocessing_threshold sentences and disabled otherwise. - :param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing. + :param **kwargs: Any additional arguments. These are ignored. The removed `batch_size`, + `show_progress_bar`, `use_multiprocessing` and `multiprocessing_threshold` raise a DeprecationWarning. :return: The encoded sentences with an embedding per token. """ - results, was_single = self._encode_dispatch( - sentences, - max_length=max_length, - batch_size=batch_size, - show_progress_bar=show_progress_bar, - use_multiprocessing=use_multiprocessing, - multiprocessing_threshold=multiprocessing_threshold, - batch_fn=self._encode_batch_as_sequence, - ) - out_array: list[np.ndarray] = [] - for r in results: - out_array.extend(r) + _warn_removed_arguments(kwargs) + was_single = isinstance(sentences, str) + sentence_list: list[str] = [sentences] if isinstance(sentences, str) else list(sentences) + if max_length is not None: + m = max_length * self.median_token_length + sentence_list = [sentence[:m] for sentence in sentence_list] - if was_single: - return out_array[0] - return out_array - - def _encode_batch_as_sequence(self, sentences: Sequence[str]) -> list[np.ndarray]: - """Encode a batch of sentences as a sequence.""" - ids = self.tokenize(sentences=sentences) - out: list[np.ndarray] = [] - for id_list in ids: - if id_list: - out.append(self._encode_helper(id_list)) - else: - out.append(np.zeros((0, self.dim))) + self._set_max_length_in_tokenizer(max_length) + try: + ids = self.tokenize(sentence_list) + finally: + self._set_max_length_in_tokenizer(self.max_length) + out = [self._encode_helper(id_list) if id_list else np.zeros((0, self.dim)) for id_list in ids] + if was_single: + return out[0] return out def encode( self, - sentences: Sequence[str], + sentences: str | Sequence[str], *, - show_progress_bar: bool = False, max_length: int | None | _UnsetType = _UNSET, normalize: bool | None = None, - batch_size: int = 1024, - use_multiprocessing: bool = True, - multiprocessing_threshold: int = 10_000, **kwargs: Any, ) -> np.ndarray: """Encode a list of sentences. This function encodes a list of sentences by averaging the word embeddings of the tokens in the sentence. - For ease of use, we don't batch sentences together. NOTE: the return type is currently underspecified. In the case of a single string, this returns a 1D array, but in the case of a list of strings, this returns a 2D array. Not possible to implement in numpy currently. :param sentences: The list of sentences to encode. You can also pass a single sentence. - :param show_progress_bar: Whether to show the progress bar. :param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated. If this is None, no truncation is done. If not passed, the model's `max_length` is used. :param normalize: Whether to normalize the resulting embeddings. If not passed, the model's `normalize` setting is used. - :param batch_size: The batch size to use. - :param use_multiprocessing: Whether to use multiprocessing. - By default, this is enabled for inputs > multiprocessing_threshold sentences and disabled otherwise. - :param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing. - :param **kwargs: Any additional arguments. These are ignored. + :param **kwargs: Any additional arguments. These are ignored. The removed `batch_size`, + `show_progress_bar`, `use_multiprocessing` and `multiprocessing_threshold` raise a DeprecationWarning. :return: The encoded sentences. If a single sentence was passed, a vector is returned. """ + _warn_removed_arguments(kwargs) if isinstance(max_length, _UnsetType): max_length = self.max_length if normalize is None: normalize = self.normalize - results, was_single = self._encode_dispatch( - sentences, - max_length=max_length, - batch_size=batch_size, - show_progress_bar=show_progress_bar, - use_multiprocessing=use_multiprocessing, - multiprocessing_threshold=multiprocessing_threshold, - batch_fn=self._encode_batch, - batch_args=(normalize,), - ) - out_array = np.concatenate(results, axis=0) - - if was_single: - return out_array[0] - return out_array + out = self._get_rust_backend().encode(sentences, max_length=max_length, normalize=normalize) + if self.embedding.dtype != np.int8: + out = out.astype(self.embedding.dtype, copy=False) + return out def _encode_helper(self, id_list: list[int]) -> np.ndarray: """Helper function to encode a list of ids. - This function is used to deduplicate the logic in `encode` and `encode_as_sequence`. It retrieves the embeddings for the given list of ids, applying weights if available. :param id_list: A list of token ids. @@ -459,40 +423,6 @@ def _encode_helper(self, id_list: list[int]) -> np.ndarray: return emb - def _encode_batch(self, sentences: Sequence[str], normalize: bool) -> np.ndarray: - """Encode a batch of sentences.""" - ids = self.tokenize(sentences=sentences) - dtype = self.embedding.dtype - if dtype == np.int8: - dtype = np.dtype(np.float32) - out = np.zeros((len(ids), self.dim), dtype=dtype) - - if self.token_mapping is None and self.weights is None: - buckets: dict[int, list[int]] = defaultdict(list) - for i, id_list in enumerate(ids): - if id_list: - buckets[len(id_list)].append(i) - for _, indices in buckets.items(): - id_matrix = np.array([ids[i] for i in indices], dtype=np.int64) - out[indices] = self.embedding[id_matrix].mean(axis=1) - else: - for i, id_list in enumerate(ids): - if id_list: - emb = self._encode_helper(id_list) - out[i] = emb.mean(axis=0) - - if normalize: - out32 = out.astype(np.float32) - norm = np.linalg.norm(out32, axis=1, keepdims=True) + 1e-32 - return (out32 / norm).astype(out.dtype) - - return out - - @staticmethod - def _batch(sentences: Sequence[str], batch_size: int) -> Iterator[Sequence[str]]: - """Batch the sentences into equal-sized.""" - return (sentences[i : i + batch_size] for i in range(0, len(sentences), batch_size)) - def push_to_hub( self, repo_id: str, private: bool = False, token: str | None = None, subfolder: str | None = None ) -> None: @@ -638,4 +568,40 @@ def _get_unk_token_id(tokenizer: Tokenizer) -> int | None: return json.loads(tokenizer.to_str())["model"].get("unk_id") +_REMOVED_ARGUMENTS = ("batch_size", "show_progress_bar", "use_multiprocessing", "multiprocessing_threshold") + + +def _warn_removed_arguments(kwargs: Mapping[str, Any], stacklevel: int = 3) -> None: + """Warn about removed encoding arguments in `kwargs`. + + :param kwargs: The keyword arguments a method received. + :param stacklevel: The stack level of the warning, counted from this function. + """ + removed = [name for name in _REMOVED_ARGUMENTS if name in kwargs] + if removed: + warnings.warn( + f"{', '.join(f'`{name}`' for name in removed)} no longer have any effect and will be removed " + "in a future version.", + DeprecationWarning, + stacklevel=stacklevel, + ) + + +@overload +def _read_only(array: np.ndarray) -> np.ndarray: ... + + +@overload +def _read_only(array: np.ndarray | None) -> np.ndarray | None: ... + + +def _read_only(array: np.ndarray | None) -> np.ndarray | None: + """Return a read-only view of an array, leaving the array itself writable.""" + if array is None or not array.flags.writeable: + return array + view = array.view() + view.setflags(write=False) + return view + + T = TypeVar("T", bound=StaticModel) diff --git a/model2vec/modelcards/model_card_template.md b/model2vec/modelcards/model_card_template.md index 3e563a13..5ae023b6 100644 --- a/model2vec/modelcards/model_card_template.md +++ b/model2vec/modelcards/model_card_template.md @@ -4,7 +4,7 @@ # {{ model_name }} Model Card -This [Model2Vec](https://github.com/MinishLab/model2vec) model is a distilled version of {% if base_model %}the {{ base_model }}(https://huggingface.co/{{ base_model }}){% else %}a{% endif %} Sentence Transformer. It uses static embeddings, allowing text embeddings to be computed orders of magnitude faster on both GPU and CPU. It is designed for applications where computational resources are limited or where real-time performance is critical. Model2Vec models are the smallest, fastest, and most performant static embedders available. The distilled models are up to 50 times smaller and 500 times faster than traditional Sentence Transformers. +This [Model2Vec](https://github.com/MinishLab/model2vec) model is a distilled version of {% if base_model %}the {{ base_model }}(https://huggingface.co/{{ base_model }}){% else %}a{% endif %} Sentence Transformer. It uses static embeddings, allowing text embeddings to be computed orders of magnitude faster on both GPU and CPU. It is designed for applications where computational resources are limited or where real-time performance is critical. Model2Vec models are the smallest, fastest, and most performant static embedders available. The distilled models are up to 50 times smaller and 30000 times faster than traditional Sentence Transformers. ## Installation diff --git a/model2vec/onnx.py b/model2vec/onnx.py index ee901f13..efcd82ff 100644 --- a/model2vec/onnx.py +++ b/model2vec/onnx.py @@ -71,13 +71,13 @@ class TorchStaticModel(torch.nn.Module): def __init__(self, model: StaticModel) -> None: """Initialize the TorchStaticModel with a StaticModel instance.""" super().__init__() - embeddings = torch.from_numpy(model.embedding) + embeddings = torch.tensor(model.embedding) if embeddings.dtype in {torch.int8, torch.uint8}: embeddings = embeddings.to(torch.float16) self.embeddings = torch.nn.Embedding.from_pretrained(embeddings, freeze=True) # Vocabulary-quantized models look up ids through `token_mapping` and weigh tokens, like `_encode_helper` - token_mapping = None if model.token_mapping is None else torch.from_numpy(model.token_mapping).long() - weights = None if model.weights is None else torch.from_numpy(model.weights).to(embeddings.dtype) + token_mapping = None if model.token_mapping is None else torch.tensor(model.token_mapping, dtype=torch.long) + weights = None if model.weights is None else torch.tensor(model.weights, dtype=embeddings.dtype) self.register_buffer("token_mapping", token_mapping) self.register_buffer("weights", weights) self.normalize = model.normalize diff --git a/model2vec/train/base.py b/model2vec/train/base.py index 386b850f..e908b880 100644 --- a/model2vec/train/base.py +++ b/model2vec/train/base.py @@ -605,10 +605,10 @@ def _static_model_arguments(model: StaticModel, *, max_length: int | None | _Uns :return: The constructor arguments. """ model.embedding = np.nan_to_num(model.embedding) - weights = torch.from_numpy(model.weights) if model.weights is not None else None + weights = torch.tensor(model.weights) if model.weights is not None else None token_mapping = model.token_mapping.tolist() if model.token_mapping is not None else None return { - "vectors": torch.from_numpy(model.embedding), + "vectors": torch.tensor(model.embedding), "tokenizer": model.tokenizer, "token_mapping": token_mapping, "weights": weights, diff --git a/model2vec/utils.py b/model2vec/utils.py index 9c9ec666..648bb38e 100644 --- a/model2vec/utils.py +++ b/model2vec/utils.py @@ -5,47 +5,13 @@ from collections.abc import Iterator from importlib import import_module from importlib.metadata import metadata -from typing import Any, Protocol +from typing import Protocol import numpy as np -from joblib import Parallel -from tqdm import tqdm logger = logging.getLogger(__name__) -class ProgressParallel(Parallel): - """A drop-in replacement for joblib.Parallel that shows a tqdm progress bar.""" - - def __init__(self, use_tqdm: bool = True, total: int | None = None, *args: Any, **kwargs: Any) -> None: - """Initialize the ProgressParallel object. - - :param use_tqdm: Whether to show the progress bar. - :param total: Total number of tasks (batches) you expect to process. If None, - it updates the total dynamically to the number of dispatched tasks. - :param *args: Additional arguments to pass to `Parallel.__init__`. - :param **kwargs: Additional keyword arguments to pass to `Parallel.__init__`. - """ - self._use_tqdm = use_tqdm - self._total = total - super().__init__(*args, **kwargs) - - def __call__(self, *args: Any, **kwargs: Any) -> Any: - """Create a tqdm context.""" - with tqdm(disable=not self._use_tqdm, total=self._total) as self._pbar: - self._pbar = self._pbar - return super().__call__(*args, **kwargs) - - def print_progress(self) -> None: - """Hook called by joblib as tasks complete. We update the tqdm bar here.""" - if self._total is None: - # If no fixed total was given, we dynamically set the total - self._pbar.total = self.n_dispatched_tasks - # Move the bar to the number of completed tasks - self._pbar.n = self.n_completed_tasks - self._pbar.refresh() - - class SafeOpenProtocol(Protocol): """Protocol to fix safetensors safe open.""" diff --git a/pyproject.toml b/pyproject.toml index 5e1ee820..579430ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,12 +24,12 @@ classifiers = [ dependencies = [ "jinja2", - "joblib", "numpy", "safetensors", - "tokenizers>=0.20", + "tokenizers>=0.22,<1.0.0", "tqdm", "huggingface-hub>=1.0.0", + "model2vec-rs>=0.5.1,<0.6.0", ] [build-system] @@ -124,4 +124,4 @@ version = {attr = "model2vec.version.__version__"} [tool.uv] exclude-newer = "1 week" -exclude-newer-package = { skeletoken = false } +exclude-newer-package = { skeletoken = false , model2vec-rs = false} diff --git a/results/README.md b/results/README.md index bb253ab1..09096e99 100644 --- a/results/README.md +++ b/results/README.md @@ -5,22 +5,22 @@ This document contains the results of the Model2Vec project. The results are pre - [MMTEB Results (Multilingual)](#mmteb-results-multilingual) - [Retrieval Results](#retrieval-results) - [Training Results](#training-results) -- [Ablations](#ablations) ## MTEB Results (English) -Model2Vec is evaluated on MTEB, as well as two additional tasks: [PEARL](https://github.com/tigerchen52/PEARL) (a phrase representation task) and WordSim (a collection of _word_ similarity tasks). The results are shown in the table below. +Model2Vec is evaluated on MTEB. The results are shown in the table below. -Note: The `potion` and `M2V` models are our static models. +Note: The `blink`, `potion` and `M2V` models are our static models. -| Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim | -|:-----------------------|------------:|-------------:|--------:|--------:|------------:|-------:|-------:|-------:|-------:|--------:|----------:| -| [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) | 55.80 | 55.93 | 69.25 | 44.90 | 82.37 | 47.14 | 42.92 | 78.95 | 25.96 | 60.83 | 49.91 | -| [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | 52.83 | 52.13 | 71.70 | 41.25 | 78.17 | 42.45 | 32.67 | 73.93 | 24.74 | 55.37 | 55.15 | -| [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | 51.32 | 51.08 | 70.34 | 39.74 | 76.62 | 41.79 | 31.11 | 72.91 | 25.06 | 53.54 | 50.75 | -| [M2V_base_output](https://huggingface.co/minishlab/M2V_base_output) | 48.77 | 47.96 | 66.84 | 33.96 | 74.90 | 39.31 | 25.36 | 68.76 | 26.61 | 54.02 | 49.18 | -| [GloVe_300d](https://huggingface.co/sentence-transformers/average_word_embeddings_glove.6B.300d) | 45.49 | 45.82 | 62.73 | 37.10 | 72.48 | 38.28 | 21.80 | 61.52 | 26.81 | 45.65 | 43.05 | -| [BPEmb_50k_300d](https://github.com/bheinzerling/bpemb) | 42.33 | 41.74 | 61.72 | 35.17 | 57.86 | 37.26 | 15.36 | 55.30 | 29.49 | 47.56 | 41.28 | +| Model | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | +|:-----------------------|-------------:|--------:|--------:|------------:|-------:|-------:|-------:|-------:| +| [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) | 55.93 | 69.25 | 44.90 | 82.37 | 47.14 | 42.92 | 78.95 | 25.96 | +| [blink-8M](https://huggingface.co/minishlab/blink-8m) | 55.35 | 67.88 | 41.49 | 78.42 | 43.12 | 38.86 | 73.56 | 22.48 | +| [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) | 52.13 | 71.70 | 41.25 | 78.17 | 42.45 | 32.67 | 73.93 | 24.74 | +| [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) | 51.08 | 70.34 | 39.74 | 76.62 | 41.79 | 31.11 | 72.91 | 25.06 | +| [M2V_base_output](https://huggingface.co/minishlab/M2V_base_output) | 47.96 | 66.84 | 33.96 | 74.90 | 39.31 | 25.36 | 68.76 | 26.61 | +| [GloVe_300d](https://huggingface.co/sentence-transformers/average_word_embeddings_glove.6B.300d) | 45.82 | 62.73 | 37.10 | 72.48 | 38.28 | 21.80 | 61.52 | 26.81 | +| [BPEmb_50k_300d](https://github.com/bheinzerling/bpemb) | 41.74 | 61.72 | 35.17 | 57.86 | 37.26 | 15.36 | 55.30 | 29.49 |
@@ -36,13 +36,13 @@ For readability, the MTEB task names are abbreviated as follows: - Sum: Summarization
-The results show that [potion-base-32M](https://huggingface.co/minishlab/potion-base-32M) is the most performant static embedding model. It reaches 93.21% of the performance of [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) with an average MTEB score of 52.13 while being orders of magnitude faster. +The results show that [blink-8M](https://huggingface.co/minishlab/blink-8m) is the most performant static embedding model. It reaches 98.96% of the performance of [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) with an average MTEB score of 55.35 while being orders of magnitude faster. The figure below shows the relationship between the number of sentences per second and the average MTEB score. The circle sizes correspond to the number of parameters in the models (larger = more parameters). -This plot shows that the potion and M2V models are much faster than the other models, while still being competitive in terms of performance with the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model. -NOTE: for fairness of comparison, we disabled multiprocessing for Model2Vec for this benchmark. All sentence-transformers models are run with the [sentence-transformers](https://github.com/UKPLab/sentence-transformers) library's default settings for `encode`. +This plot shows that [blink-8M](https://huggingface.co/minishlab/blink-8m) is much faster than the other models, while still being competitive in terms of performance with the [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) model. +NOTE: all models encode the same 1,000 Wikipedia articles on CPU. Model2Vec models are truncated to 512 tokens, like [bge-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5). All sentence-transformers models are run with the [sentence-transformers](https://github.com/UKPLab/sentence-transformers) library's default settings for `encode`. The script is [make_speed_vs_mteb_plot.py](make_speed_vs_mteb_plot.py). -| ![Description](../assets/images/speed_vs_mteb_plot.png) | +| ![Average MTEB score plotted against samples per second](../assets/images/speed_vs_mteb_plot.svg) | |:--:| |*Figure: The average MTEB score plotted against sentences per second. The circle size indicates model size.*| @@ -149,27 +149,3 @@ The table below shows inference speed. The model2vec full finetune is about 80x | | tfidf | fasttext | model2vec + logreg | model2vec full finetune | setfit | minilm full finetune | |:-----------------|------:|---------:|-------------------:|------------------------:|-------:|---------------------:| | samples / second | 93718 | 96288 | 32869 | 81018 | 1010 | 274 | - - - -## Ablations - -To better understand the factors contributing to the performance of Model2Vec, we conducted a comprehensive set of ablation studies, covering various aspects of the model's architecture and preprocessing methods. In these studies, we examined the impact of key elements such as PCA, Zipf weighting, and the use of Sentence Transformers versus regular transformer models. We also compared the performance of input embeddings versus output embeddings, since it would seem plausible that these should also work well. The results are shown in the table below. - - -| Model | Avg (All) | Avg (MTEB) | Class | Clust | PairClass | Rank | Ret | STS | Sum | Pearl | WordSim | -|:-----------------------------|------------:|-------------:|--------:|--------:|------------:|-------:|------:|------:|------:|--------:|----------:| -| M2V_base_output | 46.79 | 45.34 | 61.25 | 25.58 | 74.9 | 47.63 | 26.14 | 68.58 | 29.2 | 54.02 | 49.18 | -| M2V_base_output_nopca | 44.04 | 42.31 | 61.42 | 20.15 | 68.21 | 44.67 | 25.25 | 61.87 | 29.85 | 51.02 | 48.96 | -| M2V_base_output_nozipf | 43.61 | 41.52 | 60.44 | 21.62 | 72.15 | 45.57 | 20.35 | 62.71 | 30.66 | 52.28 | 49.17 | -| M2V_base_input_nozipf_nopca | 40.97 | 39.55 | 54.16 | 18.62 | 68.3 | 43.65 | 23.63 | 59.38 | 32.04 | 50.19 | 40.52 | -| M2V_base_output_nozipf_nopca | 40.8 | 38.44 | 59.78 | 19.31 | 62.39 | 42.26 | 19.01 | 55.16 | 30 | 49.09 | 48.97 | -| M2V_base_input | 40.74 | 39.93 | 60.35 | 22.66 | 59.63 | 43.02 | 25.47 | 50.05 | 29.35 | 50.61 | 34.47 | -| M2V_bert_output_nozipf_nopca | 35.54 | 34.82 | 55.69 | 15.42 | 58.68 | 39.87 | 12.92 | 55.24 | 30.15 | 46.9 | 26.72 | - - -There's four main findings in these results: -1. Non-Sentence Transformers do not work well. This can be seen by comparing `M2V_bert_output_nozipf_nopca` (which uses [BERT](https://huggingface.co/google-bert/bert-base-uncased), a non-Sentence Transformer) and `M2V_base_output_nozipf_nopca` (which uses [BGE-base](https://huggingface.co/BAAI/bge-base-en-v1.5), a Sentence Transformer). Using a Sentence Transformer gives a ~5.2% increase in performance. -2. PCA is crucial for performance. This can be seen by comparing `M2V_base_output_nozipf_nopca` and `M2V_base_output_nozipf` which gives a ~2.8% increase in performance. Furthermore, PCA improves performance on _all_ tasks. -3. Zipf weighting is crucial for performance. This can be seen by comparing `M2V_base_output_nozipf_nopca` and `M2V_base_output_nopca` which gives a ~3.1% increase in performance. -4. Output embeddings outperform input embeddings. This can be seen by comparing `M2V_base_input` and `M2V_base_output` which gives a ~6.1% increase in performance. Note that input embeddings do work well for some tasks. We hypothesize that this is because input embeddings are inherently normalized. diff --git a/results/make_speed_vs_mteb_plot.py b/results/make_speed_vs_mteb_plot.py index b7a48e70..4ecb77ac 100644 --- a/results/make_speed_vs_mteb_plot.py +++ b/results/make_speed_vs_mteb_plot.py @@ -2,29 +2,16 @@ import argparse import logging +from dataclasses import dataclass from pathlib import Path from time import perf_counter -from typing import Any +from typing import Any, Protocol +import matplotlib.pyplot as plt import numpy as np -import pandas as pd -from bpemb import BPEmb from datasets import load_dataset -from plotnine import ( - aes, - element_line, - geom_point, - geom_text, - ggplot, - guides, - labs, - scale_size, - scale_y_continuous, - theme, - theme_classic, - xlim, - ylim, -) +from matplotlib.lines import Line2D +from matplotlib.ticker import FixedLocator, FuncFormatter, NullLocator from sentence_transformers import SentenceTransformer from model2vec import StaticModel @@ -34,138 +21,205 @@ logger = logging.getLogger(__name__) -class BPEmbEmbedder: - def __init__(self, vs: int = 50_000, dim: int = 300) -> None: - """Initialize the BPEmbEmbedder.""" - self.bpemb_en = BPEmb(lang="en", vs=vs, dim=dim) +MAX_LENGTH = 512 - def mean_sentence_embedding(self, sentence: str) -> np.ndarray: - """Encode a sentence to a mean embedding.""" - encoded_ids = self.bpemb_en.encode_ids(sentence) - embeddings = self.bpemb_en.vectors[encoded_ids] - if embeddings.size == 0: - return np.zeros(self.bpemb_en.dim) # Return a zero vector if no tokens are found - return embeddings.mean(axis=0) +class Encoder(Protocol): def encode(self, sentences: list[str], **kwargs: Any) -> np.ndarray: - """Encode a list of sentences to embeddings.""" - return np.array([self.mean_sentence_embedding(sentence.lower()) for sentence in sentences]) - - -def make_plot(df: pd.DataFrame) -> ggplot: + """Encode a list of sentences.""" + ... + + +@dataclass(frozen=True) +class Result: + name: str + path: str + kind: str + family: str + score: float + params_million: float + + +RESULTS: list[Result] = [ + Result("bge-base-en-v1.5", "BAAI/bge-base-en-v1.5", "ST", "Transformer", 60.77, 109.0), + Result("all-MiniLM-L6-v2", "sentence-transformers/all-MiniLM-L6-v2", "ST", "Transformer", 55.93, 23.0), + Result( + "GloVe 6B 300d", + "sentence-transformers/average_word_embeddings_glove.6B.300d", + "ST", + "Word embeddings", + 45.82, + 120.0, + ), + Result("blink-8M", "minishlab/blink-8m", "M2V", "Model2Vec", 55.35, 7.68), +] + +# Cached speeds (samples/sec, best run on CPU over 1k Wikipedia texts, truncated to 512 tokens). +# Re-run with --force-benchmark to update these values. +CACHED_SPEEDS: dict[str, float] = { + "all-MiniLM-L6-v2": 100.40, + "bge-base-en-v1.5": 10.72, + "GloVe 6B 300d": 480.87, + "blink-8M": 218288.95, +} + +SURFACE = "#fcfcfb" +TEXT_PRIMARY = "#0b0b0b" +TEXT_SECONDARY = "#52514e" +TEXT_MUTED = "#8a8984" +GRID = "#e8e7e3" +FAMILY_COLORS: dict[str, str] = { + "Model2Vec": "#2a78d6", + "Transformer": "#eb6834", + "Word embeddings": "#1baf7a", +} + + +def _marker_area(params_million: float) -> float: + """Marker area in points², proportional to the number of parameters.""" + return 40 + 6 * params_million + + +def _format_speed(value: float, _: Any) -> str: + """Format a tick on the speed axis, e.g. 10k.""" + for divisor, suffix in ((1e6, "M"), (1e3, "k")): + if value >= divisor: + return f"{value / divisor:g}{suffix}" + return f"{value:g}" + + +def make_plot(speeds: dict[str, float]) -> plt.Figure: """Create a plot of the MTEB score vs samples per second.""" - df["label_y"] = ( - df["Average score"] - + 0.2 # a constant "base" offset for all bubbles - + 0.08 * np.sqrt(df["Params (Million)"]) + plt.rcParams.update( + { + "font.family": "sans-serif", + "font.sans-serif": ["Inter", "Helvetica Neue", "Helvetica", "Arial", "DejaVu Sans"], + "svg.fonttype": "path", + } ) - plot = ( - ggplot(df, aes(x="Samples per second", y="Average score")) - + geom_point(aes(size="Params (Million)", color="Model")) - + geom_text(aes(y="label_y", label="Model"), color="black", size=7) - + scale_size(range=(2, 30)) - + theme_classic() - + labs(title="Average MTEB Score vs Samples per Second") - + ylim(df["Average score"].min(), df["Average score"].max() + 3) - + scale_y_continuous(breaks=range(30, 70, 5)) - + theme( - panel_grid_major=element_line(color="lightgrey", size=0.5), - panel_grid_minor=element_line(color="lightgrey", size=0.25), - figure_size=(10, 6), + fig, ax = plt.subplots(figsize=(9, 5.6), facecolor=SURFACE) + ax.set_facecolor(SURFACE) + + for result in sorted(RESULTS, key=lambda result: -result.params_million): + speed = speeds[result.name] + area = _marker_area(result.params_million) + ax.scatter( + speed, + result.score, + s=area, + color=FAMILY_COLORS[result.family], + edgecolors=SURFACE, + linewidths=2, + zorder=3, ) - + xlim(0, df["Samples per second"].max() + 100) - + guides(None) + ax.annotate( + result.name, + (speed, result.score), + xytext=(np.sqrt(area) / 2 + 6, 0), + textcoords="offset points", + va="center", + fontsize=9, + color=TEXT_SECONDARY, + zorder=4, + ) + + ax.set_xscale("log") + ax.set_xlim(5, 2.5e6) + ax.xaxis.set_major_locator(FixedLocator([10**exponent for exponent in range(1, 7)])) + ax.xaxis.set_minor_locator(NullLocator()) + ax.xaxis.set_major_formatter(FuncFormatter(_format_speed)) + ax.set_ylim(44, 63) + ax.set_yticks(range(45, 65, 5)) + + ax.grid(True, color=GRID, linewidth=1) + ax.set_axisbelow(True) + for side in ("top", "right", "left"): + ax.spines[side].set_visible(False) + ax.spines["bottom"].set_color(TEXT_MUTED) + ax.tick_params(colors=TEXT_SECONDARY, labelsize=9, length=0, pad=6) + + ax.set_xlabel("Samples per second (log scale)", color=TEXT_SECONDARY, fontsize=10, labelpad=8) + ax.set_ylabel("Average MTEB score", color=TEXT_SECONDARY, fontsize=10, labelpad=8) + + fig.text(0.06, 0.95, "MTEB score vs. encoding speed", fontsize=14, weight="bold", color=TEXT_PRIMARY) + fig.text( + 0.06, + 0.905, + f"CPU, 1k Wikipedia articles truncated to {MAX_LENGTH} tokens. Circle area is proportional to the number of parameters.", + fontsize=9.5, + color=TEXT_SECONDARY, ) - return plot + handles = [ + Line2D([], [], marker="o", linestyle="", markersize=8, color=color, markeredgecolor=SURFACE, label=family) + for family, color in FAMILY_COLORS.items() + ] + ax.legend( + handles=handles, + loc="upper center", + ncol=len(handles), + frameon=False, + fontsize=9, + labelcolor=TEXT_SECONDARY, + handletextpad=0.3, + columnspacing=1.6, + ) + + fig.subplots_adjust(left=0.08, right=0.97, top=0.85, bottom=0.11) + return fig + + +def load_model(path: str, kind: str) -> Encoder: + """Load a model of the given kind.""" + if kind == "ST": + return SentenceTransformer(path, device="cpu") + return StaticModel.from_pretrained(path) -def benchmark_model(name: str, info: list[str], texts: list[str]) -> dict[str, float | str]: - """Benchmark a single model.""" - logger.info("Starting", name) - if info[1] == "BPEmb": - model = BPEmbEmbedder(vs=50_000, dim=300) # type: ignore - elif info[1] == "ST": - model = SentenceTransformer(info[0], device="cpu") # type: ignore - else: - model = StaticModel.from_pretrained(info[0]) # type: ignore - start = perf_counter() - if info[1] == "M2V": - # If the model is a model2vec model, disable multiprocessing for a fair comparison - model.encode(texts, use_multiprocessing=False) - else: - model.encode(texts) +def benchmark_model(name: str, path: str, kind: str, texts: list[str], n_runs: int, min_seconds: float) -> float: + """Benchmark a single model, returning the best samples per second. - total_time = perf_counter() - start - docs_per_second = len(texts) / total_time + Runs at least `n_runs` times, and keeps running until `min_seconds` have passed in total. + Static models are truncated to `MAX_LENGTH` tokens, like the transformer models. + """ + logger.info("Starting %s", name) + model = load_model(path, kind) + encode_kwargs = {"max_length": MAX_LENGTH} if kind == "M2V" else {} + model.encode(texts[:16], **encode_kwargs) - logger.info(f"{name}: {docs_per_second} docs per second") - logger.info(f"Total time: {total_time}") + best_seconds = float("inf") + total_seconds = 0.0 + runs = 0 + while runs < n_runs or total_seconds < min_seconds: + start = perf_counter() + model.encode(texts, **encode_kwargs) + elapsed = perf_counter() - start + best_seconds = min(best_seconds, elapsed) + total_seconds += elapsed + runs += 1 - return {"docs_per_second": docs_per_second, "total_time": total_time} + docs_per_second = len(texts) / best_seconds + logger.info("%s: %.2f docs per second (best of %d runs: %.4fs)", name, docs_per_second, runs, best_seconds) + return docs_per_second -def main(save_path: str, n_texts: int, force_benchmark: bool) -> None: +def main(save_path: str, n_texts: int, n_runs: int, min_seconds: float, force_benchmark: bool) -> None: """Benchmark text embedding models and generate a plot.""" save_dir = Path(save_path) save_dir.mkdir(parents=True, exist_ok=True) - # Cached speeds (samples/sec, measured on CPU with 1k Wikipedia texts). - # Re-run with --force-benchmark to update these values. - cached_speeds: dict[str, float] = { - "BPEmb-50k-300d": 84.39, - "all-MiniLM-L6-v2": 62.00, - "bge-base-en-v1.5": 7.42, - "GloVe 6B 300d": 538.39, - "potion-base-8M": 5165.96, - } - - summarized_results = [ - {"Model": "potion-base-2M", "Average score": 47.49, "Samples per second": None, "Params (Million)": 1.875}, - {"Model": "GloVe 6B 300d", "Average score": 45.82, "Samples per second": None, "Params (Million)": 120.000}, - {"Model": "potion-base-4M", "Average score": 49.77, "Samples per second": None, "Params (Million)": 3.750}, - {"Model": "all-MiniLM-L6-v2", "Average score": 55.93, "Samples per second": None, "Params (Million)": 23.000}, - {"Model": "potion-base-8M", "Average score": 51.08, "Samples per second": None, "Params (Million)": 7.500}, - {"Model": "bge-base-en-v1.5", "Average score": 60.77, "Samples per second": None, "Params (Million)": 109.000}, - {"Model": "BPEmb-50k-300d", "Average score": 41.74, "Samples per second": None, "Params (Million)": 15.000}, - {"Model": "potion-base-32M", "Average score": 52.13, "Samples per second": None, "Params (Million)": 32.300}, - ] - + speeds = dict(CACHED_SPEEDS) if force_benchmark: - models: dict[str, list[str]] = { - "BPEmb-50k-300d": ["", "BPEmb"], - "all-MiniLM-L6-v2": ["sentence-transformers/all-MiniLM-L6-v2", "ST"], - "bge-base-en-v1.5": ["BAAI/bge-base-en-v1.5", "ST"], - "GloVe 6B 300d": ["sentence-transformers/average_word_embeddings_glove.6B.300d", "ST"], - "potion-base-8M": ["minishlab/potion-base-8M", "M2V"], - } ds = load_dataset("wikimedia/wikipedia", data_files="20231101.en/train-00000-of-00041.parquet")["train"] texts = ds["text"][:n_texts] - for name, info in models.items(): - timing = benchmark_model(name, info, texts) - cached_speeds[name] = float(timing["docs_per_second"]) - logger.info("Updated speeds: %s", cached_speeds) - - for result in summarized_results: - name = str(result["Model"]) - if name in cached_speeds: - result["Samples per second"] = cached_speeds[name] - - # Set potion-base-8M as the reference speed for the other M2V models - potion_base_8m_speed = next( - result["Samples per second"] for result in summarized_results if result["Model"] == "potion-base-8M" - ) - for model_name in ["potion-base-2M", "potion-base-4M", "potion-base-32M"]: - for result in summarized_results: - if result["Model"] == model_name: - result["Samples per second"] = potion_base_8m_speed + for result in RESULTS: + speeds[result.name] = benchmark_model(result.name, result.path, result.kind, texts, n_runs, min_seconds) + logger.info("Updated speeds: %s", speeds) - # Create and save the plot - df = pd.DataFrame(summarized_results) - plot = make_plot(df) - plot_path = save_dir / "speed_vs_mteb_plot.png" - plot.save(plot_path, width=12, height=10) - logger.info(f"Plot saved to {plot_path}") + fig = make_plot(speeds) + plot_path = save_dir / "speed_vs_mteb_plot.svg" + fig.savefig(plot_path, facecolor=SURFACE) + logger.info("Plot saved to %s", plot_path) if __name__ == "__main__": @@ -174,7 +228,13 @@ def main(save_path: str, n_texts: int, force_benchmark: bool) -> None: "--save-path", type=str, required=True, help="Directory to save the benchmark results and plot." ) parser.add_argument( - "--n-texts", type=int, default=100_000, help="Number of texts to use from the dataset for benchmarking." + "--n-texts", type=int, default=1_000, help="Number of texts to use from the dataset for benchmarking." + ) + parser.add_argument( + "--n-runs", type=int, default=3, help="Minimum number of timed runs per model; the best is kept." + ) + parser.add_argument( + "--min-seconds", type=float, default=2.0, help="Keep timing a model until this many seconds have passed." ) parser.add_argument( "--force-benchmark", @@ -183,4 +243,10 @@ def main(save_path: str, n_texts: int, force_benchmark: bool) -> None: ) args = parser.parse_args() - main(save_path=args.save_path, n_texts=args.n_texts, force_benchmark=args.force_benchmark) + main( + save_path=args.save_path, + n_texts=args.n_texts, + n_runs=args.n_runs, + min_seconds=args.min_seconds, + force_benchmark=args.force_benchmark, + ) diff --git a/tests/integration/pretrained_model_metrics.py b/tests/integration/pretrained_model_metrics.py index 66a5e76e..07522c81 100644 --- a/tests/integration/pretrained_model_metrics.py +++ b/tests/integration/pretrained_model_metrics.py @@ -50,13 +50,13 @@ def measure_encoding_speed(model: StaticModel) -> dict[str, float]: :param model: The model to benchmark. :return: Best-of-N sentences/second and tokens/second over `_SPEED_CORPUS`. """ - model.encode(_SPEED_CORPUS[:64], use_multiprocessing=False) + model.encode(_SPEED_CORPUS[:64]) n_tokens = sum(len(ids) for ids in model.tokenize(_SPEED_CORPUS)) best_seconds = float("inf") for _ in range(_SPEED_RUNS): start = time.perf_counter() - model.encode(_SPEED_CORPUS, use_multiprocessing=False) + model.encode(_SPEED_CORPUS) best_seconds = min(best_seconds, time.perf_counter() - start) return { diff --git a/tests/integration/test_onnx_export.py b/tests/integration/test_onnx_export.py index e49fd7fd..4b9d85f8 100644 --- a/tests/integration/test_onnx_export.py +++ b/tests/integration/test_onnx_export.py @@ -63,7 +63,7 @@ def test_onnx_export_matches_encode_on_real_sentences(model: StaticModel, onnx_s onnx_output = onnx_session.run(None, {"input_ids": input_ids, "attention_mask": attention_mask})[0] assert isinstance(onnx_output, np.ndarray) - expected = model.encode(_SENTENCES, use_multiprocessing=False) + expected = model.encode(_SENTENCES) assert onnx_output.shape == expected.shape np.testing.assert_allclose(onnx_output, expected, rtol=1e-4, atol=1e-4) diff --git a/tests/test_export_to_onnx.py b/tests/test_export_to_onnx.py index 3aa1cef2..5489198b 100644 --- a/tests/test_export_to_onnx.py +++ b/tests/test_export_to_onnx.py @@ -68,7 +68,7 @@ def test_pipeline_onnx_matches_predict_proba(mock_inference_pipeline: StaticMode input_ids, attention_mask = _tokenize(mock_inference_pipeline, texts) onnx_output = _export(torch_model, input_ids, attention_mask, tmp_path / "model.onnx") - expected = mock_inference_pipeline.predict_proba(texts, use_multiprocessing=False) + expected = mock_inference_pipeline.predict_proba(texts) assert onnx_output.shape == expected.shape np.testing.assert_allclose(onnx_output, expected, atol=1e-4) @@ -141,7 +141,7 @@ def test_pipeline_onnx_matches_projector( input_ids, attention_mask = _tokenize(mock_inference_pipeline_projector, texts) onnx_output = _export(torch_model, input_ids, attention_mask, tmp_path / "model.onnx") - expected = mock_inference_pipeline_projector.predict(texts, use_multiprocessing=False) + expected = mock_inference_pipeline_projector.predict(texts) assert onnx_output.shape == expected.shape np.testing.assert_allclose(onnx_output, expected, atol=1e-4) @@ -159,7 +159,7 @@ def test_pipeline_onnx_matches_empty_head(mock_vectors: np.ndarray, mock_tokeniz input_ids, attention_mask = _tokenize(pipeline, texts) onnx_output = _export(torch_model, input_ids, attention_mask, tmp_path / "model.onnx") - expected = pipeline.predict(texts, use_multiprocessing=False) + expected = pipeline.predict(texts) np.testing.assert_allclose(onnx_output, expected, atol=1e-4) @@ -369,6 +369,6 @@ def test_pipeline_onnx_vocabulary_quantized(tmp_path: Path) -> None: input_ids, attention_mask = _tokenize(pipeline, texts) onnx_output = _export(torch_model, input_ids, attention_mask, tmp_path / "model.onnx") - expected = pipeline.predict_proba(texts, use_multiprocessing=False) + expected = pipeline.predict_proba(texts) np.testing.assert_allclose(onnx_output, expected, atol=1e-4) diff --git a/tests/test_inference.py b/tests/test_inference.py index 3fc8fb59..e1ce6993 100644 --- a/tests/test_inference.py +++ b/tests/test_inference.py @@ -75,6 +75,13 @@ def test_init_predict_proba(mock_inference_pipeline: StaticModelPipeline) -> Non assert mock_inference_pipeline.predict_proba(["dog"]).argmax(1).tolist() == [1] +@pytest.mark.parametrize("method", ["predict", "predict_proba"]) +def test_pipeline_removed_arguments_warn(mock_inference_pipeline: StaticModelPipeline, method: str) -> None: + """Test that the removed encoding arguments raise a DeprecationWarning in the pipeline.""" + with pytest.warns(DeprecationWarning, match="`use_multiprocessing`"): + getattr(mock_inference_pipeline, method)(["dog"], use_multiprocessing=False) + + def test_init_evaluate(mock_inference_pipeline: StaticModelPipeline) -> None: """Test successful init and evaluate with StaticModelPipeline.""" target: list[str] | list[list[str]] diff --git a/tests/test_model.py b/tests/test_model.py index aaf58665..270286b0 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -1,4 +1,3 @@ -import os from pathlib import Path import numpy as np @@ -102,35 +101,6 @@ def test_encode_as_sequence(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, assert np.allclose(means, encoded) -def test_encode_multiprocessing( - mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str] -) -> None: - """Test encoding with multiprocessing.""" - model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config) - # Generate a list of 15k inputs to test multiprocessing - sentences = ["word1 word2"] * 15_000 - encoded = model.encode(sentences, use_multiprocessing=True) - assert encoded.shape == (15000, 2) - - -@pytest.mark.parametrize("previous", [None, "true"]) -def test_encode_multiprocessing_restores_tokenizers_parallelism( - mock_vectors: np.ndarray, - mock_tokenizer: Tokenizer, - mock_config: dict[str, str], - monkeypatch: pytest.MonkeyPatch, - previous: str | None, -) -> None: - """Test that multiprocessing encoding restores TOKENIZERS_PARALLELISM.""" - if previous is None: - monkeypatch.delenv("TOKENIZERS_PARALLELISM", raising=False) - else: - monkeypatch.setenv("TOKENIZERS_PARALLELISM", previous) - model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config) - model.encode(["word1 word2"] * 15_000, use_multiprocessing=True) - assert os.environ.get("TOKENIZERS_PARALLELISM") == previous - - def test_encode_as_sequence_max_length( mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str] ) -> None: @@ -143,17 +113,6 @@ def test_encode_as_sequence_max_length( assert len(truncated[0]) < len(full[0]) -def test_encode_as_sequence_multiprocessing( - mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str] -) -> None: - """Test encoding of sentences as tokens with multiprocessing.""" - model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config) - # Generate a list of 15k inputs to test multiprocessing - sentences = ["word1 word2"] * 15_000 - encoded = model.encode_as_sequence(sentences, use_multiprocessing=True) - assert len(encoded) == 15_000 - - def test_encode_as_tokens_empty( mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str] ) -> None: @@ -380,3 +339,139 @@ def test_dim(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: d model = StaticModel(mock_vectors, mock_tokenizer, mock_config) assert model.dim == 2 assert model.dim == model.embedding.shape[1] + + +@pytest.mark.parametrize("normalize", [False, True]) +@pytest.mark.parametrize("max_length", [None, 1]) +def test_encode_matches_sequence_mean( + mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, normalize: bool, max_length: int | None +) -> None: + """Test that encode matches the mean of encode_as_sequence, with weights and a token mapping.""" + weights = np.linspace(0.5, 1.5, len(mock_vectors)).astype(np.float32) + token_mapping = np.array([0, 1, 2, 1, 0]) + model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, weights=weights, token_mapping=token_mapping) + sentences = ["word1 word2", "word3 word1 word2", "", "unknown"] + encoded = model.encode(sentences, normalize=normalize, max_length=max_length) + expected = np.stack( + [ + seq.mean(axis=0) if len(seq) else np.zeros(model.dim) + for seq in model.encode_as_sequence(sentences, max_length=max_length) + ] + ) + if normalize: + expected = expected / (np.linalg.norm(expected, axis=1, keepdims=True) + 1e-32) + assert encoded.dtype == model.embedding.dtype + np.testing.assert_allclose(encoded, expected, rtol=1e-5, atol=1e-7) + + +def test_encode_rust_backend_rebuilds(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: + """Test that the Rust backend is cached and rebuilt when the embedding is replaced.""" + model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer) + before = model.encode(["word1"]) + backend = model._get_rust_backend() + assert model._get_rust_backend() is backend + model.embedding = model.embedding * 2 + assert model._get_rust_backend() is not backend + np.testing.assert_allclose(model.encode(["word1"]), before * 2) + + +@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.int8]) +def test_arrays_are_read_only(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, dtype: type) -> None: + """Test that the model arrays cannot be changed in place, before or after encoding, and only by assignment.""" + import pickle + + model = StaticModel( + vectors=(mock_vectors * 10).astype(dtype), + tokenizer=mock_tokenizer, + weights=np.ones(len(mock_vectors), dtype=np.float32), + token_mapping=np.arange(len(mock_vectors)), + ) + for clone in (model, pickle.loads(pickle.dumps(model))): + for array in (clone.embedding, clone.weights, clone.token_mapping): + with pytest.raises(ValueError, match="read-only"): + array *= 2 + before = model.encode(["word1"]) + with pytest.raises(ValueError, match="read-only"): + model.embedding *= 2 + model.embedding = model.embedding * 2 + with pytest.raises(ValueError, match="read-only"): + model.embedding[0] = 0 + np.testing.assert_allclose(model.encode(["word1"]), before * 2) + np.testing.assert_allclose(model.encode(["word1"])[0], model.encode_as_sequence(["word1"])[0].mean(axis=0)) + + +@pytest.mark.parametrize("dtype", [np.float32, np.int8, np.float16, np.float64]) +def test_encode_shares_arrays_with_rust_backend( + mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, dtype: type +) -> None: + """Test that encoding swaps the arrays for views of the Rust backend's memory when their dtypes match.""" + original = (mock_vectors * 10).astype(dtype) + weights = np.ones(len(mock_vectors), dtype=np.float32) + model = StaticModel(vectors=original, tokenizer=mock_tokenizer, weights=weights) + expected = model.encode(["word1 word2"]) + backend = model._get_rust_backend() + + shared = dtype in (np.float32, np.int8) + assert np.shares_memory(model.embedding, backend.embeddings) == shared + assert np.shares_memory(model.embedding, original) != shared + assert np.shares_memory(model.weights, backend.weights) + assert model.embedding.dtype == dtype + np.testing.assert_array_equal(model.embedding, original) + np.testing.assert_array_equal(model.weights, weights) + assert model._get_rust_backend() is backend + np.testing.assert_array_equal(model.encode(["word1 word2"]), expected) + with pytest.raises(ValueError, match="read-only"): + model.embedding[0] = 0 + + +def test_input_arrays_stay_writable(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: + """Test that the model does not make the arrays it is given read-only.""" + vectors = mock_vectors.copy() + weights = np.ones(len(vectors), dtype=np.float32) + token_mapping = np.arange(len(vectors)) + model = StaticModel(vectors=vectors, tokenizer=mock_tokenizer, weights=weights, token_mapping=token_mapping) + model.encode(["word1"]) + for array in (vectors, weights, token_mapping): + assert array.flags.writeable + array[0] = 0 + + +def test_encode_rust_backend_rebuilds_on_tokenizer_assignment( + mock_vectors: np.ndarray, mock_tokenizer: Tokenizer +) -> None: + """Test that assigning the tokenizer rebuilds the Rust backend, so in-place changes are used.""" + from tokenizers.normalizers import Lowercase + + model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer) + before = model.encode(["WORD1"]) + backend = model._get_rust_backend() + model.tokenizer.normalizer = Lowercase() + model.tokenizer = model.tokenizer + assert model._get_rust_backend() is not backend + after = model.encode(["WORD1"]) + assert not np.allclose(before, after) + np.testing.assert_allclose(after, model.encode(["word1"])) + + +@pytest.mark.parametrize("method", ["encode", "encode_as_sequence"]) +def test_encode_removed_arguments_warn(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, method: str) -> None: + """Test that the removed encoding arguments raise a DeprecationWarning, and other arguments do not.""" + import warnings + + model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer) + with pytest.warns(DeprecationWarning, match="`batch_size`, `show_progress_bar`"): + getattr(model, method)(["word1"], show_progress_bar=True, batch_size=2) + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + getattr(model, method)(["word1"], something_else=True) + + +def test_pickle_and_copy_with_rust_backend(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: + """Test that a model with a built Rust backend can be pickled and copied.""" + import copy + import pickle + + model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer) + expected = model.encode(["word1 word2"]) + for clone in (pickle.loads(pickle.dumps(model)), copy.deepcopy(model), copy.copy(model)): + np.testing.assert_allclose(clone.encode(["word1 word2"]), expected) diff --git a/uv.lock b/uv.lock index eedafb80..691e7caf 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -368,6 +368,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "coloredlogs" +version = "15.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "humanfriendly" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cc/c7/eed8f27100517e8c0e6b923d5f0845d0cb99763da6fdee00478f91db7325/coloredlogs-15.0.1.tar.gz", hash = "sha256:7c991aa71a4577af2f82600d8f8f3a89f936baeaf9b50a9c197da014e5bf16b0", size = 278520, upload-time = "2021-06-11T10:22:45.202Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/06/3d6badcf13db419e25b07041d9c7b4a2c331d3f4e7134445ec5df57714cd/coloredlogs-15.0.1-py2.py3-none-any.whl", hash = "sha256:612ee75c546f53e92e70049c9dbfcc18c935a2b9a53b66085ce9ef6a6e5c0934", size = 46018, upload-time = "2021-06-11T10:22:42.561Z" }, +] + [[package]] name = "coverage" version = "7.13.5" @@ -827,6 +839,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a9/ae/8a3a16ea4d202cb641b51d2681bdd3d482c1c592d7570b3fa264730829ce/huggingface_hub-1.8.0-py3-none-any.whl", hash = "sha256:d3eb5047bd4e33c987429de6020d4810d38a5bef95b3b40df9b17346b7f353f2", size = 625208, upload-time = "2026-03-25T16:01:26.603Z" }, ] +[[package]] +name = "humanfriendly" +version = "10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyreadline3", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cc/3f/2c29224acb2e2df4d2046e4c73ee2662023c58ff5b113c4c1adac0886c43/humanfriendly-10.0.tar.gz", hash = "sha256:6b0b831ce8f15f7300721aa49829fc4e83921a9a301cc7f606be6686a2288ddc", size = 360702, upload-time = "2021-09-17T21:40:43.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f0/0f/310fb31e39e2d734ccaa2c0fb981ee41f7bd5056ce9bc29b2248bd569169/humanfriendly-10.0-py2.py3-none-any.whl", hash = "sha256:1697e1a8a8f550fd43c2865cd84542fc175a61dcb779b6fee18cf6b6ccba1477", size = 86794, upload-time = "2021-09-17T21:40:39.897Z" }, +] + [[package]] name = "identify" version = "2.6.18" @@ -1238,7 +1262,7 @@ source = { editable = "." } dependencies = [ { name = "huggingface-hub" }, { name = "jinja2" }, - { name = "joblib" }, + { name = "model2vec-rs" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "numpy", version = "2.4.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "safetensors" }, @@ -1268,7 +1292,7 @@ integration = [ ] onnx = [ { name = "onnx" }, - { name = "onnxruntime", version = "1.24.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "onnxruntime", version = "1.23.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "onnxruntime", version = "1.28.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "onnxscript" }, { name = "skeletoken" }, @@ -1294,7 +1318,7 @@ requires-dist = [ { name = "huggingface-hub", specifier = ">=1.0.0" }, { name = "ipython", marker = "extra == 'dev'" }, { name = "jinja2" }, - { name = "joblib" }, + { name = "model2vec-rs", directory = "../model2vec-rs/python" }, { name = "mteb", marker = "extra == 'integration'" }, { name = "mypy", marker = "extra == 'dev'" }, { name = "numpy" }, @@ -1312,7 +1336,7 @@ requires-dist = [ { name = "skeletoken", marker = "extra == 'distill'", specifier = ">=0.6.0,<0.7.0" }, { name = "skeletoken", marker = "extra == 'onnx'", specifier = ">=0.6.0,<0.7.0" }, { name = "skops", marker = "extra == 'tests'" }, - { name = "tokenizers", specifier = ">=0.20" }, + { name = "tokenizers", specifier = ">=0.22,<1.0.0" }, { name = "torch", marker = "extra == 'distill'" }, { name = "torch", marker = "extra == 'onnx'" }, { name = "torch", marker = "extra == 'train'" }, @@ -1321,6 +1345,21 @@ requires-dist = [ ] provides-extras = ["dev", "distill", "onnx", "train", "quantization", "integration", "tests"] +[[package]] +name = "model2vec-rs" +source = { directory = "../model2vec-rs/python" } +dependencies = [ + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.4.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] + +[package.metadata] +requires-dist = [ + { name = "numpy" }, + { name = "pytest", marker = "extra == 'dev'" }, +] +provides-extras = ["dev"] + [[package]] name = "mpmath" version = "1.3.0" @@ -1966,12 +2005,13 @@ wheels = [ [[package]] name = "onnxruntime" -version = "1.24.3" +version = "1.23.2" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ + { name = "coloredlogs" }, { name = "flatbuffers" }, { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, { name = "packaging" }, @@ -1979,30 +2019,28 @@ dependencies = [ { name = "sympy" }, ] wheels = [ - { url = "https://files.pythonhosted.org/packages/15/41/3253db975a90c3ce1d475e2a230773a21cd7998537f0657947df6fb79861/onnxruntime-1.24.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3e6456801c66b095c5cd68e690ca25db970ea5202bd0c5b84a2c3ef7731c5a3c", size = 17332766, upload-time = "2026-03-05T17:18:59.714Z" }, - { url = "https://files.pythonhosted.org/packages/7e/c5/3af6b325f1492d691b23844d88ed26844c1164620860c5efe95c0e22782d/onnxruntime-1.24.3-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8b2ebc54c6d8281dccff78d4b06e47d4cf07535937584ab759448390a70f4978", size = 15130330, upload-time = "2026-03-05T16:34:53.831Z" }, - { url = "https://files.pythonhosted.org/packages/03/4b/f96b46c1866a293ed23ca2cf5e5a63d413ad3a951da60dd877e3c56cbbca/onnxruntime-1.24.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fb56575d7794bf0781156955610c9e651c9504c64d42ec880784b6106244882d", size = 17213247, upload-time = "2026-03-05T17:17:59.812Z" }, - { url = "https://files.pythonhosted.org/packages/36/13/27cf4d8df2578747584e8758aeb0b673b60274048510257f1f084b15e80e/onnxruntime-1.24.3-cp311-cp311-win_amd64.whl", hash = "sha256:c958222ef9eff54018332beecd32d5d94a3ab079d8821937b333811bf4da0d39", size = 12595530, upload-time = "2026-03-05T17:18:49.356Z" }, - { url = "https://files.pythonhosted.org/packages/19/8c/6d9f31e6bae72a8079be12ed8ba36c4126a571fad38ded0a1b96f60f6896/onnxruntime-1.24.3-cp311-cp311-win_arm64.whl", hash = "sha256:a8f761857ebaf58a85b9e42422d03207f1d39e6bb8fecfdbf613bac5b9710723", size = 12261715, upload-time = "2026-03-05T17:18:39.699Z" }, - { url = "https://files.pythonhosted.org/packages/d0/7f/dfdc4e52600fde4c02d59bfe98c4b057931c1114b701e175aee311a9bc11/onnxruntime-1.24.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:0d244227dc5e00a9ae15a7ac1eba4c4460d7876dfecafe73fb00db9f1d914d91", size = 17342578, upload-time = "2026-03-05T17:19:02.403Z" }, - { url = "https://files.pythonhosted.org/packages/1c/dc/1f5489f7b21817d4ad352bf7a92a252bd5b438bcbaa7ad20ea50814edc79/onnxruntime-1.24.3-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a9847b870b6cb462652b547bc98c49e0efb67553410a082fde1918a38707452", size = 15150105, upload-time = "2026-03-05T16:34:56.897Z" }, - { url = "https://files.pythonhosted.org/packages/28/7c/fd253da53594ab8efbefdc85b3638620ab1a6aab6eb7028a513c853559ce/onnxruntime-1.24.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b354afce3333f2859c7e8706d84b6c552beac39233bcd3141ce7ab77b4cabb5d", size = 17237101, upload-time = "2026-03-05T17:18:02.561Z" }, - { url = "https://files.pythonhosted.org/packages/71/5f/eaabc5699eeed6a9188c5c055ac1948ae50138697a0428d562ac970d7db5/onnxruntime-1.24.3-cp312-cp312-win_amd64.whl", hash = "sha256:44ea708c34965439170d811267c51281d3897ecfc4aa0087fa25d4a4c3eb2e4a", size = 12597638, upload-time = "2026-03-05T17:18:52.141Z" }, - { url = "https://files.pythonhosted.org/packages/cc/5c/d8066c320b90610dbeb489a483b132c3b3879b2f93f949fb5d30cfa9b119/onnxruntime-1.24.3-cp312-cp312-win_arm64.whl", hash = "sha256:48d1092b44ca2ba6f9543892e7c422c15a568481403c10440945685faf27a8d8", size = 12270943, upload-time = "2026-03-05T17:18:42.006Z" }, - { url = "https://files.pythonhosted.org/packages/51/8d/487ece554119e2991242d4de55de7019ac6e47ee8dfafa69fcf41d37f8ed/onnxruntime-1.24.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:34a0ea5ff191d8420d9c1332355644148b1bf1a0d10c411af890a63a9f662aa7", size = 17342706, upload-time = "2026-03-05T16:35:10.813Z" }, - { url = "https://files.pythonhosted.org/packages/dd/25/8b444f463c1ac6106b889f6235c84f01eec001eaf689c3eff8c69cf48fae/onnxruntime-1.24.3-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1fd2ec7bb0fabe42f55e8337cfc9b1969d0d14622711aac73d69b4bd5abb5ed7", size = 15149956, upload-time = "2026-03-05T16:34:59.264Z" }, - { url = "https://files.pythonhosted.org/packages/34/fc/c9182a3e1ab46940dd4f30e61071f59eee8804c1f641f37ce6e173633fb6/onnxruntime-1.24.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:df8e70e732fe26346faaeec9147fa38bef35d232d2495d27e93dd221a2d473a9", size = 17237370, upload-time = "2026-03-05T17:18:05.258Z" }, - { url = "https://files.pythonhosted.org/packages/05/7e/3b549e1f4538514118bff98a1bcd6481dd9a17067f8c9af77151621c9a5c/onnxruntime-1.24.3-cp313-cp313-win_amd64.whl", hash = "sha256:2d3706719be6ad41d38a2250998b1d87758a20f6ea4546962e21dc79f1f1fd2b", size = 12597939, upload-time = "2026-03-05T17:18:54.772Z" }, - { url = "https://files.pythonhosted.org/packages/80/41/9696a5c4631a0caa75cc8bc4efd30938fd483694aa614898d087c3ee6d29/onnxruntime-1.24.3-cp313-cp313-win_arm64.whl", hash = "sha256:b082f3ba9519f0a1a1e754556bc7e635c7526ef81b98b3f78da4455d25f0437b", size = 12270705, upload-time = "2026-03-05T17:18:44.774Z" }, - { url = "https://files.pythonhosted.org/packages/b7/65/a26c5e59e3b210852ee04248cf8843c81fe7d40d94cf95343b66efe7eec9/onnxruntime-1.24.3-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:72f956634bc2e4bd2e8b006bef111849bd42c42dea37bd0a4c728404fdaf4d34", size = 15161796, upload-time = "2026-03-05T16:35:02.871Z" }, - { url = "https://files.pythonhosted.org/packages/f3/25/2035b4aa2ccb5be6acf139397731ec507c5f09e199ab39d3262b22ffa1ac/onnxruntime-1.24.3-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78d1f25eed4ab9959db70a626ed50ee24cf497e60774f59f1207ac8556399c4d", size = 17240936, upload-time = "2026-03-05T17:18:09.534Z" }, - { url = "https://files.pythonhosted.org/packages/f9/a4/b3240ea84b92a3efb83d49cc16c04a17ade1ab47a6a95c4866d15bf0ac35/onnxruntime-1.24.3-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:a6b4bce87d96f78f0a9bf5cefab3303ae95d558c5bfea53d0bf7f9ea207880a8", size = 17344149, upload-time = "2026-03-05T16:35:13.382Z" }, - { url = "https://files.pythonhosted.org/packages/bb/4a/4b56757e51a56265e8c56764d9c36d7b435045e05e3b8a38bedfc5aedba3/onnxruntime-1.24.3-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d48f36c87b25ab3b2b4c88826c96cf1399a5631e3c2c03cc27d6a1e5d6b18eb4", size = 15151571, upload-time = "2026-03-05T16:35:05.679Z" }, - { url = "https://files.pythonhosted.org/packages/cf/14/c6fb84980cec8f682a523fcac7c2bdd6b311e7f342c61ce48d3a9cb87fc6/onnxruntime-1.24.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e104d33a409bf6e3f30f0e8198ec2aaf8d445b8395490a80f6e6ad56da98e400", size = 17238951, upload-time = "2026-03-05T17:18:12.394Z" }, - { url = "https://files.pythonhosted.org/packages/57/14/447e1400165aca8caf35dabd46540eb943c92f3065927bb4d9bcbc91e221/onnxruntime-1.24.3-cp314-cp314-win_amd64.whl", hash = "sha256:e785d73fbd17421c2513b0bb09eb25d88fa22c8c10c3f5d6060589efa5537c5b", size = 12903820, upload-time = "2026-03-05T17:18:57.123Z" }, - { url = "https://files.pythonhosted.org/packages/1d/ec/6b2fa5702e4bbba7339ca5787a9d056fc564a16079f8833cc6ba4798da1c/onnxruntime-1.24.3-cp314-cp314-win_arm64.whl", hash = "sha256:951e897a275f897a05ffbcaa615d98777882decaeb80c9216c68cdc62f849f53", size = 12594089, upload-time = "2026-03-05T17:18:47.169Z" }, - { url = "https://files.pythonhosted.org/packages/12/dc/cd06cba3ddad92ceb17b914a8e8d49836c79e38936e26bde6e368b62c1fe/onnxruntime-1.24.3-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4d4e70ce578aa214c74c7a7a9226bc8e229814db4a5b2d097333b81279ecde36", size = 15162789, upload-time = "2026-03-05T16:35:08.282Z" }, - { url = "https://files.pythonhosted.org/packages/a6/d6/413e98ab666c6fb9e8be7d1c6eb3bd403b0bea1b8d42db066dab98c7df07/onnxruntime-1.24.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:02aaf6ddfa784523b6873b4176a79d508e599efe12ab0ea1a3a6e7314408b7aa", size = 17240738, upload-time = "2026-03-05T17:18:15.203Z" }, + { url = "https://files.pythonhosted.org/packages/35/d6/311b1afea060015b56c742f3531168c1644650767f27ef40062569960587/onnxruntime-1.23.2-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:a7730122afe186a784660f6ec5807138bf9d792fa1df76556b27307ea9ebcbe3", size = 17195934, upload-time = "2025-10-27T23:06:14.143Z" }, + { url = "https://files.pythonhosted.org/packages/db/db/81bf3d7cecfbfed9092b6b4052e857a769d62ed90561b410014e0aae18db/onnxruntime-1.23.2-cp310-cp310-macosx_13_0_x86_64.whl", hash = "sha256:b28740f4ecef1738ea8f807461dd541b8287d5650b5be33bca7b474e3cbd1f36", size = 19153079, upload-time = "2025-10-27T23:05:57.686Z" }, + { url = "https://files.pythonhosted.org/packages/2e/4d/a382452b17cf70a2313153c520ea4c96ab670c996cb3a95cc5d5ac7bfdac/onnxruntime-1.23.2-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8f7d1fe034090a1e371b7f3ca9d3ccae2fabae8c1d8844fb7371d1ea38e8e8d2", size = 15219883, upload-time = "2025-10-22T03:46:21.66Z" }, + { url = "https://files.pythonhosted.org/packages/fb/56/179bf90679984c85b417664c26aae4f427cba7514bd2d65c43b181b7b08b/onnxruntime-1.23.2-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4ca88747e708e5c67337b0f65eed4b7d0dd70d22ac332038c9fc4635760018f7", size = 17370357, upload-time = "2025-10-22T03:46:57.968Z" }, + { url = "https://files.pythonhosted.org/packages/cd/6d/738e50c47c2fd285b1e6c8083f15dac1a5f6199213378a5f14092497296d/onnxruntime-1.23.2-cp310-cp310-win_amd64.whl", hash = "sha256:0be6a37a45e6719db5120e9986fcd30ea205ac8103fd1fb74b6c33348327a0cc", size = 13467651, upload-time = "2025-10-27T23:06:11.904Z" }, + { url = "https://files.pythonhosted.org/packages/44/be/467b00f09061572f022ffd17e49e49e5a7a789056bad95b54dfd3bee73ff/onnxruntime-1.23.2-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:6f91d2c9b0965e86827a5ba01531d5b669770b01775b23199565d6c1f136616c", size = 17196113, upload-time = "2025-10-22T03:47:33.526Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a8/3c23a8f75f93122d2b3410bfb74d06d0f8da4ac663185f91866b03f7da1b/onnxruntime-1.23.2-cp311-cp311-macosx_13_0_x86_64.whl", hash = "sha256:87d8b6eaf0fbeb6835a60a4265fde7a3b60157cf1b2764773ac47237b4d48612", size = 19153857, upload-time = "2025-10-22T03:46:37.578Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d8/506eed9af03d86f8db4880a4c47cd0dffee973ef7e4f4cff9f1d4bcf7d22/onnxruntime-1.23.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bbfd2fca76c855317568c1b36a885ddea2272c13cb0e395002c402f2360429a6", size = 15220095, upload-time = "2025-10-22T03:46:24.769Z" }, + { url = "https://files.pythonhosted.org/packages/e9/80/113381ba832d5e777accedc6cb41d10f9eca82321ae31ebb6bcede530cea/onnxruntime-1.23.2-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:da44b99206e77734c5819aa2142c69e64f3b46edc3bd314f6a45a932defc0b3e", size = 17372080, upload-time = "2025-10-22T03:47:00.265Z" }, + { url = "https://files.pythonhosted.org/packages/3a/db/1b4a62e23183a0c3fe441782462c0ede9a2a65c6bbffb9582fab7c7a0d38/onnxruntime-1.23.2-cp311-cp311-win_amd64.whl", hash = "sha256:902c756d8b633ce0dedd889b7c08459433fbcf35e9c38d1c03ddc020f0648c6e", size = 13468349, upload-time = "2025-10-22T03:47:25.783Z" }, + { url = "https://files.pythonhosted.org/packages/1b/9e/f748cd64161213adeef83d0cb16cb8ace1e62fa501033acdd9f9341fff57/onnxruntime-1.23.2-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:b8f029a6b98d3cf5be564d52802bb50a8489ab73409fa9db0bf583eabb7c2321", size = 17195929, upload-time = "2025-10-22T03:47:36.24Z" }, + { url = "https://files.pythonhosted.org/packages/91/9d/a81aafd899b900101988ead7fb14974c8a58695338ab6a0f3d6b0100f30b/onnxruntime-1.23.2-cp312-cp312-macosx_13_0_x86_64.whl", hash = "sha256:218295a8acae83905f6f1aed8cacb8e3eb3bd7513a13fe4ba3b2664a19fc4a6b", size = 19157705, upload-time = "2025-10-22T03:46:40.415Z" }, + { url = "https://files.pythonhosted.org/packages/3c/35/4e40f2fba272a6698d62be2cd21ddc3675edfc1a4b9ddefcc4648f115315/onnxruntime-1.23.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:76ff670550dc23e58ea9bc53b5149b99a44e63b34b524f7b8547469aaa0dcb8c", size = 15226915, upload-time = "2025-10-22T03:46:27.773Z" }, + { url = "https://files.pythonhosted.org/packages/ef/88/9cc25d2bafe6bc0d4d3c1db3ade98196d5b355c0b273e6a5dc09c5d5d0d5/onnxruntime-1.23.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f9b4ae77f8e3c9bee50c27bc1beede83f786fe1d52e99ac85aa8d65a01e9b77", size = 17382649, upload-time = "2025-10-22T03:47:02.782Z" }, + { url = "https://files.pythonhosted.org/packages/c0/b4/569d298f9fc4d286c11c45e85d9ffa9e877af12ace98af8cab52396e8f46/onnxruntime-1.23.2-cp312-cp312-win_amd64.whl", hash = "sha256:25de5214923ce941a3523739d34a520aac30f21e631de53bba9174dc9c004435", size = 13470528, upload-time = "2025-10-22T03:47:28.106Z" }, + { url = "https://files.pythonhosted.org/packages/3d/41/fba0cabccecefe4a1b5fc8020c44febb334637f133acefc7ec492029dd2c/onnxruntime-1.23.2-cp313-cp313-macosx_13_0_arm64.whl", hash = "sha256:2ff531ad8496281b4297f32b83b01cdd719617e2351ffe0dba5684fb283afa1f", size = 17196337, upload-time = "2025-10-22T03:46:35.168Z" }, + { url = "https://files.pythonhosted.org/packages/fe/f9/2d49ca491c6a986acce9f1d1d5fc2099108958cc1710c28e89a032c9cfe9/onnxruntime-1.23.2-cp313-cp313-macosx_13_0_x86_64.whl", hash = "sha256:162f4ca894ec3de1a6fd53589e511e06ecdc3ff646849b62a9da7489dee9ce95", size = 19157691, upload-time = "2025-10-22T03:46:43.518Z" }, + { url = "https://files.pythonhosted.org/packages/1c/a1/428ee29c6eaf09a6f6be56f836213f104618fb35ac6cc586ff0f477263eb/onnxruntime-1.23.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45d127d6e1e9b99d1ebeae9bcd8f98617a812f53f46699eafeb976275744826b", size = 15226898, upload-time = "2025-10-22T03:46:30.039Z" }, + { url = "https://files.pythonhosted.org/packages/f2/2b/b57c8a2466a3126dbe0a792f56ad7290949b02f47b86216cd47d857e4b77/onnxruntime-1.23.2-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8bace4e0d46480fbeeb7bbe1ffe1f080e6663a42d1086ff95c1551f2d39e7872", size = 17382518, upload-time = "2025-10-22T03:47:05.407Z" }, + { url = "https://files.pythonhosted.org/packages/4a/93/aba75358133b3a941d736816dd392f687e7eab77215a6e429879080b76b6/onnxruntime-1.23.2-cp313-cp313-win_amd64.whl", hash = "sha256:1f9cc0a55349c584f083c1c076e611a7c35d5b867d5d6e6d6c823bf821978088", size = 13470276, upload-time = "2025-10-22T03:47:31.193Z" }, + { url = "https://files.pythonhosted.org/packages/7c/3d/6830fa61c69ca8e905f237001dbfc01689a4e4ab06147020a4518318881f/onnxruntime-1.23.2-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9d2385e774f46ac38f02b3a91a91e30263d41b2f1f4f26ae34805b2a9ddef466", size = 15229610, upload-time = "2025-10-22T03:46:32.239Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ca/862b1e7a639460f0ca25fd5b6135fb42cf9deea86d398a92e44dfda2279d/onnxruntime-1.23.2-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2b9233c4947907fd1818d0e581c049c41ccc39b2856cc942ff6d26317cee145", size = 17394184, upload-time = "2025-10-22T03:47:08.127Z" }, ] [[package]] @@ -2684,6 +2722,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" }, ] +[[package]] +name = "pyreadline3" +version = "3.5.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b6/6d/f94028646d7bbe6d9d873c47ee7c246f2d29129d253f0d96cb6fcab70733/pyreadline3-3.5.6.tar.gz", hash = "sha256:61e53218b99656091ddb077df9e71f25850e72e030b6183b39c9b7e6e4f4a9bf", size = 100368, upload-time = "2026-05-14T17:55:04.471Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f7/5e/35c856e186b74678c24927847ad9895a51f1bc02a0c6126477a6c6040064/pyreadline3-3.5.6-py3-none-any.whl", hash = "sha256:8449b734232e42a5dcd74048e39b60db2839a4c38cf3ae2bf7707d58b5389c0d", size = 85243, upload-time = "2026-05-14T17:55:03.262Z" }, +] + [[package]] name = "pytest" version = "9.0.2"