Model and Modality PlaybooksNovember 23, 2026Flatkey

Reranking in RAG: A Controlled Quality and Latency Example

A repeatable seven-query example shows where reranking improves passage order, where it adds no relevance benefit, and why missing candidates stay missing.

Reranking in RAG: A Controlled Quality and Latency Example

Reranking in RAG scores the relationship between a query and each retrieved passage, then changes the order of those passages before they reach the language model. It is useful when the first retrieval stage finds the right evidence but places it too far down the list. It cannot recover a relevant passage that never entered its candidate set.

This tutorial runs a small, repeatable comparison: 14 synthetic documents, seven queries, the same five retrieved candidates, and a final context budget of three passages. Two queries moved their first relevant result from second place to first. Several queries gained no measured relevance benefit while still taking extra processing time. One deliberately constructed retrieval miss remained a miss.

The documents and relevance grades are synthetic, author-defined teaching material, frozen before model scoring. They are not customer records, independently human-annotated judgments, or a production benchmark. The code below includes the complete fixture so you can inspect the assumptions and repeat the test.

Where reranking fits in a RAG pipeline

The two stages do different jobs:

  1. Retrieve candidates. A lexical method such as BM25 or an embedding search selects a manageable subset of the document collection.
  2. Rerank those candidates. A cross-encoder receives the query and each passage together and produces a relevance score. Keep the highest-ranked passages within the context budget.
  3. Generate and evaluate the answer. The language model uses the selected context. Answer correctness and citation support need their own evaluation.

The Sentence Transformers retrieve-and-rerank documentation describes this arrangement. A cross-encoder performs inference on query–passage pairs; first-stage retrieval avoids applying that more expensive step to every passage in a large collection.

This example uses BM25, not embedding similarity, as the first stage. That keeps the lexical retrieval rules visible. For a vector-based first stage, see the embeddings and semantic search tutorial. The same candidate-set check still applies.

What we held constant

The fictional knowledge base contains file deletion, recovery, subscriptions, invoices, project archives, roles, and record location. Its policies exist only for this example; they do not describe Flatkey or another real product.

Each query has explicit relevance grades across the full collection:

  • 2: directly answers the question under the fixture's stated rules.
  • 1: useful supporting information, but incomplete.
  • 0: unrelated, the wrong object, or the wrong condition.

Those grades were fixed before inference. They are transparent assumptions for demonstrating the metrics, rather than independently validated ground truth.

BM25 uses k1=1.2, b=0.75, lowercase alphanumeric tokens, and no stemming or synonym expansion. Ties use stable document IDs. Each query retrieves five documents. Both comparison arms select three passages from that identical set of five; reranking changes order, not membership.

The second stage is the public English cross-encoder/ms-marco-MiniLM-L6-v2 model, pinned to revision 233902d25c440f23af6f7d6e94d2946bac0bee0a. We use its documented Transformers query–passage classification path, FP32 on CPU, with a batch of five and maximum input length 512. The observed pairs were 37–51 tokens, so none was truncated.

No language-model answer was generated. This isolates passage ordering; it does not establish an improvement in final answers.

Reranking in RAG: the measured quality changes

Three metrics capture different aspects of the final three passages:

  • Precision@3: the fraction with grade greater than zero.
  • MRR@3: reciprocal rank of the first passage with grade greater than zero; zero if none appears in the top three.
  • nDCG@3: rank-sensitive graded relevance, using gain 2^grade - 1 and logarithmic discount. The ideal ranking comes from the full 14-document collection, not just the retrieved five.
Query Question MRR@3 before → after nDCG@3 before → after
Q1 Remove an uploaded document 0.5000 → 1.0000 0.5213 → 0.8262
Q2 Avoid next month's renewal charge 0.5000 → 1.0000 0.5213 → 0.8262
Q3 Does archiving permanently erase files? 1.0000 → 1.0000 1.0000 → 1.0000
Q4 Recovery window for a deleted upload 1.0000 → 1.0000 1.0000 → 1.0000
Q5 Download invoices 1.0000 → 1.0000 0.9639 → 1.0000
Q6 Can a viewer invite members? 1.0000 → 1.0000 1.0000 → 1.0000
Q7 Where are records kept? 0.0000 → 0.0000 0.0000 → 0.0000
Mean of seven queries 0.7143 → 0.8571 0.7152 → 0.8075

Mean Precision@3 stayed 0.4762 before and after. The reranker mostly improved placement here; it did not increase the number of relevant passages in the three-passage context. These are descriptive results for seven purpose-built queries, not a statistically supported estimate of production gains.

A closer look at the uploaded-document query

Q1 asks: “How do I remove an uploaded document?” BM25 put D13, a file-search explanation, ahead of D01, the actual deletion procedure.

Document What the passage covers Grade BM25 rank Reranked rank
D13 Finding an uploaded file with search 0 1 2
D01 Selecting a file, deleting it, and the Trash step 2 2 1
D11 Retrying a failed invoice PDF download 0 3 5
D05 Permanent project deletion versus archiving 0 4 3
D10 Activity-log entries 0 5 4

The useful deletion procedure moved up, but the final context still contained irrelevant passages. D08, another relevant passage about file recovery, was outside the five candidates. That is why the full-collection nDCG@3 remains below one even after D01 reaches the top.

The model's raw logits are ranking scores, not calibrated probabilities. For Q2 every candidate's score was negative, yet the cancellation passage ranked first. Do not turn “highest score” into a confidence or answerability guarantee without validating that behavior on suitable data.

The extra latency—and the queries that did not benefit

The run took place on 2026-11-23 UTC, on an Apple M5 with 10 physical cores, using four CPU threads, Python 3.12.13, PyTorch 2.7.1, and Transformers 4.52.4. The cross-encoder had three warm-up runs per query; both stages were then timed for 30 repetitions with fixed inputs.

BM25 timing includes query scoring and sorting. The added cross-encoder timing includes tokenization, the CPU forward pass for the five candidates, and sorting. Model download, tokenizer/model loading, and index construction are excluded. Loading the tokenizer and model took about 1.03 seconds in this run, separate from the table.

Query BM25 median, ms Added reranking median, ms Added reranking p95, ms
Q1 0.050 9.20 12.81
Q2 0.060 10.44 14.80
Q3 0.054 9.86 14.76
Q4 0.056 8.60 9.93
Q5 0.044 10.88 16.74
Q6 0.045 10.52 23.01
Q7 0.043 10.16 12.21

For Q3, Q4, and Q6, all three quality metrics were unchanged. Reranking still added processing time. Q5 had only a small graded-order improvement. Whether that tradeoff is useful depends on your application's quality requirements and latency budget.

The p95 is a coarse nearest-rank estimate from 30 repetitions. These measurements are local, warm CPU processing times for short passages. They do not represent network latency, a hosted API, GPU inference, concurrent production load, or full RAG response time.

The retrieval miss that reranking could not repair

Q7 asks “What region keeps our information?” D12 says “Customer records reside exclusively in Dublin, Ireland. Geographic replication is disabled.”

We deliberately designed that wording mismatch before inference to expose a lexical-retrieval limitation. Under this tokenizer, all BM25 document scores were zero. Stable ID ordering selected D01–D05, leaving D12 out. Reordering those five cannot introduce D12: candidate Recall@5 and all top-three relevance metrics stayed zero.

This is an engineered teaching case, not evidence that ordinary BM25 queries usually fail this way. In an application with similar misses, examine query wording, chunking, synonym handling, hybrid retrieval, and candidate count before asking a reranker to fix the result.

No quality regression was observed on this small fixture. That does not rule out regressions on other queries, domains, languages, or document lengths.

Reproduce the controlled example

Use Python 3.12 with torch==2.7.1 and transformers==4.52.4. A fresh environment needs the public model download; the pinned revision and Apache-2.0 model card are linked above. The script uses safetensors, disables remote repository code, and runs CPU inference.

Install the two packages with python -m pip install torch==2.7.1 transformers==4.52.4. Save the following as rerank_example.py and run python rerank_example.py. It contains the complete synthetic corpus, queries, and explicit relevance grades. Timing will vary with hardware and system load. Small floating-point differences can also occur across software and hardware; compare document order and metric definitions before treating a score difference as meaningful.

"""Synthetic lesson, not product policy or a production benchmark.
Python 3.12; pip install torch==2.7.1 transformers==4.52.4 numpy==2.5.5 safetensors==0.8.0
Run: python rerank_example.py --output results.json
Optional: --model-dir ./model uses an already downloaded pinned safetensors snapshot.
"""
import argparse, hashlib, json, math, platform, re, time
from collections import Counter
from pathlib import Path
from statistics import median
import torch, transformers
from transformers import AutoTokenizer, AutoModelForSequenceClassification


MODEL_ID = "cross-encoder/ms-marco-MiniLM-L6-v2"

REVISION = "233902d25c440f23af6f7d6e94d2946bac0bee0a"

DOCS = {
    "D01": "To delete an uploaded file, open Files, select the file, choose Delete, and confirm. The file moves to Trash, where an owner can restore it for 30 days.",
    "D02": "Deleting your account permanently closes the workspace and removes access. To stop future subscription renewals, use the Cancel subscription action in Billing instead; account deletion is not needed.",
    "D03": "Cancel a subscription from Billing > Subscription > Cancel renewal. Cancellation stops the next renewal charge; access continues until the paid period ends. Deleting files has no effect on renewal.",
    "D04": "Archiving a project hides it from the active project list. The owner can unarchive it at any time. Archive does not permanently delete project files.",
    "D05": "Permanent project deletion is different from archiving. Choose Settings > Delete project to remove a project permanently; archived projects remain restorable.",
    "D06": "To download invoices, open Billing > Invoices, select a billing month and choose Download PDF. Only workspace owners and billing administrators can access invoices.",
    "D07": "Only owners and workspace administrators may invite new members from Settings > Members > Invite. Members with viewer or editor roles cannot send invitations.",
    "D08": "When you delete a file, Trash retains a recoverable copy for 30 days. After 30 days it is permanently removed. The owner can restore a file from Trash before that deadline.",
    "D09": "Project exports contain file names, timestamps, and comments. Exporting a project does not delete files or cancel a subscription.",
    "D10": "The activity log records file uploads, file deletions, project archives and member invitations. Log entries do not change a member's role or a subscription's renewal settings.",
    "D11": "If a PDF invoice download fails, retry from Billing after checking that you are signed into an owner or billing administrator account. Failed PDF downloads do not change subscription charges.",
    "D12": "Customer records reside exclusively in Dublin, Ireland. Geographic replication is disabled.",
    "D13": "File search uses the document title and body. To find an uploaded file, search by its name. Search cannot restore items from Trash or change retention deadlines.",
    "D14": "Viewers can read projects and editors can update project files. Neither role is allowed to invite people; contact an owner or workspace administrator for invitation changes.",
}

QUERIES = {
    "Q1": "How do I remove an uploaded document?",
    "Q2": "How can I avoid being charged again next month?",
    "Q3": "Does archiving a project permanently erase its files?",
    "Q4": "How many days can I recover a deleted upload?",
    "Q5": "Where can I download invoices?",
    "Q6": "Can a viewer invite new members?",
    "Q7": "What region keeps our information?",
}

POSITIVES = {
    "Q1": {"D01": 2, "D08": 1},
    "Q2": {"D03": 2, "D02": 1},
    "Q3": {"D04": 2, "D05": 2},
    "Q4": {"D08": 2, "D01": 2},
    "Q5": {"D06": 2, "D11": 1},
    "Q6": {"D07": 2, "D14": 2},
    "Q7": {"D12": 2},
}

def tokens(text):
    return re.findall(r"[a-z0-9]+", text.lower())

class BM25:
    def __init__(self, docs, k1=1.2, b=0.75):
        self.ids = sorted(docs)
        self.counts = {d: Counter(tokens(docs[d])) for d in self.ids}
        self.lengths = {d: sum(c.values()) for d, c in self.counts.items()}
        self.avg = sum(self.lengths.values()) / len(self.ids)
        self.df = Counter(t for c in self.counts.values() for t in c)
        self.k1, self.b = k1, b

    def search(self, query):
        scores = {}
        for d in self.ids:
            score = 0.0
            for t in set(tokens(query)):
                f, df = self.counts[d][t], self.df[t]
                idf = math.log(1 + (len(self.ids) - df + 0.5) / (df + 0.5))
                denominator = f + self.k1 * (1 - self.b + self.b * self.lengths[d] / self.avg)
                score += idf * f * (self.k1 + 1) / denominator
            scores[d] = score
        return sorted(self.ids, key=lambda d: (-scores[d], d)), scores

def metrics(order, grades, k=3):
    top = order[:k]
    gains = [grades[d] for d in top]
    positive = lambda g: g > 0
    dcg = lambda gs: sum((2 ** g - 1) / math.log2(i + 2) for i, g in enumerate(gs))
    ideal = dcg(sorted(grades.values(), reverse=True)[:k])
    return {"precisionAt3": sum(map(positive, gains)) / k,
            "mrrAt3": next((1 / (i + 1) for i, g in enumerate(gains) if positive(g)), 0.0),
            "ndcgAt3": dcg(gains) / ideal if ideal else 0.0}

def timing(values):
    ordered = sorted(values)
    return {"samplesMs": values, "medianMs": median(values), "p95Ms": ordered[math.ceil(0.95 * len(ordered)) - 1], "minMs": min(values), "maxMs": max(values)}

parser = argparse.ArgumentParser()
parser.add_argument("--model-dir")
parser.add_argument("--runs", type=int, default=30)
parser.add_argument("--output", default="results.json")
args = parser.parse_args()
# Author-defined illustrative grades, fixed before scoring; no independent human validation.
# 2=full answer, 1=useful but incomplete, 0=other.
fixture = {"documents": DOCS, "queries": QUERIES, "labels": POSITIVES}
fixture_hash = hashlib.sha256(json.dumps(fixture, sort_keys=True).encode()).hexdigest()
Path(args.output + ".fixture.json").write_text(json.dumps(fixture, indent=2))
torch.set_num_threads(4)
torch.manual_seed(0)
torch.use_deterministic_algorithms(True)
source = args.model_dir or MODEL_ID
opts = dict(revision=REVISION, trust_remote_code=False, token=False,
            local_files_only=bool(args.model_dir))
tokenizer = AutoTokenizer.from_pretrained(source, **opts)
model = AutoModelForSequenceClassification.from_pretrained(
    source, use_safetensors=True, **opts).to("cpu").eval()
retriever, rows = BM25(DOCS), []
for qid, query in QUERIES.items():
    full_order, bm_scores = retriever.search(query)
    candidates = full_order[:5]  # Freeze these same five for both rankings.
    grades = {d: POSITIVES[qid].get(d, 0) for d in DOCS}
    def rerank():
        features = tokenizer([query] * 5, [DOCS[d] for d in candidates],
            padding=True, truncation=True, max_length=512, return_tensors="pt")
        with torch.inference_mode():
            scores = dict(zip(candidates, model(**features).logits.flatten().tolist()))
        return sorted(candidates, key=lambda d: (-scores[d], d)), scores
    for _ in range(3):
        rerank()  # Warm-up; loading and download are outside measured time.
    after, logits = rerank()
    bm_ms, ce_ms = [], []
    for _ in range(args.runs):
        start = time.perf_counter_ns(); check, _ = retriever.search(query)
        bm_ms.append((time.perf_counter_ns() - start) / 1e6)
        assert check[:5] == candidates
        start = time.perf_counter_ns(); check, _ = rerank()
        ce_ms.append((time.perf_counter_ns() - start) / 1e6)
        assert check == after
    positive = {d for d, g in grades.items() if g > 0}
    recall5 = len(positive.intersection(candidates)) / len(positive)
    rows.append(dict(queryId=qid, query=query, candidates=candidates,
        bm25Top3=candidates[:3], rerankedTop3=after[:3], logits=logits,
        before=metrics(candidates, grades), after=metrics(after, grades),
        candidateRecallAt5=recall5, missing=sorted(positive.difference(candidates)),
        bm25Timing=timing(bm_ms), crossEncoderTiming=timing(ce_ms)))
means = {stage: {m: sum(r[stage][m] for r in rows) / len(rows)
         for m in rows[0][stage]} for stage in ["before", "after"]}
result = dict(model=MODEL_ID, revision=REVISION, fixtureSha256=fixture_hash,
    gradeSource="author-defined illustrative relevance grades fixed before scoring; no independent human annotation or validation",
    device="cpu", threads=4, python=platform.python_version(),
    torch=torch.__version__, transformers=transformers.__version__,
    runs=args.runs, means=means, rows=rows)
Path(args.output).write_text(json.dumps(result, indent=2))
print(json.dumps(means, indent=2))
# Raw logits are uncalibrated scores. Same-candidate recall cannot increase.
# Q7 intentionally exposes lexical retrieval failure; all documents are fictional.

The first-stage candidate set is retained in the output so you can verify that both arms used the same passages. Keep any revised documents, queries, labels, model revision, or candidate budget as a separate experiment; changing those after looking at scores changes what the comparison measures.

Decide whether to keep a reranker

What your evaluation finds Next step
Relevant evidence is retrieved but ranked below the context cutoff Test reranking with a fixed candidate set and context budget; inspect per-query gains and losses.
The first-stage order already satisfies the task Compare any additional quality benefit with the added processing cost; retain the simpler baseline when the gain is insufficient.
Relevant evidence is missing from the candidates Improve first-stage recall, then repeat the controlled comparison.
Passages conflict, are outdated, or belong to another permission scope Apply source, freshness, and access rules; relevance ranking alone is not a truth or authorization decision.
Latency is close to an application limit Measure representative passage lengths, candidate counts, concurrency, and cold starts on the actual serving path.

For a real deployment, build a representative query set with appropriate relevance judgments, keep a held-out evaluation set, and evaluate the generated answers and citations as well as retrieval. The RAG evaluation guide explains how those measurements fit together.

Reranking in RAG is worth testing when good evidence is present but poorly ordered. The decision to keep it should come from measured per-query quality changes and added latency under your own workload.

If you are choosing the generation layer, browse Flatkey's model catalog. Disclosure: Flatkey publishes this tutorial and operates the linked service. The experiment above runs locally with the public cross-encoder model.