Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions model2vec/sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@
_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"}
_POOL_EXPONENT = 0.7


class SparseStaticModel(BaseStaticModel[SparseStaticModelConfig]):
_embedding: csr_matrix
_diagonal: np.ndarray
_query_weights: np.ndarray | None

def __init__(
Expand All @@ -57,8 +59,9 @@ def __init__(
) -> 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 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`.
Expand All @@ -76,7 +79,7 @@ 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"]`.
"""
super().__init__(
Expand All @@ -95,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
Expand All @@ -104,7 +108,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
Expand All @@ -126,6 +130,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()
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
self._query_weights = None

@property
Expand All @@ -147,7 +152,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
Expand Down Expand Up @@ -410,12 +415,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.
"""
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 = np.sqrt(pooled.data) * 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:
Expand Down
2 changes: 1 addition & 1 deletion model2vec/version.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version_triple__ = (0, 12, 0)
__version_triple__ = (0, 12, 1)
__version__ = ".".join(map(str, __version_triple__))
6 changes: 4 additions & 2 deletions tests/test_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -541,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)

Expand Down
Loading