diff --git a/model2vec/base.py b/model2vec/base.py index 8ffae1d6..f642aa9b 100644 --- a/model2vec/base.py +++ b/model2vec/base.py @@ -1,36 +1,37 @@ 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 +from typing import Any, ClassVar, Generic, TypeVar, cast +import model2vec_rs import numpy as np -from tokenizers import Encoding, Tokenizer +from tokenizers import Tokenizer -from model2vec.types import StaticModelConfig +from model2vec.types import BaseStaticModelConfig PathLike = Path | str logger = getLogger(__name__) DEFAULT_MAX_LENGTH = 512 -_DEFAULT_NORMALIZE = False -ConfigT = TypeVar("ConfigT", bound=StaticModelConfig) +ConfigT = TypeVar("ConfigT", bound=BaseStaticModelConfig) class BaseStaticModel(ABC, Generic[ConfigT]): + _RUST_CACHES: ClassVar[tuple[str, ...]] = ("_rust_tokenizer",) + _rust_tokenizer: model2vec_rs.Tokenizer | None + 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, @@ -41,8 +42,6 @@ def __init__( 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 @@ -55,38 +54,55 @@ def __init__( 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 + + def __getstate__(self) -> dict[str, Any]: + """Get the state for pickling, without the Rust objects.""" + state = vars(self).copy() + for name in self._RUST_CACHES: + state[name] = None + return state @property def tokenizer(self) -> Tokenizer: - """The tokenizer.""" + """The tokenizer. Assign it again after changing it in place, so that encoding uses the changes.""" return self._tokenizer @tokenizer.setter def tokenizer(self, value: Tokenizer) -> None: self._tokenizer = value + for name in self._RUST_CACHES: + setattr(self, name, None) + + def _tokenizer_to_save(self) -> Tokenizer: + """Get a copy of the tokenizer that truncates to `max_length` tokens and does not pad.""" + tokenizer = copy.deepcopy(self.tokenizer) + _disable_padding(tokenizer) + if self.max_length is None: + tokenizer.no_truncation() + else: + tokenizer.enable_truncation(self.max_length) + return tokenizer @property - def normalize(self) -> bool: - """Get the normalize value. + def rust_tokenizer(self) -> model2vec_rs.Tokenizer: + """The Rust tokenizer used for encoding, built from `tokenizer` and rebuilt when it is assigned.""" + if self._rust_tokenizer is None: + self._rust_tokenizer = model2vec_rs.Tokenizer.from_str(self.tokenizer.to_str()) + return self._rust_tokenizer - :return: The normalize value. - """ - return self._normalize + @property + def median_token_length(self) -> int: + """The median character length of the tokens in the vocabulary.""" + return self.rust_tokenizer.median_token_length - @normalize.setter - def normalize(self, value: bool) -> None: - """Update the config.""" - self._normalize = value - self._update_config("normalize", value) + @property + def unk_token_id(self) -> int | None: + """The id of the unk token, which is left out of tokenized sentences, or None if there is none.""" + return self.rust_tokenizer.unk_token_id @property def max_length(self) -> int | None: @@ -101,7 +117,6 @@ 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.""" @@ -123,41 +138,22 @@ def save_pretrained(self, path: PathLike, model_name: str | None = None, subfold """ def tokenize(self, sentences: Sequence[str]) -> list[list[int]]: - """Tokenize a list of sentences. + """Tokenize a list of sentences into the token ids that `encode` uses, truncated to the model's `max_length`. :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) + ids, offsets = self._tokenize_flat(sentences, max_length=self.max_length) + return [ids[start:end].tolist() for start, end in zip(offsets[:-1].tolist(), offsets[1:].tolist())] + + def _tokenize_flat(self, sentences: Sequence[str], max_length: int | None) -> tuple[np.ndarray, np.ndarray]: + """Tokenize sentences into flat token ids and offsets, as `model2vec_rs.Tokenizer.tokenize` does. + + :param sentences: The sentences to tokenize. + :param max_length: The maximum number of tokens per sentence, or None to not truncate. + :return: The token ids, and the offsets of each sentence's ids. + """ + return self.rust_tokenizer.tokenize(list(sentences), max_length=max_length) def push_to_hub( self, repo_id: str, private: bool = False, token: str | None = None, subfolder: str | None = None @@ -186,16 +182,3 @@ def _disable_padding(tokenizer: Tokenizer) -> 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/inference/model.py b/model2vec/inference/model.py index db2daa6b..7ee2ea29 100644 --- a/model2vec/inference/model.py +++ b/model2vec/inference/model.py @@ -325,7 +325,7 @@ def _save_pipeline(pipeline: StaticModelPipeline, folder_path: str | Path) -> No save_pretrained( folder_path=folder_path, embeddings=model.embedding, - tokenizer=model.tokenizer, + tokenizer=model._tokenizer_to_save(), config=config, base_model_name=name, language=model.language, diff --git a/model2vec/model.py b/model2vec/model.py index 43a1d083..a2c2cbc8 100644 --- a/model2vec/model.py +++ b/model2vec/model.py @@ -11,14 +11,19 @@ import numpy.typing as npt from tokenizers import Tokenizer -from model2vec.base import _DEFAULT_NORMALIZE, DEFAULT_MAX_LENGTH, BaseStaticModel, PathLike +from model2vec.base import DEFAULT_MAX_LENGTH, BaseStaticModel, PathLike from model2vec.quantization import DType, quantize_and_reduce_dim from model2vec.types import _UNSET, StaticModelConfig, _UnsetType logger = getLogger(__name__) +_DEFAULT_NORMALIZE = False + class StaticModel(BaseStaticModel[StaticModelConfig]): + _RUST_CACHES = ("_rust_backend",) + _rust_backend: tuple[tuple[np.ndarray, np.ndarray | None, np.ndarray | None], model2vec_rs.StaticModel] | None + def __init__( self, vectors: np.ndarray, @@ -58,11 +63,11 @@ def __init__( super().__init__( tokenizer=tokenizer, config=cast(StaticModelConfig, config), - normalize=normalize, base_model_name=base_model_name, language=language, max_length=max_length, ) + self.normalize = normalize if token_mapping is None and len(vectors) != len(self.tokens): raise ValueError( @@ -74,28 +79,29 @@ def __init__( self.weights = weights self.token_mapping = token_mapping - def __getstate__(self) -> dict[str, Any]: - """Get the state for pickling, without the Rust backend.""" - state = vars(self).copy() - state.pop("_rust_backend", None) - return state - def __setstate__(self, state: dict[str, Any]) -> None: """Restore the state from pickling, keeping the arrays read-only.""" for name in ("embedding", "weights", "token_mapping"): state[f"_{name}"] = _read_only(state.pop(f"_{name}", state.pop(name, None))) state["_tokenizer"] = state.pop("_tokenizer", state.pop("tokenizer", None)) + for name in ("median_token_length", "unk_token_id"): + state.pop(name, None) + state.setdefault("_rust_backend", None) vars(self).update(state) @property - def tokenizer(self) -> Tokenizer: - """The tokenizer. Assign it again after changing it in place, so that `encode` uses the changes.""" - return self._tokenizer + def normalize(self) -> bool: + """Get the normalize value. - @tokenizer.setter - def tokenizer(self, value: Tokenizer) -> None: - self._tokenizer = value - vars(self).pop("_rust_backend", None) + :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 embedding(self) -> np.ndarray: @@ -133,7 +139,7 @@ def _get_rust_backend(self) -> model2vec_rs.StaticModel: :return: The Rust backend. """ key = (self.embedding, self.weights, self.token_mapping) - cached = vars(self).get("_rust_backend") + cached = self._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] @@ -158,6 +164,11 @@ def _get_rust_backend(self) -> model2vec_rs.StaticModel: self._rust_backend = ((self.embedding, self.weights, self.token_mapping), backend) return backend + @property + def rust_tokenizer(self) -> model2vec_rs.Tokenizer: + """The tokenizer of the Rust backend, which shares its state with the backend.""" + return self._get_rust_backend().tokenizer + @property def dim(self) -> int: """Get the dimension of the model.""" @@ -186,7 +197,7 @@ def save_pretrained(self, path: PathLike, model_name: str | None = None, subfold save_pretrained( folder_path=Path(path), embeddings=self.embedding, - tokenizer=self.tokenizer, + tokenizer=self._tokenizer_to_save(), config=self.config, base_model_name=self.base_model_name, language=self.language, @@ -277,9 +288,11 @@ 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) - ids = self._tokenize_truncated(sentence_list, max_length) + if not sentence_list: + return [] + ids, offsets = self._tokenize_flat(sentence_list, max_length) - out = [self._encode_helper(id_list) if id_list else np.zeros((0, self.dim)) for id_list in ids] + out = np.split(self._encode_helper(ids), offsets[1:-1]) if was_single: return out[0] return out @@ -319,15 +332,15 @@ def encode( out = out.astype(self.embedding.dtype, copy=False) return out - def _encode_helper(self, id_list: list[int]) -> np.ndarray: + def _encode_helper(self, id_list: np.ndarray) -> np.ndarray: """Helper function to encode a list of ids. It retrieves the embeddings for the given list of ids, applying weights if available. - :param id_list: A list of token ids. + :param id_list: An array of token ids. :return: The embeddings for the given ids, as a sequence of vectors. """ - id_list_remapped: list[int] | np.ndarray + id_list_remapped: np.ndarray if self.token_mapping is None: id_list_remapped = id_list else: diff --git a/model2vec/sparse.py b/model2vec/sparse.py index 46c3bb46..847c9da9 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -16,11 +16,11 @@ from typing import Any, cast import numpy as np -from scipy.sparse import csr_matrix, diags +from scipy.sparse import csr_matrix 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.base import DEFAULT_MAX_LENGTH, BaseStaticModel, PathLike +from model2vec.model import _read_only from model2vec.persistence.persistence import ( SPARSE_DATA_KEY, SPARSE_INDICES_KEY, @@ -47,7 +47,6 @@ def __init__( 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, @@ -69,8 +68,6 @@ def __init__( :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 @@ -85,7 +82,6 @@ def __init__( super().__init__( tokenizer=tokenizer, config=config, - normalize=normalize, base_model_name=base_model_name, language=language, max_length=max_length, @@ -248,7 +244,7 @@ def _save( save_folder( folder_path=path, tensors=tensors, - tokenizer=self.tokenizer, + tokenizer=self._tokenizer_to_save(), config=config, modules=_SENTENCE_TRANSFORMERS_MODULES if sentence_transformers_files else None, create_model_card=sentence_transformers_files, @@ -270,7 +266,6 @@ 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, @@ -284,8 +279,6 @@ def from_pretrained( :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. @@ -319,7 +312,6 @@ def from_pretrained( 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) @@ -330,37 +322,18 @@ def from_pretrained( 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: + def encode(self, sentences: str | Sequence[str], *, max_length: int | None | _UnsetType = _UNSET) -> 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 - ) + return self._encode_sparse(sentences, batch_fn=self._encode_document_batch, max_length=max_length) def encode_query( - self, - sentences: str | Sequence[str], - *, - max_length: int | None | _UnsetType = _UNSET, - normalize: bool | None = None, - **kwargs: Any, + self, sentences: str | Sequence[str], *, max_length: int | None | _UnsetType = _UNSET ) -> csr_matrix: """Encode a list of queries into sparse vectors. @@ -369,80 +342,58 @@ def encode_query( :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 - ) + return self._encode_sparse(sentences, batch_fn=self._encode_query_batch, max_length=max_length) def encode_document( - self, - sentences: str | Sequence[str], - *, - max_length: int | None | _UnsetType = _UNSET, - normalize: bool | None = None, - **kwargs: Any, + self, sentences: str | Sequence[str], *, max_length: int | None | _UnsetType = _UNSET ) -> 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 - ) + return self._encode_sparse(sentences, batch_fn=self._encode_document_batch, max_length=max_length) def _encode_sparse( self, sentences: str | Sequence[str], *, - batch_fn: Callable[[list[list[int]], bool], csr_matrix], + batch_fn: Callable[[csr_matrix, np.ndarray], 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 batch_fn: The function that encodes the bag of token counts and the token count of each sentence. :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) + ids, offsets = self._tokenize_flat(sentence_list, max_length) + bag, lengths = self._bag(ids, offsets) + out = batch_fn(bag, lengths) 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]) + def _bag(self, ids: np.ndarray, offsets: np.ndarray) -> tuple[csr_matrix, np.ndarray]: + """Turn flat token ids and their offsets into a bag of token counts, and the token count of each sentence.""" + lengths = np.diff(offsets) bag = csr_matrix( - (np.ones(len(cols), dtype=self._dtype), (rows, cols)), shape=(len(ids), _csr_shape(self.embedding)[0]) + (np.ones(len(ids), dtype=self._dtype), ids, offsets), shape=(len(lengths), _csr_shape(self.embedding)[0]) ) + bag.sum_duplicates() return bag, lengths def saturate(self, weights: csr_matrix) -> csr_matrix: @@ -455,31 +406,28 @@ def saturate(self, weights: csr_matrix) -> csr_matrix: 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. + def _encode_document_batch(self, bag: csr_matrix, lengths: np.ndarray) -> csr_matrix: + """Encode a batch of documents into sparse vectors. - :param ids: The token ids of each document. - :param normalize: Whether to normalize the resulting vectors. + :param bag: The token counts of each document. + :param lengths: The token count of each document. :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. + length_norm = np.maximum(lengths, 1).astype(self._dtype) ** -self.length_exponent + pooled = csr_matrix(bag @ self.embedding) + pooled.data = np.sqrt(pooled.data) * np.repeat(length_norm, np.diff(pooled.indptr)) + return self.saturate(pooled) + + def _encode_query_batch(self, bag: csr_matrix, lengths: np.ndarray) -> csr_matrix: + """Encode a batch of queries into sparse vectors. + + :param bag: The token counts of each query. + :param lengths: The token count of each query. Unused. :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) + return bag def _check_finite(name: str, value: float) -> None: @@ -507,15 +455,6 @@ def _read_only_csr(matrix: csr_matrix) -> csr_matrix: 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] = { diff --git a/model2vec/train/base.py b/model2vec/train/base.py index 7c76fdd3..52337eb8 100644 --- a/model2vec/train/base.py +++ b/model2vec/train/base.py @@ -5,15 +5,15 @@ from collections.abc import Sequence, Sized from typing import Any, TypeVar +import model2vec_rs import numpy as np import torch from datasets import Column, DatasetDict, IterableColumn, IterableDataset, IterableDatasetDict from datasets import Dataset as HFDataset -from tokenizers import Encoding, Tokenizer +from tokenizers import Tokenizer 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 from model2vec.train.dataset import ( @@ -102,26 +102,44 @@ def __init__( self.embeddings = self.construct_embeddings() self._head: nn.Sequential | None = None if self.out_dim is None else self.construct_head() self.w = self.construct_weights() - # Truncation happens here through `max_length`; a StaticModel's tokenizer carries its own setting. self.tokenizer = copy.deepcopy(tokenizer) - self.tokenizer.no_truncation() - _disable_padding(self.tokenizer) - self.unk_token_id = _get_unk_token_id(self.tokenizer) + + def __getstate__(self) -> dict[str, Any]: + """Get the state for pickling, without the Rust tokenizer.""" + state = super().__getstate__() + state["_rust_tokenizer"] = None + return state + + @property + def tokenizer(self) -> Tokenizer: + """The tokenizer. Assign it again after changing it in place, so that tokenizing uses the changes.""" + return self._tokenizer + + @tokenizer.setter + def tokenizer(self, value: Tokenizer) -> None: + self._tokenizer = value + self._rust_tokenizer: model2vec_rs.Tokenizer | None = None + + @property + def rust_tokenizer(self) -> model2vec_rs.Tokenizer: + """The Rust tokenizer used for tokenizing, built from `tokenizer` and rebuilt when it is assigned.""" + if self._rust_tokenizer is None: + self._rust_tokenizer = model2vec_rs.Tokenizer.from_str(self.tokenizer.to_str()) + return self._rust_tokenizer + + @property + def unk_token_id(self) -> int | None: + """The id of the unk token, which is left out of tokenized texts, or None if there is none.""" + return self.rust_tokenizer.unk_token_id def _tokenize_ids(self, texts: Sequence[str]) -> list[list[int]]: - """Tokenize texts into lists of token ids, dropping unknown tokens and truncating to `max_length` tokens. + """Tokenize texts into lists of token ids, as `StaticModel.tokenize` does with this `max_length`. :param texts: The texts to tokenize. :return: The token ids of each text. """ - if self.max_length is not None: - truncate_length = self.max_length * 10 - texts = [text[:truncate_length] for text in texts] - encoded: list[Encoding] = self.tokenizer.encode_batch_fast(texts, add_special_tokens=False) - ids = [encoding.ids for encoding in encoded] - if self.unk_token_id is not None: - ids = [[token_id for token_id in token_ids if token_id != self.unk_token_id] for token_ids in ids] - return [token_ids[: self.max_length] for token_ids in ids] + ids, offsets = self.rust_tokenizer.tokenize(list(texts), max_length=self.max_length) + return [ids[start:end].tolist() for start, end in zip(offsets[:-1].tolist(), offsets[1:].tolist())] def _to_targets(self, labels: Any) -> torch.Tensor: """Turn a batch of labels, such as vectors, into a float tensor of targets.""" diff --git a/model2vec/types.py b/model2vec/types.py index 3493c38f..d2b878cc 100644 --- a/model2vec/types.py +++ b/model2vec/types.py @@ -10,10 +10,9 @@ class _UnsetType: _UNSET = _UnsetType() -class StaticModelConfig(TypedDict, total=False): - """The metadata config stored alongside a model2vec model, e.g. in `config.json`.""" +class BaseStaticModelConfig(TypedDict, total=False): + """The metadata config shared by dense and sparse model2vec models, e.g. in `config.json`.""" - normalize: bool max_length: int | None model_type: str architectures: list[str] @@ -28,7 +27,13 @@ class StaticModelConfig(TypedDict, total=False): head_config: dict[str, Any] -class SparseStaticModelConfig(StaticModelConfig, total=False): +class StaticModelConfig(BaseStaticModelConfig, total=False): + """The metadata config stored alongside a model2vec model, e.g. in `config.json`.""" + + normalize: bool + + +class SparseStaticModelConfig(BaseStaticModelConfig, total=False): """The metadata config stored alongside a sparse model2vec model.""" k1: float diff --git a/pyproject.toml b/pyproject.toml index 688626fd..42cdf399 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ dependencies = [ "tokenizers>=0.22,<1.0.0", "tqdm", "huggingface-hub>=1.0.0", - "model2vec-rs>=0.5.1,<0.6.0", + "model2vec-rs>=0.6.0,<0.7.0", ] [build-system] diff --git a/tests/test_model.py b/tests/test_model.py index 270286b0..a9992f7f 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -1,3 +1,4 @@ +import copy from pathlib import Path import numpy as np @@ -124,7 +125,9 @@ def test_encode_as_tokens_empty( encoded_list = model.encode_as_sequence(["", ""]) out = [np.zeros(shape=(0, 2), dtype=model.embedding.dtype) for _ in range(2)] - assert [np.array_equal(x, y) for x, y in zip(encoded_list, out)] + assert all(np.array_equal(x, y) for x, y in zip(encoded_list, out)) + + assert model.encode_as_sequence([]) == [] def test_encode_empty_sentence( @@ -314,24 +317,39 @@ def test_set_max_length(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> """Tests whether the max_length is set correctly.""" model = StaticModel(mock_vectors, mock_tokenizer, {}, max_length=128) assert model.config == {"normalize": False, "max_length": 128} - assert model.tokenizer.truncation["max_length"] == 128 - model.max_length = 256 - assert model.config == {"normalize": False, "max_length": 256} - assert model.tokenizer.truncation["max_length"] == 256 + model.max_length = 1 + assert model.config == {"normalize": False, "max_length": 1} + assert model.tokenize(["word1 word2 word3"]) == [model.tokenize(["word1"])[0]] model.max_length = None assert model.config == {"normalize": False, "max_length": None} + assert len(model.tokenize(["word1 word2 word3"])[0]) == 3 assert model.tokenizer.truncation is None -def test_models_do_not_share_tokenizer(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: - """Tests that two models built from the same tokenizer object have independent truncation state.""" - model_a = StaticModel(mock_vectors, mock_tokenizer, {}, max_length=128) - model_b = StaticModel(mock_vectors, mock_tokenizer, {}, max_length=256) +def test_save_writes_max_length_as_truncation( + mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, tmp_path: Path +) -> None: + """Tests that the saved tokenizer truncates to `max_length`, without changing the model's tokenizer.""" + tokenizer = copy.deepcopy(mock_tokenizer) + tokenizer.enable_truncation(512) + model = StaticModel(mock_vectors, tokenizer, {}, max_length=4) + model.save_pretrained(tmp_path / "four") + assert Tokenizer.from_file(str(tmp_path / "four" / "tokenizer.json")).truncation["max_length"] == 4 + assert model.tokenizer.truncation["max_length"] == 512 + + model.max_length = None + model.save_pretrained(tmp_path / "none") + assert Tokenizer.from_file(str(tmp_path / "none" / "tokenizer.json")).truncation is None + assert StaticModel.from_pretrained(tmp_path / "none").max_length is None + - model_b.max_length = 8 +def test_models_do_not_share_tokenizer(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: + """Tests that two models built from the same tokenizer object each have their own copy.""" + model_a = StaticModel(mock_vectors, mock_tokenizer, {}) + model_b = StaticModel(mock_vectors, mock_tokenizer, {}) - assert model_a.tokenizer.truncation["max_length"] == 128 - assert model_b.tokenizer.truncation["max_length"] == 8 + assert model_a.tokenizer is not mock_tokenizer + assert model_a.tokenizer is not model_b.tokenizer def test_dim(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str]) -> None: @@ -475,3 +493,35 @@ def test_pickle_and_copy_with_rust_backend(mock_vectors: np.ndarray, mock_tokeni expected = model.encode(["word1 word2"]) for clone in (pickle.loads(pickle.dumps(model)), copy.deepcopy(model), copy.copy(model)): np.testing.assert_allclose(clone.encode(["word1 word2"]), expected) + + +def test_unpickle_state_without_rust_backend(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: + """Test that a pickled state from before the Rust backend was cached can still encode.""" + model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer) + state = model.__getstate__() + del state["_rust_backend"] + clone = StaticModel.__new__(StaticModel) + clone.__setstate__(state) + np.testing.assert_allclose(clone.encode(["word1 word2"]), model.encode(["word1 word2"])) + + +@pytest.mark.parametrize("max_length", [None, 1, 3]) +def test_tokenize_matches_encode_truncation( + mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, max_length: int | None +) -> None: + """Test that tokenize gives the ids that encode pools, truncated as encode_as_sequence truncates them.""" + model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, max_length=max_length) + texts = ["word1 unknown word2 word3 word1", "word3", ""] + ids, offsets = model.rust_tokenizer.tokenize(texts, max_length=max_length) + expected = [ids[start:end].tolist() for start, end in zip(offsets[:-1], offsets[1:])] + assert model.tokenize(texts) == expected + assert [len(seq) for seq in model.encode_as_sequence(texts, max_length=max_length)] == [len(x) for x in expected] + + +def test_rust_tokenizer(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: + """Test that the Rust tokenizer is the backend's tokenizer and gives the ids of `tokenize`.""" + model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer) + ids, offsets = model.rust_tokenizer.tokenize(["word1 word2", "word3"]) + assert offsets.tolist() == [0, 2, 3] + assert [ids[:2].tolist(), ids[2:].tolist()] == model.tokenize(["word1 word2", "word3"]) + assert model.rust_tokenizer.vocab_size == model._get_rust_backend().tokenizer.vocab_size diff --git a/tests/test_sparse.py b/tests/test_sparse.py index d20dd2d7..ef9832e3 100644 --- a/tests/test_sparse.py +++ b/tests/test_sparse.py @@ -7,6 +7,7 @@ import numpy as np import pytest import safetensors +import scipy.sparse from scipy.sparse import csr_matrix from tokenizers import Tokenizer @@ -84,7 +85,6 @@ def test_initialization( assert model.length_exponent == LENGTH_EXPONENT assert model.config == { **original_config, - "normalize": False, "max_length": 512, "k1": K1, "norm_coefficient": NORM_COEFFICIENT, @@ -184,7 +184,7 @@ def test_query_weights_zero_for_zero_codes(mock_tokenizer: Tokenizer, norm_coeff @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.""" + """Test that encoding keeps the dtype of the codes, also when encoding nothing.""" model = SparseStaticModel( vectors=_CODES.astype(dtype), tokenizer=mock_tokenizer, @@ -194,7 +194,6 @@ def test_encode_keeps_dtype(mock_tokenizer: Tokenizer, dtype: type, method: str) ) encode = getattr(model, method) assert encode(["word1 word2"]).dtype == dtype - assert encode(["word1 word2"], normalize=True).dtype == dtype assert encode([]).dtype == dtype @@ -347,18 +346,19 @@ def test_pickle_and_copy(mock_sparse_model: SparseStaticModel) -> None: @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) + """Test that an empty sentence gives an all-zero row.""" + out = getattr(mock_sparse_model, method)(["", "word1"]) assert out.shape == (2, 5) assert out[0].nnz == 0 assert not np.isnan(out.toarray()).any() +@pytest.mark.parametrize("argument", ["normalize", "batch_size"]) @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) +def test_encode_rejects_unknown_arguments(mock_sparse_model: SparseStaticModel, method: str, argument: str) -> None: + """Test that encoding raises on arguments it does not take.""" + with pytest.raises(TypeError, match=argument): + getattr(mock_sparse_model, method)(["word1"], **{argument: True}) @pytest.mark.parametrize("method", ["encode", "encode_query", "encode_document"]) @@ -397,7 +397,6 @@ def test_save_and_load_roundtrip(mock_sparse_model: SparseStaticModel, tmp_path: 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 @@ -486,13 +485,12 @@ def test_load_overrides(mock_sparse_model: SparseStaticModel, tmp_path: Path) -> """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 + tmp_path, k1=2.0, norm_coefficient=0.5, length_exponent=0.1, 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 @@ -516,3 +514,80 @@ def test_load_dense_model_raises(mock_vectors: np.ndarray, mock_tokenizer: Token SparseStaticModel.from_pretrained( tmp_path, k1=K1, norm_coefficient=NORM_COEFFICIENT, length_exponent=LENGTH_EXPONENT ) + + +def _reference_tokenize(model: SparseStaticModel, sentences: list[str], max_length: int | None) -> list[list[int]]: + """Tokenize with the `tokenizers` tokenizer, cut and truncated as the Rust tokenizer does.""" + tokenizer = copy.deepcopy(model.tokenizer) + tokenizer.no_padding() + if max_length is None: + tokenizer.no_truncation() + else: + tokenizer.enable_truncation(max_length) + sentences = [sentence[: max_length * model.median_token_length] for sentence in sentences] + encodings = tokenizer.encode_batch_fast(sentences, add_special_tokens=False) + return [[token_id for token_id in encoding.ids if token_id != model.unk_token_id] for encoding in encodings] + + +def _reference_encoding( + model: SparseStaticModel, sentences: list[str], max_length: int | None, query: bool +) -> np.ndarray: + """Encode densely from the token ids of the `tokenizers` tokenizer.""" + vocab_size = model.embedding.shape[0] + rows = [] + for ids in _reference_tokenize(model, sentences, max_length): + counts = np.bincount(np.asarray(ids, dtype=np.int64), minlength=vocab_size).astype(np.float64) + if query: + rows.append(np.sqrt(counts) * model.query_weights) + else: + summed = np.asarray(model.embedding.T @ counts).ravel() + pooled = np.sqrt(summed) / max(len(ids), 1) ** model.length_exponent + rows.append(pooled * (model.k1 + 1) / (pooled + model.k1)) + return np.vstack(rows) + + +@pytest.mark.parametrize("max_length", [None, 512, 4]) +@pytest.mark.parametrize("method", ["encode_query", "encode_document"]) +def test_encode_matches_tokenizers_tokenization(max_length: int | None, method: str) -> None: + """Test that encoding with the Rust tokenizer matches encoding from the `tokenizers` token ids.""" + tokenizer = Tokenizer.from_file("tests/data/test_tokenizer/tokenizer.json") + vocab_size = tokenizer.get_vocab_size() + rng = np.random.default_rng(0) + codes = scipy.sparse.random(vocab_size, vocab_size, density=5 / vocab_size, format="csr", random_state=rng) + codes = (codes + scipy.sparse.diags(rng.random(vocab_size) + 0.1)).tocsr() + model = SparseStaticModel(codes, tokenizer, k1=K1, norm_coefficient=NORM_COEFFICIENT, length_exponent=0.3) + sentences = [ + "The quick brown fox jumps over the lazy dog.", + "", + "Héllo wörld, ünïcode and 日本語 and emoji 🙂", + "repeated repeated repeated words words", + "a much longer sentence " * 100, + ] + out = getattr(model, method)(sentences, max_length=max_length) + expected = _reference_encoding(model, sentences, max_length, query=method == "encode_query") + assert np.allclose(out.toarray(), expected, atol=1e-5) + + +def test_assigning_tokenizer_updates_encoding(mock_sparse_model: SparseStaticModel) -> None: + """Test that assigning a new tokenizer is used by the next encode.""" + model = copy.deepcopy(mock_sparse_model) + before = model.encode_query(["word1 word3"]).toarray() + swapped = json.loads(model.tokenizer.to_str()) + vocab = swapped["model"]["vocab"] + if isinstance(vocab, dict): + vocab["word1"], vocab["word3"] = vocab["word3"], vocab["word1"] + else: + vocab[1], vocab[3] = [vocab[3][0], vocab[1][1]], [vocab[1][0], vocab[3][1]] + model.tokenizer = Tokenizer.from_str(json.dumps(swapped)) + after = model.encode_query(["word1 word3"]).toarray() + assert np.allclose(after, before) + assert np.allclose(model.encode_query(["word1"]).toarray(), mock_sparse_model.encode_query(["word3"]).toarray()) + + +def test_pickle_drops_rust_tokenizer(mock_sparse_model: SparseStaticModel) -> None: + """Test that the Rust tokenizer is not pickled and is rebuilt after unpickling.""" + mock_sparse_model.encode_query(["word1"]) + assert mock_sparse_model._rust_tokenizer is not None + clone = pickle.loads(pickle.dumps(mock_sparse_model)) + assert clone._rust_tokenizer is None + assert np.allclose(clone.encode_query(["word1"]).toarray(), mock_sparse_model.encode_query(["word1"]).toarray()) diff --git a/tests/test_trainable.py b/tests/test_trainable.py index 42bb736f..8e40ca4a 100644 --- a/tests/test_trainable.py +++ b/tests/test_trainable.py @@ -1,5 +1,7 @@ +import copy import inspect import logging +import pickle from collections import Counter, UserList from tempfile import TemporaryDirectory from typing import Any, TypeVar @@ -510,6 +512,27 @@ def test_unknown_tokens_are_dropped(mock_vectors: np.ndarray, mock_tokenizer: To assert s._tokenize_ids(texts) == expected +def test_pickle_and_copy_rebuild_rust_tokenizer(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: + """A trainer can be pickled and copied, and tokenizes the same afterwards.""" + s = StaticModelForClassification(vectors=torch.from_numpy(mock_vectors).float(), tokenizer=mock_tokenizer) + texts = ["word1 word2", "word3"] + expected = s._tokenize_ids(texts) + for clone in (pickle.loads(pickle.dumps(s)), copy.deepcopy(s)): + assert clone._rust_tokenizer is None + assert clone._tokenize_ids(texts) == expected + + +def test_assigning_tokenizer_rebuilds_rust_tokenizer(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None: + """Assigning the tokenizer again makes tokenizing use its in-place changes.""" + from tokenizers.normalizers import Lowercase + + s = StaticModelForClassification(vectors=torch.from_numpy(mock_vectors).float(), tokenizer=mock_tokenizer) + before = s._tokenize_ids(["WORD1"]) + s.tokenizer.normalizer = Lowercase() + s.tokenizer = s.tokenizer + assert s._tokenize_ids(["WORD1"]) == s._tokenize_ids(["word1"]) != before + + def test_tokenize_without_unk_token(mock_vectors: np.ndarray) -> None: """A tokenizer with no unk token has nothing to drop, so tokenization is left as is.""" vocab = ["[PAD]", "word1", "word2", "word3"] @@ -532,39 +555,41 @@ def test_max_length_is_not_capped_by_the_static_model(mock_vectors: np.ndarray, """A trainer's `max_length` is its own: the static model's truncation must not cap it, in training or after export.""" static = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, max_length=2) texts = ["word1 word2 word3 word1 word2 word3"] - assert len(static.tokenize(texts)[0]) == 2 + expected = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, max_length=4).tokenize(texts) + assert len(expected[0]) > len(static.tokenize(texts)[0]) s = StaticModelForClassification.from_static_model(model=static, max_length=4) - assert s.tokenize(texts).lengths.tolist() == [4] - assert [len(row) for row in s._tokenize_ids(texts)] == [4] - assert len(s.to_static_model().tokenize(texts)[0]) == 4 + assert _sequences(s.tokenize(texts)) == expected + assert s._tokenize_ids(texts) == expected + assert s.to_static_model().tokenize(texts) == expected - # The static model keeps its own setting, and the trainer keeps its own once the static model changes. - assert len(static.tokenize(texts)[0]) == 2 + # The trainer keeps its own setting once the static model changes. static.max_length = None - assert s.tokenize(texts).lengths.tolist() == [4] + assert s._tokenize_ids(texts) == expected @pytest.mark.parametrize("cls", FINETUNEABLE_CLASSES) @pytest.mark.parametrize( - "kwargs, expected_max_length, expected_tokens", - [({}, 2, 2), ({"max_length": None}, None, 6), ({"max_length": 5}, 5, 5)], + "kwargs, expected_max_length", + [({}, 2), ({"max_length": None}, None), ({"max_length": 5}, 5)], ) def test_from_static_model_max_length_resolution( cls: type[BaseFinetuneable], kwargs: dict[str, Any], expected_max_length: int | None, - expected_tokens: int, mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, ) -> None: """Unset inherits the static model's `max_length`, None disables truncation, and an int is used as is.""" static = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, max_length=2) texts = ["word1 word2 word3 word1 word2 word3"] + expected = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, max_length=expected_max_length).tokenize( + texts + ) s = cls.from_static_model(model=static, **kwargs) assert s.max_length == expected_max_length - assert [len(row) for row in s._tokenize_ids(texts)] == [expected_tokens] - assert len(s.to_static_model().tokenize(texts)[0]) == expected_tokens + assert s._tokenize_ids(texts) == expected + assert s.to_static_model().tokenize(texts) == expected def test_predict(mock_trained_pipeline: StaticModelForClassification) -> None: