Sub topic 10
Failure modes and debugging
This chapter assumes you have built a retrieve-then-rerank pipeline like the one in the earlier chapters. You should know what a bi-encoder and a cross-encoder are, and you should be able to compute recall@k, MRR, and nDCG. Here we look at the ways a reranker goes wrong and how to find the cause.
A debugging mindset: find the stage that failed
A reranker is the second stage of a pipeline. When the final results look bad, the fault can sit in the first stage, in the reranker, or in the data you feed between them. Fixing the wrong stage wastes time.
Start with one question per failing query: is the relevant passage in the candidate pool at all?
- If it is not in the pool, the reranker cannot help. The problem is in first-stage retrieval or chunking.
- If it is in the pool but ranked low after reranking, the problem is in the reranker, its input, or the model's fit to your domain.
- If it is ranked high but the user still sees a bad answer, the problem is downstream, in prompt assembly or in the relevance labels you evaluate against.
Failure 1: a weak candidate pool
A cross-encoder only reorders what it receives. If the relevant passage is not among the top k_retrieve candidates, no reranker can recover it. This is the most common cause of "the reranker did nothing."
Symptoms:
- recall@k_retrieve of the first stage is low, for example below 0.9 on your labeled queries.
- Reranked metrics barely improve over the baseline, because the ceiling is set by the pool.
Checks and fixes:
- Measure recall at the candidate depth, not just at the final cutoff.
- Raise
k_retrieveand see whether recall rises. If it does, depth was the limit. - Add a lexical retriever and fuse results, as described in the hybrid fusion chapter. Exact identifiers, error codes, and product names often fail in dense retrieval.
- Check chunking. If the answer is split across two chunks, neither chunk may look relevant on its own.
The function below reports the ceiling that your pool places on any reranker.
def pool_recall(pools, relevant_by_query):
"""Fraction of queries whose pool contains at least one relevant doc,
and the mean share of relevant docs present in the pool."""
hit_queries = 0
shares = []
for qid, pool in pools.items():
relevant = relevant_by_query[qid]
found = set(pool) & relevant
if found:
hit_queries += 1
shares.append(len(found) / len(relevant))
return hit_queries / len(pools), sum(shares) / len(shares)
pools = {"q1": ["d3", "d7", "d1"], "q2": ["d4", "d5", "d6"]}
relevant = {"q1": {"d1"}, "q2": {"d9"}}
print(pool_recall(pools, relevant))Here query q2 has no relevant document in its pool, so the first value printed is 0.5. No reranking change will fix q2.
Failure 2: truncation hides the answer
Cross-encoders have a maximum input length, usually 512 tokens for MiniLM-style models. The query and passage share that budget. Anything beyond it is cut off silently, and the model scores only what remains.
This produces a specific pattern: long passages whose answer sits late in the text score low even though they are correct. Short passages that start with on-topic words score high.
To check whether truncation is affecting you, count tokens with the model's own tokenizer.
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=512)
tokenizer = model.tokenizer
def truncated_fraction(query, passages, max_length=512):
cut = 0
for p in passages:
n = len(tokenizer(query, p, truncation=False)["input_ids"])
if n > max_length:
cut += 1
return cut / len(passages)
passages = ["short passage about API keys."] * 3 + ["long text " * 600]
print(truncated_fraction("How do I rotate an API key?", passages))This prints 0.25 because one of four passages exceeds the limit. Run the same check over your real candidate pools. If a meaningful share is truncated, you have three options:
- Split passages into smaller chunks of roughly 100 to 300 tokens before indexing, so the answer sits near the start of a chunk.
- Score overlapping windows of a long passage and keep the maximum score.
- Use a model trained with a longer context window.
Do not just raise max_length above what the model was trained for. Position embeddings past the trained length are usually missing or untrained, and the call may fail or give poor scores.
Failure 3: misreading raw scores
Raw cross-encoder outputs are scores, not probabilities. For ms-marco-MiniLM-L-6-v2 the output is a logit, which can be negative and has no fixed upper bound. Two mistakes follow from this:
- Using one global threshold such as "keep anything above 0.5". The right cutoff depends on the model and the domain, and a value that works on one query set may drop good passages on another.
- Comparing scores across queries. A score of 4.0 for one query does not mean the same relevance as 4.0 for a different query.
Scores are meaningful for ordering the candidates of a single query. If you need a threshold, for example to return "no answer found", calibrate it on labeled data from your own domain. Pick the cutoff that gives the precision and recall you want on that set, and recheck it whenever you change the model or the corpus.
Failure 4: domain mismatch
Models such as MS MARCO cross-encoders are trained on web search queries and short passages. They can lose accuracy on legal contracts, medical notes, source code, or non-English text. The model may rate generic, fluent text above a precise but terse passage, because that is what its training data rewarded.
Signs of domain mismatch:
- The reranker scores boilerplate introductions high.
- Reranked metrics are worse than the first-stage baseline on a labeled sample.
- Results differ sharply between query types, such as natural-language questions versus keyword queries.
What to do:
- Build a small labeled set, even 100 to 200 queries with judged passages, and compare several candidate models on it.
- Try a multilingual model if your text is not English.
- If a gap remains, fine-tune on your own queries with hard negatives, covered in the training chapters.
Failure 5: input formatting and pairing bugs
Many reranking bugs are plain code errors that look like model errors.
- Swapped order. The model expects
(query, passage). Passing(passage, query)often still runs and gives weaker scores. - Misaligned scores. Sorting scores without sorting the passages with them, or reordering the candidate list after scoring.
- Wrong sort direction. Higher scores mean more relevant for these models. Sorting ascending reverses your results.
- Text mismatch. Embedding one version of a passage (with a title) and reranking another (without it), or the reverse.
- Metadata leaks. Prepending long headers or URLs to every passage, which uses up the token budget.
A reliable habit is to keep identifiers attached to scores until the end:
def rerank_with_ids(model, query, candidates, k_final=5):
"""candidates: list of (doc_id, text). Returns list of (doc_id, score)."""
scores = model.predict([(query, text) for _, text in candidates])
scored = [(doc_id, float(s)) for (doc_id, _), s in zip(candidates, scores)]
scored.sort(key=lambda x: x[1], reverse=True)
return scored[:k_final]Failure 6: ties, duplicates, and near-duplicate passages
Corpora often contain repeated text: the same paragraph in several versions of a document, or boilerplate footers. The reranker scores copies identically, so duplicates can fill the top ranks and push out distinct answers.
Deduplicate by exact hash or by a similarity threshold before reranking, and consider keeping only one passage per source document when diversity matters. Also remember that the sort is stable for ties in Python, so equal scores keep first-stage order. That is a reasonable default, but it means first-stage order still influences the result.
A practical debugging procedure
When a query fails, work through this list in order.
- Print the top candidates before and after reranking, with scores and ids.
- Find the relevant passage. Is it in the pool? If not, stop and fix retrieval.
- If present, note its rank before and after. Did reranking move it down?
- Check the token length of that passage with the model's tokenizer. If it is cut, address truncation.
- Read the passages ranked above it. Are they duplicates, boilerplate, or truly relevant? If they are truly relevant, the label may be wrong.
- Try the query with a different reranker model. If another model fixes it, suspect domain fit.
- Add the query to a regression set so that later changes do not bring the failure back.
| Symptom | Likely cause | First check |
|---|---|---|
| No metric gain after reranking | Relevant passage not in pool | Recall at `k_retrieve` |
| Long correct passages rank low | Truncation | Token counts versus `max_length` |
| Good results disappear after a fixed cutoff | Score threshold on uncalibrated logits | Score distribution per query |
| Reranked results worse than baseline | Domain mismatch or swapped inputs | Pair order, small labeled comparison |
| Top results are near copies | Duplicates in pool | Hash or similarity dedup |
Exercise
A reranker shows almost no improvement in MRR over the first-stage baseline. Pool recall at 50 candidates is 0.62. What do you check first, and why?
Show answer
Check the candidate pool, not the reranker. A recall of 0.62 means 38 percent of queries have no relevant passage among the 50 candidates, so the reranker cannot move one to the top for them. Raise the candidate depth, add lexical retrieval with fusion, or fix chunking, then remeasure. Only after pool recall is high should you judge the reranker itself.
Exercise
Your pipeline returns only passages with a score above 0.5 from a model that outputs raw logits. After switching to a different model, many queries return nothing. Why, and what should you do?
Show answer
Raw logits are not calibrated probabilities, and different models use different score ranges, so a threshold chosen for one model does not carry over. Score a labeled set from your domain with the new model, choose a cutoff that gives acceptable precision and recall, and recalibrate each time the model or corpus changes.