Sub topic 2
SQuAD-style data: questions, contexts, and answer spans
This chapter covers the data an extractive question answering (QA) model learns from and is scored on. It assumes you know basic Python, have seen JSON and dictionaries, and know that a transformer reads tokens, not characters. Tokenization comes in a later chapter. Here the unit is the character, because that is how the dataset records answers.
Why the data format deserves a chapter
An extractive QA model never writes text. It points at a piece of the passage. The training data therefore has to say which piece is correct, and the way it says so shapes everything downstream: label building, decoding, evaluation, and the handling of unanswerable questions. If you misread the format, you get silent bugs. The model trains without errors, but every label is shifted by a few characters.
The format used by the Stanford Question Answering Dataset (SQuAD) has become the standard shape for extractive QA data. Many other datasets copy it, so "SQuAD-style" has become a general name for it.
The three parts of an example
Every example has three required parts:
- Context: a passage of text, usually one paragraph from a Wikipedia article.
- Question: a natural-language question written by a crowd worker who read that paragraph.
- Answer span: a contiguous piece of the context that answers the question. It is stored as the answer text plus
answer_start, the zero-based character index in the context where the text begins.
The span is stored twice, once as text and once as a position. This redundancy is deliberate. The text lets you read the data by eye and compute metrics. The position removes ambiguity when the same words occur more than once in the context.
The original nested JSON
The released SQuAD files group examples by article, then by paragraph, then by question. One paragraph is shared by many questions.
Here is a miniature file in that layout. The code builds answer_start with str.index so the sample is guaranteed consistent. In a real file the numbers are stored directly. The code then flattens the nesting into one record per question and checks the invariant that holds for every valid answer.
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."
)
answer_text = "about seven million square kilometres"
raw = {
"version": "v2.0",
"data": [{
"title": "Amazon_River",
"paragraphs": [{
"context": context,
"qas": [
{
"id": "q1",
"question": "What does the Amazon basin cover?",
"answers": [{"text": answer_text, "answer_start": context.index(answer_text)}],
"is_impossible": False,
},
{
"id": "q2",
"question": "Who first mapped the Amazon River?",
"answers": [],
"is_impossible": True,
},
],
}],
}],
}
def flatten(raw):
"""Turn the nested article/paragraph/question layout into one flat record per question."""
rows = []
for article in raw["data"]:
for paragraph in article["paragraphs"]:
for qa in paragraph["qas"]:
answers = qa.get("answers", [])
rows.append({
"id": qa["id"],
"title": article["title"],
"context": paragraph["context"],
"question": qa["question"],
"answers": {
"text": [a["text"] for a in answers],
"answer_start": [a["answer_start"] for a in answers],
},
})
return rows
def bad_spans(row):
"""Return the answers whose text does not appear at its stated character position."""
problems = []
for text, start in zip(row["answers"]["text"], row["answers"]["answer_start"]):
if row["context"][start:start + len(text)] != text:
problems.append((text, start))
return problems
for row in flatten(raw):
print(row["id"], row["answers"], "bad:", bad_spans(row))For q1 the check finds no bad spans. For q2 both answer lists are empty, so the check has nothing to compare, and the example counts as unanswerable.
The flat form used by Hugging Face
The datasets library stores SQuAD in the flat form that flatten produced. Each row has id, title, context, question, and an answers dictionary whose values are lists. The lists are parallel: answers["text"][i] starts at answers["answer_start"][i].
from datasets import load_dataset
squad = load_dataset("rajpurkar/squad") # downloads the data on first use
print(squad) # train has 87,599 rows and validation has 10,570
example = squad["train"][0]
print(example["question"])
print(example["answers"])
# A validation example usually has several reference answers.
dev = squad["validation"][0]
print(len(dev["answers"]["text"]), dev["answers"]["text"])Note that answers is a dictionary of lists, not a list of dictionaries. Code written for the original JSON, such as qa["answers"][0]["text"], fails on this form. You need row["answers"]["text"][0].
Versions of the dataset
| Property | SQuAD 1.1 | SQuAD 2.0 |
|---|---|---|
| Every question has an answer in the context | Yes | No |
| Unanswerable questions | None | About one third of the questions are unanswerable |
| Unanswerable marker | Not applicable | `is_impossible` is true and `answers` is empty |
| Extra field | None | `plausible_answers` on unanswerable training questions |
| Hugging Face name | `rajpurkar/squad` | `rajpurkar/squad_v2` |
Version 2.0 keeps all the answerable questions of 1.1 and adds over 50,000 questions that were written to look answerable but are not. A good model for 2.0 has to decide when to give no answer. A later chapter covers that decision. For now, remember the data convention: an empty answers["text"] list means "no answer".
Training and evaluation records differ
The two splits do not look the same, and the difference matters for evaluation.
- In the training split, each question has one answer.
- In the validation split, each question has several answers, written by different annotators. They often differ in length or wording, for example "seven million square kilometres" and "about seven million square kilometres".
Evaluation takes the best match over all reference answers. A prediction counts as right if it matches any one of them. This is why the metric example in the plan passes lists of references, and why you should never compare a prediction with only answers["text"][0] in the validation set.
Gotchas when working with the data
Positions are characters, not words or tokens
answer_start counts characters in the Python string, including spaces and newlines. A transformer works on subword tokens, so you cannot use answer_start as a model label directly. Converting between the two requires the offset mappings that the tokenizer produces, which later chapters cover. Do not try to count words by splitting on whitespace.
Text that occurs more than once
If the answer is "1998" and the context mentions 1998 twice, context.find("1998") returns the first match, which may be the wrong one. Always use the stored answer_start. When you create your own SQuAD-style data, record the position at annotation time. Do not recover it by searching afterwards.
Whitespace and Unicode
The invariant context[start:start + len(text)] == text can break if a pipeline changes the context after the positions were computed. Stripping whitespace, normalizing Unicode, or replacing line breaks all shift characters. If you preprocess the context, do it before you compute positions, or recompute them. Run bad_spans over the whole dataset after any cleaning step.
Many questions share one context
A single paragraph appears in many rows. Two consequences follow:
- Splitting rows randomly into training and test sets leaks passages across the split. The released splits are divided by article, and you should keep that rule for data you build.
- Tokenizing every row repeats work on the same context. This is acceptable at SQuAD scale. Keep it in mind for large corpora.
Spans must be contiguous
An answer is one unbroken piece of the context. Questions whose answers combine two distant sentences, require counting, or need a yes or no cannot be represented. Such questions are either dropped from SQuAD-style data or handled by a different task format. The final chapter returns to this limit.
Building your own data
If you want to fine-tune on your own documents, you can produce records in the flat form shown above. Each row needs a unique id, the context, the question, and answers with parallel lists. Mark unanswerable questions with empty lists, and only if your training setup supports them. Keep contexts short enough to fit the model, or accept that they will be split into windows. The chapter on long contexts explains that split. Validate every row with the span check before you start.
Exercise
A validation row has context "The treaty was signed in 1648 and ratified in 1649." and answers {"text": ["1649"], "answerstart": [47]}. A colleague says the label is wrong because "1648" appears earlier. Is the label correct? Count the characters to decide, and explain what `answerstart` guarantees.
Show answer
Index the context from zero. "The treaty was signed in " has 25 characters, so "1648" starts at 25 and ends at 29. " and ratified in " has 17 characters, from index 29 to 46, so "1649" starts at 46, not 47. The stored position is off by one: context[47:51] is "649." and does not equal "1649". The label is therefore wrong, but the reason is the off-by-one position and not the earlier "1648". answer_start is an explicit zero-based character index. It removes any ambiguity about which occurrence is meant, as long as context[start:start + len(text)] == text holds.
Exercise
You load SQuAD 2.0 and want to count the unanswerable questions in the training split. Which condition on a row identifies them, and why is row["answers"][0] the wrong way to access an answer in the Hugging Face form?
Show answer
A row is unanswerable when len(row["answers"]["text"]) == 0. In the Hugging Face form, answers is a dictionary of parallel lists, so the first answer text is row["answers"]["text"][0]. Indexing the dictionary with 0 raises a KeyError. You would count with sum(len(r["answers"]["text"]) == 0 for r in squad_v2["train"]).