Chapter 24 of 40 · ~20 min read & lab+80 XP
Chapter 24 · Generative AI

Two-Stage RAG Reranking: Cross-Encoders & MMR Diversity Selection

How Two-Stage Retrieval (Hybrid Top-50 → Cross-Encoder Top-5) dramatically boosts precision, how Maximal Marginal Relevance (MMR) prunes redundant near-duplicate chunks, and fixing Lost-in-the-Middle context ordering.

What Is It?

Two-Stage RAG retrieves 50 fast candidates first, then re-scores them with an accurate Cross-Encoder Reranker and deduplicates near-identical chunks via MMR (Maximal Marginal Relevance).

Why Is It Required?

Fast bi-encoder retrieval often ranks a slightly off-topic chunk #1 or returns 5 near-duplicate paragraphs; reranking + MMR puts the sharpest, most diverse evidence in the prompt.

Everyday Analogy: Skimming 50 resumes quickly (bi-encoder), then carefully interviewing the top 10 finalists (cross-encoder) while picking complementary skill sets (MMR).
Why ML Engineers & Data Scientists Actually Need This

Adding a 40 ms Cross-Encoder Reranker + MMR Diversity filter is often the single biggest accuracy jump in RAG — frequently lifting answer accuracy by +10% to +20%!

ML / AI Engineer

Reranking lets you pass 5 sharp, non-redundant chunks instead of 20 noisy chunks — cutting LLM input token costs by 4× while improving answer faithfulness!

Data Scientist

Without MMR, overlapping chunks from the same paragraph crowd out all 5 slots of your Top-5 context window, leaving multi-part user questions half-answered.

Interview & Debug Edge

Classic RAG architecture question: 'Why can't we use a Cross-Encoder for Stage-1 search over 10M docs, and how does MMR prevent redundant chunks?'

Step 0 · Test Your Gut Before Any Math!

In the MMR formula score(d) = λ · sim(d, Q) − (1 − λ) · max_{s ∈ S} sim(d, s), what happens when you set λ = 1.0?

What You Will Master in This Chapter
  • Design the 2-stage production RAG funnel: high-recall Hybrid retrieval (Top-50) → high-precision Cross-Encoder reranking (Top-5)
  • Implement Maximal Marginal Relevance (MMR) greedy selection: argmax [λ·sim(d, Q) − (1−λ)·max sim(d, S)]
  • Tune MMR's λ parameter from pure relevance (λ=1) to balanced diversity (λ≈0.5–0.7)
  • Apply LongContextReorder to mitigate the LLM Lost-in-the-Middle U-shaped attention curve
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Cross-Encoder([Q;D])\text{Cross-Encoder}([Q; D])Say aloud:“joint query-doc reranker”
Plain-English Meaning
Full bidirectional Transformer attending across every query word and doc word jointly
Everyday Example
BGE-Reranker, Cohere Rerank, Jina Reranker
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of hiring for a 5-person team: Stage 1 (Hybrid Search) scans 10,000 resumes in seconds to pick the Top-50 finalists. Stage 2 (Cross-Encoder) conducts deep 1-on-1 interviews with those 50 finalists. Finally, MMR ensures you don't hire 5 identical frontend engineers — you hire 1 frontend, 1 backend, 1 ML, 1 infra, and 1 designer!

1. Two-Stage Retrieval Funnel: Bi-Encoder + Cross-Encoder

Everyday Story First (Zero Math Yet!)

By running the expensive Cross-Encoder only on the Top-50 candidates from Stage 1, you get full cross-attention accuracy in just ~40 milliseconds!

Two-Stage Production RAG Funnel: High Recall → High PrecisionCorpus10,000,000chunksStage 1: HybridTop 50~12 ms (fast)Stage 2: Cross-EncTop 10~40 ms (deep)MMR → LLMTop 5diverse gold!
Production RAG uses a 2-stage funnel: fast Bi-Encoder + BM25 retrieves Top-50 in ~10 ms, then an accurate Cross-Encoder reranks Top-50 → Top-5 in ~40 ms!

Why Cross-Encoders Beat Bi-Encoders on Subtle Queries

A Bi-Encoder compresses a 400-word chunk into 1 vector before ever seeing the query. A Cross-Encoder reads [CLS] Q [SEP] D together, catching subtle negations, exact date constraints, and multi-hop keyword matches that single-vector dot products miss!

2. Maximal Marginal Relevance (MMR): Eliminating Redundant Clones

Everyday Story First (Zero Math Yet!)

Drag the λ slider in the mini-lab below to see the exact point where Doc C (Diverse New Fact) overtakes Doc B (Near-Duplicate Clone) for Slot #2!

MMR Diversity Selection: argmax [ λ · sim(d, Q) − (1 − λ) · max sim(d, S) ]Pure Top-3 (Redundant Clones!)#1: "Paris is France's capital (2.1M pop)" (0.95)#2: "The capital of France is Paris (2.1M)" (0.94)#3: "France's capital city is Paris." (0.93)MMR Top-3 (λ = 0.6 · Rich Coverage!)#1: "Paris is France's capital (2.1M pop)"#2: "Top landmarks: Eiffel Tower & Louvre"#3: "Paris Metro has 16 lines & 308 stations"
Maximal Marginal Relevance (MMR = λ·Rel − (1−λ)·Redundancy) penalizes near-duplicate chunks so the LLM's Top-5 context window covers 5 distinct facts instead of 5 copies of the same paragraph!

Greedy MMR Algorithm (Top-K Diverse Selection)

  1. Pick #1: d1=arg⁡max⁡d∈Csim(d,Q)d_1 = \arg\max_{d \in C} \text{sim}(d, Q); initialize S={d1}S = \{d_1\}.
  2. Repeat until ∣S∣=K|S| = K: dnext=arg⁡max⁡d∈C∖S[λ⋅sim(d,Q)−(1−λ)⋅max⁡s∈Ssim(d,s)]d_{\text{next}} = \arg\max_{d \in C \setminus S} \Big[ \lambda \cdot \text{sim}(d, Q) - (1 - \lambda) \cdot \max_{s \in S} \text{sim}(d, s) \Big]
Animated Mini-Lab • 4.5

MMR λ Relevance-vs-Diversity Tuner (Pick Slot #2)

Doc B (rel=0.92, dup=0.95)
MMR = -0.015
Doc C (rel=0.80, dup=0.20)
MMR = 0.300
Winner for Slot #2: Doc C (Diverse New Fact!)

3. Beating 'Lost in the Middle' When Packing the LLM Prompt

Everyday Story First (Zero Math Yet!)

Once you have your diverse Top-5 gold chunks, don't just dump them in descending order — respect the LLM's U-shaped attention curve!

Lost-in-the-Middle U-Curve: Context Placement Order Matters!Start (#1 Best)Middle (Lowest Attention!)End (#2 Best)LongContextReorder trick: place top-ranked chunks at the edges [ #1, #3, #5, #4, #2 ]!
LLMs exhibit a U-shaped attention curve ('Lost in the Middle'): placing the highest-ranked chunks at the VERY START and VERY END of the retrieved block maximizes answer accuracy!

Edge-Heavy Context Packing

Research (Liu et al., 2023) proved LLMs pay strongest attention to tokens at the very beginning and very end of the retrieved context block, and weakest attention to the middle. Ordering Top-5 chunks as [#1, #3, #5, #4, #2] places your two strongest pieces of evidence right at the two attention peaks!

Walk Through With Me · Interactive Worked Example

Worked Example: One Step of MMR Selection (λ = 0.6)

Slot #1 already chose D1. Remaining candidates: D2 (rel=0.90, sim_to_D1=0.95) and D3 (rel=0.82, sim_to_D1=0.25).

11. Score D2 (near-clone of D1)Step 1 / 2

0.6(0.90)−0.4(0.95)=0.54−0.38=0.160.6(0.90) - 0.4(0.95) = 0.54 - 0.38 = \mathbf{0.16}.

Teacher's Note: Heavy redundancy penalty crushes the duplicate!
Pause & Check · Quick Intuition Pulse

In the Lost-in-the-Middle phenomenon, where in the retrieved context block do LLMs exhibit the LOWEST recall accuracy?

Try It YourselfStandard

Why should MMR run on the small Top-50 candidate pool (not the 10-million-doc corpus)?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

ColBERT stores per-token document embeddings offline and computes fast MaxSim sum of maximum token similarities at query time — approaching Cross-Encoder accuracy at near Bi-Encoder speed!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Two-Stage Rerank + MMR Funnel promote a buried gold chunk from #4 to #1 and prune the duplicate clone.
Interactive Animation • 4.5 Deep Lab

Two-Stage Cross-Encoder Rerank + MMR Diversity Funnel

Watch a buried gold chunk jump from #4 to #1 under Cross-Encoder attention, then watch MMR prune near-duplicates.

1. Fast Bi-Encoder (Top-50)
#1 · Doc A (0.89)
#2 · Doc A-dup (0.88)
#3 · Doc B (0.82)
#4 · Doc C-gold (0.76)
0%
1. Fast Bi-Encoder (Top-50)
Intuition Takeaway: Two-stage RAG pairs fast Hybrid retrieval (Top-50) with deep Cross-Encoder reranking, prunes near-duplicates via MMR (λ⋅Rel−(1−λ)⋅Redundancy\lambda \cdot \text{Rel} - (1-\lambda) \cdot \text{Redundancy}), and places top chunks at the prompt edges.
Where This Powers Real ML, Deep Learning & Generative AI

Multi-Facet Research & Legal RAG

Cross-Encoder + MMR ensures multi-part questions receive diverse citations across different sections and documents.

Production NumPy & PyTorch Code Patterns
import torch
import torch.nn.functional as F

# Maximal Marginal Relevance (MMR): Balance Query Relevance vs. Result Diversity
def mmr_select(query_emb: torch.Tensor, doc_embs: torch.Tensor, k: int = 3, lam: float = 0.7) -> list[int]:
    q = F.normalize(query_emb, dim=-1)
    D = F.normalize(doc_embs, dim=-1)
    rel = (D @ q).tolist()
    sim_mat = (D @ D.T).tolist()
    selected, remaining = [], list(range(len(D)))
    for _ in range(min(k, len(D))):
        best_i = max(
            remaining,
            key=lambda i: lam * rel[i] - (1 - lam) * (max(sim_mat[i][j] for j in selected) if selected else 0.0),
        )
        selected.append(best_i)
        remaining.remove(best_i)
    return selected

torch.manual_seed(0)
q = torch.randn(16)
docs = torch.stack([q + 0.01*torch.randn(16), q + 0.01*torch.randn(16), q + 0.5*torch.randn(16), torch.randn(16)])
print("MMR diverse top-3 indices (avoids near-duplicate #1):", mmr_select(q, docs, k=3, lam=0.6))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Applying MMR before Cross-Encoder reranking instead of after (or using raw unnormalized scores inside MMR).
Best Practice: Run Stage-1 Hybrid (Top-50) → Stage-2 Cross-Encoder Rerank → MMR Diversity Selection (Top-5) using normalized [0, 1] relevance and cosine doc-doc similarity!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1In MMR (λ·sim(d, Q) − (1−λ)·max sim(d, S)), lowering λ from 0.8 down to 0.3 has what effect?

Apply What You Learned — Solve Matching Coding Problems