From 9beafddc3f4c24e186af9965bbec1b369cce25c3 Mon Sep 17 00:00:00 2001 From: Pringled Date: Sat, 5 Dec 2026 08:17:37 +0100 Subject: [PATCH 1/5] feat: add pool_exponent and length_norm to SparseStaticModel --- model2vec/sparse.py | 63 +++++++++++++++++++++++++++++++++++++++++--- model2vec/types.py | 2 ++ tests/test_sparse.py | 2 ++ 3 files changed, 63 insertions(+), 4 deletions(-) diff --git a/model2vec/sparse.py b/model2vec/sparse.py index 847c9da9..2b238e8f 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -37,6 +37,10 @@ _SENTENCE_TRANSFORMERS_MODULES = [{"idx": 0, "name": "0", "path": "", "type": _SENTENCE_TRANSFORMERS_MODULE_TYPE}] _SENTENCE_TRANSFORMERS_CONFIG = {"model_type": "SparseEncoder", "similarity_fn_name": "dot"} +DEFAULT_POOL_EXPONENT = 0.5 +_LENGTH_NORMS = ("tokens", "norm") +DEFAULT_LENGTH_NORM = "tokens" + class SparseStaticModel(BaseStaticModel[SparseStaticModelConfig]): _embedding: csr_matrix @@ -54,11 +58,15 @@ def __init__( k1: float, norm_coefficient: float, length_exponent: float, + pool_exponent: float = DEFAULT_POOL_EXPONENT, + length_norm: str = DEFAULT_LENGTH_NORM, ) -> 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. + Each token has a sparse code over the tokens of the vocabulary. A document is the summed codes of its tokens + to the pool exponent (a square root by default), divided by its length to the length exponent, and saturated + as BM25 does with b = 0. The length is the token count by default, or the sum of the tokens' own code values + if `length_norm` is "norm". 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`. @@ -76,8 +84,12 @@ def __init__( 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. + :param length_exponent: The power of the length each document is divided by. Written to `config["length_exponent"]`. + :param pool_exponent: The power of the summed codes of a document's tokens. Must be positive. + Written to `config["pool_exponent"]`. + :param length_norm: "tokens" to measure a document's length as its token count, or "norm" as the sum of + its tokens' own code values. Written to `config["length_norm"]`. """ super().__init__( tokenizer=tokenizer, @@ -90,6 +102,8 @@ def __init__( self.k1 = k1 self.norm_coefficient = norm_coefficient self.length_exponent = length_exponent + self.pool_exponent = pool_exponent + self.length_norm = length_norm def __setstate__(self, state: dict[str, Any]) -> None: """Restore the state from pickling, keeping the sparse codes read-only.""" @@ -204,6 +218,41 @@ def length_exponent(self, value: float) -> None: self._length_exponent = value self._update_config("length_exponent", value) + @property + def pool_exponent(self) -> float: + """Get the pool exponent.""" + return self._pool_exponent + + @pool_exponent.setter + def pool_exponent(self, value: float) -> None: + """Validate the pool exponent and update the config. + + :param value: The new pool exponent. + :raises ValueError: If the pool exponent is not positive and finite. + """ + _check_finite("pool_exponent", value) + if not value > 0: + raise ValueError(f"pool_exponent must be positive, but got {value}.") + self._pool_exponent = value + self._update_config("pool_exponent", value) + + @property + def length_norm(self) -> str: + """Get the length measure: "tokens" or "norm".""" + return self._length_norm + + @length_norm.setter + def length_norm(self, value: str) -> None: + """Validate the length measure and update the config. + + :param value: The new length measure. + :raises ValueError: If the length measure is unknown. + """ + if value not in _LENGTH_NORMS: + raise ValueError(f"length_norm must be one of {_LENGTH_NORMS}, but got {value!r}.") + self._length_norm = value + self._update_config("length_norm", value) + def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None: """Save the pretrained sparse model. @@ -307,6 +356,8 @@ def from_pretrained( "`k1`, `norm_coefficient` and `length_exponent` must be present in the model's config, or passed to " "`from_pretrained`." ) + pool_exponent = config.get("pool_exponent", DEFAULT_POOL_EXPONENT) + length_norm = config.get("length_norm", DEFAULT_LENGTH_NORM) return cls( vectors=embeddings, @@ -320,6 +371,8 @@ def from_pretrained( k1=k1, norm_coefficient=norm_coefficient, length_exponent=length_exponent, + pool_exponent=pool_exponent, + length_norm=length_norm, ) def encode(self, sentences: str | Sequence[str], *, max_length: int | None | _UnsetType = _UNSET) -> csr_matrix: @@ -413,9 +466,11 @@ def _encode_document_batch(self, bag: csr_matrix, lengths: np.ndarray) -> csr_ma :param lengths: The token count of each document. :return: The encoded documents as a CSR matrix. """ + if self._length_norm == "norm": + lengths = np.asarray(bag @ self.embedding.diagonal()).ravel() 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)) + pooled.data = pooled.data**self._pool_exponent * 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: diff --git a/model2vec/types.py b/model2vec/types.py index d2b878cc..d5dfaa82 100644 --- a/model2vec/types.py +++ b/model2vec/types.py @@ -39,3 +39,5 @@ class SparseStaticModelConfig(BaseStaticModelConfig, total=False): k1: float norm_coefficient: float length_exponent: float + pool_exponent: float + length_norm: str diff --git a/tests/test_sparse.py b/tests/test_sparse.py index ef9832e3..b81187f8 100644 --- a/tests/test_sparse.py +++ b/tests/test_sparse.py @@ -89,6 +89,8 @@ def test_initialization( "k1": K1, "norm_coefficient": NORM_COEFFICIENT, "length_exponent": LENGTH_EXPONENT, + "pool_exponent": 0.5, + "length_norm": "tokens", } assert mock_config == original_config From 938abbd0ec567d10a863beab1cbb09ed1e1cb715 Mon Sep 17 00:00:00 2001 From: Pringled Date: Sat, 5 Dec 2026 11:45:15 +0100 Subject: [PATCH 2/5] feat: build Shimmer's new document formula into SparseStaticModel --- model2vec/sparse.py | 65 +++++--------------------------------------- model2vec/types.py | 2 -- tests/test_sparse.py | 8 +++--- 3 files changed, 11 insertions(+), 64 deletions(-) diff --git a/model2vec/sparse.py b/model2vec/sparse.py index 2b238e8f..f03a20c4 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -36,10 +36,7 @@ _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"} - -DEFAULT_POOL_EXPONENT = 0.5 -_LENGTH_NORMS = ("tokens", "norm") -DEFAULT_LENGTH_NORM = "tokens" +_POOL_EXPONENT = 0.7 class SparseStaticModel(BaseStaticModel[SparseStaticModelConfig]): @@ -58,15 +55,12 @@ def __init__( k1: float, norm_coefficient: float, length_exponent: float, - pool_exponent: float = DEFAULT_POOL_EXPONENT, - length_norm: str = DEFAULT_LENGTH_NORM, ) -> None: """Initialize the SparseStaticModel. Each token has a sparse code over the tokens of the vocabulary. A document is the summed codes of its tokens - to the pool exponent (a square root by default), divided by its length to the length exponent, and saturated - as BM25 does with b = 0. The length is the token count by default, or the sum of the tokens' own code values - if `length_norm` is "norm". + to the power 0.7, divided by its length to the length exponent, and saturated as BM25 does with b = 0. Its + length is the sum of its tokens' own code values, so frequent tokens with small codes count for less. 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`. @@ -86,10 +80,6 @@ def __init__( Written to `config["norm_coefficient"]`. :param length_exponent: The power of the length each document is divided by. Written to `config["length_exponent"]`. - :param pool_exponent: The power of the summed codes of a document's tokens. Must be positive. - Written to `config["pool_exponent"]`. - :param length_norm: "tokens" to measure a document's length as its token count, or "norm" as the sum of - its tokens' own code values. Written to `config["length_norm"]`. """ super().__init__( tokenizer=tokenizer, @@ -102,8 +92,6 @@ def __init__( self.k1 = k1 self.norm_coefficient = norm_coefficient self.length_exponent = length_exponent - self.pool_exponent = pool_exponent - self.length_norm = length_norm def __setstate__(self, state: dict[str, Any]) -> None: """Restore the state from pickling, keeping the sparse codes read-only.""" @@ -218,41 +206,6 @@ def length_exponent(self, value: float) -> None: self._length_exponent = value self._update_config("length_exponent", value) - @property - def pool_exponent(self) -> float: - """Get the pool exponent.""" - return self._pool_exponent - - @pool_exponent.setter - def pool_exponent(self, value: float) -> None: - """Validate the pool exponent and update the config. - - :param value: The new pool exponent. - :raises ValueError: If the pool exponent is not positive and finite. - """ - _check_finite("pool_exponent", value) - if not value > 0: - raise ValueError(f"pool_exponent must be positive, but got {value}.") - self._pool_exponent = value - self._update_config("pool_exponent", value) - - @property - def length_norm(self) -> str: - """Get the length measure: "tokens" or "norm".""" - return self._length_norm - - @length_norm.setter - def length_norm(self, value: str) -> None: - """Validate the length measure and update the config. - - :param value: The new length measure. - :raises ValueError: If the length measure is unknown. - """ - if value not in _LENGTH_NORMS: - raise ValueError(f"length_norm must be one of {_LENGTH_NORMS}, but got {value!r}.") - self._length_norm = value - self._update_config("length_norm", value) - def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None: """Save the pretrained sparse model. @@ -356,8 +309,6 @@ def from_pretrained( "`k1`, `norm_coefficient` and `length_exponent` must be present in the model's config, or passed to " "`from_pretrained`." ) - pool_exponent = config.get("pool_exponent", DEFAULT_POOL_EXPONENT) - length_norm = config.get("length_norm", DEFAULT_LENGTH_NORM) return cls( vectors=embeddings, @@ -371,8 +322,6 @@ def from_pretrained( k1=k1, norm_coefficient=norm_coefficient, length_exponent=length_exponent, - pool_exponent=pool_exponent, - length_norm=length_norm, ) def encode(self, sentences: str | Sequence[str], *, max_length: int | None | _UnsetType = _UNSET) -> csr_matrix: @@ -463,14 +412,14 @@ def _encode_document_batch(self, bag: csr_matrix, lengths: np.ndarray) -> csr_ma """Encode a batch of documents into sparse vectors. :param bag: The token counts of each document. - :param lengths: The token count of each document. + :param lengths: The token count of each document. Unused: a document's length is the sum of its tokens' own + code values. :return: The encoded documents as a CSR matrix. """ - if self._length_norm == "norm": - lengths = np.asarray(bag @ self.embedding.diagonal()).ravel() + lengths = np.asarray(bag @ self.embedding.diagonal()).ravel() length_norm = np.maximum(lengths, 1).astype(self._dtype) ** -self.length_exponent pooled = csr_matrix(bag @ self.embedding) - pooled.data = pooled.data**self._pool_exponent * np.repeat(length_norm, np.diff(pooled.indptr)) + pooled.data = pooled.data**_POOL_EXPONENT * 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: diff --git a/model2vec/types.py b/model2vec/types.py index d5dfaa82..d2b878cc 100644 --- a/model2vec/types.py +++ b/model2vec/types.py @@ -39,5 +39,3 @@ class SparseStaticModelConfig(BaseStaticModelConfig, total=False): k1: float norm_coefficient: float length_exponent: float - pool_exponent: float - length_norm: str diff --git a/tests/test_sparse.py b/tests/test_sparse.py index b81187f8..f746ffee 100644 --- a/tests/test_sparse.py +++ b/tests/test_sparse.py @@ -51,7 +51,8 @@ def mock_sparse_model(mock_sparse_vectors: csr_matrix, mock_tokenizer: Tokenizer 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 + length = np.diag(_CODES)[token_ids].sum() + pooled = summed**0.7 / max(length, 1) ** LENGTH_EXPONENT return pooled * (K1 + 1) / (pooled + K1) @@ -89,8 +90,6 @@ def test_initialization( "k1": K1, "norm_coefficient": NORM_COEFFICIENT, "length_exponent": LENGTH_EXPONENT, - "pool_exponent": 0.5, - "length_norm": "tokens", } assert mock_config == original_config @@ -543,7 +542,8 @@ def _reference_encoding( 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 + length = model.embedding.diagonal() @ counts + pooled = summed**0.7 / max(length, 1) ** model.length_exponent rows.append(pooled * (model.k1 + 1) / (pooled + model.k1)) return np.vstack(rows) From f7376c7353d6af4fd90b9ed660266752e9887bc2 Mon Sep 17 00:00:00 2001 From: Pringled Date: Sat, 5 Dec 2026 11:47:27 +0100 Subject: [PATCH 3/5] chore: bump version to 0.12.1 --- model2vec/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/model2vec/version.py b/model2vec/version.py index b9234632..636b6203 100644 --- a/model2vec/version.py +++ b/model2vec/version.py @@ -1,2 +1,2 @@ -__version_triple__ = (0, 12, 0) +__version_triple__ = (0, 12, 1) __version__ = ".".join(map(str, __version_triple__)) From df45c8d2bbbb3f24c4bf8565b9a2bea439086707 Mon Sep 17 00:00:00 2001 From: Pringled Date: Sat, 5 Dec 2026 11:56:15 +0100 Subject: [PATCH 4/5] perf: cache the code diagonal when the embedding is set --- model2vec/sparse.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/model2vec/sparse.py b/model2vec/sparse.py index f03a20c4..d665b58d 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -41,6 +41,7 @@ class SparseStaticModel(BaseStaticModel[SparseStaticModelConfig]): _embedding: csr_matrix + _diagonal: np.ndarray _query_weights: np.ndarray | None def __init__( @@ -106,7 +107,7 @@ def embedding(self) -> csr_matrix: @embedding.setter def embedding(self, value: csr_matrix | np.ndarray) -> None: - """Validate and store the sparse codes, and reset the query weights. + """Validate and store the sparse codes, keep their diagonal, 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 @@ -128,6 +129,7 @@ def embedding(self, value: csr_matrix | np.ndarray) -> None: codes = codes.copy() codes.sum_duplicates() self._embedding = _read_only_csr(codes) + self._diagonal = codes.diagonal() self._query_weights = None @property @@ -149,7 +151,7 @@ def _dtype(self) -> np.dtype: 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) + diagonal = self._diagonal.astype(self._dtype) weights = np.zeros_like(diagonal) positive = diagonal > 0 weights[positive] = diagonal[positive] ** self.norm_coefficient @@ -416,7 +418,7 @@ def _encode_document_batch(self, bag: csr_matrix, lengths: np.ndarray) -> csr_ma code values. :return: The encoded documents as a CSR matrix. """ - lengths = np.asarray(bag @ self.embedding.diagonal()).ravel() + lengths = np.asarray(bag @ self._diagonal).ravel() length_norm = np.maximum(lengths, 1).astype(self._dtype) ** -self.length_exponent pooled = csr_matrix(bag @ self.embedding) pooled.data = pooled.data**_POOL_EXPONENT * np.repeat(length_norm, np.diff(pooled.indptr)) From 7b57cd32b5cc8ce7cf255d00d80035a8beb75a70 Mon Sep 17 00:00:00 2001 From: Pringled Date: Sat, 5 Dec 2026 12:04:18 +0100 Subject: [PATCH 5/5] fix: rebuild the code diagonal when unpickling --- model2vec/sparse.py | 1 + 1 file changed, 1 insertion(+) diff --git a/model2vec/sparse.py b/model2vec/sparse.py index d665b58d..642b633f 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -98,6 +98,7 @@ 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._diagonal = self._embedding.diagonal() self._query_weights = None @property