Loss Overview — Sentence Transformers documentation (original) (raw)

Loss Table

Loss functions play a critical role in the performance of your fine-tuned Cross Encoder model. Sadly, there is no “one size fits all” loss function. Ideally, this table should help narrow down your choice of loss function(s) by matching them to your data formats.

Note

You can often convert one training data format into another, allowing more loss functions to be viable for your scenario. For example, (sentence_A, sentence_B) pairs with class labels can be converted into (anchor, positive, negative) triplets by sampling sentences with the same or different classes.

Additionally, mine_hard_negatives() can easily be used to turn (anchor, positive) to:

As well as formats with similarity scores instead of binarized labels, by setting output_scores=True.

Inputs Labels Number of Model Output Labels Appropriate Loss Functions
(sentence_A, sentence_B) pairs class num_classes CrossEntropyLoss
(anchor, positive) pairs none 1 MultipleNegativesRankingLossCachedMultipleNegativesRankingLoss
(anchor, positive/negative) pairs 1 if positive, 0 if negative 1 BinaryCrossEntropyLoss
(sentence_A, sentence_B) pairs float similarity score between 0 and 1 1 BinaryCrossEntropyLoss
(anchor, positive, negative) triplets none 1 MultipleNegativesRankingLossCachedMultipleNegativesRankingLoss
(anchor, positive, negative_1, ..., negative_n) none 1 MultipleNegativesRankingLossCachedMultipleNegativesRankingLoss
(query, [doc1, doc2, ..., docN]) [score1, score2, ..., scoreN] 1 LambdaLossPListMLELossListNetLossRankNetLossListMLELoss

Distillation

These loss functions are specifically designed to be used when distilling the knowledge from one model into another. For example, when finetuning a small model to behave more like a larger & stronger one, or when finetuning a model to become multi-lingual.

Texts Labels Appropriate Loss Functions
(sentence_A, sentence_B) pairs similarity score MSELoss
(query, passage_one, passage_two) triplets gold_sim(query, passage_one) - gold_sim(query, passage_two) MarginMSELoss
(query, positive, negative_1, ..., negative_n) [gold_sim(query, positive) - gold_sim(query, negative_i) for i in 1..n] MarginMSELoss
(query, positive, negative) [gold_sim(query, positive), gold_sim(query, negative)] MarginMSELoss
(query, positive, negative_1, ..., negative_n) [gold_sim(query, positive), gold_sim(query, negative_i)...] MarginMSELoss

Commonly used Loss Functions

In practice, not all loss functions get used equally often. The most common scenarios are:

Custom Loss Functions

Advanced users can create and train with their own loss functions. Custom loss functions only have a few requirements:

To get full support with the automatic model card generation, you may also wish to implement:

Consider inspecting existing loss functions to get a feel for how loss functions are commonly implemented.