Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

~8 min readNeurIPS 2020

Retrieval-Augmented
Generation, explained.

A language model is a brilliant student who took a closed-book exam on the entire internet — and now answers everything from memory, blurring details and inventing the rest. This 2020 paper handed that student a library card: retrieve the right pages first, then answer. It's the idea behind every "chat with your docs" product you've used.

The delta

What changes against retrieval alone: the retrieved text is generated from

Rungs 1 to 7 find documents. A user with a question then has to read them. And a language model asked the same question answers from its parameters, which is a fixed, undated, unattributable store — it cannot be updated without training, and it cannot say where anything came from.

The change is to wire the two together and train them as one system: retrieve passages with a dense retriever, condition a generator on the question and the retrieved text, and treat the retrieved document as a latent variable — so the generator's loss propagates back into the retriever, teaching it to fetch what actually helps generation rather than what looks similar to the question.

The property that follows is the one the whole industry took: the model's knowledge lives in an index you can edit. Swap a document and the answer changes with no gradient step; the answer can cite the passage it came from; and a claim can be checked against a source. That is a different kind of system from one that has memorised, and it is why this rung is the architecture behind essentially every deployed question-answering product. The paper also distinguishes marginalising over documents once per sequence from doing it per token — the latter lets a single answer draw on several passages, which matters exactly where one passage does not contain the whole answer.

01

The closed-book problem

By 2020, large language models could answer trivia surprisingly well — from memory alone. All their knowledge was crammed into their weights during training, a process the authors call parametric memory. Impressive, but it has three deep flaws.

It's lossy: facts get blurred into a statistical haze, so the model confidently makes things up — hallucinates. It's frozen: to teach it something new, or fix a wrong fact, you have to retrain. And it's opaque: it can't tell you where an answer came from, because there is no "where" — just a fog of weights.

02

The big idea: give it a library card

The paper's fix is elegant: don't force the model to memorize everything. Pair it with a searchable external collection — the authors used all of Wikipedia — that it can look things up in on demand. They call this searchable index non-parametric memory.

Now answering a question becomes two steps instead of one: retrieve the most relevant documents, then generate an answer grounded in them. The model no longer has to be the encyclopedia; it just has to know how to read one.

The RAG loop
Query→ Retriever→ Top-k docs→ Generator→ Grounded answer
03

The retriever: matching on meaning

Old-school search matched keywords — miss the exact word and you miss the document. RAG uses dense retrieval (DPR): a neural encoder turns the query into a vector and every document into a vector, and "relevant" simply means "close in vector space." Ask about "the capital of France" and it finds the passage about Paris even if the word "capital" never appears.

All of Wikipedia is pre-encoded once into a vector index. At query time, the retriever encodes the question and pulls the top-k nearest passages — a handful of the most relevant pages, in milliseconds.

Worth knowing

This vector-search step is exactly what a vector database does today. The RAG paper is why "embed your documents, then do nearest-neighbor search" became the backbone of modern AI applications.

04

The generator: answer from evidence

The retrieved passages are handed to a generator — a sequence-to-sequence model (BART in the paper) — alongside the original question. The generator writes its answer conditioned on that evidence, effectively reading the passages and composing a response instead of dredging one up from memory.

Crucially, the query encoder and generator are trained together. The generator's success signal flows back and teaches the query side of the retriever what "relevant" really means for producing good answers. (The document encoder and its index stay frozen.)

05

RAG-Sequence vs RAG-Token

The paper offers two flavors. RAG-Sequence commits to one set of retrieved documents and writes the entire answer from them — simple and coherent. RAG-Token is more fluid: it can lean on a different document for each token it generates, so a single answer can stitch together facts from several sources.

Ask "Where were these two authors born?" and RAG-Token can pull one author's birthplace from one passage and the other's from another, mid-sentence. More flexible. (RAG-Token is actually the cheaper one to decode; RAG-Sequence needs a beam search per document.)

The difference is exactly where the sum over documents sits. Both marginalize over the retrieved set z, but RAG-Sequence sums outside the product over answer tokens; RAG-Token sums inside:

That placement is the whole story. RAG-Sequence forces one document to account for every token, so an answer whose facts are split across two passages is penalized. RAG-Token lets each token pick its own document, so the split answer stays likely. The runnable version below puts numbers on the two-authors case — RAG-Token scores it ~2.8× higher.

How it works

How RAG retrieves, generates and trains, step by step

Retrieval-Augmented Generation (Lewis, Perez, Piktus, Petroni, Karpukhin, Goyal and colleagues, NeurIPS 2020) joins a pretrained retriever to a pretrained generator and fine-tunes them on each downstream task, without ever telling the model which document to retrieve. Two decisions define it: which parts are trained, and where the sum over documents sits.

x query encoder BERT-base document index frozen, 21M chunks q(x) top k by inner product z1: 0.6 z2: 0.3 z3: 0.1 p(z|x), top k BART-large one run per z Σ over z y sequence: sum per answer token: sum per token gradient: query encoder and BART only
RAG at training time. Accent boxes are fine-tuned — the query encoder and BART — while the document encoder and its index stay frozen. The loss is taken after summing over the top k documents, so its gradient reaches retrieval only through the document probabilities p(z|x).
  1. Build the non-parametric memory once. Take the December 2018 Wikipedia dump, split it into disjoint 100-word chunks — 21 million documents — and encode each with DPR's document encoder, a BERT-base model, into a 768-dimensional vector held in a FAISS index with an HNSW approximation for fast maximum-inner-product search.
  2. Encode the query. DPR's query encoder, also BERT-base, maps the input x to q(x). The retriever's distribution is pη(z | x) ∝ exp(d(z) · q(x)), taken over the top k documents the index returns. Both encoders start from the DPR model trained on Natural Questions and TriviaQA.
  3. Generate once per document. For each of the k retrieved documents z, the generator — BART-large, about 400 million parameters — reads the input and the document concatenated and produces token probabilities pθ(yi | x, z, y1:i−1). That is k forward passes, run as a batch.
  4. Marginalise. RAG-Sequence weights each document's whole-answer probability by pη(z | x) and sums; RAG-Token does the same sum separately at every token, so each token can lean on a different document.
  5. Train on input-output pairs only. Minimise the negative marginal log-likelihood of the target with Adam, using k = 5 or 10 documents. The gradient reaches the query encoder through pη(z | x) and the generator directly. The document encoder and the index stay frozen: updating them would mean re-encoding 21 million passages as training goes, as REALM does during pretraining, and the authors found that unnecessary for strong results.
  6. Decode RAG-Token with ordinary beam search. Its next-token distribution is already a single mixture, Σz pη(z | x) · pθ(yi | x, z, y1:i−1), so a standard beam decoder runs on it unchanged.
  7. Decode RAG-Sequence per document. Its likelihood does not split into per-token terms, so beam search runs once per retrieved document, each hypothesis scored with that document alone, and the union of hypotheses is then rescored. Thorough Decoding runs extra forward passes so every hypothesis is scored under every document; Fast Decoding treats a hypothesis that never appeared in a document's beam as having near-zero probability there and skips those passes.
  8. Swap the index at will. Because the memory is only an index of vectors made by a frozen encoder, it can be rebuilt from a newer dump and plugged in without retraining the query encoder or BART.

The parameter count shows the bargain: two 110-million-parameter BERT encoders and a 406-million-parameter BART, about 626 million in all, against 11 billion for the largest closed-book T5 it was compared with. The rest of the knowledge sits in 21 million vectors that cost nothing to train.

The math

The RAG training objective and what its gradient does

pη(z | x) = exp(d(z) · q(x)) / Σz′ ∈ top-k exp(d(z′) · q(x))
L = Σj −log p(yj | xj), p(y | x) = Σz ∈ top-k pη(z | x) · pθ(y | x, z) (RAG-Sequence)
∇q log p(y | x) = Σz [ p(z | x, y) − pη(z | x) ] · d(z), p(z | x, y) ∝ pη(z | x) · pθ(y | x, z)
  • d(z), q(x) — document and query vectors from DPR's two BERT encoders; d(z) is fixed, q(x) is trained.
  • pη(z | x) — the retriever's prior over the k retrieved documents.
  • pθ(y | x, z) — BART's probability of the whole target given the input and one document.
  • p(z | x, y) — the posterior: the share of the target's likelihood that document z explains.

The gradient line is derived here from the paper's loss by differentiating through the softmax, and it says what training does to retrieval. The query vector moves toward documents whose posterior share exceeds their prior share — documents that made the right answer more likely than the retriever expected — and away from the rest. No document label is ever needed. At the extremes: with k = 1 the prior is always 1, the bracket is zero, the retriever gets no gradient, and RAG-Sequence and RAG-Token become the same model; and if every retrieved document explains the answer equally well, the bracket is again zero and retrieval is left alone.

The evidence

What RAG scored, and what the ablations showed

RAG was fine-tuned separately for each task with 5 or 10 retrieved documents and evaluated on open-domain question answering by exact match, abstractive answers on MS MARCO, Jeopardy question generation and FEVER fact verification. Baselines were closed-book T5, the retrieve-and-read systems REALM and DPR, and BART fine-tuned without retrieval.

Model, exact matchNatural QuestionsWebQuestionsCuratedTrec
T5-11B + SSM, closed-book36.644.7—
REALM40.440.746.8
DPR, extractive reader41.541.150.6
RAG-Token44.145.550.0
RAG-Sequence44.545.252.2

That is a new state of the art on three open-domain sets; on TriviaQA's standard open test split the best DPR pipeline stayed slightly ahead, 57.9 to 56.8. Generation also earned its keep: RAG produced a correct answer for 11.8% of Natural Questions cases where no retrieved document contained it, which an extractive reader cannot do. On FEVER, with no supervision about which evidence to retrieve, it reached 72.5% three-way accuracy against 76.8% for pipeline systems trained with intermediate retrieval supervision. On Jeopardy questions, human judges found RAG more factual than BART in 42.7% of comparisons and BART more factual in 7.1%.

The ablations are informative. Swapping the learned retriever for BM25 cost a lot on question answering but was slightly better on FEVER, whose claims are entity-heavy enough for word overlap to work; freezing the retriever was worse than learning it on every task. Retrieving more documents at test time kept helping RAG-Sequence on question answering, while RAG-Token peaked at 10. And the index swap: on questions about world leaders who changed between 2016 and 2018, the model answered 70% correctly with a 2016 index for 2016 leaders and 68% with a 2018 index for 2018 leaders, but only 12% and 4% with the indexes mismatched — the knowledge followed the index, with no retraining.

Since then

What the authors admit, and what happened next

The reduction in fabrication is partial and not a guarantee, which the paper is careful about and the marketing was not. Grounding a generator in retrieved text makes it more likely to say what the text says; nothing forces it to. A model can still misread a passage, blend it with parametric knowledge, or produce a citation that does not support the sentence attached to it — and that last failure is worse than an uncited error, because it comes with a credential.

The system also inherits every weakness of its retriever. If the passage is not retrieved the answer cannot be grounded in it, and the retriever's out-of-domain fragility from rung 6 becomes the whole system's fragility. In practice most disappointing deployments of this architecture are retrieval failures wearing a generation costume.

How it held up: it is the default architecture for putting a language model on top of a corpus, and the reason the vector-database industry exists. What changed is that the joint training this paper introduced is mostly not done any more — the common deployment is an off-the-shelf retriever and an off-the-shelf model glued by a prompt, which is simpler and gives up the paper's most interesting mechanism. And the top-k framing has a structural limit that rung 9 names: some questions are not answered by any k passages.

SOLVE IT YOURSELF

Where RAG-Sequence and RAG-Token split

Retrieval is an inner-product top-k with a softmax prior; the two marginalizations are three lines each. The demo is the paper's own "where were these two authors born?" case: doc A knows author one's birthplace, doc B knows author two's, neither knows both. RAG-Sequence — which makes a single document explain the whole answer — scores it 0.09; RAG-Token, free to switch documents per token, scores it 0.25, about 2.8× higher. That gap is the reason RAG-Token exists. Change the per-document token probabilities and watch which scheme wins.

YOUR TASK

Write the body of rag_sequence. Everything else in the file is already written; this is the function the paper is about. Press ▶ Run to check it against the 5 assertions below — they start red.

WHAT IT HAS TO SATISFY — 5 ASSERTIONS
  1. Softmax is a valid distribution
  2. Retrieve picks the k highest inner products
  3. RAG-Sequence marginalizes whole sequences
  4. RAG-Token marginalizes per token
  5. Split-fact answers favor RAG-Token
CPython · WebAssembly
07

Why it still matters

Every "chat with your PDF," every enterprise knowledge assistant, every AI search box that cites its sources is a descendant of this paper. The specific models have changed — bigger generators, better embedding models, hybrid keyword-plus-vector retrieval, re-rankers, agentic multi-hop retrieval — but the core loop is unchanged: retrieve, then generate.

RAG reframed knowledge as something a model looks up rather than something it is. That separation — reasoning in the weights, facts in an index you control — is the single most important pattern in applied AI today.

Worth knowing

Building a RAG system today means choosing an embedding model, a vector database, a chunking strategy, and a re-ranker — then evaluating retrieval quality. Every one of those decisions traces back to the two-step loop this paper introduced.

Questions

Questions people ask about Retrieval-Augmented Generation

How is the RAG retriever trained without labels for which document to retrieve?

RAG treats the retrieved document as a latent variable. For each training input it retrieves the top 5 or 10 passages, asks BART for the probability of the target output given each passage, weights those probabilities by the retriever's own probability for each passage, and sums them. The loss is the negative log of that sum. Differentiating it pushes the query encoder toward passages that made the correct output more likely than the retriever expected and away from passages that did not, so the retriever learns what is useful for generation from input-output pairs alone. Only the query encoder learns this way; the document encoder and the 21-million-passage index stay fixed from DPR. In the paper's ablation, the learned retriever beat a frozen one on every task.

Which parts of RAG are fine-tuned and which stay frozen?

Two parts are fine-tuned: the query encoder, a BERT-base model from DPR, and the generator, BART-large. The document encoder, also BERT-base from DPR, and the index it produced over 21 million 100-word Wikipedia chunks stay frozen. The authors chose this because updating the document encoder would change every document vector, forcing the index to be rebuilt periodically during training as REALM does during pretraining, and they found that step unnecessary for strong results. The consequence is that relevance is learned only on the query side: the model learns to ask better questions of a fixed index, but cannot re-describe the documents. A frozen index is also what makes index swapping possible, since a new index built by the same encoder drops straight in.

How does decoding differ between RAG-Sequence and RAG-Token?

RAG-Token's probability for each next token is a single mixture over the retrieved documents, so it can be decoded with an ordinary beam search, exactly like a normal sequence-to-sequence model. RAG-Sequence cannot, because its likelihood sums whole-answer probabilities over documents and does not split into per-token terms. Instead it runs a separate beam search for each retrieved document, collects all the hypotheses, and scores each one under every document. Thorough Decoding runs the extra forward passes needed to score hypotheses under documents whose beams did not produce them; Fast Decoding treats those probabilities as roughly zero and skips the passes, which matters for long outputs. So RAG-Sequence is the more expensive of the two to decode, while RAG-Token is the one that can stitch facts from different documents into one answer.

How many documents does RAG retrieve, and does retrieving more help?

During fine-tuning the paper used 5 or 10 retrieved documents, and at test time it varied the number up to 50. For open-domain question answering, retrieving more documents kept improving RAG-Sequence, while RAG-Token peaked at around 10. For MS MARCO abstractive answers, more documents raised RAG-Token's Rouge-L at the cost of its Bleu-1, with a smaller effect on RAG-Sequence. Each extra document costs one more generator pass, since BART reads every retrieved passage separately, so the number of documents trades quality directly against compute. In today's prompt-based RAG systems the analogous choice is how many chunks to put in one context, with an extra risk RAG's separate passes avoided: relevant text placed in the middle of a long context tends to be used less, an effect Liu and colleagues called lost in the middle.

Does RAG stop a language model from hallucinating?

It reduces fabrication but does not stop it. In the RAG paper, human judges comparing Jeopardy questions written by RAG and by BART without retrieval found RAG more factual in 42.7% of cases and BART in only 7.1%, and they also rated RAG's outputs more specific. But nothing in the architecture forces the generator to copy what it retrieved. It can misread a passage, blend it with what is stored in its weights, or give an answer that no retrieved passage supports; the paper even counts this as a strength in one case, generating correct answers for 11.8% of Natural Questions examples where no retrieved document contained the answer. And if retrieval fails, the answer cannot be grounded at all. Grounding makes errors rarer and easier to check, not impossible.

What happens if you swap RAG's document index?

The model's knowledge changes with no retraining. The RAG paper built a second index from a December 2016 Wikipedia dump and tested both indexes on questions about world leaders who changed between 2016 and 2018, asked from a template such as who is the President of Peru. With the 2016 index the model answered 70% of questions about 2016 leaders correctly, and with the 2018 index 68% of questions about 2018 leaders. With the indexes mismatched, accuracy fell to 12% and 4%. The generator had learned to read whatever the retriever returned, so the facts followed the index. This works because the document encoder was frozen during training: any index built with the same encoder is compatible with the trained query encoder and generator.

Check yourself

4 questions to test what you just read

Work each one out before you open it — a number, a prediction or a reason, not a definition. Producing the answer is what makes it stick. Your progress is kept on this device.

Two retrieved documents have prior 0.6 and 0.4. For a two-token answer, document A gives token probabilities 0.8 then 0.2, and document B gives 0.2 then 0.8. What is p(y|x) under RAG-Sequence and under RAG-Token?

Show answer

Sequence: 0.6 × (0.8 × 0.2) + 0.4 × (0.2 × 0.8) = 0.096 + 0.064 = 0.16. Token: (0.6·0.8 + 0.4·0.2) × (0.6·0.2 + 0.4·0.8) = 0.56 × 0.44 = 0.246. RAG-Token rates the split answer about 1.5× higher because each token may lean on a different document.

In that example, what is document A's posterior p(z | x, y) under RAG-Sequence, and which way does training move the query vector?

Show answer

Both documents give the whole answer the same probability, 0.16, so the posterior is 0.6 × 0.16 / 0.16 = 0.6 — equal to the prior. The bracket p(z | x, y) − pη(z | x) is 0 for both documents, so the retriever gets no gradient: neither explains the answer better than expected.

If training RAG's document encoder forced the whole index to be re-encoded, roughly what would one refresh cost, and why does freezing it avoid that?

Show answer

Any update to the document encoder changes all 21 million document vectors, so the index would have to be rebuilt to stay consistent. At DPR’s reported pace — about 8.8 hours on 8 GPUs for the same 21 million passages — each refresh costs roughly 70 GPU-hours, plus building the index. Freezing it lets RAG train only the query side.

With k = 1, what is the difference between RAG-Sequence and RAG-Token, and what does the retriever learn?

Show answer

There is no difference: with one document the sum has a single term, so the sum-of-products and the product-of-sums are the same number. And pη(z | x), normalised over one document, is always 1, so the retriever receives no gradient — it needs at least two candidates to learn which is better.

Where this sits

From a word vector to RAG

The longest ladder here, and the most linear: nine papers that carry one idea — text as geometry — from a 2013 word embedding to a graph-structured retrieval system.

  1. 1Word2Vec2013
  2. 2GloVe2014
  3. 3Sentence-BERT2019
  4. 4Product Quantization2011
  5. 5HNSW2016
  6. 6Dense Passage Retrieval2020
  7. 7ColBERT2020
  8. 8Retrieval-Augmented Generation2020
  9. 9GraphRAG2024

All 110 papers, in 19 ladders →

Finished this one? 0 / 110 Paper Breakdowns done
NextGraphRAG Next on the “From a word vector to RAG” ladder · rung 9 of 9

This idea in other formats

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Paper Breakdowns