Fine-Tuning an Embedding Model
Train an embedding model on your own question-passage pairs with sentence-transformers.
When an off-the-shelf embedding model keeps retrieving the wrong chunks for your domain, fine-tuning it on your own data can give a large improvement, often more than switching to a bigger model. Thanks to sentence-transformers, fine-tuning a small embedding model takes a few dozen lines of code and runs on a single GPU, or even a CPU for small datasets.
When to fine-tune
- You have an evaluation set and general models plateau on it.
- Your domain has specialised vocabulary or unusual question styles.
- You want a small, fast model to match a large one on your specific task.
Do not fine-tune before you have an evaluation set. Without one you cannot tell whether the new model is better.
Training data: (question, passage) pairs
For retrieval, training data is a list of pairs: a question (the anchor) and a passage that answers it (the positive). Good sources are search logs with clicks, support tickets linked to help articles and FAQ pages. If you have none, generate synthetic questions from your chunks with an LLM:
import json
from pydantic import BaseModel
import anthropic
client = anthropic.Anthropic()
class Questions(BaseModel):
questions: list[str]
def questions_for(chunk: str, n: int = 3) -> list[str]:
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=1000,
output_config={"effort": "low"},
messages=[{"role": "user", "content":
f"Write {n} different questions that a user might ask which this passage answers. "
"Vary the wording and avoid copying phrases from the passage. "
f"<passage>\n{chunk}\n</passage>"}],
output_format=Questions,
)
return response.parsed_output.questions
import random
chunks = json.load(open("index/chunks.json", encoding="utf-8")) # from earlier lessons
random.seed(42)
random.shuffle(chunks)
cut = int(len(chunks) * 0.85) # hold back 15% of the chunks for testing
for file_name, part in [("train_pairs.json", chunks[:cut]), ("test_pairs.json", chunks[cut:])]:
pairs = [{"anchor": q, "positive": c["text"]} for c in part for q in questions_for(c["text"])]
json.dump(pairs, open(file_name, "w", encoding="utf-8"), indent=1)
print(file_name, len(pairs), "pairs")
The split is made by chunk, not by question: every question about a held-back chunk goes into the test set. Never test on chunks the model was trained on.
The loss: Multiple Negatives Ranking
The standard loss for retrieval fine-tuning is MultipleNegativesRankingLoss. For each question in a batch, its own passage is the positive and every other passage in the batch is treated as a negative. The model learns to pull each question towards its passage and away from the others. You only need positive pairs, and larger batches give more negatives and usually better results.
Training
pip install "sentence-transformers[train]" datasets accelerate
import json
from datasets import Dataset
from sentence_transformers import (SentenceTransformer, SentenceTransformerTrainer,
SentenceTransformerTrainingArguments)
from sentence_transformers.losses import MultipleNegativesRankingLoss
from sentence_transformers.training_args import BatchSamplers
train = Dataset.from_list(json.load(open("train_pairs.json", encoding="utf-8")))
evaluation = Dataset.from_list(json.load(open("test_pairs.json", encoding="utf-8")))
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
loss = MultipleNegativesRankingLoss(model)
args = SentenceTransformerTrainingArguments(
output_dir="models/bge-small-zentrix",
num_train_epochs=3,
per_device_train_batch_size=32,
learning_rate=2e-5,
warmup_ratio=0.1,
batch_sampler=BatchSamplers.NO_DUPLICATES, # no duplicate passages within a batch
eval_strategy="epoch",
save_strategy="epoch",
logging_steps=20,
)
trainer = SentenceTransformerTrainer(model=model, args=args, train_dataset=train,
eval_dataset=evaluation, loss=loss)
trainer.train()
model.save_pretrained("models/bge-small-zentrix/final")
The NO_DUPLICATES batch sampler matters here: if two questions in the same batch share a passage, that passage would wrongly be treated as a negative for one of them.
Evaluating the result
InformationRetrievalEvaluator computes standard retrieval metrics on a held-out set. Run it on the base model and on the fine-tuned model:
from sentence_transformers.evaluation import InformationRetrievalEvaluator
test_pairs = json.load(open("test_pairs.json", encoding="utf-8")) # held-out chunks only
corpus = {f"d{i}": text for i, text in enumerate(sorted({p["positive"] for p in test_pairs}))}
doc_id = {text: key for key, text in corpus.items()}
queries = {f"q{i}": p["anchor"] for i, p in enumerate(test_pairs)}
relevant = {f"q{i}": {doc_id[p["positive"]]} for i, p in enumerate(test_pairs)}
evaluator = InformationRetrievalEvaluator(queries, corpus, relevant, name="zentrix-test")
for name in ["BAAI/bge-small-en-v1.5", "models/bge-small-zentrix/final"]:
results = evaluator(SentenceTransformer(name))
print(name, {k: round(v, 3) for k, v in results.items() if "ndcg@10" in k or "recall@10" in k})
Improving further: hard negatives
Random in-batch negatives are often too easy. Hard negatives are passages that look similar to the question but do not answer it, for example the sick-leave paragraph for a paid-leave question. Mining them with the base model and adding them as a third column (anchor, positive, negative) usually gives a further gain. Recent versions of sentence-transformers include a mine_hard_negatives utility for this.
A fine-tuned model produces a different vector space. Re-embed the entire collection with the new model, and keep the old index until the new one has been evaluated.
Key takeaways
- Fine-tune only once you have an evaluation set showing that general models fall short.
- Training data is (question, passage) pairs; an LLM can generate synthetic questions from your chunks.
- MultipleNegativesRankingLoss with large, duplicate-free batches is the standard recipe.
- Evaluate on held-out chunks, consider hard negatives, and re-embed everything after training.