diff --git a/model2vec/base.py b/model2vec/base.py new file mode 100644 index 0000000..8ffae1d --- /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 f9a4304..43a1d08 100644 --- a/model2vec/model.py +++ b/model2vec/model.py @@ -1,31 +1,24 @@ 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, Mapping, TypeVar, cast, overload import model2vec_rs import numpy as np import numpy.typing as npt -from tokenizers import Encoding, Tokenizer +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 - -class StaticModel: +class StaticModel(BaseStaticModel[StaticModelConfig]): def __init__( self, vectors: np.ndarray, @@ -62,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 len(vectors) != 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 ({len(vectors)}). " + 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." ) @@ -76,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: StaticModelConfig = cast(StaticModelConfig, {**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 @@ -98,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: @@ -108,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: @@ -146,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] @@ -176,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.""" @@ -248,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], @@ -314,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: ... @@ -354,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: @@ -423,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, @@ -546,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") diff --git a/model2vec/modelcards/sparse_model_card_template.md b/model2vec/modelcards/sparse_model_card_template.md new file mode 100644 index 0000000..fe67010 --- /dev/null +++ b/model2vec/modelcards/sparse_model_card_template.md @@ -0,0 +1,68 @@ +--- +{{ 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 +``` + +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 + +- [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 7ae0c7d..1ab7fbd 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 1a8e4de..5f139de 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 = "embeddings.shape" + def save_pretrained( folder_path: Path, @@ -45,39 +50,81 @@ 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, + sentence_transformers_config: Mapping[str, Any] | None = None, + **kwargs: Any, +) -> None: + """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`. + :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 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 + 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) + + 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}") - # Optionally create the model card if create_model_card: make_model_card(folder_path, **kwargs) @@ -98,7 +145,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 +202,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 +213,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/sentence-transformers/sparse_encoder.py b/model2vec/sentence-transformers/sparse_encoder.py new file mode 100644 index 0000000..e55d8b4 --- /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 new file mode 100644 index 0000000..46c3bb4 --- /dev/null +++ b/model2vec/sparse.py @@ -0,0 +1,544 @@ +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 +import math +import shutil +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 +from tokenizers import Tokenizer + +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, + SPARSE_INDPTR_KEY, + SPARSE_SHAPE_KEY, +) +from model2vec.types import _UNSET, SparseStaticModelConfig, _UnsetType +from model2vec.utils import SafeOpenProtocol + +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 + _query_weights: np.ndarray | None + + def __init__( + self, + vectors: csr_matrix | np.ndarray, + 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 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: + 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. 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__( + tokenizer=tokenizer, + config=config, + normalize=normalize, + base_model_name=base_model_name, + language=language, + max_length=max_length, + ) + self.embedding = vectors + self.k1 = k1 + self.norm_coefficient = norm_coefficient + self.length_exponent = length_exponent + + 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: + """The read-only sparse code of each token.""" + return self._embedding + + @embedding.setter + 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, does not have a row per token, or contains negative or + non-finite values. + """ + codes = csr_matrix(value) + 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 {(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.") + 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 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.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.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 + + @property + def k1(self) -> float: + """Get the k1 value.""" + return self._k1 + + @k1.setter + 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 and finite. + """ + _check_finite("k1", value) + if not value > 0: + raise ValueError(f"k1 must be positive, but got {value}.") + 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: + """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) + + @property + def length_exponent(self) -> float: + """Get the length exponent.""" + return self._length_exponent + + @length_exponent.setter + def length_exponent(self, value: float) -> None: + """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) + + 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 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 + + tensors, tensor_metadata = _sparse_to_tensors(self.embedding) + config = {**self.config, "embedding_dtype": self.embedding_dtype} + + save_folder( + 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", "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( + 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( + self, + sentences: str | Sequence[str], + *, + max_length: int | None | _UnsetType = _UNSET, + normalize: bool | None = None, + **kwargs: Any, + ) -> csr_matrix: + """Encode a list of documents into sparse vectors. This is the same as `encode_document`. + + :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 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_document_batch, max_length=max_length, normalize=normalize + ) + + def encode_query( + self, + sentences: str | Sequence[str], + *, + max_length: int | None | _UnsetType = _UNSET, + normalize: bool | None = None, + **kwargs: Any, + ) -> 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. + :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 queries as a CSR matrix. If a single query was passed, a 1-row matrix is returned. + """ + _warn_removed_arguments(kwargs) + return self._encode_sparse( + sentences, batch_fn=self._encode_query_batch, max_length=max_length, normalize=normalize + ) + + def encode_document( + self, + sentences: str | Sequence[str], + *, + max_length: int | None | _UnsetType = _UNSET, + normalize: bool | None = None, + **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 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 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_document_batch, max_length=max_length, normalize=normalize + ) + + def _encode_sparse( + self, + sentences: str | Sequence[str], + *, + batch_fn: Callable[[list[list[int]], bool], csr_matrix], + max_length: int | None | _UnsetType, + normalize: bool | None, + ) -> csr_matrix: + """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 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. + """ + if isinstance(max_length, _UnsetType): + max_length = self.max_length + if normalize is None: + normalize = self.normalize + + was_single = isinstance(sentences, str) + 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) + + out = batch_fn(self._tokenize_truncated(sentence_list, max_length), normalize) + if was_single: + return out[0] + return out + + 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]) + 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: + """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_document_batch(self, ids: list[list[int]], normalize: bool) -> csr_matrix: + """Encode the token ids of a batch of documents into sparse vectors. + + :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(ids) + length_norm = diags(np.maximum(lengths, 1).astype(self._dtype) ** -self.length_exponent) + 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, ids: list[list[int]], normalize: bool) -> csr_matrix: + """Encode the token ids of a batch of queries into sparse vectors. + + :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(ids) + bag.data = np.sqrt(bag.data) * self.query_weights[bag.indices] + bag.eliminate_zeros() + 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) + + +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: + 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 canonical CSR matrix to safetensors-compatible CSR arrays and header metadata.""" + tensors: dict[str, np.ndarray] = { + 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(matrix)])} + + +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/train/base.py b/model2vec/train/base.py index e908b88..7c76fdd 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/model2vec/types.py b/model2vec/types.py index 6fcd257..3493c38 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 648bb38..8a45915 100644 --- a/model2vec/utils.py +++ b/model2vec/utils.py @@ -19,6 +19,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 579430e..688626f 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" ] @@ -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 0000000..d20dd2d --- /dev/null +++ b/tests/test_sparse.py @@ -0,0 +1,518 @@ +import copy +import json +import pickle +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.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 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 + 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] + + +@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"): + mock_sparse_model.k1 = k1 + 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 ( + 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"]) +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) + unbatched = encode(sentences) + separately = [encode(sentence) for sentence in sentences] + assert np.allclose(np.vstack([row.toarray() for row in separately]), 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_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, 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: + 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()["embeddings.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 + + 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 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 + + +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 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]) + 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(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 codes.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/tests/test_sparse_encoder.py b/tests/test_sparse_encoder.py new file mode 100644 index 0000000..7c1795f --- /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()) diff --git a/uv.lock b/uv.lock index 2e1bc67..e6cc27e 100644 --- a/uv.lock +++ b/uv.lock @@ -1303,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'" }, @@ -1333,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" }, @@ -1344,7 +1349,7 @@ requires-dist = [ { name = "tqdm" }, { name = "transformers", marker = "extra == 'distill'", specifier = "<5.4.0" }, ] -provides-extras = ["dev", "distill", "onnx", "train", "quantization", "integration", "tests"] +provides-extras = ["dev", "distill", "onnx", "train", "quantization", "sparse", "integration", "tests"] [[package]] name = "model2vec-rs"