π RAG: Retrieval-Augmented Generation
RAG: Retrieval-Augmented Generation (Lewis et al., 2020)
A language model stores what it knows in its weights. The paper calls this parametric memory. It has three problems. It cannot be updated without retraining. It cannot cite where an answer came from. And when it does not know, it guesses fluently.
Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks adds a non-parametric memory, a searchable index of documents, and lets the model read from it before answering:
- A retriever (DPR, a BERT bi-encoder) embeds the question and fetches the top-$k$ passages from an index of 21 million 100-word Wikipedia chunks.
- A generator (BART-large) reads question + passage and writes the answer.
- The two are trained together, end to end, with the retrieved passage treated as a latent variable that is marginalised out.
This page builds the retrieval step by hand, works through the two ways the paper marginalises over passages, measures where simple retrieval fails, and shows why the index can be swapped without retraining anything.
helpers ready
1. An index to retrieve from
The real system indexes Wikipedia. Here the index is 16 short passages, about the papers in this series and a few distractors, so every score can be printed.
16 passages, vocabulary of 132 terms after removing stop words
2. Retrieval as a nearest-neighbour search
The paper's retriever scores a passage $z$ for a question $x$ with an inner product of two embeddings:
$$p_\eta(z \mid x) \propto \exp\big(\mathbf{d}(z)^\top \mathbf{q}(x)\big)$$
$\mathbf{d}$ and $\mathbf{q}$ are two BERT encoders. Because the score is a plain inner product, all 21M passage vectors can be computed once and searched with maximum inner product search (FAISS) in milliseconds.
The same structure works with a much simpler encoder: TF-IDF vectors, which are L2-normalised so the inner product is the cosine similarity. The cell below computes one score by hand and then ranks the whole index.
============================================================================== RETRIEVE FOR ONE QUESTION ============================================================================== Terms shared by the question and the 'lora' passage ------------------------------------------------------------------------------ low q = 0.4713 d = 0.3122 product = 0.1471 rank q = 0.4713 d = 0.3122 product = 0.1471 trains q = 0.3338 d = 0.2211 product = 0.0738 update q = 0.4713 d = 0.3122 product = 0.1471 weights q = 0.4713 d = 0.3122 product = 0.1471 sum = 0.6624 [PASS] by-hand sum == sparse inner product Ranking the whole index ------------------------------------------------------------------------------ 1. lora score 0.6624 LoRA freezes the pre-trained weights and trains a low-rank upd... 2. gan score 0.0877 A generative adversarial network trains a generator against a ... 3. bert score 0.0822 BERT masks fifteen percent of input tokens and trains a bidire... 4. gpt score 0.0704 GPT pre-trains a decoder on unlabelled books by predicting the... 5. transformer score 0.0000 The Transformer architecture relies entirely on attention and ... [PASS] top-1 is the LoRA passage
3. Measuring retrieval: recall@k
The generator can only use what the retriever hands it, so retrieval quality caps the whole system. The standard measure is recall@k: the fraction of questions whose gold passage is among the top $k$.
Ten questions with known answers. The last four are deliberately rephrased, sharing few or no content words with their passage. That is the case where term-matching fails, and it is why the paper uses a learned dense retriever.
============================================================================== RECALL@k OVER TEN QUESTIONS ============================================================================== rank 1 bert What does BERT mask during pre-training? rank 1 diffusion How do diffusion models corrupt their training data? rank 1 vit Which model splits an image into patches? rank 1 helsinki What is the capital of Finland? rank 1 football How long does a football match last? rank 1 gan Which network plays a minimax game between two players? rank 16 everest Where is the tallest peak on Earth? <- zero overlap rank 1 coffee Which seeds are roasted for a morning drink? rank 2 peft How can I adapt a huge network cheaply? <- missed at k=1 rank 11 rope How does a model know the order of words? <- zero overlap recall@1 = 0.70 recall@3 = 0.80 recall@5 = 0.80
Questions that reuse the passage's words are found at rank 1. "Where is the tallest peak on Earth?" shares no content word with "Mount Everest is the highest mountain above sea level", so its TF-IDF score is exactly zero. A dense retriever trained on questionβanswer pairs learns that tallest peak and highest mountain mean the same thing. That is the job of DPR (Karpukhin et al., 2020), which RAG uses and fine-tunes.
The animation lays the passages out in 2-D so that their distances roughly follow the cosine distances. The ranking itself is computed in the full 132-dimensional space.
4. Two ways to use $k$ passages
Retrieval returns $k$ passages, and the paper treats "which passage" as a hidden variable to be summed out. It defines two models.
RAG-Sequence picks one passage for the whole answer, then averages over passages:
$$p(y \mid x) = \sum_{z \in \text{top-}k} p_\eta(z \mid x) \prod_{i} p_\theta(y_i \mid x, z, y_{<i})$$
RAG-Token may switch passage at every token:
$$p(y \mid x) = \prod_{i} \sum_{z \in \text{top-}k} p_\eta(z \mid x)\, p_\theta(y_i \mid x, z, y_{<i})$$
The difference is whether the sum sits outside or inside the product. RAG-Token can assemble an answer from facts spread across several passages.
A worked example with 3 passages, a 3-word vocabulary and answers 2 tokens long. That is small enough to enumerate all 9 answers and check that each model is a proper probability distribution.
============================================================================== RAG-SEQUENCE vs RAG-TOKEN, ENUMERATED ============================================================================== answer RAG-Sequence RAG-Token Paris France 0.4402 0.4236 Lyon France 0.1924 0.2015 France France 0.1054 0.1129 Paris Paris 0.0686 0.0798 Paris Lyon 0.0652 0.0706 Lyon Paris 0.0457 0.0379 Lyon Lyon 0.0349 0.0336 France Paris 0.0247 0.0213 France Lyon 0.0229 0.0188 Checks ------------------------------------------------------------------------------ [PASS] RAG-Sequence probabilities sum to 1 [PASS] RAG-Token probabilities sum to 1 p_seq(Paris France) by hand = 0.6*0.80*0.80 + 0.3*0.20*0.75 + 0.1*0.34*0.33 = 0.4402 [PASS] matches the table
Both distributions are valid, and they disagree. The sequence model rewards answers that a single passage supports from start to finish: Paris France gets 0.440. The token model mixes passages at every position, so probability moves toward answers stitched together from different passages. Paris Paris and Paris Lyon both rise, and Paris France drops to 0.424. In the paper, RAG-Token did better on tasks that combine facts from several passages, and RAG-Sequence on some open-domain QA.
5. Training: no passage labels needed
Nobody labels which passage answers which question. RAG trains on (question, answer) pairs alone, maximising $\log p(y \mid x)$ with the marginalised formulas above. Gradients reach the query encoder through $p_\eta(z \mid x)$. If a passage helps generate the right answer, its score goes up. The paper keeps the document encoder and its index fixed. Re-encoding 21M passages after every update would be too expensive, and fine-tuning the query encoder alone was enough.
6. Hot-swapping the index
Because knowledge lives in the index rather than the weights, you can change what the model knows by changing the documents. The paper demonstrated this by swapping a 2016 Wikipedia index for a 2018 one: questions about world leaders were then answered according to the newer index, with no retraining. The cell below does the same thing at small scale.
============================================================================== SWAP THE INDEX, KEEP THE MODEL ============================================================================== original index top-3: python (0.267), transformer (0.176), rope (0.167) index + one new passage top-3: mamba (0.683), python (0.149), transformer (0.082) Before the swap nothing in the index answers the question, yet retrieval still returns 3 passages: 'python' ranks first only because it shares the word 'uses'. Top-k always returns k results, relevant or not. After the swap the new passage ranks first, and neither the retriever nor the generator was retrained.
Summary
- RAG = a dense retriever (DPR) + a seq2seq generator (BART), trained end to end on questionβanswer pairs, with the retrieved passage as a latent variable.
- Retrieval is maximum inner product search over precomputed passage embeddings. The TF-IDF version here ranked the right passage first whenever the words overlapped, and scored exactly zero on paraphrases. That gap is what learned dense retrievers close.
- RAG-Sequence sums over passages outside the product over tokens, and RAG-Token inside it. Both are proper distributions, checked by full enumeration, and they rank answers differently.
- Knowledge in an index can be updated, inspected and cited. Swapping the index changes the answers without touching the model.
- Today's "RAG" usually means the inference-time pattern: retrieve, paste into the prompt, generate. It often skips the joint training. The ideas of retrieval quality capping answer quality and recall@k as the first metric carry over unchanged.