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
4142class 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 :
0 commit comments