A Sentence Transformers MultipleNegativesRankingLoss run on support-ticket (question, answer) pairs, where many tickets share one canonical answer, barely beats the base model; what is going wrong, and what do you change?
answer
- where the negatives come from
- the same answer twice in a batch
- the default batch sampler
- BatchSamplers.NO_DUPLICATES
- CachedMultipleNegativesRankingLoss and mini_batch_size
basics
~20 sThe in-batch negatives are poisoned: a repeated canonical answer lands in the same batch as its twin and is scored as a wrong answer. Set batch_sampler=BatchSamplers.NO_DUPLICATES, and raise the batch size, with CachedMultipleNegativesRankingLoss if memory runs out.
solid answer
~40 s`MultipleNegativesRankingLoss` takes its negatives from the batch: every other row's answer is a wrong answer for this question. When two tickets share the same canonical answer and land in one batch, that "negative" is the very text that is this question's positive, so the loss partly penalises the question for matching its own answer and that row can never be fully satisfied. The default `batch_sampler` is `BatchSamplers.BATCH_SAMPLER`, a plain shuffle, so this happens constantly with a skewed answer distribution. I set `batch_sampler=BatchSamplers.NO_DUPLICATES`, which never puts the same text value in a batch twice, across any column. Then I check the batch size, because it is the size of the negative pool: `gradient_accumulation_steps` does not enlarge it, so for batches of hundreds or thousands I switch to `CachedMultipleNegativesRankingLoss` and bound memory with its `mini_batch_size`.
code
python · 15 linesfrom sentence_transformers import SentenceTransformer, SentenceTransformerTrainingArguments
from sentence_transformers.sentence_transformer.losses import CachedMultipleNegativesRankingLoss
from sentence_transformers.sentence_transformer.training_args import BatchSamplers
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
# The negative pool is the whole batch; mini_batch_size only bounds memory.
loss = CachedMultipleNegativesRankingLoss(model, mini_batch_size=32)
args = SentenceTransformerTrainingArguments(
output_dir="models/support-mnrl",
per_device_train_batch_size=1024,
batch_sampler=BatchSamplers.NO_DUPLICATES, # the default sampler ignores duplicates
num_train_epochs=1,
)go deeper
Recall that this loss uses the other rows of the batch as wrong answers, and that a sampler setting exists to stop the same text appearing twice in a batch.
Explain why batch size is part of the objective, why gradient accumulation does not enlarge the negative pool, and what mini_batch_size bounds in the cached variant.
Diagnose a flat dev metric from the answer distribution, apply NO_DUPLICATES, deduplicate paraphrases, and size the batch with the cached loss and cross-device gathering in mind.
Weigh larger batches against training time and GPU budget, and decide when cleaning the answer catalogue pays more than any loss or sampler change.
## Where MultipleNegativesRankingLoss gets its negatives `MultipleNegativesRankingLoss` (MNRL) is a ranking loss with **in-batch negatives**. For each anchor in a batch it computes the similarity (cosine by default, times `scale`) to every positive in the batch, and to any extra negative columns, then applies cross-entropy with the anchor's own positive as the correct class. Every other row's positive is a negative for this anchor. Two consequences follow: - The **contents** of a batch decide which negatives the model sees. - The **size** of a batch, `per_device_train_batch_size`, decides how many negatives each anchor is ranked against. Both are controlled by training setup, not by the loss's own arguments, which is why a correct loss can still train badly. ## Failure one: duplicates become false negatives Support data is skewed. Hundreds of questions map to the same canonical answer ("reset your password from the security page"). With the default sampler, `BatchSamplers.BATCH_SAMPLER`, rows are shuffled and cut into batches with no regard for content, so two rows sharing that answer often meet. For row A, row B's positive is a negative, and it is identical to row A's own positive. The loss now asks the model to rank one text above itself, which no model can do, so that row feeds a contradictory signal into every step it appears in. `BatchSamplers.NO_DUPLICATES` fixes this. The sampler builds each batch so that **no value appears twice, even across columns**, deferring a clashing row to a later batch rather than dropping it. The library recommends it for every in-batch negatives loss. Know its limits: - It compares **exact values**, not meaning. Two answers that differ by one word are both admitted and still act as false negatives for each other. - When one answer dominates the data, its rows are deferred again and again, so the end of each epoch is a run of small batches with few negatives. The sampler's length is an upper bound for this reason. - Rows produced by hard-negative mining in triplet form repeat the same question and answer once per negative; without the sampler those copies meet in one batch and become false negatives for each other. - `BatchSamplers.NO_DUPLICATES_HASHED` does the same check on precomputed `xxhash` values, faster on large or media datasets at a small memory cost. ## Failure two: the batch is too small With 16 rows per batch each question is ranked against 15 answers, an easy task the base model already solves. Larger batches make the task harder and the signal stronger. Two tempting shortcuts do not help: 1. **`gradient_accumulation_steps`** sums gradients over several small batches, but each small batch computes its own softmax, so every anchor still sees only its own micro-batch as negatives. The library notes that gradient-scaling tricks cannot split an in-batch negatives batch. 2. **Several GPUs** run their own batches; unless `gather_across_devices=True` is set on the loss, each device's anchors only see that device's candidates. The tool built for this is **`CachedMultipleNegativesRankingLoss`**, which implements GradCache. It embeds the whole batch in chunks of `mini_batch_size` (default 32) without gradients, computes the loss and its gradients with respect to the embeddings, then re-runs the chunks with gradients. Memory is bounded by `mini_batch_size` while the negative pool is the full `per_device_train_batch_size`. The price is speed: its docstring estimates roughly 2x to 2.4x slower than the plain loss. ## The knobs in one place | Setting | Default | Effect on in-batch negatives | |---|---|---| | `batch_sampler` | `BatchSamplers.BATCH_SAMPLER` | `NO_DUPLICATES` keeps repeated texts out of one batch | | `per_device_train_batch_size` | inherited from Transformers | size of the negative pool per anchor | | `gradient_accumulation_steps` | 1 | does not enlarge the pool | | `mini_batch_size` (cached loss) | 32 | memory per chunk only, not the pool | | `gather_across_devices` (loss) | `False` | shares candidates across GPUs | ## A diagnosis order 1. Count how often each answer string repeats; a heavy head is the warning sign. 2. Switch to `BatchSamplers.NO_DUPLICATES` and re-run; this alone often moves the dev metric. 3. Deduplicate near-identical answers before training, since the sampler cannot see paraphrases. 4. Raise the batch size; move to `CachedMultipleNegativesRankingLoss` when the GPU cannot hold it. 5. Only then reach for mined hard negatives, which add difficulty on top of a clean batch.
- You enabled NO_DUPLICATES, yet two answers that differ only in punctuation still collide. Why, and what do you do?The sampler compares exact values, so near-identical strings are different values and can share a batch. Normalise or deduplicate answers before training, for example by collapsing answers to a canonical form, because no sampler setting detects paraphrases.
- Training on four GPUs with per_device_train_batch_size=128, how many candidates does each anchor see?By default, its own device's 128 rows, because each device computes the loss on its local batch. Setting `gather_across_devices=True` on `MultipleNegativesRankingLoss` or its cached variant gathers embeddings across devices, so each anchor is ranked against all 512, at some communication and memory cost.
It is like a multiple-choice exam where the wrong options are other students' correct answers: if two students wrote the same answer, one of the "wrong" options is identical to the right one, and no amount of studying can make the question fair.
- Batch size only changes speed for MultipleNegativesRankingLoss, not what it learns.
- Raising gradient_accumulation_steps gives each anchor more in-batch negatives.
- The default batch sampler already keeps duplicate answers out of one batch.
- NO_DUPLICATES also separates paraphrased answers that mean the same thing.
- CachedMultipleNegativesRankingLoss is a faster drop-in for the plain loss.