From 0332cd1ca363777bea52e5c6c702ab38b94b207b Mon Sep 17 00:00:00 2001 From: stephantul Date: Tue, 17 Nov 2026 19:31:33 +0100 Subject: [PATCH 1/4] feat: add sparse --- model2vec/model.py | 23 +- .../modelcards/sparse_model_card_template.md | 57 ++ model2vec/persistence/__init__.py | 4 +- model2vec/persistence/persistence.py | 126 ++++- model2vec/sparse.py | 522 ++++++++++++++++++ model2vec/types.py | 8 + model2vec/utils.py | 8 + pyproject.toml | 2 + tests/test_sparse.py | 470 ++++++++++++++++ uv.lock | 95 +++- 10 files changed, 1249 insertions(+), 66 deletions(-) create mode 100644 model2vec/modelcards/sparse_model_card_template.md create mode 100644 model2vec/sparse.py create mode 100644 tests/test_sparse.py diff --git a/model2vec/model.py b/model2vec/model.py index 6f430984..a595468e 100644 --- a/model2vec/model.py +++ b/model2vec/model.py @@ -9,12 +9,13 @@ from logging import getLogger from pathlib import Path from tempfile import TemporaryDirectory -from typing import Any, Mapping, TypeVar, cast, overload +from typing import Any, Generic, cast, overload import numpy as np from joblib import delayed from tokenizers import Encoding, Tokenizer from tqdm import tqdm +from typing_extensions import TypeVar from model2vec.quantization import DType, quantize_and_reduce_dim from model2vec.types import _UNSET, StaticModelConfig, _UnsetType @@ -28,12 +29,15 @@ _DEFAULT_NORMALIZE = False -class StaticModel: +ConfigT = TypeVar("ConfigT", bound=StaticModelConfig, default=StaticModelConfig) + + +class StaticModel(Generic[ConfigT]): def __init__( self, vectors: np.ndarray, tokenizer: Tokenizer, - config: Mapping[str, Any] | None = None, + config: ConfigT | None = None, normalize: bool = _DEFAULT_NORMALIZE, base_model_name: str | None = None, language: list[str] | None = None, @@ -67,9 +71,9 @@ def __init__( tokens, _ = zip(*sorted(tokenizer.get_vocab().items(), key=lambda x: x[1])) self.tokens = tokens - if token_mapping is None and len(vectors) != len(tokens): + if token_mapping is None and vectors.shape[0] != len(tokens): raise ValueError( - f"Number of tokens ({len(tokens)}) does not match number of vectors ({len(vectors)}). " + f"Number of tokens ({len(tokens)}) does not match number of vectors ({vectors.shape[0]}). " "Please provide a token mapping or ensure the number of tokens matches the number of vectors." ) @@ -84,7 +88,7 @@ def __init__( self.unk_token_id = _get_unk_token_id(self.tokenizer) self.median_token_length = int(np.median([len(token) for token in self.tokens])) - self.config: StaticModelConfig = cast(StaticModelConfig, {**config}) if config is not None else {} + self.config: ConfigT = cast(ConfigT, {**config} if config is not None else {}) self.base_model_name = base_model_name self.language = language self.max_length = max_length @@ -142,7 +146,7 @@ def embedding_dtype(self) -> str: @property def vocabulary_quantization(self) -> int | None: """Get the number of clusters used for vocabulary quantization, if applicable.""" - is_quantized = (self.token_mapping is not None) or (len(self.embedding) != len(self.tokens)) + is_quantized = (self.token_mapping is not None) or (self.embedding.shape[0] != len(self.tokens)) return int(self.embedding.shape[0]) if is_quantized else None def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None: @@ -528,7 +532,10 @@ def quantize_model( This needs to be < than the current model dimensionality. :return: A new StaticModel with the quantized embeddings. :raises ValueError: if the model is already quantized. + :raises NotImplementedError: if the model does not have dense embeddings. """ + if not isinstance(model.embedding, np.ndarray): + raise NotImplementedError("Quantization is only supported for models with dense embeddings.") token_mapping: np.ndarray | None weights: np.ndarray | None if vocabulary_quantization is not None: @@ -638,4 +645,4 @@ def _get_unk_token_id(tokenizer: Tokenizer) -> int | None: return json.loads(tokenizer.to_str())["model"].get("unk_id") -T = TypeVar("T", bound=StaticModel) +T = TypeVar("T", bound="StaticModel[Any]") diff --git a/model2vec/modelcards/sparse_model_card_template.md b/model2vec/modelcards/sparse_model_card_template.md new file mode 100644 index 00000000..d2aa5b43 --- /dev/null +++ b/model2vec/modelcards/sparse_model_card_template.md @@ -0,0 +1,57 @@ +--- +{{ card_data }} +--- + +# {{ model_name }} Model Card + +This is a sparse [Model2Vec](https://github.com/MinishLab/model2vec) model{% if base_model %} based on [{{ base_model }}](https://huggingface.co/{{ base_model }}){% endif %}. Each token has a static sparse code over the vocabulary, so sparse document and query vectors are computed with lookups alone, without running a neural network. + + +## Installation + +Install model2vec with the `sparse` extra using pip: +``` +pip install model2vec[sparse] +``` + +## Usage + +Load this model using the `from_pretrained` method of `SparseStaticModel`: +```python +from model2vec.sparse import SparseStaticModel + +# Load a pretrained sparse Model2Vec model +model = SparseStaticModel.from_pretrained("{{ model_name }}") + +# Compute sparse query and document vectors +queries = model.encode_query(["Example query"]) +documents = model.encode_document(["Example document"]) + +# Score queries against documents +scores = queries @ documents.T +``` + +## Additional Resources + +- [Model2Vec Repo](https://github.com/MinishLab/model2vec) +- [Model2Vec Docs](https://minish.ai/packages/model2vec/introduction) + + +## Library Authors + +Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team consisting of [Stephan Tulkens](https://github.com/stephantul) and [Thomas van Dongen](https://github.com/Pringled). + +## Citation + +Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work. +``` +@software{minishlab2024model2vec, + author = {Stephan Tulkens and {van Dongen}, Thomas}, + title = {Model2Vec: Fast State-of-the-Art Static Embeddings}, + year = {2024}, + publisher = {Zenodo}, + doi = {10.5281/zenodo.17270888}, + url = {https://github.com/MinishLab/model2vec}, + license = {MIT} +} +``` diff --git a/model2vec/persistence/__init__.py b/model2vec/persistence/__init__.py index 7ae0c7de..1ab7fbd6 100644 --- a/model2vec/persistence/__init__.py +++ b/model2vec/persistence/__init__.py @@ -1,4 +1,4 @@ from model2vec.persistence.hf import push_folder_to_hub -from model2vec.persistence.persistence import load_pretrained, save_pretrained +from model2vec.persistence.persistence import load_folder, load_pretrained, save_folder, save_pretrained -__all__ = ["save_pretrained", "load_pretrained", "push_folder_to_hub"] +__all__ = ["save_pretrained", "load_pretrained", "save_folder", "load_folder", "push_folder_to_hub"] diff --git a/model2vec/persistence/persistence.py b/model2vec/persistence/persistence.py index 1a8e4de8..cf3740de 100644 --- a/model2vec/persistence/persistence.py +++ b/model2vec/persistence/persistence.py @@ -3,7 +3,7 @@ import json import logging from pathlib import Path -from typing import Any, cast +from typing import Any, Mapping, cast import huggingface_hub import numpy as np @@ -21,6 +21,11 @@ logger = logging.getLogger(__name__) +SPARSE_INDPTR_KEY = "embeddings.indptr" +SPARSE_INDICES_KEY = "embeddings.indices" +SPARSE_DATA_KEY = "embeddings.data" +SPARSE_SHAPE_KEY = "shape" + def save_pretrained( folder_path: Path, @@ -45,39 +50,74 @@ def save_pretrained( :param mapping: The token mapping of the model. If None, there is no token mapping. :param **kwargs: Any additional arguments. """ - folder_path = folder_path / subfolder if subfolder else folder_path - folder_path.mkdir(exist_ok=True, parents=True) - model_weights = {"embeddings": np.ascontiguousarray(embeddings)} if weights is not None: model_weights["weights"] = np.ascontiguousarray(weights) if mapping is not None: model_weights["mapping"] = np.ascontiguousarray(mapping) - save_file(model_weights, folder_path / "model.safetensors") - tokenizer.save(str(folder_path / "tokenizer.json"), pretty=False) - - # Create a copy of config and add dtype and vocab quantization cfg = dict(config) cfg["embedding_dtype"] = np.dtype(embeddings.dtype).name if mapping is not None: cfg["vocabulary_quantization"] = int(embeddings.shape[0]) else: cfg.pop("vocabulary_quantization", None) - with open(folder_path / "config.json", "w") as config_file: - json.dump(cfg, config_file, indent=4) - # Create modules.json modules = [{"idx": 0, "name": "0", "path": ".", "type": "sentence_transformers.models.StaticEmbedding"}] if cfg.get("normalize"): # If normalize=True, add sentence_transformers.models.Normalize modules.append({"idx": 1, "name": "1", "path": "1_Normalize", "type": "sentence_transformers.models.Normalize"}) - with open(folder_path / "modules.json", "w") as modules_file: - json.dump(modules, modules_file, indent=4) + + save_folder( + folder_path=folder_path, + tensors=model_weights, + tokenizer=tokenizer, + config=cfg, + modules=modules, + create_model_card=create_model_card, + subfolder=subfolder, + **kwargs, + ) + + +def save_folder( + folder_path: Path, + tensors: dict[str, np.ndarray], + tokenizer: Tokenizer, + config: Mapping[str, Any], + modules: list[dict[str, Any]] | None = None, + create_model_card: bool = True, + subfolder: str | None = None, + tensor_metadata: dict[str, str] | None = None, + **kwargs: Any, +) -> None: + """Save tensors, a tokenizer, a config, and optionally modules.json and a model card to a folder. + + :param folder_path: The path to the folder. + :param tensors: The tensors to store in `model.safetensors`. + :param tokenizer: The tokenizer. + :param config: The config to store in `config.json`. Stored as is. + :param modules: The contents of `modules.json`. If None, no `modules.json` is written. + :param create_model_card: Whether to create a model card. + :param subfolder: The subfolder to save the model in. + :param tensor_metadata: Metadata to store in the header of `model.safetensors`. + :param **kwargs: Any additional arguments, passed to the model card. + """ + folder_path = folder_path / subfolder if subfolder else folder_path + folder_path.mkdir(exist_ok=True, parents=True) + + save_file(tensors, folder_path / "model.safetensors", metadata=tensor_metadata) + tokenizer.save(str(folder_path / "tokenizer.json"), pretty=False) + + with open(folder_path / "config.json", "w") as config_file: + json.dump(dict(config), config_file, indent=4) + + if modules is not None: + with open(folder_path / "modules.json", "w") as modules_file: + json.dump(modules, modules_file, indent=4) logger.info(f"Saved model to {folder_path}") - # Optionally create the model card if create_model_card: make_model_card(folder_path, **kwargs) @@ -98,7 +138,49 @@ def load_pretrained( :param force_download: Whether to force the download of the model. If False, the model is only downloaded if it is not already present in the cache. :return: The embeddings, tokenizer, config, metadata, weights and mapping. + :raises ValueError: If the folder contains a sparse model. + + """ + tensor_file, layout, tokenizer, config, metadata = load_folder( + folder_or_repo_path=folder_or_repo_path, subfolder=subfolder, token=token, force_download=force_download + ) + if SPARSE_INDICES_KEY in tensor_file.keys(): + raise ValueError( + "This is a sparse model. Load it with `SparseStaticModel` from `model2vec.sparse` instead, which " + "requires the `sparse` extra: `pip install model2vec[sparse]`." + ) + + embedding_name = "embedding.weight" if layout.is_sentence_transformers else "embeddings" + embeddings = tensor_file.get_tensor(embedding_name) + try: + weights = tensor_file.get_tensor("weights") + except Exception: + # Bare except because safetensors does not export its own errors. + weights = None + try: + mapping = tensor_file.get_tensor("mapping") + except Exception: + mapping = None + + return embeddings, tokenizer, cast(StaticModelConfig, config), metadata, weights, mapping + + +def load_folder( + folder_or_repo_path: str | Path, + subfolder: str | None, + token: str | None, + force_download: bool, +) -> tuple[SafeOpenProtocol, Layout, Tokenizer, dict[str, Any], dict[str, Any]]: + """Resolve a folder or repo, and open its tensors, tokenizer, config, and README metadata. + :param folder_or_repo_path: The folder or repo path to load from. + - If this is a local path, we will load from the local path. + - If the local path is not found, we will attempt to load from the huggingface hub. + :param subfolder: The subfolder to load from. + :param token: The huggingface token to use. + :param force_download: Whether to force the download of the model. If False, the model is only downloaded if it is not + already present in the cache. + :return: The opened tensor file, the selected layout, the tokenizer, the config, and the README metadata. """ folder_or_repo_path = Path(folder_or_repo_path) @@ -113,19 +195,7 @@ def load_pretrained( selected_layout = _get_paths(folder) readme_path = folder / "README.md" - opened_tensor_file = cast(SafeOpenProtocol, safetensors.safe_open(selected_layout.embeddings, framework="numpy")) - embedding_name = "embedding.weight" if selected_layout.is_sentence_transformers else "embeddings" - # Actual loading - embeddings = opened_tensor_file.get_tensor(embedding_name) - try: - weights = opened_tensor_file.get_tensor("weights") - except Exception: - # Bare except because safetensors does not export its own errors. - weights = None - try: - mapping = opened_tensor_file.get_tensor("mapping") - except Exception: - mapping = None + tensor_file = cast(SafeOpenProtocol, safetensors.safe_open(selected_layout.embeddings, framework="numpy")) if readme_path.exists(): metadata = get_metadata_from_readme(readme_path) @@ -136,7 +206,7 @@ def load_pretrained( with open(selected_layout.config) as config_file: config = json.load(config_file) - return embeddings, tokenizer, config, metadata, weights, mapping + return tensor_file, selected_layout, tokenizer, config, metadata def _resolve_folder(folder_or_repo_path: Path, subfolder: str | None, token: str | None, force_download: bool) -> Path: diff --git a/model2vec/sparse.py b/model2vec/sparse.py new file mode 100644 index 00000000..e2b51941 --- /dev/null +++ b/model2vec/sparse.py @@ -0,0 +1,522 @@ +from __future__ import annotations + +from model2vec.utils import get_package_extras, importable + +_REQUIRED_EXTRA = "sparse" + +for extra_dependency in get_package_extras("model2vec", _REQUIRED_EXTRA): + importable(extra_dependency, _REQUIRED_EXTRA) + +import json +from collections.abc import Callable, Sequence +from logging import getLogger +from pathlib import Path +from typing import Any, cast + +import numpy as np +from scipy.sparse import csr_matrix, diags, vstack +from tokenizers import Tokenizer + +from model2vec.model import _DEFAULT_NORMALIZE, DEFAULT_MAX_LENGTH, PathLike, StaticModel +from model2vec.persistence.persistence import ( + SPARSE_DATA_KEY, + SPARSE_INDICES_KEY, + SPARSE_INDPTR_KEY, + SPARSE_SHAPE_KEY, +) +from model2vec.types import _UNSET, SparseStaticModelConfig, _UnsetType +from model2vec.utils import SafeOpenProtocol + +logger = getLogger(__name__) + + +class SparseStaticModel(StaticModel[SparseStaticModelConfig]): + def __init__( + self, + vectors: csr_matrix, + tokenizer: Tokenizer, + config: SparseStaticModelConfig | None = None, + normalize: bool = _DEFAULT_NORMALIZE, + base_model_name: str | None = None, + language: list[str] | None = None, + max_length: int | None = DEFAULT_MAX_LENGTH, + *, + k1: float, + norm_coefficient: float, + length_exponent: float, + ) -> None: + """Initialize the SparseStaticModel. + + Each token has a sparse code over the tokens of the vocabulary. A document is the square root of the summed + codes of its tokens, divided by its token count to the length exponent, and saturated as BM25 does with b = 0. + A query token only activates itself: a query is the square root of its token counts, multiplied by the query + weight of each token, which is its own code value to the power norm_coefficient. + Scoring is the dot product of `encode_query` and `encode_document`. + + :param vectors: The sparse code of each token, as a CSR matrix of shape (vocabulary size, vocabulary size). + :param tokenizer: The Transformers tokenizer to use. + :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: + it is written to `config["normalize"]`, and any conflicting value already in `config` is overridden. + :param base_model_name: The used base model name. Used for creating a model card. + :param language: The language of the model. Used for creating a model card. + :param max_length: The default maximum sequence length (in tokens) used by `encode` when its own + `max_length` argument is not passed. Defaults to 512; pass None to disable truncation. + :param k1: The BM25 term frequency saturation of the document weights. Written to `config["k1"]`. + :param norm_coefficient: The power of its own code value that weights a query token. + Written to `config["norm_coefficient"]`. + :param length_exponent: The power of the token count each document is divided by. + Written to `config["length_exponent"]`. + """ + super().__init__( + vectors=cast(np.ndarray, vectors), + tokenizer=tokenizer, + config=config, + normalize=normalize, + base_model_name=base_model_name, + language=language, + weights=None, + token_mapping=None, + max_length=max_length, + ) + self.k1 = k1 + self.norm_coefficient = norm_coefficient + self.length_exponent = length_exponent + + @property # type: ignore[override] + def embedding(self) -> csr_matrix: + """Get the sparse code of each token.""" + return self._embedding + + @embedding.setter + def embedding(self, value: csr_matrix) -> None: + """Validate and store the sparse codes, and reset the query weights. + + :param value: The sparse code of each token. + :raises ValueError: If the matrix is not square, or contains negative or non-finite values. + """ + codes = csr_matrix(value) + if codes.shape[0] != codes.shape[1]: + raise ValueError( + f"The sparse codes must be square, with one latent per token, but got shape {codes.shape}." + ) + if not np.isfinite(codes.data).all(): + raise ValueError("The sparse codes must be finite.") + if codes.nnz and codes.data.min() < 0: + raise ValueError("The sparse codes must be non-negative.") + self._embedding = codes + self._query_weights: np.ndarray | None = None + + @property + def codes(self) -> csr_matrix: + """Get the sparse code of each token.""" + return self.embedding + + @property + def _dtype(self) -> np.dtype: + """Get the floating point dtype of the encoded vectors.""" + return np.result_type(self.codes.dtype, np.float32) + + @property + def query_weights(self) -> np.ndarray: + """Get the query weight of each token: its own code value to the power norm_coefficient, or 0 if that is 0.""" + if self._query_weights is None: + diagonal = self.codes.diagonal().astype(self._dtype) + weights = np.zeros_like(diagonal) + positive = diagonal > 0 + weights[positive] = diagonal[positive] ** self.norm_coefficient + self._query_weights = weights + return self._query_weights + + @property + def k1(self) -> float: + """Get the k1 value.""" + return self._k1 + + @k1.setter + def k1(self, value: float) -> None: + """Update the config.""" + self._k1 = value + self._update_config("k1", value) + + @property + def norm_coefficient(self) -> float: + """Get the norm coefficient.""" + return self._norm_coefficient + + @norm_coefficient.setter + def norm_coefficient(self, value: float) -> None: + """Update the config and reset the query weights.""" + self._norm_coefficient = value + self._query_weights = None + self._update_config("norm_coefficient", value) + + @property + def length_exponent(self) -> float: + """Get the length exponent.""" + return self._length_exponent + + @length_exponent.setter + def length_exponent(self, value: float) -> None: + """Update the config.""" + self._length_exponent = value + self._update_config("length_exponent", value) + + def _update_config(self, key: str, value: float) -> None: + """Write a value to the config, warning if it conflicts with the value already there.""" + config = cast(dict[str, Any], self.config) + config_value = config.get(key) + if config_value is not None and value != config_value: + logger.warning( + f"Set {key} to `{value}`, which does not match config value `{config_value}`. Updating config." + ) + config[key] = value + + def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None: + """Save the pretrained sparse model. + + The sparse matrix is stored in `model.safetensors` as CSR arrays: `embeddings.indptr`, an int64 array of + shape (rows + 1,), `embeddings.indices`, an int32 array of column indices of shape (nnz,), and + `embeddings.data`, an array of values of shape (nnz,). The shape of the matrix is stored in the + safetensors header. + + :param path: The path to save to. + :param model_name: The model name to use in the Model Card. + :param subfolder: The subfolder to save to. + """ + from model2vec.persistence import save_folder + + tensors, tensor_metadata = _sparse_to_tensors(self.codes) + config = {**self.config, "embedding_dtype": np.dtype(self.codes.dtype).name} + + save_folder( + folder_path=Path(path), + tensors=tensors, + tokenizer=self.tokenizer, + config=config, + subfolder=subfolder, + tensor_metadata=tensor_metadata, + base_model_name=self.base_model_name, + language=self.language, + model_name=model_name, + template_path="sparse_model_card_template.md", + tags=["embeddings", "static-embeddings", "sparse"], + ) + + @classmethod + def from_pretrained( # type: ignore[override] + cls, + path: PathLike, + token: str | None = None, + normalize: bool | None = None, + subfolder: str | None = None, + max_length: int | None | _UnsetType = _UNSET, + force_download: bool = True, + k1: float | None = None, + norm_coefficient: float | None = None, + length_exponent: float | None = None, + ) -> SparseStaticModel: + """Load a SparseStaticModel from a local path or huggingface hub path. + + NOTE: if you load a private model from the huggingface hub, you need to pass a token. + + :param path: The path to load your sparse model from. + :param token: The huggingface token to use. + :param normalize: Whether to normalize the embeddings. If not passed, the value from the model's config + is used, falling back to False if the config does not specify one. + :param subfolder: The subfolder to load from. + :param max_length: The default maximum sequence length (in tokens) for `encode`. If not passed, the + value from the model's config is used, falling back to 512 if the config does not specify one. + Pass None to disable truncation. + :param force_download: Whether to force the download of the model. If False, the model is only downloaded if it is not + already present in the cache. + :param k1: The k1 parameter. If not passed, the value from the model's config is used. + :param norm_coefficient: The norm coefficient. If not passed, the value from the model's config is used. + :param length_exponent: The length exponent. If not passed, the value from the model's config is used. + :return: A SparseStaticModel. + :raises ValueError: If `k1`, `norm_coefficient` or `length_exponent` is neither passed nor present in the + config. + """ + from model2vec.persistence import load_folder + + tensor_file, _, tokenizer, config, metadata = load_folder( + folder_or_repo_path=path, subfolder=subfolder, token=token, force_download=force_download + ) + embeddings = _tensors_to_sparse(tensor_file) + + k1 = k1 if k1 is not None else config.get("k1") + norm_coefficient = norm_coefficient if norm_coefficient is not None else config.get("norm_coefficient") + length_exponent = length_exponent if length_exponent is not None else config.get("length_exponent") + if k1 is None or norm_coefficient is None or length_exponent is None: + raise ValueError( + "`k1`, `norm_coefficient` and `length_exponent` must be present in the model's config, or passed to " + "`from_pretrained`." + ) + + return cls( + vectors=embeddings, + tokenizer=tokenizer, + config=cast(SparseStaticModelConfig, config), + normalize=normalize if normalize is not None else config.get("normalize", _DEFAULT_NORMALIZE), + base_model_name=metadata.get("base_model"), + language=metadata.get("language"), + max_length=config.get("max_length", DEFAULT_MAX_LENGTH) + if isinstance(max_length, _UnsetType) + else max_length, + k1=k1, + norm_coefficient=norm_coefficient, + length_exponent=length_exponent, + ) + + def encode( # type: ignore[override] + self, + sentences: 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, + ) -> csr_matrix: + """Encode a list of documents into saturated sparse weights, which depend on no corpus statistics. + + :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. + :return: The encoded sentences as a CSR matrix. If a single sentence was passed, a 1-row matrix is returned. + """ + return self._encode_sparse( + sentences, + batch_fn=self._encode_batch, + show_progress_bar=show_progress_bar, + max_length=max_length, + normalize=normalize, + batch_size=batch_size, + use_multiprocessing=use_multiprocessing, + multiprocessing_threshold=multiprocessing_threshold, + ) + + def encode_query( + self, + sentences: 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, + ) -> csr_matrix: + """Encode a list of queries into sparse vectors. + + :param sentences: The list of queries to encode. You can also pass a single query. + :param show_progress_bar: Whether to show the progress bar. + :param max_length: The maximum length of the queries. 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. + :return: The encoded queries as a CSR matrix. If a single query was passed, a 1-row matrix is returned. + """ + return self._encode_sparse( + sentences, + batch_fn=self._encode_query_batch, + show_progress_bar=show_progress_bar, + max_length=max_length, + normalize=normalize, + batch_size=batch_size, + use_multiprocessing=use_multiprocessing, + multiprocessing_threshold=multiprocessing_threshold, + ) + + def encode_document( + self, + sentences: 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, + ) -> csr_matrix: + """Encode a list of documents into sparse vectors. + + :param sentences: The list of documents to encode. You can also pass a single document. + :param show_progress_bar: Whether to show the progress bar. + :param max_length: The maximum length of the documents. 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. + :return: The encoded documents as a CSR matrix. If a single document was passed, a 1-row matrix is returned. + """ + return self.encode( + sentences, + show_progress_bar=show_progress_bar, + max_length=max_length, + normalize=normalize, + batch_size=batch_size, + use_multiprocessing=use_multiprocessing, + multiprocessing_threshold=multiprocessing_threshold, + ) + + def encode_as_sequence( # type: ignore[override] + self, sentences: str | list[str], **kwargs: Any + ) -> list[np.ndarray] | np.ndarray: + """Not supported for sparse models. + + :param sentences: The sentences to encode. + :param **kwargs: Any additional arguments. + :return: Never returns. + :raises NotImplementedError: Always. + """ + raise NotImplementedError("encode_as_sequence is not supported for SparseStaticModel.") + + def _encode_sparse( + self, + sentences: Sequence[str], + *, + batch_fn: Callable[[Sequence[str], bool], csr_matrix], + show_progress_bar: bool, + max_length: int | None | _UnsetType, + normalize: bool | None, + batch_size: int, + use_multiprocessing: bool, + multiprocessing_threshold: int, + ) -> csr_matrix: + """Resolve defaults, dispatch the batches to `batch_fn`, and stack the results. + + :param sentences: The sentences to encode. + :param batch_fn: The function that encodes a single batch. + :param show_progress_bar: Whether to show the progress bar. + :param max_length: The maximum length of the sentences. If unset, the model's `max_length` is used. + :param normalize: Whether to normalize the resulting vectors. If None, the model's `normalize` is used. + :param batch_size: The batch size to use. + :param use_multiprocessing: Whether to use multiprocessing. + :param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing. + :return: The encoded sentences as a CSR matrix. If a single sentence was passed, a 1-row matrix is returned. + """ + 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=batch_fn, + batch_args=(normalize,), + ) + out = vstack(results, format="csr") if results else csr_matrix((0, self.dim), dtype=self._dtype) + + if was_single: + return out[0] + return out + + def _bag(self, sentences: Sequence[str]) -> tuple[csr_matrix, np.ndarray]: + """Tokenize sentences into a bag of token counts, and their token counts.""" + ids = self.tokenize(sentences) + lengths = np.array([len(x) for x in ids], dtype=np.int64) + rows = np.repeat(np.arange(len(ids)), lengths) + cols = np.concatenate([np.asarray(x, dtype=np.int64) for x in ids]) if ids else np.zeros(0, np.int64) + bag = csr_matrix((np.ones(len(cols), dtype=self._dtype), (rows, cols)), shape=(len(ids), self.codes.shape[0])) + return bag, lengths + + def saturate(self, weights: csr_matrix) -> csr_matrix: + """Saturate encoded weights as BM25 does with b = 0: w (k1 + 1) / (w + k1). + + :param weights: Encoded weights. + :return: The saturated weights. + """ + out = weights.copy() + out.data = weights.data * (self.k1 + 1) / (weights.data + self.k1) + return out + + def _encode_batch(self, sentences: Sequence[str], normalize: bool) -> csr_matrix: # type: ignore[override] + """Encode a batch of documents into sparse vectors. + + :param sentences: The documents to encode. + :param normalize: Whether to normalize the resulting vectors. + :return: The encoded documents as a CSR matrix. + """ + bag, lengths = self._bag(sentences) + length_norm = diags(np.maximum(lengths, 1).astype(self._dtype) ** -self.length_exponent) + pooled = (length_norm @ (bag @ self.codes).sqrt()).tocsr() + return _maybe_normalize(self.saturate(pooled), normalize) + + def _encode_query_batch(self, sentences: Sequence[str], normalize: bool) -> csr_matrix: + """Encode a batch of queries into sparse vectors. + + :param sentences: The queries to encode. + :param normalize: Whether to normalize the resulting vectors. + :return: The encoded queries as a CSR matrix. + """ + bag, _ = self._bag(sentences) + bag.data = np.sqrt(bag.data) * self.query_weights[bag.indices] + bag.eliminate_zeros() + return _maybe_normalize(bag, normalize) + + +def _maybe_normalize(matrix: csr_matrix, normalize: bool) -> csr_matrix: + """L2-normalize the rows of a sparse matrix if `normalize` is True; all-zero rows stay zero.""" + if not normalize: + return matrix + norms = np.sqrt(np.asarray(matrix.multiply(matrix).sum(axis=1)).ravel()) + norms[norms == 0] = 1.0 + return csr_matrix(diags(1.0 / norms) @ matrix) + + +def _sparse_to_tensors(matrix: csr_matrix) -> tuple[dict[str, np.ndarray], dict[str, str]]: + """Convert a sparse matrix to safetensors-compatible CSR arrays and header metadata.""" + csr = csr_matrix(matrix, copy=True) + csr.sum_duplicates() + tensors: dict[str, np.ndarray] = { + SPARSE_INDPTR_KEY: np.ascontiguousarray(csr.indptr, dtype=np.int64), + SPARSE_INDICES_KEY: np.ascontiguousarray(csr.indices, dtype=np.int32), + SPARSE_DATA_KEY: np.ascontiguousarray(csr.data), + } + return tensors, {SPARSE_SHAPE_KEY: json.dumps([int(dim) for dim in csr.shape])} + + +def _tensors_to_sparse(tensor_file: SafeOpenProtocol) -> csr_matrix: + """Read a sparse matrix stored with `_sparse_to_tensors` from an opened safetensors file.""" + header = tensor_file.metadata() or {} + try: + indptr = tensor_file.get_tensor(SPARSE_INDPTR_KEY) + indices = tensor_file.get_tensor(SPARSE_INDICES_KEY) + data = tensor_file.get_tensor(SPARSE_DATA_KEY) + shape = json.loads(header[SPARSE_SHAPE_KEY]) + except Exception as e: + # Bare except because safetensors does not export its own errors. + raise ValueError( + f"Could not find a sparse matrix in `model.safetensors`. Expected tensors `{SPARSE_INDPTR_KEY}`, " + f"`{SPARSE_INDICES_KEY}` and `{SPARSE_DATA_KEY}`, and `{SPARSE_SHAPE_KEY}` in the header. " + "Is this a dense model? Use `StaticModel` instead." + ) from e + return csr_matrix((data, indices, indptr), shape=tuple(shape)) diff --git a/model2vec/types.py b/model2vec/types.py index 6fcd2577..3493c38f 100644 --- a/model2vec/types.py +++ b/model2vec/types.py @@ -26,3 +26,11 @@ class StaticModelConfig(TypedDict, total=False): embedding_dtype: str vocabulary_quantization: int head_config: dict[str, Any] + + +class SparseStaticModelConfig(StaticModelConfig, total=False): + """The metadata config stored alongside a sparse model2vec model.""" + + k1: float + norm_coefficient: float + length_exponent: float diff --git a/model2vec/utils.py b/model2vec/utils.py index 9c9ec666..c57beba5 100644 --- a/model2vec/utils.py +++ b/model2vec/utils.py @@ -53,6 +53,14 @@ def get_tensor(self, key: str) -> np.ndarray: """Get a tensor.""" ... # pragma: no cover + def metadata(self) -> dict[str, str] | None: + """Get the metadata stored in the header.""" + ... # pragma: no cover + + def keys(self) -> list[str]: + """Get the names of the stored tensors.""" + ... # pragma: no cover + _MODULE_MAP = (("scikit-learn", "sklearn"),) _DIVIDERS = re.compile(r"[=<>!]+") diff --git a/pyproject.toml b/pyproject.toml index 5e1ee820..17d21838 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,6 +29,7 @@ dependencies = [ "safetensors", "tokenizers>=0.20", "tqdm", + "typing-extensions>=4.4.0", "huggingface-hub>=1.0.0", ] @@ -63,6 +64,7 @@ distill = ["torch", "transformers<5.4.0", "skeletoken>=0.6.0,<0.7.0"] onnx = ["onnx", "torch", "onnxruntime", "onnxscript", "skeletoken>=0.6.0,<0.7.0"] train = ["torch", "datasets>=4.0.0"] quantization = ["scikit-learn"] +sparse = ["scipy"] integration = ["mteb"] tests = ["scikit-learn", "skops"] diff --git a/tests/test_sparse.py b/tests/test_sparse.py new file mode 100644 index 00000000..1dce62dc --- /dev/null +++ b/tests/test_sparse.py @@ -0,0 +1,470 @@ +import json +from pathlib import Path +from typing import Any + +import numpy as np +import pytest +import safetensors +from scipy.sparse import csr_matrix +from tokenizers import Tokenizer + +from model2vec import StaticModel +from model2vec.model import quantize_model +from model2vec.sparse import SparseStaticModel + +K1 = 1.2 +LENGTH_EXPONENT = 0.3 + +# Vocabulary: [PAD], word1, word2, word3, [UNK] +_CODES = np.array( + [ + [0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 2.0, 0.5, 0.0, 0.0], + [0.0, 0.5, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 3.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0], + ] +) +NORM_COEFFICIENT = 0.75 + + +@pytest.fixture +def mock_sparse_vectors() -> csr_matrix: + """Create mock sparse codes, one latent per token.""" + return csr_matrix(_CODES) + + +@pytest.fixture +def mock_sparse_model(mock_sparse_vectors: csr_matrix, mock_tokenizer: Tokenizer) -> SparseStaticModel: + """Create a mock sparse model.""" + return SparseStaticModel( + vectors=mock_sparse_vectors, + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + + +def _expected_document(token_ids: list[int]) -> np.ndarray: + """Compute the expected document encoding densely.""" + summed = _CODES[token_ids].sum(axis=0) + pooled = np.sqrt(summed) / max(len(token_ids), 1) ** LENGTH_EXPONENT + return pooled * (K1 + 1) / (pooled + K1) + + +def _expected_query(token_ids: list[int]) -> np.ndarray: + """Compute the expected query encoding densely.""" + counts = np.bincount(token_ids, minlength=len(_CODES)).astype(float) + return np.sqrt(counts) * np.diag(_CODES) ** NORM_COEFFICIENT + + +def test_initialization( + mock_sparse_vectors: csr_matrix, mock_tokenizer: Tokenizer, mock_config: dict[str, Any] +) -> None: + """Test successful initialization of SparseStaticModel.""" + original_config = dict(mock_config) + model = SparseStaticModel( + vectors=mock_sparse_vectors, + tokenizer=mock_tokenizer, + config=mock_config, # type: ignore[arg-type] + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + assert isinstance(model.embedding, csr_matrix) + assert model.embedding.shape == (5, 5) + assert model.dim == 5 + assert len(model.tokens) == 5 + assert model.weights is None + assert model.token_mapping is None + assert model.vocabulary_quantization is None + assert np.allclose(model.query_weights, np.diag(_CODES) ** NORM_COEFFICIENT) + assert model.k1 == K1 + assert model.norm_coefficient == NORM_COEFFICIENT + assert model.length_exponent == LENGTH_EXPONENT + assert model.config == { + **original_config, + "normalize": False, + "max_length": 512, + "k1": K1, + "norm_coefficient": NORM_COEFFICIENT, + "length_exponent": LENGTH_EXPONENT, + } + assert mock_config == original_config + + +def test_initialization_converts_to_csr(mock_tokenizer: Tokenizer) -> None: + """Test that non-CSR input is stored as a CSR matrix.""" + model = SparseStaticModel( + vectors=_CODES, + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + assert isinstance(model.embedding, csr_matrix) + assert np.array_equal(model.embedding.toarray(), _CODES) + + +def test_initialization_non_square_raises(mock_tokenizer: Tokenizer) -> None: + """Test that codes that are not square raise.""" + with pytest.raises(ValueError, match="square"): + SparseStaticModel( + vectors=csr_matrix(np.ones((5, 2))), + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + + +def test_initialization_token_vector_mismatch(mock_tokenizer: Tokenizer) -> None: + """Test if error is raised when number of tokens and vectors don't match.""" + with pytest.raises(ValueError, match="Number of tokens"): + SparseStaticModel( + vectors=csr_matrix(np.eye(2)), + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + + +def test_initialization_negative_codes_raises(mock_tokenizer: Tokenizer) -> None: + """Test that negative codes raise.""" + with pytest.raises(ValueError, match="codes must be non-negative"): + SparseStaticModel( + vectors=csr_matrix(-np.eye(5)), + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + + +def test_initialization_non_finite_codes_raises(mock_tokenizer: Tokenizer) -> None: + """Test that NaN or infinite codes raise.""" + for value in (np.nan, np.inf): + codes = _CODES.copy() + codes[1, 1] = value + with pytest.raises(ValueError, match="codes must be finite"): + SparseStaticModel( + vectors=codes, + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + + +def test_set_embedding_validates_and_updates_query_weights(mock_sparse_model: SparseStaticModel) -> None: + """Test that assigning new codes validates them and recomputes the query weights.""" + mock_sparse_model.embedding = csr_matrix(_CODES * 2) + assert np.allclose(mock_sparse_model.query_weights, np.diag(_CODES * 2) ** NORM_COEFFICIENT) + with pytest.raises(ValueError, match="non-negative"): + mock_sparse_model.embedding = csr_matrix(-np.eye(5)) + + +@pytest.mark.parametrize("norm_coefficient", [0.0, -0.5]) +def test_query_weights_zero_for_zero_codes(mock_tokenizer: Tokenizer, norm_coefficient: float) -> None: + """Test that tokens without a code value of their own get query weight 0 for any norm coefficient.""" + model = SparseStaticModel( + vectors=_CODES, + tokenizer=mock_tokenizer, + norm_coefficient=norm_coefficient, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + diagonal = np.diag(_CODES) + positive = diagonal > 0 + assert np.allclose(model.query_weights[positive], diagonal[positive] ** norm_coefficient) + assert np.all(model.query_weights[~positive] == 0) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("method", ["encode", "encode_query", "encode_document"]) +def test_encode_keeps_dtype(mock_tokenizer: Tokenizer, dtype: type, method: str) -> None: + """Test that encoding keeps the dtype of the codes, also when normalizing or encoding nothing.""" + model = SparseStaticModel( + vectors=_CODES.astype(dtype), + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + encode = getattr(model, method) + assert encode(["word1 word2"]).dtype == dtype + assert encode(["word1 word2"], normalize=True).dtype == dtype + assert encode([]).dtype == dtype + + +def test_integer_codes_give_float_query_weights(mock_tokenizer: Tokenizer) -> None: + """Test that integer codes do not truncate the query weights.""" + model = SparseStaticModel( + vectors=(_CODES * 2).astype(np.int32), + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + assert np.allclose(model.query_weights, np.diag(_CODES * 2) ** NORM_COEFFICIENT) + + +def test_conflicting_config_warns( + mock_sparse_vectors: csr_matrix, mock_tokenizer: Tokenizer, caplog: pytest.LogCaptureFixture +) -> None: + """Test that a parameter that conflicts with the config warns and overrides the config.""" + model = SparseStaticModel( + vectors=mock_sparse_vectors, + tokenizer=mock_tokenizer, + config={"k1": 9.0, "norm_coefficient": NORM_COEFFICIENT}, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + assert model.config["k1"] == K1 + assert "Set k1 to" in caplog.text + assert "Set norm_coefficient" not in caplog.text + + +def test_initialization_requires_parameters(mock_sparse_vectors: csr_matrix, mock_tokenizer: Tokenizer) -> None: + """Test that k1, norm_coefficient and length_exponent are required.""" + with pytest.raises(TypeError): + SparseStaticModel(vectors=mock_sparse_vectors, tokenizer=mock_tokenizer) # type: ignore[call-arg] + + +def test_setters_update_config(mock_sparse_model: SparseStaticModel) -> None: + """Test that setting the parameters updates the config.""" + mock_sparse_model.k1 = 2.0 + mock_sparse_model.norm_coefficient = 0.5 + mock_sparse_model.length_exponent = 0.1 + assert mock_sparse_model.config["k1"] == 2.0 + assert mock_sparse_model.config["norm_coefficient"] == 0.5 + assert mock_sparse_model.config["length_exponent"] == 0.1 + + +@pytest.mark.parametrize("method", ["encode", "encode_document"]) +def test_encode_document(mock_sparse_model: SparseStaticModel, method: str) -> None: + """Test document encoding against a dense computation.""" + out = getattr(mock_sparse_model, method)(["word1 word2", "word3 word3 word1", "word2"]) + assert isinstance(out, csr_matrix) + assert out.shape == (3, 5) + expected = np.stack([_expected_document([1, 2]), _expected_document([3, 3, 1]), _expected_document([2])]) + assert np.allclose(out.toarray(), expected) + + +def test_encode_query(mock_sparse_model: SparseStaticModel) -> None: + """Test query encoding against a dense computation.""" + out = mock_sparse_model.encode_query(["word1 word1 word3", "word2"]) + assert isinstance(out, csr_matrix) + assert out.shape == (2, 5) + expected = np.stack([_expected_query([1, 1, 3]), _expected_query([2])]) + assert np.allclose(out.toarray(), expected) + + +def test_query_only_activates_its_own_tokens(mock_sparse_model: SparseStaticModel) -> None: + """Test that a query token does not activate its neighbours, unlike a document token.""" + query = mock_sparse_model.encode_query("word1").toarray()[0] + document = mock_sparse_model.encode_document("word1").toarray()[0] + assert np.flatnonzero(query).tolist() == [1] + assert np.flatnonzero(document).tolist() == [1, 2] + + +def test_norm_coefficient_setter_updates_query_encoding(mock_sparse_model: SparseStaticModel) -> None: + """Test that changing norm_coefficient changes query weights.""" + mock_sparse_model.norm_coefficient = 1.0 + out = mock_sparse_model.encode_query("word3").toarray()[0] + assert np.isclose(out[3], 3.0) + + +def test_query_tokens_with_zero_weight_are_dropped(mock_tokenizer: Tokenizer) -> None: + """Test that query tokens with a zero code value are not stored.""" + codes = _CODES.copy() + codes[2, 2] = 0.0 + model = SparseStaticModel( + vectors=codes, + tokenizer=mock_tokenizer, + k1=K1, + norm_coefficient=NORM_COEFFICIENT, + length_exponent=LENGTH_EXPONENT, + ) + out = model.encode_query("word1 word2") + assert out.indices.tolist() == [1] + + +def test_quantize_model_raises(mock_sparse_model: SparseStaticModel) -> None: + """Test that quantizing a sparse model raises.""" + with pytest.raises(NotImplementedError, match="dense"): + quantize_model(mock_sparse_model, quantize_to="float16") + + +@pytest.mark.parametrize("method", ["encode", "encode_query", "encode_document"]) +def test_encode_empty_sentence(mock_sparse_model: SparseStaticModel, method: str) -> None: + """Test that an empty sentence gives an all-zero row, also when normalizing.""" + out = getattr(mock_sparse_model, method)(["", "word1"], normalize=True) + assert out.shape == (2, 5) + assert out[0].nnz == 0 + assert not np.isnan(out.toarray()).any() + + +@pytest.mark.parametrize("method", ["encode", "encode_query", "encode_document"]) +def test_encode_normalize(mock_sparse_model: SparseStaticModel, method: str) -> None: + """Test that normalize gives unit-length rows.""" + out = getattr(mock_sparse_model, method)(["word1 word2", "word3"], normalize=True) + assert np.allclose(np.linalg.norm(out.toarray(), axis=1), 1.0) + + +@pytest.mark.parametrize("method", ["encode", "encode_query", "encode_document"]) +def test_encode_empty_input(mock_sparse_model: SparseStaticModel, method: str) -> None: + """Test that encoding no sentences gives an empty matrix.""" + out = getattr(mock_sparse_model, method)([]) + assert isinstance(out, csr_matrix) + assert out.shape == (0, 5) + + +@pytest.mark.parametrize("method", ["encode", "encode_query", "encode_document"]) +def test_encode_batches_match_single_batch(mock_sparse_model: SparseStaticModel, method: str) -> None: + """Test that batching does not change the output, and a single sentence gives one row.""" + sentences = ["word1", "word2 word3", "word3", "word1 word1"] + encode = getattr(mock_sparse_model, method) + batched = encode(sentences, batch_size=3) + unbatched = encode(sentences, batch_size=1024) + assert np.allclose(batched.toarray(), unbatched.toarray()) + + single = encode("word1") + assert isinstance(single, csr_matrix) + assert single.shape == (1, 5) + assert np.allclose(single.toarray(), unbatched[0].toarray()) + + +def test_encode_as_sequence_not_implemented(mock_sparse_model: SparseStaticModel) -> None: + """Test that encode_as_sequence raises NotImplementedError.""" + with pytest.raises(NotImplementedError): + mock_sparse_model.encode_as_sequence(["word1 word2"]) + + +def test_save_and_load_roundtrip(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that saving and loading a sparse model preserves the matrix, query weights and config.""" + mock_sparse_model.save_pretrained(tmp_path) + loaded = SparseStaticModel.from_pretrained(tmp_path) + + assert isinstance(loaded.embedding, csr_matrix) + assert loaded.embedding.shape == mock_sparse_model.embedding.shape + assert loaded.embedding.dtype == mock_sparse_model.embedding.dtype + assert np.array_equal(loaded.embedding.toarray(), mock_sparse_model.embedding.toarray()) + assert np.array_equal(loaded.query_weights, mock_sparse_model.query_weights) + assert loaded.k1 == mock_sparse_model.k1 + assert loaded.norm_coefficient == mock_sparse_model.norm_coefficient + assert loaded.length_exponent == mock_sparse_model.length_exponent + assert loaded.normalize == mock_sparse_model.normalize + assert loaded.max_length == mock_sparse_model.max_length + assert loaded.tokens == mock_sparse_model.tokens + + +def test_save_stores_csr_arrays(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test the on-disk format: CSR arrays and query weights, shape in the header, no modules.json.""" + mock_sparse_model.save_pretrained(tmp_path) + + with safetensors.safe_open(tmp_path / "model.safetensors", framework="numpy") as f: + assert set(f.keys()) == {"embeddings.indptr", "embeddings.indices", "embeddings.data"} + nnz = mock_sparse_model.embedding.nnz + rows = mock_sparse_model.embedding.shape[0] + indptr = f.get_tensor("embeddings.indptr") + indices = f.get_tensor("embeddings.indices") + assert indptr.shape == (rows + 1,) + assert indptr.dtype == np.int64 + assert indices.shape == (nnz,) + assert indices.dtype == np.int32 + assert f.get_tensor("embeddings.data").shape == (nnz,) + assert json.loads(f.metadata()["shape"]) == list(mock_sparse_model.embedding.shape) + + config = json.loads((tmp_path / "config.json").read_text()) + assert config["k1"] == mock_sparse_model.k1 + assert config["norm_coefficient"] == mock_sparse_model.norm_coefficient + assert config["length_exponent"] == mock_sparse_model.length_exponent + assert config["embedding_dtype"] == "float64" + assert "sparse" not in config + assert not (tmp_path / "modules.json").exists() + + +def test_save_model_card(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that the model card shows how to load the model as a sparse model.""" + mock_sparse_model.save_pretrained(tmp_path, model_name="sparse-model") + readme = (tmp_path / "README.md").read_text() + assert 'SparseStaticModel.from_pretrained("sparse-model")' in readme + assert "from model2vec import StaticModel" not in readme + + +def test_load_sparse_model_as_dense_raises(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that loading a sparse model as a dense model gives an informative error.""" + mock_sparse_model.save_pretrained(tmp_path) + with pytest.raises(ValueError, match="SparseStaticModel"): + StaticModel.from_pretrained(tmp_path) + + +def test_save_and_load_non_canonical_matrix(mock_tokenizer: Tokenizer, tmp_path: Path) -> None: + """Test that a matrix with unsorted and duplicate entries round-trips without changing the model.""" + rows = np.array([1, 1, 1, 3]) + cols = np.array([2, 1, 2, 3]) + data = np.array([0.25, 2.0, 0.25, 3.0]) + codes = csr_matrix((data, cols, np.array([0, 0, 3, 3, 4, 4])), shape=(5, 5)) + assert not codes.has_canonical_format + model = SparseStaticModel( + vectors=codes, + tokenizer=mock_tokenizer, + norm_coefficient=NORM_COEFFICIENT, + k1=K1, + length_exponent=LENGTH_EXPONENT, + ) + model.save_pretrained(tmp_path) + loaded = SparseStaticModel.from_pretrained(tmp_path) + + expected = np.zeros((5, 5)) + np.add.at(expected, (rows, cols), data) + assert np.allclose(loaded.embedding.toarray(), expected) + assert loaded.embedding.has_canonical_format + assert not model.embedding.has_canonical_format + + +def test_save_and_load_subfolder(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test saving and loading a sparse model in a subfolder.""" + mock_sparse_model.save_pretrained(tmp_path, subfolder="sparse") + loaded = SparseStaticModel.from_pretrained(tmp_path, subfolder="sparse") + assert np.array_equal(loaded.embedding.toarray(), mock_sparse_model.embedding.toarray()) + + +def test_load_overrides(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that arguments to from_pretrained override the config.""" + mock_sparse_model.save_pretrained(tmp_path) + loaded = SparseStaticModel.from_pretrained( + tmp_path, k1=2.0, norm_coefficient=0.5, length_exponent=0.1, normalize=True, max_length=None + ) + assert loaded.k1 == 2.0 + assert loaded.norm_coefficient == 0.5 + assert np.allclose(loaded.query_weights, np.diag(_CODES) ** 0.5) + assert loaded.length_exponent == 0.1 + assert loaded.normalize + assert loaded.max_length is None + + +def test_load_missing_k1_raises(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that loading without k1 in the config or as an argument raises.""" + mock_sparse_model.save_pretrained(tmp_path) + config_path = tmp_path / "config.json" + config = json.loads(config_path.read_text()) + del config["k1"] + config_path.write_text(json.dumps(config)) + + with pytest.raises(ValueError, match="k1"): + SparseStaticModel.from_pretrained(tmp_path) + assert SparseStaticModel.from_pretrained(tmp_path, k1=3.0).k1 == 3.0 + + +def test_load_dense_model_raises(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, tmp_path: Path) -> None: + """Test that loading a dense model as a sparse model gives an informative error.""" + StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer).save_pretrained(tmp_path) + with pytest.raises(ValueError, match="Is this a dense model"): + SparseStaticModel.from_pretrained( + tmp_path, k1=K1, norm_coefficient=NORM_COEFFICIENT, length_exponent=LENGTH_EXPONENT + ) diff --git a/uv.lock b/uv.lock index eedafb80..ceb1b503 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" @@ -1244,6 +1268,7 @@ dependencies = [ { name = "safetensors" }, { name = "tokenizers" }, { name = "tqdm" }, + { name = "typing-extensions" }, ] [package.optional-dependencies] @@ -1268,7 +1293,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" }, @@ -1278,6 +1303,10 @@ quantization = [ { name = "scikit-learn", version = "1.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "scikit-learn", version = "1.8.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] +sparse = [ + { name = "scipy", version = "1.15.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] tests = [ { name = "scikit-learn", version = "1.7.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "scikit-learn", version = "1.8.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, @@ -1308,6 +1337,7 @@ requires-dist = [ { name = "safetensors" }, { name = "scikit-learn", marker = "extra == 'quantization'" }, { name = "scikit-learn", marker = "extra == 'tests'" }, + { name = "scipy", marker = "extra == 'sparse'" }, { name = "setuptools", marker = "extra == 'dev'" }, { name = "skeletoken", marker = "extra == 'distill'", specifier = ">=0.6.0,<0.7.0" }, { name = "skeletoken", marker = "extra == 'onnx'", specifier = ">=0.6.0,<0.7.0" }, @@ -1318,8 +1348,9 @@ requires-dist = [ { name = "torch", marker = "extra == 'train'" }, { name = "tqdm" }, { name = "transformers", marker = "extra == 'distill'", specifier = "<5.4.0" }, + { name = "typing-extensions", specifier = ">=4.4.0" }, ] -provides-extras = ["dev", "distill", "onnx", "train", "quantization", "integration", "tests"] +provides-extras = ["dev", "distill", "onnx", "train", "quantization", "sparse", "integration", "tests"] [[package]] name = "mpmath" @@ -1966,12 +1997,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 +2011,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 +2714,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 2996153450e14eb506b4c0a6daacfbd6abec9e4d Mon Sep 17 00:00:00 2001 From: stephantul Date: Tue, 1 Dec 2026 10:41:36 +0100 Subject: [PATCH 2/4] new version with base class --- model2vec/base.py | 201 +++++++++++++++++ model2vec/model.py | 177 ++------------- .../modelcards/sparse_model_card_template.md | 2 + model2vec/persistence/persistence.py | 2 +- model2vec/sparse.py | 206 ++++++++++-------- model2vec/train/base.py | 3 +- pyproject.toml | 1 - tests/test_sparse.py | 55 +++-- uv.lock | 2 - 9 files changed, 378 insertions(+), 271 deletions(-) create mode 100644 model2vec/base.py diff --git a/model2vec/base.py b/model2vec/base.py new file mode 100644 index 00000000..8ffae1d6 --- /dev/null +++ b/model2vec/base.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +import copy +import json +from abc import ABC, abstractmethod +from collections.abc import Sequence +from logging import getLogger +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Any, Generic, TypeVar, cast + +import numpy as np +from tokenizers import Encoding, Tokenizer + +from model2vec.types import StaticModelConfig + +PathLike = Path | str + +logger = getLogger(__name__) + +DEFAULT_MAX_LENGTH = 512 +_DEFAULT_NORMALIZE = False + + +ConfigT = TypeVar("ConfigT", bound=StaticModelConfig) + + +class BaseStaticModel(ABC, Generic[ConfigT]): + def __init__( + self, + tokenizer: Tokenizer, + config: ConfigT | None = None, + normalize: bool = _DEFAULT_NORMALIZE, + base_model_name: str | None = None, + language: list[str] | None = None, + max_length: int | None = DEFAULT_MAX_LENGTH, + ) -> None: + """Initialize the tokenizer, config and settings shared by dense and sparse static models. + + :param tokenizer: The 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: + it is written to `config["normalize"]`, and any conflicting value already in `config` is overridden. + :param base_model_name: The used base model name. Used for creating a model card. + :param language: The language of the model. Used for creating a model card. + :param max_length: The default maximum sequence length (in tokens) used by `encode` when its own + `max_length` argument is not passed. Defaults to 512; pass None to disable truncation. This value + is authoritative: it is written to `config["max_length"]`, and any conflicting value already in + `config` is overridden. + """ + super().__init__() + tokens, _ = zip(*sorted(tokenizer.get_vocab().items(), key=lambda x: x[1])) + self.tokens = tokens + + self.tokenizer = copy.deepcopy(tokenizer) + _disable_padding(self.tokenizer) + self.unk_token_id = _get_unk_token_id(self.tokenizer) + + self.median_token_length = int(np.median([len(token) for token in self.tokens])) + self.config: ConfigT = cast(ConfigT, {**config} if config is not None else {}) + self.base_model_name = base_model_name + self.language = language + self.max_length = max_length + self.normalize = normalize + + @property + def tokenizer(self) -> Tokenizer: + """The tokenizer.""" + return self._tokenizer + + @tokenizer.setter + def tokenizer(self, value: Tokenizer) -> None: + self._tokenizer = value + + @property + def normalize(self) -> bool: + """Get the normalize value. + + :return: The normalize value. + """ + return self._normalize + + @normalize.setter + def normalize(self, value: bool) -> None: + """Update the config.""" + self._normalize = value + self._update_config("normalize", value) + + @property + def max_length(self) -> int | None: + """Get the max_length value. + + :return: The max_length value. + """ + return self._max_length + + @max_length.setter + def max_length(self, value: int | None) -> None: + """Update the config.""" + self._max_length = value + self._update_config("max_length", value) + self._set_max_length_in_tokenizer(value) + + def _update_config(self, key: str, value: Any) -> None: + """Write a value to the config, warning if it conflicts with the value already there.""" + config = cast(dict[str, Any], self.config) + config_value = config.get(key) + if config_value is not None and value != config_value: + logger.warning( + f"Set {key} to `{value}`, which does not match config value `{config_value}`. Updating config." + ) + config[key] = value + + @abstractmethod + def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None: + """Save the pretrained model. + + :param path: The path to save to. + :param model_name: The model name to use in the Model Card. + :param subfolder: The subfolder to save to. + """ + + def tokenize(self, sentences: Sequence[str]) -> list[list[int]]: + """Tokenize a list of sentences. + + :param sentences: The sentences to tokenize. + :return: A list of list of tokens. + """ + encodings: list[Encoding] = self.tokenizer.encode_batch_fast(sentences, add_special_tokens=False) + + encodings_ids = [encoding.ids for encoding in encodings] + + if self.unk_token_id is not None: + # NOTE: Remove the unknown token: necessary for word-level models. + encodings_ids = [ + [token_id for token_id in token_ids if token_id != self.unk_token_id] for token_ids in encodings_ids + ] + + return encodings_ids + + def _tokenize_truncated(self, sentences: list[str], max_length: int | None) -> list[list[int]]: + """Tokenize sentences, truncated to `max_length` tokens, or not truncated if `max_length` is None.""" + if max_length is not None: + m = max_length * self.median_token_length + sentences = [sentence[:m] for sentence in sentences] + + self._set_max_length_in_tokenizer(max_length) + try: + return self.tokenize(sentences) + finally: + self._set_max_length_in_tokenizer(self.max_length) + + def _set_max_length_in_tokenizer(self, max_length: int | None) -> None: + """Sets the max length in the tokenizer.""" + if max_length is None: + self.tokenizer.no_truncation() + else: + self.tokenizer.enable_truncation(max_length) + + def push_to_hub( + self, repo_id: str, private: bool = False, token: str | None = None, subfolder: str | None = None + ) -> None: + """Push the model to the huggingface hub. + + NOTE: you need to pass a token if you are pushing a private model. + + :param repo_id: The repo id to push to. + :param private: Whether the repo, if created is set to private. + If the repo already exists, this doesn't change the visibility. + :param token: The huggingface token to use. + :param subfolder: The subfolder to push to. + """ + from model2vec.persistence import push_folder_to_hub + + with TemporaryDirectory() as temp_dir: + self.save_pretrained(temp_dir, model_name=repo_id) + push_folder_to_hub(Path(temp_dir), subfolder=subfolder, repo_id=repo_id, private=private, token=token) + + +def _disable_padding(tokenizer: Tokenizer) -> None: + """Stop the tokenizer from padding, while keeping its pad token.""" + padding = tokenizer.padding + if padding is not None: + tokenizer.enable_padding( + pad_id=padding["pad_id"], pad_token=padding["pad_token"], pad_type_id=padding["pad_type_id"], length=0 + ) + + +def _get_unk_token_id(tokenizer: Tokenizer) -> int | None: + """Get the unk token id.""" + model = tokenizer.model + # Wordpiece + BPE + Word level + if hasattr(model, "unk_token"): + token = model.unk_token + if token is None: + return None + return tokenizer.token_to_id(token) + # Unigram + return json.loads(tokenizer.to_str())["model"].get("unk_id") diff --git a/model2vec/model.py b/model2vec/model.py index 80bc8d40..43a1d083 100644 --- a/model2vec/model.py +++ b/model2vec/model.py @@ -1,40 +1,29 @@ from __future__ import annotations -import copy -import json import warnings from collections.abc import Sequence from logging import getLogger from pathlib import Path -from tempfile import TemporaryDirectory -from typing import Any, Generic, Mapping, cast, overload +from typing import Any, Mapping, TypeVar, cast, overload import model2vec_rs import numpy as np import numpy.typing as npt -from tokenizers import Encoding, Tokenizer -from typing_extensions import TypeVar +from tokenizers import Tokenizer +from model2vec.base import _DEFAULT_NORMALIZE, DEFAULT_MAX_LENGTH, BaseStaticModel, PathLike from model2vec.quantization import DType, quantize_and_reduce_dim from model2vec.types import _UNSET, StaticModelConfig, _UnsetType -PathLike = Path | str - logger = getLogger(__name__) -DEFAULT_MAX_LENGTH = 512 -_DEFAULT_NORMALIZE = False - - -ConfigT = TypeVar("ConfigT", bound=StaticModelConfig, default=StaticModelConfig) - -class StaticModel(Generic[ConfigT]): +class StaticModel(BaseStaticModel[StaticModelConfig]): def __init__( self, vectors: np.ndarray, tokenizer: Tokenizer, - config: ConfigT | None = None, + config: Mapping[str, Any] | None = None, normalize: bool = _DEFAULT_NORMALIZE, base_model_name: str | None = None, language: list[str] | None = None, @@ -66,13 +55,18 @@ def __init__( `config` is overridden. :raises ValueError: if the number of tokens does not match the number of vectors. """ - super().__init__() - tokens, _ = zip(*sorted(tokenizer.get_vocab().items(), key=lambda x: x[1])) - self.tokens = tokens + super().__init__( + tokenizer=tokenizer, + config=cast(StaticModelConfig, config), + normalize=normalize, + base_model_name=base_model_name, + language=language, + max_length=max_length, + ) - if token_mapping is None and vectors.shape[0] != len(tokens): + if token_mapping is None and len(vectors) != len(self.tokens): raise ValueError( - f"Number of tokens ({len(tokens)}) does not match number of vectors ({vectors.shape[0]}). " + f"Number of tokens ({len(self.tokens)}) does not match number of vectors ({len(vectors)}). " "Please provide a token mapping or ensure the number of tokens matches the number of vectors." ) @@ -80,20 +74,9 @@ def __init__( self.weights = weights self.token_mapping = token_mapping - self.tokenizer = copy.deepcopy(tokenizer) - _disable_padding(self.tokenizer) - self.unk_token_id = _get_unk_token_id(self.tokenizer) - - self.median_token_length = int(np.median([len(token) for token in self.tokens])) - self.config: ConfigT = cast(ConfigT, {**config} if config is not None else {}) - self.base_model_name = base_model_name - self.language = language - 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 = vars(self).copy() state.pop("_rust_backend", None) return state @@ -102,7 +85,7 @@ def __setstate__(self, state: dict[str, Any]) -> None: 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) + vars(self).update(state) @property def tokenizer(self) -> Tokenizer: @@ -112,7 +95,7 @@ def tokenizer(self) -> Tokenizer: @tokenizer.setter def tokenizer(self, value: Tokenizer) -> None: self._tokenizer = value - self.__dict__.pop("_rust_backend", None) + vars(self).pop("_rust_backend", None) @property def embedding(self) -> np.ndarray: @@ -150,7 +133,7 @@ def _get_rust_backend(self) -> model2vec_rs.StaticModel: :return: The Rust backend. """ key = (self.embedding, self.weights, self.token_mapping) - cached = self.__dict__.get("_rust_backend") + cached = vars(self).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] @@ -180,45 +163,6 @@ def dim(self) -> int: """Get the dimension of the model.""" return self.embedding.shape[1] - @property - def normalize(self) -> bool: - """Get the normalize value. - - :return: The normalize value. - """ - return self._normalize - - @normalize.setter - def normalize(self, value: bool) -> None: - """Update the config.""" - config_normalize = self.config.get("normalize") - self._normalize = value - if config_normalize is not None and value != config_normalize: - logger.warning( - f"Set normalization to `{value}`, which does not match config value `{config_normalize}`. Updating config." - ) - self.config["normalize"] = value - - @property - def max_length(self) -> int | None: - """Get the max_length value. - - :return: The max_length value. - """ - return self._max_length - - @max_length.setter - def max_length(self, value: int | None) -> None: - """Update the config.""" - config_max_length = self.config.get("max_length") - self._max_length = value - if config_max_length is not None and value != config_max_length: - logger.warning( - f"Set max_length to `{value}`, which does not match config value `{config_max_length}`. Updating config." - ) - self.config["max_length"] = value - self._set_max_length_in_tokenizer(value) - @property def embedding_dtype(self) -> str: """Get the dtype (precision) of the embedding matrix.""" @@ -227,7 +171,7 @@ def embedding_dtype(self) -> str: @property def vocabulary_quantization(self) -> int | None: """Get the number of clusters used for vocabulary quantization, if applicable.""" - is_quantized = (self.token_mapping is not None) or (self.embedding.shape[0] != len(self.tokens)) + is_quantized = (self.token_mapping is not None) or (len(self.embedding) != len(self.tokens)) return int(self.embedding.shape[0]) if is_quantized else None def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None: @@ -252,24 +196,6 @@ def save_pretrained(self, path: PathLike, model_name: str | None = None, subfold mapping=self.token_mapping, ) - def tokenize(self, sentences: Sequence[str]) -> list[list[int]]: - """Tokenize a list of sentences. - - :param sentences: The sentences to tokenize. - :return: A list of list of tokens. - """ - encodings: list[Encoding] = self.tokenizer.encode_batch_fast(sentences, add_special_tokens=False) - - encodings_ids = [encoding.ids for encoding in encodings] - - if self.unk_token_id is not None: - # NOTE: Remove the unknown token: necessary for word-level models. - encodings_ids = [ - [token_id for token_id in token_ids if token_id != self.unk_token_id] for token_ids in encodings_ids - ] - - return encodings_ids - @classmethod def from_pretrained( cls: type[T], @@ -318,13 +244,6 @@ def from_pretrained( force_download=force_download, ) - def _set_max_length_in_tokenizer(self, max_length: int | None) -> None: - """Sets the max length in the tokenizer.""" - if max_length is None: - self.tokenizer.no_truncation() - else: - self.tokenizer.enable_truncation(max_length) - @overload def encode_as_sequence(self, sentences: str, *, max_length: int | None = None, **kwargs: Any) -> np.ndarray: ... @@ -358,15 +277,7 @@ def encode_as_sequence( _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] - - self._set_max_length_in_tokenizer(max_length) - try: - ids = self.tokenize(sentence_list) - finally: - self._set_max_length_in_tokenizer(self.max_length) + ids = self._tokenize_truncated(sentence_list, 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: @@ -427,25 +338,6 @@ def _encode_helper(self, id_list: list[int]) -> np.ndarray: return emb - def push_to_hub( - self, repo_id: str, private: bool = False, token: str | None = None, subfolder: str | None = None - ) -> None: - """Push the model to the huggingface hub. - - NOTE: you need to pass a token if you are pushing a private model. - - :param repo_id: The repo id to push to. - :param private: Whether the repo, if created is set to private. - If the repo already exists, this doesn't change the visibility. - :param token: The huggingface token to use. - :param subfolder: The subfolder to push to. - """ - from model2vec.persistence import push_folder_to_hub - - with TemporaryDirectory() as temp_dir: - self.save_pretrained(temp_dir, model_name=repo_id) - push_folder_to_hub(Path(temp_dir), subfolder=subfolder, repo_id=repo_id, private=private, token=token) - def quantize_model( model: T, @@ -462,10 +354,7 @@ def quantize_model( This needs to be < than the current model dimensionality. :return: A new StaticModel with the quantized embeddings. :raises ValueError: if the model is already quantized. - :raises NotImplementedError: if the model does not have dense embeddings. """ - if not isinstance(model.embedding, np.ndarray): - raise NotImplementedError("Quantization is only supported for models with dense embeddings.") token_mapping: np.ndarray | None weights: np.ndarray | None if vocabulary_quantization is not None: @@ -553,28 +442,6 @@ def _loading_helper( ) -def _disable_padding(tokenizer: Tokenizer) -> None: - """Stop the tokenizer from padding, while keeping its pad token.""" - padding = tokenizer.padding - if padding is not None: - tokenizer.enable_padding( - pad_id=padding["pad_id"], pad_token=padding["pad_token"], pad_type_id=padding["pad_type_id"], length=0 - ) - - -def _get_unk_token_id(tokenizer: Tokenizer) -> int | None: - """Get the unk token id.""" - model = tokenizer.model - # Wordpiece + BPE + Word level - if hasattr(model, "unk_token"): - token = model.unk_token - if token is None: - return None - return tokenizer.token_to_id(token) - # Unigram - return json.loads(tokenizer.to_str())["model"].get("unk_id") - - _REMOVED_ARGUMENTS = ("batch_size", "show_progress_bar", "use_multiprocessing", "multiprocessing_threshold") @@ -611,4 +478,4 @@ def _read_only(array: np.ndarray | None) -> np.ndarray | None: return view -T = TypeVar("T", bound="StaticModel[Any]") +T = TypeVar("T", bound=StaticModel) diff --git a/model2vec/modelcards/sparse_model_card_template.md b/model2vec/modelcards/sparse_model_card_template.md index d2aa5b43..16dac6cf 100644 --- a/model2vec/modelcards/sparse_model_card_template.md +++ b/model2vec/modelcards/sparse_model_card_template.md @@ -31,6 +31,8 @@ documents = model.encode_document(["Example document"]) scores = queries @ documents.T ``` +This model can only be loaded with `SparseStaticModel`; it cannot be loaded with `StaticModel` or Sentence Transformers. + ## Additional Resources - [Model2Vec Repo](https://github.com/MinishLab/model2vec) diff --git a/model2vec/persistence/persistence.py b/model2vec/persistence/persistence.py index cf3740de..352c6ff4 100644 --- a/model2vec/persistence/persistence.py +++ b/model2vec/persistence/persistence.py @@ -24,7 +24,7 @@ SPARSE_INDPTR_KEY = "embeddings.indptr" SPARSE_INDICES_KEY = "embeddings.indices" SPARSE_DATA_KEY = "embeddings.data" -SPARSE_SHAPE_KEY = "shape" +SPARSE_SHAPE_KEY = "embeddings.shape" def save_pretrained( diff --git a/model2vec/sparse.py b/model2vec/sparse.py index 0dcf56be..3c0af3e6 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -17,7 +17,8 @@ from scipy.sparse import csr_matrix, diags from tokenizers import Tokenizer -from model2vec.model import _DEFAULT_NORMALIZE, DEFAULT_MAX_LENGTH, PathLike, StaticModel, _warn_removed_arguments +from model2vec.base import _DEFAULT_NORMALIZE, DEFAULT_MAX_LENGTH, BaseStaticModel, PathLike +from model2vec.model import _read_only, _warn_removed_arguments from model2vec.persistence.persistence import ( SPARSE_DATA_KEY, SPARSE_INDICES_KEY, @@ -30,10 +31,13 @@ logger = getLogger(__name__) -class SparseStaticModel(StaticModel[SparseStaticModelConfig]): +class SparseStaticModel(BaseStaticModel[SparseStaticModelConfig]): + _embedding: csr_matrix + _query_weights: np.ndarray | None + def __init__( self, - vectors: csr_matrix, + vectors: csr_matrix | np.ndarray, tokenizer: Tokenizer, config: SparseStaticModelConfig | None = None, normalize: bool = _DEFAULT_NORMALIZE, @@ -53,8 +57,9 @@ def __init__( weight of each token, which is its own code value to the power norm_coefficient. Scoring is the dot product of `encode_query` and `encode_document`. - :param vectors: The sparse code of each token, as a CSR matrix of shape (vocabulary size, vocabulary size). - :param tokenizer: The Transformers tokenizer to use. + :param vectors: The sparse code of each token, as a matrix of shape (vocabulary size, vocabulary size). + The model stores it as a read-only CSR matrix; assign a new matrix to `embedding` to change it. + :param tokenizer: The tokenizer to use. Stored as a copy. :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: @@ -63,69 +68,87 @@ def __init__( :param language: The language of the model. Used for creating a model card. :param max_length: The default maximum sequence length (in tokens) used by `encode` when its own `max_length` argument is not passed. Defaults to 512; pass None to disable truncation. - :param k1: The BM25 term frequency saturation of the document weights. Written to `config["k1"]`. + :param k1: The BM25 term frequency saturation of the document weights. Must be positive. + Written to `config["k1"]`. :param norm_coefficient: The power of its own code value that weights a query token. Written to `config["norm_coefficient"]`. :param length_exponent: The power of the token count each document is divided by. Written to `config["length_exponent"]`. """ super().__init__( - vectors=cast(np.ndarray, vectors), tokenizer=tokenizer, config=config, normalize=normalize, base_model_name=base_model_name, language=language, - weights=None, - token_mapping=None, max_length=max_length, ) + self.embedding = vectors self.k1 = k1 self.norm_coefficient = norm_coefficient self.length_exponent = length_exponent - @property # type: ignore[override] + def __setstate__(self, state: dict[str, Any]) -> None: + """Restore the state from pickling, keeping the sparse codes read-only.""" + vars(self).update(state) + self._embedding = _read_only_csr(self._embedding) + self._query_weights = None + + @property def embedding(self) -> csr_matrix: - """Get the sparse code of each token.""" + """The read-only sparse code of each token.""" return self._embedding @embedding.setter - def embedding(self, value: csr_matrix) -> None: + def embedding(self, value: csr_matrix | np.ndarray) -> None: """Validate and store the sparse codes, and reset the query weights. :param value: The sparse code of each token. - :raises ValueError: If the matrix is not square, or contains negative or non-finite values. + :raises ValueError: If the matrix is not square, does not have a row per token, or contains negative or + non-finite values. """ codes = csr_matrix(value) - if codes.shape[0] != codes.shape[1]: + n_rows, n_cols = _csr_shape(codes) + if n_rows != n_cols: raise ValueError( - f"The sparse codes must be square, with one latent per token, but got shape {codes.shape}." + f"The sparse codes must be square, with one latent per token, but got shape {(n_rows, n_cols)}." ) + if n_rows != len(self.tokens): + raise ValueError(f"Number of tokens ({len(self.tokens)}) does not match number of vectors ({n_rows}).") if not np.isfinite(codes.data).all(): raise ValueError("The sparse codes must be finite.") if codes.nnz and codes.data.min() < 0: raise ValueError("The sparse codes must be non-negative.") - self._embedding = codes - self._query_weights: np.ndarray | None = None + if not codes.has_canonical_format: + codes = codes.copy() + codes.sum_duplicates() + self._embedding = _read_only_csr(codes) + self._query_weights = None + + @property + def dim(self) -> int: + """Get the dimension of the model.""" + return _csr_shape(self.embedding)[1] @property - def codes(self) -> csr_matrix: - """Get the sparse code of each token.""" - return self.embedding + def embedding_dtype(self) -> str: + """Get the dtype (precision) of the sparse codes.""" + return np.dtype(self.embedding.dtype).name @property def _dtype(self) -> np.dtype: """Get the floating point dtype of the encoded vectors.""" - return np.result_type(self.codes.dtype, np.float32) + return np.result_type(self.embedding.dtype, np.float32) @property def query_weights(self) -> np.ndarray: """Get the query weight of each token: its own code value to the power norm_coefficient, or 0 if that is 0.""" if self._query_weights is None: - diagonal = self.codes.diagonal().astype(self._dtype) + diagonal = self.embedding.diagonal().astype(self._dtype) weights = np.zeros_like(diagonal) positive = diagonal > 0 weights[positive] = diagonal[positive] ** self.norm_coefficient + weights.setflags(write=False) self._query_weights = weights return self._query_weights @@ -136,7 +159,13 @@ def k1(self) -> float: @k1.setter def k1(self, value: float) -> None: - """Update the config.""" + """Validate k1 and update the config. + + :param value: The new k1 value. + :raises ValueError: If k1 is not positive. + """ + if not value > 0: + raise ValueError(f"k1 must be positive, but got {value}.") self._k1 = value self._update_config("k1", value) @@ -163,23 +192,13 @@ def length_exponent(self, value: float) -> None: self._length_exponent = value self._update_config("length_exponent", value) - def _update_config(self, key: str, value: float) -> None: - """Write a value to the config, warning if it conflicts with the value already there.""" - config = cast(dict[str, Any], self.config) - config_value = config.get(key) - if config_value is not None and value != config_value: - logger.warning( - f"Set {key} to `{value}`, which does not match config value `{config_value}`. Updating config." - ) - config[key] = value - def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None: """Save the pretrained sparse model. The sparse matrix is stored in `model.safetensors` as CSR arrays: `embeddings.indptr`, an int64 array of shape (rows + 1,), `embeddings.indices`, an int32 array of column indices of shape (nnz,), and `embeddings.data`, an array of values of shape (nnz,). The shape of the matrix is stored in the - safetensors header. + safetensors header as `embeddings.shape`. :param path: The path to save to. :param model_name: The model name to use in the Model Card. @@ -187,8 +206,8 @@ def save_pretrained(self, path: PathLike, model_name: str | None = None, subfold """ from model2vec.persistence import save_folder - tensors, tensor_metadata = _sparse_to_tensors(self.codes) - config = {**self.config, "embedding_dtype": np.dtype(self.codes.dtype).name} + tensors, tensor_metadata = _sparse_to_tensors(self.embedding) + config = {**self.config, "embedding_dtype": self.embedding_dtype} save_folder( folder_path=Path(path), @@ -205,7 +224,7 @@ def save_pretrained(self, path: PathLike, model_name: str | None = None, subfold ) @classmethod - def from_pretrained( # type: ignore[override] + def from_pretrained( cls, path: PathLike, token: str | None = None, @@ -269,31 +288,33 @@ def from_pretrained( # type: ignore[override] length_exponent=length_exponent, ) - def encode( # type: ignore[override] + def encode( self, - sentences: Sequence[str], + sentences: str | Sequence[str], *, max_length: int | None | _UnsetType = _UNSET, normalize: bool | None = None, **kwargs: Any, ) -> csr_matrix: - """Encode a list of documents into saturated sparse weights, which depend on no corpus statistics. + """Encode a list of documents into sparse vectors. This is the same as `encode_document`. - :param sentences: The list of sentences to encode. You can also pass a single sentence. - :param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated. + :param sentences: The list of documents to encode. You can also pass a single document. + :param max_length: The maximum length of the documents. 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 **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 as a CSR matrix. If a single sentence was passed, a 1-row matrix is returned. + :return: The encoded documents as a CSR matrix. If a single document was passed, a 1-row matrix is returned. """ _warn_removed_arguments(kwargs) - return self._encode_sparse(sentences, batch_fn=self._encode_batch, max_length=max_length, normalize=normalize) + return self._encode_sparse( + sentences, batch_fn=self._encode_document_batch, max_length=max_length, normalize=normalize + ) def encode_query( self, - sentences: Sequence[str], + sentences: str | Sequence[str], *, max_length: int | None | _UnsetType = _UNSET, normalize: bool | None = None, @@ -301,6 +322,8 @@ def encode_query( ) -> csr_matrix: """Encode a list of queries into sparse vectors. + Query tokens with a query weight of 0, which are tokens whose own code value is 0, are left out. + :param sentences: The list of queries to encode. You can also pass a single query. :param max_length: The maximum length of the queries. 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. @@ -317,7 +340,7 @@ def encode_query( def encode_document( self, - sentences: Sequence[str], + sentences: str | Sequence[str], *, max_length: int | None | _UnsetType = _UNSET, normalize: bool | None = None, @@ -335,32 +358,22 @@ def encode_document( :return: The encoded documents as a CSR matrix. If a single document was passed, a 1-row matrix is returned. """ _warn_removed_arguments(kwargs) - return self._encode_sparse(sentences, batch_fn=self._encode_batch, max_length=max_length, normalize=normalize) - - def encode_as_sequence( # type: ignore[override] - self, sentences: str | list[str], **kwargs: Any - ) -> list[np.ndarray] | np.ndarray: - """Not supported for sparse models. - - :param sentences: The sentences to encode. - :param **kwargs: Any additional arguments. - :return: Never returns. - :raises NotImplementedError: Always. - """ - raise NotImplementedError("encode_as_sequence is not supported for SparseStaticModel.") + return self._encode_sparse( + sentences, batch_fn=self._encode_document_batch, max_length=max_length, normalize=normalize + ) def _encode_sparse( self, - sentences: Sequence[str], + sentences: str | Sequence[str], *, - batch_fn: Callable[[Sequence[str], bool], csr_matrix], + batch_fn: Callable[[list[list[int]], bool], csr_matrix], max_length: int | None | _UnsetType, normalize: bool | None, ) -> csr_matrix: - """Resolve defaults, truncate, and encode the sentences with `batch_fn`. + """Resolve defaults, tokenize, and encode the token ids with `batch_fn`. :param sentences: The sentences to encode. - :param batch_fn: The function that encodes the sentences. + :param batch_fn: The function that encodes the token ids. :param max_length: The maximum length of the sentences. If unset, the model's `max_length` is used. :param normalize: Whether to normalize the resulting vectors. If None, the model's `normalize` is used. :return: The encoded sentences as a CSR matrix. If a single sentence was passed, a 1-row matrix is returned. @@ -374,27 +387,20 @@ def _encode_sparse( sentence_list: list[str] = [sentences] if isinstance(sentences, str) else list(sentences) if not sentence_list: return csr_matrix((0, self.dim), dtype=self._dtype) - if max_length is not None: - m = max_length * self.median_token_length - sentence_list = [sentence[:m] for sentence in sentence_list] - - self._set_max_length_in_tokenizer(max_length) - try: - out = batch_fn(sentence_list, normalize) - finally: - self._set_max_length_in_tokenizer(self.max_length) + out = batch_fn(self._tokenize_truncated(sentence_list, max_length), normalize) if was_single: return out[0] return out - def _bag(self, sentences: Sequence[str]) -> tuple[csr_matrix, np.ndarray]: - """Tokenize sentences into a bag of token counts, and their token counts.""" - ids = self.tokenize(sentences) + def _bag(self, ids: list[list[int]]) -> tuple[csr_matrix, np.ndarray]: + """Turn token ids into a bag of token counts, and the token count of each sentence.""" lengths = np.array([len(x) for x in ids], dtype=np.int64) rows = np.repeat(np.arange(len(ids)), lengths) - cols = np.concatenate([np.asarray(x, dtype=np.int64) for x in ids]) if ids else np.zeros(0, np.int64) - bag = csr_matrix((np.ones(len(cols), dtype=self._dtype), (rows, cols)), shape=(len(ids), self.codes.shape[0])) + cols = np.concatenate([np.asarray(x, dtype=np.int64) for x in ids]) + bag = csr_matrix( + (np.ones(len(cols), dtype=self._dtype), (rows, cols)), shape=(len(ids), _csr_shape(self.embedding)[0]) + ) return bag, lengths def saturate(self, weights: csr_matrix) -> csr_matrix: @@ -407,31 +413,47 @@ def saturate(self, weights: csr_matrix) -> csr_matrix: out.data = weights.data * (self.k1 + 1) / (weights.data + self.k1) return out - def _encode_batch(self, sentences: Sequence[str], normalize: bool) -> csr_matrix: # type: ignore[override] - """Encode a batch of documents into sparse vectors. + def _encode_document_batch(self, ids: list[list[int]], normalize: bool) -> csr_matrix: + """Encode the token ids of a batch of documents into sparse vectors. - :param sentences: The documents to encode. + :param ids: The token ids of each document. :param normalize: Whether to normalize the resulting vectors. :return: The encoded documents as a CSR matrix. """ - bag, lengths = self._bag(sentences) + bag, lengths = self._bag(ids) length_norm = diags(np.maximum(lengths, 1).astype(self._dtype) ** -self.length_exponent) - pooled = (length_norm @ (bag @ self.codes).sqrt()).tocsr() + summed = csr_matrix(bag @ self.embedding) + summed.data = np.sqrt(summed.data) + pooled = csr_matrix(length_norm @ summed) return _maybe_normalize(self.saturate(pooled), normalize) - def _encode_query_batch(self, sentences: Sequence[str], normalize: bool) -> csr_matrix: - """Encode a batch of queries into sparse vectors. + def _encode_query_batch(self, ids: list[list[int]], normalize: bool) -> csr_matrix: + """Encode the token ids of a batch of queries into sparse vectors. - :param sentences: The queries to encode. + :param ids: The token ids of each query. :param normalize: Whether to normalize the resulting vectors. :return: The encoded queries as a CSR matrix. """ - bag, _ = self._bag(sentences) + bag, _ = self._bag(ids) bag.data = np.sqrt(bag.data) * self.query_weights[bag.indices] bag.eliminate_zeros() return _maybe_normalize(bag, normalize) +def _csr_shape(matrix: csr_matrix) -> tuple[int, int]: + """Get the shape of a CSR matrix.""" + return cast(tuple[int, int], matrix.shape) + + +def _read_only_csr(matrix: csr_matrix) -> csr_matrix: + """Return a CSR matrix that shares the arrays of `matrix` through read-only views.""" + frozen = csr_matrix(matrix) + frozen.data = _read_only(frozen.data) + frozen.indices = _read_only(frozen.indices) + frozen.indptr = _read_only(frozen.indptr) + return frozen + + def _maybe_normalize(matrix: csr_matrix, normalize: bool) -> csr_matrix: """L2-normalize the rows of a sparse matrix if `normalize` is True; all-zero rows stay zero.""" if not normalize: @@ -442,15 +464,13 @@ def _maybe_normalize(matrix: csr_matrix, normalize: bool) -> csr_matrix: def _sparse_to_tensors(matrix: csr_matrix) -> tuple[dict[str, np.ndarray], dict[str, str]]: - """Convert a sparse matrix to safetensors-compatible CSR arrays and header metadata.""" - csr = csr_matrix(matrix, copy=True) - csr.sum_duplicates() + """Convert a canonical CSR matrix to safetensors-compatible CSR arrays and header metadata.""" tensors: dict[str, np.ndarray] = { - SPARSE_INDPTR_KEY: np.ascontiguousarray(csr.indptr, dtype=np.int64), - SPARSE_INDICES_KEY: np.ascontiguousarray(csr.indices, dtype=np.int32), - SPARSE_DATA_KEY: np.ascontiguousarray(csr.data), + SPARSE_INDPTR_KEY: np.ascontiguousarray(matrix.indptr, dtype=np.int64), + SPARSE_INDICES_KEY: np.ascontiguousarray(matrix.indices, dtype=np.int32), + SPARSE_DATA_KEY: np.ascontiguousarray(matrix.data), } - return tensors, {SPARSE_SHAPE_KEY: json.dumps([int(dim) for dim in csr.shape])} + return tensors, {SPARSE_SHAPE_KEY: json.dumps([int(dim) for dim in _csr_shape(matrix)])} def _tensors_to_sparse(tensor_file: SafeOpenProtocol) -> csr_matrix: diff --git a/model2vec/train/base.py b/model2vec/train/base.py index e908b880..7c76fdd3 100644 --- a/model2vec/train/base.py +++ b/model2vec/train/base.py @@ -13,8 +13,9 @@ from torch import nn from tqdm import trange +from model2vec.base import _disable_padding, _get_unk_token_id from model2vec.inference import StaticModelPipeline -from model2vec.model import DEFAULT_MAX_LENGTH, PathLike, StaticModel, _disable_padding, _get_unk_token_id +from model2vec.model import DEFAULT_MAX_LENGTH, PathLike, StaticModel from model2vec.train.dataset import ( ColumnRows, PairDataset, diff --git a/pyproject.toml b/pyproject.toml index d1ab19d7..76a66d85 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,6 @@ dependencies = [ "safetensors", "tokenizers>=0.22,<1.0.0", "tqdm", - "typing-extensions>=4.4.0", "huggingface-hub>=1.0.0", "model2vec-rs>=0.5.1,<0.6.0", ] diff --git a/tests/test_sparse.py b/tests/test_sparse.py index 0b45354f..78d3ecbb 100644 --- a/tests/test_sparse.py +++ b/tests/test_sparse.py @@ -1,4 +1,6 @@ +import copy import json +import pickle from pathlib import Path from typing import Any @@ -9,7 +11,6 @@ from tokenizers import Tokenizer from model2vec import StaticModel -from model2vec.model import quantize_model from model2vec.sparse import SparseStaticModel K1 = 1.2 @@ -76,9 +77,7 @@ def test_initialization( assert model.embedding.shape == (5, 5) assert model.dim == 5 assert len(model.tokens) == 5 - assert model.weights is None - assert model.token_mapping is None - assert model.vocabulary_quantization is None + assert not isinstance(model, StaticModel) assert np.allclose(model.query_weights, np.diag(_CODES) ** NORM_COEFFICIENT) assert model.k1 == K1 assert model.norm_coefficient == NORM_COEFFICIENT @@ -293,10 +292,34 @@ def test_query_tokens_with_zero_weight_are_dropped(mock_tokenizer: Tokenizer) -> assert out.indices.tolist() == [1] -def test_quantize_model_raises(mock_sparse_model: SparseStaticModel) -> None: - """Test that quantizing a sparse model raises.""" - with pytest.raises(NotImplementedError, match="dense"): - quantize_model(mock_sparse_model, quantize_to="float16") +@pytest.mark.parametrize("k1", [0.0, -1.0, float("nan")]) +def test_non_positive_k1_raises(mock_sparse_model: SparseStaticModel, k1: float) -> None: + """Test that k1 must be positive.""" + with pytest.raises(ValueError, match="k1 must be positive"): + mock_sparse_model.k1 = k1 + assert mock_sparse_model.k1 == K1 + + +def test_codes_are_read_only(mock_sparse_model: SparseStaticModel) -> None: + """Test that the stored codes and query weights cannot be changed in place.""" + for array in ( + mock_sparse_model.embedding.data, + mock_sparse_model.embedding.indices, + mock_sparse_model.embedding.indptr, + mock_sparse_model.query_weights, + ): + with pytest.raises(ValueError, match="read-only"): + array[0] = 1 + + +def test_pickle_and_copy(mock_sparse_model: SparseStaticModel) -> None: + """Test that a sparse model can be pickled and copied, and stays read-only.""" + expected = mock_sparse_model.encode_query(["word1 word3"]).toarray() + for clone in (pickle.loads(pickle.dumps(mock_sparse_model)), copy.deepcopy(mock_sparse_model)): + assert isinstance(clone.embedding, csr_matrix) + assert not clone.embedding.data.flags.writeable + assert np.allclose(clone.encode_query(["word1 word3"]).toarray(), expected) + assert clone.k1 == K1 @pytest.mark.parametrize("method", ["encode", "encode_query", "encode_document"]) @@ -338,12 +361,6 @@ def test_encode_batches_match_single_batch(mock_sparse_model: SparseStaticModel, assert np.allclose(single.toarray(), unbatched[0].toarray()) -def test_encode_as_sequence_not_implemented(mock_sparse_model: SparseStaticModel) -> None: - """Test that encode_as_sequence raises NotImplementedError.""" - with pytest.raises(NotImplementedError): - mock_sparse_model.encode_as_sequence(["word1 word2"]) - - def test_save_and_load_roundtrip(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: """Test that saving and loading a sparse model preserves the matrix, query weights and config.""" mock_sparse_model.save_pretrained(tmp_path) @@ -363,7 +380,7 @@ def test_save_and_load_roundtrip(mock_sparse_model: SparseStaticModel, tmp_path: def test_save_stores_csr_arrays(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: - """Test the on-disk format: CSR arrays and query weights, shape in the header, no modules.json.""" + """Test the on-disk format: CSR arrays, shape in the header, no modules.json.""" mock_sparse_model.save_pretrained(tmp_path) with safetensors.safe_open(tmp_path / "model.safetensors", framework="numpy") as f: @@ -377,7 +394,7 @@ def test_save_stores_csr_arrays(mock_sparse_model: SparseStaticModel, tmp_path: assert indices.shape == (nnz,) assert indices.dtype == np.int32 assert f.get_tensor("embeddings.data").shape == (nnz,) - assert json.loads(f.metadata()["shape"]) == list(mock_sparse_model.embedding.shape) + assert json.loads(f.metadata()["embeddings.shape"]) == list(mock_sparse_model.embedding.shape) config = json.loads((tmp_path / "config.json").read_text()) assert config["k1"] == mock_sparse_model.k1 @@ -404,7 +421,7 @@ def test_load_sparse_model_as_dense_raises(mock_sparse_model: SparseStaticModel, def test_save_and_load_non_canonical_matrix(mock_tokenizer: Tokenizer, tmp_path: Path) -> None: - """Test that a matrix with unsorted and duplicate entries round-trips without changing the model.""" + """Test that a matrix with unsorted and duplicate entries is stored canonically, and round-trips.""" rows = np.array([1, 1, 1, 3]) cols = np.array([2, 1, 2, 3]) data = np.array([0.25, 2.0, 0.25, 3.0]) @@ -422,9 +439,11 @@ def test_save_and_load_non_canonical_matrix(mock_tokenizer: Tokenizer, tmp_path: expected = np.zeros((5, 5)) np.add.at(expected, (rows, cols), data) + assert np.allclose(model.embedding.toarray(), expected) assert np.allclose(loaded.embedding.toarray(), expected) + assert model.embedding.has_canonical_format assert loaded.embedding.has_canonical_format - assert not model.embedding.has_canonical_format + assert not codes.has_canonical_format def test_save_and_load_subfolder(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: diff --git a/uv.lock b/uv.lock index d3c5098c..e6cc27e9 100644 --- a/uv.lock +++ b/uv.lock @@ -1269,7 +1269,6 @@ dependencies = [ { name = "safetensors" }, { name = "tokenizers" }, { name = "tqdm" }, - { name = "typing-extensions" }, ] [package.optional-dependencies] @@ -1349,7 +1348,6 @@ requires-dist = [ { name = "torch", marker = "extra == 'train'" }, { name = "tqdm" }, { name = "transformers", marker = "extra == 'distill'", specifier = "<5.4.0" }, - { name = "typing-extensions", specifier = ">=4.4.0" }, ] provides-extras = ["dev", "distill", "onnx", "train", "quantization", "sparse", "integration", "tests"] From 16200201bf600f9826a9e41279e3cdf0dc5b15ce Mon Sep 17 00:00:00 2001 From: stephantul Date: Tue, 1 Dec 2026 11:18:01 +0100 Subject: [PATCH 3/4] fix sparse --- .../modelcards/sparse_model_card_template.md | 11 +- model2vec/persistence/persistence.py | 9 +- .../sentence-transformers/sparse_encoder.py | 121 ++++++++++++ model2vec/sparse.py | 36 +++- pyproject.toml | 1 + tests/test_sparse.py | 12 +- tests/test_sparse_encoder.py | 185 ++++++++++++++++++ 7 files changed, 368 insertions(+), 7 deletions(-) create mode 100644 model2vec/sentence-transformers/sparse_encoder.py create mode 100644 tests/test_sparse_encoder.py diff --git a/model2vec/modelcards/sparse_model_card_template.md b/model2vec/modelcards/sparse_model_card_template.md index 16dac6cf..fe67010b 100644 --- a/model2vec/modelcards/sparse_model_card_template.md +++ b/model2vec/modelcards/sparse_model_card_template.md @@ -31,7 +31,16 @@ documents = model.encode_document(["Example document"]) scores = queries @ documents.T ``` -This model can only be loaded with `SparseStaticModel`; it cannot be loaded with `StaticModel` or Sentence Transformers. +This model can also be loaded as a [Sentence Transformers](https://github.com/huggingface/sentence-transformers) `SparseEncoder`, which requires `model2vec[sparse]` to be installed: +```python +from sentence_transformers import SparseEncoder + +model = SparseEncoder("{{ model_name }}", trust_remote_code=True) + +queries = model.encode_query(["Example query"]) +documents = model.encode_document(["Example document"]) +scores = model.similarity(queries, documents) +``` ## Additional Resources diff --git a/model2vec/persistence/persistence.py b/model2vec/persistence/persistence.py index 352c6ff4..5f139dec 100644 --- a/model2vec/persistence/persistence.py +++ b/model2vec/persistence/persistence.py @@ -89,9 +89,10 @@ def save_folder( create_model_card: bool = True, subfolder: str | None = None, tensor_metadata: dict[str, str] | None = None, + sentence_transformers_config: Mapping[str, Any] | None = None, **kwargs: Any, ) -> None: - """Save tensors, a tokenizer, a config, and optionally modules.json and a model card to a folder. + """Save tensors, a tokenizer, a config, and optionally Sentence Transformers files and a model card to a folder. :param folder_path: The path to the folder. :param tensors: The tensors to store in `model.safetensors`. @@ -101,6 +102,8 @@ def save_folder( :param create_model_card: Whether to create a model card. :param subfolder: The subfolder to save the model in. :param tensor_metadata: Metadata to store in the header of `model.safetensors`. + :param sentence_transformers_config: The contents of `config_sentence_transformers.json`. If None, no + `config_sentence_transformers.json` is written. :param **kwargs: Any additional arguments, passed to the model card. """ folder_path = folder_path / subfolder if subfolder else folder_path @@ -116,6 +119,10 @@ def save_folder( with open(folder_path / "modules.json", "w") as modules_file: json.dump(modules, modules_file, indent=4) + if sentence_transformers_config is not None: + with open(folder_path / "config_sentence_transformers.json", "w") as st_config_file: + json.dump(dict(sentence_transformers_config), st_config_file, indent=4) + logger.info(f"Saved model to {folder_path}") if create_model_card: diff --git a/model2vec/sentence-transformers/sparse_encoder.py b/model2vec/sentence-transformers/sparse_encoder.py new file mode 100644 index 00000000..e55d8b4e --- /dev/null +++ b/model2vec/sentence-transformers/sparse_encoder.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, cast + +import torch +from sentence_transformers.base.modality_types import PairInput, SingleInput +from sentence_transformers.base.modules import InputModule +from transformers import PreTrainedTokenizerFast + +from model2vec.sparse import SparseStaticModel + +_TASKS = (None, "query", "document") + + +class SparseStaticEmbedding(InputModule): + def __init__(self, model: SparseStaticModel) -> None: + """A Sentence Transformers input module that encodes texts with a SparseStaticModel. + + Texts encoded with the "query" task, as `SparseEncoder.encode_query` does, are encoded with + `SparseStaticModel.encode_query`. All other texts are encoded with `SparseStaticModel.encode_document`. + + :param model: The sparse model. + """ + super().__init__() + self.model = model + self.tokenizer = PreTrainedTokenizerFast(tokenizer_object=model.tokenizer) + + @property + def max_seq_length(self) -> int | None: + """The maximum number of tokens of a text.""" + return self.model.max_length + + @max_seq_length.setter + def max_seq_length(self, value: int | None) -> None: + self.model.max_length = value + + def get_embedding_dimension(self) -> int: + """Get the dimension of the sparse vectors. + + :return: The dimension. + """ + return self.model.dim + + def preprocess( + self, + inputs: list[SingleInput | PairInput], + prompt: str | None = None, + task: str | None = None, + **kwargs: Any, + ) -> dict[str, Any]: + """Collect the texts and the task to encode them with. + + :param inputs: The texts. Only text inputs are supported. + :param prompt: A prompt to prepend to each text. + :param task: The task: "query", "document", or None, which is encoded as "document". + :param **kwargs: Any additional arguments. These are ignored. + :return: The texts and the task. + :raises ValueError: If the task is not "query", "document" or None. + """ + if task not in _TASKS: + raise ValueError(f"Unknown task `{task}`. Expected one of {_TASKS}.") + texts = cast(list[str], inputs) + texts = self._prepend_prompt(texts, prompt) if prompt else list(texts) + return {"texts": texts, "task": task} + + def forward(self, features: dict[str, Any], **kwargs: Any) -> dict[str, Any]: + """Encode the texts as queries or documents. + + :param features: The texts and the task, as returned by `preprocess`. + :param **kwargs: Any additional arguments. These are ignored. + :return: The features, with the sparse vectors as a dense tensor under `sentence_embedding`. + """ + encode = self.model.encode_query if features["task"] == "query" else self.model.encode_document + features["sentence_embedding"] = torch.from_numpy(encode(features["texts"]).toarray()) + return features + + def save(self, output_path: str, *args: Any, safe_serialization: bool = True, **kwargs: Any) -> None: + """Save the sparse model, without the files that Sentence Transformers writes itself. + + :param output_path: The folder to save to. + :param *args: Any additional arguments. These are ignored. + :param safe_serialization: Ignored: the model is always stored as safetensors. + :param **kwargs: Any additional arguments. These are ignored. + """ + self.model._save(Path(output_path), sentence_transformers_files=False) + + @classmethod + def load( + cls, + model_name_or_path: str, + subfolder: str = "", + token: bool | str | None = None, + cache_folder: str | None = None, + revision: str | None = None, + local_files_only: bool = False, + **kwargs: Any, + ) -> SparseStaticEmbedding: + """Load the module from a local folder or a Hugging Face repo. + + :param model_name_or_path: The local folder or the Hugging Face repo id. + :param subfolder: The subfolder to load from. + :param token: The Hugging Face token to use. + :param cache_folder: The folder to cache downloaded files in. + :param revision: The revision of the repo to load. + :param local_files_only: Whether to only use local files. + :param **kwargs: Any additional arguments. These are ignored. + :return: The module. + :raises ValueError: If the model could not be found. + """ + folder = cls.load_dir_path( + model_name_or_path, + subfolder=subfolder, + token=token, + cache_folder=cache_folder, + revision=revision, + local_files_only=local_files_only, + ) + if folder is None: + raise ValueError(f"Could not find a sparse model at `{model_name_or_path}`.") + return cls(SparseStaticModel.from_pretrained(folder, force_download=False)) diff --git a/model2vec/sparse.py b/model2vec/sparse.py index 3c0af3e6..70ea20b7 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -8,6 +8,7 @@ importable(extra_dependency, _REQUIRED_EXTRA) import json +import shutil from collections.abc import Callable, Sequence from logging import getLogger from pathlib import Path @@ -30,6 +31,11 @@ logger = getLogger(__name__) +_SENTENCE_TRANSFORMERS_MODULE_FILE = Path(__file__).parent / "sentence-transformers" / "sparse_encoder.py" +_SENTENCE_TRANSFORMERS_MODULE_TYPE = f"{_SENTENCE_TRANSFORMERS_MODULE_FILE.stem}.SparseStaticEmbedding" +_SENTENCE_TRANSFORMERS_MODULES = [{"idx": 0, "name": "0", "path": "", "type": _SENTENCE_TRANSFORMERS_MODULE_TYPE}] +_SENTENCE_TRANSFORMERS_CONFIG = {"model_type": "SparseEncoder", "similarity_fn_name": "dot"} + class SparseStaticModel(BaseStaticModel[SparseStaticModelConfig]): _embedding: csr_matrix @@ -199,10 +205,30 @@ def save_pretrained(self, path: PathLike, model_name: str | None = None, subfold shape (rows + 1,), `embeddings.indices`, an int32 array of column indices of shape (nnz,), and `embeddings.data`, an array of values of shape (nnz,). The shape of the matrix is stored in the safetensors header as `embeddings.shape`. + The folder also contains `modules.json` and `config_sentence_transformers.json`, so that it can be loaded + as a Sentence Transformers `SparseEncoder`. + + :param path: The path to save to. + :param model_name: The model name to use in the Model Card. + :param subfolder: The subfolder to save to. + """ + self._save(Path(path), model_name=model_name, subfolder=subfolder, sentence_transformers_files=True) + + def _save( + self, + path: Path, + *, + model_name: str | None = None, + subfolder: str | None = None, + sentence_transformers_files: bool, + ) -> None: + """Save the sparse model, with or without the model card and the Sentence Transformers files. :param path: The path to save to. :param model_name: The model name to use in the Model Card. :param subfolder: The subfolder to save to. + :param sentence_transformers_files: Whether to write the model card, `modules.json`, + `config_sentence_transformers.json` and the source file of the Sentence Transformers module. """ from model2vec.persistence import save_folder @@ -210,18 +236,24 @@ def save_pretrained(self, path: PathLike, model_name: str | None = None, subfold config = {**self.config, "embedding_dtype": self.embedding_dtype} save_folder( - folder_path=Path(path), + folder_path=path, tensors=tensors, tokenizer=self.tokenizer, config=config, + modules=_SENTENCE_TRANSFORMERS_MODULES if sentence_transformers_files else None, + create_model_card=sentence_transformers_files, subfolder=subfolder, tensor_metadata=tensor_metadata, + sentence_transformers_config=_SENTENCE_TRANSFORMERS_CONFIG if sentence_transformers_files else None, base_model_name=self.base_model_name, language=self.language, model_name=model_name, template_path="sparse_model_card_template.md", - tags=["embeddings", "static-embeddings", "sparse"], + tags=["embeddings", "static-embeddings", "sparse", "sentence-transformers", "sparse-encoder"], ) + if sentence_transformers_files: + folder = path / subfolder if subfolder else path + shutil.copyfile(_SENTENCE_TRANSFORMERS_MODULE_FILE, folder / _SENTENCE_TRANSFORMERS_MODULE_FILE.name) @classmethod def from_pretrained( diff --git a/pyproject.toml b/pyproject.toml index 76a66d85..688626fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,6 +45,7 @@ license-files = [] model2vec = [ "assets/modelcards/model_card_template.md", "assets/modelcards/classifier_template.md", + "sentence-transformers/sparse_encoder.py", "py.typed" ] diff --git a/tests/test_sparse.py b/tests/test_sparse.py index 78d3ecbb..24a43834 100644 --- a/tests/test_sparse.py +++ b/tests/test_sparse.py @@ -380,7 +380,7 @@ def test_save_and_load_roundtrip(mock_sparse_model: SparseStaticModel, tmp_path: def test_save_stores_csr_arrays(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: - """Test the on-disk format: CSR arrays, shape in the header, no modules.json.""" + """Test the on-disk format: CSR arrays, shape in the header, and the Sentence Transformers files.""" mock_sparse_model.save_pretrained(tmp_path) with safetensors.safe_open(tmp_path / "model.safetensors", framework="numpy") as f: @@ -402,14 +402,20 @@ def test_save_stores_csr_arrays(mock_sparse_model: SparseStaticModel, tmp_path: assert config["length_exponent"] == mock_sparse_model.length_exponent assert config["embedding_dtype"] == "float64" assert "sparse" not in config - assert not (tmp_path / "modules.json").exists() + + modules = json.loads((tmp_path / "modules.json").read_text()) + assert modules == [{"idx": 0, "name": "0", "path": "", "type": "sparse_encoder.SparseStaticEmbedding"}] + assert (tmp_path / "sparse_encoder.py").exists() + st_config = json.loads((tmp_path / "config_sentence_transformers.json").read_text()) + assert st_config == {"model_type": "SparseEncoder", "similarity_fn_name": "dot"} def test_save_model_card(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: - """Test that the model card shows how to load the model as a sparse model.""" + """Test that the model card shows how to load the model as a sparse model and as a SparseEncoder.""" mock_sparse_model.save_pretrained(tmp_path, model_name="sparse-model") readme = (tmp_path / "README.md").read_text() assert 'SparseStaticModel.from_pretrained("sparse-model")' in readme + assert 'SparseEncoder("sparse-model", trust_remote_code=True)' in readme assert "from model2vec import StaticModel" not in readme diff --git a/tests/test_sparse_encoder.py b/tests/test_sparse_encoder.py new file mode 100644 index 00000000..7c1795f3 --- /dev/null +++ b/tests/test_sparse_encoder.py @@ -0,0 +1,185 @@ +import importlib +import importlib.util +from pathlib import Path +from typing import Any + +import numpy as np +import pytest +import torch +from scipy.sparse import csr_matrix +from tokenizers import Tokenizer + +from model2vec.sparse import _SENTENCE_TRANSFORMERS_MODULE_FILE, SparseStaticModel + +pytest.importorskip("sentence_transformers") + +from sentence_transformers import SparseEncoder # noqa: E402 + + +def _load_module_class() -> Any: + """Load SparseStaticEmbedding from the source file that is copied into saved models.""" + spec = importlib.util.spec_from_file_location("sparse_encoder", _SENTENCE_TRANSFORMERS_MODULE_FILE) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.SparseStaticEmbedding + + +SparseStaticEmbedding = _load_module_class() + +QUERIES = ["word1 word1 word3", "word2", ""] +DOCUMENTS = ["word1 word2", "word3 word3 word1", "word2", ""] + + +@pytest.fixture +def sparse_model(mock_tokenizer: Tokenizer) -> SparseStaticModel: + """Create a sparse model over the mock vocabulary: [PAD], word1, word2, word3, [UNK].""" + codes = np.array( + [ + [0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 2.0, 0.5, 0.0, 0.0], + [0.0, 0.5, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 3.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 0.0], + ], + dtype=np.float32, + ) + return SparseStaticModel( + vectors=csr_matrix(codes), tokenizer=mock_tokenizer, k1=1.2, norm_coefficient=0.75, length_exponent=0.3 + ) + + +@pytest.fixture +def encoder(sparse_model: SparseStaticModel) -> SparseEncoder: + """Create a SparseEncoder from the module in the model2vec package.""" + return SparseEncoder(modules=[SparseStaticEmbedding(sparse_model)], similarity_fn_name="dot") + + +@pytest.fixture +def remote_encoder(sparse_model: SparseStaticModel, tmp_path: Path) -> SparseEncoder: + """Save the sparse model and load it as a SparseEncoder, with the module from the saved source file.""" + sparse_model.save_pretrained(tmp_path / "model") + return SparseEncoder(str(tmp_path / "model"), trust_remote_code=True) + + +def _tensor(value: object) -> torch.Tensor: + """Check that an encoded value is a single tensor.""" + assert isinstance(value, torch.Tensor) + return value + + +def _dense(value: object) -> np.ndarray: + """Convert an encoded sparse or dense tensor to a numpy array.""" + return _tensor(value).to_dense().numpy() + + +def test_module_is_not_importable_from_model2vec() -> None: + """Test that the module source is not part of the model2vec API.""" + for name in ("model2vec.sparse_encoder", "model2vec.sentence_transformers.sparse_encoder"): + with pytest.raises(ModuleNotFoundError): + importlib.import_module(name) + + +def test_save_copies_module_source(sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that saving puts the module's source file next to modules.json, also in a subfolder.""" + for subfolder in (None, "sub"): + sparse_model.save_pretrained(tmp_path, subfolder=subfolder) + folder = tmp_path / subfolder if subfolder else tmp_path + assert (folder / "sparse_encoder.py").read_bytes() == _SENTENCE_TRANSFORMERS_MODULE_FILE.read_bytes() + + +def test_load_from_saved_source(remote_encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None: + """Test that a saved sparse model loads as a SparseEncoder with the module from its own source file.""" + module = remote_encoder[0] + assert type(module).__name__ == "SparseStaticEmbedding" + assert type(module).__module__.startswith("transformers_modules.") + assert len(remote_encoder) == 1 + assert remote_encoder.similarity_fn_name == "dot" + assert remote_encoder.get_embedding_dimension() == sparse_model.dim + assert np.allclose(_dense(remote_encoder.encode_query(QUERIES)), sparse_model.encode_query(QUERIES).toarray()) + assert np.allclose( + _dense(remote_encoder.encode_document(DOCUMENTS)), sparse_model.encode_document(DOCUMENTS).toarray() + ) + + +def test_save_and_load(remote_encoder: SparseEncoder, sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that a SparseEncoder saved by Sentence Transformers keeps the source file, and loads in both libraries.""" + remote_encoder.save(str(tmp_path / "saved")) + assert (tmp_path / "saved" / "sparse_encoder.py").exists() + reloaded = SparseEncoder(str(tmp_path / "saved"), trust_remote_code=True) + assert np.allclose(_dense(reloaded.encode_query(QUERIES)), _dense(remote_encoder.encode_query(QUERIES))) + + model = SparseStaticModel.from_pretrained(tmp_path / "saved") + assert np.array_equal(model.embedding.toarray(), sparse_model.embedding.toarray()) + assert model.k1 == sparse_model.k1 + + +def test_encode_matches_sparse_model(encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None: + """Test that the SparseEncoder gives the vectors of encode_query and encode_document.""" + queries = _tensor(encoder.encode_query(QUERIES)) + documents = _tensor(encoder.encode_document(DOCUMENTS)) + assert queries.is_sparse + assert np.allclose(_dense(queries), sparse_model.encode_query(QUERIES).toarray()) + assert np.allclose(_dense(documents), sparse_model.encode_document(DOCUMENTS).toarray()) + assert np.allclose(_dense(encoder.encode(DOCUMENTS)), _dense(documents)) + + expected_scores = (sparse_model.encode_query(QUERIES) @ sparse_model.encode_document(DOCUMENTS).T).toarray() + assert np.allclose(encoder.similarity(queries, documents).numpy(), expected_scores) + + +def test_encode_single_and_dense(encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None: + """Test encoding a single text, and encoding to a dense tensor.""" + single = _tensor(encoder.encode_query("word1 word3")) + assert single.shape == (sparse_model.dim,) + assert np.allclose(_dense(single), sparse_model.encode_query("word1 word3").toarray()[0]) + + dense = _tensor(encoder.encode_document(DOCUMENTS, convert_to_sparse_tensor=False)) + assert not dense.is_sparse + assert np.allclose(dense.numpy(), sparse_model.encode_document(DOCUMENTS).toarray()) + + +def test_encode_with_prompt(encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None: + """Test that a prompt is prepended to each text.""" + out = encoder.encode_query(["word3"], prompt="word1 ") + assert np.allclose(_dense(out), sparse_model.encode_query(["word1 word3"]).toarray()) + + +def test_unknown_task_raises(encoder: SparseEncoder) -> None: + """Test that a task other than query or document raises.""" + with pytest.raises(ValueError, match="Unknown task"): + encoder.encode(DOCUMENTS, task="classification") + + +def test_max_seq_length(encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None: + """Test that max_seq_length reads and sets the sparse model's max_length.""" + assert encoder.max_seq_length == 512 + assert encoder.get_embedding_dimension() == sparse_model.dim + encoder.max_seq_length = 1 + assert sparse_model.max_length == 1 + assert np.allclose(_dense(encoder.encode_document(["word3 word1"])), _dense(encoder.encode_document(["word3"]))) + + +def test_decode(encoder: SparseEncoder) -> None: + """Test that decode maps dimensions to tokens.""" + decoded = encoder.decode(_tensor(encoder.encode_query("word3 word1"))) + assert {token for token, _ in decoded} == {"word1", "word3"} + + +def test_module_save_writes_only_model_files(sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that the module saves the model2vec files, and leaves the other files to Sentence Transformers.""" + SparseStaticEmbedding(sparse_model).save(str(tmp_path)) + assert {path.name for path in tmp_path.iterdir()} == {"model.safetensors", "tokenizer.json", "config.json"} + + +def test_load_missing_folder_raises(monkeypatch: pytest.MonkeyPatch) -> None: + """Test that loading raises when the model folder cannot be found.""" + monkeypatch.setattr(SparseStaticEmbedding, "load_dir_path", staticmethod(lambda *args, **kwargs: None)) + with pytest.raises(ValueError, match="Could not find a sparse model"): + SparseStaticEmbedding.load("missing-model") + + +def test_load(sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that the module in the model2vec package loads a saved sparse model.""" + sparse_model.save_pretrained(tmp_path) + module = SparseStaticEmbedding.load(str(tmp_path)) + assert np.array_equal(module.model.embedding.toarray(), sparse_model.embedding.toarray()) From 7368d017a0348ce3325c6ee74e8ed9b0f259a68d Mon Sep 17 00:00:00 2001 From: stephantul Date: Tue, 1 Dec 2026 11:30:22 +0100 Subject: [PATCH 4/4] nonfinity --- model2vec/sparse.py | 27 ++++++++++++++++++++++++--- tests/test_sparse.py | 25 ++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/model2vec/sparse.py b/model2vec/sparse.py index 70ea20b7..46c3bb46 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -8,6 +8,7 @@ importable(extra_dependency, _REQUIRED_EXTRA) import json +import math import shutil from collections.abc import Callable, Sequence from logging import getLogger @@ -168,8 +169,9 @@ def k1(self, value: float) -> None: """Validate k1 and update the config. :param value: The new k1 value. - :raises ValueError: If k1 is not positive. + :raises ValueError: If k1 is not positive and finite. """ + _check_finite("k1", value) if not value > 0: raise ValueError(f"k1 must be positive, but got {value}.") self._k1 = value @@ -182,7 +184,11 @@ def norm_coefficient(self) -> float: @norm_coefficient.setter def norm_coefficient(self, value: float) -> None: - """Update the config and reset the query weights.""" + """Validate the norm coefficient, update the config and reset the query weights. + + :param value: The new norm coefficient. + """ + _check_finite("norm_coefficient", value) self._norm_coefficient = value self._query_weights = None self._update_config("norm_coefficient", value) @@ -194,7 +200,11 @@ def length_exponent(self) -> float: @length_exponent.setter def length_exponent(self, value: float) -> None: - """Update the config.""" + """Validate the length exponent and update the config. + + :param value: The new length exponent. + """ + _check_finite("length_exponent", value) self._length_exponent = value self._update_config("length_exponent", value) @@ -472,6 +482,17 @@ def _encode_query_batch(self, ids: list[list[int]], normalize: bool) -> csr_matr return _maybe_normalize(bag, normalize) +def _check_finite(name: str, value: float) -> None: + """Raise if a parameter is NaN or infinite. + + :param name: The name of the parameter. + :param value: The value of the parameter. + :raises ValueError: If the value is NaN or infinite. + """ + if not math.isfinite(value): + raise ValueError(f"{name} must be finite, but got {value}.") + + def _csr_shape(matrix: csr_matrix) -> tuple[int, int]: """Get the shape of a CSR matrix.""" return cast(tuple[int, int], matrix.shape) diff --git a/tests/test_sparse.py b/tests/test_sparse.py index 24a43834..d20dd2d7 100644 --- a/tests/test_sparse.py +++ b/tests/test_sparse.py @@ -292,7 +292,7 @@ def test_query_tokens_with_zero_weight_are_dropped(mock_tokenizer: Tokenizer) -> assert out.indices.tolist() == [1] -@pytest.mark.parametrize("k1", [0.0, -1.0, float("nan")]) +@pytest.mark.parametrize("k1", [0.0, -1.0]) def test_non_positive_k1_raises(mock_sparse_model: SparseStaticModel, k1: float) -> None: """Test that k1 must be positive.""" with pytest.raises(ValueError, match="k1 must be positive"): @@ -300,6 +300,29 @@ def test_non_positive_k1_raises(mock_sparse_model: SparseStaticModel, k1: float) assert mock_sparse_model.k1 == K1 +@pytest.mark.parametrize("name", ["k1", "norm_coefficient", "length_exponent"]) +@pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf")]) +def test_non_finite_parameters_raise(mock_sparse_model: SparseStaticModel, name: str, value: float) -> None: + """Test that the parameters must be finite, and that a rejected value leaves the model and config unchanged.""" + old_value = getattr(mock_sparse_model, name) + with pytest.raises(ValueError, match=f"{name} must be finite"): + setattr(mock_sparse_model, name, value) + assert getattr(mock_sparse_model, name) == old_value + assert mock_sparse_model.config[name] == old_value + + +def test_non_finite_parameter_in_config_raises(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> None: + """Test that loading a config with a non-finite parameter raises.""" + mock_sparse_model.save_pretrained(tmp_path) + config_path = tmp_path / "config.json" + config = json.loads(config_path.read_text()) + config["k1"] = float("inf") + config_path.write_text(json.dumps(config)) + + with pytest.raises(ValueError, match="k1 must be finite"): + SparseStaticModel.from_pretrained(tmp_path) + + def test_codes_are_read_only(mock_sparse_model: SparseStaticModel) -> None: """Test that the stored codes and query weights cannot be changed in place.""" for array in (