Retrieval-Augmented Generation (RAG) Questions
Grounding language-model outputs in external knowledge at inference time. Covers document ingestion, chunking and embedding, sparse, dense and hybrid retrieval (BM25, score fusion, contrastive training of retrievers), vector search and approximate-nearest-neighbour index engineering (HNSW, IVF, product quantization, filtering, updates, sharding), re-ranking with cross-encoders, and context assembly with prompt templates and citations. Also covers reducing hallucination through verification and abstention, evaluating retrieval-augmented systems, and production concerns such as freshness, access control, prompt injection through retrieved documents, deletion and privacy, caching, cost, and weighing retrieval against fine-tuning. Generic LLM evaluation and release gates, the craft of prompts beyond retrieved-context templates, attention internals, parameter-efficient fine-tuning, model serving and distributed inference engineering, database indexes, and whole-product ML system design are covered elsewhere.
How would you decide when a RAG system should abstain or ask a clarifying question instead of answering? What signals from the model and the retrieval pipeline would you combine?
Sample Answer
Direct answer
Make the decision a three-way choice, answer, ask a clarifying question, or abstain, and decide it from signals that measure different failures, not from one confidence number. Abstain when the retrieved evidence does not cover the question. Ask a clarifying question when the evidence is plentiful but points at several different valid answers and the user can resolve which. Answer when the evidence covers the question and agrees. Combine retrieval signals (how well the top passage matches, how far ahead it is of the runner-up, what share of the question's own words the passage contains, called word coverage below) with generation signals (is each claim supported by the passages, do repeated samples agree), set the thresholds on labelled data, and choose them by the relative cost of a wrong answer and a needless refusal.
Signals
From retrieval:
- Top score: a low best-match score says nothing relevant was found. On its own it is a weak signal, because a question can share many words with a wrong passage.
- Margin: top score minus second score. A tiny margin between passages from different entities (two products, two policy versions) means ambiguity: clarify.
- Word coverage (
coveragein the rule and the code below): the share of the question's content words (especially names, numbers, entities) found in the best passage. A question about an unknown product can still score high on the words it shares ("password reset") while missing the name that matters. - Agreement: whether the top passages say the same thing or contradict each other.
From generation:
5. Support check: after drafting, test whether each claim is entailed by the cited passages (entailed means logically implied by them; the test is done by an entailment model or a judge asked whether the passages imply the claim). Unsupported claims mean the draft should be withheld or trimmed.
6. Sample consistency: draw several answers; if they disagree, the model is guessing. This costs several generations.
7. Token probabilities or the model stating its own confidence: usable features, but often poorly calibrated (a calibrated 0.8 would mean the model is right on about 8 of 10 questions it scores 0.8, and raw model numbers often do not match that), so treat them as inputs to be calibrated, not as the decision.
The decision rule
if best score < t_top or coverage < t_cov: abstain
elif margin < t_margin and top two come from different entities: ask a clarifying question
else: answer (then run the support check; if it fails, abstain)
Thresholds come from a labelled set of questions marked "should answer / clarify / abstain". Pick them to meet a stated error budget (for example, at most 2 percent of answered questions may be wrong) and report the trade-off as a risk-coverage curve: the share of questions the system answers (its answer rate, which this literature calls coverage; it is a different quantity from the word coverage signal above) against the error rate among the questions it did answer (the risk). The last lines of the program below compute a few points of that curve. A medical or legal assistant sits at low coverage and low error; a casual helper sits higher. Evaluate on questions held out from threshold tuning.
Computed example
Stand-ins: a TF-IDF retriever (scikit-learn 1.5.2; it scores a passage by the query words it contains, giving more weight to words that are rare across the passages) over twelve made-up passages (4 products times 3 topics) plays the retrieval pipeline; there is no generator here, only the retrieval-side signals. The 46 labelled queries are also made up. Thresholds are picked on the even-numbered half (23 queries) by trying every combination in a small grid (top score from 0.05 in steps of 0.05, margin from 0 in steps of 0.02, word coverage 0, 0.5, 0.8 or 1) and keeping the combination with the best accuracy, ties going to the smallest values; they are then scored on the other half (23). This is a clean toy: perfect scores here show the mechanism and say nothing about the accuracy of a real system, which needs real held-out traffic.
import itertools, re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
products = ["Atlas", "Borealis", "Cirrus", "Delta"]
topics = {
"password reset": "To reset your password in {p}, open Settings, choose Security and select Reset password. A link is emailed to you.",
"billing cycle": "{p} bills monthly on the day you subscribed. Invoices are in the Billing tab of {p}.",
"data export": "To export data from {p}, go to Admin, choose Export and pick a file format. Large exports are emailed.",
}
docs, meta = [], []
for p in products:
for t, tpl in topics.items():
docs.append(f"{p} {t}. " + tpl.format(p=p)); meta.append(p)
# (query, true action)
queries = []
for p in products:
for t in topics:
queries.append((f"How do I do a {t} in {p}?", "answer"))
queries.append((f"{p} {t} steps please", "answer"))
for t in topics:
queries.append((f"How do I do a {t}?", "clarify")) # no product named: several products match equally
queries.append((f"{t} steps please", "clarify"))
queries += [("Does Atlas support biometric login?", "abstain"), ("What is the weather in Paris?", "abstain"),
("How do I do a password reset in Echo?", "abstain"), ("Is Borealis available on mainframes?", "abstain"),
("Who is the CEO of Cirrus?", "abstain"), ("How do I do a data export in Foxtrot?", "abstain"),
("How do I cancel an order in Delta?", "abstain"), ("Which cloud region does Atlas use?", "abstain"),
("Echo billing cycle steps please", "abstain"), ("Is Cirrus compliant with ISO standards?", "abstain"),
("How do I migrate from Atlas to Delta?", "abstain"), ("What does Borealis cost per seat?", "abstain"),
("Foxtrot data export steps please", "abstain"), ("Can Delta run offline?", "abstain"),
("Tell me a joke about invoices", "abstain"), ("Atlas API rate limits?", "abstain")]
vec = TfidfVectorizer(stop_words="english").fit(docs)
D = vec.transform(docs)
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS as ENGLISH_STOP
FILLER = {"steps", "please", "tell", "does", "support"}
def signals(q):
s = (vec.transform([q]) @ D.T).toarray()[0]
order = np.argsort(-s)
top1, top2 = s[order[0]], s[order[1]]
margin = top1 - top2
different_products = meta[order[0]] != meta[order[1]]
content = [w for w in re.findall(r"[a-z]+", q.lower()) if w not in ENGLISH_STOP and w not in FILLER]
top_words = set(re.findall(r"[a-z]+", docs[order[0]].lower()))
coverage = np.mean([w in top_words for w in content]) if content else 0.0 # share of query words the best passage contains
return top1, margin, different_products, coverage
def decide(sig, t_top, t_margin, t_cov):
top1, margin, diff, cov = sig
if top1 < t_top or cov < t_cov:
return "abstain"
if margin < t_margin and diff:
return "clarify"
return "answer"
feats = [signals(q) for q, _ in queries]
truth = [a for _, a in queries]
dev = [i for i in range(len(queries)) if i % 2 == 0]
test = [i for i in range(len(queries)) if i % 2 == 1]
def acc(idx, tt, tm, tc):
return np.mean([decide(feats[i], tt, tm, tc) == truth[i] for i in idx])
# choose thresholds on the dev half only; ties go to the first (smallest) pair for a deterministic result
grid = [(round(a, 2), round(b, 3), round(c, 2)) for a in np.arange(0.05, 0.6, 0.05) for b in np.arange(0.0, 0.2, 0.02) for c in (0.0, 0.5, 0.8, 1.0)]
best = max(grid, key=lambda g: (acc(dev, *g), -g[0], -g[1], -g[2]))
print("queries:", len(queries), "| dev:", len(dev), "| test:", len(test))
print("thresholds chosen on dev: top1 >=", best[0], ", margin >=", best[1], ", coverage >=", best[2], "-> dev accuracy", round(acc(dev, *best), 3))
print("test accuracy:", round(acc(test, *best), 3), "| always-answer baseline on test:", round(np.mean([truth[i] == "answer" for i in test]), 3))
# baseline: one signal only (retrieval score threshold), thresholds again chosen on dev
grid1 = [(round(a, 2), 0.0, 0.0) for a in np.arange(0.05, 0.95, 0.05)]
best1 = max(grid1, key=lambda g: (acc(dev, *g), -g[0]))
print("top1-only baseline: threshold", best1[0], "-> dev accuracy", round(acc(dev, *best1), 3), "| test accuracy", round(acc(test, *best1), 3))
labels = ["answer", "clarify", "abstain"]
print("\nconfusion on test (rows = should do, columns = did)")
print(" " + "".join(f"{l:>9s}" for l in labels))
for t in labels:
row = [sum(1 for i in test if truth[i] == t and decide(feats[i], *best) == l) for l in labels]
print(f"{t:>9s} " + "".join(f"{c:9d}" for c in row))
print("\nsignals for some test queries: top1, margin, top-2 from a different product, coverage")
shown = [i for i in test if truth[i] != "answer"][:6]
for i in shown:
t1, m, dp, cv = feats[i]
print(f"{queries[i][0]:42s} {t1:.2f} {m:.2f} {str(dp):5s} {cv:.2f} -> {decide(feats[i], *best)} (should {truth[i]})")
# risk-coverage: how often we answer (coverage) against how often an answered question was one that should not have been answered (risk)
print("\nrisk-coverage over all", len(queries), "queries: answer rate (coverage) and wrong-answer rate (risk)")
for t in (0.0, 0.3, 0.5, 0.7, 0.75, 0.8):
answered = [i for i in range(len(queries)) if feats[i][0] >= t]
risk = np.mean([truth[i] != "answer" for i in answered])
print(f"top1 score alone, threshold {t:.2f}: coverage {len(answered)/len(queries):.2f}, risk {risk:.2f}")
answered = [i for i in range(len(queries)) if decide(feats[i], *best) == "answer"]
risk = np.mean([truth[i] != "answer" for i in answered])
print(f"three-signal rule: coverage {len(answered)/len(queries):.2f}, risk {risk:.2f}")
Output:
queries: 46 | dev: 23 | test: 23
thresholds chosen on dev: top1 >= 0.05 , margin >= 0.02 , coverage >= 0.8 -> dev accuracy 1.0
test accuracy: 1.0 | always-answer baseline on test: 0.522
top1-only baseline: threshold 0.75 -> dev accuracy 0.826 | test accuracy 0.87
confusion on test (rows = should do, columns = did)
answer clarify abstain
answer 12 0 0
clarify 0 3 0
abstain 0 0 8
signals for some test queries: top1, margin, top-2 from a different product, coverage
password reset steps please 0.79 0.00 True 1.00 -> clarify (should clarify)
billing cycle steps please 0.45 0.00 True 1.00 -> clarify (should clarify)
data export steps please 0.71 0.00 True 1.00 -> clarify (should clarify)
What is the weather in Paris? 0.00 0.00 False 0.00 -> abstain (should abstain)
Is Borealis available on mainframes? 0.71 0.26 False 0.33 -> abstain (should abstain)
How do I do a data export in Foxtrot? 0.71 0.00 True 0.67 -> abstain (should abstain)
risk-coverage over all 46 queries: answer rate (coverage) and wrong-answer rate (risk)
top1 score alone, threshold 0.00: coverage 1.00, risk 0.48
top1 score alone, threshold 0.30: coverage 0.96, risk 0.45
top1 score alone, threshold 0.50: coverage 0.89, risk 0.41
top1 score alone, threshold 0.70: coverage 0.87, risk 0.40
top1 score alone, threshold 0.75: coverage 0.59, risk 0.11
top1 score alone, threshold 0.80: coverage 0.35, risk 0.00
three-signal rule: coverage 0.52, risk 0.00
Reading the run
- The signals table prints, for each query, the top score (
top1), the margin between the top two passages, whether those two passages are about different products, and the word coverage of the best passage, then the decision and the correct action. - One query by hand. "Is Borealis available on mainframes?" has three content words once stop words and filler are removed (borealis, available, mainframes). The best passage contains only "borealis", so word coverage is 1 of 3 = 0.33, below the 0.8 threshold, and the rule abstains even though the top score is a high 0.71. "password reset steps please" has two content words (password, reset), both in the best passage, so coverage is 1.00; the margin is 0.00 because the four products' password passages tie and they are about different products, so the rule clarifies.
- The risk-coverage lines read as follows. Raising the threshold on the top score alone trades answer rate for risk: at 0.80 no wrong answers are given (risk 0.00) but only 35 percent of the queries are answered, so answerable questions are refused. The three-signal rule reaches risk 0.00 at an answer rate of 0.52, the highest possible here because 24 of the 46 queries are answerable (24/46 = 0.52). A perfect score on 23 held-out queries with 3 clarify and 8 abstain cases shows the mechanism and is not a target for a real system, whose held-out accuracy will be lower and whose curve is smoother.
- A single retrieval-score threshold (the baseline line) reaches 0.826 on the tuning half and 0.87 on the held-out half. It has no way to ask for clarification, and it cannot tell an unknown product from a known one: the Foxtrot query in the signals table (a product that is not in the corpus) still has a top score of 0.71, because "data export" matches the export passages.
- Adding coverage and margin separates the three actions: unknown-entity questions can have high top scores but low coverage (0.33 for the mainframes query, 0.67 for the Foxtrot query) and are sent to abstain; product-less questions have full coverage but a margin near 0 between passages of different products and are sent to clarify. On this toy set the three-signal rule gets all 23 held-out queries right, against 0.522 for always answering.
- The tuned thresholds (top score 0.05, margin 0.02, coverage 0.8) sit at the edge of the grid searched for the top score, a sign the top-score signal is doing little here and the other two are doing the work.
Trade-offs and failure modes
- Over-abstaining frustrates users and hides a retrieval gap; track the refusal rate by topic and review refusals, since they point to missing content.
- Under-abstaining gives confident wrong answers, the costlier error in most settings.
- Clarification has a cost: each question is a conversational turn. Limit it to one turn, offer the likely options ("Atlas, Borealis, Cirrus or Delta?") and fall back to abstaining if the user does not help.
- A fixed threshold drifts when the corpus or traffic changes; re-measure on fresh labelled samples regularly.
- Partial answers: when part of a multi-part question is covered, answer that part and say what is missing.
Common mistakes
- Using the raw model-reported confidence or the raw similarity score as a probability.
- Tuning thresholds and reporting accuracy on the same questions.
- Treating "no answer" as a single outcome, so ambiguity and missing evidence are handled identically.
- Not logging the signals with the decision, so wrong decisions cannot be audited later.
Design a RAG pipeline for multimodal documents (text + images + tables). How would you index multimodal content, retrieve relevant items, and present grounded multimodal context to the LLM so it can reason across modalities?
Sample Answer
Direct answer
Convert every modality into units that can be indexed, retrieved and cited, keep a link from each unit to its page and source, and hand the generator the right form of each unit. Text is chunked as usual. A table is turned into self-describing row or block chunks plus a short summary. An image is represented by a caption or description, any text read from it (OCR, optical character recognition, which reads text out of an image), and, if you have a multimodal embedding model (one trained so that an image and a text describing it land close together), an image embedding in a shared space, meaning a text query vector can be compared directly with image vectors. At query time you retrieve across all of these, rerank, and pass the original table text or the original image to a model that can read it, with each item labelled by its source and page. The principle: the thing you search over may be a derived text, but the thing you show the model should be the original or a lossless form of it (one that drops nothing the question may need).
Indexing by modality
| Content | What is indexed | What is stored for the generator |
|---|---|---|
| Text | Overlapping chunks with heading path | The chunk text |
| Table | Row chunks or small row groups, each with caption, header and column names repeated; plus one summary chunk for the whole table | The table as markdown or CSV text; row chunks point to it |
| Image, chart, diagram | A generated description, nearby caption, alt text, OCR text; optionally an image embedding | The original picture file (if the generator accepts images) and its description |
| Page layout | Page number, bounding box (the rectangle that locates the region on the page), section path | Used for citations and for ordering context |
Layout parsing (a step that detects headings, tables and figures on each page) comes first, because a PDF is a page of positioned glyphs, and tables and figures are split across text extraction unless detected as regions.
Retrieval
- Text-first with derived text: index descriptions and OCR next to the text chunks and use one hybrid search (keyword plus embeddings). This works with any text embedding model and is the base design.
- Shared embedding space: a multimodal embedding model puts images and text in one space so a text query can retrieve an image directly; use it as an additional retriever and fuse its results with the text results by rank (rank fusion: merge the lists by each item's position in its own list, not by raw scores that live on different scales). It helps when a picture holds information that no caption captures (the shape of a curve, a floor plan).
- Rerank the pooled candidates; tables and figures often need the cross-encoder (a model that reads the query and a candidate together and outputs one relevance score) to see the caption together with the content.
- Expand to neighbours: when a chunk from a table or a figure caption is retrieved, bring the whole table or the figure and its caption, because a fragment is not interpretable.
Presenting grounded context
Give each item a stable label ([T3 p12]) with kind, source, page, then the content: text as text, tables as markdown with their header, pictures as pictures or descriptions. Ask the generator to cite labels, and verify citations after generation. Keep the total within the context budget by prioritising scored items; a full-page screenshot can cost many more tokens than the same table in markdown, so use the picture only when the structure or visual is the point.
Worked example: assembling labelled multimodal context
Three retrieved items are assembled into the prompt the generator sees: a text chunk, a table kept as markdown, and a bar chart. The description and the OCR text of the chart are written by hand here as stand-ins for a captioning model and an OCR engine; TF-IDF (a score that counts how many of the query's words a text contains, weighting rare words more) stands in for the retriever. The bbox is the bounding box, the rectangle (left, top, right, bottom in page units) that locates the figure on the page, kept so a citation can point at the region. The chart is indexed by its derived text, so a text query reaches it, while the context carries a reference to the original image file, which a model that accepts images receives as the picture itself.
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
# STAND-INS: the image description and the OCR text are written by hand here. A real system would
# produce them with a captioning model and an OCR engine. TF-IDF plays the retriever.
items = [
{"label": "text-1 p11", "kind": "text", "source": "annual_report.pdf",
"content": "Regional revenue grew in the third quarter, led by North America."},
{"label": "table-3 p12", "kind": "table", "source": "annual_report.pdf",
"content": "| Region | Q3 revenue (USD m) | Churn rate |\n|---|---|---|\n| North America | 66.5 | 1.9% |\n| Latin America | 12.3 | 4.8% |",
"index_text": "Table 3 regional performance third quarter revenue churn rate North America Latin America"},
{"label": "image-2 p12", "kind": "image", "source": "annual_report.pdf",
"content": "[image: figures/p12_fig2.png]",
"index_text": "Bar chart of Q3 revenue by region. Bars: North America 66.5, Europe 41.2, Latin America 12.3. OCR text: Q3 revenue (USD m)",
"bbox": [72, 310, 520, 620]},
]
for it in items:
it.setdefault("index_text", it["content"])
def search(query, k):
vec = TfidfVectorizer(stop_words="english").fit([i["index_text"] for i in items] + [query])
sims = (vec.transform([i["index_text"] for i in items]) @ vec.transform([query]).T).toarray().ravel()
order = sorted(range(len(items)), key=lambda i: (-sims[i], i))
return [(items[i], round(float(sims[i]), 2)) for i in order[:k]]
query = "Which region had the highest Q3 revenue?"
hits = search(query, 3)
print("retrieved (label, score):", [(h["label"], s) for h, s in hits])
print()
# Assemble the context the generator sees: a label line, then the ORIGINAL form of each item.
blocks = []
for h, s in hits:
where = f"{h['kind']}, {h['source']}, page {h['label'].split(' p')[1]}"
extra = f", region {h['bbox']}" if "bbox" in h else ""
blocks.append(f"[{h['label']}] ({where}{extra})\n{h['content']}")
prompt = ("Answer using only the items below. Cite the label of every item you use.\n\n"
+ "\n\n".join(blocks) + f"\n\nQuestion: {query}")
print(prompt)
Output:
retrieved (label, score): [('image-2 p12', 0.37), ('text-1 p11', 0.08), ('table-3 p12', 0.06)]
Answer using only the items below. Cite the label of every item you use.
[image-2 p12] (image, annual_report.pdf, page 12, region [72, 310, 520, 620])
[image: figures/p12_fig2.png]
[text-1 p11] (text, annual_report.pdf, page 11)
Regional revenue grew in the third quarter, led by North America.
[table-3 p12] (table, annual_report.pdf, page 12)
| Region | Q3 revenue (USD m) | Churn rate |
|---|---|---|
| North America | 66.5 | 1.9% |
| Latin America | 12.3 | 4.8% |
Question: Which region had the highest Q3 revenue?
Reading it: the chart ranks first (0.37) because its description and OCR text contain "Q3", "revenue" and "region", so a text query reaches an item whose numbers exist only as pixels. The text chunk (0.08) and the table (0.06) score low here because they share only one or two words with the query; with k=3 all three are passed on, and in a full system a reranker would reorder them. Each block starts with a label line giving kind, source and page, so the generator can cite table-3 p12 or image-2 p12 and a verifier can check that the label exists. The table stays markdown with its header row, and the chart is passed as the image reference, not as its description.
Worked example: why table chunks must repeat their header
The program splits one four-row table two ways: naively every two lines (only the first chunk carries the header), and one chunk per row with the caption and "column: value" pairs. TF-IDF stands in for the retriever (scored as in the previous example), and the query asks for the churn rate in Latin America. Both splits find the Latin America row; what differs is whether the retrieved text says which number is the churn rate.
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
# One table extracted from a PDF page, as a header plus rows.
header = ["Region", "Q3 revenue (USD m)", "Churn rate"]
rows = [["Europe", "41.2", "2.1%"], ["Asia Pacific", "37.8", "3.4%"],
["North America", "66.5", "1.9%"], ["Latin America", "12.3", "4.8%"]]
def naive_chunks(rows, per_chunk=2):
# split the serialised table every 2 rows; only the first chunk carries the header
lines = [" | ".join(header)] + [" | ".join(r) for r in rows]
return ["\n".join(lines[i:i + per_chunk]) for i in range(0, len(lines), per_chunk)]
def row_chunks(rows, caption):
# every chunk is self-describing: caption + "column: value" pairs for one row
out = []
for r in rows:
pairs = "; ".join(f"{h}: {v}" for h, v in zip(header, r))
out.append(f"{caption}. {pairs}")
return out
caption = "Table 3, regional performance for the third quarter"
a, b = naive_chunks(rows), row_chunks(rows, caption)
def top1(chunks, query):
vec = TfidfVectorizer().fit(chunks + [query])
sims = (vec.transform(chunks) @ vec.transform([query]).T).toarray().ravel()
return int(np.argmax(sims)), np.round(sims, 2).tolist()
# Chunks are in a fixed order; query the churn rate for Latin America.
q = "churn rate Latin America"
print("naive chunks:", len(a), "| row chunks:", len(b))
i, s = top1(a, q); print("naive top-1 chunk text:", repr(a[i]), s)
i, s = top1(b, q); print("row-chunk top-1 text :", repr(b[i]), s)
Output:
naive chunks: 3 | row chunks: 4
naive top-1 chunk text: 'Latin America | 12.3 | 4.8%' [0.31, 0.12, 0.48]
row-chunk top-1 text : 'Table 3, regional performance for the third quarter. Region: Latin America; Q3 revenue (USD m): 12.3; Churn rate: 4.8%' [0.15, 0.14, 0.29, 0.51]
Reading it: both approaches retrieve a chunk containing Latin America, but the naive chunk's text is Latin America | 12.3 | 4.8%, with no column names, so a reader or model cannot tell which number is the churn rate and which is the revenue. The row chunk carries Churn rate: 4.8% and the table caption, so the retrieved text is interpretable and citable on its own. The naive splitter's first chunk is the header line plus the Europe row, and it scores 0.31 for the words "churn rate" only because the header contains them, so a fragment about the wrong region competes with the chunk that holds the answer. This is one table and one query; it shows the mechanism, not a measured accuracy gain.
Trade-offs and failure modes
- Description quality caps image retrieval. If the captioning model misses a detail, the detail is unsearchable; test with questions about content that appears only in images.
- OCR and table extraction errors (merged cells, rotated text, multi-page tables) silently change numbers; sample and spot check, and keep the source page for human verification.
- Cost. Describing every image at ingestion costs a model call per image; describe only images above a size or those inside relevant sections, and cache by image hash.
- Large tables. Row chunks lose cross-row context (totals, comparisons); keep the summary chunk and let the generator get the full table when a comparison is asked.
- Citations should point to page and region so a user can check them against the original.
- What would flip the design: documents that are mostly diagrams or scans (the visual embedding path matters more); mostly clean digital text with simple tables (derived text alone is enough).
Evaluation
Make separate question sets for text-only, table, figure and cross-modal questions; report retrieval recall@k (the share of the items that should be found that appear in the top k results) and answer correctness per set, so a weak modality is visible rather than averaged away.
Explain product-level metrics for RAG quality beyond IR metrics: examples include citation-precision, answer-correctness judging F1, user satisfaction, and downstream task completion. How would you instrument and correlate these with retrieval signals?
Sample Answer
Direct answer
Retrieval metrics say whether the right passage was found: recall@k is the share of questions whose supporting passage is among the top k results, MRR (mean reciprocal rank) averages 1 divided by the rank of the first correct passage, and NDCG scores a ranked list higher when the more relevant passages sit nearer the top. They do not say whether the answer was cited properly, was correct, helped the user or finished their task. Product-level RAG quality needs four more layers: citation quality (are the cited passages the ones that actually support the claims), answer correctness (are the claims true and complete against a reference), user satisfaction (did the person say so) and task completion (did they get done what they came for). You instrument them by giving every request one trace id (a single identifier stamped on every log record of that request, so the records can be joined later) and logging, on that id, what was retrieved, what was given to the model, what was cited and what the user did next. Then you correlate by splitting sessions into strata (groups of sessions that share an outcome at an earlier stage; one group is a stratum) such as "gold passage retrieved and cited", "retrieved but not cited" and "not retrieved".
The metrics, defined
- Citation precision: of the passages the answer cites, the share that are in the gold set (the passages a person has marked as supporting the reference answer, the ground truth for that question). Citation recall: of the gold passages, the share that are cited. Both are set-overlap measures on passage ids. When an answer cites nothing, precision has no denominator; pick a convention (here 0.0) and say so.
- Answer-correctness F1 (claim level): split the answer into atomic claims (one checkable statement each). Precision = supported claims / claims in the answer. Recall = reference claims that the answer covers / reference claims. F1 = 2PR/(P+R), the harmonic mean, which is low if either side is low. The judge that marks a claim "supported" or "covered" is a model or a human; its agreement with humans must itself be measured on a labelled sample before its F1 is trusted.
- User satisfaction: explicit thumbs, follow-up rephrasing (the same question asked again), copy actions. Ratings are sparse and biased toward the unhappy and the delighted, so report the rating rate next to the thumbs-up share.
- Downstream task completion: whether the thing the answer was for happened (ticket not escalated, form submitted, no second search within a window). This is the closest signal to value and the slowest and noisiest.
Worked example 1: scoring six logged requests
One logged request, in an illustrative layout (the field names are examples, not a standard):
{"trace_id": "t-0042", "query": "refund window for enterprise?", "retrieved": ["b1", "x4", "b2"],
"in_prompt": ["b1", "x4"], "cited": ["b1"], "answer_claims": 2, "latency_ms": 1800,
"events": [{"type": "thumbs", "value": "up"}]}
Everything later is computed from rows like this: retrieved against the gold set gives the retrieval hit, cited against the gold set gives citation precision and recall, and events carries what the user did next.
Each request has a gold set, a cited set and claim counts from a judge. The numbers below are computed by the program from those inputs.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
# Part 1: six logged requests, scored by hand-checkable rules.
# gold = passages that support the reference answer; cited = passages the answer cites.
# claims: (answer claims, answer claims the judge marks supported, reference claims, reference claims covered)
log = [
dict(gold={"a1"}, cited={"a1"}, claims=(3, 3, 3, 3)),
dict(gold={"b1", "b2"}, cited={"b1"}, claims=(2, 2, 4, 2)),
dict(gold={"c1"}, cited={"c9", "c1"}, claims=(4, 3, 3, 3)),
dict(gold={"d1"}, cited={"d7"}, claims=(3, 1, 2, 1)),
dict(gold={"e1"}, cited=set(), claims=(2, 1, 2, 1)),
dict(gold={"f1", "f2"}, cited={"f1", "f2"}, claims=(5, 5, 5, 5)),
]
def f1(p, r):
return 0.0 if p + r == 0 else 2 * p * r / (p + r)
print("req cite_prec cite_rec ans_prec ans_rec ans_F1")
cp_all, ca_all = [], []
for i, r in enumerate(log, 1):
hit = len(r["cited"] & r["gold"])
cite_p = hit / len(r["cited"]) if r["cited"] else 0.0
cite_r = hit / len(r["gold"])
n_ans, n_sup, n_ref, n_cov = r["claims"]
ap, ar = n_sup / n_ans, n_cov / n_ref
print(f"{i} {cite_p:.2f} {cite_r:.2f} {ap:.2f} {ar:.2f} {f1(ap, ar):.2f}")
# Part 2: synthetic log of 400 sessions to show how to relate retrieval to product signals.
# Assumptions (invented for the demo): gold passage in top-5 with prob 0.8; cited | hit with prob 0.75;
# P(correct) = 0.9 if hit and cited, 0.45 if hit and not cited, 0.2 if miss;
# P(task completed) = 0.85 if correct else 0.35; only 15% of sessions leave a thumbs rating.
rng = np.random.default_rng(0)
N = 400
hit = rng.random(N) < 0.8
cited = hit & (rng.random(N) < 0.75)
p_corr = np.where(cited, 0.9, np.where(hit, 0.45, 0.2))
correct = rng.random(N) < p_corr
done = rng.random(N) < np.where(correct, 0.85, 0.35)
rated = rng.random(N) < 0.15
up = rng.random(N) < np.where(correct, 0.8, 0.3)
print()
print("stratum n correct completed")
for name, m in [("hit and cited", cited), ("hit, not cited", hit & ~cited), ("miss", ~hit)]:
print(f"{name:<18} {m.sum():4d} {correct[m].mean():.2f} {done[m].mean():.2f}")
print(f"recall@5 over all sessions: {hit.mean():.2f}")
print(f"corr(hit, correct): {np.corrcoef(hit, correct)[0, 1]:.2f}")
print(f"corr(correct, completed): {np.corrcoef(correct, done)[0, 1]:.2f}")
print(f"sessions with a rating: {rated.sum()}; thumbs-up share among rated: {up[rated].mean():.2f}")
Output:
req cite_prec cite_rec ans_prec ans_rec ans_F1
1 1.00 1.00 1.00 1.00 1.00
2 1.00 0.50 1.00 0.50 0.67
3 0.50 1.00 0.75 1.00 0.86
4 0.00 0.00 0.33 0.50 0.40
5 0.00 0.00 0.50 0.50 0.50
6 1.00 1.00 1.00 1.00 1.00
stratum n correct completed
hit and cited 230 0.93 0.80
hit, not cited 71 0.38 0.63
miss 99 0.21 0.43
recall@5 over all sessions: 0.75
corr(hit, correct): 0.53
corr(correct, completed): 0.46
sessions with a rating: 70; thumbs-up share among rated: 0.67
Reading the table with request 4 as the example: the gold set is {d1} and the answer cites {d7}, so the overlap is 0 of 1 cited (precision 0.00) and 0 of 1 gold (recall 0.00). The judge marks 1 of the answer's 3 claims supported (answer precision 1/3 = 0.33) and 1 of the reference's 2 claims covered (answer recall 1/2 = 0.50), so F1 = 2 x 0.33 x 0.50 / (0.33 + 0.50) = 0.40. Reading the rest: request 2 cites correctly but only half the gold passages (recall 0.50), so the answer is accurate yet incomplete (answer recall 0.50). Request 3 cites an extra passage that does not support anything (precision 0.50). Request 4 cites a passage that is not in the gold set at all and the judge supports only one of three claims: the answer rests on the wrong evidence, and the logged retrieved and in_prompt lists would show whether the gold passage was never retrieved or was retrieved and not used. Request 5 cites nothing, so none of its claims can be checked against a citation, even though the judge, comparing against the reference answer, still marks one of its two claims supported (answer precision 0.50).
Worked example 2: relating the product signals to retrieval
The second part of the program builds a synthetic log of 400 sessions. In its code, hit marks sessions where the gold passage was in the top 5, cited marks sessions that were a hit and where the answer then cited it, p_corr is the chance that the answer is correct given that session's stratum (0.9, 0.45 or 0.2), and correct, done, rated and up are random draws from those chances; np.corrcoef then measures how strongly two of the yes/no columns move together. For example, a session with a hit and a citation has a 0.9 chance of being correct, and about 0.85 of correct sessions complete the task. It is a demonstration, not a measurement of any real system: the generating rules are stated in the code comment (gold passage in the top 5 with probability 0.8, cited given a hit with probability 0.75, correctness probability 0.9, 0.45 or 0.2 depending on the stratum, and so on), and the correlations that come out are consequences of those rules. What carries over is the method: stratify by retrieval outcome and then read the downstream rates inside each stratum.
In the output, the "hit and cited" stratum is correct 0.93 of the time and completes 0.80. "Hit, not cited" drops to 0.38 correct in this draw. The rule in the code sets that stratum at 0.45, so it sits below a coin flip by construction and another draw lands near, not at, 0.38. The right passage was retrieved but the answer did not rest on it. If the log shows the passage was in the prompt (in_prompt), that points at the generation prompt, context ordering or context length; if truncation dropped it, at context assembly. Either way it is not the retriever, and a recall@5 number alone would have hidden it. "Miss" sessions are correct 0.21 of the time. The correlation coefficient measures how strongly two columns move together on a scale from -1 to 1, where 0 means knowing one tells you nothing about the other and 1 means one fully determines the other. The correlation of retrieval hit with correctness is 0.53 and of correctness with completion 0.46: clearly positive and clearly below 1, which is the point of measuring beyond IR metrics, since retrieval explains only part of the outcome. Only 70 of 400 sessions left a rating, so a satisfaction number computed from them rests on a small, self-selected group.
How I would instrument it
- One trace id per request, carried through every stage. Log: query, rewritten query, retrieved ids with ranks and scores, ids placed in the prompt (after any truncation), the answer with the ids it cited, latency per stage, index version.
- Join keys for outcomes: the same id on the thumbs event, the "asked again within 5 minutes" event and the downstream business event, so outcomes can be attached after the fact.
- Offline labelled set (a few hundred real queries with gold passages and reference claims) to calibrate the judge and to compute citation precision, recall and claim F1 with known ground truth. Online, sample a small share of traffic for judge scoring and a smaller share for human review.
- Dashboards by stratum, not by average: hit and cited, hit not cited, miss; also by query type and by index version.
Trade-offs and pitfalls
- Judge bias. A model judge can favour longer or more fluent answers and can disagree with humans on borderline claims. Report judge-vs-human agreement on a labelled slice and re-check after any change to the judge.
- Correlation is not a causal lever. Sessions with good retrieval may also be the easy questions. To claim that a retrieval change improved completion, run an A/B test with the change as the only difference.
- Metric gaming. Optimising citation precision alone rewards citing one safe passage; pair it with citation recall and claim recall.
- Delay and sparsity of satisfaction and completion mean they are tracked weekly, while the cheap per-request metrics gate each release.
- Common mistake: reporting one blended "RAG accuracy" number. Keep retrieval, citation, correctness and outcome separate so a drop can be located.
Design an evaluation suite for a production RAG system. What automated and human evaluation would you run, how would you build test data for edge cases, and how would you weigh answer quality against latency?
Sample Answer
Direct answer
Evaluate retrieval and generation separately, then together. Retrieval gets its own labelled test (did the gold passage come back, and how high), generation gets faithfulness and correctness checks given what was retrieved, and a small end-to-end set with human review confirms that the automatic scores mean something. Build the test set deliberately, with named edge-case categories, hold every other factor fixed when you change one (prompt template, few-shot examples, retrieval setup), report each number with an uncertainty interval, and choose the configuration by the best quality that fits a latency budget you state up front.
The suite, layer by layer
1. Retrieval metrics (needs gold passages). For each answerable question, a person marks which passage(s) contain the answer. Then compute recall@k (the share of questions whose gold passage is in the top k) and MRR (mean reciprocal rank: the average of 1 divided by the rank of the first gold passage). These do not involve the language model at all, so a change to chunking or the embedding model can be judged in seconds.
2. Faithfulness (groundedness) given the retrieved context. Faithfulness asks: is every claim in the answer supported by the passages the model was given? It is not the same as correctness. An answer can be faithful to a stale passage and wrong, or correct from memory and unfaithful. Measure it by splitting the answer into claims and checking each against the context, with a model-graded check (an LLM-as-judge, a model asked to grade another model's output, with a rubric) or an entailment classifier (a small model that reads a passage and a claim and says whether the passage supports, contradicts or is silent on the claim). Calibrate the judge: have people label a sample, compute agreement with the judge, and keep the human labels as the reference.
3. Answer correctness (needs gold answers). Exact or normalised match (compare after lower-casing and stripping punctuation and filler words) for short facts, a rubric judge (a model or person scoring against written criteria such as "states the 30-day limit") for longer answers, and human review for a sample. For unanswerable questions, correct means abstaining.
4. Abstention. Track abstention precision (when it refuses, was the answer truly absent?) and the rate of wrong answers shown, which is the number users feel.
5. Human evaluation. Reviewers rate a stratified sample (a sample drawn so that every category below is represented, rather than purely at random) for correctness, support by the cited passage, and usefulness. Measure inter-annotator agreement (how often two reviewers give the same label, corrected for chance, for example Cohen's kappa) and write down tie-break rules; low agreement means the rubric is unclear, not that the reviewers are wrong.
6. System metrics. End-to-end latency percentiles (the p95 is the time that 95% of requests beat, so it describes the slow tail that averages hide), cost per query (tokens in and out, reranker calls), and the rate of timeouts and empty retrievals.
Building test data for edge cases
Start from real logged questions, then add categories so rare failures are represented on purpose:
- direct lookups (one passage, wording close to the text);
- paraphrases and vocabulary mismatch (the user says "bill", the document says "invoice");
- unanswerable questions, including ones that look close to a real topic;
- stale or conflicting passages (an old rule and its replacement);
- multi-passage questions (the answer needs two chunks);
- abbreviations, typos, very short or very long questions;
- permission cases (the user must not see a restricted document).
Write the gold passage, gold answer and category for each, keep a frozen release set that is never used for prompt tuning, and add every production failure to the regression set.
Controlling variability from prompts, few-shot examples and retrieval
Scores move when the prompt template, the few-shot examples (worked question and answer pairs placed in the prompt) or the retrieval settings change, so change one factor at a time, or run a small grid and report every cell. Keep the sampling settings fixed, run each cell on the same questions, and, if the generator is stochastic, repeat the run several times and report the spread. Separate the retrieval metrics (which only depend on the retrieval setup) from the faithfulness and correctness metrics (which depend on both) so a retrieval gain and a prompt gain are not confused.
Worked example
The program evaluates four configurations on 11 questions in four categories (direct, paraphrase, stale, unanswerable): retrieval depth k in {1, 3} crossed with two prompt behaviours. Retrieval is BM25 (rank_bm25 0.2.2). The generator is a stand-in, not a real model: it reads only the first retrieved passage, and the "abstain" template mimics an instruction "answer only from the sources, otherwise say you do not know" by refusing when the top BM25 score is below 1.5. A real system would put an LLM there and judge faithfulness with a calibrated judge. The latencies are assumed numbers (30 ms retrieval, 40 ms generation base, 6 ms per passage in the prompt, so total latency is 30 + 40 + 6k ms: 76 ms at k = 1 and 88 ms at k = 3), chosen only to show the arithmetic of the trade-off, with a budget of 80 ms.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import re, math
from rank_bm25 import BM25Okapi
from sklearn.metrics import cohen_kappa_score
C = {
"c1": "Annual plans can be refunded within 30 days of purchase.",
"c2": "Monthly plans can be refunded within 7 days of purchase.",
"c3": "Support is open from 9am to 6pm on weekdays.",
"c4": "Enterprise plans include single sign-on and a dedicated manager.",
"c5": "Invoices are emailed on the first day of each month.",
"c6": "Data exports are limited to 10000 rows per file.",
"c7": "Legacy plans were refundable within 14 days. This rule ended in 2023.",
"c8": "Teams can add up to 50 members on the standard plan.",
}
# (category, question, gold chunk or None, gold answer substring or None)
Q = [
("direct", "Refund period for annual plans?", "c1", "30 days"),
("direct", "Refund period for monthly plans?", "c2", "7 days"),
("direct", "When is support open?", "c3", "9am to 6pm"),
("direct", "How many rows per data export file?", "c6", "10000"),
("direct", "How many members on the standard plan?", "c8", "50 members"),
("paraphrase", "When will I receive my bill?", "c5", "first day"),
("paraphrase", "What is the cap on rows when I download my data?", "c6", "10000"),
("stale", "Can legacy annual plans be refunded?", "c7", "14 days"),
("unanswerable", "Do you support SAML for contractors?", None, None),
("unanswerable", "What is the refund period for quarterly plans?", None, None),
("unanswerable", "Who is the CEO?", None, None),
]
STOP = {"the", "a", "an", "of", "is", "for", "in", "on", "to", "do", "you", "can", "be", "when", "what", "how", "i", "my", "per", "are", "after", "it", "up"}
tok = lambda t: [w for w in re.findall(r"[a-z0-9]+", t.lower()) if w not in STOP]
ids = list(C); bm = BM25Okapi([tok(C[i]) for i in ids])
TAU = 1.5
def retrieve(q, k):
s = bm.get_scores(tok(q))
order = sorted(range(len(ids)), key=lambda j: (-s[j], j))[:k]
return [(ids[j], float(s[j])) for j in order]
def generate(template, hits): # stand-in generator, one rule per template
top_id, top_score = hits[0]
if template == "plain": # always answers from the top passage
return C[top_id], top_id
if top_score < TAU: # "answer only from sources, else say you do not know"
return "I do not know", None
return C[top_id], top_id
CONFIGS = [(k, t) for k in (1, 3) for t in ("plain", "abstain")]
LAT = {"retrieve": 30, "generate_base": 40, "generate_per_passage": 6} # ASSUMED milliseconds
def evaluate(k, t):
rec = rr_sum = n_ans = good = wrong = 0
per_cat = {}
for cat, q, gid, gans in Q:
hits = retrieve(q, k)
ans, cited = generate(t, hits)
if gid:
n_ans += 1
ranked = [h[0] for h in hits]
if gid in ranked:
rec += 1; rr_sum += 1 / (ranked.index(gid) + 1)
ok = (gans in ans) if gans else (cited is None) # unanswerable: correct = abstain
good += ok; wrong += (cited is not None) and not ok
per_cat.setdefault(cat, []).append(ok)
lat = LAT["retrieve"] + LAT["generate_base"] + k * LAT["generate_per_passage"]
return rec / n_ans, rr_sum / n_ans, good / len(Q), lat, per_cat, wrong / len(Q)
print("gold chunk rank per answerable question (None = not in top 3)")
for cat, q, gid, gans in Q:
if gid:
ranked = [h[0] for h in retrieve(q, 3)]
print(f" {q[:42]:42s} gold {gid} rank", ranked.index(gid) + 1 if gid in ranked else None)
print()
print("config (k, template) recall@k MRR correct wrong_shown latency_ms(assumed)")
rows = []
for cfg in CONFIGS:
r, m, g, lat, pc, w = evaluate(*cfg)
rows.append((cfg, g, lat, pc, w))
print(f"{str(cfg):22s} {r:7.2f} {m:5.2f} {g:7.2f} {w:11.2f} {lat:5d}")
budget = 80
ok_rows = [r for r in rows if r[2] <= budget]
best = max(ok_rows, key=lambda r: (r[1], -r[2]))
print("\nbest within", budget, "ms:", best[0], "correct", round(best[1], 2), "latency", best[2])
print("per-category correct for it:", {c: f"{sum(v)}/{len(v)}" for c, v in best[3].items()})
def wilson(p, n, z=1.96):
c = (p + z * z / (2 * n)) / (1 + z * z / n)
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return round(c - h, 2), round(c + h, 2)
print("\n95% Wilson interval for an observed 0.80 correct:")
for n in (len(Q), 100, 400):
print(" n =", n, wilson(0.8, n))
a = [1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1]
b = [1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1]
po = sum(x == y for x, y in zip(a, b)) / 12
pe = (sum(a) / 12) * (sum(b) / 12) + (1 - sum(a) / 12) * (1 - sum(b) / 12)
print("\nobserved agreement p_o:", round(po, 3), "| chance agreement p_e:", round(pe, 3))
print("kappa by hand (p_o - p_e) / (1 - p_e):", round((po - pe) / (1 - pe), 3), "| sklearn:", round(cohen_kappa_score(a, b), 3))
Output:
gold chunk rank per answerable question (None = not in top 3)
Refund period for annual plans? gold c1 rank 1
Refund period for monthly plans? gold c2 rank 1
When is support open? gold c3 rank 1
How many rows per data export file? gold c6 rank 1
How many members on the standard plan? gold c8 rank 1
When will I receive my bill? gold c5 rank None
What is the cap on rows when I download my gold c6 rank 1
Can legacy annual plans be refunded? gold c7 rank 2
config (k, template) recall@k MRR correct wrong_shown latency_ms(assumed)
(1, 'plain') 0.75 0.75 0.55 0.45 76
(1, 'abstain') 0.75 0.75 0.73 0.18 76
(3, 'plain') 0.88 0.81 0.55 0.45 88
(3, 'abstain') 0.88 0.81 0.73 0.18 88
best within 80 ms: (1, 'abstain') correct 0.73 latency 76
per-category correct for it: {'direct': '5/5', 'paraphrase': '1/2', 'stale': '0/1', 'unanswerable': '2/3'}
95% Wilson interval for an observed 0.80 correct:
n = 11 (0.5, 0.94)
n = 100 (0.71, 0.87)
n = 400 (0.76, 0.84)
observed agreement p_o: 0.833 | chance agreement p_e: 0.556
kappa by hand (p_o - p_e) / (1 - p_e): 0.625 | sklearn: 0.625
What the run shows:
- Recall and MRR by hand. Eight questions have a gold passage. At k = 1 the gold passage is first for six of them, so recall@1 is 6/8 = 0.75 and MRR is 6/8 = 0.75. At k = 3 the legacy-plan question now finds its gold passage at rank 2, which adds 1 to the hit count and 0.5 to the reciprocal-rank sum, so recall@3 is 7/8 = 0.88 and MRR is (6 + 0.5) / 8 = 0.81. The bill question is missed at every k because the question shares no word with the invoice passage (the vocabulary gap that dense embeddings are meant to bridge).
- recall@k and MRR change only when k changes; they are identical for the two templates, which is the point of measuring retrieval separately.
- Correctness and wrong answers shown change only with the template in this stand-in: the abstain behaviour lowers the share of wrong answers shown from 0.45 to 0.18 and raises correctness from 0.55 to 0.73, because it refuses whenever the best score is low, which covers two of the three unanswerable questions (it also refuses the answerable bill question, which counts as not correct). The stand-in generator reads only the first passage, so the recall gain at k = 3 never reaches the answer and correctness is identical at k = 1 and k = 3 (0.73 and 0.73). That is a property of this stand-in, not of retrieval depth: a real generator that reads all retrieved passages could turn the extra recall into correct answers, and only a measurement on that generator would show it.
- With the 80 ms budget the k = 3 rows (88 ms under the assumed costs) are excluded, so the choice is k = 1 with abstention. With a 100 ms budget all four rows would be allowed, the two abstain rows would tie on correctness at 0.73, and the tie would go to the cheaper k = 1 row, so the pick would not change here. It would change only if the k = 3 rows scored higher on correctness, which is the case in which paying the extra 12 ms is justified.
- Per category, the weak spots are the paraphrase with no word overlap (a retrieval gap), the stale-versus-current question (a ranking gap), and the unanswerable question that shares the word "support" with a real passage (a threshold gap). A single average would have hidden all three.
- With 11 questions an observed 0.80 has a 95% Wilson interval (a range for a proportion that stays valid at small n) of 0.50 to 0.94; at n = 100 it is 0.71 to 0.87. Two configurations 0.05 apart on a set this small are not distinguishable.
- Cohen's kappa by hand: the two annotators agree on 10 of 12 labels, so observed agreement p_o = 10/12 = 0.833. Annotator A says 1 on 8 of 12 labels and annotator B on 8 of 12, so by luck alone they would agree with probability p_e = (8/12)(8/12) + (4/12)(4/12) = 0.556. Kappa = (p_o - p_e) / (1 - p_e) = (0.833 - 0.556) / 0.444 = 0.625, the share of the possible above-chance agreement that was achieved.
Weighing answer quality against latency
Fix the budget first (for example a p95 target from the product, meaning 95% of requests must finish within it), list the options with their quality and latency, drop what exceeds the budget, and pick the best that remains. Spend latency where it buys the most: a reranker or a larger k when recall is the weak metric, a verification step when wrong answers are costly, and nothing on stages that the per-category table shows are already fine. Report quality at the chosen point together with its interval so the trade is explicit.
Trade-offs and common mistakes
- Averaging everything into one score; use per-category tables.
- Using the same questions for prompt tuning and for the final report.
- Trusting an LLM judge without checking it against human labels.
- Treating faithfulness as correctness.
- Comparing configurations on a few dozen questions without an interval.
- Measuring quality at one latency and shipping at another (cold caches, meaning the first requests after a restart before any results are stored for reuse; and longer contexts).
You need to build a reranker (cross-encoder) to improve top-k relevance. Outline the training data you would use (positives, negatives), loss function, and a strategy for mining hard negatives from the retrieval stage.
Sample Answer
Direct answer
Train the cross-encoder (a pretrained transformer that reads the query and one passage joined into a single text, for example "query [separator] passage", and outputs one relevance number for that pair) on groups: one query, one or more positives, and several negatives drawn from the first-stage retriever's own mistakes. Use a listwise softmax loss over each group as the default, mine hard negatives from a rank band just below the true positives, and filter out probable false negatives before they reach training. Evaluate on held-out queries by re-ranking the retriever's real shortlist.
Training data
Queries and positives.
- Human-judged relevance on real queries is the cleanest source. Label a passage as relevant only if it contains the answer, and keep graded labels (answer, partly relevant, not relevant) if you have them.
- Click and dwell logs (dwell time is how long the user stayed on the result) scale cheaply but carry position bias (people click what is shown at the top), so use them as weak labels and check a sample against human judgement.
- Synthetic queries (a language model writes a question that a given passage answers) cover documents with no traffic; validate the generated questions on a human sample, and drop questions that name the document instead of asking about its content.
- Split train, validation and test by query (and by source document where documents are near-duplicates), never by pair, or the test set leaks.
Negatives, from easiest to hardest.
- Random passages: almost always trivially irrelevant, they teach little once the model is past the basics.
- In-batch negatives: the positives of the other queries in the same batch. They need no extra labels or mining, but they are easy, and for a cross-encoder they are not free in compute: a bi-encoder gets every query-versus-passage score from one matrix product of vectors it has already computed, whereas a cross-encoder must run a separate forward pass for each query-passage pair, so every in-batch negative costs one more pass.
- Retriever negatives: passages the first stage actually ranked high that are not positives. These match what the reranker sees at inference and are the ones that matter.
- Hard negatives from a stronger or the previous model's mistakes: a later round, mined with the reranker you already trained.
Loss function
For one group with a positive score s+ and negative scores s1−,…,sm− (the scores are the model's raw, unbounded outputs, called logits). Two building blocks first. Softmax turns a list of scores into probabilities that sum to 1: each score becomes es and is divided by the sum of all of them, so a higher score gets a larger share. Cross-entropy is the penalty −logp on the probability p given to the correct item: near 0 when p is close to 1, large when p is small.
- Pointwise (binary cross-entropy, BCE: squash each score to a probability with the sigmoid 1/(1+e−s) and apply cross-entropy to each pair on its own, label 1 for the positive and 0 for a negative): simple, and its scores can be read as probabilities of relevance if the training data matches the real mix, but it ignores the other passages in the group.
- Pairwise (the positive should beat each negative). The hinge version with margin δ charges max(0,δ−(s+−s−)), so a negative costs nothing once the positive leads it by at least δ. The logistic version charges log(1+e−(s+−s−)), a smooth penalty that shrinks as the lead grows.
- Listwise softmax (cross-entropy over the group: softmax over the positive and all negatives, penalty on the positive's probability):
The gradient of the loss with respect to a score is how much the loss changes if that score moves up by a small amount, and it is what training follows. Writing the loss as −s++log(es++∑jesj−), the derivative with respect to a negative's score sk− is esk− divided by that same sum, which is exactly that negative's softmax probability. So the passage that scores closest to the positive gets the largest push and the easy ones almost none. That is the property you want when the real task is to put the right passage first among similar ones. Recommended default: listwise over groups of one positive and 7 to 15 negatives (a group size you tune against memory, since every pair is one forward pass), with a few in-batch negatives added only if the extra forward passes fit the compute budget. If you have graded labels or teacher scores (scores from a larger, stronger model or a human-calibrated judge), a regression loss on score differences is the alternative; training a small model to imitate a larger one's scores is called distillation.
Mining hard negatives from the retrieval stage
- Run the production first stage (the same hybrid retriever that will feed the reranker) over the training queries and record the ranked list.
- Remove every passage labelled relevant. Sample negatives from a rank band, for example ranks 2 to 50 on a corpus of millions of passages, rather than only the very top, to limit false negatives and keep variety; mix in a few easy ones so the model does not forget them.
- Guard against false negatives. The top-ranked unlabelled passage is often another correct answer that nobody labelled (a paraphrase, a duplicated policy page). Training on it as a negative teaches the model to push down right answers. Mitigations: drop passages whose similarity to a positive is above a threshold, verify the borderline cases with a stronger judge (a larger model or a human sample), and check training loss on mined negatives against a clean set.
- Refresh: after a first model, re-mine with it, and retrain, which finds the mistakes of the model itself. Watch validation quality each round: if it drops while training loss falls, suspect false negatives.
Worked example
The first part mines hard negatives with BM25 (rank_bm25 0.2.2) as a stand-in for a production retriever, for one query over seven passages, with a similarity filter. The second part computes the four losses on one group with hand-set model scores (a stand-in for a trained cross-encoder's outputs), checks each against a numpy implementation of its formula (the program asserts agreement) and shows which negative receives the gradient (PyTorch 2.5.1, autograd).
import os
os.environ["OMP_NUM_THREADS"] = "1"
import re
import numpy as np
import torch
import torch.nn.functional as F
torch.set_num_threads(1)
from rank_bm25 import BM25Okapi
from sklearn.feature_extraction.text import TfidfVectorizer
# ---- 1. hard-negative mining from a first-stage retriever ----
DOCS = ["Annual plans can be refunded within 30 days of purchase.",
"Yearly subscriptions can be refunded within 30 days of buying them.", # unlabelled paraphrase of the positive
"Monthly plans can be refunded within 7 days of purchase.",
"Refunds are sent to the original payment method.",
"Annual plans renew automatically unless cancelled.",
"Support is open from 9am to 6pm on weekdays.",
"Invoices are emailed on the first day of each month."]
QUERY, POS = "refund window for annual plans", 0
STOP = {"for", "the", "of", "is", "to", "a", "on", "be", "can", "are", "from"}
tok = lambda t: [w for w in re.findall(r"[a-z0-9]+", t.lower()) if w not in STOP]
bm = BM25Okapi([tok(d) for d in DOCS])
s = bm.get_scores(tok(QUERY))
ranked = sorted(range(len(DOCS)), key=lambda i: (-s[i], i))
print("BM25 ranking:", [(i, round(float(s[i]), 2)) for i in ranked[:5]])
tf = TfidfVectorizer().fit(DOCS); V = tf.transform(DOCS)
def sim(i, j): return float((V[i] @ V[j].T).toarray()[0, 0])
def mine(ranked, pos, n=2, dup_threshold=0.3):
out, dropped = [], []
for i in ranked:
if i == pos: continue
if sim(i, pos) >= dup_threshold: dropped.append((i, round(sim(i, pos), 2))); continue # probable unlabelled positive
out.append(i)
if len(out) == n: break
return out, dropped
neg, dropped = mine(ranked, POS)
UNLABELLED_RELEVANT = {1} # ground truth for this demo: doc 1 is a paraphrase of the positive; doc 2 is a different plan
print("mined hard negatives:", neg, "| skipped as probable false negatives (id, tfidf cosine to positive):", dropped)
print("skipped ids that are really relevant:", [i for i, _ in dropped if i in UNLABELLED_RELEVANT], "| skipped ids that were good negatives:", [i for i, _ in dropped if i not in UNLABELLED_RELEVANT])
# ---- 2. losses on one query group: 1 positive + 3 negatives (hand-set scores from the cross-encoder) ----
scores = torch.tensor([2.0, 1.6, 0.2, -1.0], requires_grad=True) # index 0 = positive; index 1 is a hard negative
pos, negs = scores[0], scores[1:]
labels = torch.tensor([1.0, 0.0, 0.0, 0.0])
bce = F.binary_cross_entropy_with_logits(scores, labels) # pointwise
hinge = F.margin_ranking_loss(pos.expand(3), negs, torch.ones(3), margin=1.0) # pairwise hinge, margin 1
logistic = F.softplus(-(pos - negs)).mean() # pairwise logistic
listwise = F.cross_entropy(scores[None], torch.tensor([0])) # softmax over the group
# the same four from the formulas, in numpy
x = scores.detach().numpy(); p = 1 / (1 + np.exp(-x))
np_bce = -(np.log(p[0]) + np.log(1 - p[1:]).sum()) / 4
np_hinge = np.maximum(0, 1.0 - (x[0] - x[1:])).mean()
np_logistic = np.log1p(np.exp(-(x[0] - x[1:]))).mean()
np_list = -(x[0] - np.log(np.exp(x).sum()))
print(f"\npointwise BCE {bce.item():.4f} (numpy {np_bce:.4f}) | pairwise hinge {hinge.item():.4f} (numpy {np_hinge:.4f}) | "
f"pairwise logistic {logistic.item():.4f} (numpy {np_logistic:.4f}) | listwise softmax CE {listwise.item():.4f} (numpy {np_list:.4f})")
assert np.allclose([bce.item(), hinge.item(), logistic.item(), listwise.item()], [np_bce, np_hinge, np_logistic, np_list], atol=1e-6)
# the terms behind each loss, so the four numbers can be redone by hand
e = np.exp(x)
print("exp of the 4 scores:", np.round(e, 3), "| sum", round(float(e.sum()), 3), "| softmax probabilities:", np.round(e / e.sum(), 4))
print("BCE terms (positive, then 3 negatives):", np.round([-np.log(p[0]), *(-np.log(1 - p[1:]))], 4), "| mean", round(float(np_bce), 4))
print("hinge terms (margin 1):", np.round(np.maximum(0, 1.0 - (x[0] - x[1:])), 4), "| mean", round(float(np_hinge), 4))
print("logistic terms:", np.round(np.log1p(np.exp(-(x[0] - x[1:]))), 4), "| mean", round(float(np_logistic), 4))
# ---- 3. which negative gets the gradient? ----
for name, loss in [("listwise softmax CE", listwise), ("pointwise BCE", bce)]:
g, = torch.autograd.grad(loss, scores, retain_graph=True)
print(f"{name:20s} gradient on the 3 negatives (hard, medium, easy): {np.round(g[1:].numpy(), 4)}")
if name.startswith("listwise"):
print(" equals the softmax probabilities of those negatives:", np.allclose(g[1:].numpy(), (e / e.sum())[1:], atol=1e-6))
Output:
BM25 ranking: [(4, 1.06), (0, 0.99), (2, 0.24), (1, 0.0), (3, 0.0)]
mined hard negatives: [4, 3] | skipped as probable false negatives (id, tfidf cosine to positive): [(2, 0.78), (1, 0.56)]
skipped ids that are really relevant: [1] | skipped ids that were good negatives: [2]
pointwise BCE 0.7556 (numpy 0.7556) | pairwise hinge 0.2000 (numpy 0.2000) | pairwise logistic 0.2382 (numpy 0.2382) | listwise softmax CE 0.6341 (numpy 0.6341)
exp of the 4 scores: [7.389 4.953 1.221 0.368] | sum 13.931 | softmax probabilities: [0.5304 0.3555 0.0877 0.0264]
BCE terms (positive, then 3 negatives): [0.1269 1.7839 0.7981 0.3133] | mean 0.7556
hinge terms (margin 1): [0.6 0. 0. ] | mean 0.2
logistic terms: [0.513 0.153 0.0486] | mean 0.2382
listwise softmax CE gradient on the 3 negatives (hard, medium, easy): [0.3555 0.0877 0.0264]
equals the softmax probabilities of those negatives: True
pointwise BCE gradient on the 3 negatives (hard, medium, easy): [0.208 0.1375 0.0672]
Reading it:
- BM25 is the keyword-matching score used as the first stage here. After the filter, the first mined negative is passage 4 (score 1.06, distinct from every other score) and the second is passage 3 (score 0.00). Four passages (1, 3, 5 and 6) tie at 0.00 because none shares a query word, and the code breaks that tie by passage id, so passage 3 is the one picked; any of 3, 5 or 6 would be an equally easy negative, so the identity of the second negative is an artefact of the tie-break while the fact that it is easy is not. With only seven passages the rank band runs out of lexically close candidates, whereas a real corpus has many near-misses in ranks 2 to 50.
- BM25 ranks passage 4 first, the true positive (0) second, and the monthly-plan passage (2) third. The paraphrase of the positive (1) uses "yearly" and "buying", so BM25 ranks it low; a vector retriever would likely rank it high, which is where false negatives bite.
- The similarity filter (TF-IDF cosine at least 0.3) is applied to candidates in ranked order. Passage 1, the unlabelled paraphrase, ties at 0.00 with other passages, and the id tie-break puts it ahead of passage 3, so the filter reaches it and removes it, which is right (a different tie-break could leave it unreached, which is why a real pipeline filters every candidate it might sample). The filter also removes passage 2, the monthly-plan passage, which is a genuinely good negative because it differs from the positive in exactly the detail that matters. Lexical similarity cannot separate "a paraphrase" from "a near-miss with a different fact", which is why borderline cases go to a stronger judge or a human sample rather than a fixed threshold.
- With scores 2.0 for the positive and 1.6, 0.2, -1.0 for the negatives, the pointwise loss is 0.7556, the pairwise hinge with margin 1 is 0.2000, the pairwise logistic loss is 0.2382 and the listwise softmax loss is 0.6341. The hinge loss is already zero for the two easier negatives (the positive beats them by more than the margin) and non-zero only for the hard one.
- Redoing them by hand from the printed terms: the exponentials of the four scores sum to 13.931, so the positive's softmax probability is 7.389 / 13.931 = 0.5304 and the listwise loss is −ln0.5304=0.6341. The hinge terms are 1 - (2.0 - 1.6) = 0.6, then 0 and 0 (the leads of 1.8 and 3.0 exceed the margin), and their mean over three negatives is 0.2000. The logistic and BCE losses are the means of the per-term values printed above (three and four terms respectively).
- In the program,
margin_ranking_lossis the hinge (it takes the positive score repeated three times byexpand, the negative scores and a target of +1 meaning "first should be larger");softplus(-d)is log(1+e−d);cross_entropyapplies softmax over the four scores with class 0 (the positive) as the target;autograd.gradreturns the gradient of a loss with respect to the four scores. - The softmax gradient on the three negatives is 0.3555, 0.0877 and 0.0264: the hard negative gets more than 13 times the push of the easy one, because each negative's push equals the probability the softmax gives it. The pointwise gradients (0.2080, 0.1375, 0.0672, averaged over the four pairs) differ by only about 3 times.
Evaluation and trade-offs
- Measure nDCG@10 (normalised discounted cumulative gain over the top 10: relevant passages add credit that shrinks with their rank and the total is divided by the best possible ordering's total, so 1.0 is perfect) and MRR (mean reciprocal rank: the average of 1 divided by the rank of the first relevant passage) on held-out queries by re-ranking the real retriever shortlist, and compare with the retriever alone. Also report recall of the shortlist, since the reranker cannot add passages.
- Cost grows with group size: each negative is one more forward pass of the query plus the passage. Truncate passages to a fixed length that matches inference.
- Hard negatives raise quality up to the point where false negatives dominate; the cleaner the labels, the harder the negatives you can use.
- Calibrate the score on a validation set if you use a threshold to refuse to answer (calibrating means choosing the cut-off, or mapping scores to probabilities, so that a given score corresponds to a known chance of being relevant), since the softmax loss gives scores that are only meaningful relative to each other within a group.
Common mistakes
- Using only random negatives, then finding that the model cannot separate similar policy pages.
- Treating every unlabelled top-ranked passage as a negative.
- Training and testing on passages from the same source document.
- Evaluating on pairs instead of on re-ranking the retriever's list.
Unlock Full Question Bank
Get access to all 22 Retrieval-Augmented Generation (RAG) interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.