Papers · 2020 · Reading: 19 min, plus 1 in closed details · +4h 10m of resources.
Paper · NeurIPS 2020 · arXiv 2005.11401

Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (RAG)

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
Facebook AI Research; University College London; New York University · May 2020 (arXiv v1, 22 May 2020); v4 April 2021; published at NeurIPS 2020

In one line: Coined RAG: a DPR retriever and a BART generator fine-tuned jointly (query encoder and generator; the document encoder and index stay fixed), the retrieved documents treated as a latent variable and marginalised (RAG-Sequence against RAG-Token); state of the art on three of four open-domain QA sets (Natural Questions, WebQuestions, CuratedTrec), and knowledge updated by swapping the index, not the weights.

44.5 exact match
Natural Questions, RAG-Sequence
against 41.5 for DPR's extract-and-rerank pipeline and 36.6 for closed-book T5-11B+SSM · Table 1
70% vs 12% of 82 leaders
the same model, two indexes
2016 leaders answered with a 2016 index, against the 2018 index: knowledge updated with no retraining · §4.5, hot-swapping
42.7% vs 7.1% of 452 pairs
judged more factual, RAG against BART
human evaluation of Jeopardy question generation · Table 4

How far to trust it: Believe the mechanism, the hot-swap and the factuality gain; of the four open-domain QA "state of the art" claims two are clear (Natural Questions by about 2.6 standard errors, TriviaQA-Wiki) and two sit inside the noise (WebQuestions, CuratedTrec), and every result is one run. The evidence, judged.

The idea in one sentence

Treat the retrieved Wikipedia passage as a hidden variable: a dense retriever picks the top k of 21M passages, a seq2seq generator writes the answer conditioned on each, the output sums over them weighted by the retriever, and the generation loss alone trains the query encoder, so knowledge lives in an index you can read and replace rather than only in weights.

Two memories in one model: a frozen passage index to read, a generator's weights to remember, and one loss that trains the query side. The paper's Figure 1 as a 3D stage, run by this page's trained toy RAG-Token on one held-out question:

  1. The question meets the query encoder. A question about a held-out country (its facts were never a training answer) goes through the query encoder q(x), BERTq in the paper (orange glass: fine-tuned). In the toy the encoder is one learned weight per token, the signed bars, plus syllable-pair features.
  2. Maximum inner product search. q(x) is scored against d(z) for every document of the index (teal glass: embedded once by the document encoder, then frozen): 21M Wikipedia chunks in the paper, toy documents here. The five best light up.
  3. The top 5 and their weights. The five leave the index with their prior p(z|x), the softmax of their five scores (blue bars); the top one carries of it.
  4. The generator reads each document. The generator (purple glass: fine-tuned; BART-large in the paper) reads each document concatenated with the question, z // x: five passes, one per document.
  5. Marginalise. RAG-Token mixes the five next-token distributions weighted by p(z|x) at every token (each stream is as dense as its weight) and writes . RAG-Sequence sums once per answer instead: Two marginalisations.
  6. Training: one loss, two trained parts. The loss −log p(y|x) sends a gradient back into the generator and, through p(z|x), into the query encoder (the red streams: the gradient's path, not its values). The document encoder and the index get none, so the index is never rebuilt during training (§2.4).

Redrawn from Figure 1 (the arXiv paper is not CC BY, so no copy of the original). The query encoder and the generator are fine-tuned; the document encoder and the index stay fixed (§2.4). The example question and the five documents in the boxes are from this page's toy model (see Ask a trained toy RAG), not from the paper.

You need nothing beyond a seq2seq Transformer and dot-product retrieval; how retrieval is built today is mapped on Topic: rag-and-retrieval.

New terms. Parametric memory: what the generator's weights store. Non-parametric memory: the passage index, readable and replaceable. Latent document: the passage the answer depends on, never labelled, summed over. RAG-Sequence and RAG-Token: one passage for the whole answer, or a new mixture at every token. MIPS: maximum inner product search, the top k by dot product. Hot-swapping: replacing the index at test time without retraining.

Problem

§1 Introduction

By 2020, pretrained language models demonstrably stored facts in their parameters (GPT-2, T5): T5 fine-tuned to answer with no documents, "closed-book", was competitive with retrieval systems (Roberts et al. 2020). But parametric knowledge has three structural flaws (§1):

  • It cannot be inspected: no provenance for why the model said something, and "hallucinations".
  • It cannot be updated without retraining: the world changes, the weights do not.
  • It runs out on knowledge-intensive tasks, "tasks that humans could not reasonably be expected to perform without access to an external knowledge source", where task-specific retrieve-and-extract pipelines still beat general seq2seq models (abstract).

Hybrid parametric plus non-parametric models existed. REALM and ORQA combine a masked language model with a differentiable retriever, but they "have only explored open-domain extractive question answering": they point at a span of a retrieved passage, they do not generate (§1).

The gap: a general-purpose fine-tuning recipe that gives any pretrained seq2seq generator a differentiable, non-parametric memory, applicable to the whole range of generation and classification tasks, with both memories pretrained and pre-loaded with knowledge.

Idea: two memories, one probabilistic model

Figure 1, §2

RAG treats the retrieved document as a latent variable in a probabilistic seq2seq model and trains retriever and generator jointly, end to end, with no supervision on which document to retrieve (§2, §2.4). The paper names the two halves: the generator's weights are the parametric memory, the dense vector index of Wikipedia is the non-parametric memory (§2.2, §2.3). The hero figure above is the paper's Figure 1.

Retriever and generator

§2.2, §2.3, §3

Retriever: DPR. pη(z|x) is DPR, a bi-encoder of two BERT-base networks (§2.2):

pη(z|x) ∝ exp(d(z)⊤q(x)), d(z) = BERTd(z), q(x) = BERTq(x)

The top k by this score is a Maximum Inner Product Search (MIPS), solved approximately in sub-linear time. The memory is the December 2018 Wikipedia dump split into disjoint 100-word chunks, 21M documents (about 2.1 billion words), embedded once into a FAISS index with a Hierarchical Navigable Small World (HNSW) approximation (§3; how HNSW works is on Vector indexes, how bi-encoders are trained on Embedding models). The retriever starts from DPR's bi-encoder, which "was trained to retrieve documents which contain answers to TriviaQA questions and Natural Questions" (§2.2): RAG's own training uses no retrieval labels, but its starting point did.

Generator: BART. pθ(yi|x, z, y1:i−1) could be any encoder-decoder; the paper uses BART-large, a denoising-pretrained seq2seq Transformer of "400M parameters" (§2.3; 406M in Appendix G). Input x and passage z are "simply" concatenated.

Two marginalisations

§2.1 Models

The evidence document is never observed, so the output sums over the top k documents, weighted by the retriever, in two ways (§2.1):

  • RAG-Sequence: one document is responsible for the whole output. p(y|x) ≈ Σz ∈ top-k pη(z|x) Πi pθ(yi|x, z, y1:i−1) (equation 1). The same document conditions every token.
  • RAG-Token: each token can draw on a different document. p(y|x) ≈ Πi Σz ∈ top-k pη(z|x) pθ(yi|x, z, y1:i−1) (equation 2). The sum moves inside the product, so the generator can stitch an answer from several passages.

For classification (a target of length one, such as a FEVER label) the two are the same model.

The trained toy model on this page is asked "novels by " for an author it never saw in training. The answer is "first ... second ...", and each novel is named in a different document; both documents are retrieved. Which formulation gets both titles right?

    Computed in your browser by the trained toy models (details), k = 5; bar heights are probabilities, to scale. Decoding as §2.5: greedy on the mixture for RAG-Token, greedy per document plus Thorough Decoding for RAG-Sequence.

    Training and decoding

    §2.4, §2.5, Appendix A

    Training. Minimise the negative marginal log-likelihood Σj −log p(yj|xj) with Adam (§2.4). Only the query encoder BERTq and the BART generator are fine-tuned; the document encoder and the index stay frozen, because re-embedding and re-indexing 21M passages during training, as REALM does, is costly, and the authors "do not find this step necessary for strong performance". Retrieval is learned purely from the generation loss: the gradient reaches the query encoder only through the pη(z|x) weights, raising documents in proportion to how well they explain the target (a document's gradient is its posterior minus its prior; standard calculus, not stated in the paper). Training retrieves 5 or 10 documents, with no significant difference (§4.5).

    Decoding (§2.5). RAG-Token's per-token mixture plugs into a standard beam decoder. RAG-Sequence does not decompose per token, so the paper runs one beam search per document and scores each hypothesis with an extra forward pass for every document whose beam did not contain it ("Thorough Decoding"), or skips those passes by treating such hypotheses as having probability about zero ("Fast Decoding").

    The decoding settings actually used (Appendix A)

    QA uses greedy decoding, 15 documents for RAG-Token and 50 for RAG-Sequence with Thorough Decoding; MS-MARCO and Jeopardy use 10 documents, beam 4 and Fast Decoding (Appendix A).

    Tried and dropped: a null document; where retrieval collapsed

    Tried and dropped: a REALM-style "null document" for inputs with nothing useful to retrieve did not help (Appendix F; on MS-MARCO the model instead learned to retrieve a fixed set of documents for such questions). On some tasks, such as story generation, retrieval "collapsed" to the same documents for every input, after which RAG behaved like BART (Appendix H).

    Results

    §4 Results

    Six task families against one Wikipedia index; sizes in Table 7, every table rebuilt and recomputed in the tables tab.

    Open-domain QA (Table 1)

    RAG-Sequence reaches 44.5 exact match on Natural Questions against 41.5 for DPR's pipeline and 36.6 for closed-book T5-11B+SSM; TriviaQA 56.8 on the standard split and 68.0 on the Wikipedia test split T5 used; WebQuestions 45.5 (RAG-Token) and CuratedTrec 52.2 (RAG-Sequence). The text claims a new state of the art on all four, "only on the T5-comparable split for TQA" (§4.1); the abstract says three. A generator beats extractive readers on extractive tasks, without REALM's and T5+SSM's "salient span masking" pretraining and with no re-ranker: "neither a re-ranker nor extractive reader is necessary".

    On Natural Questions, when the correct answer appears in none of the retrieved documents, how often is RAG still right?

    Generation and classification (Table 2)

    • MS-MARCO NLG, with its gold passages dropped to make it open-domain (§3.2): RAG-Sequence beats BART by 2.6 BLEU-1 and 2.6 Rouge-L and "approaches" the gold-passage state of the art, still 5.7 and 9.0 behind; some questions ("What is the weather in Volcano, CA?") need the gold passages. RAG hallucinates less (Table 3: BART puts the middle ear "between the middle ear and the nose").
    • Jeopardy question generation, a new task: given "The World Cup", write a clue such as "In 1986 Mexico scored as the first country to host this international sports competition twice" (SearchQA splits, 100K, 14K and 27K; §3.3). On Q-BLEU-1, a BLEU that weights entities more, RAG-Token 22.2 beats RAG-Sequence 21.4 and BART 19.7; on plain BLEU-1 RAG-Sequence is below BART (14.7 against 15.1). Over 452 human-judged pairs, RAG was more factual in 42.7% and BART in 7.1%, and RAG more specific in 37.4% against 16.8% (Table 4). Figure 2 shows why RAG-Token can stitch: generating a clue for "Hemingway", the document posterior is high on the "The Sun Also Rises" document while generating "Sun" and on the "A Farewell to Arms" one for that title, then flattens after each title's first token: BART alone completes "The Sun" into "The Sun Also Rises", so the document steers the parametric memory (§4.3).
    • FEVER, labels as single tokens, trained from claim and label with no evidence supervision (§3.4): within 4.3 points of the 3-way state of the art (72.5 against 76.8), a pipeline trained with retrieval supervision, and within 2.7 of a 2-way RoBERTa classifier given the gold evidence sentence. The top retrieved document is from a gold article 71% of the time, a gold article is in the top 10 in 90% (§4.4).
    • Diversity: distinct trigrams are 53.8% (RAG-Sequence) and 46.8% (RAG-Token) against BART's 32.4% on Jeopardy, with no diversity-promoting decoding (Table 5).
    Human judges found RAG-Token more factual than BART six times as often (42.7% against 7.1% of pairs)

    Table 4 as printed, 452 pairs of Jeopardy questions. Factuality sums to 100.0%; specificity sums to 93.0%, so 7% of pairs are missing from the table (dashed; see How much of this to believe).

    Ablations (Table 6, dev sets)

    A frozen retriever is worse on every task (one tie), most on QA: WebQuestions drops 9.4 points for RAG-Token. BM25 scores as the logits of p(z|x) cost 8 to 20 points on QA but at most 1.0 on RAG-Token's generation metrics, and BM25 is best on FEVER (75.1 against 74.5), plausibly because FEVER claims are entity-centric (§4.5). More documents at test time (Figure 3) keep improving NQ for RAG-Sequence, while RAG-Token peaks at 10; on MS-MARCO they raise RAG-Token's Rouge-L at the expense of BLEU-1 (described, not redrawn: the figure prints no values).

    Index hot-swapping

    §4.5 Index hot-swapping

    Parametric-only models like T5 or BART need further training to change what they know. RAG's knowledge can be replaced at test time. The test (§4.5): build a second index from the DrQA Wikipedia dump of December 2016, list 82 world leaders who changed between the two dumps, and ask the NQ RAG model "Who is {position}?" (for example "Who is the President of Peru?") with each index.

    The same trained model, index swapped to the 2016 dump, asked about the leaders of 2016. How many does it get right?

    How much of this to believe

    §4, Tables 1, 2, 4, 6, Appendices D, G

    What holds up. Natural Questions has 3,611 test questions, so 44.5 against DPR's 41.5 is a 3.0-point lead against a standard error of about 1.2 (√(p(1 − p)/n) for each system, combined): about 2.6 standard errors. TriviaQA-Wiki's 7.5-point lead over T5-11B+SSM is far beyond plausible noise (the paper does not give that test set's size). FEVER's 10,000 test claims put its 4.3-point gap far outside a 0.45-point noise, and the hot-swap's 70% against 12% dwarfs its 5 points. The structure has held up best of all: every later retrieval-augmented system keeps the frozen index and retrieve-then-generate (Then and now).

    What to discount.

    • "State of the art on all four" is two clear wins. WebQuestions (2,033 test questions): 45.5 against T5-11B+SSM's 44.7, 0.8 points against a noise of 1.6 (0.5 standard errors). CuratedTrec (635): 52.2 against DPR's 50.6, 1.6 against 2.8 (0.6). On standard TriviaQA RAG is 1.1 below DPR. The clear wins are NQ and TQA-Wiki (recomputed).
    • Best of two per column. The headline takes RAG-Token's WebQuestions and RAG-Sequence's CuratedTrec numbers, and each model gets its own test-time k tuned on dev (15 against 50 documents, Appendix A).
    • "No retrieval supervision" is not a cold start, as the authors say themselves. The retriever starts from DPR, trained with retrieval labels on NQ and TriviaQA (§4.1); WebQuestions and CuratedTrec models start from the NQ model (§3.1); TriviaQA targets are filtered to answers found in the top 1,000 retrieved documents, and CuratedTrec's regex answers are resolved by retrieval (Appendix D). Stating this counts in their favour.
    • One run each, no error bars. The ablations are on dev sets, and several learned-against-frozen margins in Table 6 are under a point (RAG-Token 0.9, 0.3 and 0.0; RAG-Sequence 0.5 and 0.2), which a second seed could flip. The toy on this page, retrained with three seeds, moves by points on its own held-out set.
    • Baselines differ in knowledge access. MS-MARCO's and FEVER-2's state of the art read gold passages, which favours the baselines (fair to RAG); the BART baseline gets no retrieval, so the generation gains measure retrieval and marginalisation together.
    • A task and metric of the authors' own. Jeopardy generation and its Q-BLEU-1 are introduced here, and plain BLEU-1 ranks RAG-Sequence below BART.
    • Hot-swapping tests one template on one kind of fact. 82 "Who is {position}?" questions show the index steers answers; they do not measure how often parametric memory overrides a contradicting document, which later work found to be a real failure (Longpre et al. 2021, beyond the paper).
    Two bookkeeping slips: Table 4's sums and Appendix G's counts
    • The human-evaluation table does not add up. In Table 4 factuality sums to 100.0% but specificity to 93.0% (about 420 of the 452 pairs), and the text's "both factual in a further 17%" is the table's "Both poor" (17.7%), not "Both good" (11.7%) (§4.3). The 42.7% against 7.1% is too lopsided for this to matter.
    • Appendix slips. Appendix G counts "626M trainable parameters" as 110M + 110M + 406M, including the document encoder that is never trained (516M are), and gives the index as "21M 728 dimensional vectors" (15.3B values) where BERT-base's 768 gives 16.1B. Two references are off by one ("Table 2" for Table 1, "5" for Table 4).

    Verdict. Believe the mechanism, the hot-swap and the human-judged factuality gain, and the Natural Questions and TriviaQA-Wiki leads. Read "state of the art on all four" as two clear wins and two ties, and treat sub-point ablation differences as unproven: every number is one run.

    What it takes to use this

    Appendix C, Appendix G
    • Code and weights, Apache-2.0: the models in Hugging Face Transformers (RagSequenceForGeneration, RagTokenForGeneration, RagRetriever), fine-tuning scripts in transformers-research-projects/rag, NQ checkpoints facebook/rag-token-nq and facebook/rag-sequence-nq, and the index as the wiki_dpr dataset. The paper trained in Fairseq; the port "achieves equivalent performance" (Appendix C).
    • Hardware: mixed precision on 8 × 32 GB V100s, though training and inference "can be run on one GPU"; the index lives in CPU memory, about 100 GB, or 36 GB after FAISS compression (Appendix C). The 21M × 768 float32 vectors alone are 64.5 GB (derived).
    • When it pays off: short factual targets (QA, fact checking, question generation), a fixed corpus, and a generator you can fine-tune. It did not work where retrieval collapsed (story generation, Appendix H), and with a frozen API model the joint training is unavailable, which is why deployed RAG is the frozen pipeline below.

    Why it matters (beyond the paper)

    This paper coined "RAG", and what it proposed differs substantially from what the term now means. The original is a trained model, not a prompting pattern. Documents are latent variables, the likelihood marginalises over them, and the generation loss trains the query encoder end to end. Both marginalisations exist because the model must combine evidence probabilistically rather than just read it.

    Modern usage kept the name and the architecture diagram, and dropped the training. The dominant pattern since 2023: embed the query with an off-the-shelf embedding model, run approximate nearest-neighbour search in a vector database, concatenate the top-k chunks into the prompt of a frozen instruction-tuned LLM, generate. No marginalisation (the LLM attends over all chunks at once, closer to Fusion-in-Decoder than to RAG-Token), no gradient into the retriever, no joint objective; In-Context RALM names it: "prepending grounding documents to the input, without any further training of the LM". Why the shift: in-context learning got strong enough that concatenation works without fine-tuning, frontier LLMs are frozen behind APIs, and a pipeline you rebuild by re-chunking a document base is far simpler to run than co-training a retriever and a generator. The end-to-end idea survives in research descendants (REALM before it; FiD, RETRO and Atlas after, and REPLUG, which trains only the retriever from a frozen LM's likelihoods), while the deployed world runs the frozen version.

    What did survive is most of the paper: dense bi-encoder retrieval over chunked passages (DPR's BERT bi-encoder is the ancestor of every modern embedding model); fixed, roughly 100-word chunking into a searchable index; MIPS and approximate nearest-neighbour search as the retrieval primitive (FAISS then, dedicated vector databases now); grounding to reduce hallucination and give provenance; and the killer operational argument, update knowledge by updating the index, not the weights. The modern stack is this architecture with the learning removed and the engineering scaled up, and each part is taught on its own page: embedding models, vector indexes, chunking and the retrieval pipeline, rerankers, agentic retrieval and GraphRAG (the GraphRAG paper); the Gao et al. survey's Naive, Advanced and Modular RAG is the usual map, and the topic root draws the stages.

    For open-domain QA it also settled an argument of its moment: one general retrieve-and-generate recipe beat both closed-book giants (T5-11B has 11 billion trainable parameters against RAG's 516M trained; the closest-sized T5, T5-large at 770M, scores 28.9 on NQ, Appendix G) and specialised extractive pipelines, across four benchmarks, clearly on two.

    Connections

    • BERT: the DPR retriever is a pair of BERT-base encoders; retrieval embeddings remain BERT's main living habitat.
    • GPT-3: the same month's parametric-only counterpoint; ironically, GPT-3-style in-context learning is what let modern RAG drop this paper's end-to-end training.
    • ReAct: retrieval moved from a fixed pipeline step to a tool an agent decides to call; the road to agentic RAG.
    • T5: the closed-book baselines of Table 1 are T5 models.
    • Topic: rag-and-retrieval: this is the founding paper of the topic.