muscari.training¶
Losses, schedules and caps for training sparse retrievers. The losses and schedules require the retrieval extra.
Losses¶
ContrastiveWithDistillation
¶
ContrastiveWithDistillation(
model: SparseEncoder,
*,
scale: float = 1.0,
weight: float = 1.0,
student_temperature: float | None = None,
teacher_temperature: float = 1.0,
squared_temperature_factor: bool = False,
contrastive_weight: float = 1.0,
margin_mse_weight: float = 0.0,
soft_label_weight: float = 0.0,
)
Bases: Module
In-batch contrastive loss plus distillation from a teacher over each query's own candidates.
The contrastive part ranks a query's positive above every document of the batch, with the
scores multiplied by scale. The KL part matches the softmax of the model's scores of the
query's positive and hard negatives to the softmax of the teacher's scores labels
(batch, 1 + negatives). The MarginMSE part matches the differences between the score of
the positive and of each negative to the teacher's differences. The soft-label part is the
cross-entropy of the softmax of the model's scores against the teacher's probabilities
sigmoid(labels), used as they are, without making them sum to one. It is the base loss
of SpladeLoss or CachedSpladeLoss, which add the regularisers.
Two choices keep the contrastive and the KL part on one footing:
student_temperaturedefaults to1 / scale, so the model's scores enter both softmaxes with the same factor.weightmultiplies the plain KL divergence.SparseDistillKLDivLossmultiplies its value by the squared student temperature, after Hinton et al.; that factor is divided out here unlesssquared_temperature_factoris set. With it, a student temperature of 5 makes the distillation 25 times larger than the same weight suggests, and a temperature below 1 makes it vanish.
Published combinations:
- contrastive and KL with weights 1 and 1: SlideOn; also the Shizuku models and SPARSEUP v2, with their own weights. How much the distillation adds differs between those sources.
- KL and MarginMSE without the contrastive part (
contrastive_weight=0): SPLADE-v3 and SAE-SPLADE, with weights 1 and 0.05 and no temperature. - KL alone (
contrastive_weight=0) with a temperature on the model's scores only: SPLARE,student_temperature80, 50 or 10 depending on the head,teacher_temperature1. - the soft-label cross-entropy alone (
soft_label_weight=1, the other weights 0): the first Japanese SPLADE models trained with YAST, whose labels are the scores between 0 and 1 of two rerankers, averaged; its second version adds a KL term.
The teacher's scores must be on a scale whose differences mean something after
teacher_temperature: logits, not probabilities. MarginMSE compares raw score
differences, so it also ties the scale of the model's scores to the teacher's.
Source code in src/muscari/training/losses/contrastive.py
MatryoshkaCaps
¶
Bases: Module
A weighted sum of one loss computed under several caps on the number of non-zero weights.
At every level (query, document) the query vectors keep their query largest weights
and the document vectors their document largest, and loss is computed on the result;
None on a side keeps everything. The gradient reaches only the weights a level keeps, so
the largest weights of a vector learn to carry the ranking on their own. It is the base loss
of SpladeLoss or CachedSpladeLoss, whose regularisers see the vectors once, uncapped.
Two published forms:
- SPARSEUP v2 (arXiv 2611.09680v2) pairs the caps and weights the levels:
levels=[(16, 64), (32, 128), (64, 256), (None, None)]withweights=[0.05, 0.08, 0.1, 0.8]. The paper lists levels and weights in this order; which weight belongs to which capped level is read from that order. - SlideOn (LightOn) takes every combination of query caps
(128, 64, 32)and document caps(1024, 512)with equal weights and no uncapped level:MatryoshkaCaps.gridbuilds it.
weights default to 1 / len(levels) each, the mean; given weights are used as they
are, without normalising. A cap of a level should not exceed what the head can emit, or the
level equals the uncapped one.
Sentence Transformers has SparseMatryoshkaLoss on its main branch, after release 6.3. It
wraps the whole loss instead of the base loss and takes the two sides as parallel lists
(max_active_dims, query_max_active_dims), which is the paired form here.
Source code in src/muscari/training/losses/matryoshka.py
grid
classmethod
¶
grid(
loss: Module,
query_caps: Sequence[int | None],
document_caps: Sequence[int | None],
) -> MatryoshkaCaps
Every combination of a query cap and a document cap, equally weighted.
Source code in src/muscari/training/losses/matryoshka.py
TokenPenalty
¶
Bases: Module
A loss plus the weights that the vectors give to chosen dimensions, as a penalty.
The penalty is weight * factor times the sum, over the queries and documents of the
batch, of their weights in dimensions. It is the noise-token loss of YAST, the trainer
of the Japanese SPLADE models of hotchpotch, which uses the weight 1 for a list of
punctuation and symbols and the classifier, separator and unknown tokens, and raises it
like its query regulariser; WeightWarmup(penalty, "factor", ...) does that here. The
author reports that the listed tokens then almost disappear from the vectors and that
training becomes steadier. VocabularyPooling(masked_tokens=...) removes dimensions
outright instead.
It wraps the base loss of SpladeLoss or CachedSpladeLoss and is itself one.
Source code in src/muscari/training/losses/penalties.py
L1Regularizer
¶
Bases: Module
The mean over the batch of the sum of a vector's weights, as a regulariser for SpladeLoss.
FLOPS penalises dimensions that many texts use; L1 penalises every weight alike, which
acts on the number of terms of each vector. Lassance and Clinchant ("An Efficiency Study
for SPLADE Models", 2022) use L1 on the queries and FLOPS on the documents to make queries
short; YAST has the same default, and its first Japanese SPLADE model uses L1 on both sides.
Pass it as query_regularizer or document_regularizer of SpladeLoss or
CachedSpladeLoss. The weights are not negative after ReLU, so no absolute value is lost
by summing; it is taken anyway.
Source code in src/muscari/training/losses/penalties.py
LoadBalancedSpladeLoss
¶
LoadBalancedSpladeLoss(
model: SparseEncoder,
loss: Module,
*,
load_balance_weight: float,
**kwargs: Any,
)
Bases: SpladeLoss
SpladeLoss plus the load-balance term of an SAE head, which spreads tokens over the latents.
The term comes from the head (see muscari.heads.SAEPooling): one value per forward of
the model, averaged here and multiplied by load_balance_weight. SlideOn uses it with
weight 0.01 next to FLOPS weights of 0.01 on both sides. The other arguments are those of
SpladeLoss; the regulariser weight schedule of Sentence Transformers does not touch
this weight, as in SlideOn, whose ramp covers FLOPS only.
It cannot be combined with CachedSpladeLoss: GradCache computes the loss from stored
vectors, and this term needs the graph of the head's own forward pass.
Raises:
-
ValueError–if the last module of the model does not provide the term.
Source code in src/muscari/training/losses/splade.py
Schedules¶
WeightWarmup
¶
Bases: TrainerCallback
Raises a number on a loss from zero to its value, quadratically, over the first share of the steps.
attribute names the number, for example "factor" of a TokenPenalty. At step
s of n it is value * min(1, s / (share * n)) ** 2, the shape Sentence
Transformers uses for the regulariser weights of SpladeLoss.
Source code in src/muscari/training/schedules.py
LossScaleSchedule
¶
Bases: TrainerCallback
Moves the scale of a contrastive loss from start to end over the first share of the steps.
The scale multiplies the scores inside the loss, so it acts like an inverse temperature. The
path is geometric: after a fraction p of the scheduled steps the scale is
start * (end / start) ** p, and it stays at end afterwards. loss is any object
with a scale attribute that is read at every forward pass.
No published recipe schedules this scale. In this project's own small runs the result of a schedule equalled the result of training at the final scale throughout.
Source code in src/muscari/training/schedules.py
Caps¶
parse_cap
¶
full or QUERY/DOCUMENT, where either side may be full: 64/400, full/256.
Source code in src/muscari/training/caps.py
cap_label
¶
keep_largest
¶
Each row with all but its count largest weights set to zero; None keeps everything.