CSCE 471 Natural Language Processing · Spring 2027

Retrieval-Augmented Generation

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

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.

After reading this, you should be able to explain the motivations for RAG · describe the retrieve-then-generate pipeline · compare sparse (BM25) and dense retrieval · explain how Dense Passage Retrieval is trained with in-batch negatives · explain how a document index is built and searched · describe how retrieved passages are given to a language model · discuss the limitations of RAG

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:

  1. Retrieves the most relevant passages from the datastore using the input as a query;
  2. Augments the input by adding the retrieved passages to the prompt;
  3. Generates the output with the language model, conditioned on both.
Datastoredocuments, split into chunks→Indexbuilt once, in advance
Question→Retrieversearch the index→top-$k$ passages→LLMquestion + passages→Answer

2Why RAG?

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)
Representationword counts (very high-dimensional, mostly zeros)learned vectors (a few hundred dimensions)
Matchesexact wordsmeaning, paraphrases
Trainingnoneneeds (question, passage) pairs
Strengthsrare names, codes, numbersvocabulary 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^-))}.$$

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.

Question:
Retriever:Top $k$:
Ranking
Prompt sent to the LLM
Figure 1 (interactive). A miniature RAG system over a 10-passage datastore, including two “private” course documents. BM25 scores are computed in your browser; dense scores are real cosine similarities from 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

7Summary

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”?

(a) BM25: exact rare strings like “E1047” and “X200” are matched perfectly by word overlap, while dense vectors may blur them. (b) Dense: the query and passage share almost no words but have related meanings.

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?

The batch contains $256$ passages ($128$ positives and $128$ hard negatives). One is the question's own positive, so each question sees $255$ negatives: $127$ other positives and all $128$ hard negatives.

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?

A cross-encoder would need 20 million BERT passes for every single question. With separate encoders, the 20 million passage vectors are computed once; each question then needs one BERT pass plus a fast vector search.

Quick quiz

9Further reading