Contents Working with Large Language Models Code Course home

Chapter 22Retrieval-Augmented Generation

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.

What a language model does not know

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.

The fix

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.

The pipeline

Four stages, and almost every part is machinery from Part II.

Figure 22.1. The four stages. The index is built once. Every question is embedded the same way, retrieves chunks, and is passed to the generator together with them.

Chunk

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.

Embed and index

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.

Retrieve

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.

Keyword retrieval: BM25

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 dd against a query qq by summing over the query terms:

BM25⁡(q,d)=∑t∈qidf⁡t⋅tft,d(k1+1)tft,d+k1(1−b+b|d|/|d|¯),idf⁡t=ln⁡(1+N−dft+0.5dft+0.5).(22.1)\begin{equation} \operatorname{BM25}(q, d) \;=\; \sum_{t \in q} \operatorname{idf}_t \cdot \frac{\mathrm{tf}_{t,d}\,(k_1 + 1)} {\mathrm{tf}_{t,d} + k_1\big(1 - b + b\,|d|/\overline{|d|}\big)}, \qquad \operatorname{idf}_t = \ln\!\Big(1 + \frac{N - \mathrm{df}_t + 0.5}{\mathrm{df}_t + 0.5}\Big). \label{eq:bm25} \quad\text{(22.1)} \end{equation}

It differs from tf-idf in two ways. The idf is the probabilistic form of Equation (4.8), with 11 added inside the logarithm so that it never goes negative. And the term frequency is saturated: the fraction rises with tf\mathrm{tf} but approaches k1+1k_1 + 1 and never passes it, so the fiftieth occurrence adds almost nothing. The parameter bb sets how much a document longer than average is penalised, and the usual defaults are k1=1.2k_1 = 1.2 and b=0.75b = 0.75.

Figure 22.2. Term-frequency saturation at k1=1.2k_1 = 1.2 for a document of average length. The weight is 1.01.0 at one occurrence, 1.3751.375 at two and 1.771.77 at five, and it never exceeds 2.22.2. Raw counts, the dashed line, grow without limit.

Run it on the four documents of Section that section. All have five tokens, so the length factor is 11, and with N=4N = 4 the idf is 0.69310.6931 for moon, orbits, earth and sun, 1.20401.2040 for the words that occur once, and 0.10540.1054 for the.

query d1d_1 d2d_2 d3d_3 d4d_4
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 d1d_1 and d3d_3 tied at the top. It differs in one respect. The word the still contributes a little, 0.14490.1449 to d2d_2, 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 0.10540.1054. For the second query d1d_1 wins by matching all three terms, d2d_2 matches two, d3d_3 one and d4d_4 none.

BM25 term-frequency saturation and a four-document ranking
BM25 gives repeated words diminishing returns and weights each query word by how rare it is, so a document ranks highly when it covers the rare words of the query.

Merging two rankings

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 1/(k+rank)1/(k + \text{rank}), with k=60k = 60 by convention. Take a dense ranking A,B,C,DA, B, C, D and a keyword ranking C,A,E,BC, A, E, B.

document dense rank keyword rank fused score
AA 1 2 0.032522
CC 3 1 0.032266
BB 2 4 0.031754
EE none 3 0.015873
DD 4 none 0.015625

The fused order is A,C,B,E,DA, C, B, E, D. Document AA is in the top two of both lists, so it wins although only one list ranks it first. CC 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 EE and DD 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.

Two ranked lists of documents and their reciprocal rank fusion scores
Reciprocal rank fusion merges rankings from different retrievers using only the ranks, so documents that rank well in several lists rise to the top without comparing raw scores.

Generate

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.

What RAG fixes, and what it does not

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.

Where the failures actually happen

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 1/(k+rank)1/(k+\text{rank}) over the lists.

reranker. a model that rescores a short list of candidates by reading query and passage together.

Further reading.

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.

Practice problems

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 k1=1.2k_1 = 1.2 and b=0.75b = 0.75. Which document wins, and which would win under raw term counts?

22.2 Saturation. Compute tf(k1+1)/(tf+k1)\mathrm{tf}(k_1+1)/(\mathrm{tf}+k_1) at k1=1.2k_1 = 1.2 for tf=1,3,10\mathrm{tf} = 1, 3, 10 and 100100. At what tf\mathrm{tf} does the weight first exceed 9090 per cent of its ceiling?

22.3 Fuse by hand. A dense ranking is P,Q,R,SP, Q, R, S and a keyword ranking is S,P,T,QS, P, T, Q. Compute the reciprocal rank fusion scores with k=60k = 60 and give the fused order.

Build and measure

22.4 Chunk it wrong, twice. Take a document and chunk it at 5050 tokens and at 20002000. 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 11 upwards. At nprobe=1 expect to recover roughly a third of the true neighbours, and expect recall to reach 1.01.0 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 tf=2\mathrm{tf} = 2. Then compute it with b=0.75b = 0.75 and compare.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.