Skip to content

Chapter 7 · RAG Evaluation and Training


7.1 Evaluation Dimensions ★★

Five quality dimensions ★★

Dimension Question it answers What is compared Typical metrics
Retrieval quality Did we retrieve the relevant documents and rank them high? Retrieved list vs labeled relevant documents Recall@k, MRR, nDCG (Ch. 2)
Context relevance How much of the retrieved context is actually useful for this question? Question vs context LLM-judged relevance, context precision
Faithfulness / groundedness Is every claim in the answer supported by the context? Answer vs context Supported-claim ratio, NLI entailment
Answer relevance Does the answer address the question that was asked? Answer vs question LLM- or embedding-based relevance
Answer correctness Is the answer actually right? Answer vs reference answer EM, F1, claim-level F1, LLM judge

A RAG system has two parts, retrieval and generation, and a failure in either one leads to a bad answer, so evaluation can't look only at whether the final answer is right. A useful way to organize it: a single RAG request involves four things, namely the question, the retrieved context, the answer and the reference answer, and comparing them pairwise gives the dimensions in the table above. Retrieval quality uses the Recall@k, MRR and nDCG of Chapter 2; the problem is that it needs human labels for "which documents are relevant", which are expensive, and it only cares whether the right documents were found, not how generation went afterwards. Context relevance doesn't depend on labels; instead an LLM judges how much of the retrieved content actually helps answer the question, and the more irrelevant content there is, the more tokens are wasted and the more generation is disrupted. Faithfulness (also called groundedness) checks whether every claim in the answer can be backed by something in the context; this dimension is specific to RAG and directly measures whether the model "made things up beyond the material". Answer relevance checks whether the answer is on topic and complete, or misses the point or stuffs in unrelated content. Answer correctness is the only dimension that strictly requires a reference answer.

Context relevance, faithfulness and answer relevance need no reference answer and are often called the RAG triad together. Their advantage is that they can be computed directly on unlabeled live traffic; the cost is that they only show the system is "self-consistent", not that the answer is "correct". So faithfulness and correctness must be measured separately: when the retrieved document is itself outdated, an answer can be faithful yet wrong; when the model fills in from memory, an answer can be correct yet unfaithful. The two cases point to completely different fixes: the first calls for fixing retrieval and the corpus, the second for constraining generation (the distinction is covered in Chapter 5, §5.4).

Interview questions

  • ★★ Along which dimensions should you evaluate a RAG system?
  • ★ What is the RAG triad, and why does it need no reference answer?
  • ★ Why should faithfulness and correctness be evaluated separately?

Latency and cost ★

In real deployments, latency and cost are often as important as quality, and they can decide outright whether a solution ships. Broken down by stage: retrieval latency comes from query encoding, vector search (ANN) and reranking, and a cross-encoder reranker, which runs every candidate document through the model together with the query, is often the slowest step; generation latency grows mainly with prompt length, since more retrieved documents mean a slower prefill and a higher time to first token (TTFT) (serving metrics are covered in LLM Basic Chapter 6); and cost covers tokens per request (most input tokens are retrieved context), the number of LLM calls (query rewriting, LLM reranking and multi-step agents all multiply the calls), and the embedding and storage costs of building the index.

There are trade-offs with quality everywhere: a larger \(k\) raises recall but also raises cost and noise; adding a reranker improves precision but adds latency; agentic RAG markedly improves accuracy on multi-hop questions at several or even tens of times the cost (see Chapter 6). So when comparing solutions, rather than reporting a single accuracy number, plot a quality–cost curve and see which solutions lie on the Pareto frontier. In production you should also watch tail latency such as P95, not just the average.

Interview questions

  • ★ Where does the latency of a RAG system mainly come from, and how do you trade off quality against cost?

7.2 RAGAS-Style Metrics ★★

Three reference-free metrics ★★

\[\text{Faithfulness} = \frac{|V|}{|S|}, \qquad \text{AnswerRelevance} = \frac{1}{n}\sum_{i=1}^{n} \cos\big(E(q),\, E(q_i)\big), \qquad \text{ContextRelevance} = \frac{N_{\text{rel}}}{N_{\text{ctx}}}\]

RAGAS (Es et al. 2023) is the most widely used set of automatic RAG metrics. Its core idea: break a holistic judgment that is hard to score directly into several small questions an LLM can easily answer, then combine them with simple ratios or similarities. The original paper proposed three metrics that need no reference answer:

Faithfulness is computed in two steps. First, an LLM splits the answer into a set of atomic statements \(S\); second, for each statement, the LLM judges whether it can be inferred from the context (yes/no). The set of statements that can be inferred is \(V\), and the score is \(|V|/|S|\). Why split first? Because a long answer often mixes correct and made-up content, so scoring it as a whole is too coarse, while each individual statement is easy to judge. For example, if the answer says "the drug was approved in 2019 for adults and children" and the context only mentions approval in 2019 for adults, then 2 of 3 statements are supported, a score of about 0.67.

Answer relevance uses a "reverse" trick: an LLM generates \(n\) questions \(q_i\) that the answer might be responding to, an embedding model \(E\) computes the cosine similarity between each \(q_i\) and the original question \(q\), and the scores are averaged. If the answer is on point, the questions inferred from it should resemble the original question; if the answer is incomplete or mixed with lots of irrelevant content, the inferred questions drift away from the original. Note that this metric does not check facts; it only checks whether the answer responds to this question.

Context relevance has an LLM extract the sentences from the context that are needed to answer the question; the score is the number of extracted sentences \(N_{\text{rel}}\) divided by the total number of sentences in the context \(N_{\text{ctx}}\). It penalizes the case where "lots of text came back but only one or two sentences are useful".

The original paper measured agreement between these metrics and human judgments on the WikiEval dataset (pairwise accuracy): 0.95 for faithfulness, 0.78 for answer relevance and 0.70 for context relevance. Context relevance is the hardest to evaluate: when the context is long, the LLM's sentence extraction itself becomes unreliable, and scoring by sentence ratio penalizes documents that are complete but long.

Interview questions

  • ★★ How is RAGAS faithfulness computed, and why split the answer into statements first?
  • ★ Why does answer relevance generate questions from the answer? Does it measure whether the answer is correct?

Reference-based metrics ★★

\[\text{ContextPrecision@}K = \frac{\sum_{k=1}^{K} \text{Precision@}k \times v_k}{\text{number of relevant chunks in the top } K}, \qquad v_k \in \{0, 1\}\]

After the original paper, the RAGAS library added several reference-based metrics to evaluate the retrieval side and the generation side more precisely:

Context precision measures whether the relevant documents are ranked near the top. \(v_k\) indicates whether the document at rank \(k\) is relevant (judged by an LLM against the reference answer), and Precision@\(k\) is the share of relevant documents among the top \(k\). The formula is essentially Average Precision (AP) from information retrieval: the higher the relevant documents rank, the higher the score. For example, if three documents have relevance [1, 0, 1], the score is \((1 + 2/3)/2 \approx 0.83\); with [0, 1, 1], it drops to \((1/2 + 2/3)/2 \approx 0.58\). This matters for RAG because LLMs make better use of content at the beginning and end of the context (see Chapter 3, §3.5), and documents ranked lower are the first to be dropped when the context is truncated.

Context recall measures whether all the information needed for the answer was retrieved. An LLM splits the reference answer into statements and checks each one for a source in the retrieved context; the score is the share that can be traced. The clever part is that the reference answer replaces "human-labeled relevant documents": labeling one answer is much cheaper than labeling a set of relevant documents.

Answer correctness measures how well the answer agrees with the reference. Both are split into statements: those in both count as TP, those only in the answer as FP (extra and possibly wrong), and those only in the reference as FN (missed). The statement-level F1, \(\mathrm{TP} / (\mathrm{TP} + 0.5(\mathrm{FP} + \mathrm{FN}))\), is then combined by weights with embedding-based semantic similarity.

Putting these metrics together enables a first round of diagnosis: low context recall means what should have been found wasn't, so the problem is retrieval; high context recall but low faithfulness means the material was found but the model didn't use it well, so the problem is generation (a more systematic attribution method is in 7.5).

Interview questions

  • ★★ What do context precision and context recall each measure, and how do you use them to locate problems?
  • ★ Why can context recall work without labeled relevant documents?

ARES: trained judges with confidence intervals ★

\[\hat{\theta}_{\text{PPI}} = \frac{1}{N}\sum_{i=1}^{N} f(\tilde{x}_i) \;-\; \frac{1}{n}\sum_{j=1}^{n}\big(f(x_j) - y_j\big)\]

RAGAS-style metrics prompt a general-purpose LLM directly for scores, which has two problems: every evaluation needs many calls to a large model, which is expensive; and the scores come with no statistical guarantee, so when the judge has a systematic bias, we don't know how large it is. ARES (Saad-Falcon et al. 2023) improves on both points. Step one, train small dedicated judges: automatically generate synthetic (question, passage, answer) data from the target corpus, including deliberately constructed negatives, and use it to fine-tune lightweight LM classifiers that judge context relevance, answer faithfulness and answer relevance separately.

Step two, correct statistically with a small set of human labels, using prediction-powered inference (PPI; Angelopoulos et al. 2023). In the formula, \(f\) is the judge's prediction (e.g. 0/1 for faithful or not), \(\tilde{x}_i\) are \(N\) samples without human labels, and \((x_j, y_j)\) are \(n\) samples with human labels \(y_j\) (usually a few hundred). The first term is the judge's average verdict over the many samples; the second is the judge's average error on the labeled set, which corrects its systematic bias. This uses lots of cheap judge predictions while relying on a few human labels to keep the estimate unbiased, and it also yields confidence intervals. The paper reports that ARES is more accurate than RAGAS and similar methods while needing only a few hundred human annotations.

Interview questions

  • ★ What does ARES improve over RAGAS, and what role does PPI play?

7.3 LLM-as-a-Judge for RAG ★★

Why and how ★

RAG answers are mostly open-ended natural language, so string metrics like exact match are barely usable, while human evaluation is expensive and slow and can't be done after every change. So using a strong LLM as a judge has become standard practice (the pointwise, pairwise and reference-guided modes and the general biases of judges are covered in LLM Basic Chapter 7, §7.7). For RAG, what the judge receives depends on which dimension is being evaluated: faithfulness needs the context, correctness needs the reference answer, and answer relevance needs only the question. The RAGAS approach of "split into statements, then judge each one" is essentially a fine-grained form of LLM-as-a-judge.

Interview questions

  • ★ When using an LLM to evaluate RAG, what inputs does the judge need for each dimension?

Pitfalls ★★

The general biases, namely position bias, verbosity bias and self-preference (Zheng et al. 2023), show up in RAG evaluation too (see LLM Basic Chapter 7, §7.7). Beyond them, RAG evaluation has a few pitfalls of its own:

  1. The judge substitutes its own knowledge for the context. When judging faithfulness, the judge should only check "is there support in the context", but if it knows the fact is true, it often marks it as "supported", overestimating faithfulness. Conversely, if the judge's own knowledge is outdated, it may mark a correct answer that matches the latest documents as wrong. At heart this confuses "supported by the context" with "true".
  2. The granularity of statement splitting changes the score. For the same answer, coarse splitting buries an error inside one long statement; fine splitting dilutes the error with many "obviously supported" small statements and inflates the score. Different splitting prompts or judge models give different scores.
  3. Support gets missed in long contexts. When the context runs to thousands of tokens, the judge itself may overlook the sentence supporting a statement and wrongly mark a supported statement as unsupported.
  4. Partial support and implicit reasoning. Some statements can only be inferred by combining two passages or doing a bit of arithmetic, and judges are very inconsistent on such cases.
  5. Instability and prompt sensitivity. The same sample can get different scores across runs, and changing the prompt wording or the judge model version changes the scores too. So scores under different judge setups can't be compared directly.
  6. Gaming once it becomes an optimization target. Once a judge score is used as an RL reward or a prompt-tuning objective, the system learns to please the judge (Goodhart's law). For example, an answer that restates large chunks of the context scores high on faithfulness but is of little use to the user.

Interview questions

  • ★★ What are the pitfalls of using LLM-as-a-judge to evaluate RAG?
  • ★ Why do judges overestimate faithfulness?

Making judges more reliable ★

The most important remedy is to validate the judge first: have humans label a few hundred samples, measure the agreement between the judge and the human labels, and only trust its scores once it meets the bar; re-validate after changing the judge model or prompt, keep the judge version and prompt fixed, and report confidence intervals rather than a single number. Next, constrain what the judge bases its verdict on: state explicitly in the prompt "judge only from the given context, not from your own knowledge", and require it to quote the sentence supporting the statement before giving its verdict; the quote can be checked, and it reduces the judge declaring "supported" out of thin air. Then, use binary verdicts instead of fine-grained scores: "Is this statement supported: yes/no" is far more stable than "rate faithfulness from 1 to 10", which is why RAGAS judges statement by statement. The general remedies for position, length and self-preference bias (judging twice with the order swapped, stating in the rubric that verbosity isn't rewarded, using a judge from a different model family) are in LLM Basic Chapter 7, §7.7.

There are also cheaper alternatives. Faithfulness can be judged with an NLI (natural language inference) model that checks "does the context entail this statement". NLI models are cheap and deterministic, and they don't "fill in" with their own world knowledge; ALCE's citation-quality evaluation works this way (citation recall/precision are defined in Chapter 5, §5.7). You can also train small dedicated judges as ARES does. The cost is that NLI models are weaker on long contexts and on statements that need multi-step reasoning.

Interview questions

  • ★★ How can you make LLM-judge evaluations more reliable?
  • ★ Besides LLM judges, how else can faithfulness or citation quality be evaluated?

7.4 Common Benchmarks ★

Benchmark Task type What it stresses
Natural Questions (Kwiatkowski et al. 2019) Real Google search queries with answers from Wikipedia Open-domain factoid QA; the open version (NQ-open) uses short answers
TriviaQA (Joshi et al. 2017) Trivia questions with evidence documents Factoid QA with more complex phrasing
HotpotQA (Yang et al. 2018) Multi-hop questions over Wikipedia Bridge and comparison reasoning (Ch. 6)
PopQA (Mallen et al. 2022) Questions about entities of varying popularity Long-tail knowledge, where retrieval helps most
ASQA (Stelmakh et al. 2022), ELI5 (Fan et al. 2019) Long-form answers Ambiguous questions, long-form generation
FEVER (Thorne et al. 2018) Fact verification Supporting or refuting a claim with evidence
KILT (Petroni et al. 2020) Suite of knowledge-intensive tasks over one Wikipedia snapshot Answers and provenance evaluated together
RGB (Chen et al. 2023) Diagnostic RAG test Noise robustness, negative rejection, information integration, counterfactual robustness
CRAG benchmark (Yang et al. 2024; not the Corrective RAG of Ch. 4) Diverse questions with mock web and knowledge-graph APIs Time-sensitive facts, many question types
FRAMES (Krishna et al. 2024) Questions needing several documents Factuality, retrieval and reasoning together
BEIR (Thakur et al. 2021) Retrieval only Zero-shot retrieval across domains (Ch. 2)
\[\mathrm{EM} = \mathbb{1}\big[\mathrm{norm}(\hat{a}) = \mathrm{norm}(a)\big], \qquad F_1 = \frac{2PR}{P + R},\quad P = \frac{|\hat{a} \cap a|}{|\hat{a}|},\quad R = \frac{|\hat{a} \cap a|}{|a|}\]

NQ, TriviaQA and HotpotQA are the classic trio left over from the open-domain QA era. Their answers are short text spans, and the metrics are EM and F1. In the formula, \(\hat{a}\) is the predicted answer, \(a\) is the gold answer, and \(\mathrm{norm}\) is normalization (lowercasing, removing punctuation and articles); EM requires an exact match after normalization, while F1 counts word overlap: \(P\) is how many words of the prediction appear in the gold answer, and \(R\) is how many words of the gold answer the prediction covers. These metrics run into trouble in the LLM era: LLMs tend to output full sentences, so "The answer is 1879." gets an EM of 0 against the gold answer "1879", scoring nothing despite being right. So people now often use "does the gold answer appear in the output" as accuracy, or use an LLM judge. The former has a loophole too: a model that lists several candidate answers can also get a "hit".

The classic datasets have two deeper problems. One is saturation and contamination: they are all based on Wikipedia, which models have long seen in pretraining, so many questions can be answered without retrieval, making it hard to tell how much value retrieval actually adds. The other is that they only test short answers, so they can't measure long-form answers, abstention or robustness to noise, which are what RAG really cares about. Newer benchmarks are designed around these problems: PopQA shows that retrieval helps most for less popular entities (see Chapter 4, §4.2), while for popular entities the model's parametric knowledge is already enough and retrieval sometimes even hurts; RGB tests four specific abilities, where negative rejection means declining to answer when no document contains the answer; CRAG adds facts that change over time; and FRAMES requires combining several documents. In practice, public benchmarks are only a reference; what matters most is building your own evaluation set from real user questions.

Interview questions

  • ★ Which benchmarks are commonly used for RAG, and what does each test?
  • ★ Why is EM ill-suited to the LLM era, and what are the alternatives?
  • ★ How should a production RAG system build its own evaluation set?

    Sample questions from real user logs, stratified by scenario and difficulty, rather than relying only on hand-written ones; label each question with a reference answer and the documents that support it, and deliberately add a few kinds of hard cases: questions whose answer isn't in the knowledge base (to test abstention), questions that need several documents combined, time-sensitive questions, and questions where documents contradict each other. Refresh the set regularly as the product and knowledge base change, and keep it strictly separate from the data used for training and tuning.


7.5 Component-Level vs End-to-End Evaluation ★★

What each kind answers ★★

Component-level evaluation evaluates the retriever, reranker and generator separately. The retriever is scored with Recall@k and nDCG against labeled relevant documents; the generator is evaluated on a fixed context (for example, given the correct documents directly), so what is measured is its ability to understand and use the material, independent of how well retrieval went. The benefits are precise localization of problems, fast iteration (evaluating the retriever doesn't even need an LLM call) and stable results. The drawback is that component metrics don't always line up with final quality: for example, the retriever's nDCG@10 goes up, but the generator only reads the top 3 documents, so it never sees the improvement; or the extra documents the retriever now finds are ones the generator could answer without anyway.

End-to-end evaluation looks directly at the overall effect of "question in, answer out", measured with correctness, faithfulness and similar metrics. It reflects the real user experience and captures interactions between components. The drawbacks are that when the score drops you don't know which stage is to blame, and it is noisy and expensive. In practice the two are used together: the end-to-end metric is the final "north star" that decides whether a change ships, and component metrics are used for diagnosis and fast iteration.

Interview questions

  • ★★ What are the pros and cons of component-level and end-to-end evaluation?
  • ★ The retriever's metrics improved but final answers didn't. What could be the reasons?

Error attribution over an evaluation set ★★

Answer correct Answer wrong
Relevant evidence retrieved Working as intended Generation problem: the model ignored, misread or overrode the evidence
Relevant evidence not retrieved Answered from parametric knowledge (or by luck): unfaithful and fragile Retrieval problem: query, chunking, index, retriever or corpus coverage

Chapter 1 explained how to trace a single wrong answer backward through the pipeline. At evaluation time the question is an aggregate one: across the whole evaluation set, how many errors does retrieval cause and how many does generation cause, and where should the next effort go? The method is to ask two questions of every sample: was the relevant evidence retrieved (judged by labeled relevant documents or context recall), and is the answer correct? Then place the samples into the four cells of the table and count the share in each cell. The share of "retrieved but wrong" shows how big the generation-side problem is: the model missed buried evidence, misread it, or trusted its parametric knowledge more (see Chapter 5). The share of "not retrieved and wrong" shows the retrieval-side problem. The cell most easily overlooked is "not retrieved but correct": these samples look right in the accuracy number, but the answers are neither faithful nor traceable; the system is really being held up by the model's memory and will fail on a batch of questions the model doesn't know, so these should count as a hidden retrieval problem. Counting by cell has one more benefit: after a change you can see how errors move between cells. For example, after switching retrievers, more samples may land in "retrieved" while the share of wrong answers among them rises, which shows the new retriever brings in more distracting documents.

Interview questions

  • ★★ How do you quantify, over a whole evaluation set, how many errors come from retrieval and how many from generation?
  • ★ Why do samples that are answered correctly without the relevant evidence deserve attention?

Diagnostic baselines ★

\[\underbrace{\mathrm{Acc}_{\text{oracle}} - \mathrm{Acc}_{\text{RAG}}}_{\text{loss from retrieval}}, \qquad \underbrace{1 - \mathrm{Acc}_{\text{oracle}}}_{\text{loss from generation}}\]

Besides per-sample attribution, a few controlled comparisons quickly reveal where a system's bottleneck is:

  1. Closed-book baseline: no retrieval; the model answers directly, which answers "how much does retrieval actually add?" If RAG is about the same as closed-book, either the model memorized the questions long ago or retrieval isn't doing anything; RAG can even be worse than closed-book, which means retrieval noise is leading the model astray (see Chapter 5, §5.5).
  2. Oracle context: feed the correct documents directly to the generator, roughly the upper bound of what the generator can achieve. In the formula, \(\mathrm{Acc}_{\text{oracle}}\) is the accuracy given the correct documents and \(\mathrm{Acc}_{\text{RAG}}\) is the accuracy with real retrieval. Their difference is the loss caused by retrieval; \(1 - \mathrm{Acc}_{\text{oracle}}\) is the part that can't be answered even with perfect material, the loss caused by generation. Whichever is larger gets fixed first.
  3. Noise injection: add irrelevant or plausible-but-wrong distractor documents alongside the correct ones and see how much accuracy drops, to measure robustness to noise.
  4. Position and count sweeps: put the correct document at different positions in the context, or vary \(k\), and see how quality changes. Many models make worse use of documents placed in the middle (see Chapter 3, §3.5).
  5. Counterfactual documents: deliberately alter facts in a document and see whether the model follows the document or sticks to its parametric knowledge, to test faithfulness (see Chapter 5).

After launch, you also need A/B tests, user feedback (thumbs up/down, whether citations get clicked) and continuous computation of the RAG triad on sampled traffic to monitor quality.

Interview questions

  • ★★ What do the oracle-context and closed-book baselines each tell you?
  • ★ Once a RAG system is live, how do you keep monitoring its quality?

7.6 End-to-End Trained Retrieval-Augmented Models ★★

\[p(y \mid x) = \sum_{z \in \mathcal{Z}} p_\eta(z \mid x)\; p_\theta(y \mid x, z)\]

Most RAG systems today are "assembled": take an off-the-shelf retriever and an off-the-shelf LLM, stuff the retrieved results into the prompt, and train the two separately with no connection between them. But in 2020–2022, a line of work tried to train the retriever and generator together end to end. Their shared mathematical framework is the formula above: the retrieved document \(z\) is treated as a latent variable; \(p_\eta(z \mid x)\) is the probability that the retriever with parameters \(\eta\) assigns to document \(z\); \(p_\theta(y \mid x, z)\) is the probability that the generator with parameters \(\theta\) produces target \(y\) given the document; and \(\mathcal{Z}\) is the whole document collection. Training maximizes this marginal likelihood without any labels for "which document is relevant": the retriever learns what a useful document is from whether that document helps the generator predict \(y\). The four models below are all variants of this framework, differing in which stage retrieval is used, how documents are fused with the input, and whether the retriever is trained.

Interview questions

  • ★★ What does it mean to treat the retrieved document as a latent variable, and why does training this way need no labels for which document is relevant?

REALM ★

REALM (Guu et al. 2020) was the first to put retrieval into pretraining. It is a BERT-style masked language model: for a sentence \(x\) with some words masked, it first uses a dense retriever to fetch a document \(z\) from Wikipedia, then concatenates \(x\) and \(z\) and predicts the masked words \(y\). The retriever's score is \(f(x, z) = \mathrm{Embed}_{\text{input}}(x)^\top \mathrm{Embed}_{\text{doc}}(z)\), and a softmax over the whole collection gives \(p(z \mid x)\). Predicting the masked words correctly means the retrieved document was useful, which is how the retriever gets its training signal.

To make this idea actually work, REALM used several key designs: summing over tens of millions of documents is intractable, so maximum inner product search (MIPS) keeps only the top k (8 in the paper, including a null document); the document encoder keeps changing during training, so a background job asynchronously rebuilds the index about every 500 steps (see 7.7); the retriever starts out random, so it is first warmed up with the Inverse Cloze Task (given a sentence, retrieve its surrounding context); ordinary random masking can often be solved with local grammar alone, so it uses salient span masking instead, masking spans like names, places and dates that need world knowledge, which forces the model to use retrieval; and for cases that need no retrieval, a null document gives the model somewhere to "put" that probability.

After pretraining, REALM was fine-tuned on open-domain QA (NQ, WebQuestions, CuratedTrec), with the document index fixed during fine-tuning and only the query encoder updated, and it beat the previous best methods by 4–16 points. Its significance is in showing that a retriever can be learned from the unsupervised signal of a language model alone, and that knowledge stored in external documents is more interpretable, since you can see which document the model used.

Interview questions

  • ★ How does REALM train the retriever during pretraining, and what problem does salient span masking solve?

RAG(Lewis et al. 2020):RAG-Sequence vs RAG-Token ★★

\[p_{\text{RAG-Seq}}(y \mid x) \approx \sum_{z \in \text{top-}k} p_\eta(z \mid x) \prod_{i=1}^{N} p_\theta(y_i \mid x, z, y_{1:i-1})\]
\[p_{\text{RAG-Tok}}(y \mid x) \approx \prod_{i=1}^{N} \sum_{z \in \text{top-}k} p_\eta(z \mid x)\, p_\theta(y_i \mid x, z, y_{1:i-1})\]
RAG-Sequence RAG-Token
Where documents are marginalized Over the whole sequence (sum outside the product) At every token (sum inside the product)
One answer can combine documents No, each answer comes from one document Yes, different tokens can rely on different documents
Decoding Beam search per document, then thorough or fast decoding Standard beam search
Better suited to Answers fully contained in one passage Answers that combine information from several passages

The name "RAG" comes from Lewis et al. (2020). Its retriever is DPR (two BERT-base encoders for queries and documents), the collection is Wikipedia from December 2018, split into 100-word passages, about 21 million in total; the generator is the seq2seq model BART-large, whose input is the concatenation of the question \(x\) and one retrieved document \(z\). Each query retrieves the top 5 or top 10. In the formulas, \(y_i\) is the \(i\)-th token of the answer, \(N\) is the answer length, and the sum runs only over the top-k documents, approximating the sum over the whole collection.

The two variants differ in at which level documents are marginalized:

  • RAG-Sequence: the whole answer is generated from the same document. Fix one document, generate the full answer with it, compute the answer's probability under that document, then average over the top-k documents weighted by their retrieval probabilities. The sum is outside the product.
  • RAG-Token: every generated token is marginalized over all documents. The sum is inside the product, so different parts of the answer can come from different documents.

For example, suppose the question is "Where was this person born, and which university did they attend?", with the birthplace in document A and the university in document B. RAG-Token can rely mainly on A for the first half of the answer and on B for the second half; RAG-Sequence needs one document containing both facts. The paper found RAG-Token better on Jeopardy question generation, a task that needs to combine several pieces of information.

Training: minimize \(-\sum_j \log p(y_j \mid x_j)\), again with no labels for which document is relevant. Only the query encoder and BART are fine-tuned; the document encoder and index stay fixed. The paper notes that updating the document encoder would require periodically rebuilding the index as REALM does, which is costly, and experiments showed this step isn't necessary for good performance. The paper also demonstrated index hot-swapping: replacing the 2016 Wikipedia index with the 2018 one, without retraining, let the model answer questions about newly installed world leaders. Knowledge can be updated by swapping the index, an important advantage of RAG over purely parametric models.

The difference in decoding is also frequently asked about. RAG-Token's marginal probability can be written as a per-token transition probability \(p'(y_i \mid x, y_{1:i-1}) = \sum_z p_\eta(z \mid x)\, p_\theta(y_i \mid x, z, y_{1:i-1})\), so standard beam search works directly. RAG-Sequence's likelihood doesn't factor into per-token terms, so a single beam search isn't possible; instead, beam search runs separately for each document, producing a set of candidate answers, and then there are two options: thorough decoding runs an extra forward pass for every candidate under every document to compute the full marginal probability, which is accurate but expensive; fast decoding assumes a candidate's probability is roughly 0 under the documents whose beams didn't produce it, skipping the extra passes.

Interview questions

  • ★★ What is the difference between RAG-Sequence and RAG-Token, and when does each fit?
  • ★ Why can't RAG-Sequence be decoded directly with beam search?
  • ★ Why does the RAG paper keep the document encoder fixed?

RETRO ★

RETRO (Borgeaud et al. 2021) has a different goal from the previous two: REALM and RAG mainly target QA, while RETRO aims to improve the language model itself, using a huge retrieval database to replace some of the parameters, "trading memory for parameters". It works like this: the input is split into chunks of 64 tokens; for each chunk, a frozen BERT computes an embedding and retrieves nearest neighbors from a database of about 2 trillion tokens (each neighbor includes the matched passage and its continuation in the original text); the neighbors are encoded by an encoder, and the decoder reads them in some of its layers through chunked cross-attention. There is a detail that preserves causality: the neighbors of chunk \(u\) were retrieved using the content of the whole chunk \(u\), so letting tokens inside that chunk see those neighbors would amount to peeking at later tokens in the chunk; therefore each chunk can only attend to the neighbors retrieved for the previous chunk.

Freezing the retriever is a deliberate trade-off: an index over 2 trillion tokens can't be rebuilt frequently, so a frozen retriever avoids index staleness entirely (see 7.7), at the cost that the retriever can never learn from the generator "which documents are useful". The paper reports that a 7.5B-parameter RETRO performs comparably to GPT-3 and Jurassic-1 on the Pile with 25 times fewer parameters; and an already-trained Transformer can be "converted" into RETRO by adding chunked cross-attention layers and training briefly (RETROfitting). The paper also specifically analyzed overlap (leakage) between the evaluation text and the retrieval database: the more overlap, the bigger the gain, though there are still gains on data with little overlap.

Interview questions

  • ★ How does RETRO's chunked cross-attention work, and why can each chunk only see the previous chunk's neighbors?
  • ★ Why does RETRO freeze its retriever, and what does that cost?

Atlas ★

\[p_{\text{LM}}(d_k) = \frac{p_\theta(a \mid d_k, q)}{\sum_{i=1}^{K} p_\theta(a \mid d_i, q)}, \qquad p_{\text{retr}}(d_k) = \frac{\exp\big(s(d_k, q)/\tau\big)}{\sum_{i=1}^{K} \exp\big(s(d_i, q)/\tau\big)}, \qquad \mathcal{L}_{\text{retr}} = \mathrm{KL}\big(p_{\text{LM}} \,\|\, p_{\text{retr}}\big)\]

Atlas (Izacard et al. 2022) asks: with retrieval, can a much smaller model beat huge models on few-shot knowledge-intensive tasks? Its retriever is Contriever (a dual encoder pretrained with unsupervised contrastive learning), and its generator is T5 with Fusion-in-Decoder (FiD): each retrieved document is concatenated with the question and passed through the encoder separately, and the decoder then reads the encodings of all documents at once through cross-attention. This way the encoder's cost grows only linearly with the number of documents, so dozens of documents can be read at once, while information is fused across documents in the decoder.

Atlas jointly pretrains the retriever and generator (MLM was chosen after comparing pretext tasks), then fine-tunes on a few examples. The retriever is trained by distilling from the generator: the paper compared four losses (attention distillation, EMDR², perplexity distillation and leave-one-out perplexity distillation), found little difference, and settled on perplexity distillation (PDist), which is stable and efficient; that's the formula above. \(q\) is the question, \(a\) is the target answer, \(d_k\) is the \(k\)-th retrieved document, and \(K\) is the number of retrieved documents. \(p_{\text{LM}}\) builds a target distribution over the \(K\) documents from "how likely the generator is to produce the correct answer given this document", \(s(d_k, q)\) is the retriever's score, and \(\tau\) is a temperature. Training makes the retriever's distribution \(p_{\text{retr}}\) match \(p_{\text{LM}}\): whichever document helps the generator most, the retriever learns to rank higher.

In terms of results, the 11B-parameter Atlas reaches about 42% accuracy on NQ with only 64 training examples, about 3 points higher than the 540B PaLM, which has 50 times more parameters. Atlas also showed that knowledge can be updated by swapping the index: a model trained with a 2017 index, given a 2020 index at test time without retraining, reaches 53.1% accuracy on 2020 answers, while closed-book T5, which can't update its knowledge, gets only 2.9%.

Interview questions

  • ★ What is Fusion-in-Decoder, and why does it suit reading many documents?
  • ★ How does Atlas train its retriever?

Comparing the four models ★★

REALM RAG RETRO Atlas
Retriever Dense BERT bi-encoder, trained DPR; query encoder trained, document encoder frozen Frozen BERT embeddings Contriever, trained jointly
Reader / generator BERT encoder (extractive QA at fine-tuning) BART seq2seq Decoder LM with chunked cross-attention T5 with Fusion-in-Decoder
Retrieval-augmented training stage Pretraining and fine-tuning Fine-tuning Pretraining Pretraining and fine-tuning
How documents are fused Concatenated with the input Concatenated; marginalized over top-k Cross-attention per chunk Encoded separately, fused in the decoder
Index refresh Asynchronous during pretraining None (fixed index) None (frozen retriever) Full re-index, re-ranking or query-side tuning
Headline result +4–16 points on open-domain QA State of the art on open-domain QA 7.5B on par with GPT-3 on the Pile ~42% on NQ with 64 examples

Looking at the four models together reveals a clear common thread: they all answer the question "should the retriever be trained, and if so, what happens to the index?" REALM and Atlas chose to train the retriever and therefore had to pay for refreshing the index; RAG trains only the query side, and RETRO freezes the retriever altogether, trading the retriever's ability to adapt for engineering simplicity. Another thread is how documents are fused: from simple concatenation (REALM, RAG), to fusing many documents in the decoder (Atlas's FiD), to reading them through cross-attention inside the model (RETRO), the number of documents that can be read keeps growing.

Interview questions

  • ★★ Compare REALM, RAG, RETRO and Atlas.

7.7 Difficulties of Joint Retriever–Generator Training ★★

Back-propagating through retrieval ★★

\[\nabla \log p(y \mid x) = \sum_{z} r(z)\, \nabla f(x, z), \qquad r(z) = \left[\frac{p(y \mid z, x)}{p(y \mid x)} - 1\right] p(z \mid x)\]

The first difficulty of joint training: retrieval picks the top k out of tens of millions of documents, a discrete selection that is not differentiable. The generator's loss can't directly tell the retriever "you should have retrieved document X".

Method one: marginal likelihood (REALM, RAG). Instead of passing gradients through the discrete "which document" choice, the retrieval scores enter the marginal likelihood as probabilities \(p(z \mid x)\) that serve as mixture weights over documents, so gradients can flow into the scores of the retrieved documents. REALM derived the formula above: \(f(x, z)\) is the retriever's score for document \(z\), \(p(y \mid z, x)\) is the probability of predicting the correct \(y\) with document \(z\), and \(p(y \mid x)\) is its expectation under the retrieval distribution, i.e. "how much an average document helps". So \(r(z) > 0\) exactly when \(p(y \mid z, x) > p(y \mid x)\): a document that helps more than average gets its score raised, and one that helps less than average gets it lowered. That is how the retriever learns "useful = helps the generator get it right". This method has a built-in limitation: gradients land only on the top-k documents, and documents outside the top k never get any signal. The retriever can only reorder documents it can already find; it can't "discover" a good document that has never entered the top k. So it depends heavily on how the retriever is initialized (see the cold-start problem below).

Method two: distill from the generator (Atlas, REPLUG). For each retrieved document, compute how much it helps the generator (for example, the likelihood of the correct answer given it, or the generator's attention to it), normalize that into a target distribution, and train the retriever to match it with a KL divergence (Atlas's PDist in 7.6 works this way). The advantage is that only the generator's output probabilities are needed, not its gradients, so the generator can be frozen or even a black box. REPLUG (Shi et al. 2023) uses this kind of LM supervision to train a retriever for a frozen black-box LLM. (In agent settings, retrieval can also be treated as an action and "what to search" trained with RL; see Chapter 6, §6.4.)

Interview questions

  • ★★ The top-k retrieval step isn't differentiable. How do gradients reach the retriever in joint training?
  • ★ What does REALM's gradient formula tell us?
  • ★ Can you still train the retriever when the generator is a black-box API?

Index staleness ★★

Strategy How it works Cost Downside
Freeze the document encoder Train only the query encoder (RAG; Atlas query-side tuning) No re-indexing The document side can't adapt
Asynchronous refresh A background job re-embeds the corpus from a parameter snapshot (REALM, about every 500 steps) Extra compute running in parallel The index is slightly stale between refreshes
Re-rank with the current encoder Retrieve L ≫ K with the old index, re-embed those L documents with the current encoder, keep the top K (Atlas) Moderate Still needs an occasional full refresh
Freeze the retriever Don't train the retriever at all (RETRO) None The retriever never learns from the generator
Periodic full re-index Re-embed everything every N steps (Atlas) Highest Best quality

The second difficulty is index staleness. Dense retrieval has to encode every document into a vector \(\mathrm{Embed}_{\text{doc}}(z)\) ahead of time and store it in an ANN index. Once training updates the document encoder, every vector stored in the index becomes "stale": the new query vectors are computed with new parameters, but the document vectors were computed with old ones, so the two no longer live in the same space, retrieval quality drops, and the retriever's training signal becomes biased. Re-encoding the whole collection is very expensive: REALM used 16 TPUs just for document encoding; in Atlas's experiments, rebuilding the full index every 1,000 steps added about 30% training overhead.

The table lists several remedies, all of which trade off "how much the retriever can learn" against "how much rebuilding the index costs". REALM's approach has a clever twist: the stale index is used only to select the top-k candidates; once selected, \(p(z \mid x)\) and the gradients for those k documents are recomputed with the latest parameters. So staleness only affects "which documents become candidates", not the gradients themselves. Even so, the paper's ablation shows that refreshing 30 times less often hurts quality noticeably.

Interview questions

  • ★★ What is the index staleness problem, and what are the solutions?
  • ★ REALM's index is stale, so why are its gradients still accurate?

Other difficulties and what practice looks like ★

Cold start and collapse. If the retriever starts out random, the retrieved documents are all useless, and the generator quickly learns to ignore them. Once the generator ignores documents, \(p(y \mid z, x)\) is about the same for every document, \(r(z) \approx 0\), and the retriever gets no signal and never improves: a vicious cycle. The fix is to warm up the retriever first: REALM uses the Inverse Cloze Task, RAG uses DPR already trained with supervision, Atlas uses Contriever; and to make the training objective genuinely need knowledge (REALM's salient span masking). REALM also excludes one kind of "cheating" retrieval: if the masked sentence itself comes from some document, retrieving that document lets the model copy the answer directly, and the retriever degenerates into finding exact string matches, so that document is excluded during training.

Compute cost and black-box models. Every training example makes the generator read \(k\) documents, multiplying compute by roughly \(k\). FiD keeps this cost linear, but for today's LLMs with tens of billions of parameters, end-to-end joint training is still prohibitively expensive; and today's generator is often a closed API anyway, with no gradients available and fine-tuning possibly ruled out.

So in practice, end-to-end joint training is rarely used directly in production systems. The mainstream approach is decoupling: the retriever is trained on its own (with contrastive learning and hard negatives, see Chapter 2), or, as in REPLUG, trained only from LLM feedback; the generator is fine-tuned separately to make better use of retrieved results (RAFT in 7.8, RA-DIT in 7.9, and others). Decoupling brings modularity: the retriever, the LLM and the document collection can each be swapped and updated independently. The ideas of end-to-end training live on in the form of "distilling the retriever from generator signals" and "fine-tuning the generator for RAG".

Interview questions

  • ★ Why can joint training collapse into "the generator ignores retrieved results", and how do you avoid it?
  • ★★ Why does industry RAG today rarely train the retriever and generator jointly end to end?

7.8 RAFT: Retrieval-Augmented Fine-Tuning ★★

Motivation: preparing for an open-book exam ★★

Domain SFT (closed-book) RAG with a general model RAFT
Learns domain knowledge Yes No Yes
Uses retrieved documents No Yes Yes
Robust to irrelevant documents Not applicable Weak Trained for it
Exam analogy Closed-book exam, studied Open-book exam, didn't study Open-book exam, studied

RAFT (Zhang et al. 2024) targets domain-specific RAG: the document collection is already fixed at training time (for example, internal company documents, medical literature or a piece of software's API docs), and at test time the retriever's top-k always contains some irrelevant documents. The paper uses exams as a good analogy. SFT on domain data alone is like cramming for a closed-book exam: you memorize some knowledge, but you can't use reference material during the exam, and anything you didn't memorize you can't answer. Doing RAG directly with a general model is like taking an open-book exam without studying: you can look things up, but you don't know the field, don't know which pages are useful, and are easily misled by irrelevant content. RAFT aims to study properly for an open-book exam: learn the domain knowledge while also practicing how to quickly find the relevant passage in a pile of material, ignore distracting content, and reason to the answer from the evidence found.

Interview questions

  • ★★ How does RAFT differ from ordinary domain SFT and ordinary RAG?

How the training data is built ★★

\[\begin{aligned} \text{fraction } P \text{ of the data:}\quad & (Q,\ D^*,\ D_1, \dots, D_k) \;\rightarrow\; A^* \\ \text{fraction } 1-P \text{ of the data:}\quad & (Q,\ D_1, \dots, D_k) \;\rightarrow\; A^* \end{aligned}\]
Question: <Q>
Context:  [D_2: distractor] [D*: oracle] [D_1: distractor] [D_3: distractor] ...
Answer:   The context says ##begin_quote## <exact sentence from D*> ##end_quote##,
          which means ... ##Answer: <final answer>

Each RAFT training example contains a question \(Q\), a set of documents and a target answer \(A^*\). The documents come in two kinds: the oracle document \(D^*\) contains the answer (there can be more than one; HotpotQA, for example, needs two), and the distractor documents \(D_1, \dots, D_k\) are documents from the same corpus that are irrelevant to the question. The key design is to mix two kinds of examples in proportion: in a fraction \(P\) of examples, the context contains both the oracle and the distractors; in the remaining \(1-P\), the context contains only distractors, but the target answer is still \(A^*\). Document order is shuffled. The paper's main training setup is 1 oracle plus 4 distractors.

The target answer \(A^*\) is not a short answer but a chain-of-thought rationale: it first quotes the relevant text from the documents verbatim, marked with ##begin_quote## and ##end_quote##, then reasons from the quotes, and finally gives the conclusion after ##Answer:. These rationales are generated by GPT-4. Training itself is standard SFT: the input is the question plus the documents, and the supervision target is the rationale.

Interview questions

  • ★★ How is RAFT's training data built?

Why each design choice works ★★

Why add distractor documents? Real retrieval always returns some irrelevant documents. If the context contains only correct documents during training, the model learns that "everything in the context is useful" and is easily led astray by irrelevant documents at test time. Adding distractors forces the model to learn which passages are truly relevant. The paper found that models trained only with correct documents often do worse than models trained with distractors, and that models trained with distractors are also more robust when the number of test-time documents changes.

Why drop the oracle document from some examples? This is RAFT's most counterintuitive design: the context doesn't contain the answer at all, yet the model must still output the correct answer. Its effect is to force the model to store domain knowledge in its parameters, so that when the retriever misses the correct document, the model can still answer from memory; it also keeps the model from developing a habit of "trusting the context unconditionally". The best \(P\) depends on the dataset (40% or 60% for some datasets in the paper, 100% for others); in other words, on many datasets, leaving the oracle out of some examples works better than always including it. There is a trade-off to watch here: if \(P\) is too low, the model learns to ignore the context and answer from memory; and the \(1-P\) examples essentially teach the model to "answer even without evidence", which is in tension with the requirement "decline if it isn't in the documents", so it should be set carefully in settings with strict faithfulness requirements.

Why use chain-of-thought with quotes? First, it makes the model find and quote the evidence before concluding, so answers are better grounded and easier to verify. Second, the reasoning provides a much richer training signal than a short answer, reducing overfitting to answer strings. The ablation shows that removing CoT drops HotpotQA performance from 35.28 to 25.62.

Interview questions

  • ★★ Why does RAFT drop the oracle document from some training examples, and how is P chosen?
  • ★ Why does RAFT use chain-of-thought with quotes as its training target?

Results and limitations ★

The paper experiments with Llama2-7B on PubMedQA (biomedical), HotpotQA (multi-hop QA) and Gorilla's APIBench (API-call generation for HuggingFace, Torch Hub and TensorFlow Hub). RAFT beats the "domain SFT plus RAG" baseline on every dataset, with the largest gaps on HotpotQA (4.41 → 35.28) and HuggingFace (42.59 → 74.00); the gap is smallest on PubMedQA, which the authors attribute to it being a yes/no classification task with limited room for reasoning.

RAFT's limitations are also clear: it needs a domain corpus and a set of domain questions fixed in advance; generating CoT answers with a strong model costs money; \(P\) and the number of distractors have to be tuned per dataset; and the closer the training distractors are to the "hard negatives" the retriever actually returns at test time, the better training matches testing, so how to construct distractors is itself a design choice.

Interview questions

  • ★ If you applied RAFT to your own product, how would you choose the distractor documents?

    Ideally, retrieve them with the retriever you actually deploy: for each training question, take its top-k results and remove the documents that really contain the answer; what remains are hard negatives. They look related to the question but don't contain the answer, which is exactly the kind of document most likely to mislead the model at test time. You can mix in a few random documents for diversity. Be careful not to treat a document that actually also contains the answer as a distractor, or you will teach the model to ignore useful evidence.


7.9 Instruction Tuning for Better Context Use ★

General instruction-tuning data rarely contains examples where "the prompt is stuffed with a long block of retrieved results, half of them irrelevant". So general models doing RAG often show three problems: ignoring the context, trusting their parametric knowledge more; being distracted by irrelevant documents, writing unrelated content into the answer; and not abstaining, making something up when the material doesn't contain the answer. RAG-specific instruction tuning trains the model on exactly these kinds of examples. A few representative works:

  • RA-DIT (Lin et al. 2023) splits joint training into two separate lightweight fine-tuning steps, sidestepping the difficulties of 7.7. Step one fine-tunes the LLM: retrieved passages are prepended to instruction data so the model learns to use relevant information and ignore irrelevant information. Step two fine-tunes the retriever: feedback from the LLM (an LM-supervised signal similar to REPLUG's) makes it return the documents the LLM prefers. The best model, RA-DIT 65B, outperforms methods that only add retrieved results in context by up to 8.9 points on average in the zero-shot setting.
  • ChatQA (Liu et al. 2024) uses two-stage instruction tuning: ordinary SFT first, then "context-enhanced" instruction tuning that trains the model to answer questions in multi-turn conversations over given documents. The paper specifically found that adding a small number of unanswerable examples (with "cannot answer" as the target output) teaches the model to say it doesn't know when the material lacks the answer, greatly reducing hallucination.
  • Robustness to irrelevant context: mixing irrelevant retrieved results into the training data so the model learns to ignore them (Yoran et al. 2023; see Chapter 5, §5.5).
  • Self-RAG (Asai et al. 2023) trains the model to output reflection tokens that decide whether to retrieve, judge whether retrieved results are relevant, and check whether the answer is supported by the evidence (see Chapter 4, §4.5).

The data recipe behind these methods is shared: mix correct documents with distractors; include examples whose answer isn't in the material, with abstention as the target; place the correct document at random positions in the context to ease the model's under-use of the middle; require answers to cite sources; and include examples where the context conflicts with the model's old knowledge, training it to go with the context (this kind of counterfactual data augmentation is in Chapter 5; general SFT methods are in Post-Training Chapter 1).

Interview questions

  • ★ What typical problems do general models have in RAG, and how can fine-tuning improve them?
  • ★ If you were building instruction-tuning data for RAG, what kinds of examples would you include?