Skip to content
Edit this page

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_temperature defaults to 1 / scale, so the model's scores enter both softmaxes with the same factor.
  • weight multiplies the plain KL divergence. SparseDistillKLDivLoss multiplies its value by the squared student temperature, after Hinton et al.; that factor is divided out here unless squared_temperature_factor is 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_temperature 80, 50 or 10 depending on the head, teacher_temperature 1.
  • 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
def __init__(
    self,
    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,
) -> None:
    super().__init__()
    if scale <= 0 or teacher_temperature <= 0 or (student_temperature is not None and student_temperature <= 0):
        raise ValueError("The scale and the temperatures must be positive.")
    weights = (weight, contrastive_weight, margin_mse_weight, soft_label_weight)
    if min(weights) < 0 or sum(weights) == 0:
        raise ValueError("The weights must not be negative, and one of them must be positive.")

    self.model = model
    self.weight = weight
    self.contrastive_weight = contrastive_weight
    self.margin_mse_weight = margin_mse_weight
    self.soft_label_weight = soft_label_weight
    self.student_temperature = 1.0 / scale if student_temperature is None else student_temperature
    self.squared_temperature_factor = squared_temperature_factor

    self.contrastive = SparseMultipleNegativesRankingLoss(model, scale=scale)
    self.distillation = SparseDistillKLDivLoss(
        model,
        student_temperature=self.student_temperature,
        teacher_temperature=teacher_temperature,
    )
    self.margin_mse = SparseMarginMSELoss(model)

MatryoshkaCaps

MatryoshkaCaps(
    loss: Module,
    levels: Sequence[Cap],
    weights: Sequence[float] | None = None,
)

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)] with weights=[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.grid builds 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
def __init__(self, loss: torch.nn.Module, levels: Sequence[Cap], weights: Sequence[float] | None = None) -> None:
    super().__init__()
    require_base_loss(loss)
    if not levels:
        raise ValueError("At least one level is needed.")
    for level in levels:
        if len(level) != 2 or any(side is not None and side <= 0 for side in level):
            raise ValueError(f"A level is (query, document) with positive integers or None, not {level!r}.")
    if weights is not None and (len(weights) != len(levels) or any(weight < 0 for weight in weights)):
        raise ValueError("There must be one non-negative weight per level.")

    self.loss = loss
    self.levels = [(level[0], level[1]) for level in levels]
    self.weights = [1.0 / len(levels)] * len(levels) if weights is None else [float(w) for w in weights]

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
@classmethod
def grid(
    cls,
    loss: torch.nn.Module,
    query_caps: Sequence[int | None],
    document_caps: Sequence[int | None],
) -> MatryoshkaCaps:
    """Every combination of a query cap and a document cap, equally weighted."""
    return cls(loss, list(itertools.product(query_caps, document_caps)))

TokenPenalty

TokenPenalty(
    loss: Module,
    dimensions: Sequence[int],
    weight: float = 1.0,
)

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
def __init__(self, loss: torch.nn.Module, dimensions: Sequence[int], weight: float = 1.0) -> None:
    super().__init__()
    require_base_loss(loss)
    if not dimensions or weight < 0:
        raise ValueError("At least one dimension and a non-negative weight are needed.")

    self.loss = loss
    self.weight = weight
    self.factor = 1.0
    self.dimensions: torch.Tensor
    self.register_buffer("dimensions", torch.tensor(sorted({int(d) for d in dimensions}), dtype=torch.long))

L1Regularizer

L1Regularizer(model: SparseEncoder | None = None)

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
def __init__(self, model: SparseEncoder | None = None) -> None:
    super().__init__()
    self.model = model

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
def __init__(self, model: SparseEncoder, loss: torch.nn.Module, *, load_balance_weight: float, **kwargs: Any):
    super().__init__(model, loss, **kwargs)
    if not hasattr(model[-1], "balance_terms"):
        raise ValueError("The last module of the model must be an SAE head that provides load-balance terms.")
    if load_balance_weight < 0:
        raise ValueError("load_balance_weight must not be negative.")

    self.load_balance_weight = load_balance_weight

Schedules

WeightWarmup

WeightWarmup(loss: Any, attribute: str, share: float)

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
def __init__(self, loss: Any, attribute: str, share: float) -> None:
    if not 0 < share <= 1:
        raise ValueError("The share must be in (0, 1].")
    self.loss, self.attribute, self.share = loss, attribute, share
    self.value = float(getattr(loss, attribute))

LossScaleSchedule

LossScaleSchedule(
    loss: Any, start: float, end: float, share: float = 1.0
)

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
def __init__(self, loss: Any, start: float, end: float, share: float = 1.0) -> None:
    if start <= 0 or end <= 0 or not 0 < share <= 1:
        raise ValueError("The scales must be positive and the share must be in (0, 1].")
    self.loss, self.start, self.end, self.share = loss, start, end, share

Caps

parse_cap

parse_cap(value: str) -> Cap

full or QUERY/DOCUMENT, where either side may be full: 64/400, full/256.

Source code in src/muscari/training/caps.py
def parse_cap(value: str) -> Cap:
    """``full`` or ``QUERY/DOCUMENT``, where either side may be ``full``: ``64/400``, ``full/256``."""
    if value == "full":
        return FULL
    parts = value.split("/")
    if len(parts) != 2:
        raise argparse.ArgumentTypeError(f"A cap is 'full' or 'QUERY/DOCUMENT', not {value!r}.")
    sides: list[int | None] = []
    for part in parts:
        if part == "full":
            sides.append(None)
        elif part.isdigit() and int(part) > 0:
            sides.append(int(part))
        else:
            raise argparse.ArgumentTypeError(f"A cap side is a positive integer or 'full', not {part!r}.")
    return sides[0], sides[1]

cap_label

cap_label(cap: Cap) -> str
Source code in src/muscari/training/caps.py
def cap_label(cap: Cap) -> str:
    if cap == FULL:
        return "full"
    return "/".join("full" if side is None else str(side) for side in cap)

keep_largest

keep_largest(vectors: Tensor, count: int | None) -> Tensor

Each row with all but its count largest weights set to zero; None keeps everything.

Source code in src/muscari/training/caps.py
def keep_largest(vectors: torch.Tensor, count: int | None) -> torch.Tensor:
    """Each row with all but its ``count`` largest weights set to zero; ``None`` keeps everything."""
    if count is None or count >= vectors.shape[1]:
        return vectors
    values, indices = vectors.topk(count, dim=1)
    return torch.zeros_like(vectors).scatter_(1, indices, values)