From 839b6a41acb2b7c219e709c62c62b8530f425e22 Mon Sep 17 00:00:00 2001 From: stephantul Date: Sun, 22 Nov 2026 11:24:22 +0100 Subject: [PATCH 1/3] feat: add model2vec-rs --- README.md | 4 +- model2vec/inference/README.md | 2 +- model2vec/inference/model.py | 73 ++---- model2vec/model.py | 247 +++++------------- model2vec/modelcards/model_card_template.md | 2 +- model2vec/utils.py | 36 +-- pyproject.toml | 2 +- tests/integration/pretrained_model_metrics.py | 4 +- tests/integration/test_onnx_export.py | 2 +- tests/test_export_to_onnx.py | 8 +- tests/test_model.py | 86 +++--- uv.lock | 105 ++++++-- 12 files changed, 213 insertions(+), 358 deletions(-) diff --git a/README.md b/README.md index ff4b9d8b..019e18b1 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). 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..1e901665 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 @@ -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,23 @@ 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, such as the removed `show_progress_bar`, `batch_size` and + `use_multiprocessing`. These are ignored. :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, - ) + 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 +113,42 @@ 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, such as the removed `show_progress_bar`, `batch_size` and + `use_multiprocessing`. These are ignored. :return: The predicted labels or probabilities. :raises ValueError: If the classifier type is projector. """ 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, such as the removed `batch_size`. These are ignored. :return: A classification report, as a dictionary. :raises ValueError: If the classifier type is projector. """ 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..6b52554e 100644 --- a/model2vec/model.py +++ b/model2vec/model.py @@ -2,23 +2,19 @@ import copy import json -import math -import os -from collections import defaultdict -from collections.abc import Iterator, Sequence +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 @@ -90,6 +86,38 @@ 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 _get_rust_backend(self) -> model2vec_rs.StaticModel: + """Get the Rust backend used by `encode`, rebuilding it if the vectors or tokenizer were replaced. + + :return: The Rust backend. + """ + key = (self.embedding, self.weights, self.token_mapping, self.tokenizer) + 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) + ), + ) + self._rust_backend = (key, backend) + return backend + @property def dim(self) -> int: """Get the dimension of the model.""" @@ -240,105 +268,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,73 +294,49 @@ 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, such as the removed `batch_size`, `show_progress_bar`, + `use_multiprocessing` and `multiprocessing_threshold`. These are ignored. :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) + 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, such as the removed `show_progress_bar`, `batch_size` and + `use_multiprocessing`. These are ignored. :return: The encoded sentences. If a single sentence was passed, a vector is returned. """ if isinstance(max_length, _UnsetType): @@ -423,26 +344,14 @@ def encode( 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 +368,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: 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/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..94d1184f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,12 +24,12 @@ classifiers = [ dependencies = [ "jinja2", - "joblib", "numpy", "safetensors", "tokenizers>=0.20", "tqdm", "huggingface-hub>=1.0.0", + "model2vec-rs", ] [build-system] 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_model.py b/tests/test_model.py index aaf58665..1c016a1f 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,48 @@ 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) + + +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..d8546f91 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" }, @@ -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" From c812458df1f92bc51eb6632dbd0a09ffe2bc7045 Mon Sep 17 00:00:00 2001 From: stephantul Date: Sun, 22 Nov 2026 11:30:16 +0100 Subject: [PATCH 2/3] pin --- pyproject.toml | 4 ++-- uv.lock | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 94d1184f..e80e5317 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,10 +26,10 @@ dependencies = [ "jinja2", "numpy", "safetensors", - "tokenizers>=0.20", + "tokenizers>=0.22,<1.0.0", "tqdm", "huggingface-hub>=1.0.0", - "model2vec-rs", + "model2vec-rs>=0.5.0,<0.6.0", ] [build-system] diff --git a/uv.lock b/uv.lock index d8546f91..691e7caf 100644 --- a/uv.lock +++ b/uv.lock @@ -1336,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'" }, From 273d0bd59bc8f17cd4750cc9c5729b5e923043c8 Mon Sep 17 00:00:00 2001 From: stephantul Date: Sun, 22 Nov 2026 11:33:59 +0100 Subject: [PATCH 3/3] exclude model2vec-rs from exclude-newer --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index e80e5317..6ac15984 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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}