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
A RAG model has two parts. Given an input , such as a question, a retriever assigns a probability to each passage in a fixed collection . Given the input and one passage, a generator assigns a probability to each output , such as an answer. The parameters are for the retriever and for the generator. The passage is never given as a label during training. The model averages over it instead, which is why is called a latent variable.
The retriever
Every passage is turned into a vector once, ahead of time, by a document encoder. Every question is turned into a vector 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:
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 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:
Here is the -th output token and are the tokens written before it. The passage is just more context in the prompt, which is why the same generator can be used with any retriever.
Marginalising over passages
Because 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 be the number of output tokens.
RAG-Sequence uses one passage for the whole answer:
RAG-Token may use a different passage for each token:
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 :
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
These numbers are made up for illustration. The query vector is . The three passage vectors are , and .
- Scores are the dot products: , , .
- Exponentials: , , . Their sum is .
- Retrieval probabilities: , , . They sum to 1.
- Suppose the generator gives the answer "Paris" these probabilities under each passage: , and .
- RAG-Sequence marginalises over the three passages: .
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.
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.
- Gap for RAG-Sequence: points.
- Relative gain: , about 7 percent more questions answered exactly right than DPR.
- On WebQuestions the scores are 41.1 for DPR and 45.2 for RAG-Sequence. The gap is points, a relative gain of , about 10 percent.
- 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.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Answers depend on facts that change often or are private | Weights go stale, and retraining to refresh them is slow and costly | RAG over an index you can rebuild |
| The task is about style, format or reasoning, not facts | Retrieved text adds noise and latency and may not help | Prompting, [[in-context-learning |
| The right passage is not retrieved | The generator answers from its prior and can sound confident while being wrong | Measure 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 codes | Dense vectors blur exact strings, so the right passage can rank low | Hybrid retrieval that combines dense scores with keyword search |
| The corpus is large and queries are frequent | Index memory and lookup latency grow | Approximate 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 scores every passage in the index against the input and keeps the top . The generator 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: , , . Sum: . The top passage gets , which rounds to 0.67. The answer depends on using all three; with a top- 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
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020): https://arxiv.org/abs/2005.11401
- Karpukhin et al., Dense Passage Retrieval for Open-Domain Question Answering (2020): https://arxiv.org/abs/2004.04906
- Retrieval-augmented generation, Wikipedia: https://en.wikipedia.org/wiki/Retrieval-augmented_generation