Run this model with HF Jobs

Run minishlab/shimmer on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/minishlab/shimmer. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/minishlab/shimmer on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
shimmer / sparse_encoder.py
Pringled's picture
New document formula (model2vec 0.12.1): k1 0.2, length exponent 0.4; updated results and plot
7b8c1f2 verified
Raw History Blame Contribute Delete
5.87 kB
from __future__ import annotations
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
from model2vec.sparse import SparseStaticModel
_TASKS = (None, "query", "document")
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.
Texts encoded with the "query" task, as `SparseEncoder.encode_query` does, are encoded with
`SparseStaticModel.encode_query`. All other texts are encoded with `SparseStaticModel.encode_document`.
:param model: The sparse model.
"""
super().__init__()
self.model = model
self.tokenizer = PreTrainedTokenizerFast(tokenizer_object=model.tokenizer)
@property
def max_seq_length(self) -> int | None:
"""The maximum number of tokens of a text."""
return self.model.max_length
@max_seq_length.setter
def max_seq_length(self, value: int | None) -> None:
self.model.max_length = value
def get_embedding_dimension(self) -> int:
"""Get the dimension of the sparse vectors.
:return: The dimension.
"""
return self.model.dim
def preprocess(
self,
inputs: list[SingleInput | PairInput],
prompt: str | None = None,
task: str | None = None,
**kwargs: Any,
) -> dict[str, Any]:
"""Collect the texts and the task to encode them with.
:param inputs: The texts. Only text inputs are supported.
:param prompt: A prompt to prepend to each text.
:param task: The task: "query", "document", or None, which is encoded as "document".
:param **kwargs: Any additional arguments. These are ignored.
:return: The texts and the task.
:raises ValueError: If the task is not "query", "document" or None.
"""
if task not in _TASKS:
raise ValueError(f"Unknown task `{task}`. Expected one of {_TASKS}.")
texts = cast(list[str], inputs)
texts = self._prepend_prompt(texts, prompt) if prompt else list(texts)
return {"texts": texts, "task": task}
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 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
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:
"""Save the sparse model, without the files that Sentence Transformers writes itself.
:param output_path: The folder to save to.
:param *args: Any additional arguments. These are ignored.
:param safe_serialization: Ignored: the model is always stored as safetensors.
:param **kwargs: Any additional arguments. These are ignored.
"""
self.model._save(Path(output_path), sentence_transformers_files=False)
@classmethod
def load(
cls,
model_name_or_path: str,
subfolder: str = "",
token: bool | str | None = None,
cache_folder: str | None = None,
revision: str | None = None,
local_files_only: bool = False,
**kwargs: Any,
) -> SparseStaticEmbedding:
"""Load the module from a local folder or a Hugging Face repo.
:param model_name_or_path: The local folder or the Hugging Face repo id.
:param subfolder: The subfolder to load from.
:param token: The Hugging Face token to use.
:param cache_folder: The folder to cache downloaded files in.
:param revision: The revision of the repo to load.
:param local_files_only: Whether to only use local files.
:param **kwargs: Any additional arguments. These are ignored.
:return: The module.
:raises ValueError: If the model could not be found.
"""
folder = cls.load_dir_path(
model_name_or_path,
subfolder=subfolder,
token=token,
cache_folder=cache_folder,
revision=revision,
local_files_only=local_files_only,
)
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()