Fine-tuning embeddings & rerankers

In one sentence

Train your retriever on domain (query, relevant passage) pairs with a contrastive loss, using LLM-generated queries and mined hard negatives. A tuned embedder means re-indexing everything; a tuned reranker doesn't.

Analogy: Training a new librarian with flashcards: "this question goes to this shelf, not the look-alike shelf next to it". The look-alike shelves teach the most.

Synthetic pairs and mined negatives train the model; only real held-out queries decide whether the re-index is worth paying for.

How it works

  • General embedders learn similarity from web data, so they miss your jargon: SKU codes, internal product names.
  • With in-batch negatives (MNRL), every other positive in the batch is a free negative, so bigger batches help.
  • Keep a synthetic pair only if its chunk ranks near the top for that query (round-trip filter).
  • Sample hard negatives from ranks ~10–50; the very top hides unlabeled true positives.
  • Judge the result only on real, held-out queries, such as labelled questions from actual users.

Check yourself

Answer to mark it learned; your answers aren't scored.

You fine-tune an embedder on 52k LLM-generated (query, chunk) pairs. On a held-out slice of those same synthetic pairs, recall@10 jumps from 0.61 to 0.93. The team wants to re-index tonight. What do you do?

Go deeper

Full explanation

General embedding models learn what "similar" means from web data, so they miss your jargon: "PTO" vs "leave of absence", SKU codes, internal product names. Fine-tuning re-teaches similarity with your own examples.

The signal is contrastive. Each example is a (query, positive) pair, optionally plus a hard negative: a passage that looks relevant but isn't. With MultipleNegativesRankingLoss (InfoNCE), every other positive in the batch is a free negative, so a batch of 64 gives each query 63 negatives; bigger batches help.

Where the data comes from:

  1. Synthetic queries: an LLM writes 1–3 questions each chunk answers (Synthetic data). Keep a pair only if its chunk ranks near the top for that query (a round-trip filter) to drop vague questions.
  2. Hard negatives: retrieve with the base model or BM25 and sample from ranks ~10–50. Skip the very top: unlabeled true positives hide there and would teach the model to push away right answers.
  3. Real signals: passages users clicked or the LLM cited are the best positives you'll get.

Rerankers (Reranking (cross-encoders)) train as cross-encoders on the same data with a classification or listwise loss, and swapping one in needs no re-index, so it's often the cheaper first move.

An embedding fine-tune changes every vector: you must re-embed the whole corpus (Index freshness & lifecycle). Judge it only on real, held-out queries (Evaluating RAG).

Code Hard negatives + MNRL with sentence-transformers
pythonHard negatives + MNRL with sentence-transformers
from datasets import load_dataset
from sentence_transformers import (SentenceTransformer, SentenceTransformerTrainer,
                                   SentenceTransformerTrainingArguments)
from sentence_transformers.losses import MultipleNegativesRankingLoss
from sentence_transformers.training_args import BatchSamplers
from sentence_transformers.util import mine_hard_negatives

BASE = "BAAI/bge-base-en-v1.5"  # any open embedding model
model = SentenceTransformer(BASE)

# (anchor, positive) pairs: LLM-written queries per chunk, round-trip filtered
pairs = load_dataset("json", data_files="synthetic_pairs.jsonl", split="train")

# Hard negatives from ranks 10-50: skip the top, where false negatives hide
triplets = mine_hard_negatives(pairs, model, range_min=10, range_max=50,
                               num_negatives=1, sampling_strategy="random")

# InfoNCE: each query vs its positive, its hard negative and every other doc in the batch
loss = MultipleNegativesRankingLoss(model)
args = SentenceTransformerTrainingArguments(
    output_dir="bge-ft", num_train_epochs=1, per_device_train_batch_size=64,
    learning_rate=2e-5, warmup_ratio=0.1, bf16=True,
    batch_sampler=BatchSamplers.NO_DUPLICATES,  # duplicates = fake negatives
)
SentenceTransformerTrainer(model=model, args=args, train_dataset=triplets, loss=loss).train()
model.save("bge-ft/final")
# Next: recall@10 / nDCG@10 on REAL held-out queries, then re-embed the corpus
Real example

An internal IT-helpdesk RAG has 40k chunks of runbooks. On 300 real, labelled employee questions, bge-base gets recall@10 = 0.61; it doesn't connect "VPN keeps dropping" with the "GlobalProtect tunnel reset" runbook. An LLM writes 2 questions per chunk (80k pairs; 52k survive the round-trip filter), hard negatives come from ranks 10–50, and one epoch on a single L4 takes ~40 minutes. Recall@10 rises to 0.74 on the same 300 questions. Re-embedding 40k chunks takes minutes; the team schedules a re-tune when the runbook corpus doubles.

Trade-offs +4 · −3

+ You gain

  • Fixes domain jargon, acronyms and internal names that general models embed poorly.
  • Cheap to train: a base-size open model fine-tunes in under an hour on one GPU from synthetic data.
  • Can let a small, fast self-hosted model match a larger API model on your domain.
  • Reranker fine-tunes need no re-index, so they roll out and roll back easily.

− You pay

  • A new embedding model means re-embedding and re-indexing the whole corpus, plus a migration plan.
  • Needs open weights or a provider that supports it; with a closed embedding API, a small query-side adapter is the usual workaround.
  • Can overfit to the style of synthetic queries and lose general retrieval quality.

Use it when

Recall on real queries stays poor after hybrid search and a reranker, the misses are domain vocabulary, you can run an open model, and you have a labelled eval set to prove the gain.

Avoid it when

Before trying hybrid search and an off-the-shelf reranker, without a held-out eval of real queries, or when frequent re-indexing of a fast-changing corpus is unaffordable.

Numbers to know 4
  • MNRL: a batch of B pairs gives each query B−1 free in-batch negatives; default scale 20 (temperature 0.05).
  • Rule of thumb: ~1k–10k good pairs move a base-size (~110M) model; training takes minutes to an hour on one GPU.
  • Rule of thumb: sample hard negatives from ranks ~10–50, not the top few, where false negatives live.
  • Re-index cost: 10M chunks × ~500 tokens = 5B tokens to re-embed after every model change.
Common pitfalls 4
  • Evaluating on synthetic queries generated from the same chunks: it measures memorization, not retrieval.
  • Hardest negatives that are actually relevant: the model learns to push correct answers away.
  • Duplicate texts in a batch acting as false in-batch negatives; use a no-duplicates batch sampler.
  • Dropping the model's query/passage prefixes (E5 expects query: and passage: ) at training or inference time.
Interview questions 3

Answer out loud first, then reveal.

Retrieval on our internal docs is weak. When would you fine-tune the embedding model?Show answer

Late on the cheap list, not first. I'd error-analyze misses on real queries. Exact codes and names: hybrid search with BM25 fixes them for free. Right chunk retrieved but ranked low: a reranker. If the misses are domain vocabulary the vector model doesn't connect, I fine-tune: LLM-generated queries per chunk, a round-trip filter, hard negatives from ranks 10–50, MultipleNegativesRankingLoss. I ship only if recall@10 improves on held-out real queries, and I budget the full re-embed plus an index migration with rollback.

Why do hard negatives matter, and how can they hurt?Show answer

In-batch negatives are random passages, so after a few steps they're trivially easy and contribute almost no gradient. Hard negatives, passages that share words or topic but don't answer, are where the model learns fine distinctions. The danger is false negatives: in a real corpus, many top-ranked passages for a synthetic query are genuinely relevant but unlabeled, and training on them teaches the model to push right answers away. So I skip the top ranks, sample from a band like 10–50, and drop candidates a cross-encoder scores as relevant.

Embedding fine-tune or reranker fine-tune: which first?Show answer

Usually the reranker. It trains on the same pairs, swaps in without touching the index and rolls back instantly. But it can only reorder what first-stage retrieval returns: if the right chunk isn't in the top 50, no reranker saves it, and then the embedder (or hybrid search) is the fix. So I measure recall@50 first. High recall with poor ordering means reranker; poor recall means embedder, with the re-index cost accepted up front.