Sub topic 1
What extractive question answering is
Extractive question answering (QA) takes a question and a passage of text, then returns a piece of that passage as the answer. The model never writes new words. It points at a stretch of the passage and says "this is the answer." This chapter defines the task, shows how it differs from nearby approaches, and covers the ways it fails. The later chapters build and run the models.
Prerequisites
This chapter assumes you have the following:
- Basic Python, including strings, slicing, and dictionaries.
- Familiarity with PyTorch tensors or a similar array library. You won't need it until later chapters, but the series uses it.
- A general idea of what a neural network and a pretrained language model are.
- A basic understanding of tokenization, which means splitting text into smaller units that a model can read.
You don't need to know how transformers work internally. Later chapters explain the parts you need.
The task in one sentence
Given a question and a context, an extractive QA system returns a span of the context that answers the question. A span is a contiguous run of text, such as "seven million square kilometres". It is identified by where it starts and where it ends.
Here is a small example.
- Context: "The Amazon River in South America is the largest river by discharge volume of water in the world. Its drainage basin covers about seven million square kilometres."
- Question: "What does the Amazon basin cover?"
- Answer: "about seven million square kilometres" (or just "seven million square kilometres", depending on annotation)
The answer is a substring of the context. This one property defines the task, and it has consequences for what the model can and cannot do.
The answer is a pair of positions
An extractive QA system does not produce text. It produces two positions in the context: where the answer starts and where it ends. The answer string is recovered afterwards by slicing the context.
The next snippet shows this contract in plain Python. It uses no model, only the data shape that the rest of the series relies on.
context = (
"The Amazon River in South America is the largest river by discharge "
"volume of water in the world. Its drainage basin covers about seven "
"million square kilometres."
)
question = "What does the Amazon basin cover?"
answer_text = "seven million square kilometres"
answer_start = context.index(answer_text) # character position
answer_end = answer_start + len(answer_text) # exclusive end
print(answer_start, answer_end)
print(context[answer_start:answer_end])
assert context[answer_start:answer_end] == answer_textEverything a model does in this task amounts to predicting answer_start and answer_end, or the token positions that correspond to them. Later chapters turn that idea into logits (raw scores), decoding, and training labels.
How it differs from other approaches
Question answering is a family of tasks. They differ in where the answer comes from and what the model is allowed to output.
| Approach | Input | Output | Where the answer comes from |
|---|---|---|---|
| Extractive QA | Question and one passage | A span copied from the passage | The passage you supply |
| Generative QA | Question, with or without a passage | Newly written text | The model's own generation |
| Retrieval-based QA | Question and a large collection | Documents or passages | An index over many documents |
| Open-domain QA | Question only | An answer string | Retrieval, then reading or generation |
Extractive versus generative
A generative model, such as a sequence-to-sequence or decoder-only language model, writes the answer token by token. It can paraphrase, combine facts from two sentences, or answer "yes" when "yes" appears nowhere in the text. It can also state something the passage never said. This is usually called hallucination.
An extractive model can't do any of that. This is its main limitation and its main strength.
- Every answer can be traced to exact characters in the source. You can highlight it in the document and show the user where it came from.
- The output space is small. The model chooses among positions, not among all possible strings.
- Models are small and fast. The distilled model used in this series has roughly 66 million parameters and runs on a CPU.
- It cannot answer questions that need a paraphrase, a count, a comparison, or a summary, unless the exact words are in the text.
Extractive versus retrieval
Retrieval finds which document or passage is relevant. Extractive QA finds the answer inside a passage you have already chosen. The two are often combined. A retriever narrows a large collection down to a few passages, and an extractive reader then scans each passage for a span. This chapter covers only the reader. The retriever is a separate component, and the reader's quality does not depend on how it was built.
Why the span formulation works
Predicting a span turns a language task into a classification task over positions. A passage with 300 tokens gives 300 candidate start positions and 300 candidate end positions. The model gives each position a score, and the best valid pair wins. This has several practical benefits:
- A fixed, simple output. The model needs no decoder loop, no sampling settings, and no length control.
- Verifiable answers. The span can be checked against the source by simple string comparison.
- Easy evaluation. Predicted and reference answers are short strings. They can be compared with exact match and F1, which later chapters cover.
- Good use of pretrained encoders. An encoder such as BERT or DistilBERT already builds a rich representation of each token in context. The span head only has to score those representations.
The standard benchmark for this setup is SQuAD, the Stanford Question Answering Dataset. Its questions were written by crowd workers who read a Wikipedia paragraph and marked the answer span in it. The next chapter looks at that data format in detail.
What the model reads
The model sees the question and the context together as one input sequence. It does not read the context first and then answer from memory. Each token of the context is represented with knowledge of the question, so the model can notice which words in the passage match what was asked. The "What does the Amazon basin cover?" question points at "covers" and at the phrase after it.
Two details matter for the rest of the series, so remember them now.
- Models work on subword tokens, not words or characters. An answer is therefore first found as token positions, and then mapped back to character positions in the original string.
- Models have a maximum input length, often 384 or 512 tokens. A long document must be split into windows before it can be read.
Both details are covered in their own chapters.
Common errors and misconceptions
These are the mistakes people make most often when they first meet the task.
- Expecting the model to know facts. The model answers from the context you pass in. Ask "What is the capital of France?" with an unrelated context, and it will still return some span, because it has no way to say "I don't know" unless it was trained to. Handling that case takes a separate mechanism, covered in the chapter on unanswerable questions.
- Expecting reasoning or aggregation. A question such as "How many rivers are mentioned?" needs counting. Unless the passage states the number, the extractive model has nothing to copy.
- Expecting a full sentence. The answer is usually a short phrase. Spans in SQuAD average only a few words, so the model learns to return short ones.
- Treating the score as a probability of being right. The confidence score reflects how the model ranks spans within a passage. It is not calibrated, and it can be high for a wrong answer.
- Ignoring answer variation. "about seven million square kilometres" and "seven million square kilometres" both express the same fact, and a human might accept either. Boundary disagreements are a normal source of metric loss, which is why F1 exists next to exact match.
- Passing the wrong context. If the answer is not in the passage you supply, no model setting can fix it. Check retrieval or document splitting before you blame the reader.
Failure modes to watch for
Even a well-trained extractive model fails in predictable ways.
| Failure | What it looks like | Typical cause |
|---|---|---|
| Wrong entity | Returns a similar item from the passage, such as a different date | The question matches several candidates by surface similarity |
| Boundary error | Returns "seven million" instead of "seven million square kilometres" | Ambiguous annotation or overly short span preference |
| Answer from nowhere | Confident span for an unanswerable question | The model was never trained to abstain |
| Missed answer in a long document | Correct text is present but not found | The answer sits outside the window the model read |
| Needs inference | Returns an unrelated phrase | The answer requires reasoning, not matching |
You will see most of these again when we cover long contexts, unanswerable questions, and error analysis.
Where this chapter sits in the series
Here is the path ahead. You will look at the data format, then at tokenization and offsets, then at how a pretrained encoder and a pair of start and end scores produce an answer. After running a ready-made model, you will decode its outputs by hand, handle long and unanswerable inputs, measure quality, and finally build labels and fine-tune a model. Each step turns the same idea, picking two positions in a passage, into working code.
Exercise
A user wants a QA system that answers "Summarize the main argument of this report in one sentence." Would an extractive QA model be a good fit, and why or why not? Name one task from this chapter where it would fit better.
Show answer
No. An extractive model can only copy a contiguous span of the report, so it cannot write a new summary sentence or combine ideas from several places. A generative model fits better. An extractive model fits a factual lookup such as "What does the Amazon basin cover?", where the exact answer words appear in the passage.
Exercise
In the code example, the answer is found with context.index(answer_text). What two numbers define the answer span, and why is the end position computed as answer_start + len(answer_text) and treated as exclusive?
Show answer
The two numbers are the start character position and the end character position. The end is exclusive so that Python slicing context[start:end] returns exactly the answer, and the span length is end - start. This matches the convention used by tokenizer offset mappings in later chapters.
Exercise
You pass a passage about the Amazon River to an extractive QA model and ask "Who wrote Hamlet?". The model returns a confident-looking phrase from the passage. Explain why this happens and name one fix.
Show answer
The model always chooses the best-scoring span in the text it is given, and a model trained only on answerable questions has no way to abstain. The returned phrase is the least bad candidate, not a real answer. One fix is to train or use a model that supports a null answer for unanswerable questions, as in SQuAD 2.0. Another is to set a score threshold below which the system reports "no answer."