Search

Search papers and lessons

Retrieval-Augmented Generation

Level 4 · 12 min read

Retrieval-augmented generation lets a language model look up supporting passages in an external index and write its answer from them, so its knowledge can be inspected and updated without retraining.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Language & LLMs
  • Sign in to see your progress

TL;DR

Retrieval-augmented generation, or RAG, lets a language model look up evidence before it answers. A retriever searches an external index of text passages for the ones most related to the question, and a generator writes the answer while reading those passages next to the question. Part of the model's knowledge then lives in the index, which can be inspected, cited and changed without retraining.

Where you'll see it: in question answering over a company's documents, in chat assistants that cite their sources, and in the 2020 system from Lewis and colleagues that set the state of the art on several open-domain question answering benchmarks.

Intuition

An open-book exam

A closed-book exam asks you to answer from memory. An open-book exam lets you bring the textbook, but only if you can find the right page quickly and then write the answer from it. A plain language model is sitting a closed-book exam. Everything it knows was squeezed into its weights during training, and whatever it cannot recall, it has to produce from the patterns it learned. RAG hands the model the textbook and a fast way to find the page.

The two halves have different jobs. The retriever is a search engine: given the question, it returns a short list of passages. The generator is the writer: given the question and those passages, it produces the answer. Neither is much use alone. A search engine cannot answer a question in full sentences, and a writer without the right page will produce something plausible that may be wrong.

Why the idea exists

A large pretrained model stores facts in its parameters, and that causes three problems. Facts are hard to update, because changing one means more training. The model cannot easily say where an answer came from. And when it does not know something, it can give a fluent, confident answer that is false. People call this hallucination. Retrieval addresses all three. The index is a separate object that can be swapped or extended, each passage has an identity that can be cited, and the answer is tied to text the model was shown when it wrote it.

flowchart LR
  Q["Question x"] --> R["Retriever: embed the question and search the index"]
  I["Index: passages stored as vectors"] --> R
  R --> P["Top-k passages z"]
  Q --> G["Generator: reads x and z, writes answer y"]
  P --> G
  G --> A["Answer y"]

The retriever and the generator are fine-tuned together. The retriever's query side learns to fetch passages that help the generator, and the generator learns to use whatever it is given.

The math

Definition: Retrieval-augmented generation

A RAG model has two parts. Given an input xx, such as a question, a retriever pη(z∣x)p_\eta(z \mid x) assigns a probability to each passage zz in a fixed collection Z\mathcal{Z}. Given the input and one passage, a generator pθ(y∣x,z)p_\theta(y \mid x, z) assigns a probability to each output yy, such as an answer. The parameters are η\eta for the retriever and θ\theta for the generator. The passage zz is never given as a label during training. The model averages over it instead, which is why zz is called a latent variable.

The retriever

Every passage is turned into a vector d(z)\mathbf{d}(z) once, ahead of time, by a document encoder. Every question is turned into a vector q(x)\mathbf{q}(x) at query time by a query encoder. The score of a passage is the dot product of the two, and the probability is a softmax over all passages:

pη(z∣x)∝exp⁡(d(z)⊤q(x))p_\eta(z \mid x) \propto \exp\left(\mathbf{d}(z)^\top \mathbf{q}(x)\right)

This is the bi-encoder design. The two encoders never see each other, so the document vectors can be precomputed and stored in an index. Finding the top passages then becomes a maximum inner product search problem. The model keeps only the top kk passages, the ones with the largest scores, and ignores the rest.

The generator

Any sequence model that reads text and writes text can serve as the generator. The Lewis et al. system used BART-large, a Transformer encoder-decoder with about 400 million parameters, and simply concatenated the question with the retrieved passage. The generator produces the answer one token at a time, using the usual next-token idea:

pθ(yi∣x,z,y1:i−1)p_\theta(y_i \mid x, z, y_{1:i-1})

Here yiy_i is the ii-th output token and y1:i−1y_{1:i-1} are the tokens written before it. The passage zz is just more context in the prompt, which is why the same generator can be used with any retriever.

Marginalising over passages

Because zz is latent, the model has to average over the passages it retrieved, weighting each by how likely the retriever thought it was. The paper gives two ways to do this. Let NN be the number of output tokens.

RAG-Sequence uses one passage for the whole answer:

pRAG-Seq(y∣x)≈∑z∈top-kpη(z∣x)∏i=1Npθ(yi∣x,z,y1:i−1)p_{\text{RAG-Seq}}(y \mid x) \approx \sum_{z \in \text{top-}k} p_\eta(z \mid x) \prod_{i=1}^{N} p_\theta(y_i \mid x, z, y_{1:i-1})

RAG-Token may use a different passage for each token:

pRAG-Tok(y∣x)≈∏i=1N∑z∈top-kpη(z∣x) pθ(yi∣x,z,y1:i−1)p_{\text{RAG-Tok}}(y \mid x) \approx \prod_{i=1}^{N} \sum_{z \in \text{top-}k} p_\eta(z \mid x)\, p_\theta(y_i \mid x, z, y_{1:i-1})

The only difference is where the sum over passages sits. In RAG-Sequence the sum is outside the product over tokens, so one passage has to support the whole answer. In RAG-Token the sum is inside, so each token can draw on a different passage. That lets the second model combine facts from several documents in one answer.

Training

Training minimises the negative log likelihood of the correct answers over a set of question-answer pairs (xj,yj)(x_j, y_j):

L=∑j−log⁡p(yj∣xj)\mathcal{L} = \sum_j -\log p(y_j \mid x_j)

The loss is computed with the marginal probability above, so the gradient flows back into both the retriever and the generator without any labels saying which passage was right. The paper optimises this with stochastic gradient descent and Adam, and it is a standard Fine-Tuning setup on top of a pretrained generator. The document encoder and the index are held fixed. Only the query encoder and the generator are updated, because rebuilding the index during training is expensive, and the authors report that updating the document encoder was not necessary for strong performance.

Worked examples

Example
A toy retriever with three passages

These numbers are made up for illustration. The query vector is q=(1,0)\mathbf{q} = (1, 0). The three passage vectors are d1=(0.9,0.1)\mathbf{d}_1 = (0.9, 0.1), d2=(0.2,0.8)\mathbf{d}_2 = (0.2, 0.8) and d3=(−0.5,0.5)\mathbf{d}_3 = (-0.5, 0.5).

  1. Scores are the dot products: s1=0.9s_1 = 0.9, s2=0.2s_2 = 0.2, s3=−0.5s_3 = -0.5.
  2. Exponentials: e0.9=2.460e^{0.9} = 2.460, e0.2=1.221e^{0.2} = 1.221, e−0.5=0.607e^{-0.5} = 0.607. Their sum is 4.2884.288.
  3. Retrieval probabilities: p(z1∣x)=0.574p(z_1 \mid x) = 0.574, p(z2∣x)=0.285p(z_2 \mid x) = 0.285, p(z3∣x)=0.141p(z_3 \mid x) = 0.141. They sum to 1.
  4. Suppose the generator gives the answer "Paris" these probabilities under each passage: 0.800.80, 0.100.10 and 0.300.30.
  5. RAG-Sequence marginalises over the three passages: 0.574×0.80+0.285×0.10+0.141×0.30=0.459+0.029+0.042=0.5300.574 \times 0.80 + 0.285 \times 0.10 + 0.141 \times 0.30 = 0.459 + 0.029 + 0.042 = 0.530.

The answer "Paris" gets probability about 0.53. Most of that comes from the first passage, because the retriever ranked it highest and the generator liked it most. If the first passage had been a distractor, the same retriever weights would have pulled the answer down sharply. This is the sense in which the answer is only as good as what was retrieved.

Example
Retrieval gains on Natural Questions, from the paper

The paper reports Exact Match scores on the Natural Questions (NQ) benchmark. The DPR baseline, which retrieves and then extracts an answer span, scores 41.5. RAG-Sequence scores 44.5 and RAG-Token scores 44.1.

  1. Gap for RAG-Sequence: 44.5−41.5=3.044.5 - 41.5 = 3.0 points.
  2. Relative gain: 3.0/41.5=0.0723.0 / 41.5 = 0.072, about 7 percent more questions answered exactly right than DPR.
  3. On WebQuestions the scores are 41.1 for DPR and 45.2 for RAG-Sequence. The gap is 4.14.1 points, a relative gain of 4.1/41.1=0.104.1 / 41.1 = 0.10, about 10 percent.
  4. Knowledge update test: the authors wrote questions about 82 world leaders whose office holders changed between the 2016 and 2018 Wikipedia snapshots. With the matching index, RAG answered 70 percent correctly for 2016 leaders and 68 percent for 2018 leaders. With a mismatched index the accuracy fell to 12 percent and 4 percent.

The interpretation: the gains are real but modest on these benchmarks. The largest lesson is step 4. Swapping the index changed what the model said without any retraining, which is the property that motivates RAG in the first place.

Tradeoffs and failure modes

RAG is not a free upgrade. It adds a search step, an index to maintain, and new ways to fail.

SituationWhat goes wrongBetter choice
Answers depend on facts that change often or are privateWeights go stale, and retraining to refresh them is slow and costlyRAG over an index you can rebuild
The task is about style, format or reasoning, not factsRetrieved text adds noise and latency and may not helpPrompting, [[in-context-learning
The right passage is not retrievedThe generator answers from its prior and can sound confident while being wrongMeasure retrieval recall separately; improve chunking or the retriever; tell the model to abstain when the context does not support an answer
The question contains rare identifiers such as product codesDense vectors blur exact strings, so the right passage can rank lowHybrid retrieval that combines dense scores with keyword search
The corpus is large and queries are frequentIndex memory and lookup latency growApproximate nearest-neighbour search, with the trade of a few missed results

Other failure modes are less visible. The generator may copy a passage that contradicts the truth but happens to be ranked first. Chunk size matters: the paper splits Wikipedia into disjoint 100-word passages, and a fact split across two chunks can be missed entirely. Finally, citing a passage does not guarantee the answer follows from it. A citation shows where the model looked, not that it reasoned correctly.

History

Open-domain question answering, where the system must answer from a large collection rather than a given paragraph, has long used a two-stage design. A retrieval step finds documents, and a separate reader extracts an answer span from them. DrQA, from Chen and colleagues in 2017, is a well-known early example, using sparse keyword retrieval over Wikipedia.

The next step was to train the retriever along with the reader. ORQA (Lee, Chang and Toutanova, 2019) and REALM (Guu and colleagues, 2020) learned retrieval end to end (ORQA with an inverse-cloze pre-training task, REALM with a masked-language-model objective), but they only produced extracted spans. Dense Passage Retrieval (Karpukhin and colleagues, 2020) showed that a pair of learned encoders could beat keyword search on open-domain benchmarks, and it is the design the next system reused.

Lewis and colleagues, in their 2020 paper, combined a DPR-style retriever with a generative model, BART, and marginalised over the retrieved passages during training. The name "retrieval-augmented generation" comes from that paper. It caught on because it produced free-form answers rather than extracted spans, and because the index could be replaced to update knowledge. It also gave a clear recipe that later systems used, with the retriever and generator built from separate, swappable pretrained parts.

Check yourself

QuestionWhat are the two components of a RAG model, and what does each one output?Show answer

The retriever pη(z∣x)p_\eta(z \mid x) scores every passage in the index against the input xx and keeps the top kk. The generator pθ(y∣x,z)p_\theta(y \mid x, z) produces the answer tokens from the input and a passage. The retriever's output is a distribution over passages; the generator's output is a distribution over answers for each passage.

QuestionA retriever gives three passages dot-product scores of 2.0, 1.0 and 0.0. Using all three, what is the retrieval probability of the top passage, to two decimal places?Show answer

Exponentials: e2.0=7.389e^{2.0} = 7.389, e1.0=2.718e^{1.0} = 2.718, e0.0=1e^{0.0} = 1. Sum: 11.10711.107. The top passage gets 7.389/11.107=0.6657.389 / 11.107 = 0.665, which rounds to 0.67. The answer depends on using all three; with a top-kk cut-off the normalisation would change.

QuestionWhy can RAG-Token combine facts from several passages in one answer, while RAG-Sequence cannot?Show answer

In RAG-Sequence the sum over passages sits outside the product over tokens, so a single passage is chosen for the whole answer and every token is conditioned on it. In RAG-Token the sum sits inside the product, so each token's distribution is a mixture over passages, and different tokens can lean on different passages.

QuestionApplied: a support team updates its product manual every week. Should it fine-tune the generator on the new manual or rebuild the retrieval index? Why?Show answer

Rebuild the index. Re-embedding the changed passages is cheap and takes effect at once, and the generator can keep reading whatever passages come back. Fine-tuning would need new training runs each week, would be slow and costly, and could still forget or misstate details that are not in the training data. The index is the part of the system designed to change.

Sources