What is learned sparse retrieval?¶
For readers who have used the dense models of Sentence Transformers and have not tried a sparse one. It takes about ten minutes and ends where muscari begins. The terms are collected in the glossary.
In one paragraph¶
A dense embedding model turns a text into a few hundred numbers. All of them are non-zero and none means anything on its own. A learned sparse model turns a text into a vector with one dimension per entry of a dictionary: tens of thousands of dimensions, of which a hundred or so are non-zero. Every non-zero dimension is an entry of the dictionary with a weight, so the vector can be read. Two texts are scored by the dot product, as with dense vectors, but only the entries both texts hold contribute, and that is what lets an inverted index, the data structure behind BM25, find the best documents without comparing the query to every one of them. "Learned" says where the weights come from: a trained language model chooses them, and it can give weight to an entry that does not occur in the text.
What a vector looks like¶
The output of a model trained with muscari: a vocabulary head on sbintuitions/modernbert-ja-310m after a small training run (2,000 steps of 16 queries, the conditions of the measurements). Its dictionary is the tokenizer's vocabulary of 102,400 entries.
from muscari.evaluation.models import load_model
model = load_model("runs/retriever/model") # a Sentence Transformers SparseEncoder
query = model.encode_query("日本で一番高い山はどこ?")
documents = model.encode_document(
[
"富士山は静岡県と山梨県にまたがる日本一高い山である。",
"味噌カツは名古屋の名物で、豚カツに八丁味噌のたれをかけて食べる。",
]
)
print(query.shape, model.sparsity(query)["active_dims"]) # torch.Size([102400]) 42.0
print(model.decode(query, top_k=8)) # the entries with the largest weights
print(model.similarity(query, documents)) # tensor([[111.5734, 1.5711]])
The query asks "Which is the highest mountain in Japan?". The tokenizer cuts it into 日本で / 一番高い / 山 / はどこ / ?. Of 102,400 dimensions, 42 are non-zero:
| Entry | Meaning | Weight | |
|---|---|---|---|
| 山 | mountain | 2.72 | a token of the query |
| 最高 | highest | 2.39 | added by the model |
| 日本 | Japan | 2.36 | added (the query's token is 日本で, "in Japan") |
| 世界一 | number one in the world | 2.35 | added |
| 山登り | mountain climbing | 2.35 | added |
| 一番高い | the highest | 2.32 | a token of the query |
| 標高 | elevation | 2.08 | added |
| 登山 | mountaineering | 2.06 | added |
| 日本一 | number one in Japan | 2.00 | added |
| mountain | 1.89 | added | |
| 富士 | Fuji | 1.59 | added |
| … 31 more |
Three of the 42 entries are tokens of the query. The other 39 are expansion: words the model expects in a text that answers the question, 富士 among them, which the query never mentions. はどこ ("where is") received no weight at all. That is term weighting: a learned model also decides which of the text's own words do not matter.
The first document says "Mount Fuji, on the border of Shizuoka and Yamanashi, is the highest mountain in Japan" and has 134 non-zero entries. Its score against the query is the sum, over the 29 entries both vectors hold, of the product of the two weights:
| Entry | Meaning | Query | Document | Product |
|---|---|---|---|---|
| 山 | mountain | 2.72 | 2.63 | 7.15 |
| 世界一 | number one in the world | 2.35 | 2.71 | 6.36 |
| 日本一 | number one in Japan | 2.00 | 2.85 | 5.69 |
| 山登り | mountain climbing | 2.35 | 2.08 | 4.87 |
| 日本 | Japan | 2.36 | 2.03 | 4.79 |
| 富士 | Fuji | 1.59 | 2.97 | 4.72 |
| … 23 more | ||||
| Score | 111.57 |
With this tokenizer the two texts have one token in common, 山: the query says 一番高い and 日本で where the document says 高い and 日本一. An index of the texts' own tokens would match on that one entry, which gives 7.15 of the 111.57 here. The second document is about a pork cutlet from Nagoya; it shares a single entry with the query and scores 1.57.
Not every entry is sensible. The query's vector also holds 生命 (life) and 東京で (in Tokyo), and the document's holds 東京タワー (Tokyo Tower) and ピラミッド (pyramid). This model saw 32,000 queries; the example shows what a sparse vector is, not what a finished model gives.
How a model produces it¶
A SPLADE model, the family Sentence Transformers supports out of the box, is a masked language model used in an unusual way:
tokens → encoder → language-model head a score per vocabulary entry, per token
→ log(1 + ReLU(score)) keep positive scores, dampen large ones
→ maximum over tokens one weight per vocabulary entry
The language-model head was pre-trained to guess a hidden token from its context, so at every position it already scores the words that could stand there. That is where the expansion comes from: at 山 in a question about the highest mountain, 標高 and 登山 are likely words. Retrieval training then teaches the model which of those guesses help ranking.
In Sentence Transformers this is a SparseEncoder made of a transformer with its language-model head and a SpladePooling module, used like a SentenceTransformer: encode_query, encode_document, similarity. Two methods have no dense counterpart: decode turns a vector into entries and weights, and sparsity counts its non-zero dimensions.
Keeping it sparse¶
Nothing in those three steps makes the vector sparse. A language-model head can give a positive score to most of the vocabulary; on some encoders it does, and training then collapses. Sparsity comes from three places:
- A regulariser during training. A penalty on the weights is added to the ranking loss: L1, or FLOPS (Paria et al., arXiv 2004.05665), which penalises an entry by the square of its mean weight over the batch, so that entries active in many texts cost more than rare ones. The weight of the penalty sets the trade between accuracy and cost.
- The shape of the head. A limit on the entries each token may keep, or a threshold the scores must pass, makes the vector sparse before training starts. Most of the methods muscari supports differ in this.
- A cap at inference. Keeping only the largest weights of a vector, for example 64 for a query and 256 for a document, bounds the cost whatever the model does.
Two numbers describe the cost. The non-zero entries per document set the size of the index, and those per query set how many lists a search reads. FLOPS, in the sense of an evaluation figure, is the expected number of entries a query and a document share: it is high when the same entries are active in most texts, as stop words are. Neither figure alone predicts the latency of a search engine, which also depends on how the engine prunes its lists.
The index¶
A search engine stores sparse vectors the way it stores words: for every entry, the list of documents that hold it, with their weights.
entry documents that hold it, with their weights
山 doc 1: 2.63 doc 7: 1.90 doc 9: 0.41 …
富士 doc 1: 2.97 doc 4: 2.20 …
標高 doc 1: 1.89 doc 7: 2.44 …
(Schematic; only the weights of doc 1 are the model's.) A query reads the lists of its own entries and nothing else, and an engine can return the exact top of the ranking this way, where a nearest-neighbour index for dense vectors returns an approximation. Elasticsearch, OpenSearch and Qdrant store such vectors, and Sentence Transformers has helper functions for them.
The score is the dot product and nothing else. BM25 needs the statistics of the collection at search time, an IDF for every word and the length of every document; a learned sparse model needs neither, because what they do has been learned into the weights: a common word gets a small weight or none, as はどこ did above. The one exception among the methods here is Latent Terms, which scores the latents of an untrained SAE with BM25.
Next to BM25 and dense retrieval¶
| BM25 | Dense | Learned sparse | |
|---|---|---|---|
| The vector | counts of the text's own words | hundreds to thousands of numbers, all non-zero | tens of thousands of dimensions, a hundred or so non-zero |
| A dimension | a word | nothing on its own | a word, or a latent of an SAE |
| Matches a text that uses other words | no | yes | yes, through expansion |
| Index | inverted index | nearest-neighbour index, usually approximate at scale | inverted index |
| A model at search time | none | the encoder | the encoder (some models encode queries with a lookup table instead; Sentence Transformers supports them, muscari adds nothing for them) |
| Training | none | needed | needed, and more delicate |
| Why a document matched | visible | not visible | visible, entry by entry |
What speaks for a learned sparse model:
- It runs where BM25 runs. A search stack built on an inverted index can serve it, and combine it with BM25 or with a dense model in a hybrid search.
- Its matches can be read. Every score is a sum over named entries, as in the table above. A wrong result can be traced to the entries that caused it.
- It keeps exact terms. With a vocabulary as the dictionary, the word pieces of a product code or a rare name are dimensions of their own, and a match on them is exact.
- Its size is adjustable after training. A cap trades accuracy for cost per query or per document, without a new model.
What it costs:
- The model still runs for every query, and its output has the size of the dictionary. Encoding with a head of 102,400 dimensions is slower than pooling an embedding.
- Training is delicate. The penalty that makes vectors sparse works against the loss that makes them accurate, and published settings do not carry over between encoders. In this project's runs several published recipes ended with empty vectors on an encoder they were not written for.
- The dictionary is fixed. With a vocabulary head it is the tokenizer's, so a model is bound to the languages and the word pieces of its tokenizer.
- Cost depends on the data. A few entries that are active in most documents make every search slow, whatever the average vector size is.
How accurate, next to dense retrieval?¶
The closest thing to a controlled comparison is a family of English models on one backbone, ModernBERT-base, and one training set: a dense model (DenseOn), a late-interaction model (LateOn), and sparse models that two groups trained on the same base. Their authors report nDCG@10 on BEIR:
| Sparse model | Head | Reported | Next to |
|---|---|---|---|
| SPARSEUP (paper) | vocabulary | 56.4 on 13 datasets | DenseOn 57.9, LateOn 58.9 |
| the same, with a contrastive pre-training stage of its own, as the other two have | vocabulary | 58.1 | between the two |
| SPARSEUP, second version, with more training stages | vocabulary | 59.2 | SlideOn 58.7 |
| SlideOn (model card) | SAE latents | 56.68 on 15 datasets | DenseOn 56.20 |
Read with care: these are the authors' own figures, the cards do not all give the same number for the same model (DenseOn's own card reports 56.75 on the 15 datasets), the benchmarks are English, and nothing of it was reproduced here. What they support is modest. At the same size and with the same data, a sparse model is reported within a point or two of the dense one, on either side, and a late-interaction model above both. On these reports, choosing an inverted index no longer means giving up accuracy.
This project ran one such comparison on a small scale, in Japanese: one encoder trained as a dense retriever and with two sparse heads, on the same data for the same 2,000 steps. The sparse heads were not behind the dense retriever, and none of the three reached the fine-tuned dense model that the encoder's authors publish. The training was short and its batches small, which gave the dense retriever little, so it supports no more than the reports above do, and one thing besides: a sparse head can take over what an encoder brings as a dense retriever within a short run.
Two kinds of dictionary¶
Everything above used the tokenizer's vocabulary as the dictionary. The second family that muscari supports uses the latents of a sparse autoencoder (SAE) instead.
An SAE is a small network trained to rewrite a hidden state of the encoder as a sum of a few directions out of a large set, for example 16 out of 65,536. Each direction is a latent. Put in the place of the language-model head, the SAE gives every token a handful of active latents, and the maximum over the tokens gives a sparse vector with one dimension per latent.
| Vocabulary as the dictionary | SAE latents as the dictionary | |
|---|---|---|
| Size | the tokenizer's | your choice |
| Sparse before training | no, unless the head is changed | yes: a fixed number of latents per token |
| Reading a dimension | it is a word piece | it has no name; you look at what it fires on |
| What you need first | an encoder that kept its language-model head | an SAE of the encoder: published, or trained on your texts |
A latent can join words that an exact match keeps apart. In the quickstart, one latent links 一番高い with 高い, and another 日本で with 日本一, with nothing trained for retrieval.
Where muscari comes in¶
Sentence Transformers trains SPLADE models as they are. muscari adds the parts for what came after: the changes that make a vocabulary head train on modern encoders, heads built on SAE latents and the tools to train and inspect the SAEs, losses that combine a contrastive term with distillation, and diagnostics that measure a setting before you train with it. All of it plugs into SparseEncoder and its trainer.
- Coming from dense models: what stays and what changes when you train a sparse model.
- Methods at a glance: what each supported method does, its strengths and its costs.
- Quickstart: search with a published SAE, then train your own.
- Sentence Transformers' sparse encoder documentation, for the library everything here builds on.
Further reading¶
- Formal et al., SPLADE, 2021: the model family described on this page.
- Paria et al., Minimizing FLOPs to Learn Efficient Sparse Representations, 2020: the regulariser.
- Lassance and Clinchant, An Efficiency Study for SPLADE Models, 2022: what makes a sparse model fast or slow in an index.