AI engineering paper · 2020

RAG

Lewis, Perez, Piktus, Petroni, Karpukhin, Goyal, Küttler, Lewis, Yih, Rocktäschel, Riedel and Kiela · NeurIPS 2020

How the 2020 RAG paper let a model look up passages before answering, and trained its question search and its answerer together.

The paper’s RAG: search 21 million passages, read the best few one at a time, then combine the answers in proportion to how well each passage matched.

You’ll learn to

  • Explain how RAG finds passages by meaning, reads them and turns the result into one answer.
  • Compare RAG-Sequence and RAG-Token, and work through each on a small example.
  • Say which parts the paper trained, which it froze, and why most apps today train neither.
  • Name what replaced the paper’s design in practice, and what held up.

The idea in short

A language model keeps what it learned inside its parameters, the numbers that make up the model. You cannot check them and they are hard to update. This paper adds a second memory: a large collection of text, here 21 million short Wikipedia passages. For each question, a search step finds a few passages by meaning, and the model reads them while it writes the answer.

The authors trained the question side of the search and the answering step together, from question and answer pairs alone, with no labels saying which passage was the right one. Today the name RAG usually means something simpler: search, paste the passages into the prompt of a model that is not trained any further, and let it answer.

The problem

A language model learns facts while it is trained, and stores them in its parameters: the hundreds of millions to billions of numbers that make up the model. The paper calls this . It has three weaknesses. You cannot see where a fact came from. You cannot change one fact without more training. And the model can state something false with full confidence, which is called a .

Question answering shows the cost. In , the model gets only the question and must answer from its parameters. The T5-11B model, with 11 billion parameters, scored 34.5 on Natural Questions, a set of real questions people typed into Google. The score is exact match: the share of questions where the model’s answer is the same, word for word, as one of the accepted answers. Getting better meant a bigger model.

The other style is : the system may look things up in a large collection of text before it answers. Earlier lookup systems usually found a passage and copied a short span of words out of it, using what is called an extractive reader. That works only when the answer is written in the passage, word for word.

The paper, by Patrick Lewis and colleagues, asks a direct question. Can a model that writes its own answers also look things up, and can the whole thing be trained as one system? They call the result , or RAG. Retrieval is the lookup. Generation is writing the answer in new words.

The design choices

RAG joins two models and one stored collection:

  • The text collection. The paper calls it , because it is stored text, not model parameters, and you can replace it without training anything. They use a December 2018 copy of Wikipedia, cut into 21 million passages of 100 words each.
  • A retriever. It takes the question and returns the passages most likely to help. The paper uses one built earlier by other authors, called DPR.
  • A generator. It reads the question plus a passage and writes text. The paper uses BART-large, a model that reads an input and writes an output one word at a time.

Two choices set this paper apart from earlier work:

  • The same design for every task. Question answering, writing quiz clues and checking facts all use the same system. Only the training data changes.
  • No labels for the lookup. The training data holds a question and its answer. It never says which passage held the answer. The system learns what to retrieve from whether the final answer came out right.
Question The paper’s answer Section
How do you find passages by meaning Turn question and passages into lists of numbers and compare them Finding passages by meaning
How does the model use a passage Read the question and the passage together Reading the passages
How do several passages become one answer Add up the answers, in proportion to how well each passage matched, in one of two ways Combining the passages
How does the search step learn The error from the final answer flows back into the question side of the search Training the question side and the generator

Finding passages by meaning

Searching by keywords fails when the question and the passage use different words. “Who wrote The Sun Also Rises” should find a passage that says “Hemingway’s first novel”. Searching by meaning handles this with : a model turns a piece of text into a list of numbers, and texts with similar meaning get lists that point in similar directions.

The retriever is called DPR, for dense passage retriever (Karpukhin and colleagues, 2020). “Dense” means each text becomes a list of several hundred numbers that all carry meaning, instead of a count of which words appear. DPR is a : two separate BERT models, one for the question and one for the passage. BERT is a widely used model that reads text and turns it into numbers. The question model makes a list q. The passage model makes a list p. The score of a passage is the of the two: multiply the lists number by number and add the results. A higher score means a closer match, though a longer list also scores higher.

The two sides are separate for a reason. Every passage list can be worked out once, before any question arrives, and stored in the index: the stored lists of all 21 million passages, arranged so that the highest scores can be found quickly without checking every passage. A question then needs only one model run and one fast search.

The score is a dot product. Passages are encoded ahead of time, so a question costs one model run plus one fast search.

The scores are not used as they are. The paper turns them into passage chances that add up to 1, using a function called . It raises e (about 2.718) to the power of each score, then divides each result by the total. A high score gets a large share and a low score a small one.

passage chance=e^score÷(sum of e^score over the retrieved passages)
The chance that this passage is the right one for the question.

Three passages are scored

Scores: 2.0, 1.3 and 0.2

Our own toy numbers, to show the arithmetic. The real scores come out of the two BERT models.

Raise e to each score

e^2.0 = 7.39, e^1.3 = 3.67, e^0.2 = 1.22

Each result is positive, and bigger scores grow faster.

Divide by the total

7.39 + 3.67 + 1.22 = 12.28

The passage chances are 7.39 ÷ 12.28 = 0.60, 3.67 ÷ 12.28 = 0.30 and 1.22 ÷ 12.28 = 0.10. They add up to 1.

Keeping the passage side frozen, meaning fixed and not changed by training, was a choice. The authors note that training the passage model would mean re-encoding all 21 million passages every so often, which is costly, and they found it was not needed. So the passage model and the index stay frozen, and only the question model is trained further.

Reading the passages

The generator reads the question and one passage joined into a single input, and writes an answer. It does this one word at a time: at each step, it gives a chance to every possible next word. Nothing special is built into BART for using passages. It learns during training to use whatever the passage supplies.

With several passages, the generator runs once per passage, and each run gives its own chances for every possible next word. The paper calls the choice of passage a latent variable: a quantity the model must account for but is never told. Nobody labels the right passage. The model keeps every retrieved passage in play, each at its passage chance, and adding up over them is what the next section calls marginalising.

This design has one practical limit. Each run sees one passage, so the generator never reads two passages side by side. The model can still use several passages, because the combining step mixes the runs, but the mixing happens on chances, not on text. Later work changed this, as the section on what changed explains.

Combining the passages: two ways

The runs give different answers, so the paper needs a rule to turn them into one. The rule is : add up the chance of an answer over every passage that could have produced it, each scaled by the passage’s own chance. The paper offers two versions. They differ in when the passage is allowed to change.

  • picks one passage and uses it for the whole answer. It works out the chance of the full answer under each passage, then adds those up, scaled by the passage chances.
  • lets each word of the answer use a different passage. At every word, it adds up the chances over all passages, then moves on to the next word. (A token is a word or a piece of a word.)

Take a two-word answer, “A then B”, and three passages with passage chances 0.6, 0.3 and 0.1. Passage 1 gives a high chance to A, passage 2 gives a high chance to B, and passage 3 is no help. These are our own toy numbers.

RAG-Sequence, passage by passage

0.6 × 0.9 × 0.1 = 0.054

Passage 1 has a 0.9 chance for A and 0.1 for B. Passage 2: 0.3 × 0.1 × 0.9 = 0.027. Passage 3: 0.1 × 0.1 × 0.1 = 0.001.

RAG-Sequence, add them up

0.054 + 0.027 + 0.001 = 0.082

Each passage is stuck with its own answers for both words, so neither passage alone writes “A then B” well.

RAG-Token, word A

0.6×0.9 + 0.3×0.1 + 0.1×0.1 = 0.58

All three passages contribute to the first word, each scaled by its passage chance.

RAG-Token, word B

0.6×0.1 + 0.3×0.9 + 0.1×0.1 = 0.34

The passage chances stay the same, but passage 2 now carries most of the total.

RAG-Token, multiply

0.58 × 0.34 = 0.197

About 0.20, compared with 0.082 for RAG-Sequence. Token can borrow A from passage 1 and B from passage 2.

Same passages, same passage chances. Sequence commits to one passage for the whole answer and scores 0.082. Token may switch passages word by word and scores 0.197.

The paper’s own examples show where each one wins. On Jeopardy, where the task is to write the quiz clue for a given answer, clues often combine two facts, and RAG-Token did better. For a clue about Hemingway, the paper’s figure shows one passage driving the first novel’s title and a different passage driving the second. On short factual answers, RAG-Sequence was slightly ahead.

The answer is written word by word with , which keeps several likely partial answers going instead of committing to one. For RAG-Token this works as it is, because each word’s chance already includes every passage. For RAG-Sequence the chance of a whole answer needs every passage, and an answer found under passage 1 may never come up under passage 2. For short answers, the paper ran extra passes to score each candidate under every passage. For long outputs it used a cheaper shortcut that treats unseen combinations as impossible.

Training the question side and the generator

Training minimises the negative marginal log-likelihood of the right answer. In plain words: take the combined chance the model gave the correct answer, take its logarithm and flip the sign. A chance of 1 gives a loss of 0. A smaller chance gives a larger loss. Because the answer’s chance is a sum over passages scaled by the passage chances, those passage chances sit inside the loss.

That is the trick. When training works out how to adjust each number to lower the loss (the gradient), the signal flows back through the passage chances into the question model, in the same way it flows into any other number used to compute the answer. A passage that helped produce the right answer has its chance pushed up for similar questions, and a passage that did not is pushed down. No one labels the right passage.

Before training

0.6×0.2 + 0.3×0.9 + 0.1×0.1 = 0.40

Our own toy numbers. Passage chances are 0.6, 0.3 and 0.1. The chance of the correct answer given each passage is 0.2, 0.9 and 0.1, chosen so that passage 2 clearly holds the answer and the others mostly do not. Passage 2 gets only 0.3.

The loss

−ln 0.40 = 0.92

The logarithm is natural. A model that was confident and correct would have a loss near 0.

Passage 2 is rewarded

chances move to 0.3, 0.6, 0.1

Raising the chance of passage 2 is the change that lowers the loss most, so training pushes that way. We moved 0.3 from passage 1 to passage 2 to show the direction. Real training moves the numbers in small steps, over many questions.

After training

0.3×0.2 + 0.6×0.9 + 0.1×0.1 = 0.61

The loss is now −ln 0.61 = 0.49. The generator did not change in this example. Only the passage chances did.

The paper trains the question model and BART, and keeps the passage model and index frozen. That reconciles with the paper’s parameter count: two BERT-base models of about 110 million parameters each, plus BART’s 406 million, give 626 million, our sum. Of those, the frozen passage model’s 110 million are not trained. During training, each question retrieves 5 or 10 passages, and the authors saw no significant difference between them. At test time they retrieve more: 15 passages for RAG-Token and 50 for RAG-Sequence on question answering.

Joint training can also fail. For story writing, the authors report in an appendix that the retriever : it learned to return the same passages for every input, the generator learned to ignore them, and the model matched plain BART. They suspect that tasks with less need for facts, or long outputs, give the retriever too weak a signal. An earlier system, REALM (Guu and colleagues, 2020), trained a retriever and a language model together during pre-training, which is training on large amounts of text before a model is adapted to a task. REALM could “retrieve” an empty passage when nothing useful exists. The RAG authors tried the same and found no gain.

What the experiments showed

The paper tests on open-domain question answering (four sets, among them Natural Questions and TriviaQA), Jeopardy clue writing, answer writing, and fact checking. Numbers are from the final version of the paper on arXiv, which differs a little from the first version: the first reported 56.1 for RAG-Sequence on TriviaQA, and the final reports 56.8.

Model Natural Questions TriviaQA WebQuestions CuratedTrec
T5-11B, closed-book 34.5 not scored 37.4 not scored
REALM 40.4 not scored 40.7 46.8
DPR 41.5 57.9 41.1 50.6
RAG-Token 44.1 55.2 45.5 50.0
RAG-Sequence 44.5 56.8 45.2 52.2

Scores are exact match on the test sets. WebQuestions and CuratedTrec are two smaller question sets of the same kind. TriviaQA has two test splits, and the table shows the standard one.

  • Better than closed-book with far fewer parameters. RAG-Sequence beats T5-11B by 44.5 − 34.5 = 10.0 points on Natural Questions. At 626 million parameters against 11 billion, RAG is about 18 times smaller (our arithmetic), or more if you leave out the frozen passage model.
  • No second model or copying step needed. DPR’s own system used a , a second model that re-scores the top results more carefully, and an extractive reader. The paper says: “RAG demonstrates that neither a re-ranker nor extractive reader is necessary for state-of-the-art performance.”
  • Right answers without the passage. On Natural Questions, RAG answered 11.8% of questions correctly even when the answer was in none of the retrieved passages. An extractive reader would score 0% there, because it can only copy.
  • More factual. In a human check of 452 pairs of Jeopardy clues, evaluators judged RAG more factual than BART in 42.7% of cases and BART more factual in 7.1%. In the rest, 11.7% were good from both, 17.7% were poor from both and in 20.8% evaluators could not agree.
  • Learned retrieval helps. These runs used the dev set, held-out questions used to compare variants before the final test. Freezing the retriever dropped Natural Questions exact match for RAG-Sequence from 44.0 to 41.2. Replacing it with BM25, a keyword scoring method, dropped it to 31.8. For FEVER, a fact-checking set where the model labels a claim as true, false or not enough information, BM25 was best: 75.1 accuracy against 74.5 for learned retrieval on the three-way labelling. The authors think FEVER claims are full of names, which keyword overlap handles well.
  • Retrieval finds the right pages. For FEVER, the top retrieved page came from a gold article, one the dataset marks as holding the evidence, in 71% of cases, and a gold article appeared in the top 10 in 90%. This is a hit rate: the share of questions where a right result shows up in the first few. The retrieval metrics calculator shows how hit rate and related measures move as results change places.
  • More passages helps, up to a point. For Natural Questions, the paper’s test of retrieving more passages found accuracy kept improving for RAG-Sequence, but peaked at 10 passages for RAG-Token. The main results use 15 for RAG-Token anyway, as set out above.

One experiment shows the point of a second memory. The authors built a second index from a December 2016 copy of Wikipedia and asked “Who is the President of Peru?” style questions about 82 world leaders who had changed between 2016 and 2018. With the 2016 index, 70% of answers were right for 2016 leaders. With the 2018 index, 68% were right for 2018 leaders. With the wrong index for the year, the scores fell to 12% (2018 index, 2016 leaders) and 4% (2016 index, 2018 leaders). The model had not been retrained. Only the index was swapped.

What held up and what changed

Several parts of the paper hold today. Some were overtaken. The name itself drifted.

What held up

  • Two memories. Keeping facts in a text collection and swapping it without retraining is the main reason people use RAG. The index swap above is still the plainest argument for it.
  • A frozen passage side. The paper’s reason for keeping it, that training the passage model means re-encoding everything, still applies. REALM did refresh its index during training, every several hundred training steps, in a separate process, and needed that extra machinery to do it. We have not surveyed production systems, but the setups in the sources below all use their retrieval models as they come.
  • Dense retrieval beats keywords on many tasks. DPR found its dense retriever beat a strong BM25 system by 9% to 19% absolute in top-20 accuracy, which is the share of questions where a right passage is in the top 20. On Natural Questions, that was 78.4% against 59.1%. The FEVER result above is the counter-case, and it matters in practice.
  • Joint training can fail. The collapse the appendix describes is a real risk. The prompt-based pipelines in the sources below skip joint training altogether.

What changed

  • Frozen models took over. In 2023, Ram and colleagues (In-Context RALM) put retrieved documents in front of the input of a language model without changing the model at all, using off-the-shelf retrievers, and found “surprisingly large” gains. This is the pattern most people mean by RAG now: search, paste the passages into the prompt, and ask. It works through an API, with no training at all. The paper’s version trains two models.
The paper trains the question side of the search and the generator together. Most apps today train neither and only change the search index.
  • Reading all passages together beat reading one at a time. (Izacard and Grave, 2020) encoded each passage separately but let the decoder look at all of them at once, using 100 passages. Its large model scored 51.4 on Natural Questions and 67.6 on TriviaQA, against 44.5 and 56.1 for RAG-Sequence in its comparison table, which quotes the paper’s first version. RAG’s state-of-the-art claim was overtaken within months. Putting several passages into one prompt is the same idea in a new form.
  • Joint training came back, at scale. Atlas (Izacard and colleagues, 2022) pre-trained the retriever and the language model together. With 11 billion parameters and only 64 training examples (what is called few-shot learning), it scored 42.4 on Natural Questions, beating the 540-billion-parameter PaLM by almost 3 points. So the paper’s core idea is not dead. It needs far more engineering than a prompt.
  • More passages is not always better. The RAG paper already saw RAG-Token peak at 10 retrieved passages. Liu and colleagues (2023) found that models do worse when the useful passage is in the middle of a long input than at the start or the end, a U-shaped curve. Where you put passages matters, not only how many.
  • Better search became the main lever. Today’s pipelines rarely use one retriever. They combine keyword search (BM25) with embedding search, called , then re-score the top results with a reranker. means cutting documents into pieces small enough to search, a decision the paper settled once with 100-word passages. The chunk splitter shows what different sizes do to a text. Anthropic’s 2024 write-up of contextual retrieval adds a short note to each chunk saying where it sits in its document, before the chunk is indexed. On its own test sets, the share of questions where the right chunk was missing from the top 20 fell from 5.7% to 2.9% when it combined that with embeddings and BM25, and to 1.9% with a reranker. These are the vendor’s numbers on its own data, not an independent test.
  • Fewer claims about hallucination. The paper says RAG models “hallucinate less”, based on its own human check. Passing retrieved text to a model lowers the chance of a made-up answer but does not remove it, since the model can still ignore or misread a passage. Measure the retrieval step and the answer step separately.

The paper’s results on specific benchmarks have not been the thing that lasted. The pattern did: keep knowledge outside the model, find it by meaning, and let the model write the answer from it.

References

About the paper

Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks by Lewis, Perez, Piktus, Petroni, Karpukhin, Goyal, Küttler, Lewis, Yih, Rocktäschel, Riedel and Kiela, NeurIPS 2020.

Read the original paper

More AI engineering papers

All papers