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
6 changes: 5 additions & 1 deletion model2vec/modelcards/sparse_model_card_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ documents = model.encode_document(["Example document"])
scores = queries @ documents.T
```

This model can also be loaded as a [Sentence Transformers](https://github.com/huggingface/sentence-transformers) `SparseEncoder`, which requires `model2vec[sparse]` to be installed:
This model can also be loaded as a [Sentence Transformers](https://github.com/huggingface/sentence-transformers) `SparseEncoder`. This requires Sentence Transformers in addition to `model2vec[sparse]`:
```
pip install model2vec[sparse] sentence-transformers
```

```python
from sentence_transformers import SparseEncoder

Expand Down
24 changes: 21 additions & 3 deletions model2vec/sentence-transformers/sparse_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
from pathlib import Path
from typing import Any, cast

import numpy as np
import torch
from scipy.sparse import csr_matrix
from sentence_transformers.base.modality_types import PairInput, SingleInput
from sentence_transformers.base.modules import InputModule
from transformers import PreTrainedTokenizerFast
Expand All @@ -14,6 +16,8 @@


class SparseStaticEmbedding(InputModule):
forward_kwargs = {"max_active_dims"}

def __init__(self, model: SparseStaticModel) -> None:
"""A Sentence Transformers input module that encodes texts with a SparseStaticModel.

Expand Down Expand Up @@ -64,15 +68,22 @@ def preprocess(
texts = self._prepend_prompt(texts, prompt) if prompt else list(texts)
return {"texts": texts, "task": task}

def forward(self, features: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
def forward(self, features: dict[str, Any], max_active_dims: int | None = None, **kwargs: Any) -> dict[str, Any]:
"""Encode the texts as queries or documents.

:param features: The texts and the task, as returned by `preprocess`.
:param max_active_dims: The maximum number of active dimensions per vector. If passed, the vectors are
returned as a dense tensor, which Sentence Transformers then prunes to the top `max_active_dims` values.
:param **kwargs: Any additional arguments. These are ignored.
:return: The features, with the sparse vectors as a dense tensor under `sentence_embedding`.
:return: The features, with the vectors under `sentence_embedding` as a sparse COO tensor, or as a dense
tensor if `max_active_dims` is passed.
"""
encode = self.model.encode_query if features["task"] == "query" else self.model.encode_document
features["sentence_embedding"] = torch.from_numpy(encode(features["texts"]).toarray())
encoded = encode(features["texts"])
if max_active_dims is not None:
features["sentence_embedding"] = torch.from_numpy(encoded.toarray())
else:
features["sentence_embedding"] = _csr_to_torch(encoded)
return features

def save(self, output_path: str, *args: Any, safe_serialization: bool = True, **kwargs: Any) -> None:
Expand Down Expand Up @@ -119,3 +130,10 @@ def load(
if folder is None:
raise ValueError(f"Could not find a sparse model at `{model_name_or_path}`.")
return cls(SparseStaticModel.from_pretrained(folder, force_download=False))


def _csr_to_torch(matrix: csr_matrix) -> torch.Tensor:
"""Convert a CSR matrix to a coalesced sparse COO tensor."""
coo = matrix.tocoo()
indices = torch.from_numpy(np.vstack([coo.row, coo.col]).astype(np.int64))
return torch.sparse_coo_tensor(indices, torch.from_numpy(coo.data), size=coo.shape).coalesce()
28 changes: 23 additions & 5 deletions tests/test_sparse_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,15 +127,33 @@ def test_encode_matches_sparse_model(encoder: SparseEncoder, sparse_model: Spars
assert np.allclose(encoder.similarity(queries, documents).numpy(), expected_scores)


def test_encode_single_and_dense(encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None:
"""Test encoding a single text, and encoding to a dense tensor."""
def test_encode_single(encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None:
"""Test encoding a single text."""
single = _tensor(encoder.encode_query("word1 word3"))
assert single.shape == (sparse_model.dim,)
assert np.allclose(_dense(single), sparse_model.encode_query("word1 word3").toarray()[0])

dense = _tensor(encoder.encode_document(DOCUMENTS, convert_to_sparse_tensor=False))
assert not dense.is_sparse
assert np.allclose(dense.numpy(), sparse_model.encode_document(DOCUMENTS).toarray())

def test_forward_stays_sparse(sparse_model: SparseStaticModel) -> None:
"""Test that forward returns a sparse tensor, also when a dense tensor is requested from encode."""
module = SparseStaticEmbedding(sparse_model)
out = module(module.preprocess(DOCUMENTS, task="document"))["sentence_embedding"]
assert out.is_sparse
assert out.is_coalesced()
assert out._nnz() == sparse_model.encode_document(DOCUMENTS).nnz

encoder = SparseEncoder(modules=[module], similarity_fn_name="dot")
encoded = _tensor(encoder.encode_document(DOCUMENTS, convert_to_sparse_tensor=False))
assert encoded.is_sparse
assert np.allclose(_dense(encoded), sparse_model.encode_document(DOCUMENTS).toarray())


def test_encode_max_active_dims(encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None:
"""Test that max_active_dims keeps the largest values of each vector."""
out = _dense(encoder.encode_document(DOCUMENTS, max_active_dims=1))
expected = sparse_model.encode_document(DOCUMENTS).toarray()
assert ((out != 0).sum(axis=1) <= 1).all()
assert np.allclose(out.max(axis=1), expected.max(axis=1))


def test_encode_with_prompt(encoder: SparseEncoder, sparse_model: SparseStaticModel) -> None:
Expand Down
Loading