Question Answering
A question-answering system takes a natural-language question and returns an answer, not a ranked list of documents. Almost every modern system is built on one pattern: retrieve then read.
╌╌╌╌
A search engine returns documents; a question-answering system returns an answer.
For the question What's the official language of Algeria?
, the correct output
is the word Arabic, not ten Wikipedia pages ranked by relevance. Almost every
modern system produces the answer with one pattern: retrieve a small set of
promising passages from a large collection, then read or generate the
answer from them.1
Two distinctions organize the field. The first is what
kind of question is asked. A factoid question has a short, factual answer that
can be stated in a phrase — a name, a date, a place (Where is the Louvre?
→
in Paris
). A complex question needs synthesis across several facts or a
paragraph of explanation (Why did the Roman Republic fall?
). The second is how
the answer is produced. Extractive QA returns a literal span copied out of
some source text; generative (or abstractive) QA writes the answer in its own
words, possibly combining several sources. Most of this lesson is factoid QA,
because it exposes the machinery most cleanly, but the retrieve-then-generate
skeleton scales straight up to the complex, generative case.
Information retrieval
Everything downstream depends on the retriever handing the reader a handful of passages that actually contain the answer, so we start there. Information retrieval (IR) is the task of returning, from a large document collection, the documents most relevant to a query.2 We write the query as and a document as , and represent both as vectors in a shared space; relevance is then a geometric quantity — how aligned the query vector is with the document vector.
Term weighting and the vector space model
The oldest representation is a sparse word-count vector: one dimension per vocabulary term, most entries zero. Raw counts overweight common words, so each term in a document is weighted by tf-idf, the product of a term frequency and an inverse document frequency,
where is the number of documents and the number that contain . The idf term does the real work here: a word appearing in every document (like the) carries and is downweighted to nothing, while a rare, discriminating word gets a large weight. Documents are then scored against the query by the cosine of their vectors, which for the usual simplification (query terms counted once, query normalization constant across documents) reduces to a sum over the query's terms,
with the document's vector length; the denominator prevents a long document from scoring highly on term count alone.
A slightly richer member of the same family is BM25, which adds two knobs: a parameter balancing term frequency against idf, and controlling how much document length is penalized. The BM25 score of given is
where is the average document length. Reasonable defaults are and . At BM25 ignores term frequency entirely and reduces to a binary idf-weighted match; large recovers raw term frequency. BM25 remains a strong, ubiquitous baseline that dense retrievers do not always beat.
Worked example: tf-idf vs. BM25 on two documents
Run both scorers on one query against two toy documents to see the effect of and . The query is tragic love; the collection has documents, in of which love occurs and of which tragic occurs, so the idf weights are and . Two candidate documents, with the average document length :
| doc | length | count(love) | count(tragic) |
|---|---|---|---|
is short and focused; is long and repeats love forty times. Plain tf-idf (using the log-squashed and summing over the query terms) rewards that repetition:
against . Plain tf-idf ranks the long, keyword-stuffed above .
BM25 at the default , (using the raw term count as inside the saturation term, per the formula above) flips the ranking. The love term in , despite forty occurrences, contributes almost the same as love in with eight, because the tf saturates and the length penalty grows the denominator:
Forty occurrences in the long document beat eight in the short one by less than a hundredth of a point. Summing both query terms gives the full scores below, and varying the knobs isolates what each controls:
| scorer / setting | winner | ||
|---|---|---|---|
| plain tf-idf | |||
| BM25 (default) | |||
| BM25 (ignore tf) | tie | ||
| BM25 (no length norm) | |||
| BM25 (full length norm) |
Read the last three rows as controlled experiments. At term frequency drops out of the formula entirely and both documents score — a pure binary idf match, since both contain both query terms. Turning length normalization off () lets 's extra occurrences win again, exactly as plain tf-idf did; turning it fully on () penalizes 's length hardest and gives the largest margin. The default sits between, enough to stop a long document from ranking first on sheer term count. BM25's two parameters correct the two ways plain tf-idf misranks: unbounded term-frequency reward and no penalty for length.2
The inverted index
To score documents we first have to find the ones sharing a term with the query, and scanning the whole collection per query is far too slow. The inverted index is the data structure that makes it fast.3 It maps each term to a postings list — the document IDs that contain it, usually annotated with the term's count or positions — through a dictionary of terms built for quick lookup. Given the query's terms, a lookup in the dictionary yields exactly the candidate documents that could score above zero, together with the counts needed to compute tf-idf.
Dense retrieval
tf-idf and BM25 share a structural weakness: they only match when the query and document use the same words. A user asking about a tragic love story will never match a passage that says star-crossed lovers — this is the vocabulary mismatch problem.4 To address it, replace sparse word-count vectors with dense ones: a fixed-length embedding, a few hundred real numbers, produced by an encoder that has learned to place synonymous text nearby. Because the vectors come from a model trained on meaning rather than surface form, tragic love story and star-crossed lovers land close together even with no shared word.
Modern dense retrieval uses a bi-encoder: two encoders, one for the query and
one for the document, each a transformer like BERT.
We take the [CLS] output of each as the vector and score by dot product,
Encoding both sides separately is what makes this practical at scale: every document vector is computed once, offline, and stored, so a query only has to encode and find its nearest neighbors. That nearest-neighbor search over millions of dense vectors is itself expensive, so systems use approximate nearest neighbor libraries like Faiss instead of an exact scan.
Evaluating retrieval
A ranked retriever is judged with precision and recall: precision is the fraction of returned documents that are relevant, recall the fraction of relevant documents returned. Because both ignore order, ranked systems are usually summarized by mean average precision (MAP), which averages the precision measured at each rank where a relevant document appears, then averages that over a set of queries. Higher precision across all recall levels is the goal; MAP folds the whole precision-recall curve into one comparable number.
IR-based factoid QA: retrieve and read
With a retriever in hand, the dominant IR-based architecture is retrieve and read.5 Stage one retrieves relevant passages from the collection using the IR machinery above. Stage two runs a neural reading-comprehension model over each passage: given the question and a passage that may contain the answer, it extracts the answer span — a contiguous run of tokens.
Span extraction with BERT
The reading model computes, for a question of tokens and a passage of tokens , the probability that each candidate span is the answer. It factors that span probability into a start and an end: for span from token to token ,
So the model only has to compute, for every passage token , the probability
that it begins the answer and that it ends
it. The standard baseline concatenates the question and passage into one BERT
input, separated by a [SEP] token and prefixed by [CLS], yielding an
embedding for every passage token.6 This reuses the
fine-tuning
recipe wholesale — a pretrained encoder plus a small task head trained on labelled data.
The head is two learned vectors, a span-start embedding and a span-end embedding . The start probability of token is a softmax of the dot product between and that token's embedding, and the end probability is the same with ,
The score of a candidate span from to is , and the model returns the highest-scoring span with . Fine-tuning minimizes the negative log-likelihood of the gold start and end positions,
Unanswerable questions get a simple treatment. Datasets like SQuAD 2.0 include
questions whose answer is not in the passage; the model learns to point both the
start and end at the [CLS] token in that case, so [CLS] serves as the
no-answer prediction. And because passages are often longer than BERT's token
limit, a long document is chopped into overlapping windows, each treated as its own
passage, and the answer is the highest-scoring span across all of them.
A worked retrieve-and-read trace
Carry a real question through both stages. Ask When was Mozart born?
against a
tiny collection of three passages, with a dense bi-encoder retriever and a BERT
reader.
Stage one — dense retrieval. The query encoder maps the question to a vector , and each passage was encoded offline to . Scoring by dot product gives a ranking; suppose the numbers come out as
| passage | text (excerpt) | |
|---|---|---|
| Wolfgang Amadeus Mozart was born in Salzburg on 27 January 1756 … | ||
| Mozart composed more than 600 works before his death in 1791 … | ||
| Salzburg is a city on the Salzach river in Austria … |
Note that shares the word Mozart and shares Salzburg, but the passage
that actually states the birth, , wins because the bi-encoder places the meaning
of when born
near was born … on … 1756
even though the question's words when
and born appear differently in the passage. A sparse BM25 retriever keying on the
word born would also surface here, but would rank a passage using birth or
native of far lower — the vocabulary-mismatch gap dense retrieval closes. The top
passages (say : ) pass to the reader.
Stage two — span extraction. The reader concatenates the question with into
one BERT input, [CLS] when was Mozart born ? [SEP] Wolfgang Amadeus Mozart was born in Salzburg on 27 January 1756 [SEP], and produces an embedding per token. The
learned start vector dots highest with the token 27 and the end vector dots
highest with 1756, giving the candidate span 27 January 1756. Suppose the dot
products land at
and that this beats every span the reader extracts from (whose best span, around
1791, scores lower because is about his death, not his birth) and beats the
[CLS]-to-[CLS] no-answer score. The system returns 27 January 1756 — or, under a
stricter answer normalization that keeps only the year, 1756. The retriever narrowed
the collection to two passages; the reader extracted one span from the top passage.
Datasets
Reading-comprehension datasets are built as (passage, question, answer-span) triples. SQuAD takes Wikipedia passages and has annotators write questions whose answers are spans of the passage; HotpotQA forces reasoning across multiple documents; Natural Questions uses real Google queries paired with a Wikipedia page, annotating a long and a short answer or null. At training time the reader sees the gold passage; at inference in the full two-stage system the passage is withheld and the retriever must find it — which is why open-domain QA is harder than reading comprehension alone. The retriever-plus-reader pattern handles any answer that appears verbatim in some passage. Two cases fall outside it: answers that live in a structured knowledge base rather than prose, and answers a large language model can generate from its own weights. This continues in Question Answering: Knowledge Bases and Language Models.
Footnotes
- Jurafsky & Martin, Speech and Language Processing (3rd ed.), Ch. 23 — Question Answering: factoid vs. complex questions, extractive vs. abstractive answers, and the retrieve-and-read paradigm shared across IR-based systems. ↩
- Jurafsky & Martin, §23.1 — Information Retrieval: the vector space model, tf-idf term weighting, cosine document scoring, and BM25. ↩ ↩2
- Jurafsky & Martin, §23.1.3 — Inverted Index: dictionary and postings lists for efficiently finding documents that contain query terms. ↩
- Jurafsky & Martin, §23.1.5 — IR with Dense Vectors: the vocabulary-mismatch problem, the BERT bi-encoder, and approximate nearest-neighbor search with Faiss. ↩
- Jurafsky & Martin, §23.2 — IR-based Factoid Question Answering: the retrieve-and-read model and the reading-comprehension task, with SQuAD, HotpotQA, and Natural Questions. ↩
- Jurafsky & Martin, §23.2.2 — Reader (Answer Span Extraction): the BERT span model with learned start/end vectors, the
[CLS]-as-no-answer trick, and the span-position log-likelihood loss. ↩
╌╌ END ╌╌