Fine-tuning embedding models
If your RAG system retrieves the wrong chunks, the generator cannot save you. Off-the-shelf embedding models are trained on broad web data, so they often miss what "similar" means in your domain: internal product names, legal clause types, part numbers, or the way your customers phrase problems. Fine-tuning the embedding model is one of the highest-leverage, lowest-cost training jobs you can run, often fitting on a single GPU in under an hour for small models.
Why it matters
Embedding fine-tuning improves retrieval recall directly, and recall is usually the bottleneck in RAG quality. Unlike LLM fine-tuning, the risk profile is low: the model only produces vectors, so there is no new way for it to say something harmful. The main cost is that you must re-embed your corpus whenever you change the model.
Sentence Transformers (now at v5, maintained by Hugging Face) is the standard library for this. It has a SentenceTransformerTrainer built on the Transformers trainer, dozens of losses, evaluators for retrieval metrics, and it also trains rerankers (cross-encoders) and sparse encoders. Unsloth also added embedding model support.
How it works
Most retrieval fine-tuning is contrastive. You give the model (anchor, positive) pairs, such as (user question, the passage that answers it), and train it to place each anchor closer to its positive than to other passages.
MultipleNegativesRankingLoss is the default choice. Within a batch, each anchor's positive is the target and every other positive in the batch serves as a negative. Larger batches mean more negatives and usually better results; CachedMultipleNegativesRankingLoss lets you reach large effective batch sizes on limited memory. Adding a third column of hard negatives (passages that look relevant but are wrong) gives a much sharper signal.
Rendering diagram…
Matryoshka training wraps the loss so it is applied to truncated prefixes of the embedding as well as the full vector. The sbert.net docs describe training a 768-dimension model so its first 512, 256, 128 and 64 dimensions also work as embeddings. That lets you store short vectors for a fast first pass and use full vectors for reranking, cutting vector database cost.
Reference architecture
The training data usually comes from your own corpus. If you lack real query logs, generate synthetic queries per chunk with an LLM, then mine hard negatives with the current embedding model.
Rendering diagram…
Two cautions on hard negative mining. First, filter out "negatives" that are actually relevant (near-duplicates or other passages that answer the query), or you will train the model to push away correct answers. Second, keep a test set of real queries if at all possible; synthetic queries are easier than real ones and inflate scores.
Code
This follows the Sentence Transformers v5 trainer API: a dataset with anchor, positive and negative columns, MNRL wrapped in Matryoshka, and an InformationRetrievalEvaluator for recall and NDCG.
from datasets import load_dataset
from sentence_transformers import (
SentenceTransformer, SentenceTransformerTrainer,
SentenceTransformerTrainingArguments, losses,
)
from sentence_transformers.evaluation import InformationRetrievalEvaluator
from sentence_transformers.training_args import BatchSamplers
model = SentenceTransformer("BAAI/bge-base-en-v1.5")
train = load_dataset("json", data_files="triplets.jsonl", split="train") # anchor, positive, negative
base_loss = losses.MultipleNegativesRankingLoss(model)
loss = losses.MatryoshkaLoss(model, base_loss, matryoshka_dims=[768, 512, 256, 128])
# held-out real queries: ids -> text, and query id -> set of relevant doc ids
queries, corpus, relevant = load_ir_eval("eval/") # your own loader
evaluator = InformationRetrievalEvaluator(queries, corpus, relevant, name="support-ir")
args = SentenceTransformerTrainingArguments(
output_dir="bge-support",
num_train_epochs=1,
per_device_train_batch_size=64,
learning_rate=2e-5,
warmup_ratio=0.1,
batch_sampler=BatchSamplers.NO_DUPLICATES, # avoid false in-batch negatives
eval_strategy="steps",
eval_steps=200,
)
trainer = SentenceTransformerTrainer(
model=model, args=args, train_dataset=train, loss=loss, evaluator=evaluator,
)
print("before", evaluator(model))
trainer.train()
print("after", evaluator(model))
model.save_pretrained("bge-support/final")
BatchSamplers.NO_DUPLICATES matters with MNRL: if the same passage appears twice in a batch, it becomes a false negative for itself.
Trade-offs and pitfalls
- Re-embedding cost. A new model means re-embedding the whole corpus and swapping the index atomically. Plan the migration, including dual-writing during cutover.
- False negatives. In-batch and mined negatives can be secretly relevant. Deduplicate and filter mined negatives by a similarity threshold or a reranker.
- Overfitting to synthetic queries. LLM-written queries copy wording from the passage. Mix in real queries and paraphrases.
- Forgetting general retrieval. Heavy domain tuning can hurt queries outside the domain. Keep a small general retrieval check in your eval.
- Bigger is not always better. A tuned small model frequently beats an untuned large one on domain retrieval, at a fraction of the latency.
- Consider the reranker first. If you already retrieve a decent top 50, fine-tuning a cross-encoder reranker can be an easier win than retraining the embedder.
Checklist
- Measure baseline recall at k and NDCG on real queries before training.
- Build (query, positive) pairs from logs or synthetic generation, plus hard negatives.
- Filter mined negatives for false negatives.
- Use MNRL with large batches and the no-duplicates sampler.
- Consider Matryoshka training if vector storage cost matters.
- Plan a full re-embed and atomic index swap for rollout.