Skip to content
Visual explainer 3h to learn 5 steps

Rerank candidates and fit evidence into a context budget

Rerank a candidate set and select deduplicated evidence within a token budget, with thresholds you can justify.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.

Topic 11 of 34

In short

First-stage search is fast but rough, so a reranker reads each question and candidate pair together and reorders a small set, often 20 to 50 chunks. You then drop near-duplicates, cut anything below a tested score threshold and pack the best evidence into a fixed token budget. A high score only means the reranker found the text similar; it does not prove the chunk answers the question.

Think of it like this: Search is a recruiter shortlisting fifty CVs by keywords; reranking is the interview that orders the best ten.

Explained simply

Hybrid search gives you, say, 30 candidate chunks. Some are great, some are only loosely related and some repeat each other. You can only send a limited amount of text to the model, so you need to choose carefully.

A reranker helps choose. It is a second model that reads the question and one chunk together and gives a relevance score. Because it reads both at once, it notices details that plain vector search misses. It is slower, so you only use it on the short list.

Next you remove near-duplicates. The same paragraph might appear in two articles, or in versions 2 and 3 of a policy. Sending both wastes space and gives the model the false impression that two sources agree.

Finally you fill a context budget: a fixed number of tokens for evidence. Add the best chunks one by one until the next would not fit. Drop anything below a score threshold you chose by testing. A high score means similar, not proven correct.

Press Play on a diagram to walk through it one step at a time.

FlowFrom candidates to the context window
  1. 1
    Candidates

    Top 30 from hybrid search

  2. 2
    Rerank

    Cross-encoder scores each pair

  3. 3
    Deduplicate

    Drop near-identical chunks

  4. 4
    Threshold

    Remove scores below the cut-off

  5. 5
    Pack

    Add chunks until the budget is full

LayersHow a context window is spent
  1. 1
    Answer room

    Reserved for the model's reply, e.g. 500 tokens

  2. 2
    Evidence

    Packed chunks with IDs, e.g. 2,000 tokens

  3. 3
    Question

    The user's text plus any clarification

  4. 4
    Instructions

    System prompt and output schema

In depth

Why a cross-encoder reranks better

Vector search uses a bi-encoder: the question and each chunk are embedded separately, and similarity is computed between the two vectors. That is fast because chunk vectors are computed once, at ingest. A cross-encoder instead feeds the question and the chunk into the model together, so every word of the question can interact with every word of the chunk. It catches things like a chunk that mentions refunds but is about a different plan.

The price is that nothing can be precomputed: each question needs one model pass per candidate. On a CPU, a small cross-encoder may take a few milliseconds to tens of milliseconds per pair, so 30 pairs is fine and 3,000 is not. Hosted rerank APIs exist and are usually paid per request; the labs use a local or stub scorer.

CompareBi-encoder versus cross-encoder
Bi-encoder (vector search)
  • Embeds query and chunk separately
  • Chunk vectors precomputed
  • Fast over millions of rows
  • Less precise ordering
Cross-encoder (reranker)
  • Reads query and chunk together
  • Nothing precomputed
  • One model pass per pair
  • More precise on a short list

Suppressing near-duplicates

Duplicates come from copied paragraphs, overlapping windows and several versions of the same document. Start with cheap rules: keep at most one chunk per doc_id and section_id, and only the current version unless the question is about history. Then catch near-copies across documents by comparing text. Two common checks are cosine similarity between chunk embeddings above a high cut-off, such as 0.95, or word overlap (Jaccard similarity of word sets) above a cut-off.

Work down the reranked list and skip any chunk too similar to one you already kept. This greedy approach keeps the higher-ranked copy. Log what was suppressed, so you can see whether the rule ever removed a chunk that held different, important detail.

  • One chunk per doc_id and section_id by default
  • Current version only, unless history is asked for
  • Skip if too similar to an already kept chunk
  • Log suppressed chunk IDs for review

Score thresholds you can defend

A threshold removes weak evidence, which reduces noise and helps the model abstain when nothing fits. But reranker scores are not probabilities. Their range depends on the model; some output raw logits that can be negative. A score of 0.8 from one model means something different from 0.8 from another, and nothing about either says the chunk is current, permitted or actually contains the answer.

So choose a threshold from data. Score every candidate in your labelled set, mark which were relevant, and look at the two distributions. Pick a cut that keeps nearly all relevant chunks while dropping many irrelevant ones, and write the chosen value, model name and evaluation date in configuration. Re-check it whenever the model or corpus changes.

Packing a token budget and paying for latency

The model's context window holds instructions, the question, evidence and the answer. Decide the evidence budget explicitly, for example 2,000 tokens, and count tokens with the tokenizer of the model that will answer. Add chunks in reranked order with their IDs and headings, and stop when the next chunk would not fit. Prefer whole chunks over cutting one in half, which can drop a condition.

Every stage adds latency. Measure each one separately: keyword query, vector query, fusion, reranking and packing. If reranking dominates, shrink the candidate set, use a smaller model or cache scores per question and index version. Then check on the evaluation set that quality held.

  • Budget: instructions + question + evidence + answer room
  • Count tokens with the answer model's tokenizer
  • Add whole chunks in rank order
  • Time each stage separately

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Rerank a small candidate set~35m
  2. 2
    Suppress near-duplicate chunks~35m
  3. 3
    Set score thresholds~35m
  4. 4
    Fit evidence to a token budget~35m
  5. 5
    Weigh reranking latency~35m

Key points

  • A cross-encoder scores the question and chunk together, which is more accurate but much slower than comparing stored vectors.
  • Rerank only a small candidate set; cost and latency grow with every pair you score.
  • Near-duplicates (the same paragraph in v2 and v3, or in two FAQs) waste budget and can drown out other evidence.
  • Choose thresholds from labelled data and log what was cut, so a too-strict threshold shows up in evaluation.
  • Count tokens with the same tokenizer as the answer model and leave room for instructions and the answer.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")

def rerank(question: str, chunks: list[dict], keep: int = 8) -> list[dict]:
    pairs = [(question, c["text"]) for c in chunks]
    scores = reranker.predict(pairs)
    for c, s in zip(chunks, scores):
        c["rerank_score"] = float(s)
    return sorted(chunks, key=lambda c: c["rerank_score"], reverse=True)[:keep]

Optional: downloads a small model on first run. The local labs can use a deterministic stub scorer instead.

Greedy packing with duplicate suppression

Input: 12 reranked chunks for 'Can annual plans get a refund after 30 days?'. Step 1: walk down the list. Step 2: skip chunks below the threshold of 0.2 (a value chosen from your labelled set). Step 3: skip a chunk whose word overlap with a kept one is above 0.8; here the v2 copy of the exceptions section is skipped. Step 4: add each kept chunk until 2,000 tokens. Expected evidence: 5 chunks kept, 1 below threshold, 1 duplicate, and a log line for each skip.

python
def jaccard(a: str, b: str) -> float:
    x, y = set(a.lower().split()), set(b.lower().split())
    return len(x & y) / max(len(x | y), 1)

def pack(ranked: list[dict], budget=2000, threshold=0.2, dup=0.8) -> list[dict]:
    kept, used = [], 0
    for c in ranked:
        if c["rerank_score"] < threshold:
            log.info("below threshold %s", c["chunk_id"]); continue
        if any(jaccard(c["text"], k["text"]) > dup for k in kept):
            log.info("duplicate %s", c["chunk_id"]); continue
        if used + c["tokens"] > budget:
            break
        kept.append(c); used += c["tokens"]
    return kept

Measuring whether reranking pays off

Step 1: run your 20 labelled questions through hybrid search only and record hit@3 and the 95th percentile latency. Step 2: add the reranker on the top 30 and record the same. Step 3: try the top 10. Expected evidence, for example: hybrid only hit@3 14/20 at 40 ms; rerank top 30 hit@3 17/20 at 400 ms; rerank top 10 hit@3 16/20 at 150 ms. Pick the option that meets your success criteria from the baseline module; these numbers are illustrative.

Quick reference

  • Rerank a short list: typically 20 to 50 candidates
  • Cross-encoder = one model pass per (question, chunk) pair
  • Reranker scores are not probabilities; ranges differ by model
  • Pick thresholds from labelled data; store value, model and date
  • Dedupe: one chunk per section, then skip near-copies of kept chunks
  • Budget evidence explicitly and leave room for the answer
  • Time every retrieval stage separately

Common mistakes

  • Treating the reranker score as a probability that the answer is correct.
  • Copying a threshold from a blog post; scores differ between models and corpora.
  • Packing evidence until the window is completely full, leaving no space for the answer.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why not use a cross-encoder for first-stage search over the whole corpus?

Question 2

2Two chunks are the same paragraph from versions 2 and 3 of a policy. What should usually happen?

Question 3

3A chunk has a reranker score of 0.97. What can you conclude?

Question 4

4How should you choose a score threshold?

Question 5

5Your model allows 8,000 tokens. Instructions take 600 and you want 700 for the answer. What is the most evidence you can pack, ignoring the question?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a stub reranker that scores a chunk by the share of question words it contains, and use it to reorder 10 hybrid results.

  2. Exercise 2medium

    Collect reranker scores for all candidates of your labelled questions, split them into relevant and irrelevant, and pick a threshold that keeps at least 95 percent of relevant chunks.

  3. Exercise 3hard

    Build the full select_evidence(question, scopes) function: hybrid top 30, rerank, dedupe, threshold, pack to 2,000 tokens, and return chunk IDs plus timing for each stage.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I always need a reranker?
No. If hybrid search already meets your success criteria, a reranker only adds latency and cost. Add it when evaluation shows ranking errors.
How many chunks should go into the prompt?
As many as fit the evidence budget after deduplication and thresholds, often 3 to 8. More is not better if the extra chunks are weak.
Is a bigger context window a replacement for ranking?
Not really. Models can miss evidence buried among irrelevant text, and every extra token costs time and money.

Go deeper

ShareXLinkedInWhatsApp