🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Question Answering: Reading Comprehension and Open-Domain QA

Natural Language ProcessingQuestion Answering: Reading Comprehension and Open-Domain QAđŸŸĸ Free Lesson

Question Answering: Reading Comprehension and Open-Domain QA

What You'll Learn

  • 1Frame extractive QA as joint start and end span prediction over a passage
  • 2Score candidate answers with exact match and token level F1
  • 3Decompose open-domain QA into a retrieval step and a reader step
  • 4Pick the right benchmark for your regime

Question answering turns a natural question into a short, correct answer, and unlike classification the output space is every span inside a passage, so the model must both locate and phrase the answer. Regimes differ by what the model may see: the passage, retrieved passages, or only its parameters. This lesson separates those regimes and builds the arithmetic behind exact match, token F1, and retrieval marginalization.

Extractive QA

Given a question and a paragraph , an extractive reader selects a contiguous span and never emits a token absent from the passage:

A bidirectional encoder such as BERT produces one hidden state per token, two linear heads project those states into start logits and end logits , and decoding picks the highest scoring admissible span:

Constraining and capping span length at 30 tokens keeps the search cheap: a 500 token passage yields a few thousand candidates, one vectorized reduction rather than a loop.

BERT-large reaches 88.5 exact match and 93.2 F1 on the SQuAD development split (Devlin et al., 2019), already above the human F1 of 86.8 reported for that set.

Unanswerable questions

SQuAD 2.0 appends adversarially written questions that no paragraph answers, so the reader learns a third option, the null span. It answers nothing when the best span score falls below a threshold tuned on dev:

Lowering trades precision for recall, and because 53,912 of the 150,000 SQuAD 2.0 questions are unanswerable, an untuned threshold costs several F1 points.

Generative and Open-Domain QA

A generative reader abandons the span constraint and models the answer string with an encoder-decoder, which is the only option when the answer is a date, a paraphrase, or a combination of facts no single sentence contains. The freedom has a cost: generators produce fluent text unsupported by the passage, so systems log the supporting span and reject answers without provenance.

Open-domain QA removes the assumption that a passage was given. A retriever scores a corpus of paragraphs and the reader runs over the top , factorizing as a product of two components that fail independently:

In practice the sum truncates to the retrieved set, so end-to-end accuracy is bounded by retrieval recall: if the correct paragraph never enters the top , no reader can recover it. Dense Passage Retrieval (Karpukhin et al., 2020) improved top-20 accuracy by 9 to 19 percent absolute over BM25 on six open-domain datasets, and the gain carried into downstream F1.

DatasetSizeAnswer formWhat it tests
SQuAD 1.1107,785 questionsspan in one paragraphreader accuracy
SQuAD 2.0150,000 questionsspan or abstentionunanswerable detection
Natural Questions307,373 train examplesshort or long answerreal user queries
TriviaQA650,000 evidence triplesshort factoid stringlong tail knowledge

Evaluation Metrics

Exact match is strict equality after normalization, while token F1 rewards partial overlap, which is why SQuAD style leaderboards report both:

Normalization lowercases, strips punctuation, and removes articles, so a prediction with the right content words often reaches F1 above 0.8 while EM stays zero, a signal the entity was found.

Worked Examples

Worked Code

python
"""Extractive QA with a released SQuAD 2.0 checkpoint."""
from transformers import pipeline

qa = pipeline("question-answering",
              model="deepset/roberta-base-squad2",
              handle_impossible_answer=True)
out = qa(question="How many parameters does BERT-large have?",
         context="BERT-large contains 340 million parameters, "
                 "while the base model has 110 million.")
print(out["answer"], round(out["score"], 4))
python
"""SQuAD style exact match and token level F1."""
import re
import string
from collections import Counter


def normalize(text):
    text = text.lower()
    text = "".join(c for c in text if c not in string.punctuation)
    return re.sub(r"\b(a|an|the)\b", " ", text).split()


def score(pred, gold):
    p, g = normalize(pred), normalize(gold)
    overlap = sum((Counter(p) & Counter(g)).values())
    if not overlap:
        return float(p == g), 0.0
    precision, recall = overlap / len(p), overlap / len(g)
    return float(p == g), 2 * precision * recall / (precision + recall)


print(score("Barack Hussein Obama", "Barack Obama"))

Real-World Applications

  • Enterprise search - Employees ask questions over contract corpora, and a reader quotes the clause that answers it.
  • Assistants - Spoken questions route to a retriever first, because a model with only parameters cannot cite a source.
  • Medical literature - Readers answer over abstracts with evidence spans, and clinicians reject answers without a supporting sentence.
  • Support automation - Ticket deflection answers from a knowledge base and falls back to a human when the null span wins.

💡Measure retrieval and reading separately

Report recall at k for the retriever and F1 for the reader on the passages it received. One end-to-end number hides which half regressed.

Common Mistakes

Tuning the null span threshold on the test set

Fix: Select tau on dev data, since SQuAD 2.0 makes threshold choice worth several F1 points.

Reporting F1 without exact match

Fix: Publish both, because high F1 with low EM usually signals span boundary errors.

Ignoring retrieval recall before blaming the reader

Fix: Check whether the gold paragraph reached the top k before investigating the reader.

Best Practices

  • Report recall at 20 for retrieval and F1 on retrieved passages for the reader separately
  • Normalize answers exactly as the benchmark does, including article removal
  • Store the supporting span with every answer so users can verify it

Key Takeaways

  • Extractive QA scores each candidate span as start logit plus end logit under the constraint e at least s
  • Token F1 rewards partial overlap while exact match requires normalized equality
  • Open-domain QA factorizes into retrieval and reading, so quality is capped by recall at k
  • SQuAD 2.0 adds 53,912 unanswerable questions, making threshold calibration part of the task

Frequently Asked Questions

Why is F1 reported next to exact match?

F1 gives partial credit when the model finds the right entity but words it differently, so it separates localization failures from phrasing failures. Watching only EM hides whether retrieval or boundary detection regressed.

How does an extractive model answer something not in the passage?

It cannot, which is why SQuAD 2.0 added a null span and why generative readers exist. If you need paraphrased answers, switch to a generator and keep an evidence check.

When does BM25 still beat dense retrieval?

On rare tokens, identifiers, and product codes, where term overlap is strong evidence and embedding space is sparse. Hybrid setups that fuse both scores inherit the two behaviors.

Interview Questions

Q1: How do you evaluate a QA system over ten million passages?

Split the metric: recall at 20 for the retriever, then reader F1 on the passages retrieved, since one end-to-end score cannot say which stage failed.

Q2: Why does an extractive reader give a confident wrong answer?

With a misconfigured threshold the span decoder must return something, so an unanswerable question becomes a quotation from an unrelated sentence.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement