Chapter 25 of 40 · ~24 min read & lab+85 XP
Chapter 25 · Generative AI

RAG Evaluation Metrics: Precision@K, Recall@K, MRR, NDCG@K & Faithfulness

How to evaluate and debug production RAG systematically: Precision@K, Recall@K, Mean Reciprocal Rank (MRR), graded NDCG@K with logarithmic position discount, and the RAG Triad (Context Relevance, Faithfulness & Answer Relevance).

What Is It?

RAG Evaluation separates retrieval quality (Precision@K, Recall@K, MRR, NDCG@K) from generation quality (Faithfulness and Answer Relevance).

Why Is It Required?

If a RAG bot gives a wrong answer, you must know whether the retriever failed to fetch the right paragraph or the LLM ignored the retrieved evidence.

Everyday Analogy: Separating 'did the research assistant hand the writer the right source?' (retrieval) from 'did the writer accurately summarize it?' (faithfulness).
Why ML Engineers & Data Scientists Actually Need This

Never tune prompts when your Retriever has 40% Recall@5 — evaluating Retriever and Generator separately is the #1 secret of top RAG teams!

ML / AI Engineer

Tracking Recall@5, MRR, and NDCG@5 on a 100-question golden dataset lets you A/B test chunk sizes, embeddings, BM25+RRF, and rerankers in 30 seconds without even calling an LLM!

Data Scientist

Pairing IR metrics with Faithfulness (checking that every claim in the LLM's answer is entailed by the retrieved chunks) catches subtle hallucinations automatically.

Interview & Debug Edge

Guaranteed RAG interview question: 'How do you measure if a RAG failure is a retrieval bug or a generation bug, and when do you use NDCG@K instead of MRR?'

Step 0 · Test Your Gut Before Any Math!

When should you prefer NDCG@K over MRR to evaluate your RAG retriever?

What You Will Master in This Chapter
  • Compute Precision@K, Recall@K, and Mean Reciprocal Rank (MRR) from retrieved vs. ground-truth document IDs
  • Compute graded NDCG@K = DCG@K / IDCG@K using both gain (2^rel − 1) and position discount 1/log₂(rank + 1)
  • Separate Retriever evaluation (offline IR metrics) from Generator evaluation (RAG Triad: Context Relevance, Faithfulness, Answer Relevance)
  • Diagnose whether a bad RAG answer was caused by a Retriever miss vs. an LLM hallucination in seconds
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
Precision@K,Recall@K\text{Precision@}K, \text{Recall@}KSay aloud:“precision & recall at K”
Plain-English Meaning
Precision@K = hits/K (purity); Recall@K = hits/|Relevant| (completeness)
Everyday Example
2 hits in Top-5 out of 4 total → P@5=0.4, R@5=0.5
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Evaluating RAG is like grading an open-book exam: first check whether the student brought the right pages to the desk (Recall@K, MRR, NDCG@K). Then check whether their written answer actually stayed faithful to those pages instead of making up facts from thin air (Faithfulness) and actually answered the question asked (Answer Relevance)!

1. Binary Retrieval Metrics: Precision@K, Recall@K & MRR

Everyday Story First (Zero Math Yet!)

Every RAG retrieval benchmark starts with these three fast, deterministic metrics.

Core Retrieval Metrics: Precision@K, Recall@K & MRRPrecision@K(Rel in Top-K) / KPurity of retrieved contextRecall@K(Rel in Top-K) / Total RelCompleteness of evidenceMRRmean( 1 / rank_first )How early the 1st hit lands!
Precision@K measures signal purity in top-K, Recall@K measures how much total relevant truth you found, and MRR (1/rank_first) measures how high the very first relevant chunk appears.

Quick Definitions

Given retrieved list R1:KR_{1:K} and ground-truth relevant set GG:

  • Precision@K: ∣R1:K∩G∣K\frac{|R_{1:K} \cap G|}{K} — are we wasting LLM context tokens on junk?
  • Recall@K: ∣R1:K∩G∣∣G∣\frac{|R_{1:K} \cap G|}{|G|} — did we retrieve all the facts needed to answer? (Most critical metric for Stage-1 retrieval!)
  • MRR: 1rfirst\frac{1}{r_{\text{first}}} where rfirstr_{\text{first}} is the 1-indexed position of the first relevant document (0.0 if none in Top-K).

2. Graded Ranking Quality: NDCG@K & Logarithmic Discount

Everyday Story First (Zero Math Yet!)

Click Rank #1 / #2 / #3 in the mini-lab below to see how moving a 3-star gold document down by just 1 slot slashes both MRR and NDCG@3!

NDCG@K Position Discount Weight: 1 / log₂(rank + 1)1.00Rank #10.63Rank #20.50Rank #30.43Rank #40.39Rank #5
NDCG@K handles graded relevance (0, 1, 2, 3) with a logarithmic position discount 1/log₂(rank+1), rewarding systems that put 3-star gold chunks at Rank #1!

The Exact NDCG@K Formula

DCG@K=∑i=1K2reli−1log⁡2(i+1),NDCG@K=DCG@KIDCG@K\text{DCG@}K = \sum_{i=1}^{K} \frac{2^{\text{rel}_i} - 1}{\log_2(i + 1)}, \qquad \text{NDCG@}K = \frac{\text{DCG@}K}{\text{IDCG@}K} where IDCG@K\text{IDCG@}K is the DCG of the ideal ranking (sorting all ground-truth relevances descending). If IDCG@K=0\text{IDCG@}K = 0 (no relevant docs exist), define NDCG@K=0.0\text{NDCG@}K = 0.0!

Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of NDCG@K

DCG@K = Σ (2^rel_i − 1) / log₂(i + 1)

Exponential Relevance Gain

Strongly separates 3-star gold docs (gain=7) from 1-star weak hints (gain=1)!

In our example: rel=0→0, 1→1, 2→3, 3→7
Put it together with real numbers: For relevances [3, 0, 1] vs. ideal [3, 1, 0]: DCG = 7/1 + 0/1.585 + 1/2 = 7.50; IDCG = 7/1 + 1/1.585 + 0 = 7.631 → NDCG@3 = 0.983!
Animated Mini-Lab • 4.6

Move the Gold Doc (Rel = 3) to See MRR & NDCG@3

MRR (1 / rank_gold)
1.000
NDCG@3 (Graded Quality)
1.000

3. End-to-End Diagnostics: The RAG Triad

Everyday Story First (Zero Math Yet!)

Use the RAG Triad (popularized by TruLens & RAGAS) to isolate every production bug cleanly.

The RAG Evaluation Triad: Pinpoint Retriever vs. Generator Bugs1. Context RelevanceQuery ↔ ContextLow → Fix Chunking / Hybrid Search2. FaithfulnessContext ↔ AnswerLow → LLM Hallucinated!3. Answer RelevanceQuery ↔ AnswerLow → Fix Prompt / Reranker
The RAG Triad isolates every failure mode: Context Relevance (Retriever bug), Faithfulness / Groundedness (Hallucination bug), and Answer Relevance (Prompt/Generator bug).

Pinpointing the Exact Broken Component

  1. Context Relevance (Query ↔ Retrieved Chunks): Low? → Retriever bug! Fix chunking, add Hybrid BM25+RRF, or add Cross-Encoder reranking.
  2. Faithfulness / Groundedness (Retrieved Chunks ↔ LLM Answer): Low? → Hallucination bug! Tighten system prompt ("Answer ONLY from context; say I don't know if missing"), lower temperature, or add inline citations.
  3. Answer Relevance (Query ↔ LLM Answer): Low despite good context? → Generator / Prompt bug!
Walk Through With Me · Interactive Worked Example

Worked Example: Computing P@4, R@4 & MRR

Ground-truth relevant docs G = {'D2', 'D5', 'D9'}. Retrieved Top-4: ['D1', 'D5', 'D8', 'D2'].

11. Count hits in Top-4Step 1 / 3

Hits = {'D5', 'D2'} → 2 hits.

Teacher's Note: D9 was missed in Top-4.
Pause & Check · Quick Intuition Pulse

Your RAG system has Context Relevance = 0.94 and Answer Relevance = 0.88, but Faithfulness = 0.35. What is happening?

Try It YourselfStandard

Why does increasing K from Top-5 to Top-50 always increase (or maintain) Recall@K while usually DECREASING Precision@K?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Use Synthetic Data Generation: sample 100 diverse chunks from your corpus, prompt a frontier LLM to generate realistic user questions answerable only from each chunk, and have a domain expert quickly review/filter them!

Interactive Visual Lab
Lab Challenge: Inspect all 3 failure-mode presets in the 60 FPS RAG Failure-Mode Doctor to diagnose Retriever vs. Hallucination bugs.
Interactive Animation • 4.6 Deep Lab

RAG Failure-Mode Doctor (RAG Triad Diagnostics)

Switch between production failure modes to diagnose whether the Retriever or the Generator is broken.

Case A: Retriever Miss
Context Rel
25%
Faithfulness
95%
Answer Rel
30%
Diagnosis: Low Context Relevance → Add Hybrid BM25+RRF & Contextual Chunking!
0%
Case A: Retriever Miss
Intuition Takeaway: Evaluate RAG in two halves: deterministic IR metrics (Recall@K, MRR, NDCG@K) for your Retriever, and the RAG Triad (Context Relevance, Faithfulness, Answer Relevance) to separate retrieval misses from LLM hallucinations.
Where This Powers Real ML, Deep Learning & Generative AI

Automated RAG CI/CD Regression Gates

Blocks deployments automatically if Recall@5 or Faithfulness drops by >2% on the golden eval suite.

Production NumPy & PyTorch Code Patterns
import math

# Core RAG Retrieval Metrics: Precision@K, Recall@K, MRR & NDCG@K
def eval_retrieval(retrieved: list[str], relevant: set[str], k: int = 4) -> dict:
    top_k = retrieved[:k]
    hits = [1 if d in relevant else 0 for d in top_k]
    precision = sum(hits) / k
    recall = sum(hits) / max(1, len(relevant))
    mrr = next((1.0 / (i + 1) for i, h in enumerate(hits) if h), 0.0)
    dcg = sum(h / math.log2(i + 2) for i, h in enumerate(hits))
    idcg = sum(1.0 / math.log2(i + 2) for i in range(min(k, len(relevant))))
    return {"P@K": round(precision, 2), "R@K": round(recall, 2), "MRR": round(mrr, 2), "NDCG@K": round(dcg / max(1e-9, idcg), 2)}

print(eval_retrieval(["d9", "d2", "d7", "d1"], relevant={"d1", "d2", "d5"}, k=4))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Dividing by zero in NDCG@K when a query has zero relevant documents (IDCG@K = 0).
Best Practice: Explicitly return 0.0 whenever idcg == 0!
Chapter Mastery Check (+85 XP)
Score: 0 / 2
1If the first relevant document appears at Rank #4 in a retrieved list, what is its Reciprocal Rank (RR)?
2In the RAG Triad, which metric directly detects LLM hallucinations (claims not supported by the retrieved context)?

Apply What You Learned — Solve Matching Coding Problems