Skip to content
LLM application engineering Advanced 32 min read

Advanced RAG: hybrid search, reranking, graphs

Basic RAG embeds chunks and takes the nearest few. Advanced RAG treats retrieval as what it always was, a ranking problem from information retrieval: cast a wide net with several complementary retrievers, fuse their rankings, spend expensive compute re-scoring only the survivors, and build indexes (contextual chunks, summaries, graphs) that make the right evidence findable at all. The one idea: recall first, precision second, and measure each separately.

10,000 ft

Retrieval-augmented generation (RAG) gives a model evidence it was never trained on. Its quality is capped by retrieval: a model cannot cite a passage it never saw. The first wave of RAG systems (2023) used one dense retriever over fixed-size chunks and discovered its blind spots quickly: exact identifiers, rare names, numbers, questions about a whole corpus, and answers spread over several documents. The fixes came mostly from the older field of information retrieval: lexical scoring (BM25), rank fusion, learned rerankers, query expansion, and evaluation by recall and nDCG. Newer ideas added LLMs at every stage: writing hypothetical documents, contextualising chunks, reranking listwise, and building knowledge graphs and summary trees. The same machinery powers search inside agents, long-term memory and the "deep research" products of 2025–2026. It sits on top of embeddings and vector search and is judged with the methods of evals in practice.

2,000 ft

Production retrieval is a funnel. Cheap, high-recall retrievers pull a few hundred candidates; a fusion step merges their rankings; an expensive, high-precision reranker orders the survivors; a context assembler picks, de-duplicates and orders the final handful for the generator. Offline, the indexes are built to be findable: chunks carry their document's context, and summary or graph indexes answer questions no single chunk can.

Advanced RAG: widen the net, then narrow it
Advanced RAG: widen the net, then narrow it. User question, Query transform rewrite · expand · decompose, Lexical retriever BM25 / SPLADE, Dense retriever ANN over embeddings, Graph / summary index entities · communities, Fusion RRF over ranked lists, Reranker cross-encoder or LLM, Context assembly dedupe · order · budget, Generator answer with citations, top 100–200, top 50–150, top 5–20Advanced RAG: widen the net, then narrow it. User question, Query transform rewrite · expand · decompose, Lexical retriever BM25 / SPLADE, Dense retriever ANN over embeddings, Graph / summary index entities · communities, Fusion RRF over ranked lists, Reranker cross-encoder or LLM, Context assembly dedupe · order · budget, Generator answer with citations, top 100–200, top 50–150, top 5–20

  1. Diagnose: label a few hundred questions with their relevant passages and measure retrieval recall separately from answer quality.
  2. Widen: run lexical and dense retrieval in parallel; they fail on different queries.
  3. Fuse by rank, not by score (reciprocal rank fusion).
  4. Rerank the top 50–150 with a model that reads query and passage together.
  5. Fix the index when the evidence is unfindable: contextual chunks, parent documents, summary trees, graphs.
  6. Assemble a short, ordered, de-duplicated context; more is not better.

Ground level

Start with a diagnosis, not a technique

Every technique on this page costs latency, money or complexity, and each fixes one failure. So the first job is to find out which failure you have. A RAG answer can be wrong for three separable reasons:

Failure Symptom Measured by Typical fix
Not retrieved The right passage is not in the top \(k\) candidates recall@\(k\) on labelled queries Hybrid search, query expansion, better chunking, contextual chunks
Retrieved but buried It is in the top 100 but not the top 5 that reach the model nDCG@10, MRR Reranking
Retrieved but not used It reached the model, which ignored or misread it Faithfulness and answer correctness Context assembly, prompt, a stronger generator
Not answerable by any chunk The answer needs the whole corpus or many hops Per-question-type accuracy Summary trees, GraphRAG, iterative retrieval

The instrument is a retrieval eval set: a few hundred real questions, each labelled with the passages that answer it. Build it before you build anything else on this page. You can bootstrap labels by having an LLM generate questions from passages, but real user questions from logs are better, because synthetic questions copy the passage's wording and make lexical retrieval look better than it is. Then report recall@\(k\) for the candidate stage (does the evidence get into the funnel?) and nDCG@\(k\) for the final ordering (does it reach the top?). Jason Liu's "systematically improving RAG" series (Go deeper) is the clearest practical guide to this loop.

Tuning the generator to fix a retrieval problem

If recall@50 is 70%, then for 30% of questions the answer is not in anything the model can see. No prompt, model upgrade or reranker fixes that; a reranker can only reorder what it is given. Always read the retrieval metrics first.

Lexical retrieval: BM25 is still a baseline you must beat

Dense embeddings compress a passage into one vector of meaning. That is wonderful for paraphrase and terrible for exact tokens: product codes, error numbers, function names, legal clause numbers, people's names, rare jargon. An embedding model has no reason to keep E1042 far from E1043; to it they are both "an error code". A lexical retriever matches the literal string.

BM25 (Robertson and colleagues, refined through the 1990s) scores a document \(d\) for a query \(q\) by summing, over query terms, an inverse-document-frequency weight times a saturating function of the term's frequency in the document:

\[ \operatorname{BM25}(q, d) = \sum_{t \in q} \operatorname{IDF}(t)\cdot \frac{f_{t,d}\,(k_1 + 1)}{f_{t,d} + k_1\left(1 - b + b\,\frac{|d|}{\operatorname{avgdl}}\right)}, \qquad \operatorname{IDF}(t) = \ln\!\left(1 + \frac{N - n_t + 0.5}{n_t + 0.5}\right). \]

Here \(f_{t,d}\) is how often term \(t\) occurs in \(d\), \(|d|\) the document length, avgdl the mean length, \(N\) the number of documents and \(n_t\) the number containing \(t\). The defaults \(k_1 \approx 1.2\) and \(b = 0.75\) are good starting points. Three ideas are packed in:

  • Rarity is information. A term in 1 of 10 documents gets IDF \(\ln(1 + 9.5/1.5) = 1.99\); a term in 2 of 10 gets \(1.48\). "the" in every document gets almost nothing.
  • Saturation. With \(k_1 = 1.2\), the term-frequency factor is 1.00 for one occurrence, 1.375 for two, 1.571 for three and 1.964 for ten. The tenth mention adds little: repetition is weak evidence once you know the term is there.
  • Length normalisation. A match in a short document counts for more. At \(b = 0.75\), one occurrence in a document half the average length scores about 1.23 times one in an average-length document; in a document 1.8 times average, about 0.76 times.

Worked example. In the ten-document toy corpus of the Build-it section (average length 6.2 terms after stop-word removal), the query "E1042 payment retry" scores the document "Error E1042 means the payment gateway timed out" (7 terms) as \(1.992 \times 0.950 + 1.482 \times 0.950 = 3.30\). "The gateway retries a timed out payment three times" scores only \(1.41\): it matches "payment" but not "retry", because without stemming "retry" and "retries" are different strings. Real engines (Lucene, Elasticsearch, OpenSearch, Tantivy) stem and normalise; check what your analyser does before you blame BM25.

BM25 is not a relic. The BEIR benchmark (Thakur et al., 2021) tested retrievers zero-shot on 18 datasets and found BM25 "a robust baseline", with dense retrievers often underperforming it out of domain, and reranking and late-interaction models best on average at higher cost. Dense models have improved a great deal since (track them on the MTEB leaderboard), but the complementarity remains: lexical and dense retrievers make different mistakes.

Learned sparse retrieval sits in between. SPLADE (Formal et al., 2021) uses a masked language model to produce a sparse vector over the vocabulary for each passage, with learned term weights and expansion terms ("refund" can light up "reimbursement"), and serves it from an ordinary inverted index. It keeps exact matching and adds some paraphrase.

Why dense retrieval has a ceiling

Dense retrieval scores with a dot product between independently computed vectors, \(s(q, d) = \mathbf{e}_q^\top \mathbf{e}_d\). Two structural limits follow. First, the passage is compressed before the query is known, so whatever the encoder dropped is gone. Second, the dot product of \(d\)-dimensional vectors can only realise so many distinct top-\(k\) sets. Weller et al. (2025) made this precise: the number of top-\(k\) subsets of documents that any query can return is bounded by the embedding dimension, and even embeddings optimised directly on the test set fail their deliberately simple LIMIT dataset once the combinations outgrow the dimension. In practice that means queries combining several constraints ("papers by X about Y after 2020") are where single-vector retrieval breaks first, and where lexical filters, metadata and reranking earn their keep.

Hybrid search and rank fusion

Run both retrievers and combine. The obvious combination, adding the scores, fails because the scales are unrelated: BM25 scores are unbounded and depend on query length and IDF; cosine similarities live in a narrow band such as 0.6–0.9 that differs by embedding model. You can normalise (min–max or z-score per query) and take a weighted sum \(\alpha \tilde{s}_\text{dense} + (1 - \alpha)\tilde{s}_\text{bm25}\), tuning \(\alpha\) on your eval set. That works, but the normalisation is fragile: one outlier score stretches the min–max range for a whole query.

Reciprocal rank fusion (Cormack, Clarke and Büttcher, 2009) throws the scores away and uses only ranks:

\[ \operatorname{RRF}(d) = \sum_{r \in \text{rankers}} \frac{1}{k + \operatorname{rank}_r(d)}, \qquad k = 60 . \]

A document missing from a ranker's list contributes nothing from it. The constant \(k\) was "fixed during a pilot investigation" in the original paper and found near-optimal; it is still a common library default (Elasticsearch's rrf retriever, for example, defaults its rank_constant to 60).

Worked example. Document A is first for BM25 and fifth for dense: \(1/61 + 1/65 = 0.03178\). Document B is second for both: \(2/62 = 0.03226\). B wins. Document C is first for BM25 and absent from the dense list: \(1/61 = 0.01639\), about half of either. RRF rewards agreement between rankers more than a single strong vote, which is what you want when each ranker has blind spots.

k = 60: rank 50 keeps 55%k = 10: 18%k = 1: 4%1rank in one list501.00weight vs rank 1
How much a document gains from one ranker, relative to being ranked first, as its rank falls. Small k makes fusion winner-take-all; k = 60 keeps a long tail, so a document ranked well by several retrievers beats one ranked first by only one.

Hybrid search is worth it when your queries mix vocabularies: support logs with error codes, code search, legal and medical text, product catalogues. Anthropic's contextual-retrieval study (below) found adding BM25 to contextual embeddings cut the top-20 retrieval failure rate from 3.7% to 2.9% on their test sets. Measure on yours.

Reranking: spend compute where it counts

Retrieval must be fast over millions of passages, so it scores query and passage independently and precomputes passage vectors. A reranker gets to read them together, which is far more accurate and far too slow to run on the whole corpus, so it runs on the top 50–150 candidates only.

Three ways to score a query against a document
Three ways to score a query against a document. Bi-encoder (dense retrieval), encode(query) → q, encode(doc) → d precomputed offline, score = q · d, Late interaction (ColBERT), query token vectors, doc token vectors precomputed offline, score = Σ max sim, Cross-encoder (reranker), encode(query ⊕ doc) jointly, at query time, score = head(h_CLS)Three ways to score a query against a document. Bi-encoder (dense retrieval), encode(query) → q, encode(doc) → d precomputed offline, score = q · d, Late interaction (ColBERT), query token vectors, doc token vectors precomputed offline, score = Σ max sim, Cross-encoder (reranker), encode(query ⊕ doc) jointly, at query time, score = head(h_CLS)
  • Cross-encoders. Concatenate query and passage, run a transformer over the pair and read a relevance score from the output. Nogueira and Cho (2019) showed a BERT cross-encoder re-ranking BM25 candidates jumped to the top of the MS MARCO passage leaderboard. Every query token attends to every passage token, so the model can check that "after 2020" is satisfied, that the negation goes the right way, that the entity is the right one. The cost is one forward pass per (query, passage) pair, at query time.
  • Late interaction. ColBERT (Khattab and Zaharia, 2020) keeps one vector per token. The score is the sum over query tokens of the best-matching passage token: \(s(q, d) = \sum_i \max_j \mathbf{q}_i^\top \mathbf{d}_j\) ("MaxSim"). Passage token vectors are still precomputed, so it can retrieve, not just rerank, while keeping token-level matching. The price is storage: one vector per token rather than per passage. ColBERTv2 compresses residuals to reduce the footprint 6–10×.
  • LLM rerankers. Ask an instruction-tuned LLM to order passages. RankGPT (Sun et al., 2023) showed listwise prompting ("rank these 20 passages") was competitive with supervised rerankers, using a sliding window to rank more passages than fit in one prompt, and distilled the ability into a 440M-parameter model. LLM reranking is accurate and flexible (you can say what "relevant" means in words) and is the slowest and most expensive option.

What reranking costs. The compute-maths rule of thumb is 2 FLOPs per parameter per token for a forward pass. A 300M-parameter cross-encoder reading 100 pairs of 300 tokens needs \(2 \times 3\times10^8 \times 3\times10^4 = 1.8\times10^{13}\) FLOPs, a few tens of milliseconds on a modern GPU and seconds on a laptop CPU. Retrieval of the candidates, by contrast, is one query encoding plus an approximate nearest-neighbour lookup. The funnel exists because these differ by orders of magnitude.

In the contextual-retrieval study, adding a reranker (top 150 retrieved, reranked to 20) took the failure rate from 2.9% to 1.9%. Rerankers are usually the single highest-value addition to a working hybrid system.

Why reading together beats comparing summaries

A bi-encoder is two people each writing a one-line summary in separate rooms, then comparing summaries. A cross-encoder is one person reading both documents side by side. Late interaction is two people writing one note per word and then matching notes. The more interaction happens before compression, the more the score can depend on the specific question.

Query transformation

Users write short, ambiguous, conversational queries; passages are written in a different register. Several transformations bridge the gap, each usually one cheap LLM call:

  • Rewrite to standalone. "What about for her?" becomes "What is the refund window for annual plans bought by a spouse?" using the conversation. Essential in chat; without it the retriever sees "her".
  • Multi-query. Generate 3–5 paraphrases, retrieve for each, fuse with RRF. Cheap recall.
  • HyDE (Gao et al., 2022). Ask an LLM to write a hypothetical answer passage, embed that, and retrieve real passages near it. The fake passage is in the same register as the corpus, and "the encoder's dense bottleneck" filters out its invented details. Strong when you have no relevance labels; risky when the LLM's guess points confidently in the wrong direction.
  • Query2doc (Wang et al., 2023). The same idea for lexical retrieval: append a generated pseudo-document to the query so BM25 gets more matching terms.
  • Decomposition. Split "Compare the refund policies of plans A and B" into two retrievals. Multi-hop questions ("Which team does the CEO of the company that acquired X support?") need the answer of one hop to form the next query; that is iterative retrieval, a small agent loop.
  • Routing and filters. Classify the query and send it to the right index, or extract structured filters ("after 2020", "type = invoice") and apply them as metadata filters instead of hoping the embedding encodes them.

Fixing the index: chunks that carry their context

Many retrieval failures are made at indexing time. A chunk that says "Revenue grew 3% over the previous quarter" is useless out of its document: which company, which quarter? Three remedies:

  • Contextual retrieval (Anthropic, September 2024). Before embedding, have an LLM write 50–100 tokens situating each chunk in its document ("This chunk is from ACME's Q2 2023 SEC filing; the previous quarter's revenue was…"), prepend it, and index the result for both embeddings and BM25. Reported on their test sets, as 1 − recall@20: contextual embeddings cut the failure rate from 5.7% to 3.7% (35%); adding contextual BM25 to 2.9% (49%); adding reranking to 1.9% (67%). Prompt caching makes it cheap: the whole document is the cached prefix and each chunk is the varying suffix, about USD 1.02 per million document tokens in their estimate.
  • Late chunking (Günther et al., 2024). Run a long-context embedding model over the whole document first, then pool token embeddings per chunk, so every chunk vector was computed with the full document in view. No LLM calls; needs a long-context embedding model.
  • Small-to-big (parent-document) retrieval. Index small units (sentences, short chunks) for precise matching, but return their parent section to the generator for context.

Chunking itself deserves an experiment, not a default. Split on document structure (headings, sections, functions, table rows) before falling back to token counts, keep tables whole, include titles and section paths in each chunk, and test two or three chunk sizes against your eval set. Attach metadata (date, author, product, access level) and filter on it; access control in particular must be a filter, never a hope.

Summary trees and graphs: questions no chunk can answer

"What are the main themes across these 5,000 customer interviews?" has no answering chunk. Similarity search returns five vaguely thematic passages, and the model generalises from five. Two families of index answer global questions.

RAPTOR (Sarthi et al., 2024) builds a tree bottom-up: embed chunks, cluster them, have an LLM summarise each cluster, then embed, cluster and summarise the summaries, recursively. At query time it retrieves from all levels at once, so a broad question matches a high-level summary and a detailed one matches a leaf. Coupled with GPT-4 it improved the best reported accuracy on the QuALITY long-document benchmark by 20 points.

GraphRAG (Edge et al., Microsoft, 2024) builds an entity graph instead:

GraphRAG: index a corpus as a graph of communities
GraphRAG: index a corpus as a graph of communities. Source chunks, LLM extraction entities · relations · claims, Entity graph, Community detection Leiden, hierarchical, Community summaries written by an LLM, Global question 'main themes?', Map: partial answer per community, Reduce: final answer, relevant summariesGraphRAG: index a corpus as a graph of communities. Source chunks, LLM extraction entities · relations · claims, Entity graph, Community detection Leiden, hierarchical, Community summaries written by an LLM, Global question 'main themes?', Map: partial answer per community, Reduce: final answer, relevant summaries

An LLM reads every chunk and extracts entities and relationships; the graph is partitioned into a hierarchy of communities of densely connected entities (with the Leiden algorithm); an LLM writes a summary of each community. A global query is answered map-reduce style: each relevant community summary yields a partial answer, and the partials are summarised into the final one. A local query ("What did Priya say about pricing?") starts from matching entities and walks their neighbourhood. On "global sensemaking" questions over corpora around a million tokens, the paper reports substantially more comprehensive and diverse answers than vector RAG, judged by an LLM.

The costs are real. Indexing calls an LLM over the entire corpus, often several times, and must be redone (or incrementally patched) as documents change. Extraction errors become graph errors. Lighter variants trade some quality for cost: LightRAG (Guo et al., 2024) uses the graph mainly as a retrieval index with dual-level (entity and theme) keys; HippoRAG (Gutiérrez et al., 2024) runs Personalized PageRank from the query's entities over an LLM-built graph, reporting multi-hop QA gains of up to 20% and single-step retrieval 10–30× cheaper than iterative retrieval with comparable quality.

When a graph is worth it

Use GraphRAG-style indexes when questions are about the corpus as a whole (themes, trends, "who is connected to whom") or need multi-hop joins across documents, and the corpus changes slowly. For "find the passage that answers this", hybrid search plus a reranker is cheaper and usually better. If your data is already structured (tables, a database, an API), do not extract a graph from text about it: query the structure directly (text-to-SQL, or tools).

Adaptive retrieval: let the model decide when and what to retrieve

Fixed "retrieve top 5, then generate" wastes retrieval on questions that need none and under-retrieves on hard ones. Self-RAG (Asai et al., 2023) trains a model to emit reflection tokens deciding whether to retrieve, whether each passage is relevant and whether its own output is supported. Corrective RAG (Yan et al., 2024) adds a lightweight evaluator that grades retrieved documents and, when confidence is low, triggers web search and filters passages. In production today the same ideas mostly appear as an agent with a search tool: the model issues queries, reads results, and searches again until it is satisfied. That buys recall on hard questions at the cost of latency and predictability.

Assembling the context

The last step decides what the generator actually sees.

  • Order matters. Liu et al.'s "Lost in the Middle" (2023) found models use information at the start and end of a long context better than in the middle. Put the strongest evidence first (and, for long contexts, consider repeating the question at the end).
  • Fewer, better passages. Each irrelevant passage is a distractor that competes for attention; see context engineering for the evidence. Five well-ranked passages often beat twenty.
  • De-duplicate and diversify. Near-duplicate chunks waste budget. Maximal marginal relevance (Carbonell and Goldstein, 1998) picks each next passage by \(\lambda\,\text{sim}(q, d) - (1 - \lambda)\max_{d' \in S}\text{sim}(d, d')\), trading relevance against redundancy with what is already selected.
  • Cite. Give each passage an id and ask for citations by id; then you can check them in code, and users can verify.

Jarvis: when the right retriever is not a vector index

Finny's assistant answers questions about one member's financial plan, which is structured data with a fixed schema, not a pile of documents. So it does no similarity search over plan data at all. A routing call picks from about 40 named chunks of the plan (such as the FIRE age or the goals list) and one of 7 deterministic utilities; code fetches exactly those and computes the figures. Retrieval became classification over a closed menu, which is small enough to evaluate exhaustively and impossible to "half-match". For its future knowledge base (shared articles, not personal data), the design starts with long context plus prompt caching before adding a vector store. See the Jarvis case study.

First principles

Why rank, and why this order? The probability ranking principle (Robertson, 1977; see the BM25 review in Go deeper) says that if a system's only job is to present documents in an order, and relevance judgements are independent, ranking by decreasing probability of relevance \(P(\text{rel} \mid q, d)\) maximises expected precision at every cutoff. Every stage of the funnel is an estimator of that probability with a different cost and accuracy. BM25 itself falls out of a probabilistic model: assume term occurrences follow a mixture of "elite" (the document is about the term) and non-elite Poisson distributions, take the log-odds of relevance, and approximate. The saturating \(f(k_1+1)/(f + k_1\cdot\ldots)\) shape is a cheap approximation to that two-Poisson log-odds, and the IDF term is the Robertson–Spärck Jones weight with no relevance information.

Why a funnel? Let stage \(i\) score \(n_i\) candidates at cost \(c_i\) each. Total cost is \(\sum_i n_i c_i\), and you choose \(n_1 \gg n_2 \gg n_3\) so that the expensive \(c_i\) multiply small \(n_i\). Recall can only fall along the funnel: no later stage can recover a document an earlier stage dropped. So each stage's cutoff is set by the recall it preserves, measured on your eval set, and the last stages are where precision is bought.

Why fuse ranks, not scores? Scores from different systems are on incomparable scales and are often badly calibrated; ranks are scale-free. RRF is also robust: one ranker's wild score for one document cannot dominate, because a rank contributes at most \(1/(k+1)\). Its weakness is the mirror image: it ignores how much better rank 1 was than rank 2. Where you have calibrated probabilities (for example from rerankers trained with a cross-entropy loss), combining log-odds is principled; where you do not, RRF is the safe default.

Why does interaction beat independent encoding? A bi-encoder must choose one vector for a passage before seeing the question, so it must keep, in \(d\) numbers, everything any future question might ask. That is a compression with a hard information budget, and Weller et al.'s dimension bound shows it is not only a matter of training. A cross-encoder computes a function of the pair, \(g(q, d)\), with no bottleneck between them. Late interaction is the middle point: a bottleneck per token rather than per passage.

Why do graphs help global questions? A global question asks for an aggregate over the corpus. Top-\(k\) similarity retrieval estimates that aggregate from \(k\) samples chosen by similarity, which is a biased and tiny sample. Community summaries are a precomputed hierarchical aggregation: the LLM has already read every chunk once at indexing time, so the query reads summaries that each stand for many chunks. It is the same trade databases make with materialised views: pay at write time to answer aggregate queries cheaply.

The maths

Retrieval metrics. For one query with relevant set \(R\) and ranking \(d_1, d_2, \ldots\):

\[ \text{recall@}k = \frac{|\{d_1,\ldots,d_k\} \cap R|}{|R|}, \qquad \text{MRR} = \frac{1}{\operatorname{rank of first relevant}}, \qquad \text{nDCG@}k = \frac{\sum_{i=1}^{k} \frac{g_i}{\log_2(i+1)}}{\sum_{i=1}^{k} \frac{g_i^\ast}{\log_2(i+1)}} \]

where \(g_i\) is the graded relevance of \(d_i\) (1 or 0 in the binary case) and \(g^\ast\) the gains of the ideal ordering. Worked example: two relevant documents, ranking [relevant, irrelevant, relevant]. DCG \(= 1/\log_2 2 + 1/\log_2 4 = 1 + 0.5 = 1.5\); ideal DCG \(= 1 + 1/\log_2 3 = 1.631\); nDCG@3 \(= 0.920\). Recall@3 is 1 and MRR is 1. Report all three averaged over queries, with confidence intervals (see statistics for evals); a 200-query set cannot resolve a one-point difference.

Score normalisation for weighted fusion. Min–max per query: \(\tilde{s} = (s - \min s)/(\max s - \min s)\); z-score: \(\tilde{s} = (s - \mu)/\sigma\). Then \(s_\text{hybrid} = \alpha\,\tilde{s}_\text{dense} + (1 - \alpha)\,\tilde{s}_\text{lex}\). Note that min–max maps the top document of each list to 1 regardless of how good it is, which is exactly the calibration problem RRF sidesteps.

Late interaction. With query token embeddings \(Q \in \mathbb{R}^{m \times h}\) and passage token embeddings \(D \in \mathbb{R}^{n \times h}\) (rows L2-normalised),

\[ s(q, d) = \sum_{i=1}^{m} \max_{j \le n} \, (Q D^\top)_{ij}, \]

an \(m \times n\) similarity matrix, a row-wise max and a sum. Storage per passage is \(n \times h\) numbers instead of \(h\).

Derivation: why HyDE works in embedding space

Let the encoder \(f\) map text to the unit sphere, and suppose relevant passages for \(q\) cluster around a direction \(\boldsymbol{\mu}_q\). A query \(q\) is short and in a different register, so \(f(q)\) may sit far from \(\boldsymbol{\mu}_q\). HyDE samples \(N\) hypothetical passages \(\hat{d}_i \sim p_\text{LLM}(\cdot \mid q)\) and uses \(\mathbf{v} = \frac{1}{N+1}\big(f(q) + \sum_i f(\hat{d}_i)\big)\). If each \(f(\hat{d}_i)\) equals \(\boldsymbol{\mu}_q\) plus noise \(\boldsymbol{\epsilon}_i\) from invented details, averaging shrinks the noise like \(1/\sqrt{N}\) while keeping the shared relevant direction. The retrieval step then grounds the vector in real passages: invented details move \(\mathbf{v}\) only slightly, and nothing invented is ever shown to the user. The failure mode is a biased LLM: if \(\mathbb{E}[f(\hat{d})] \ne \boldsymbol{\mu}_q\) (the model is confidently wrong about the topic), averaging converges to the wrong place.

Build it

Lexical, dense and fused retrieval on a toy corpus built so that each retriever has a blind spot. The "dense" encoder is a stand-in that maps words to concepts, so synonyms meet but exact error codes blur, which is exactly the failure pattern of real embeddings on identifiers. NumPy only:

import numpy as np, re
docs = ["How to reset your password from the login screen",          # 0
        "Error E1042 means the payment gateway timed out",            # 1
        "Error E1043 means the card was declined by the bank",        # 2
        "Recover account access when you forget your credentials",    # 3
        "Refunds are issued to the original card within seven days", # 4
        "Money back requests take up to a week to reach you",         # 5
        "Two factor codes expire after thirty seconds",               # 6
        "The gateway retries a timed out payment three times",        # 7
        "Change the email address linked to your profile",            # 8
        "Card declined errors usually come from the issuing bank"]    # 9
queries = {"cannot remember my sign in": {0, 3}, "what does E1042 mean": {1},
           "how long does a refund take": {4, 5}, "E1042 payment retry": {1, 7}}
STOP = set("a the to of in my your you how does what when from by is are up".split())
tok = lambda s: [t for t in re.findall(r"[a-z0-9]+", s.lower()) if t not in STOP]
D = [tok(d) for d in docs]; N = len(D); avgdl = np.mean([len(d) for d in D])

def bm25(q, k1=1.2, b=0.75):
    s = np.zeros(N)
    for t in set(tok(q)):
        n = sum(t in d for d in D)
        if n == 0: continue
        idf = np.log(1 + (N - n + 0.5) / (n + 0.5))
        for i, d in enumerate(D):
            f = d.count(t)
            s[i] += idf * f * (k1 + 1) / (f + k1 * (1 - b + b * len(d) / avgdl))
    return s

# A toy "dense" encoder: words map to concepts, so synonyms meet but exact codes blur.
concept = {"password": 0, "credentials": 0, "login": 0, "access": 0, "account": 0,
           "forgot": 1, "forget": 1, "remember": 1, "sign": 0, "reset": 1, "recover": 1,
           "refund": 2, "refunds": 2, "money": 2, "back": 2,
           "long": 3, "week": 3, "days": 3, "seven": 3, "take": 3,
           "e1042": 4, "e1043": 4, "error": 4, "errors": 4,
           "payment": 5, "gateway": 5, "card": 5,
           "timed": 6, "retry": 6, "retries": 6, "declined": 7, "bank": 7}
rng = np.random.default_rng(0); noise = {}
def embed(text):
    v = np.zeros(8)
    for t in tok(text):
        if t in concept: v[concept[t]] += 1
        else: v += 0.05 * noise.setdefault(t, rng.normal(size=8))   # unknown words: small noise
    return v / np.linalg.norm(v)
E = np.array([embed(d) for d in docs])
dense = lambda q: E @ embed(q)

def rrf(*rankings, k=60):
    s = np.zeros(N)
    for r in rankings:                       # a ranking may be shorter than N
        s[r] += 1 / (k + np.arange(1, len(r) + 1))
    return s

def ndcg(rank, rel, k=3):
    dcg = sum(1 / np.log2(i + 2) for i, d in enumerate(rank[:k]) if d in rel)
    return dcg / sum(1 / np.log2(i + 2) for i in range(min(k, len(rel))))

for name in ["bm25", "dense", "rrf"]:
    rec, nd = [], []
    for q, rel in queries.items():
        sb = bm25(q); rb = np.argsort(-sb)[: (sb > 0).sum()]   # BM25 returns matches only
        rd = np.argsort(-dense(q))
        rank = {"bm25": rb, "dense": rd, "rrf": np.argsort(-rrf(rb, rd))}[name]
        rec.append(len(set(rank[:3].tolist()) & rel) / len(rel)); nd.append(ndcg(rank.tolist(), rel))
        print(f"{name:5} {q:28} top3={rank[:3].tolist()}  relevant={sorted(rel)}")
    print(f"{name:5} mean recall@3={np.mean(rec):.3f}  mean nDCG@3={np.mean(nd):.3f}\n")
bm25  cannot remember my sign in   top3=[]  relevant=[0, 3]
bm25  what does E1042 mean         top3=[1]  relevant=[1]
bm25  how long does a refund take  top3=[5]  relevant=[4, 5]
bm25  E1042 payment retry          top3=[1, 7]  relevant=[1, 7]
bm25  mean recall@3=0.625  mean nDCG@3=0.653

dense cannot remember my sign in   top3=[3, 0, 8]  relevant=[0, 3]
dense what does E1042 mean         top3=[2, 1, 8]  relevant=[1]
dense how long does a refund take  top3=[5, 4, 8]  relevant=[4, 5]
dense E1042 payment retry          top3=[1, 7, 2]  relevant=[1, 7]
dense mean recall@3=1.000  mean nDCG@3=0.908

rrf   cannot remember my sign in   top3=[3, 0, 8]  relevant=[0, 3]
rrf   what does E1042 mean         top3=[1, 2, 8]  relevant=[1]
rrf   how long does a refund take  top3=[5, 4, 8]  relevant=[4, 5]
rrf   E1042 payment retry          top3=[1, 7, 2]  relevant=[1, 7]
rrf   mean recall@3=1.000  mean nDCG@3=1.000

Read the failures. BM25 finds nothing for the paraphrase "cannot remember my sign in" (no shared words) and misses "refunds" for "refund" (no stemming). The dense stand-in gets every relevant passage into the top 3 but ranks E1043 above E1042, because it cannot tell error codes apart. Fusion keeps dense's recall and BM25's exact-match precision. This corpus was built to show the mechanism; the size of the gain on your data is an empirical question your eval set answers.

Things to try

  • Add a crude stemmer (strip a trailing "s" and "ies" → "y") to tok and watch BM25's refund and retry misses disappear.
  • Replace RRF with min–max-normalised weighted fusion and sweep \(\alpha\) from 0 to 1. Is there an \(\alpha\) that matches RRF on all four queries? How sensitive is it?
  • Swap the concept encoder for a real embedding model (for example from sentence-transformers) and a real cross-encoder reranker over the fused top 10. Which queries change?
  • Write ten new queries from real support tickets you have seen and label them. Does the ranking of the three methods hold?
  • Implement MMR over the fused list with \(\lambda = 0.7\) and add a near-duplicate of document 5. Does MMR stop both copies reaching the top 3?

In practice

  • Default stack (as of 2026). Hybrid retrieval (BM25 or learned sparse plus a strong embedding model chosen on your own data, not only on MTEB), RRF, a cross-encoder or LLM reranker on the top 50–150, 5–20 passages to the generator with ids for citation. Many vector databases and search engines now offer hybrid search and rank fusion natively.
  • Latency budget. Index lookups are typically tens of milliseconds; the reranker is a model call on the critical path whose cost grows with candidate count and passage length; query rewriting and HyDE each add an LLM call. Measure each stage, run independent retrievals in parallel and stream the answer.
  • Evaluate per question type. Lookup, paraphrase, identifier, multi-hop, aggregate and "not in the corpus" questions fail differently. A single average hides which technique you need.
  • Freshness and deletes. Indexes go stale. Re-embed when you change embedding models (old and new vectors are not comparable), and make deletion real for personal data, including in derived indexes such as graphs and summaries.
  • Long context is a competitor, not a replacement. If the whole corpus fits comfortably in context and is reused across many queries (with prompt caching), stuffing it may beat retrieval on quality and simplicity. Above that size, or with many tenants, retrieval wins on cost, and on quality too once distractors pile up.

Common misconceptions

  • "Dense retrieval replaced keyword search." It complemented it. Identifier-heavy domains still need lexical matching, and hybrid usually beats either alone.
  • "A reranker fixes bad retrieval." It reorders candidates; it cannot add a missing one. Fix recall first.
  • "GraphRAG is better RAG." It is a different index for a different question type (aggregate, multi-hop), with a large indexing cost. For point lookups it is usually slower and no better.
  • "More retrieved passages give the model more to work with." Past a few good passages, extra ones are mostly distractors that lower accuracy and raise cost.

Check yourself

Your RAG system's answers are wrong 20% of the time. What do you measure first, and why?

Retrieval recall@k on a labelled set of questions, at the candidate cutoff and at the final cutoff. It separates "evidence never retrieved" from "retrieved but buried" from "retrieved but misused", and each has a different fix. Without it you might tune a prompt for a failure that is really missing evidence.

Compute the RRF score (k = 60) of a document ranked 3rd by BM25, 10th by dense retrieval and absent from a third ranker.

\(1/63 + 1/70 = 0.01587 + 0.01429 = 0.03016\). The absent ranker contributes 0.

Why can't you just add a BM25 score and a cosine similarity?

They are on unrelated, query-dependent scales: BM25 is unbounded and grows with query length and term rarity; cosine similarities sit in a narrow model-specific band. The sum is dominated by whichever has the larger spread for that query. You must normalise (fragile) or fuse ranks (RRF).

A cross-encoder is more accurate than a bi-encoder. Why not use it for first-stage retrieval?

It needs a forward pass per (query, passage) pair at query time, and nothing can be precomputed. Over 10 million passages that is 10 million transformer passes per query. Bi-encoders precompute passage vectors once and search them with approximate nearest-neighbour indexes in milliseconds.

Users ask 'What are the recurring complaints across all support tickets this quarter?' Your hybrid RAG gives shallow answers. Why, and what would you try?

It is an aggregate question: no chunk contains the answer, and top-\(k\) retrieval samples a handful of tickets by similarity. Options: a map-reduce over all tickets (expensive but exact), a summary tree (RAPTOR) or GraphRAG communities precomputed at indexing time, or structured extraction of complaint categories into a table you can count with SQL. The last is often best when the question will be asked repeatedly.

Hard: HyDE improves zero-shot retrieval on a public benchmark but hurts on your internal product docs. Give two plausible reasons.

(1) The LLM does not know your product, so its hypothetical document confidently describes the wrong thing, biasing the query vector (the averaging argument fails when the generator is biased). (2) Your docs use internal names and codes that the hypothetical document paraphrases away, so it moves the query from lexical-match territory into generic semantic space. Mitigations: keep the original query in the fusion (multi-query plus RRF), or condition HyDE on retrieved passages first.

Hard: why does the dimension of an embedding limit which top-k results are possible?

Each query vector induces an ordering of documents by dot product, i.e. the documents are sorted by a linear function. The set of top-\(k\) subsets realisable by linear functions of fixed \(d\)-dimensional document vectors is limited (a sign-rank style argument), so once the number of distinct relevant combinations the task requires exceeds what \(d\) dimensions can realise, some queries must fail, however the encoder is trained. Weller et al. (2025) show this happening on a deliberately simple dataset.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

  • Introduction to Information Retrieval — Manning, Raghavan and Schütze (free online). Chapters 6, 8 and 11: scoring, evaluation and probabilistic IR. The foundation under all of this.

Code

Where this leads