Skip to content
Edit this page

Train a retriever

A model built with a head on an SAE or on the vocabulary is a Sentence Transformers SparseEncoder. It trains with that library's trainer; muscari adds losses, schedules and a script that puts them together.

With the library

The model trains with the trainer and evaluators of sentence_transformers.sparse_encoder. The losses of muscari.training.losses are base losses and wrappers for its SpladeLoss and CachedSpladeLoss:

from sentence_transformers.sparse_encoder import SparseEncoderTrainer
from sentence_transformers.sparse_encoder.losses import CachedSpladeLoss

from muscari.training.losses import ContrastiveWithDistillation, MatryoshkaCaps

# in-batch contrastive loss plus KL to a teacher
base = ContrastiveWithDistillation(model, scale=0.2, weight=1.0)
# also train the vectors cut to 64 and 256 weights
base = MatryoshkaCaps(base, [(64, 256), (None, None)])
loss = CachedSpladeLoss(
    model,
    base,
    document_regularizer_weight=3e-5,  # measure before choosing: see the diagnostics
    query_regularizer_weight=3e-5,
    mini_batch_size=8,
)
trainer = SparseEncoderTrainer(model=model, train_dataset=train_dataset, loss=loss)
trainer.train()
model.save("runs/retriever")

The losses are in muscari.training.losses and the callbacks in muscari.training.schedules; the API reference lists them with the sources of each.

A saved model names its modules by their import path. Sentence Transformers asks for trust_remote_code=True for every module class outside its own namespace, muscari's included; muscari.evaluation.models.load_model(path) sets the flag only when every module of the saved model belongs to Sentence Transformers or muscari and the directory holds no code of its own:

from muscari.evaluation.models import load_model

model = load_model("runs/retriever")

With the recipe script

examples/train_retriever is a complete script: it reads the data, builds the head, trains, evaluates before and after and saves the model. It needs the retrieval extra.

examples/train_retriever trains a sparse retriever with Sentence Transformers and evaluates it before and after. It needs the retrieval extra. Three heads train with the same data, loss and schedule, so that they can be compared:

  • --head sae uses the latents of an exported SAE as the vocabulary, through muscari.heads. The SAE encoder stays frozen unless --trainable-sae is given. --sae-k sets how many latents each token keeps, which need not be the SAE's own k (SAE-SPLADE, arXiv 2604.21511, treats the two separately), and --sae-saturation none drops the log(1 + x) on the activations, as LightOn's SlideOn does. An SAE trained with muscari train-sae --normalize-inputs makes the head scale every token state to unit length before the SAE encoder; the head reads this from the SAE. --sae-latent-gate adds a trained non-negative factor per latent on the pooled weights, and --load-balance-weight adds the head's load-balance term to the loss, which grows when few latents take most tokens (muscari.training.losses.LoadBalancedSpladeLoss); both follow SlideOn's published code, which uses the weight 0.01. The term needs the head's own forward pass, so it cannot be combined with --mini-batch-size.
  • --head vocab uses the tokenizer's vocabulary through the language-model head (muscari.heads.VocabularyPooling). It pools exactly the tokens the SAE head pools, no framing tokens and no prompt tokens, so the two heads differ in their dictionary only. --shift subtracts a constant from the logits before ReLU and --fan-out keeps that many logits per token, the two changes SPARSEUP (arXiv 2611.09680) makes to start training sparse; --shift auto estimates the shift as the --shift-quantile (default 0.999) of the content-token logits of --shift-texts training documents. With no shift, no fan-out and every token pooled the head equals SpladePooling. The gradient of the fan-out reaches the kept logits only, as in the model the SPARSEUP authors released, whose code was read and not run. That model pools the special tokens and leaves out only the prompt; --pool-special-tokens does the same here. --probability-threshold is an experimental alternative to --shift, and this project's own: each token's logits are normalised to log-probabilities and the entries above the threshold are kept, --energy adds back that share of the token's log-sum-exp measured from --energy-center (auto: the median over the --shift-texts documents), --logit-temperature divides the logits first, and --no-saturate pools the scores without log(1 + x). The runs used --probability-threshold 0.015625 --energy 0.25 --no-saturate, with and without --regularizer-weight 0; they were ahead of the shift on a 30M encoder at small vector sizes and behind it on a 310M encoder. --capacity (experimental, this project's own) caps the share of the training texts an entry appears in, with one bias per entry moved at --capacity-rate per --capacity-window texts; the runs used 0.01 to 0.05 with --regularizer-weight 0.
  • --head mlm is Sentence Transformers' SpladePooling unchanged, prompt and special tokens included.

The encoder must still have its language-model head for vocab and mlm.

python examples/train_retriever \
  --head sae --sae runs/ruri-v3-30m-sae-trial \
  --query-prompt "検索クエリ: " --document-prompt "検索文書: " \
  --dataset cl-nagoya/ruri-v3-dataset-ft --subsets jsquad \
  --query-column anc --positive-column pos --negative-column neg \
  --eval-benchmark jqara --eval-split dev --max-steps 1000 \
  --out runs/ruri-v3-30m-retriever-trial

The loss is a contrastive loss with in-batch negatives and one hard negative per query, plus a FLOPS regulariser on queries and documents whose weight rises quadratically from zero over the first 30% of the steps. The learning rate, the regulariser weight and that schedule are the ones the model card of sae-splade-ja-310m states for its first training stage; the batch size, the length limit and the number of steps are small defaults and not that card's. --mini-batch-size encodes each batch in pieces with GradCache (CachedSpladeLoss), which gives the same gradients with less memory. --exclude-queries takes files with one query per line and drops the training rows that have such a query, compared after NFKC normalisation; use it to keep the queries of an evaluation set out of the training data. --loss-scale multiplies the scores inside the contrastive loss (default 1). --loss-scale-end moves that factor during training, geometrically, over the --loss-scale-share of the steps; a small factor early makes the softmax less saturated, a larger one later sharpens it. With --distill-weight the loss also contains the KL divergence between the model's scores of a query's positive and hard negatives and a teacher's scores, read from --positive-score-column and --negative-score-column; --teacher-probabilities turns scores between 0 and 1 into logits first, and --student-temperature and --teacher-temperature divide the two sides. The weight multiplies the plain KL divergence, and the student temperature defaults to the inverse of --loss-scale, so that the model's scores enter both terms with the same factor (muscari.training.losses.ContrastiveWithDistillation). --train-caps computes that loss under several caps on the number of non-zero weights and adds the results up, so that a vector still ranks well after it is cut to its largest weights (muscari.training.losses.MatryoshkaCaps); the regulariser sees the uncapped vectors once. Each cap is QUERY/DOCUMENT or full, and --train-cap-weights gives one weight per cap (default: the mean). SPARSEUP v2 (arXiv 2611.09680v2, Section 4.3) uses --train-caps 16/64 32/128 64/256 full --train-cap-weights 0.05 0.08 0.1 0.8; SlideOn averages over every combination of the query caps 128, 64, 32 and the document caps 1024, 512, without an uncapped level. Neither setting has been measured in this project.

Read the start before training

--diagnose ROWS measures, before training and on that many training rows, the quantities these settings act on, and writes them to diagnostics.json (--diagnose-only stops there): how many dimensions are non-zero per text and how many are non-zero for most texts; for the vocabulary head, the quantiles of the logits and the share a shift lets through; the contrastive loss at several values of --loss-scale, next to the loss of a uniform guess; and, with teacher scores, the margin between the positive and the best negative and how peaked the teacher's softmax is at several temperatures. The functions are in muscari.evaluation.diagnostics. They report numbers and recommend none: published values of the shift, the scale, the regulariser weight and the distillation temperature differ by orders of magnitude between sources, because they depend on the encoder, the head, the loss and the teacher.

Checkpoints and results

Training saves a checkpoint every tenth of the steps; started again with the same --out, the script reuses the evaluation before training and continues from the last checkpoint. results.json holds the configuration of the head, the training log and both evaluations; the model is saved in model/. Before training, an SAE head gives the sparse.plain result of muscari probe-sae on the same queries. Train the SAE head in float32: with --bf16 it ended clearly lower than two float32 runs. With sbintuitions/modernbert-ja-30m the unshifted vocabulary head starts nearly dense and collapses within a few hundred steps under these defaults. Both results are under Measurements.

More options

Options can be read from a file named with @, and options after it override the file. recipes/ holds such files with the published settings of several methods (SlideOn, SAE-SPLADE, SPARSEUP, a rescaled head, two Japanese SPLADE models), each line naming the setting of the source it copies. Further options that the recipes use: --contrastive-weight 0 drops the in-batch contrastive loss, so that the model trains on the teacher's scores alone; --margin-mse-weight adds MarginMSE on the teacher's score differences; --query-regularizer-weight and --document-regularizer-weight set the two FLOPS weights apart; --lr-scheduler, --max-grad-norm and --gradient-accumulation are passed to the trainer; --pool-special-tokens pools the special tokens with either head.

For an SAE head: --sae-masked-latents leaves the listed latents out of every vector, in training and afterwards (what that changed in one measurement).

For a vocabulary head: --head-divisor divides the head's projection before training; --fold-vocabulary merges entries that differ in case or word-boundary marker; --noise-tokens mask keeps punctuation, symbols, byte fallbacks and special tokens out of every vector, and --noise-tokens penalty adds their weights to the loss instead; --query-regularizer l1 and --document-regularizer l1 replace FLOPS with the mean L1 norm; --soft-label-weight adds the cross-entropy against a teacher's probabilities. muscari graft-head saves a masked-language model with the encoder of one checkpoint and the head of another. The sources of each are in recipes/ and in the docstrings of muscari.heads and muscari.training.losses.

Queries can have a smaller encoder than documents: see A smaller encoder for queries.