After this chapter you will be able to
say which three kinds of question a frozen model cannot answer, and how RAG answers them;
chunk, embed, index, retrieve and generate, and name the trade-off at each stage;
compute a BM25 score by hand and say what saturation does;
fuse a dense and a keyword ranking with reciprocal rank fusion;
diagnose a wrong answer as a retrieval failure or a generation failure.
This chapter builds on Chapters 4 and 16, which supply tf-idf and the embeddings used for retrieval.
A pretrained model knows what was in its training corpus, frozen at the moment training stopped, so three kinds of question have no good answer. Recent facts come first, since anything after the cutoff date does not exist for the model. Private facts come next, meaning your company’s policies, your codebase and your customer records, none of which was in the corpus and none of which should have been. And rare facts are the third kind, being things technically present in the corpus but seen so few times that the model’s memory of them is unreliable.
In all three cases the model does not say it does not know but produces the most plausible continuation, which is a confident and specific falsehood. This is Chapter 21’s hallucination, and no amount of prompting fixes it, because prompting selects from what the model has.
Do not ask the model to remember, but give it the document and ask it to read. That is retrieval-augmented generation (RAG) (Lewis et al. 2020), where you find the relevant text, put it in the context window, and generate an answer grounded in it.
The change in what is being asked matters most. Recall from parameters is unreliable and unverifiable, whereas reading comprehension over supplied text is something these models are extremely good at, and the source can be shown.
Four stages, and almost every part is machinery from Part II.
Documents are too long for a context window and too long to retrieve usefully, so split them. Chunk size is a trade-off and not a detail.
| chunk size | retrieval | context supplied |
|---|---|---|
| too small | precise matches | fragments, missing sense |
| too large | one vector, many topics | whole sections, mostly noise |
The failure at the small end is easy to miss, because a chunk of one sentence retrieves precisely and then hands the model a sentence whose antecedents are in the paragraph above. Overlapping chunks reduce that at the cost of storing the overlap, and splitting on structure, at paragraph or section boundaries, usually beats splitting at a fixed token count.
Each chunk becomes a vector from an embedding model, which is Chapter 16’s machinery applied to passages and not words. The vectors go into an index built for approximate nearest-neighbour search, because exact search over millions of vectors is too slow and approximate search gives up a small amount of recall for a very large amount of speed.
Embed the query the same way and find the nearest chunks by cosine similarity, which is Equation (9.24) from Chapter 9. Dense retrieval of this kind (Karpukhin et al. 2020) has one clear advantage over keyword search and one clear weakness.
It matches on meaning, so a query about “refund window” can retrieve a passage saying “returns accepted within 30 days” with no shared words. It is weak on exact strings, though, whether a part number, a person’s name or an error code, and those are precisely the cases where a keyword index is unbeatable.
Production systems therefore usually run both and merge, which is called hybrid retrieval. The two methods fail on different queries, and that is the only good reason to run two of anything.
The keyword half deserves its own formula, because it is the strongest baseline in retrieval and it is the descendant of the weighting of Chapter 4. BM25 scores a document against a query by summing over the query terms:
It differs from tf-idf in two ways. The idf is the probabilistic form of Equation (4.8), with added inside the logarithm so that it never goes negative. And the term frequency is saturated: the fraction rises with but approaches and never passes it, so the fiftieth occurrence adds almost nothing. The parameter sets how much a document longer than average is penalised, and the usual defaults are and .
Run it on the four documents of Section that section. All have five tokens, so the length factor is , and with the idf is for moon, orbits, earth and sun, for the words that occur once, and for the.
| query | ||||
|---|---|---|---|---|
| the moon | 0.8380 | 0.1449 | 0.8380 | 0.1054 |
| moon orbits earth | 2.0794 | 1.3863 | 0.6931 | 0.0000 |
For the first query BM25 agrees with tf-idf on the ranking, with and tied at the top. It differs in one respect. The word the still contributes a little, to , where tf-idf gave exactly zero, because the BM25 idf is positive for every word that does not occur in all documents and for the here it is . For the second query wins by matching all three terms, matches two, one and none.
Hybrid retrieval has a practical problem. A BM25 score and a cosine live on different scales, so adding them needs a calibration nobody has. Reciprocal rank fusion sidesteps it by using only ranks. A document’s fused score is the sum, over the rankings it appears in, of , with by convention. Take a dense ranking and a keyword ranking .
| document | dense rank | keyword rank | fused score |
|---|---|---|---|
| 1 | 2 | 0.032522 | |
| 3 | 1 | 0.032266 | |
| 2 | 4 | 0.031754 | |
| none | 3 | 0.015873 | |
| 4 | none | 0.015625 |
The fused order is . Document is in the top two of both lists, so it wins although only one list ranks it first. is first for keywords and third for dense, and it comes second. A document that only one retriever returns can still make the list, as and do, but it scores about half of one that both found. A reranker, a model that reads the query and each candidate together and rescores the top few dozen, usually follows fusion, because it can compare the two texts directly and the retrievers cannot.
Put the retrieved chunks in the prompt with the question and ask for an answer based on them. The instruction that matters most is the one about not knowing.
Answer using only the passages below. If they do not contain the answer, say so.
Without that line the model falls back on its parameters and you are back to hallucination, now with citations that look authoritative. With it, the system can return “I don’t know”, which an ungrounded model rarely does.
| problem | does RAG help? |
|---|---|
| model lacks recent or private knowledge | yes, directly |
| answers cannot be verified | yes, the source is shown |
| knowledge changes often | yes, update the index not the model |
| model reasons badly over supplied text | no |
| model’s default behaviour is wrong | no, that is Chapter 21 |
| the answer is not in any document | no, and it should say so |
The third row is the underrated one, because updating a document store is a database write while updating a model’s parametric knowledge is a training run. The fourth row is the limit, since RAG supplies context and does nothing for a model that misreads the context it is given.
Most RAG failures are retrieval failures, and diagnosing one takes two steps rather than one. First ask whether the right chunk was retrieved at all, because if it was not then the generator never had a chance and no prompt engineering will help. Only if the right chunk was retrieved and the answer is still wrong is the generator at fault.
That split matters because the two have entirely different repairs. Retrieval failures are fixed with chunking, embeddings, hybrid search or reranking, while generation failures are fixed with prompting or a better model. Teams routinely spend weeks on the second when the problem was the first.
Summary
A pretrained model cannot answer questions about recent, private or rare facts, and it produces a confident falsehood instead of saying so. Retrieval-augmented generation finds relevant text, puts it in the prompt and asks for an answer grounded in it. The pipeline chunks documents, embeds the chunks, retrieves the nearest ones and generates with an instruction to refuse when the answer is absent. Dense retrieval matches meaning and fails on exact strings, and BM25 matches terms with a saturated term frequency and a length penalty, so production systems merge both, for example by reciprocal rank fusion, and often rerank. RAG fixes missing and changing knowledge and shows the source, and it does not fix bad reasoning over the text. Most failures are retrieval failures, so check the retrieved chunk before touching the prompt.
Key terms
retrieval-augmented generation. generating an answer from a prompt that includes retrieved passages.
chunk. a passage of a document short enough to embed and to place in a prompt.
dense retrieval. finding passages by the cosine similarity of learned embeddings.
BM25. a keyword score that saturates term frequency and penalises long documents.
hybrid retrieval. combining dense and keyword rankings.
reciprocal rank fusion. merging rankings by summing over the lists.
reranker. a model that rescores a short list of candidates by reading query and passage together.
Lewis et al. (2020) introduced the term and the architecture.
Karpukhin et al. (2020) is the dense passage retrieval paper that made
the retrieval half work. Manning et al. (2009) covers the information
retrieval foundations, including the keyword methods that hybrid search
still depends on. The three pieces of the pipeline exist as
sentence-transformers for the encoder, faiss
for the index and rank_bm25 for the keyword half, and
assembling them is a short afternoon.
22.1 BM25 by hand. Using the four documents of this chapter, compute the BM25 score of every document for the query sun earth, with and . Which document wins, and which would win under raw term counts?
22.2 Saturation. Compute at for and . At what does the weight first exceed per cent of its ceiling?
22.3 Fuse by hand. A dense ranking is and a keyword ranking is . Compute the reciprocal rank fusion scores with and give the fused order.
Build and measure
22.4 Chunk it wrong, twice. Take a document and chunk it at tokens and at . For a handful of questions, record which chunks are retrieved. Describe the failure mode at each extreme in terms of what the generator receives.
22.5 Dense against keyword. Write five queries where dense retrieval should beat keyword search, and five where it should lose. State the property that separates the two lists.
22.6 The refusal instruction. Build a small RAG system, then ask it a question whose answer is not in any document. Report what it says with and without the instruction to refuse. Which behaviour would you ship?
In practice
22.7 Diagnose the layer. A RAG system gives a wrong answer. Describe the exact procedure you would follow to decide whether retrieval or generation is at fault, and name the repair you would attempt in each case.
22.8 Update cost. A policy document changes weekly. Compare the cost of keeping a RAG index current against the cost of keeping a fine-tuned model’s knowledge current. Then name one situation where fine-tuning is still the right answer.
22.9 Your index is allowed to be
wrong. Build a faiss IndexFlatIP over
a few thousand normalised vectors and confirm that its top five matches
are identical to a brute force dot product against every vector. Now
build an IndexIVFFlat over the same data and measure recall
at five against that brute force answer, sweeping nprobe
from
upwards. At nprobe=1 expect to recover roughly a third of
the true neighbours, and expect recall to reach
only once nprobe equals the number of cells, at which point
you are searching everything again. Then answer the question this raises
about the pipeline earlier in this chapter: when a RAG system returns a
bad answer, how would you tell a retrieval failure from an index that
was never asked to look?
22.10 Which retriever? Choose dense, BM25 or hybrid for each of three corpora: error logs with codes, a legal archive in plain prose, and a product catalogue with part numbers and descriptions. Justify each choice and say what you would measure.
22.11 Add a reranker. Add a reranker to the system of the previous section’s problems and measure whether the correct chunk moves up. Report the change in the rank of the right chunk over twenty questions and what it costs in latency.
22.12 Predict the length effect. Before computing, predict whether a document twice the average length with the same term frequency scores higher or lower under BM25 than one of average length, and by roughly how much for . Then compute it with and compare.
From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.