Question Answering
Prerequisites
- !Softmax over sequence positions
- !How encoders produce per-token representations
- !Precision, recall and F1 on token overlap
What You'll Learn
- 1Choose extractive, generative or open-domain QA from the cost of a wrong answer
- 2Decode answer spans with a length constraint and a calibrated no-answer threshold
- 3Implement exact match and token F1 and read them honestly
- 4Attribute failures to retrieval, reading, or formulation stages instead of guessing
Three architectures, three contracts with the reader
Extractive QA points at a span inside a supplied passage: the answer is copied, not written. Its contract is strong â every answer is anchored to text someone can open â and its limit is equally clear: it can only answer questions whose answer is literally present as a contiguous span.
Generative QA composes an answer from the context, which allows merging facts across sentences and paraphrasing for readability, and allows fabrication in exactly the same motion. The contract must therefore be rebuilt with citations: every claim in the answer should map to a supporting span, or be flagged as synthesis.
Open-domain QA answers without a given passage, so retrieval becomes part of the system. It is the most useful and the most failure-prone, because the model may answer from memory rather than from the document you retrieved â a correct-looking answer that your source does not support.
| Type | Answer form | Primary failure | Verification available |
|---|---|---|---|
| Extractive | Span offsets | Wrong span, no answer exists | Highlight the span |
| Generative | Free text | Confabulation | Citation-to-span check |
| Open-domain | Free text | Wrong or missing retrieval | Source coverage check |
| Conversational | Span or text | Lost pronoun resolution | Turn-level trace |
Pick the weakest contract that satisfies the product. Support deflection often works with extractive answers plus a link; an executive briefing needs generation and therefore needs citations checked mechanically.
Decoding spans instead of tokens
An extractive model scores every position as a possible start and a possible end. Naively taking the two highest scores produces ends before starts and absurd lengths, so decoding applies constraints: end must follow start, the span must fit a length budget, and the pair is scored jointly.
import numpy as np
def decode_span(start_logits: np.ndarray, end_logits: np.ndarray,
max_answer_len: int = 30, null_score: float | None = None,
n_best: int = 5):
"""Return ranked candidate spans as (start, end, score) inclusive."""
T = len(start_logits)
candidates = []
# Log-softmax keeps scores comparable across passages of different length.
def log_softmax(x):
z = x - x.max()
return z - np.log(np.exp(z).sum())
s = log_softmax(start_logits)
e = log_softmax(end_logits)
for i in range(T):
for j in range(i, min(T, i + max_answer_len)):
candidates.append((i, j, float(s[i] + e[j])))
candidates.sort(key=lambda c: -c[2])
best = candidates[:n_best]
if null_score is not None:
# A confident null beats every span: the question is unanswerable here.
best.sort(key=lambda c: -(null_score - c[2]))
if null_score > best[0][2]:
return [(None, None, float(null_score))]
return best
def answer_text(tokens: list[str], span) -> str:
start, end, _ = span
if start is None:
return ""
return " ".join(tokens[start:end + 1])
The null-score comparison is the whole answerability mechanism. In practice the model emits a start position reserved for "no answer" whose logit is compared against the best span score, and the threshold on that difference is calibrated on a validation set â not set to zero â because the model's confidence distribution differs between naturally unanswerable questions and ordinary ones.
Answerability is a threshold, not a vibe
Users do not experience accuracy; they experience what happens on the questions you cannot answer. A system that answers 90% of questions at 85% precision frustrates more people than one that answers 70% at 97% precision, because the wrong answers arrive with no warning attached.
Treat the null threshold as a product parameter. Sweep it on a validation set containing unanswerable questions, and plot coverage against precision; choose the operating point from the cost of a bad answer, then monitor the abstain rate in production. A rising abstain rate with flat conditional accuracy means retrieval quality or question phrasing changed upstream â the model is telling you the passage no longer contains the answer, which is a signal to act on rather than a metric to hide.
â ī¸Never ship an answer without its evidence
For extractive QA, return the offsets and highlight them in the UI. For generative QA, return the citation spans and verify each one programmatically. Answers without evidence train users to trust the system blindly, and the first confident mistake then costs more than a year of correct responses bought.
Grounding generation in retrievable evidence
Generative QA is worth it when the answer needs combining: "which of our plans include SSO and what does the upgrade cost" pulls a feature row and a price row into one sentence. The discipline that keeps it honest has three parts â a prompt that constrains the answer to the provided context, a requirement that the model quote the supporting text for each claim, and a verifier that checks those quotes against the source before anything reaches the user.
import re
def verify_grounding(answer: str, passages: list[str], min_chars: int = 12):
"""Flag answer sentences whose longest quoted span is missing from source."""
source = " ".join(passages).lower()
sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", answer) if s.strip()]
findings = []
for sent in sentences:
quotes = re.findall(r'"([^"]{10,120})"', sent)
supported = False
for q in quotes:
probe = q.lower().strip(".,;:")
if probe in source:
supported = True
break
if not quotes:
# No quotation: look for any long exact overlap with the source.
words = re.findall(r"[a-z0-9']+", sent.lower())
for n in range(len(words), min_chars, -1):
if " ".join(words[:n]) in source:
supported = True
break
findings.append({"sentence": sent, "grounded": supported})
return findings
def summarize_findings(findings):
total = len(findings)
grounded = sum(1 for f in findings if f["grounded"])
return {"sentences": total, "grounded": grounded,
"grounded_pct": round(100 * grounded / max(1, total), 1)}
print(summarize_findings(verify_grounding(
'The Team plan includes SSO. "Contact sales" applies to Enterprise.',
["The Team plan includes single sign-on via SAML.",
"Enterprise customers should contact sales for custom pricing."],
)))
Exact-substring verification is deliberately conservative: it flags sentences it cannot verify rather than guessing at semantic support. A false alarm prompts a reviewer to look; a false pass ships a hallucination.
Evaluation: exact match, token F1, and their limits
Exact match requires the prediction to equal the gold answer after normalization; token F1 rewards partial overlap. Both are cheap and both flatter systems that answer only easy questions.
import re
from collections import Counter
def normalize(text: str) -> str:
text = text.lower()
text = re.sub(r"\b(a|an|the)\b", " ", text)
text = re.sub(r"[^a-z0-9\s]", "", text)
return " ".join(text.split())
def exact_match(prediction: str, gold: str) -> float:
return float(normalize(prediction) == normalize(gold))
def token_f1(prediction: str, gold: str) -> float:
pred, ref = normalize(prediction).split(), normalize(gold).split()
if not pred or not ref:
return float(pred == ref)
common = Counter(pred) & Counter(ref)
overlap = sum(common.values())
if overlap == 0:
return 0.0
precision, recall = overlap / len(pred), overlap / len(ref)
return 2 * precision * recall / (precision + recall)
assert exact_match("the Paris", "Paris") == 1.0
assert abs(token_f1("Bank of America Corp", "Bank of America") - 0.857) < 0.01
Normalize deliberately and document how: article stripping and case folding are standard, punctuation handling is not, and lenient normalization can quietly merge answers that differ. Then supplement with the checks overlap metrics cannot do â answer type accuracy (did it say a date when asked for a date), citation coverage for generative systems, and abstain precision on unanswerable questions.
Question types change what the model must do
Not every question exercises the same machinery, and mixing them in one metric hides which part of your system is weak. Factoid questions â who, when, where â resolve to a single span and are what extractive models handle best. Definition and how-to questions need a sentence or two assembled from adjacent evidence, which pushes toward generation or multi-span extraction. Aggregation questions ("which region had the most tickets") require computing over the passage, something span extraction cannot do at all and generation does only when it does not silently drop a candidate. Comparison questions need two pieces of evidence held simultaneously, and the classic failure is retrieving one side. Multi-hop questions â where the answer depends on a fact introduced elsewhere â fail most often at retrieval rather than reading, because the second hop never entered the context.
Track a small labelled slice per question type rather than one blended score. A model that gains two points overall while losing eight on aggregation questions is a regression that a single aggregate would have celebrated. The same discipline applies to prompt design: tell the model which type it is answering and what form the answer must take, because a system asked for a date and given latitude to write prose will eventually write a paragraph where a date belonged.
Retrieval QA and where the failures really come from
When the answer is not in the prompt, the pipeline becomes retrieve, read, formulate â and most failures are attributable to exactly one stage. Bucket them. Retrieval failures: the right passage never entered the context, so the model either abstains or answers from memory. Reading failures: the passage is present and the model picks the wrong span or misreads scope â "up to 5%" becoming "5%". Formulation failures: the reading was right and the wording lost a hedge, a unit or an attribution. Evaluation failures: the prediction was correct but the gold answer used different phrasing or the normalization was too strict.
Each bucket demands a different fix. Retrieval failures go to chunking, query rewriting and hybrid search; reading failures to context formatting and distractor removal; formulation failures to constrained generation and number copying; evaluation failures to your gold set. Sample twenty failures a week, label the bucket, and the distribution tells you where the next engineering week has the highest expected return â a discipline that beats arguing about models.
Common Mistakes
Answering unanswerable questions instead of abstaining
Fix: Calibrate the null-score threshold on data containing unanswerable questions and monitor the abstain rate
Shipping generative answers without checking their citations
Fix: Verify quoted spans against the source programmatically and block ungrounded sentences
Reading EM and F1 as the whole quality story
Fix: Add answer-type accuracy, citation coverage and abstain precision to the dashboard
Blaming the model for what is a retrieval miss
Fix: Label failures by stage â retrieval, reading, formulation, evaluation â before changing anything
Best Practices
- Return offsets or citations with every answer so the user can verify in one click
- Return ranked span candidates; a second-best span often exposes a decoding bug instantly
- Set thresholds from the cost of a wrong answer rather than from the validation optimum
- Keep a frozen set of unanswerable questions in every evaluation run
- Track failure buckets weekly so fixes are chosen by expected value instead of fashion
Key Takeaways
- Choose the weakest answer contract the product allows: spans are verifiable, generation is flexible, open-domain is both useful and leaky
- Span decoding needs a length constraint and a calibrated no-answer threshold â both are product parameters
- Abstain rate is the leading indicator of system health; conditional accuracy stays flat while retrieval degrades
- Grounding verification should be conservative: flag what you cannot prove rather than trusting fluent prose
- Attribute failures to retrieval, reading, formulation or evaluation before touching the model