diff --git a/model2vec/sparse.py b/model2vec/sparse.py index 847c9da9..642b633f 100644 --- a/model2vec/sparse.py +++ b/model2vec/sparse.py @@ -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__( @@ -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`. @@ -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__( @@ -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 @@ -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 @@ -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() self._query_weights = None @property @@ -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 @@ -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: 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__)) diff --git a/tests/test_sparse.py b/tests/test_sparse.py index ef9832e3..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) @@ -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)