Back to paper library
Paper notesarXiv 2020NeurIPS 2020

RAG

Why Are We Calling It a Rag?

Original paper

Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks

Paper authors

Patrick Lewis · Ethan Perez · Aleksandra Piktus …

Show all 12 authors

Patrick Lewis · Ethan Perez · Aleksandra Piktus · Fabio Petroni · Vladimir Karpukhin · Naman Goyal · Heinrich Küttler · Mike Lewis · Wen-tau Yih · Tim Rocktäschel · Sebastian Riedel · Douwe Kiela

Publication
NeurIPS 2020Conference
First submitted to arXiv
arXiv:2005.11401
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{retrievalaugmentedgenerationrag2020,
  title = {{Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks}},
  author = {Patrick Lewis and Ethan Perez and Aleksandra Piktus and Fabio Petroni and Vladimir Karpukhin and Naman Goyal and Heinrich Küttler and Mike Lewis and Wen-tau Yih and Tim Rocktäschel and Sebastian Riedel and Douwe Kiela},
  year = {2020},
  eprint = {2005.11401},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2005.11401}
}
On this page

These days, whenever someone talks about getting a language model to read company documents, “RAG” is almost bound to come up.

The name comes from this 2020 paper.

Of course, a rag is also a piece of old cloth. A technique that would eventually sweep through the AI industry ended up sharing its name with something used to wipe the floor. You have to laugh.

In an interview with NVIDIA, first author Patrick Lewis later apologized for the unfortunate acronym, saying that had they known how widely it would spread, they would have put more thought into the name. They had meant to come up with something better, but nobody did while writing the paper.

So the name stuck.

If you first encountered RAG after ChatGPT, though, this paper may surprise you. Today's usual recipe is to retrieve a few passages, paste them into a prompt, and ask a large language model to answer. Here, RAG uses a 400-million-parameter BART, trains the retriever and generator together, and treats the retrieved document as a random variable.

Let us go back to what the name originally referred to.

Defining the Problem

Around 2020, pretrained language models were already known to store substantial factual knowledge in their parameters. Models such as T5 could answer some questions directly, without any reference material.

This is called closed-book question answering. Like a closed-book exam, all the knowledge has to be in your head.

That creates several problems:

  1. Knowledge is hard to update. The world changes, but the knowledge in the parameters stays put until the model is trained again.
  2. Sources are unavailable. Even when the answer is correct, you do not know where the model learned it.
  3. The model can invent things with a straight face. What we now routinely call hallucination.

Another approach, known as open-book, lets the model bring external material to the exam. Before this paper, REALM and ORQA had already connected differentiable retrievers to masked language models, but only for extractive question answering, where the answer had to be a span in the source text and the model's job was to locate it.

The authors wanted something broader:

  • Could a general sequence-to-sequence generator carry a searchable external memory and use the same approach to fine-tune for different tasks?

This is hard because the training data contains only questions and answers, and nobody has labeled which document to retrieve.

How is the retriever supposed to learn?

Solving the Problem

Architecture

RAG overview: the Query Encoder encodes the input as q(x), MIPS retrieves top-K documents from the Document Index, and the Generator produces an answer while marginalizing over documents
Figure 1 of the paper, from page 2 of the v4 PDF. Inputs for three tasks appear on the left, with their outputs on the right.

Read the diagram from left to right.

At the far left is the input xx: a question (“define middle ear”), a statement to fact-check, or an answer term from which to generate a Jeopardy clue (“The Divine Comedy”).

The green box is the retriever, pηp_\eta. The Query Encoder maps the input to a vector q(x)q(x); the Document Index stores a precomputed vector d(z)d(z) for each document. MIPS selects the most relevant documents, z1,…,z4z_1,\dots,z_4.

The blue box is the generator, pθp_\theta. It concatenates the input with each document separately and generates an answer. “Marginalize” then combines the document-conditioned results into a prediction.

The dashed arrow at the top reads “End-to-End Backprop through q and pθp_\theta,” meaning that during training, gradients flow back to the Query Encoder and generator. Notice that the Document Index is not mentioned. We will return to that.

The authors describe the two components as two kinds of memory:

  • Parametric memory: the generator's parameters—the knowledge BART has learned.
  • Non-parametric memory: the external document index, which can be replaced directly.

External Memory: 21 Million Wikipedia Passages

The only external knowledge source is the December 2018 English Wikipedia dump.

Articles are split into non-overlapping passages of 100 words, yielding about 21 million “documents.” A document encoder produces their vectors, which are stored in an index built with FAISS.

The retriever is DPR, the Dense Passage Retriever. It uses two BERT-base encoders, one for questions and one for documents. Relevance is the inner product of their vectors:

pη(z∣x)∝exp⁡ ⁣(d(z)⊤q(x)),d(z)=BERTd(z), q(x)=BERTq(x)p_\eta(z\mid x)\propto \exp\!\left(d(z)^\top q(x)\right),\quad d(z)=\text{BERT}_d(z),\ q(x)=\text{BERT}_q(x)

Finding the KK largest inner products among 21 million vectors is a MIPS, or Maximum Inner Product Search, problem.

The generator is BART-large, with about 400 million parameters. Concatenate input xx and document zz, then let it generate the answer. That part is straightforward.

The Document Is a Random Variable

Now we reach the paper's central idea.

As noted above, training data does not identify the right document. The authors simply leave that choice unresolved, treating the retrieved document zz as an unobserved latent variable and taking a weighted average over the possible documents.

The retriever assigns each document a probability pη(z∣x)p_\eta(z\mid x). Conditioned on that document, the generator assigns the answer a probability pθ(y∣x,z)p_\theta(y\mid x,z). Multiply the two and sum across documents to obtain the answer probability.

There are two ways to arrange that summation.

RAG-Sequence ties the entire answer to one document. Compute the probability of the whole sequence under each document, then weight across documents:

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

RAG-Token allows each token to draw on a different document. At each step, average across documents to obtain that token's probability, then multiply over tokens:

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

Only the order of ∑\sum and ∏\prod changes. What difference does that make?

Let us try some small numbers.

Suppose the retriever finds two documents, assigning doc1 probability 0.6 and doc2 probability 0.4. The answer has two tokens:

  • Under doc1, the generator assigns the first token probability 0.9 and the second 0.2.
  • Under doc2, the pattern reverses, with 0.3 for the first token and 0.8 for the second.

In other words, doc1 supports the first part of the answer, while doc2 supports the second.

RAG-Sequence gives 0.6×0.9×0.2+0.4×0.3×0.8=0.2040.6\times0.9\times0.2+0.4\times0.3\times0.8=0.204; RAG-Token gives (0.6×0.9+0.4×0.3)×(0.6×0.2+0.4×0.8)=0.66×0.44≈0.290(0.6\times0.9+0.4\times0.3)\times(0.6\times0.2+0.4\times0.8)=0.66\times0.44\approx0.290.

RAG-Sequence needs one document to support the whole answer. Doc1 supports the first half but struggles with the second; doc2 has the opposite problem. Both paths are penalized.

RAG-Token draws mainly on doc1 for the first token and doc2 for the second, giving this assembled answer a higher probability.

This also explains why RAG-Token performs better on Jeopardy clue generation in the experiments. We will see a concrete example in the discussion.

How Does the Retriever Learn Without Document Labels?

The training objective is to maximize the marginal probability of the correct answer, that is, to minimize −log⁡p(y∣x)-\log p(y\mid x).

Look back at the equations. Since pη(z∣x)p_\eta(z\mid x) appears inside the sum, gradients reach it. If a document helps the generator produce the correct answer, increasing that document's probability raises the overall marginal probability. Training teaches the retriever to score such documents more highly.

Nobody tells it which document is right. It learns from which documents help.

However, the authors update only the question encoder, BERTq\text{BERT}_q, and BART. The document encoder and index remain frozen.

Any change to the document encoder would mean recomputing all 21 million document vectors and rebuilding the index as well. REALM periodically rebuilds its index during pretraining; the authors found that their results were already good without this step.

Decoding at Inference Time

RAG-Token produces a next-token probability at each step, so standard beam search applies directly.

RAG-Sequence is harder to decode because its sequence probability cannot be decomposed into individual next-token probabilities in the same way. The authors run beam search separately for each document, collect all candidate answers, then compute each candidate's probability under the other documents and take the weighted sum. They call this “Thorough Decoding.”

With many candidates, those additional forward passes become expensive. An approximation, “Fast Decoding,” assigns zero probability under a document to any candidate absent from that document's beam, avoiding the extra computation.

Discussion

Open-Domain Question Answering

The authors evaluate on Natural Questions (NQ), TriviaQA (TQA), WebQuestions (WQ), and CuratedTrec (CT), four open-domain QA datasets. The metric is Exact Match, the proportion of answers matching the reference exactly.

Table 1: test scores for closed-book T5, open-book REALM and DPR, RAG-Token, and RAG-Sequence on NQ, TQA, WQ, and CT
Table 1 of the paper, from page 6 of the v4 PDF. The left TQA column uses the standard open-domain test set; the right uses TQA-Wiki.

The table has three sections: closed-book T5 at the top, open-book REALM and DPR in the middle, and RAG at the bottom.

On NQ, RAG-Sequence scores 44.5, compared with 34.5 for closed-book T5-11B.

Parameter counts matter here. T5-11B has 11 billion trainable parameters. RAG has about 626 million in total: two BERT-base encoders of roughly 110 million each, with the document encoder actually frozen, plus BART's approximately 400 million. The appendix notes that T5-large, the closest in size at 770 million parameters, scores only 28.9 on NQ.

Another comparison is DPR's QA system, which additionally uses a cross-encoder reranker and an extractive reader. RAG uses neither and still scores 3 points higher on NQ.

Generation also has an advantage extraction cannot provide. When a document contains clues but not the literal answer, the model may still generate the correct response. Among NQ questions whose answers were absent from every retrieved document, RAG answered 11.8% correctly. An extractive model necessarily scores 0% in that situation.

Jeopardy Clues: Combining Two Documents

Jeopardy is an American quiz show with an unusual format, in which you are first given an answer and then asked to write its clue. For “The World Cup,” a clue might read, “In 1986, Mexico became the first country to host this international event twice.”

These clues often combine two facts, making them a useful test of RAG-Token's ability to assemble information. The figure below shows which document the model considers helpful at each generated token for the input “Hemingway,” with five documents retrieved:

Posterior probability heatmap over five documents for each token generated by RAG-Token when producing a Jeopardy clue for Hemingway
Figure 2 of the paper, from page 7 of the v4 PDF. Generated tokens run horizontally and retrieved documents vertically; darker colors indicate higher posterior probabilities.

Two documents are shown on the left. Document 1 mentions A Farewell to Arms, and Document 2 mentions The Sun Also Rises.

Look at the heatmap on the right. When the model generates “Sun,” Doc 2's row becomes dark. When it generates “A” to begin “A Farewell to Arms,” Doc 1 takes over.

This is the situation we just calculated by hand, where different documents support different parts of one sentence.

After the first token of a book title, the heatmap fades. The authors believe BART can finish the rest of the title on its own. They fed just “"The Sun” to BART without retrieval, and it completed the title. In their account, the two memories cooperate, with a retrieved document pointing the model in the right direction and parametric knowledge finishing the phrase.

Human evaluation compared factual correctness in 452 pairs of BART and RAG-Token clues. BART was judged more factual in 7.1% of pairs, versus 42.7% for RAG, according to Table 4.

Is the Learned Retriever Better?

The authors run two ablations, one freezing the retriever instead of training it and the other replacing it with BM25 keyword retrieval.

For RAG-Sequence on the NQ development set, Table 6 gives:

  1. BM25 replacement: 31.8.
  2. Frozen retriever: 41.2.
  3. Joint training: 44.0.

Learned retrieval makes a substantial difference for QA.

FEVER fact-checking is an exception. BM25 reaches 75.1 three-way classification accuracy, slightly above learned retrieval's 74.5. The authors suggest that FEVER claims often concern specific entities, so matching a name is a good way to find the material, making keyword retrieval well suited to the task.

Replace the Index, Update the Knowledge

This experiment makes the value of external memory particularly clear.

The authors build another index from December 2016 Wikipedia, then collect 82 world-leader positions whose occupants changed between 2016 and 2018. They ask “Who is {position}?,” for example, “Who is the President of Peru?”

IndexQuestions about 2016 leadersQuestions about 2018 leaders
2016 index70%4%
2018 index12%68%

Compiled from §4.5 of the paper.

Match the index year to the questions and roughly seven in ten answers are correct. Mismatch them and accuracy drops to single digits or a little above ten percent.

No model parameters change. Replacing the external memory changes the answers—something a closed-book model cannot achieve this way.

Where Things Were Less Smooth

  1. More retrieval is not always better. On NQ, RAG-Sequence improves as more documents are retrieved at test time; RAG-Token peaks at around 10.
  2. Retrieval can collapse. The appendix describes preliminary story-generation experiments where the retriever returned the same documents regardless of input. The generator learned to ignore them, reducing the system to ordinary BART. The authors suggest that such tasks may not clearly require factual knowledge, or that long answers provide less useful gradients to the retriever.
  3. Wikipedia cannot answer every question. MS-MARCO includes questions such as “What is the weather in Volcano, California right now?” For questions less likely to benefit from retrieval, the authors observed the model consistently retrieving a particular set of documents.

Conclusion

This paper connects a pretrained generator to a searchable external memory, then fine-tunes the same formulation for question answering, clue generation, and fact-checking.

Its most persuasive results are these:

  1. A smaller model with external memory beats a much larger closed-book model. On NQ, RAG-Sequence's 626 million parameters yield 44.5, compared with 34.5 for the 11-billion-parameter T5-11B.
  2. Document-selection labels are unnecessary. Marginalizing over documents as latent variables lets the retriever learn what to retrieve from the answer probabilities.
  3. Replacing the index updates knowledge. Switching the 2016 and 2018 indexes changes answers about leaders without changing model parameters.

Looking at today's RAG, two ideas have survived: retrieve before handing documents to the generator, and keep external memory replaceable. The other half—joint retriever-generator training and document marginalization—is much less common in later LLM applications built around prompt concatenation. Models have become expensive to fine-tune, and retrievers are often replaced with ready-made embedding models or search engines.

That is what developed afterward, rather than a claim made by this paper.

The name, at least, never changed.