A large language model learns its knowledge from its training data and stores it in its parameters. Ask it about something that happened after training, about your company's internal documents, or about a narrow technical detail it rarely saw, and it may say it does not know, or worse, confidently make something up.
Retrieval-augmented generation (RAG) gives the model an open book. Before answering, a retriever searches a collection of documents for passages relevant to the question, and these passages are placed in the model's input. The model then answers using both what it learned during training and the retrieved evidence. This reading covers why RAG is useful, how retrieval works (sparse and dense), how a dense retriever is trained, and the practical details and limitations of RAG systems.
1From language models to RAG
A standard language model is trained on a large text corpus. At training time it might read “The capital city of Ontario is Toronto”; at test time, given “The capital city of Ontario is ___”, it must recall the answer from its parameters. Everything it knows is frozen at training time.
RAG keeps a datastore of text available at test time. Given an input, the system:
- Retrieves the most relevant passages from the datastore using the input as a query;
- Augments the input by adding the retrieved passages to the prompt;
- Generates the output with the language model, conditioned on both.
2Why RAG?
- Knowledge cutoff. A model knows nothing about events after its training data was collected. Asked about a sports result from last week, it may reply that the event has not happened yet. Updating a datastore is far cheaper than retraining the model.
- Domain knowledge. Specialized facts (chemistry, medicine, law, a company's products) are rare in general training data, so models often get them wrong. For example, given the chemical structure (SMILES string) of the anticoagulant ximelagatran, a chatbot confidently identified it as dabigatran, a different drug of the same class. A domain-specific datastore supplies the missing facts.
- Hallucination. Models can produce fluent but false statements, such as claiming that Charles Lindbergh was the first person to walk on the Moon. Grounding answers in retrieved text, and asking the model to cite the passages it used, makes answers more accurate and easier to verify.
- Private data. Language models can memorize parts of their training data, and researchers have extracted names, contact information, and other text from trained models (Carlini et al., 2021). Training on private data therefore risks leaking it. With RAG, private documents stay in a datastore, where access can be controlled and documents can be updated or deleted at any time.
- Other sources. The same idea extends to knowledge bases, tables, graphs, and other modalities.
3Retrieval: sparse and dense
The retriever's job is to score every passage in the datastore for relevance to the query and return the top $k$. There are two main families.
Sparse retrieval: BM25
Sparse retrievers represent text by its words, like the bag-of-words and TF-IDF vectors used for text classification. The classic scoring function BM25 rewards passages that contain the query's words, giving more weight to rare words (high inverse document frequency) and diminishing returns for repeated words. BM25 is fast, needs no training, and is very good at exact matches such as names and course numbers. Its weakness is vocabulary mismatch: “Who first set foot on the lunar surface?” shares few words with a passage saying “Neil Armstrong became the first person to walk on the Moon.”
Dense retrieval
Dense retrievers encode the query and each passage into vectors and score them by similarity, just like the sentence embeddings for text similarity. The difference is the kind of pairs involved: instead of comparing two sentences with the same meaning, we compare a short question with a longer passage that answers it. Dense retrievers can match paraphrases and related concepts, but they need training data and can miss exact rare terms.
| Sparse (BM25) | Dense (e.g., DPR) | |
|---|---|---|
| Representation | word counts (very high-dimensional, mostly zeros) | learned vectors (a few hundred dimensions) |
| Matches | exact words | meaning, paraphrases |
| Training | none | needs (question, passage) pairs |
| Strengths | rare names, codes, numbers | vocabulary mismatch |
In practice the two are often combined (hybrid retrieval), since their errors differ.
4Dense Passage Retrieval
Dense Passage Retrieval (DPR; Karpukhin et al., 2020) uses two BERT encoders: a question encoder $E_Q$ and a passage encoder $E_P$. Unlike Sentence-BERT, the two do not share weights, because questions and passages look quite different. Relevance is the inner product of the two vectors:
$$\text{sim}(q,p) = E_Q(q)^\top E_P(p).$$Training
DPR is trained on question-answering data: each question $q$ comes with a positive passage $p^+$ that contains the answer. The loss is the contrastive loss from sentence embeddings, here without a temperature:
$$L(q,p^+,p_1^-,\dots,p_n^-) = -\log\frac{\exp(\text{sim}(q,p^+))}{\exp(\text{sim}(q,p^+))+\sum_{j=1}^{n}\exp(\text{sim}(q,p_j^-))}.$$- In-batch negatives: the positive passages of the other questions in the batch serve as negatives for each question.
- Hard negatives: DPR also adds, for each question, a passage that BM25 ranks highly but that does not contain the answer: similar-looking but wrong, and therefore very informative.
The result was a large improvement over BM25. On the Natural Questions benchmark, the correct answer appeared in the top 20 retrieved passages for 78.4% of questions with DPR, versus 59.1% with BM25.
Indexing and search
Before any question arrives, every passage in the corpus is encoded once with $E_P$ and the vectors are stored in an index. At query time, only the question is encoded, and the system searches for the passage vectors with the largest inner product (maximum inner product search). For millions of passages, libraries such as FAISS perform approximate nearest-neighbor search in milliseconds; vector databases provide the same service with storage and updates. This is the bi-encoder advantage: passage vectors are computed once and reused for every query.
5Putting it together
To give the retrieved passages to the language model, the documents are first split into chunks (e.g., a few hundred tokens each), which are what gets indexed and retrieved. For each question, the top $k$ chunks are inserted into a prompt template such as
Answer the question using the documents below. Cite the documents you use. [1] ...retrieved chunk... [2] ...retrieved chunk... Question: ... Answer:
Optionally, a more accurate but slower cross-encoder re-ranks a larger candidate set before the top $k$ are chosen.
multi-qa-MiniLM-L6-cos-v1, a bi-encoder trained on question–answer pairs. The green passage is the one that answers the question; passages inside the red outline go into the prompt. The answers are illustrative: they show what a good LLM would typically answer given that prompt.Some things to try in Figure 1: the course questions cannot be answered at all without retrieval; for “When do I have to hand in the second homework for my NLP class?”, which shares no content words with the schedule passage, BM25 fails while the dense retriever succeeds; and for “How does DPR score passages?” with $k=1$, the dense retriever puts the BM25 passage first while BM25 gets it right, a reminder that dense retrievers make mistakes too.
Training the retriever and the LM
In most RAG systems today, the retriever and the language model are trained independently: the LM is pretrained and instruction-tuned as usual, the retriever is trained on its own (question, passage) data, and the two are connected only at inference time. The original RAG model (Lewis et al., 2020), which introduced the name, instead fine-tuned the question encoder and the generator together, so that retrieval was optimized for the final answers.
6Limitations
- Retrieval errors propagate. If the retriever misses the right passage, the model either answers from memory or is misled by irrelevant text.
- More context is not always better. Irrelevant passages can distract the model. Models also use long contexts unevenly: they tend to use information at the beginning or end of the prompt better than information in the middle (“lost in the middle”; Liu et al., 2023).
- Conflicts. When a retrieved passage contradicts what the model learned in training, the model does not always follow the passage.
- Cost and latency. Retrieval adds a search step, and long prompts with many passages are slower and more expensive to process.
- Chunking and indexing choices matter. Chunks that are too small lose context; chunks that are too large dilute relevance and fill the prompt.
7Summary
- RAG retrieves relevant passages from a datastore and adds them to the LLM's input before generating.
- It addresses knowledge cutoffs, missing domain knowledge, hallucination, and private data.
- Sparse retrieval (BM25) matches words; dense retrieval matches meaning with learned vectors; hybrids combine both.
- DPR trains separate question and passage encoders with a contrastive loss, using in-batch and BM25 hard negatives, and ranks by inner product.
- Passage vectors are indexed once; queries use fast (approximate) maximum inner product search.
- Retrieved chunks are placed in a prompt, optionally after re-ranking; retrieval errors, distracting context, and knowledge conflicts remain challenges.
8Practice
Exercise 1: sparse or dense?
For each query, which retriever is more likely to find the right passage: (a) “error code E1047 on printer X200”; (b) “why does my phone die so quickly” when the relevant passage says “tips to extend battery life”?
Exercise 2: negatives
DPR is trained with a batch of 128 questions, each with one positive and one BM25 hard negative passage, and all passages in the batch are shared as negatives. How many negative passages does each question see?
Exercise 3: why an index?
A corpus has 20 million passages. Why does DPR encode the passages in advance instead of encoding them together with each question, as a cross-encoder would?
Quick quiz
9Further reading
- Asai, Min, Zhong & Chen (2023). Retrieval-based Language Models and Applications. ACL 2023 Tutorial. (Slides and references.)
- Lewis et al. (2020). Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. NeurIPS.
- Karpukhin et al. (2020). Dense Passage Retrieval for Open-Domain Question Answering. EMNLP.
- Liu et al. (2023). Lost in the Middle: How Language Models Use Long Contexts. TACL.
- Gao et al. (2023). Retrieval-Augmented Generation for Large Language Models: A Survey.