Evaluating Retrieval and RAG
A RAG system can fail in two places: the right chunk never reaches the prompt, or it does and the answer is still wrong. One end-to-end score ("the bot was right 70% of the time") cannot tell those apart, so it cannot tell you what to fix. Evaluating LLM Apps introduced test sets, simple metrics and LLM judges. This lesson turns that into a measurement kit for RAG, stage by stage: retrieval metrics with graded relevance, answer metrics as SQuAD defines them, a faithfulness check per claim, an LLM judge with its known biases, and a failure analysis that assigns every wrong answer to the stage that caused it.
Everything runs on the TAD Bikes help centre and its 12 questions from Building a RAG Pipeline, with the same BM25 index and the same extractive reader, so the numbers can be compared with that lesson.
Relevance judgements
Retrieval metrics compare a ranking with relevance judgements (qrels): for each query, which chunks are relevant and how much. Binary labels ("chunk 5 answers it") are enough for recall and MRR; graded labels add "related, useful context" and let a metric reward a ranking that puts the answer first and the context second. Here grade 2 means "answers the question" (the article the course notes list for each query) and grade 1 means "related": for "how much does one hour cost", the day-pass article is related.
Let be the set of grade-2 chunks for query , the ranking and its top . Averaged over the queries:
where is the position of the first grade-2 chunk (and if there is none). With graded relevance , discounted cumulative gain sums the grades with a logarithmic discount, and nDCG divides by the DCG of the ideal ordering, so a perfect ranking scores 1:
This is the linear-gain form that scikit-learn's ndcg_score uses. Many IR papers use the gain instead, which rewards highly relevant documents more; say which one you report.
docs = [
"Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
"A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
"To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
"If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
"Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
"If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
"Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
"Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
"Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
"Helmets are not included in the rental, but we recommend wearing one on every ride.",
"You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
"Refunds for a ride that was charged twice are sent to the original card within five working days.",
"A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
"Our support team answers chat messages every day from 7 am to 10 pm.",
"Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
"Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [ # (query, id of the relevant document)
("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
("can I hold a bike for later", 15),
]
import re, math
from collections import Counter
from nltk.stem import PorterStemmer
STOP = set("a an and are as at be but by for if in into is it no not of on or such that the their "
"then there these they this to was will with".split()) # the short list of keyword-retrieval
stem = PorterStemmer().stem
def tokens(text): # lowercase, words of 2+ characters, stop words out, Porter stems
return [stem(w) for w in re.findall(r"\b\w\w+\b", text.lower()) if w not in STOP]
class BM25:
def __init__(self, texts, k1=1.5, b=0.75):
self.docs = [Counter(tokens(t)) for t in texts]
self.len = [sum(d.values()) for d in self.docs]
self.avg = sum(self.len) / len(self.len)
df = Counter(w for d in self.docs for w in d)
n = len(texts)
self.idf = {w: math.log((n - c + 0.5) / (c + 0.5) + 1) for w, c in df.items()}
self.k1, self.b = k1, b
def scores(self, query):
out = []
for d, L in zip(self.docs, self.len):
s = 0.0
for w in tokens(query):
f = d.get(w, 0)
if f:
s += self.idf[w] * f * (self.k1 + 1) / (f + self.k1 * (1 - self.b + self.b * L / self.avg))
out.append(s)
return out
def search(self, query, k=3):
s = self.scores(query)
top = sorted(range(len(s)), key=lambda i: (-s[i], i))[:k]
return [(i, round(s[i], 2)) for i in top]
import math
# graded relevance: 2 = answers the question, 1 = related (useful context)
qrels = [{0: 2, 1: 1}, {1: 2, 0: 1}, {3: 2, 2: 1}, {5: 2, 4: 1}, {6: 2}, {7: 2},
{8: 2}, {10: 2}, {11: 2}, {12: 2}, {14: 2}, {15: 2}]
def recall_at(ranking, rel, k): # share of the answering chunks found in the top k
answer = {d for d, g in rel.items() if g == 2}
return len(answer & set(ranking[:k])) / len(answer)
def precision_at(ranking, rel, k): # share of the top k that is relevant at all (grade >= 1)
return sum(d in rel for d in ranking[:k]) / k
def reciprocal_rank(ranking, rel):
for r, d in enumerate(ranking, 1):
if rel.get(d) == 2:
return 1 / r
return 0.0
def ndcg_at(ranking, rel, k):
dcg = sum(rel.get(d, 0) / math.log2(r + 1) for r, d in enumerate(ranking[:k], 1))
ideal = sorted(rel.values(), reverse=True)[:k]
return dcg / sum(g / math.log2(r + 1) for r, g in enumerate(ideal, 1))
import numpy as np
from sklearn.metrics import ndcg_score
index = BM25(docs)
rows = []
print(f"{'query':<48} R@3 P@3 RR nDCG@5")
for (q, _), rel in zip(queries, qrels):
s = index.scores(q)
ranking = sorted(range(len(docs)), key=lambda j: (-s[j], j))
row = [recall_at(ranking, rel, 3), precision_at(ranking, rel, 3),
reciprocal_rank(ranking, rel), ndcg_at(ranking, rel, 5)]
rows.append(row)
print(f"{q:<48} {row[0]:.0f} {row[1]:.2f} {row[2]:.2f} {row[3]:.2f}")
mean = np.mean(rows, axis=0)
print(f"{'mean over 12 queries':<48} {mean[0]:.2f} {mean[1]:.2f} {mean[2]:.2f} {mean[3]:.2f}")
# check our nDCG with scikit-learn (same linear gain, same log2 discount)
q, rel = queries[0][0], qrels[0]
true = np.array([[rel.get(j, 0) for j in range(len(docs))]])
print("sklearn nDCG@5 for query 1:", round(float(ndcg_score(true, np.array([index.scores(q)]), k=5)), 2))query R@3 P@3 RR nDCG@5
how much does one hour cost 1 0.67 1.00 1.00
price for a whole day 1 0.33 0.33 0.54
the lock will not open 1 0.33 1.00 0.92
where do I leave the bike when the dock is full 1 0.67 1.00 1.00
my bike has a flat tyre 0 0.00 0.25 0.43
how far can an e-bike go 0 0.00 0.17 0.00
can my 12 year old rent a bike 1 0.33 1.00 1.00
do you take cash 1 0.33 1.00 1.00
I was charged twice 1 0.33 1.00 1.00
what happens if my bike is stolen 0 0.00 0.17 0.00
discount for students 1 0.33 1.00 1.00
can I hold a bike for later 1 0.33 1.00 1.00
mean over 12 queries 0.75 0.31 0.74 0.74
sklearn nDCG@5 for query 1: 1.0
Mean recall@3 is 0.75 (9 of 12, as in the previous lesson), MRR 0.74 and nDCG@5 0.74 for BM25. The columns tell different stories:
- Precision@3 is capped. Most queries have one relevant chunk, so precision@3 can be at most for them; the mean of 0.31 says little. Precision matters when there are many relevant chunks (and for the token cost of irrelevant ones in the prompt); for "one answer somewhere in the help centre", recall@k and MRR are the metrics.
- MRR sees rank. "price for a whole day" is a hit at 3 (recall@3 = 1) but its reciprocal rank is 0.33: the reader has to dig through two wrong articles first.
- nDCG sees the related chunk. "the lock will not open" has the answer first (RR = 1), but its related article 2 ("To unlock a bike...") scores 0 ("unlock" and "lock" are different stems) and lands at rank 4 only by tie-breaking, so nDCG@5 is 0.92, not 1.
- The check against scikit-learn gives the same 1.0 for the first query. Mind ties:
ndcg_scoreaverages over tied scores, while our ranking breaks ties by article number. With BM25's many zero scores they differ on some queries, which is why the check uses a query without ties.
Answer metrics: exact match and token F1
When a gold answer exists, the standard extractive-QA metrics are those of the SQuAD benchmark: both prediction and gold are normalised (lower case, punctuation and the articles "a", "an", "the" removed, whitespace collapsed); exact match (EM) is 1 if they are identical, and token F1 is the harmonic mean of precision and recall over the bag of tokens:
with the multiset intersection. With several accepted answers, take the maximum over them. Faithfulness (also called groundedness) is a different question: not "does the answer match the gold?" but "is every claim in the answer supported by the retrieved sources?". A cheap version splits the answer into claims (sentences), counts a claim as supported if at least 80% of its content words occur in one source and every number in it occurs in a source, and reports the share of supported claims.
import re, string
from collections import Counter
def normalize(text): # the SQuAD evaluation script's normalisation
text = "".join(ch for ch in text.lower() if ch not in set(string.punctuation))
text = re.sub(r"\b(a|an|the)\b", " ", text)
return " ".join(text.split())
def exact_match(pred, golds):
return max(float(normalize(pred) == normalize(g)) for g in golds)
def token_f1(pred, golds):
def f1(p, g):
p, g = normalize(p).split(), normalize(g).split()
common = sum((Counter(p) & Counter(g)).values())
if common == 0:
return 0.0
prec, rec = common / len(p), common / len(g)
return 2 * prec * rec / (prec + rec)
return max(f1(pred, g) for g in golds)
cases = [ # (prediction, accepted gold answers)
("15 euros.", ["15 euros", "fifteen euros"]),
("A day pass costs 15 euros", ["15 euros", "fifteen euros"]),
("It is about 60 km on a full battery", ["about 60 km", "60 km"]),
("Within five working days", ["within five working days"]),
("Within 5 working days", ["within five working days"]),
("400 euros", ["a fee of 400 euros"]),
("Cash is accepted", ["cash is not accepted", "no"]),
]
print(f"{'prediction':<38} EM F1")
for pred, golds in cases:
print(f"{pred:<38} {exact_match(pred, golds):.0f} {token_f1(pred, golds):.2f}")
# faithfulness: share of the answer's claims that the retrieved sources support
def content(text):
stop = {"the", "a", "an", "is", "are", "and", "it", "of", "to", "for", "on", "in", "you", "be", "can"}
return [w for w in normalize(text).split() if w not in stop]
def supported(claim, sources, min_share=0.8):
words = content(claim)
best = max(sum(w in content(s) for w in words) / len(words) for s in sources)
nums_ok = all(any(n in s for s in sources) for n in re.findall(r"\d+", claim))
return best >= min_share and nums_ok
def faithfulness(answer, sources):
claims = [c for c in re.split(r"(?<=[.!?])\s+", answer) if c]
ok = [supported(c, sources) for c in claims]
return sum(ok) / len(claims), ok
sources = ["A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock."]
for answer in ["A day pass costs 15 euros. It covers unlimited rides for 24 hours.",
"A day pass costs 15 euros. It includes a free helmet.",
"A day pass costs 15 euros. It is valid for 48 hours."]:
score, ok = faithfulness(answer, sources)
print(f"faithfulness {score:.2f} {ok} {answer}")prediction EM F1
15 euros. 1 1.00
A day pass costs 15 euros 0 0.57
It is about 60 km on a full battery 0 0.55
Within five working days 1 1.00
Within 5 working days 0 0.75
400 euros 0 0.67
Cash is accepted 0 0.86
faithfulness 1.00 [True, True] A day pass costs 15 euros. It covers unlimited rides for 24 hours.
faithfulness 0.50 [True, False] A day pass costs 15 euros. It includes a free helmet.
faithfulness 0.50 [True, False] A day pass costs 15 euros. It is valid for 48 hours.
- "15 euros." scores EM 1 after normalisation (the full stop is removed). "A day pass costs 15 euros" is correct and complete but gets EM 0 and F1 0.57: EM punishes verbose readers, which is why generative RAG is rarely scored by EM.
- "Within 5 working days" against "within five working days" gets F1 0.75. Normalise numbers too, or accept both forms in the gold set.
- "Cash is accepted" gets F1 0.86, nearly full marks, while it says the opposite of the gold "cash is not accepted". Token overlap does not understand negation. Use F1 to track a reader, never as the only check of correctness.
- The faithfulness check passes the first answer (1.00) and gives 0.50 to the other two: "includes a free helmet" is not in the source, and "48 hours" contradicts its "24 hours". The first is a claim from outside the sources, the second a distorted one; both are what users call hallucinations (Hallucinations).
Production systems replace the word-overlap test with an entailment model (natural language inference: does the source entail the claim?) or with an LLM judge asked claim by claim. Frameworks such as RAGAS (Es et al., 2023) package these as "faithfulness", "answer relevancy" and "context precision", computed by an LLM. Know that they are judge prompts, with the biases below.
LLM as a judge
For free-form answers without a single gold string, a strong model grades answers against a rubric. This is reference code, not run here; client.generate stands for any chat API:
RUBRIC = """You grade answers of a bike-rental help assistant.
<question>{question}</question>
<sources>{sources}</sources>
<answer>{answer}</answer>
Score each criterion and reply with JSON only:
{{"supported": 0-2, // 2: every claim is in the sources; 1: minor unsupported detail; 0: a wrong or invented fact
"answers": 0-2, // 2: answers the question fully; 1: partly; 0: does not
"refusal_ok": true|false, // refused exactly when the sources do not contain the answer
"evidence": "<the source sentence that supports the main claim, copied>"}}"""
def judge(item):
reply = client.generate(RUBRIC.format(**item), temperature=0, max_tokens=200)
return json.loads(reply)Ask for evidence (a quote) and small integer scales: a judge is more consistent on "0, 1 or 2 with a reason" than on "rate from 1 to 10". Then measure the judge like any other classifier:
- Position bias: in pairwise comparisons judges prefer the answer shown first (or second, depending on the model). Run both orders and count a win only if it survives the swap.
- Verbosity bias: longer answers get higher scores even when they add nothing. Control length or state in the rubric that extra text is not rewarded.
- Self-preference: a judge tends to rate answers in its own style higher, so a judge from the same model family as the system flatters it.
- Agreement with humans: label 50 to 100 items by hand and report the judge's agreement (accuracy, or Cohen's ) before trusting it on thousands. The pairwise version, with confidence intervals and ratings, is in Evaluating LLMs.
A golden set
The 12 TAD Bikes questions are a toy golden set. A real one is built, not scraped:
- Sources of questions: real user questions from logs (anonymised, with consent under your privacy policy), plus questions written by support staff for the important articles, plus adversarial ones: unanswerable ("is there a night tariff?"), ambiguous, multi-hop ("what does a lost e-bike cost a student?"), and injection attempts.
- Labels per question: the relevant chunk ids with grades, a short gold answer (several accepted forms), and whether it should be refused.
- Size: with questions and a success rate near 0.8, the standard error of a rate is : 0.115 for , 0.028 for . A few hundred questions are the minimum to see a 5-point change.
- Stable ids and versioning: label chunks by stable ids (previous lesson) and version the set with the index. When documents change, re-check the labels that point at them.
- Never tune on it alone. Keep a held-out part that no prompt or setting was tuned on, as for any model (leakage rules).
Failure analysis by stage
With chunk labels and gold answers, every question falls into exactly one bucket: retrieval miss (no grade-2 chunk in the top given to the reader), reader error (the chunk was there, but the answer's F1 is below a threshold, here 0.5), or correct. The buckets point at different fixes: a retriever, an embedding model or chunking for the first; a reader, a prompt or a bigger model for the second.
docs = [
"Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
"A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
"To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
"If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
"Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
"If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
"Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
"Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
"Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
"Helmets are not included in the rental, but we recommend wearing one on every ride.",
"You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
"Refunds for a ride that was charged twice are sent to the original card within five working days.",
"A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
"Our support team answers chat messages every day from 7 am to 10 pm.",
"Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
"Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [ # (query, id of the relevant document)
("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
("can I hold a bike for later", 15),
]
import re, math
from collections import Counter
from nltk.stem import PorterStemmer
STOP = set("a an and are as at be but by for if in into is it no not of on or such that the their "
"then there these they this to was will with".split()) # the short list of keyword-retrieval
stem = PorterStemmer().stem
def tokens(text): # lowercase, words of 2+ characters, stop words out, Porter stems
return [stem(w) for w in re.findall(r"\b\w\w+\b", text.lower()) if w not in STOP]
class BM25:
def __init__(self, texts, k1=1.5, b=0.75):
self.docs = [Counter(tokens(t)) for t in texts]
self.len = [sum(d.values()) for d in self.docs]
self.avg = sum(self.len) / len(self.len)
df = Counter(w for d in self.docs for w in d)
n = len(texts)
self.idf = {w: math.log((n - c + 0.5) / (c + 0.5) + 1) for w, c in df.items()}
self.k1, self.b = k1, b
def scores(self, query):
out = []
for d, L in zip(self.docs, self.len):
s = 0.0
for w in tokens(query):
f = d.get(w, 0)
if f:
s += self.idf[w] * f * (self.k1 + 1) / (f + self.k1 * (1 - self.b + self.b * L / self.avg))
out.append(s)
return out
def search(self, query, k=3):
s = self.scores(query)
top = sorted(range(len(s)), key=lambda i: (-s[i], i))[:k]
return [(i, round(s[i], 2)) for i in top]
import re, string
from collections import Counter
def normalize(text): # the SQuAD evaluation script's normalisation
text = "".join(ch for ch in text.lower() if ch not in set(string.punctuation))
text = re.sub(r"\b(a|an|the)\b", " ", text)
return " ".join(text.split())
def exact_match(pred, golds):
return max(float(normalize(pred) == normalize(g)) for g in golds)
def token_f1(pred, golds):
def f1(p, g):
p, g = normalize(p).split(), normalize(g).split()
common = sum((Counter(p) & Counter(g)).values())
if common == 0:
return 0.0
prec, rec = common / len(p), common / len(g)
return 2 * prec * rec / (prec + rec)
return max(f1(pred, g) for g in golds)
golds = [
"the first 30 minutes cost 2 euros and every extra hour costs 3 euros",
"a day pass costs 15 euros", "check that Bluetooth is on and move closer to the bike",
"the app shows the nearest station with free docks", "report a damaged bike in the app",
"about 60 km", "children under 14 may not rent bikes", "cash is not accepted",
"refunds are sent to the original card within five working days",
"report it within 24 hours, otherwise a fee of 400 euros is charged",
"30 percent off the monthly pass", "bikes can be reserved for up to 10 minutes",
]
index = BM25(docs)
def reader(question, ids): # the extractive reader of the previous lesson
q = set(tokens(question))
best = (0, "I don't know")
for d in ids:
for sent in re.split(r"(?<=\.) ", docs[d]):
overlap = len(q & set(tokens(sent)))
if overlap > best[0]:
best = (overlap, sent)
return best[1]
stages = Counter()
for (q, rel), gold in zip(queries, golds):
ids = [i for i, s in index.search(q, k=3) if s > 0]
pred = reader(q, ids)
f1 = token_f1(pred, [gold])
if rel not in ids:
stage = "retrieval miss"
elif f1 < 0.5:
stage = "reader error"
else:
stage = "correct"
stages[stage] += 1
print(f"{stage:<15} F1 {f1:.2f} {q:<44} -> {pred}")
print(dict(stages))
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
print('"full" in our stop list:', "full" in STOP, "| in scikit-learn's:", "full" in ENGLISH_STOP_WORDS)correct F1 1.00 how much does one hour cost -> The first 30 minutes cost 2 euros and every extra hour costs 3 euros.
reader error F1 0.00 price for a whole day -> Refunds for a ride that was charged twice are sent to the original card within five working days.
correct F1 0.71 the lock will not open -> If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.
correct F1 0.61 where do I leave the bike when the dock is full -> If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.
retrieval miss F1 0.20 my bike has a flat tyre -> To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.
retrieval miss F1 0.00 how far can an e-bike go -> Bikes can be reserved for up to 10 minutes before unlocking.
correct F1 1.00 can my 12 year old rent a bike -> Children under 14 may not rent bikes.
reader error F1 0.00 do you take cash -> You can pay with a credit card, a debit card or the app wallet.
correct F1 0.77 I was charged twice -> Refunds for a ride that was charged twice are sent to the original card within five working days.
retrieval miss F1 0.00 what happens if my bike is stolen -> To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.
correct F1 0.53 discount for students -> Students get 30 percent off the monthly pass with a valid student card uploaded in the app.
correct F1 0.90 can I hold a bike for later -> Bikes can be reserved for up to 10 minutes before unlocking.
{'correct': 7, 'reader error': 2, 'retrieval miss': 3}
"full" in our stop list: False | in scikit-learn's: True
Seven of 12 are correct, three are retrieval misses ("flat tyre", "e-bike", "stolen", all vocabulary mismatch), and two are reader errors. Each reader error has its own cause, and so does one "correct" answer:
- "do you take cash": article 10 is retrieved first, but its first sentence shares "you" with the question and its second shares "cash"; on the tie the reader takes the first sentence, "You can pay with a credit card...", which does not answer the question. A reader that weights rare terms (like BM25's idf) would prefer "cash".
- "price for a whole day": the reader picks article 11 for "days".
- "can I hold a bike for later" counts as correct (F1 0.90), but only because "can" and "bike" happen to select the reservation sentence; "hold" matched nothing. A lucky hit passes every metric, so read the answers, not only the scores.
- The analyser matters for the reader too. The last line shows that scikit-learn's stop list contains "full"; with that list, the reader loses the word that marks article 5 on "where do I leave the bike when the dock is full" and answers "Return the bike at any station." from article 4. A preprocessing choice made for retrieval can silently damage the reader.
Dense retrieval and a confidence interval (recorded)
The same metrics for MiniLM embeddings, with a paired bootstrap over queries: resample the 12 queries with replacement, recompute the MRR difference, and read the 2.5th and 97.5th percentiles. Paired, because both systems answer the same queries; the per-query differences carry the comparison.
import numpy as np
from sentence_transformers import SentenceTransformer
docs = [
"Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
"A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
"To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
"If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
"Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
"If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
"Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
"Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
"Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
"Helmets are not included in the rental, but we recommend wearing one on every ride.",
"You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
"Refunds for a ride that was charged twice are sent to the original card within five working days.",
"A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
"Our support team answers chat messages every day from 7 am to 10 pm.",
"Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
"Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [ # (query, id of the relevant document)
("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
("can I hold a bike for later", 15),
]
import re, math
from collections import Counter
from nltk.stem import PorterStemmer
STOP = set("a an and are as at be but by for if in into is it no not of on or such that the their "
"then there these they this to was will with".split()) # the short list of keyword-retrieval
stem = PorterStemmer().stem
def tokens(text): # lowercase, words of 2+ characters, stop words out, Porter stems
return [stem(w) for w in re.findall(r"\b\w\w+\b", text.lower()) if w not in STOP]
class BM25:
def __init__(self, texts, k1=1.5, b=0.75):
self.docs = [Counter(tokens(t)) for t in texts]
self.len = [sum(d.values()) for d in self.docs]
self.avg = sum(self.len) / len(self.len)
df = Counter(w for d in self.docs for w in d)
n = len(texts)
self.idf = {w: math.log((n - c + 0.5) / (c + 0.5) + 1) for w, c in df.items()}
self.k1, self.b = k1, b
def scores(self, query):
out = []
for d, L in zip(self.docs, self.len):
s = 0.0
for w in tokens(query):
f = d.get(w, 0)
if f:
s += self.idf[w] * f * (self.k1 + 1) / (f + self.k1 * (1 - self.b + self.b * L / self.avg))
out.append(s)
return out
def search(self, query, k=3):
s = self.scores(query)
top = sorted(range(len(s)), key=lambda i: (-s[i], i))[:k]
return [(i, round(s[i], 2)) for i in top]
import math
# graded relevance: 2 = answers the question, 1 = related (useful context)
qrels = [{0: 2, 1: 1}, {1: 2, 0: 1}, {3: 2, 2: 1}, {5: 2, 4: 1}, {6: 2}, {7: 2},
{8: 2}, {10: 2}, {11: 2}, {12: 2}, {14: 2}, {15: 2}]
def recall_at(ranking, rel, k): # share of the answering chunks found in the top k
answer = {d for d, g in rel.items() if g == 2}
return len(answer & set(ranking[:k])) / len(answer)
def precision_at(ranking, rel, k): # share of the top k that is relevant at all (grade >= 1)
return sum(d in rel for d in ranking[:k]) / k
def reciprocal_rank(ranking, rel):
for r, d in enumerate(ranking, 1):
if rel.get(d) == 2:
return 1 / r
return 0.0
def ndcg_at(ranking, rel, k):
dcg = sum(rel.get(d, 0) / math.log2(r + 1) for r, d in enumerate(ranking[:k], 1))
ideal = sorted(rel.values(), reverse=True)[:k]
return dcg / sum(g / math.log2(r + 1) for r, g in enumerate(ideal, 1))
import re, string
from collections import Counter
def normalize(text): # the SQuAD evaluation script's normalisation
text = "".join(ch for ch in text.lower() if ch not in set(string.punctuation))
text = re.sub(r"\b(a|an|the)\b", " ", text)
return " ".join(text.split())
def exact_match(pred, golds):
return max(float(normalize(pred) == normalize(g)) for g in golds)
def token_f1(pred, golds):
def f1(p, g):
p, g = normalize(p).split(), normalize(g).split()
common = sum((Counter(p) & Counter(g)).values())
if common == 0:
return 0.0
prec, rec = common / len(p), common / len(g)
return 2 * prec * rec / (prec + rec)
return max(f1(pred, g) for g in golds)
golds = [
"the first 30 minutes cost 2 euros and every extra hour costs 3 euros",
"a day pass costs 15 euros", "check that Bluetooth is on and move closer to the bike",
"the app shows the nearest station with free docks", "report a damaged bike in the app",
"about 60 km", "children under 14 may not rent bikes", "cash is not accepted",
"refunds are sent to the original card within five working days",
"report it within 24 hours, otherwise a fee of 400 euros is charged",
"30 percent off the monthly pass", "bikes can be reserved for up to 10 minutes",
]
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
D = model.encode(docs, normalize_embeddings=True)
Q = model.encode([q for q, _ in queries], normalize_embeddings=True)
bm25 = BM25(docs)
rankings = {
"BM25": [sorted(range(16), key=lambda j, s=bm25.scores(q): (-s[j], j)) for q, _ in queries],
"MiniLM": [[int(j) for j in np.argsort(-(Q[i] @ D.T), kind="stable")] for i in range(12)],
}
per_query = {}
for name, ranks in rankings.items():
m = np.array([[recall_at(r, rel, 3), precision_at(r, rel, 3), reciprocal_rank(r, rel), ndcg_at(r, rel, 5)]
for r, rel in zip(ranks, qrels)])
per_query[name] = m
print(f"{name:<7} R@3 {m[:, 0].mean():.2f} P@3 {m[:, 1].mean():.2f} MRR {m[:, 2].mean():.2f} nDCG@5 {m[:, 3].mean():.2f}")
# paired bootstrap over queries: how sure are we that MiniLM beats BM25 on MRR?
rng = np.random.default_rng(0)
diff = per_query["MiniLM"][:, 2] - per_query["BM25"][:, 2]
boot = [diff[rng.integers(0, 12, 12)].mean() for _ in range(10000)]
lo, hi = np.percentile(boot, [2.5, 97.5])
print(f"MRR difference {diff.mean():.2f}, 95% bootstrap CI [{lo:.2f}, {hi:.2f}], share of resamples <= 0: {np.mean(np.array(boot) <= 0):.3f}")
def reader(question, ids):
q = set(tokens(question))
best = (0, "I don't know")
for d in ids:
for sent in re.split(r"(?<=\.) ", docs[d]):
overlap = len(q & set(tokens(sent)))
if overlap > best[0]:
best = (overlap, sent)
return best[1]
stages = Counter()
for i, ((q, rel), gold) in enumerate(zip(queries, golds)):
ids = rankings["MiniLM"][i][:3]
f1 = token_f1(reader(q, ids), [gold])
stages["retrieval miss" if rel not in ids else "reader error" if f1 < 0.5 else "correct"] += 1
print("MiniLM top-3 + extractive reader:", dict(stages))BM25 R@3 0.75 P@3 0.31 MRR 0.74 nDCG@5 0.74
MiniLM R@3 1.00 P@3 0.44 MRR 0.92 nDCG@5 0.96
MRR difference 0.17, 95% bootstrap CI [-0.04, 0.40], share of resamples <= 0: 0.058
MiniLM top-3 + extractive reader: {'correct': 8, 'reader error': 4}
MiniLM reaches recall@3 1.00, MRR 0.92 and nDCG@5 0.96, against 0.75, 0.74 and 0.74 for BM25. The MRR gain of 0.17 has a 95% bootstrap interval of , and 5.8% of the resamples show no gain: the interval includes 0, so 12 queries cannot establish the gain at the 95% level, although recall@3 (12 against 9) points the same way. A golden set of a few hundred questions would settle it; the questions here were also written by the same person as the articles. With dense retrieval there are no retrieval misses left, and all 4 remaining errors are reader errors: the bottleneck has moved to the reader, which is exactly what the stage analysis is for. Improving retrieval further would not help these questions.
Pitfalls
- One end-to-end number. It hides which stage failed; always report retrieval and answer metrics separately.
- Precision@k for single-answer questions. It is capped at ; report recall@k and MRR.
- Labels on unstable chunk ids. Re-chunking invalidates them silently; use stable ids and re-validate on every index change.
- F1 and ROUGE as correctness. They reward word overlap, not meaning ("Cash is accepted": F1 0.86).
- Trusting a judge you did not measure. Check position and length bias and agreement with human labels first.
- No confidence intervals. Twelve or fifty questions give intervals wider than most improvements. Bootstrap over queries, paired.
- Lucky hits. A relevant chunk retrieved by a tie on a common word counts as a hit in recall@k; look at the scores and the reader's output.
Practice
- For "price for a whole day", the table gives nDCG@5 = 0.54. Find the ranks of articles 1 (grade 2) and 0 (grade 1) in BM25's ranking (print
ranking[:5]) and compute DCG@5, IDCG@5 and nDCG@5 by hand. - With scikit-learn's stop list, "full" disappears from "where do I leave the bike when the dock is full". Why does that hurt the extractive reader more than the retriever?
- A colleague reports "RAG accuracy improved from 78% to 81%" on 100 questions. What two things do you ask for before believing it?
- Write a gold answer and a wrong prediction that get token F1 above 0.8.
- In the recorded example, MiniLM leaves 4 reader errors and no retrieval misses. Name two changes that could fix them and one that cannot.
Answers
- BM25's ranking starts 11, 13, 1, 0: article 1 (grade 2) is at rank 3 and article 0 (grade 1) at rank 4, the latter only because the many zero scores are tied and broken by article number. . The ideal order is article 1 then article 0: . So . Without the lucky tie it would be .
- Retrieval still has "bike", "leave" and "dock", and "dock" is rare, so article 5 stays near the top of the ranking. The reader compares single sentences, where losing one of three terms turns a 2-term match into a tie with an unrelated sentence.
- A confidence interval or a paired test (on 100 questions a 3-point difference is well within noise: the standard error of a rate near 0.8 is 0.04), and the split: was the set used to tune the change? Also whether both runs used the same index, prompt and temperature.
- Gold "the first 30 minutes are free", prediction "the first 30 minutes are not free": precision (after removing "the"), recall 1, , and the meaning is reversed.
- A better reader (a generative LLM), or a reader that weights rare terms by idf so that "cash" beats "you"; also showing the reader fewer, better-ordered chunks. More retrieval work cannot fix them: the right chunk is already in the top 3.
Test yourself
A query has one relevant chunk, found at rank 4. What are its recall@3, recall@5 and reciprocal rank?
- 0, 1, 0.25
- 1, 1, 0.25
- 0, 1, 4
- 0.25, 0.25, 0.25
Why is precision@3 a poor metric for the TAD Bikes questions?
- It ignores the rank order
- Most questions have one relevant chunk, so it is capped at 1/3
- It cannot be computed without graded labels
- It is always equal to recall@3
With MiniLM retrieval, all 4 remaining wrong answers on the 12 questions were reader errors. What does that imply?
- The embedding model must be replaced
- Effort should go into the reader or the prompt, not into retrieval
- The golden set is wrong
- Chunks should be made larger
An LLM judge prefers answer A when A is shown first and answer B when B is shown first. What is this, and what is the fix?
- Verbosity bias; shorten the answers
- Position bias; judge both orders and count only consistent wins
- Self-preference; use a different judge model
- Temperature; set it to 1
The prediction "Cash is accepted" against the gold "cash is not accepted" gets token F1 0.86. What does that show?
- The SQuAD normalisation is wrong
- Token overlap does not capture meaning such as negation
- F1 should be replaced by exact match everywhere
- The gold answer is too long