Skip to content

Commit a6fa396

Browse files
authored
feat: update Shimmer's document formula (#430)
1 parent 80500f8 commit a6fa396

3 files changed

Lines changed: 19 additions & 10 deletions

File tree

‎model2vec/sparse.py‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,12 @@
3636
_SENTENCE_TRANSFORMERS_MODULE_TYPE = f"{_SENTENCE_TRANSFORMERS_MODULE_FILE.stem}.SparseStaticEmbedding"
3737
_SENTENCE_TRANSFORMERS_MODULES = [{"idx": 0, "name": "0", "path": "", "type": _SENTENCE_TRANSFORMERS_MODULE_TYPE}]
3838
_SENTENCE_TRANSFORMERS_CONFIG = {"model_type": "SparseEncoder", "similarity_fn_name": "dot"}
39+
_POOL_EXPONENT = 0.7
3940

4041

4142
class SparseStaticModel(BaseStaticModel[SparseStaticModelConfig]):
4243
_embedding: csr_matrix
44+
_diagonal: np.ndarray
4345
_query_weights: np.ndarray | None
4446

4547
def __init__(
@@ -57,8 +59,9 @@ def __init__(
5759
) -> None:
5860
"""Initialize the SparseStaticModel.
5961
60-
Each token has a sparse code over the tokens of the vocabulary. A document is the square root of the summed
61-
codes of its tokens, divided by its token count to the length exponent, and saturated as BM25 does with b = 0.
62+
Each token has a sparse code over the tokens of the vocabulary. A document is the summed codes of its tokens
63+
to the power 0.7, divided by its length to the length exponent, and saturated as BM25 does with b = 0. Its
64+
length is the sum of its tokens' own code values, so frequent tokens with small codes count for less.
6265
A query token only activates itself: a query is the square root of its token counts, multiplied by the query
6366
weight of each token, which is its own code value to the power norm_coefficient.
6467
Scoring is the dot product of `encode_query` and `encode_document`.
@@ -76,7 +79,7 @@ def __init__(
7679
Written to `config["k1"]`.
7780
:param norm_coefficient: The power of its own code value that weights a query token.
7881
Written to `config["norm_coefficient"]`.
79-
:param length_exponent: The power of the token count each document is divided by.
82+
:param length_exponent: The power of the length each document is divided by.
8083
Written to `config["length_exponent"]`.
8184
"""
8285
super().__init__(
@@ -95,6 +98,7 @@ def __setstate__(self, state: dict[str, Any]) -> None:
9598
"""Restore the state from pickling, keeping the sparse codes read-only."""
9699
vars(self).update(state)
97100
self._embedding = _read_only_csr(self._embedding)
101+
self._diagonal = self._embedding.diagonal()
98102
self._query_weights = None
99103

100104
@property
@@ -104,7 +108,7 @@ def embedding(self) -> csr_matrix:
104108

105109
@embedding.setter
106110
def embedding(self, value: csr_matrix | np.ndarray) -> None:
107-
"""Validate and store the sparse codes, and reset the query weights.
111+
"""Validate and store the sparse codes, keep their diagonal, and reset the query weights.
108112
109113
:param value: The sparse code of each token.
110114
:raises ValueError: If the matrix is not square, does not have a row per token, or contains negative or
@@ -126,6 +130,7 @@ def embedding(self, value: csr_matrix | np.ndarray) -> None:
126130
codes = codes.copy()
127131
codes.sum_duplicates()
128132
self._embedding = _read_only_csr(codes)
133+
self._diagonal = codes.diagonal()
129134
self._query_weights = None
130135

131136
@property
@@ -147,7 +152,7 @@ def _dtype(self) -> np.dtype:
147152
def query_weights(self) -> np.ndarray:
148153
"""Get the query weight of each token: its own code value to the power norm_coefficient, or 0 if that is 0."""
149154
if self._query_weights is None:
150-
diagonal = self.embedding.diagonal().astype(self._dtype)
155+
diagonal = self._diagonal.astype(self._dtype)
151156
weights = np.zeros_like(diagonal)
152157
positive = diagonal > 0
153158
weights[positive] = diagonal[positive] ** self.norm_coefficient
@@ -410,12 +415,14 @@ def _encode_document_batch(self, bag: csr_matrix, lengths: np.ndarray) -> csr_ma
410415
"""Encode a batch of documents into sparse vectors.
411416
412417
:param bag: The token counts of each document.
413-
:param lengths: The token count of each document.
418+
:param lengths: The token count of each document. Unused: a document's length is the sum of its tokens' own
419+
code values.
414420
:return: The encoded documents as a CSR matrix.
415421
"""
422+
lengths = np.asarray(bag @ self._diagonal).ravel()
416423
length_norm = np.maximum(lengths, 1).astype(self._dtype) ** -self.length_exponent
417424
pooled = csr_matrix(bag @ self.embedding)
418-
pooled.data = np.sqrt(pooled.data) * np.repeat(length_norm, np.diff(pooled.indptr))
425+
pooled.data = pooled.data**_POOL_EXPONENT * np.repeat(length_norm, np.diff(pooled.indptr))
419426
return self.saturate(pooled)
420427

421428
def _encode_query_batch(self, bag: csr_matrix, lengths: np.ndarray) -> csr_matrix:

‎model2vec/version.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
__version_triple__ = (0, 12, 0)
1+
__version_triple__ = (0, 12, 1)
22
__version__ = ".".join(map(str, __version_triple__))

‎tests/test_sparse.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ def mock_sparse_model(mock_sparse_vectors: csr_matrix, mock_tokenizer: Tokenizer
5151
def _expected_document(token_ids: list[int]) -> np.ndarray:
5252
"""Compute the expected document encoding densely."""
5353
summed = _CODES[token_ids].sum(axis=0)
54-
pooled = np.sqrt(summed) / max(len(token_ids), 1) ** LENGTH_EXPONENT
54+
length = np.diag(_CODES)[token_ids].sum()
55+
pooled = summed**0.7 / max(length, 1) ** LENGTH_EXPONENT
5556
return pooled * (K1 + 1) / (pooled + K1)
5657

5758

@@ -541,7 +542,8 @@ def _reference_encoding(
541542
rows.append(np.sqrt(counts) * model.query_weights)
542543
else:
543544
summed = np.asarray(model.embedding.T @ counts).ravel()
544-
pooled = np.sqrt(summed) / max(len(ids), 1) ** model.length_exponent
545+
length = model.embedding.diagonal() @ counts
546+
pooled = summed**0.7 / max(length, 1) ** model.length_exponent
545547
rows.append(pooled * (model.k1 + 1) / (pooled + model.k1))
546548
return np.vstack(rows)
547549

0 commit comments

Comments
 (0)