Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

14.3 Advanced Retrieval & Reranking

An exact error code and a description of its symptoms require different retrieval signals. A dense retriever may match the concept while missing an identifier; a lexical retriever may find the identifier while missing a synonym. Hybrid retrieval combines their candidate sets, and reranking spends more computation on the candidates most likely to matter. Neither stage can manufacture evidence absent from the corpus.

1. Learned Sparse Retrieval

BM25 scores lexical matches with term-frequency saturation and document-length normalization. An exact identifier can be useful, but a query containing only “automobile” can miss a document containing only “car” unless preprocessing or expansion bridges the terms.

SPLADE learns vocabulary-weighted sparse representations using a masked-language-model head, nonnegative log-saturated weights, pooling, and sparsity regularization [1]. Expansion can assign weight to a term absent from the original passage. The actual sparsity and retrieval cost depend on the trained checkpoint and indexing policy; there is no universal “95% zero” guarantee. Audit postings volume, query expansion, latency, and relevance together.

2. Reciprocal Rank Fusion

A support engineer searches for “404 error on legacy system X.” BM25 puts the manual with the exact product name first. The dense retriever prefers a guide about missing pages. Both put the same incident log second. Which document should the engineer open first?

BM25 scores and embedding similarities use different scales. Reciprocal rank fusion (RRF) adds up contributions based on rank, which both retrievers supply [2]. With a cutoff on each result list, let MdM_d be the lists that retained document dd and rm(d)r_m(d) its one-based rank in list mm. The fused score is

RRF(d)=∑m∈Md1k+rm(d).\mathrm{RRF}(d)=\sum_{m\in M_d}\frac{1}{k+r_m(d)}.

The score from a list that missed dd is zero. The original authors chose the smoothing constant k=60k=60 in a pilot and kept it fixed in their experiments. Their rule gives every list equal weight. The optional dense weight in the example multiplies only the dense term, so you can try giving one retriever twice the influence.

Which document wins for “404 error on legacy system X”?

Each retriever returns its own ordering. Crossed-out documents fall below the selected cutoff.

Dense
  1. 1. B
  2. 2. C
  3. 3. D
  4. 4. A
BM25
  1. 1. A
  2. 2. C
  3. 3. E
  4. 4. B

8 hits give 5 distinct documents. First place: C.

  • #1
    C · System X 404 log
    Dense 1/(60+2)+ BM25 1/(60+2)
    Total 0.032258
  • #2
    A · System X manual
    Dense 1/(60+4)+ BM25 1/(60+1)
    Total 0.032018
  • #2
    B · 404 error guide
    Dense 1/(60+1)+ BM25 1/(60+4)
    Total 0.032018
  • #4
    D · Broken link troubleshooting
    Dense 1/(60+3)+ BM25 0 (absent)
    Total 0.015873
  • #4
    E · System X release notes
    Dense 0 (absent)+ BM25 1/(60+3)
    Total 0.015873

Constructed example. BM25 has weight 1. Equal scores share a rank and are displayed in document ID order.

Try the cutoff first. Keep one hit per retriever. Only the manual A and the guide B reach fusion. The incident log C could answer the question perfectly and still be unavailable. Keep two hits instead. The log now gets one contribution from each retriever, and its single fused entry scores 2/622/62 at k=60k=60. Keeping four hits gives you five distinct documents from eight entries. Document D appears only in the dense list, in third place, so its score is 1/63+01/63+0.

Then try the smoothing constant. Keep all four hits and equal weights. A and B each score 1/(k+1)+1/(k+4)1/(k+1)+1/(k+4), while C scores 2/(k+2)2/(k+2). At k=0k=0, A and B win. At k=2k=2, all three tie at 0.50.5. Above 2, C wins. Return to k=60k=60 and double the dense weight. B just overtakes C because its dense hit is first, with 2/61+1/64>3/622/61+1/64>3/62.

The Python example takes ordered document IDs as input. Each retriever contributes at most once per ID. If the same ID occurs twice in one input, this implementation keeps its first occurrence and applies the cutoff to the distinct IDs. Use the same passage ID in both indexes so that the same passage can collect both contributions.

def fuse(dense, bm25, depth=4, k=60, dense_weight=1):
    scores = {}
    for hits, weight in [(dense, dense_weight), (bm25, 1)]:
        unique_ids = list(dict.fromkeys(hits))[:depth]
        for rank, doc_id in enumerate(unique_ids, start=1):
            scores[doc_id] = scores.get(doc_id, 0) + weight / (k + rank)
    return sorted(scores.items(), key=lambda pair: (-pair[1], pair[0]))


dense = ["B", "C", "D", "A"]
bm25 = ["A", "C", "E", "B"]
assert fuse(dense, bm25)[0] == ("C", 2 / 62)
assert [doc for doc, _ in fuse(dense, bm25, depth=1)] == ["A", "B"]
assert fuse(dense, bm25, dense_weight=2)[0][0] == "B"

At the second BM25 hit, C already has a score of 0.016129 from the dense list. What will one more second-place hit add? Open the Python Tutor trace at that update and select Next. C’s running score becomes 0.0322581, just ahead of A’s 0.0320184.

These fixed lists show how fusion changes the answer order. To measure whether the new first result actually helps, judge passages for held-out support queries and compare BM25, dense search, and fusion on those same queries. Record recall at the candidate cutoff separately from relevance at the displayed rank. No choice of kk can recover a log that both retrievers missed.

3. Query Transformation Without Losing the Question

HyDE generates a hypothetical relevant document, embeds it, and retrieves real documents near that representation [5]. The hypothetical text is a search aid, not a factual source. Query expansion can improve recall but can also drift toward an invented entity or interpretation.

Retain the original query and exact identifiers alongside expansions. Log transformation versions, compare against an unexpanded baseline, and measure whether useful evidence survives the final context budget. Evaluate recall at candidate depth and downstream answer quality separately: more retrieved text can increase cost or introduce distractors.

4. Spend Joint Attention on a Candidate Pool

A bi-encoder can precompute document vectors. A cross-encoder jointly processes the query and each candidate, allowing token-level interaction before producing a relevance score. Across NN candidates it needs roughly NN pair evaluations, each with its own sequence-length and architecture cost. This is distinct from saying that its complete computation is merely O(N)O(N).

Choose the candidate pool by a measured recall/latency trade-off, not a fixed “top 100” rule. First-stage misses are unavailable to the reranker. Account for batching, truncation, document length, language, and query-domain shift. A high reranking score is neither proof of truth nor permission to expose a document.

5. Late Interaction and MaxSim

ColBERT independently encodes queries and documents but preserves multiple token vectors, then computes a fine-grained interaction [3]:

S(q,d)=∑i∈Iqmax⁡j∈Id⟨Eqi,Edj⟩.S(q,d)=\sum_{i\in I_q}\max_{j\in I_d}\langle E_{q_i},E_{d_j}\rangle.

IqI_q and IdI_d are the valid query/document token positions and EE the token representations. With normalized vectors, the dot product is cosine similarity. Taking the best document match per query token preserves local evidence that a single pooled vector can lose.

Mask document padding before taking the maximum: a zero padding vector can otherwise beat every negative real-token similarity. Mask query padding after the maximum; reject an empty document explicitly. Define special-token filtering and query augmentation consistently with the selected checkpoint. A dense batched implementation materializing [B,Q,D][B,Q,D] similarities needs approximately BQDsB Q D s bytes just for that tensor, where ss is bytes per value; it is not a production memory estimate for the full pipeline. Chunking and index-specific kernels change the trade-off.

ColBERT can support indexed retrieval as well as reranking; it is not restricted to a second stage. Multi-vector storage and index construction must be included in its cost comparison.

6. Generative and Decision-based Reranking

RankGPT studies prompted LLM reranking, including listwise identifier permutations [4]. A listwise system may use sliding windows rather than fitting the entire corpus into one prompt. Pointwise, pairwise, and listwise methods trade query budget, context, calibration, and ordering sensitivity; none universally replaces cross-encoders.

Validate identifier membership, duplicates, omissions, truncation, and output order. Treat passage text as untrusted data and test instruction injection inside passages. Randomize candidate order for evaluation and report variation. Typed relevance judgments offer another bounded interface; Section 16.7 explains why typed outputs still require semantic and calibration checks.

7. A Release Gate for Retrieval Changes

Compare lexical-only, dense-only, fused, and reranked systems on the same frozen queries and corpus version. Report recall@K, nDCG@K or MRR where appropriate, paired uncertainty, language/domain slices, and downstream citation-supported answer quality. Measure index build/storage, p95 latency, token cost, and empty-result/error rates.

Apply tenant/ACL filters before evidence reaches the model, preserving authorization through caches and reranking. Pin corpus lineage, deletion tombstones, embedding/tokenizer versions, index parameters, fusion policy, reranker, and prompt as an artifact bundle. Keep a known-good index route and test rollback without resurrecting deleted content.

For a case where rank leaves the answer ambiguous, follow the tied CEO and vendor in the §14.5 graph example. Which edge and source passage identify the CEO?

Quizzes

Quiz 1: Why can a document absent from one list still win RRF? It receives no contribution from the missing list but can accumulate enough rank contribution elsewhere. Candidate depth, k, and competing documents determine the result.

Quiz 2: Why must document padding be masked before MaxSim? A zero padded vector can beat negative similarities from real tokens. Query masking alone does not prevent that document-side error.

Quiz 3: Does listwise reranking establish that a passage is true? No. It estimates ordering under a prompt and candidate set. Validate source support, identifiers, access permissions, and injection resistance independently.

Quiz 4: Why measure downstream quality as well as recall? More candidates can add cost, distractors, or context truncation. A retrieval gain need not survive the reranker and generator.

Quiz 5: With four hits per list and equal weights, who leads at k = 2? A, B, and C share first place with 0.5. D and E each appear once in third place and receive 1/5. The ID determines the display order within each tie.

References

  1. Formal, T., et al. (2021). SPLADE v2: Sparse Lexical and Expansion Model for Information Retrieval. Paper.
  2. Cormack, G. V., Clarke, C. L. A., & Büttcher, S. (2009). Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods. SIGIR paper.
  3. Khattab, O., & Zaharia, M. (2020). ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT. Paper.
  4. Sun, W., et al. (2023). Is ChatGPT Good at Search? Investigating Large Language Models as Re-Ranking Agents. Paper.
  5. Gao, L., et al. (2022). Precise Zero-Shot Dense Retrieval without Relevance Labels. Paper.