Skip to content

Chapter 6 · RAG Evaluation and Training

6.1 Along which dimensions should a RAG system be evaluated? ★★

One-sentence answer

Comparing pairwise the four things in a RAG request, namely the question, the retrieved context, the answer and the reference answer, gives five quality dimensions: retrieval quality, context relevance, faithfulness, answer relevance and answer correctness; context relevance, faithfulness and answer relevance need no reference answer and together are called the RAG triad. Latency and cost must also be evaluated, because they often decide outright whether a solution can ship.

I will address three aspects: where the five quality dimensions come from, the role and limits of the RAG triad, and latency and cost.

(1) Comparing the question, context, answer and reference answer pairwise gives five quality dimensions.

A RAG system has two parts, retrieval and generation, and a failure in either leads to a bad answer, so evaluation cannot look only at whether the final answer is right.

  • Retrieval quality: whether the relevant documents were retrieved and ranked near the top, measured with Recall@k, MRR and nDCG (see Chapter 1). 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: how much of the retrieved content actually helps answer the question, usually judged by an LLM without labels. The more irrelevant content, the more tokens are wasted and the more generation is disrupted.
  • Faithfulness (also called groundedness): 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 (see 4.3).
  • Answer relevance: whether the answer is on topic and complete, or misses the point or stuffs in unrelated content.
  • Answer correctness: whether the answer is actually right, the only dimension that strictly requires a reference answer.

(2) The RAG triad needs no reference answer and can be computed on live traffic, but it shows only that the system is self-consistent, not that the answer is correct.

Context relevance, faithfulness and answer relevance compare "question and context", "answer and context" and "answer and question" respectively; none involves the reference answer, so together they are often called the RAG triad. Its advantage is that it can be computed continuously on unlabeled live traffic. However, high scores on all three only show that the retrieved content is on topic, the answer is supported and the answer is on topic; they do not show that the answer is correct. Faithfulness and correctness must therefore 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 former calls for fixing retrieval and the corpus, the latter for constraining generation.

(3) Latency and cost matter as much as quality, and they trade off against quality everywhere.

Latency comes from both retrieval and generation: retrieval latency includes 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 in the Inference, Evaluation and Deployment direction, 0.3). 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. These trade off against 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 5). 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, also watch tail latency such as P95, not just the average.

In summary: RAG evaluation must cover both the retrieval side and the generation side, use the RAG triad for label-free continuous monitoring, use correctness metrics to confirm that answers are really right, and always compare latency and cost alongside quality.

The 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 (see Chapter 1)
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

Going deeper: breaking down latency and cost

(1) Where the latency and cost of a RAG request come from.

Stage Main source of latency Main source of cost
Query processing Extra LLM calls for query rewriting, decomposition, etc. Extra LLM calls
Retrieval Query encoding, ANN search Embedding computation; building and storing the index
Reranking A cross-encoder runs one forward pass per candidate, often the slowest retrieval step Reranker compute; calls for LLM reranking
Generation Longer prompts mean slower prefill and higher TTFT; longer outputs mean longer decoding Input tokens (mostly retrieved context) and output tokens

(2) Common quality–cost trade-offs.

  • The size of \(k\): the larger \(k\), the higher the recall, but the longer the prompt, so cost, latency and noise all rise.
  • Whether to rerank: reranking improves the precision of the top-ranked documents and thus allows a smaller \(k\), but adds the latency of one more model call.
  • One shot or multi-step: multi-step or agentic retrieval improves accuracy on multi-hop questions, but multiplies calls and tokens.

When comparing solutions, place each one on the quality–cost plane, keep only those on the Pareto frontier, and then choose among them according to the application's budget and latency requirements.

Follow-up questions

Follow-up 1: What is the RAG triad, and why does it need no reference answer?

The RAG triad is the collective name for context relevance, faithfulness and answer relevance. They compare "question and context", "answer and context" and "answer and question" respectively; both sides of each comparison are the system's own inputs and outputs, with no reference answer involved, so they can be computed directly on unlabeled live traffic and suit continuous monitoring.

Follow-up 2: Why should faithfulness and correctness be evaluated separately?

Because the two can disagree, and when they do they point to different fixes. With an outdated document, an answer can be faithful yet wrong, which calls for fixing retrieval and the corpus; when the model fills in from memory, an answer can be correct yet unfaithful, which calls for constraining generation. Looking at only one of them makes it impossible to tell these two kinds of problems apart.

Follow-up 3: Why can't RAG evaluation look only at whether the final answer is right?

Because when the final answer is wrong you cannot tell which stage failed, and when it is right it may rest only on the model's memory. Not retrieving the evidence, retrieving it but ranking it low, and retrieving it but not using it all lead to wrong answers, each with a different fix; and samples where retrieval failed but the model answered correctly from memory will fail on a batch of questions the model does not know. Per-stage metrics are therefore needed to locate problems (a systematic attribution method is in 6.3).

Follow-up 4: Where does the latency of a RAG system mainly come from, and how do you trade off quality against cost?

Mainly from reranking, the prefill of long prompts, and extra calls in multi-step flows. The way to trade off is to plot the quality–cost curve and consider only solutions on the Pareto frontier; common levers include using a reranker to allow a smaller \(k\), using small models for query rewriting and reranking, retrieving less or not at all for easy questions, and monitoring tail latency such as P95 in production.

Common mistakes

  • Do not look only at the accuracy of the final answer: It cannot separate retrieval problems from generation problems, and it hides answers that are right only thanks to memory.
  • Do not say that high RAG-triad scores mean the answer is correct: They show only that the system is self-consistent; correctness needs a reference answer.
  • Do not report only average latency: The production experience is driven more by tail latency such as P95.

6.2 How are the RAGAS metrics computed? ★

One-sentence answer

The core idea of RAGAS is to break a holistic judgment that is hard to score directly into small questions an LLM can easily answer, then combine them with ratios or similarities: faithfulness is the share of atomic claims in the answer supported by the context, answer relevance is the average cosine similarity between questions inferred from the answer and the original question, and context relevance is the share of sentences in the context needed to answer the question. The RAGAS library later added reference-based metrics: context precision (a rank-aware Average Precision), context recall (the share of claims in the reference answer that can be traced to the context) and answer correctness.

I will address four aspects: the core idea of RAGAS, the three reference-free metrics, the reference-based metrics, and how to combine them to locate problems.

(1) RAGAS breaks a holistic judgment that is hard to score directly into several small questions an LLM can easily answer.

RAGAS (Es et al. 2023) is the most widely used set of automatic RAG metrics. Asking an LLM directly "what is this answer's faithfulness score?" gives coarse and unstable results, whereas a small question such as "can this claim be inferred from the context: yes or no?" can be answered fairly reliably. RAGAS therefore first splits the answer or the context into small units, makes a simple judgment on each unit, and then combines the results into a score with ratios or similarities.

(2) The original paper proposed three metrics that need no reference answer.

  • Faithfulness: an LLM first splits the answer into a set of atomic claims, then judges for each claim whether it can be inferred from the context; the score is the share of claims that can be inferred. The answer is 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 claim is easy to judge. For example, if the answer says "the drug was approved in 2019 for adults and children" and the context mentions only approval in 2019 for adults, then 2 of 3 claims are supported, a score of about 0.67.
  • Answer relevance: an LLM generates several questions the answer might be responding to, an embedding model computes the cosine similarity between each of them and the original question, and the results 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. This metric does not check facts; it only checks whether the answer responds to this question.
  • Context relevance: an LLM extracts the sentences from the context that are needed to answer the question, and the score is the number of extracted sentences divided by the total number of sentences in the context. It penalizes the case where "lots of text came back but only one or two sentences are useful".

(3) The RAGAS library later added 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. An LLM judges, against the reference answer, whether the document at each rank is relevant, and the Average Precision from information retrieval is computed, so the higher the relevant documents rank, the higher the score. This matters for RAG because LLMs make better use of content at the beginning of the context, 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 claims 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", and 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 claims, a claim-level F1 is computed, and it is combined by weights with embedding-based semantic similarity.

(4) Combining these metrics enables a first round of diagnosis.

Low context recall means what should have been found was not, so the problem is retrieval; high context recall but low faithfulness means the material was found but the model did not use it well, so the problem is generation; low context precision means the relevant documents were ranked low, so reranking should be improved. A more systematic attribution method is in 7.3.

In summary: the essence of RAGAS is "decompose, make simple judgments item by item, then combine with ratios", so it is a fine-grained form of LLM-as-a-judge that inherits both its convenience and its biases.

The RAGAS metrics at a glance:

Metric Needs a reference? What is compared How it is computed
Faithfulness No Answer vs context Share of atomic claims supported by the context
Answer relevance No Answer vs question Average cosine similarity of inferred questions to the original
Context relevance No Question vs context Needed sentences divided by total sentences in the context
Context precision Yes Context vs reference answer Rank-aware Average Precision
Context recall Yes Context vs reference answer Share of reference claims that can be traced to the context
Answer correctness Yes Answer vs reference answer Weighted combination of claim-level F1 and semantic similarity

Going deeper: formulas, worked numbers and ARES

(1) The 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}}} \]

Here \(S\) is the set of atomic claims split from the answer and \(V\) is the subset that can be inferred from the context; \(q\) is the original question, \(q_i\) are the \(n\) questions inferred from the answer, \(E\) is an embedding model and \(\cos\) is cosine similarity; \(N_{\text{rel}}\) is the number of needed sentences extracted from the context and \(N_{\text{ctx}}\) is the total number of sentences in the context. The original paper measured agreement between the three 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.

(2) Context precision and answer correctness.

\[ \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\} \]

Here \(v_k\) indicates whether the document at rank \(k\) is relevant, and Precision@\(k\) is the share of relevant documents among the top \(k\). 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\). In answer correctness, claims present 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), and the claim-level F1 is \(\mathrm{TP} / (\mathrm{TP} + 0.5(\mathrm{FP} + \mathrm{FN}))\).

(3) ARES: trained judges with statistical correction from a few human labels.

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 do not know how large it is. ARES (Saad-Falcon et al. 2023) improves on both points. It first automatically generates synthetic (question, passage, answer) data from the target corpus, including deliberately constructed negatives, and uses it to fine-tune lightweight LM classifiers that judge context relevance, answer faithfulness and answer relevance separately; it then corrects the scores statistically with a small set of human labels, using prediction-powered inference (PPI; Angelopoulos et al. 2023):

\[ \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) \]

Here \(f\) is the judge's prediction (e.g. 0 or 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 term before the minus sign is the judge's average verdict over the many samples; the term after it 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.

Follow-up questions

Follow-up 1: Why does RAGAS faithfulness split the answer into claims first?

Because a long answer often mixes right and wrong content, so scoring it as a whole is too coarse, while each split-out claim is easy to judge. When scoring as a whole, the LLM struggles to give a stable score, and a single error is easily masked by lots of correct content; after splitting into atomic claims, each one only needs a judgment of "can it be inferred from the context", which is more stable and also pinpoints which claim lacks support.

Follow-up 2: Why does answer relevance generate questions from the answer? Does it measure whether the answer is correct?

Generating questions checks whether the answer responds to the original question; it does not measure correctness. If the answer is on point, the questions inferred from it should resemble the original; if it misses the point or contains irrelevant content, the inferred questions drift away. But a completely wrong answer that is on topic still yields questions very similar to the original, so it does not check facts.

Follow-up 3: Why can context recall work without labeled relevant documents?

Because it uses the reference answer in place of relevant-document labels. It splits the reference answer into claims and checks whether each claim can be traced to the retrieved context; if it can, the needed information was retrieved. Labeling one reference answer is far cheaper than labeling a set of relevant documents for every question.

Follow-up 4: What does ARES improve over RAGAS, and what role does PPI play?

ARES cuts cost with small trained judges and uses PPI to produce unbiased estimates with confidence intervals. RAGAS calls a general-purpose large model every time, and its scores carry no statistical guarantee; ARES fine-tunes lightweight classifiers on synthetic data to act as judges, then uses PPI with a few hundred human labels to estimate and subtract the judge's systematic bias, making the final score unbiased and allowing confidence intervals to be reported.

Common mistakes

  • Do not say that answer relevance measures whether the answer is correct: It measures only whether the answer is on topic.
  • Do not treat RAGAS scores as absolute ground truth: They depend on the judge model, the splitting prompt and the splitting granularity, and scores under different setups cannot be compared directly.
  • Do not say that context precision is just the share of relevant documents: It is computed over the ranking, and the higher the relevant documents rank, the higher the score.

6.3 How do you use LLM-as-a-judge to evaluate RAG, and how does component-level evaluation differ from end-to-end evaluation? ★

One-sentence answer

When using an LLM to evaluate RAG, the judge's inputs depend on the dimension: faithfulness needs the context, correctness needs the reference answer, and answer relevance needs only the question. Beyond the general position, length and self-preference biases, RAG has pitfalls of its own, the most typical being a judge that substitutes its own knowledge for the context and thus overestimates faithfulness, so the judge should first be validated against human labels and constrained to make binary judgments based only on the context. Component-level evaluation scores the retriever and generator separately, which helps locate problems and iterate quickly; end-to-end evaluation looks directly at the final answer and reflects the real user experience; in practice the end-to-end metric is the final arbiter, and component metrics and controlled baselines are used for diagnosis.

I will address four aspects: how to choose the judge's inputs, the pitfalls specific to RAG evaluation, how to make judges more reliable, and how component-level and end-to-end evaluation relate.

(1) What the judge receives depends on which dimension is being evaluated.

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 cannot be done after every change, so using a strong LLM as a judge has become standard practice (pointwise and pairwise modes and the general biases are in the Inference, Evaluation and Deployment direction, 5.3). For RAG, faithfulness requires giving the judge the context and the answer, correctness requires the reference answer, and answer relevance needs only the question and the answer. The RAGAS approach of "split into claims, then judge each one" is essentially a fine-grained form of LLM-as-a-judge (see 6.2).

(2) Beyond the general biases, RAG evaluation has a few pitfalls of its own.

  • 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".
  • The granularity of claim splitting changes the score: for the same answer, coarse splitting buries an error inside one long claim, while fine splitting dilutes the error with many "obviously supported" small claims and inflates the score. Different splitting prompts or judge models give different scores.
  • Misjudgments in long contexts and implicit reasoning: when the context runs to thousands of tokens, the judge itself may overlook the sentence supporting a claim; some claims can only be inferred by combining two passages or doing a bit of arithmetic, and judges are very inconsistent on such cases.
  • 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.

(3) The key to a more reliable judge is to validate it first and then constrain what it bases its verdict on.

  • Validate the judge first: have humans label a few hundred samples, measure the agreement between the judge and the human labels, and trust its scores only 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.
  • Constrain the basis of the verdict: state explicitly in the prompt "judge only from the given context, not from your own knowledge", and require the judge to quote the sentence supporting the claim before giving its verdict. The quote can be checked, and it reduces the judge declaring "supported" out of thin air.
  • Use binary verdicts instead of fine-grained scores: "Is this claim supported: yes or no" is far more stable than "rate faithfulness from 1 to 10", which is why RAGAS judges claim by claim.
  • Use cheaper, more deterministic alternatives: faithfulness can be judged with an NLI model that checks "does the context entail this claim"; it is cheap and deterministic and does not "fill in" with its own world knowledge, which is how ALCE's citation evaluation works (see 4.6); one can also train small dedicated judges as ARES does. The cost is that NLI models are weaker on long contexts and on claims that need multi-step reasoning.

(4) Component-level evaluation is for diagnosis and fast iteration, end-to-end evaluation is for the final decision, and the two must be used together.

Component-level evaluation scores the retriever, reranker and generator separately: the retriever with Recall@k and nDCG against labeled relevant documents, and the generator on a fixed context, for example by giving it the correct documents directly, so that what is measured is its ability to understand and use the material, independent of how well retrieval went. It localizes problems precisely, iterates quickly and gives stable results; however, component metrics do not always line up with final quality, for example the retriever's nDCG@10 goes up, but the generator reads only the top 3 documents and never sees the improvement. End-to-end evaluation looks directly at "question in, answer out", reflecting the real user experience and capturing interactions between components, but when the score drops you do not know which stage is to blame, and it is noisy and expensive. In practice, therefore, the end-to-end metric serves as the "north star" that decides whether a change ships, while component metrics, error attribution over the evaluation set (see the table below) and controlled baselines are used for diagnosis and fast iteration.

In summary: the key to evaluating RAG with an LLM is to make the judge rely only on the context and validate it against humans first; component-level and end-to-end evaluation handle diagnosis and decision respectively, and neither can be dropped.

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

Going deeper: how to do error attribution, controlled baselines and monitoring after launch

(1) Error attribution over a whole evaluation set.

Chapter 0 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, namely whether the relevant evidence was retrieved (judged by labeled relevant documents or context recall) and whether the answer is correct, then place the samples into the four cells of the table above and count the share in each. The share of "retrieved but wrong" shows how big the generation-side problem is; 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 does not 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.

(2) Common controlled 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}} \]

Here \(\mathrm{Acc}_{\text{oracle}}\) is the accuracy when the generator is given the correct documents directly 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 cannot be answered even with perfect material, the loss caused by generation. Whichever is larger gets fixed first.

  • 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 is not doing anything; RAG can even be worse than closed-book, which means retrieval noise is leading the model astray (see 4.4).
  • Oracle context: feed the correct documents directly to the generator, roughly the upper bound of what the generator can achieve, used to compute the two losses above.
  • 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.
  • 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 the Model Architecture direction, 3.6).
  • 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 4).

(3) The instability of judges.

The same sample can get different scores across runs, and changing the prompt wording or the judge model version changes the scores too. Scores under different judge setups therefore cannot be compared directly, and reports should state the judge's model, version and prompt.

(4) Monitoring after launch.

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.

Follow-up questions

Follow-up 1: Why do judges overestimate faithfulness?

Because the judge substitutes its own knowledge for the context. If a claim has no support in the context but the judge itself knows it is true, it tends to mark it as "supported". Remedies are to require explicitly that the judgment rely only on the context, to have the judge quote the original sentence before concluding, or to use an NLI model that does not rely on world knowledge.

Follow-up 2: The retriever's metrics improved but final answers did not. What could be the reasons?

Component metrics and final quality do not always line up. Possible reasons include: the improvement happened where the generator cannot see it, for example nDCG@10 rose while the generator reads only the top 3; the newly retrieved documents are ones the generator could answer without anyway; the new retriever also brought in more distracting documents, cancelling out the gain; or the bottleneck was on the generation side all along, for example the model was not making good use of evidence it already had.

Follow-up 3: How do you quantify, over a whole evaluation set, how many errors come from retrieval and how many from generation?

Split the samples into four cells by "was the relevant evidence retrieved" and "is the answer correct", and combine this with an oracle-context baseline. The shares of the four cells directly give the size of retrieval failures and generation failures; the gap between oracle accuracy and real RAG accuracy is the loss from retrieval, and one minus oracle accuracy is the loss from generation.

Follow-up 4: What do the oracle-context and closed-book baselines each tell you?

Oracle context gives the generator's upper bound; closed-book gives the lower bound without retrieval. The gap between oracle and real RAG shows how much room retrieval still has to improve; the gap between RAG and closed-book shows how much value retrieval actually adds. If RAG is even worse than closed-book, retrieval noise is misleading the model.

Follow-up 5: Why do samples that are answered correctly without the relevant evidence deserve attention?

Because they are a hidden risk held up by the model's memory. These answers count as correct in accuracy, but they are neither faithful nor traceable; once the questions are ones the model does not know, or the knowledge has been updated, the system will fail. They should therefore count as a retrieval-side problem.

Common mistakes

  • Do not take an LLM judge's scores as ground truth: First validate its agreement with human labels, and fix the judge's version and prompt.
  • Do not let a faithfulness judge use its own knowledge: That mistakes "true" for "supported".
  • Do not rely only on component-level evaluation: Better component metrics do not mean better final answers.
  • Do not rely only on end-to-end evaluation: When the score drops, without component metrics you cannot tell which stage is at fault.

6.4 Which benchmarks are commonly used for RAG? ★

One-sentence answer

The classics are the open-domain QA trio NQ, TriviaQA and HotpotQA, evaluated with EM and F1; but in the LLM era they have three problems: EM marks correct answers phrased as full sentences as wrong, their Wikipedia basis leads to saturation and contamination, and they test only short answers. Newer benchmarks each fill one gap: PopQA tests long-tail knowledge, RGB tests noise robustness and abstention, CRAG tests facts that change over time, FRAMES tests multi-document synthesis, and ASQA and ELI5 test long-form answers; in practice, what matters most is building your own evaluation set from real user questions.

I will address four aspects: the classic benchmarks and their metrics, their problems in the LLM era, what each newer benchmark adds, and how to build your own evaluation set.

(1) The classic open-domain QA benchmarks mostly have short answers and are evaluated with EM and F1.

NQ (Natural Questions), TriviaQA and HotpotQA are the classic trio left over from the open-domain QA era, and their answers are short text spans. EM requires the predicted answer to match the reference exactly after normalization (lowercasing, removing punctuation and articles); F1 counts word overlap, taking into account both how many words of the prediction appear in the reference and how many words of the reference the prediction covers (the formulas are in "Going deeper" below).

(2) These classic benchmarks have three problems in the LLM era.

  • EM marks correct answers as wrong: LLMs tend to output full sentences, so "The answer is 1879." gets an EM of 0 against the reference "1879", scoring nothing despite being right. People therefore now often use "does the reference answer appear in the output" as accuracy, or an LLM judge; the former has a loophole too, since a model that lists several candidate answers can also get a "hit".
  • Saturation and contamination: these datasets 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 (see the LLM Training Pipeline direction, 1.7).
  • They test only short answers: they cannot measure long-form answers, abstention or robustness to noise, which are what RAG really cares about.

(3) Newer benchmarks each fill one gap.

  • PopQA: builds questions by entity popularity and shows that retrieval helps most for less popular entities, while for popular entities the model's parametric knowledge is already enough and retrieval sometimes even hurts (see Chapter 3).
  • RGB: tests four specific abilities, namely noise robustness, negative rejection, information integration and counterfactual robustness, where negative rejection means declining to answer when no document contains the answer (see 4.4).
  • CRAG: adds facts that change over time and many question types, and provides mock web and knowledge-graph APIs.
  • FRAMES: requires combining several documents, testing factuality, retrieval and reasoning together.
  • ASQA and ELI5: need long-form answers and are often used together with citation evaluation (ALCE).

(4) Public benchmarks are only a reference; what matters most is building your own evaluation set from real user questions.

The distribution of public benchmarks often differs greatly from a specific product, and they may already be contaminated. When building your own 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 is not 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.

In summary: classic benchmarks are good for quick comparisons but are saturated and test only short answers; newer benchmarks each fill one gap; what actually decides a launch is your own evaluation set, built from real traffic and refreshed regularly.

Common benchmarks at a glance:

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 (see Chapter 5)
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 Chapter 3) 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 (see Chapter 1)

Going deeper: definitions of EM and F1, and benchmarks for agentic settings

(1) EM and F1.

\[ \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|} \]

Here \(\hat{a}\) is the predicted answer, \(a\) is the reference answer, \(\mathrm{norm}\) is normalization (lowercasing, removing punctuation and articles), \(\hat{a} \cap a\) denotes the words the two share, \(P\) is the share of the prediction's words that appear in the reference, and \(R\) is the share of the reference's words covered by the prediction. F1 gives partial credit to partly correct answers but still penalizes extra words, so it is also too strict for LLMs' full-sentence outputs.

(2) Design points of a few benchmarks.

  • KILT: all tasks share one Wikipedia snapshot, and it evaluates not only the answer but also whether the provenance the model gives is correct, so retrieval and generation can be compared within one framework.
  • CRAG: its questions span several domains and many types (such as simple facts, comparisons, aggregations, multi-hop and false premises), and it distinguishes facts that change quickly from those that change slowly, to test how systems handle time-sensitive information.
  • BEIR: evaluates retrieval only, gathering retrieval tasks from many domains to test the zero-shot generalization of retrievers.

(3) Benchmarks for agentic settings.

Search agents and deep research systems are usually evaluated with multi-hop QA (2WikiMultiHopQA, MuSiQue, Bamboogle), web-browsing benchmarks (BrowseComp, BrowseComp-Plus) and long-report evaluation (DeepResearch Bench); see 5.5.

Follow-up questions

Follow-up 1: Why is EM ill-suited to the LLM era, and what are the alternatives?

Because LLMs output full sentences, and EM marks correct answers as wrong. There are three alternatives: word-level F1, which gives partial credit but still penalizes extra words; cover EM, which checks whether the reference answer appears in the output and is lenient but can be gamed by "listing several candidates"; and an LLM judge, which is the most flexible but more expensive and has its own biases. In practice two of them are often reported together.

Follow-up 2: How should a production RAG system build its own evaluation set?

Sample from real user logs with stratification, and deliberately add hard cases. Sample questions stratified by scenario and difficulty; label each with a reference answer and the supporting documents; add hard cases such as answers missing from the knowledge base, multi-document synthesis, time-sensitive questions and contradictory documents; and refresh the set regularly, keeping it strictly separate from training and tuning data.

Follow-up 3: What does PopQA show?

It shows that the value of retrieval depends on how popular the knowledge is. For obscure long-tail entities, the model's parametric knowledge is unreliable and retrieval helps most; for popular entities, the model already remembers the facts, retrieval adds little, and retrieved noise can sometimes even lower accuracy. This is the basis for "retrieve only when needed" in adaptive retrieval (see Chapter 3).

Common mistakes

  • Do not evaluate LLM answers with EM alone: Correct answers phrased as full sentences are marked wrong.
  • Do not decide on a solution from public benchmarks alone: They may be contaminated, and their distribution differs from the product's.
  • Do not confuse the CRAG benchmark with Corrective RAG: The former is a 2024 evaluation benchmark; the latter is the retrieval-correction method of Chapter 3.

6.5 Can the retriever and generator be trained jointly end to end, and what makes it hard? ★★

One-sentence answer

Yes. The unifying framework treats the retrieved document as a latent variable and maximizes the answer likelihood marginalized over the top-k documents, so no labels for which document is relevant are needed: the retriever learns what a useful document is from whether that document helps the generator predict the answer, with REALM, RAG, RETRO and Atlas as representative works. There are four difficulties: top-k retrieval is not differentiable and must be worked around with marginal likelihood or distillation from the generator; updating the document encoder makes the whole index stale; when the retriever starts cold, the generator learns to ignore documents and training collapses; and compute is expensive while today's generators are often black boxes. Industry therefore mostly trains the two separately.

I will address four aspects: the unifying framework of joint training, four representative models, the difficulties of joint training, and what practice looks like.

(1) The unifying framework of joint training treats the retrieved document as a latent variable and maximizes the marginal likelihood.

Most RAG systems today are "assembled": an off-the-shelf retriever plus an off-the-shelf LLM, trained separately with no connection between them. Between 2020 and 2022, a line of work tried to train the two together end to end, and their shared mathematical framework is:

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

Here \(x\) is the input, \(y\) is the target output, \(z\) is a retrieved document, \(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 \(y\) given the document, and \(\mathcal{Z}\) is the whole document collection (in practice the sum runs only over the top k). Training maximizes this marginal likelihood without any labels for which document is relevant: if a document helps the generator predict \(y\) better, its probability under the retriever is raised, so what the retriever learns as "useful" is "helps the generator get it right".

(2) The four representative models 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.

  • REALM (Guu et al. 2020): the first to put retrieval into pretraining. It is a BERT-style masked language model that first retrieves a document and then concatenates it with a sentence whose words are partly masked, predicting the masked words; predicting them correctly means the retrieved document was useful, which is how the retriever gets its training signal.
  • RAG (Lewis et al. 2020): the origin of the name "RAG". Its retriever is DPR and its generator is BART, fine-tuned on downstream tasks, updating only the query encoder and the generator while the document encoder and index stay fixed; it comes in RAG-Sequence, where the whole answer uses one document, and RAG-Token, where every token is marginalized over all documents.
  • RETRO (Borgeaud et al. 2021): aims to improve the language model itself, using a retrieval database of about 2 trillion tokens to replace some of the parameters; its retriever is a frozen BERT, and the decoder reads the retrieved neighbors through chunked cross-attention.
  • Atlas (Izacard et al. 2022): jointly pretrains the Contriever retriever and a T5 generator with Fusion-in-Decoder, then fine-tunes on a few examples; the retriever is trained by distilling signals from the generator, with the goal of letting a much smaller model beat huge models on few-shot knowledge-intensive tasks.

(3) Joint training has four difficulties.

  • Retrieval is not differentiable: retrieval picks the top k out of tens of millions of documents, a discrete selection, so the generator's loss cannot directly tell the retriever "you should have retrieved document X". One workaround is marginal likelihood (REALM, RAG): the retrieval scores enter the likelihood as probabilities that serve as mixture weights over documents, so gradients flow into the scores of the retrieved documents, raising those that help more than average and lowering the rest. Another is distillation from the generator (Atlas, REPLUG): compute how much each document helps the generator, normalize that into a target distribution, and train the retriever to match it with a KL divergence, which needs only the generator's output probabilities, not its gradients.
  • Index staleness: dense retrieval has to encode every document into a vector ahead of time and store it in an index; once training updates the document encoder, every vector in the index becomes stale, the new query vectors and the old document vectors no longer live in the same space, retrieval quality drops and the training signal becomes biased; yet re-encoding the whole collection is very expensive.
  • 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, every document helps prediction about equally, the retriever gets no signal at all, and a vicious cycle forms. The fix is to warm up the retriever first and to make the training objective genuinely need knowledge.
  • Compute cost and black-box models: every training example makes the generator read \(k\) documents, multiplying compute by roughly \(k\); 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.

(4) In practice, therefore, the two are mostly trained separately, and the ideas of end-to-end training survive as distillation and RAG-specific fine-tuning.

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 1), or, as in REPLUG (Shi et al. 2023), trained only from the feedback of a frozen black-box LLM; the generator is fine-tuned separately to make better use of retrieved results (RAFT, RA-DIT and others; see 6.6). Decoupling brings modularity, since the retriever, the LLM and the document collection can each be swapped and updated independently; the ideas of end-to-end training live on as "distilling the retriever from generator signals" and "fine-tuning the generator for RAG" (in agent settings, retrieval can also be treated as an action and "what to search" trained with RL; see 5.3).

In summary: the core of joint training is treating documents as latent variables so that the retriever learns "what is useful" from the generator; it is elegant in theory, but non-differentiability, index staleness, cold start and cost have moved industry toward decoupled training.

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

Going deeper: the key designs of each model and remedies for index staleness

(1) RAG-Sequence and 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}), \qquad 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}) \]

Here \(y_i\) is the \(i\)-th token of the answer and \(N\) is the answer length. RAG's retriever, DPR, consists of two BERT-base encoders, the collection is Wikipedia from December 2018 split into 100-word passages, about 21 million in total, and each query retrieves the top 5 or top 10. The two variants differ in at which level documents are marginalized: in RAG-Sequence the sum is outside the product, so the whole answer is generated from the same document; in RAG-Token the sum is inside the product, so different parts of the answer can come from different documents. For example, for "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, while 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. For decoding, RAG-Token's marginal probability can be written as a per-token transition probability, so standard beam search works directly; RAG-Sequence's likelihood does not factor into per-token terms, so beam search must run separately for each document to produce a candidate set, followed by thorough decoding (an extra forward pass for every candidate under every document, accurate but expensive) or fast decoding (assuming a candidate's probability is roughly 0 under the documents whose beams did not produce it, skipping the extra passes). 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.

(2) REALM's gradient and key designs.

\[ \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) \]

Here \(f(x, z) = \mathrm{Embed}_{\text{input}}(x)^\top \mathrm{Embed}_{\text{doc}}(z)\) is the retriever's score, and a softmax over the whole collection gives \(p(z \mid x)\); \(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 the document helps more than average. The method's built-in limitation is that gradients land only on the top-k documents, so a good document outside the top k never gets any signal. REALM therefore used several key designs: maximum inner product search (MIPS) keeps only the top k (8 in the paper, including a null document where the model can "put" probability when no retrieval is needed); a background job asynchronously rebuilds the index about every 500 steps; the retriever is first warmed up with the Inverse Cloze Task (given a sentence, retrieve its surrounding context); salient span masking masks spans such as names, places and dates that need world knowledge, forcing the model to use retrieval; and the document containing the masked sentence itself is excluded, to keep the retriever from degenerating into finding exact string matches. After pretraining, REALM was fine-tuned on NQ, WebQuestions and CuratedTrec (with the document index fixed and only the query encoder updated) and beat the previous best methods by 4–16 points.

(3) RETRO's chunked cross-attention.

RETRO splits the input 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. To preserve causality, each chunk can only attend to the neighbors retrieved for the previous chunk: the neighbors of chunk \(u\) were retrieved using the content of the whole chunk \(u\), so letting tokens inside that chunk see them would amount to peeking at later tokens in the chunk. Freezing the retriever is a deliberate trade-off, since an index over 2 trillion tokens cannot be rebuilt frequently, at the cost that the retriever can never learn from the generator which documents are useful. 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 analyzed overlap 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.

(4) Atlas's Fusion-in-Decoder and perplexity distillation.

\[ 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) \]

Here \(q\) is the question, \(a\) is the target answer, \(d_k\) is the \(k\)-th retrieved document, \(K\) is the number of retrieved documents, \(s(d_k, q)\) is the retriever's score and \(\tau\) is a temperature. \(p_{\text{LM}}\) builds a target distribution from "how likely the generator is to produce the correct answer given this document", and training makes the retriever's distribution \(p_{\text{retr}}\) match it. The paper compared four retriever losses (attention distillation, EMDR², perplexity distillation and leave-one-out perplexity distillation), found little difference, and settled on perplexity distillation, which is stable and efficient. Fusion-in-Decoder (FiD) concatenates each document with the question and passes it through the encoder separately, and the decoder then reads the encodings of all documents at once through cross-attention, so the encoder's cost grows only linearly with the number of documents and dozens of documents can be read at once. 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; 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 cannot update its knowledge, gets only 2.9%.

(5) Remedies for 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

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 affects only "which documents become candidates", not the gradients themselves. Even so, the ablation shows that refreshing 30 times less often hurts quality noticeably. Re-encoding is also costly: REALM used 16 TPUs just for document encoding, and in Atlas's experiments rebuilding the full index every 1,000 steps added about 30% training overhead.

Follow-up questions

Follow-up 1: 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?

It means not specifying which document the answer comes from, but summing over all candidate documents weighted by their retrieval probabilities. Training maximizes only the likelihood of the final answer, and whichever document makes the answer more likely gets its retrieval probability raised. "Relevant" is thus defined implicitly by the generator's feedback, with no human labels needed.

Follow-up 2: What is the difference between RAG-Sequence and RAG-Token, and when does each fit?

The difference is whether documents are marginalized at the sequence level or the token level. RAG-Sequence generates the whole answer from one document and fits answers fully contained in one passage; RAG-Token lets each token rely on a different document and fits answers that combine information from several documents.

Follow-up 3: Why can't RAG-Sequence be decoded directly with beam search?

Because its likelihood does not factor into per-token terms. RAG-Sequence first computes the probability of the whole answer under each document and then sums across documents; the sum is outside the product, so there is no per-token transition probability for beam search to use. Beam search has to run separately for each document, and the candidates are then merged with thorough or fast decoding.

Follow-up 4: Why does the RAG paper keep the document encoder fixed?

Because updating the document encoder would require periodically rebuilding the index, which is costly, and experiments showed this step is unnecessary. With the document encoder fixed, the index stays valid throughout training, and fine-tuning only the query encoder and the generator already gives good results.

Follow-up 5: REALM's index is stale, so why are its gradients still accurate?

Because the stale index is used only to select candidates, while probabilities and gradients are recomputed with the latest parameters. The old index decides which k documents enter the candidate set; for those k documents, REALM recomputes the scores and \(p(z \mid x)\) with the current encoders, so the gradients themselves are accurate, and staleness affects only the quality of the candidate set.

Follow-up 6: Why can each chunk in RETRO only see the previous chunk's neighbors?

To preserve causality. A chunk's neighbors were retrieved using the content of the whole chunk, which contains information about the later tokens in that chunk; letting tokens inside the chunk see those neighbors would amount to seeing future tokens in advance.

Follow-up 7: Why can joint training collapse into "the generator ignores retrieved results", and how do you avoid it?

Because when the retriever starts out poor, the generator learns not to rely on documents, which in turn leaves the retriever without a signal. Once the generator ignores documents, every document helps prediction about equally, \(r(z) \approx 0\) in REALM's gradient, and the retriever cannot improve. The remedies are to warm up the retriever (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 (such as salient span masking).

Follow-up 8: Can you still train the retriever when the generator is a black-box API?

Yes, by distilling the retriever from the generator's output probabilities. REPLUG computes, for each retrieved document, the likelihood that the black-box LLM produces the correct answer conditioned on it, normalizes these into a target distribution, and trains the retriever to match it with a KL divergence. This needs only probabilities returned by the LLM, with no gradients and no fine-tuning of the LLM.

Common mistakes

  • Do not say that the top-k retrieval step can be back-propagated through directly: It is a discrete selection, and gradients reach the retrieval scores only via marginal likelihood or distillation.
  • Do not say that marginal likelihood lets the retriever discover any good document: Gradients land only on documents in the top k, so documents that never enter the top k get no signal.
  • Do not say that index staleness makes REALM's gradients inaccurate: Staleness affects only the candidate set; gradients are recomputed with the latest parameters.
  • Do not say that industry commonly trains the retriever and generator jointly end to end: The mainstream is decoupled training, with the retriever distilled from generator signals.

6.6 What is RAFT, and how can fine-tuning improve a model's use of retrieved content? ★★

One-sentence answer

RAFT targets domain-specific RAG and uses "SFT with distractor documents" to prepare the model for an open-book exam: each training example contains a question, several distractor documents and, in a fraction \(P\) of examples, the oracle document containing the answer, and the target is a chain-of-thought that quotes the evidence verbatim; the distractors teach the model to ignore irrelevant content, the examples without the oracle force it to store domain knowledge in its parameters, and the quoted CoT makes answers verifiable. More generally, RAG-specific instruction tuning (such as RA-DIT and ChatQA) uses data that mixes distractors, unanswerable examples, random positions and knowledge conflicts to teach the model to use the context better and to abstain when there is no answer.

I will address four aspects: the motivation for RAFT, how its training data is built, why each design works, and RAG-oriented instruction tuning more generally.

(1) RAFT's motivation is best explained by an open-book exam: you must learn the material and also learn to use the reference books.

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. SFT on domain data alone is like cramming for a closed-book exam: you memorize some knowledge, but you cannot use reference material during the exam, and anything you did not memorize you cannot answer. Doing RAG directly with a general model is like taking an open-book exam without studying: you can look things up, but you do not know the field, do not 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.

(2) RAFT's training data combines the question, the oracle document, distractor documents and a reasoning answer with quotes.

Each training example contains a question, a set of documents and a target answer. The documents come in two kinds: the oracle document contains the answer (there can be more than one; HotpotQA, for example, needs two), and the distractor documents 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, yet the target is still the correct answer; document order is shuffled. The paper's main setup is 1 oracle plus 4 distractors. The target is not a short answer but a chain-of-thought: it first quotes the relevant text from the documents verbatim, then reasons from the quotes, and finally gives the conclusion; these rationales are generated by GPT-4. Training itself is standard SFT, with the question plus documents as input and the rationale as the supervision target.

(3) Each of RAFT's three designs solves one problem.

  • Adding distractor documents teaches the model to tell relevant from irrelevant: 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. The paper found that models trained only with correct documents often do worse than models trained with distractors, and that the latter are also more robust when the number of documents changes at test time.
  • Dropping the oracle from some examples forces the model to store domain knowledge in its parameters: this is RAFT's most counterintuitive design. The context does not contain the answer at all, yet the model must still output the correct answer, 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, and on many datasets leaving the oracle out of some examples works better than always including it. There is a trade-off, however: 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 is not in the documents", so it should be set carefully in settings with strict faithfulness requirements.
  • Using a chain-of-thought with quotes as the target makes answers verifiable and the training signal richer: finding and quoting the evidence before concluding makes answers better grounded and easier to check, and the reasoning provides a much richer training signal than a short answer, reducing overfitting to answer strings.

(4) More generally, RAG-oriented instruction tuning uses purpose-built data to fix three bad habits general models show when using context.

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 bad habits: ignoring the context and trusting their parametric knowledge more; being distracted by irrelevant documents and writing unrelated content into the answer; and not abstaining, making something up when the material does not contain the answer. RA-DIT (Lin et al. 2023) splits joint training into two separate lightweight fine-tuning steps, sidestepping the difficulties of 6.5: it first fine-tunes the LLM with retrieved passages prepended to instruction data, so the model learns to use relevant information and ignore irrelevant information, and then fine-tunes the retriever with feedback from the LLM, so it returns the documents the LLM prefers. ChatQA (Liu et al. 2024) does ordinary SFT first and then "context-enhanced" instruction tuning, and found that adding a small number of unanswerable examples (with "cannot answer" as the target) teaches the model to say it does not know when the material lacks the answer, greatly reducing hallucination. The data recipe behind these methods is shared (see "Going deeper" below); general SFT methods are in the LLM Training Pipeline direction, Chapter 5.

In summary: the core of RAFT is simulating noisy test-time retrieval during training and using quoted reasoning as the target; RAG instruction tuning more generally uses distractors, unanswerable examples and conflict examples to train three abilities at once: using the context, ignoring noise and abstaining.

Comparing three approaches:

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

Going deeper: data format, results, limitations and the data recipe for RAG instruction tuning

(1) The two kinds of examples and the training template.

\[ \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} \]

Here \(Q\) is the question, \(D^*\) is the oracle document, \(D_1, \dots, D_k\) are the distractor documents, and \(A^*\) is the reasoning answer with quotes. Quotes are marked with ##begin_quote## and ##end_quote##, and the conclusion follows ##Answer::

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>

(2) Results.

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. The ablation shows that removing CoT drops HotpotQA performance from 35.28 to 25.62. The best \(P\) depends on the dataset: 40% or 60% for some datasets in the paper, 100% for others.

(3) Limitations.

RAFT 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.

(4) Details of RA-DIT and ChatQA.

In its retriever fine-tuning step, RA-DIT uses an LM-supervised signal similar to REPLUG's: whichever document makes the LLM more likely to produce the correct answer, the retriever learns to rank higher. 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. In addition, 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 3); and Yoran et al. (2023) mix irrelevant retrieved results into the training data so the model learns to ignore them (see 4.4).

(5) The data recipe for RAG-oriented instruction tuning.

  • Mix correct documents with distractors: trains the model to find useful information amid noise.
  • Include examples whose answer is not in the material, with abstention as the target: trains the model to say it does not know when the evidence is insufficient.
  • Place the correct document at random positions in the context: eases the model's under-use of the middle of the context.
  • Require answers to cite sources: makes answers verifiable.
  • Include examples where the context conflicts with the model's old knowledge: trains the model to go with the context (counterfactual data augmentation; see 4.7).

Follow-up questions

Follow-up 1: How does RAFT differ from ordinary domain SFT and ordinary RAG?

Domain SFT learns the knowledge but not how to use material, ordinary RAG uses material without learning the knowledge, and RAFT learns both. Domain SFT trains without retrieved documents, so the model does not learn to use material at test time; a general model doing RAG can use material but does not know the domain and is easily misled by irrelevant documents; RAFT mixes distractors into training and uses quoted reasoning as the target, so it learns the domain knowledge and also learns to use material amid noise.

Follow-up 2: Why does RAFT drop the oracle document from some training examples, and how is \(P\) chosen?

To force the model to store domain knowledge in its parameters and to keep it from trusting the context unconditionally. When the retriever misses the correct document, the model can still answer from memory. \(P\) has to be tuned per dataset: too low and the model learns to ignore the context, too high and the knowledge-memorization effect is lost; in settings that require "decline if it is not in the documents", the \(1-P\) examples are in tension with that requirement, so \(P\) should be set more conservatively.

Follow-up 3: Why does RAFT use a chain-of-thought with quotes as its training target?

Because it makes answers verifiable and provides a richer training signal. Quoting the original text before reasoning forces the model to find real evidence and makes the answer easier to check; the reasoning carries more information than a short answer, reducing overfitting to answer strings. The ablation shows that removing CoT drops HotpotQA performance from 35.28 to 25.62.

Follow-up 4: If you applied RAFT to your own product, how would you choose the distractor documents?

Ideally, pick hard negatives with the retriever you actually deploy. For each training question, take the top-k it returns and remove the documents that really contain the answer; what remains are hard negatives, which look related to the question but do not contain the answer, 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.

Follow-up 5: What typical problems do general models have in RAG, and if you were building instruction-tuning data for RAG, what kinds of examples would you include?

The typical problems are ignoring the context, being distracted by irrelevant documents and failing to abstain, and the data should include matching kinds of examples. I would include examples that mix correct documents with distractors, examples whose answer is not in the material with abstention as the target, examples with the correct document at random positions, examples that require citing sources, and examples where the context conflicts with the model's old knowledge with the context as the target, while also keeping examples where the context can answer and the model must answer, so it does not become overly conservative.

Common mistakes

  • Do not say that every RAFT training example contains the oracle document: A fraction \(1-P\) of the examples contain only distractors.
  • Do not say that RAFT is just ordinary domain SFT: Its key lies in the distractors, the examples without the oracle and the quoted reasoning target.
  • Do not lower \(P\) casually in settings with strict faithfulness requirements: The distractor-only examples teach the model to "answer even without evidence".
  • Do not treat a document that actually contains the answer as a distractor: That teaches the model to ignore useful evidence.