Sub topic 12
Training data and hard negatives
This chapter assumes you know how a cross-encoder scores a (query, passage) pair, how a first-stage retriever produces candidates, and basic Python. It explains where the training data for a reranker comes from, why negative examples matter more than positives, and how to mine them without poisoning the dataset.
What a reranker learns from
A cross-encoder is trained on labeled pairs. Each example says, in some form, "this passage is relevant to this query" or "this passage is not." The model has no other source of knowledge about what relevance means in your domain. The data defines it.
Three sources are common:
- Public relevance datasets. MS MARCO is the most widely used. It contains real search queries with passages marked as relevant. Many off-the-shelf rerankers, including
cross-encoder/ms-marco-MiniLM-L-6-v2, were trained on it. - Your own click or feedback logs. Clicks, "was this helpful" votes, and accepted answers show what users found relevant in your domain. They are noisy and biased toward results that were already ranked high.
- Synthetic queries. You take passages from your corpus and ask a language model to write questions each passage answers. The pair (generated question, source passage) becomes a positive example.
Positives are usually easy to find. The harder question is what to use as negatives.
Why negatives decide the quality
A negative is a passage that should score lower than the positive for the same query. The model learns the decision boundary from them, so the kind of negative you choose shapes what the model can tell apart.
Random negatives are cheap. Take a query about rotating API keys and pair it with a random passage about invoices. The model learns quickly that invoices are not about API keys. It also learns almost nothing useful, because the first-stage retriever would never have returned that passage anyway.
At inference time the reranker sees only the retriever's candidates. Those candidates are topically close to the query, and the reranker must separate the truly relevant ones from near misses. Training should look like that situation. A hard negative is a passage that looks relevant, usually because the retriever ranks it highly, but does not answer the query.
For the query "How do I rotate an API key?", compare these negatives:
| Negative passage | Type | What the model learns |
|---|---|---|
| "Billing invoices are emailed monthly." | Random | Almost nothing; trivially different |
| "Our API supports JSON and XML." | Moderately hard | Mentioning "API" is not enough |
| "To change your password, open Account Settings." | Hard | Similar intent ("change a credential") is not the same task |
| "API keys expire after 90 days." | Very hard | Related facts about keys do not answer how to rotate one |
The last row also shows the risk. Very hard negatives are close to the line between relevant and not relevant, so some of them are actually relevant and unlabeled. That problem gets its own section below.
Mining hard negatives with a retriever
The standard method uses the same kind of first stage you deploy. For each training query:
- Run the retriever (bi-encoder, BM25, or both) and take the top N results, for example 50.
- Remove the known positives.
- Sample negatives from what remains.
Using a retriever to mine negatives means the training distribution matches what the reranker will see in production. The following code builds a set of hard negatives with a bi-encoder.
from sentence_transformers import SentenceTransformer, util
bi_encoder = SentenceTransformer("all-MiniLM-L6-v2")
corpus = [
"Rotate API keys from the Security page.",
"API keys expire after 90 days.",
"Reset your password in Account Settings.",
"Our API returns JSON by default.",
"Billing invoices are emailed on the first of each month.",
]
corpus_emb = bi_encoder.encode(corpus, convert_to_tensor=True, normalize_embeddings=True)
# query -> set of corpus indices known to be relevant
labeled = {
"How do I rotate an API key?": {0},
"How do I change my password?": {2},
}
def mine_hard_negatives(query, positives, top_n=4, skip_top=0):
q_emb = bi_encoder.encode(query, convert_to_tensor=True, normalize_embeddings=True)
hits = util.semantic_search(q_emb, corpus_emb, top_k=top_n)[0]
negatives = [h["corpus_id"] for h in hits if h["corpus_id"] not in positives]
return negatives[skip_top:]
training_examples = []
for query, positives in labeled.items():
for pos in positives:
training_examples.append((query, corpus[pos], 1.0))
for neg in mine_hard_negatives(query, positives):
training_examples.append((query, corpus[neg], 0.0))
for example in training_examples:
print(example)Each tuple is (query, passage, label). A label of 1.0 marks a positive and 0.0 a negative. The next chapter covers the loss functions that consume these labels. Here the point is how the examples are built.
The false negative problem
A passage is a false negative when it is relevant to the query but is not in your labels, so mining treats it as a negative. Training on it teaches the model to push down a good answer.
False negatives are common because relevance labels are sparse. MS MARCO has roughly one labeled positive per query, even though many passages in the collection may answer the question. The better your retriever, the more likely its top results include an unlabeled correct answer. Aggressive mining therefore makes the problem worse.
Several mitigations are used together:
- Skip the very top. Drop the first few retrieved results, or only sample from a rank window such as 10 to 100. Passages at rank 1 and 2 are the most likely to be unlabeled positives.
- Use a score margin. Keep a negative only if a stronger model scores it clearly below the positive. For example, require the negative's score to be at most 95% of the positive's score under an existing cross-encoder.
- Filter with a stronger model. Run a larger reranker or an LLM over the mined negatives and discard any it judges relevant.
- Spot check. Read a sample of 50 mined negatives by hand. If more than a few look relevant, tighten the filters.
Choosing how many negatives per positive
Datasets differ in how they pair examples. Three layouts are common:
| Layout | Example structure | Notes |
|---|---|---|
| Pairs with binary labels | (query, passage, 0 or 1) | Simple; the class balance is something you set |
| Triplets | (query, positive, negative) | One comparison per row; used by pairwise training |
| Groups | (query, positive, negative 1 ... negative n) | One positive against several negatives; used by listwise training |
A ratio of one positive to several negatives, often between 1:4 and 1:15, is typical. More negatives give a richer signal per query but cost more compute, because each pair is a full forward pass through the transformer. You also want a mix: mostly hard negatives, plus a few random ones so the model does not forget easy distinctions.
Synthetic queries and their limits
When you have no labeled queries, you can generate them. The usual process:
- Sample a passage from your corpus.
- Prompt a language model to write one or more questions that the passage answers.
- Treat (question, passage) as a positive.
- Mine negatives for the question using the retriever, excluding the source passage.
This gives you in-domain training data cheaply. It has known weaknesses. Generated questions tend to copy words from the passage, so the model may learn to reward lexical overlap. They are also more specific than real user queries, which are often short and vague. Always mix in some real queries if you have them, and evaluate on real queries, not generated ones.
A second false-negative risk applies here. Corpora often contain near-duplicate passages, so another passage may answer the generated question equally well. Deduplicate the corpus before mining.
Building the dataset step by step
The flow below summarizes the pipeline from raw material to training examples.
Two practical details matter at the end of this pipeline:
- Split by query, not by row. If rows for the same query land in both training and validation sets, the validation score is inflated.
- Keep a held-out set with clean labels. Use it for the recall@k, MRR, and nDCG measurements from the evaluation chapter. Do not mine negatives for it using the same filters as the training set, or you will measure only how well the model agrees with your filter.
Matching the retriever you deploy
The negatives are only as relevant as the retriever that produced them. If you train with negatives from BM25 but deploy a dense retriever, the reranker sees a different kind of near miss in production. Dense retrievers return semantically similar but off-target passages. BM25 returns passages that share keywords. A reranker trained mainly on one type can be weaker on the other.
When the production first stage is hybrid, mine from both lexical and dense results and combine them. The reciprocal rank fusion code from the hybrid retrieval chapter works for this. It gives a single list of candidates whose mix resembles what the reranker will face.
If you replace the retriever later, plan to re-mine. A retrieval change shifts the candidate pool, and the old negatives no longer represent it.
Common mistakes
- Treating all non-labeled passages as negatives. Only retrieved, unlabeled passages are plausible hard negatives, and even those need filtering.
- Mining only the top few ranks. This maximizes false negatives.
- Training only on easy negatives. The model scores well on training data and fails to separate near misses in production.
- Evaluating on synthetic queries only. Scores will look better than real-world quality.
- Leaking passages across splits. The same passage as a positive in training and in the test set inflates results.
Exercise
You mine hard negatives for a support-documentation reranker by taking the top 5 bi-encoder results for each query and removing the labeled positive. After training, the reranker ranks the correct passage below the retriever's own ranking on a held-out set. Name the most likely cause in the data, and give two changes that address it.
Show answer
The most likely cause is false negatives. Passages at ranks 1 to 5 often contain unlabeled but correct answers, so the model learned to push down good passages. Two fixes: sample negatives from a deeper rank window such as 10 to 100 instead of the top 5, and filter mined negatives with a stronger reranker or a score margin against the positive. Hand-checking a sample of the mined negatives would confirm the diagnosis.
Exercise
Why is it a problem to train a reranker only on random negatives, even though they are guaranteed not to be relevant?
Show answer
Random negatives are topically far from the query, so the model learns only coarse distinctions. In production the reranker sees candidates that the retriever already judged similar to the query, and it must separate relevant passages from near misses. Training on easy negatives does not teach that skill.