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.
Instructions to use minishlab/shimmer with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Model2Vec
How to use minishlab/shimmer with Model2Vec:
from model2vec import StaticModel model = StaticModel.from_pretrained("minishlab/shimmer") embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to everybody."]) print(embeddings.shape) - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub
Browse filesFiles changed (7)
- README.mdAdded+78
- config.jsonAdded+14
- config_sentence_transformers.jsonAdded+4
- model.safetensorsAdded+3
- modules.jsonAdded+8
- sparse_encoder.pyAdded+121
- tokenizer.jsonAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778---language:- enlibrary_name: model2veclicense: mitmodel_name: minishlab/shimmer-72ktags:- embeddings- static-embeddings- sparse- sentence-transformers- sparse-encoder---
# minishlab/shimmer-72k Model Card
This is a sparse [Model2Vec](https://github.com/MinishLab/model2vec) model. Each token has a static sparse code over the vocabulary, so sparse document and query vectors are computed with lookups alone, without running a neural network.
## Installation
Install model2vec with the `sparse` extra using pip:```pip install model2vec[sparse]```
## Usage
Load this model using the `from_pretrained` method of `SparseStaticModel`:```pythonfrom model2vec.sparse import SparseStaticModel
# Load a pretrained sparse Model2Vec modelmodel = SparseStaticModel.from_pretrained("minishlab/shimmer-72k")
# Compute sparse query and document vectorsqueries = model.encode_query(["Example query"])documents = model.encode_document(["Example document"])
# Score queries against documentsscores = 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:```pythonfrom sentence_transformers import SparseEncoder
model = SparseEncoder("minishlab/shimmer-72k", trust_remote_code=True)
queries = model.encode_query(["Example query"])documents = model.encode_document(["Example document"])scores = model.similarity(queries, documents)```
## Additional Resources
- [Model2Vec Repo](https://github.com/MinishLab/model2vec)- [Model2Vec Docs](https://minish.ai/packages/model2vec/introduction)
## Library Authors
Model2Vec was developed by the [Minish Lab](https://github.com/MinishLab) team consisting of [Stephan Tulkens](https://github.com/stephantul) and [Thomas van Dongen](https://github.com/Pringled).
## Citation
Please cite the [Model2Vec repository](https://github.com/MinishLab/model2vec) if you use this model in your work.```@software{minishlab2024model2vec, author = {Stephan Tulkens and {van Dongen}, Thomas}, title = {Model2Vec: Fast State-of-the-Art Static Embeddings}, year = {2024}, publisher = {Zenodo}, doi = {10.5281/zenodo.17270888}, url = {https://github.com/MinishLab/model2vec}, license = {MIT}}```1234567891011121314{ "codebook": { "n_neighbours": 15, "neighbour_weight": 1.0, "min_similarity": 0.4, "norm_scale": 1254.419921875 }, "max_length": 2048, "normalize": false, "k1": 0.4, "norm_coefficient": 2.0, "length_exponent": 0.3, "embedding_dtype": "float32"}1234{ "model_type": "SparseEncoder", "similarity_fn_name": "dot"}123version https://git-lfs.github.com/spec/v1oid sha256:19c678d93f5680294327eb08cd33d25c96c8393344e7097d7833cb039a187f5dsize 85065612345678[ { "idx": 0, "name": "0", "path": "", "type": "sparse_encoder.SparseStaticEmbedding" }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121from __future__ import annotations
from pathlib import Pathfrom typing import Any, cast
import torchfrom sentence_transformers.base.modality_types import PairInput, SingleInputfrom sentence_transformers.base.modules import InputModulefrom transformers import PreTrainedTokenizerFast
from model2vec.sparse import SparseStaticModel
_TASKS = (None, "query", "document")
class SparseStaticEmbedding(InputModule): 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], **kwargs: Any) -> dict[str, Any]: """Encode the texts as queries or documents.
:param features: The texts and the task, as returned by `preprocess`. :param **kwargs: Any additional arguments. These are ignored. :return: The features, with the sparse vectors as a dense tensor under `sentence_embedding`. """ encode = self.model.encode_query if features["task"] == "query" else self.model.encode_document features["sentence_embedding"] = torch.from_numpy(encode(features["texts"]).toarray()) 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))README.mdAdded+78
config.jsonAdded+14
config_sentence_transformers.jsonAdded+4
model.safetensorsAdded+3
modules.jsonAdded+8
sparse_encoder.pyAdded+121
tokenizer.jsonAdded