Skip to content
Edit this page

Coming from dense models

If you have trained a SentenceTransformer, most of what you know carries over. This page lists what stays, what changes and where muscari comes in, for Sentence Transformers 6.3.

What stays the same

  • The data. Columns for a query, a positive and hard negatives, optionally with a teacher's scores as the label.
  • The trainer. SparseEncoderTrainer and SparseEncoderTrainingArguments are the dense ones with another model class: batch size, learning rate, checkpoints, evaluators and callbacks work as before.
  • The model's interface. encode_query, encode_document, similarity, prompts, save and loading by name or path.
  • The memory trick for large batches. GradCache exists for both: CachedMultipleNegativesRankingLoss there, CachedSpladeLoss here.

What changes

Dense Sparse, in Sentence Transformers What muscari adds
Model SentenceTransformer SparseEncoder builders that return a SparseEncoder: build_vocabulary_encoder, build_sparse_encoder
Modules a transformer, Pooling, often Normalize a transformer with its language-model head, SpladePooling VocabularyPooling, SAEPooling
What the encoder must have any encoder the language-model head it was pre-trained with graft_head for an encoder saved without one; an SAE head needs no language-model head
Output an array of a few hundred numbers per text a sparse tensor with one dimension per dictionary entry; decode and sparsity read it shared_latents reads a match between SAE vectors
Similarity cosine dot product, not normalised
Smaller vectors truncate_dim, trained with MatryoshkaLoss max_active_dims keeps the largest weights MatryoshkaCaps trains under several caps; --caps evaluates under them
Contrastive loss MultipleNegativesRankingLoss: cosine times 20 SparseMultipleNegativesRankingLoss: dot product times 1 a scale you choose, and LossScaleSchedule to move it during training
Distillation MarginMSELoss, DistillKLDivLoss SparseMarginMSELoss, SparseDistillKLDivLoss ContrastiveWithDistillation: the contrastive, KL, MarginMSE and soft-label terms in one loss
Sparsity does not exist SpladeLoss wraps the ranking loss and adds FLOPS with a weight for queries and one for documents L1Regularizer, WeightWarmup, TokenPenalty, and heads that are sparse before training
Before training nothing to check nothing built in --diagnose, and probe-sae for an SAE
Evaluation InformationRetrievalEvaluator, NanoBEIREvaluator the same with a Sparse prefix, which also report the vector sizes eval-retriever at several caps with FLOPS; compare-runs with intervals over seeds and queries
Queries and documents through different models Router Router, also with a lookup table for queries combine_encoders, build_asymmetric_sae_encoder
Index a vector index an inverted index; helper functions for several engines nothing: use the library's

One name means two things. Sentence Transformers has a module called SparseAutoEncoder, which makes the pooled sentence embedding of a dense model sparse. The SAEs of muscari work one step earlier, on the state of every token, and their latents are pooled afterwards as SPLADE pools vocabulary entries.

The same training, three times

The shortest training of each kind. train_dataset has the columns anchor, positive and negative in all three.

from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer
from sentence_transformers.sentence_transformer import losses

model = SentenceTransformer("your/encoder")
loss = losses.MultipleNegativesRankingLoss(model)  # cosine similarity, times 20

trainer = SentenceTransformerTrainer(
    model=model,
    train_dataset=train_dataset,
    loss=loss,
)
trainer.train()
from sentence_transformers import SparseEncoder
from sentence_transformers.sparse_encoder import SparseEncoderTrainer, losses

model = SparseEncoder("your/masked-language-model")  # its head, then SpladePooling
loss = losses.SpladeLoss(
    model,
    losses.SparseMultipleNegativesRankingLoss(model),  # dot product, times 1
    document_regularizer_weight=3e-5,
    query_regularizer_weight=5e-5,
)

trainer = SparseEncoderTrainer(
    model=model,
    train_dataset=train_dataset,
    loss=loss,
)
trainer.train()
from sentence_transformers.sparse_encoder import SparseEncoderTrainer, losses

from muscari.heads import build_vocabulary_encoder

model = build_vocabulary_encoder(
    "your/masked-language-model",
    shift="auto",  # estimated from the documents: sparse before the first step
    shift_texts=document_sample,
    fan_out=16,
)
loss = losses.SpladeLoss(
    model,
    losses.SparseMultipleNegativesRankingLoss(model, scale=0.2),
    document_regularizer_weight=3e-5,
    query_regularizer_weight=3e-5,
)

trainer = SparseEncoderTrainer(
    model=model,
    train_dataset=train_dataset,
    loss=loss,
)
trainer.train()

Only the model and the loss differ. The numbers in the second and third are placeholders: the regulariser weights and the scale depend on the encoder, the head and the loss, which is the subject of the next section. examples/train_vocabulary_head.py and examples/train_sae_head.py are complete scripts of the third kind.

What will surprise you

Scores are not bounded. A cosine lies between -1 and 1, and the default scale of 20 suits that range. A dot product of sparse vectors can be 5 or 500, depending on how many entries are active and how large they are, so the scale of the contrastive loss is a setting you have to look at. In this project's runs, multiplying the scores by 0.2 instead of 1 changed the result more than any other setting; SPARSEUP trains with a temperature of 6.

There are two objectives. The ranking loss wants more and larger weights, the regulariser fewer and smaller ones, and one number sets the balance. Published values for it differ by orders of magnitude, because they belong to one encoder, one head and one loss. A dense model has nothing like it.

A run can collapse. If the head starts with most of the vocabulary active, the first losses are huge and the regulariser can push every weight to zero within a few hundred steps, after which nothing trains. The opposite, vectors that stay dense, happens too. Both are visible before the first update: --diagnose prints how dense the vectors start and how the loss compares with its chance value.

Your retrieval encoder may not fit. A dense retriever is usually saved without its language-model head, and a SPLADE-style head needs one. Either start from the masked language model, graft a head onto the retriever, or train an SAE on the encoder you have and use its latents.

A result is a pair of numbers. A sparse model that scores higher with vectors three times as large has not simply won. Evaluation reports the non-zero entries and FLOPS next to nDCG, and a fair comparison fixes one of the two, for example with a cap.

Half precision is not free. With an SAE head, bfloat16 autocast ended clearly lower than float32 in one comparison here: rounding the hidden states changes which latents the Top-K selects.

The output is large. A batch of vectors over a vocabulary of 100,000 entries is small as a sparse tensor and large as a dense one. Keep the sparse tensors that encode returns unless you need otherwise.

Next