AI Logic

Datasets and Benchmarks

SQuAD

Updated:

How SQuAD is built and evaluated. Left: the pipeline that selects 536 top-ranked Wikipedia articles, extracts paragraphs, has crowd workers write questions and mark answer spans, adds extra answers for evaluation to produce SQuAD 1.1, and adds unanswerable questions to make SQuAD 2.0, along with the number of questions in the train, dev, and test sets. Right: an example of extracting an answer span from a paragraph and question, and an example calculation of exact match and F1.

Overview

SQuAD (Stanford Question Answering Dataset) is a reading comprehension dataset in which pairs of Wikipedia paragraphs and human-written questions about them are annotated with answer spans in the paragraph. Rajpurkar and colleagues at Stanford University published it in 2016 (EMNLP 2016). The first version has 536 articles and about 108,000 questions, and it became the standard benchmark for extractive question answering, in which the answer is taken verbatim from the paragraph.

For example, given a paragraph about precipitation and the question "What causes precipitation to fall?", the model answers by extracting the phrase "gravity" from the paragraph. There are no choices; every span in the paragraph is a candidate answer.

It was created because earlier reading comprehension datasets had the following shortcomings.

  • High-quality datasets were too small: Human-made datasets such as MCTest had only a few thousand questions, not enough for models trained on large amounts of data.
  • Large datasets were generated automatically: Cloze-style datasets that blank out words in news summaries are large, but differ in nature from genuine reading comprehension questions.

SQuAD achieved both by collecting high-quality human-written questions on a scale nearly two orders of magnitude larger than previous manually built datasets. Restricting answers to spans in the paragraph also has the advantage of making scoring easier than with free-form answers.

SQuAD 2.0 (2018) added more than 50,000 questions that cannot be answered from the paragraph. SQuAD 2.0 models must not only extract answers but also abstain when there is no answer.

Contents: construction, splits, and format

Construction has three stages: select articles, have people write questions and answers for each paragraph, and add extra answers for evaluation.

  1. Select paragraphs. 536 articles are randomly sampled from the top 10,000 English Wikipedia articles by PageRank. Paragraphs are extracted with images, figures, and tables removed, and paragraphs shorter than 500 characters are discarded. This yielded 23,215 paragraphs. Articles are split 80% train, 10% dev, and 10% test, with the article as the unit.
  2. Write questions and answers. Crowd workers (experienced workers in the US or Canada) write up to five questions per paragraph and mark the span in the paragraph that answers each one. They are asked to phrase questions in their own words rather than copying the paragraph, and copying and pasting text from the paragraph is disabled.
  3. Add answers for evaluation. For dev and test questions, at least two additional workers each add an answer by selecting the shortest span that answers the question. For 2.6% of the dev and test questions, at least one of the additional workers judged them "not answerable from the paragraph."

Answer types are not limited to dates and numbers (19.8%) or proper nouns such as person and place names (32.6%); they extend to common noun phrases (31.8%) and adjective phrases, verb phrases, clauses, and so on (15.8%). In the original paper's analysis of the dev set, every question differs in some way from the answer sentence in the paragraph through paraphrasing or syntactic variation.

Splits are made with the article as the unit. SQuAD 2.0 keeps the same article split and adds unanswerable questions.

SplitSQuAD 1.1 questionsArticlesSQuAD 2.0 questionsOf which unanswerableArticles
Train87,599442130,31943,498442
Dev10,5704811,8735,94535
Test (hidden)9,533468,8624,33228

(Counts are from Table 2 of the SQuAD 2.0 paper.)

The unanswerable questions in SQuAD 2.0 were written by crowd workers, up to five per paragraph, to resemble answerable questions. They are about entities that appear in the paragraph and are constructed so that a plausible answer candidate (plausible but wrong) exists in the paragraph. In the dev and test sets, answerable and unanswerable questions are roughly half and half.

The format is JSON that lists paragraphs per article, with a list of questions attached to each paragraph. Each question has a question ID, the question text, and answers (the answer string and its start position in the paragraph). In SQuAD 2.0, unanswerable questions carry a flag (is_impossible) and plausible answer candidates.

Evaluation rules

Evaluation uses two metrics: exact match (EM) and F1. Both compare answers after lowercasing and removing punctuation, articles (a, an, the), and extra whitespace.

  1. Exact match: The fraction of questions for which the prediction is the same string as any one of the reference answers.
  2. F1: Treat the prediction and the reference as bags of words, compute precision and recall from the number of shared words, and take their harmonic mean. When there are multiple references, the highest F1 is taken, and the result is averaged over all questions.

With PP as the set of predicted words and GG as the set of reference words, the F1 for one question is as follows.

precision=∣P∩G∣∣P∣,recall=∣P∩G∣∣G∣,F1=2⋅precision⋅recallprecision+recall\mathrm{precision} = \frac{|P \cap G|}{|P|}, \quad \mathrm{recall} = \frac{|P \cap G|}{|G|}, \quad F_1 = \frac{2 \cdot \mathrm{precision} \cdot \mathrm{recall}}{\mathrm{precision} + \mathrm{recall}}

For example, if the reference is "gravity" and the prediction is "under gravity," exact match is 0 and F1 is 2/3, from precision 1/2 and recall 1. F1 gives partial credit to predictions whose span is only slightly off.

In SQuAD 2.0, answering "no answer" to an unanswerable question scores 1 on both EM and F1, and answering anything scores 0. The test set is not public, so models are submitted to CodaLab and the authors evaluate them on the test set.

Human performance is measured by treating the second additional answer as the human prediction and the other answers as references. On the test set of the original paper (v1.0), it was 77.0% EM and 86.8% F1. Most disagreements concerned whether to include extra words in the answer span (such as "monsoon trough" vs. "movement of the monsoon trough"), not disagreement on the answer itself.

Training questions have only one reference answer, while dev and test questions have three or more. Because EM and F1 compare against any one of the references, scores are lower when measured on data with only one reference. When comparing scores, match the version (1.1 or 2.0) and whether the dev or test set was used.

Usage and historical significance

SQuAD became the central dataset for training reading comprehension models on large amounts of data and comparing them under the same conditions.

At the time of the original paper, the gap to human performance was large.

MethodEM (test)F1 (test)
Random guess1.34.3
Sliding window12.519.7
Logistic regression (lexical and dependency features)40.451.0
Human77.086.8

Values are in %. All values in the original paper are for v1.0.

Neural network models then improved rapidly. The revised version of the original paper notes that a model with 70.3% F1 (v1.1) appeared within four months of publication. BERT uses fine-tuning to predict the probability that each token in the paragraph is the start or end of the answer, and as a single model reached 85.1 EM and 91.8 F1 on the v1.1 test set (also trained on TriviaQA), surpassing the human EM of 82.3.

While models matching humans on SQuAD 1.1 appeared, the same authors pointed out that these models return plausible guesses even for questions whose answer is not in the paragraph. SQuAD 2.0 was created to address this: a model scoring 85.8 F1 on SQuAD 1.1 (DocQA + ELMo) reached only 66.3 F1 on the SQuAD 2.0 test set (humans: 89.5).

PaperModelVersionEM (test)F1 (test)
Rajpurkar et al. (2018)DocQA + ELMo1.178.685.8
Devlin et al. (2018)BERT-Large (single, also trained on TriviaQA)1.185.191.8
Rajpurkar et al. (2018)Human1.182.391.2
Rajpurkar et al. (2018)DocQA + ELMo2.063.466.3
Devlin et al. (2018)BERT-Large (single)2.080.083.1
Rajpurkar et al. (2018)Human2.086.989.5

Values are in %. Papers on later pretrained models, such as RoBERTa, XLNet, ALBERT, and ELECTRA, also compare SQuAD scores side by side.

SQuAD also served as material for other benchmarks. QNLI in GLUE pairs each SQuAD question with each sentence of its paragraph and recasts the task as binary classification of "whether the sentence contains the answer."

Caveats

License: It is distributed under CC BY-SA 4.0 on the official page. Commercial use is allowed, but attribution is required, and data derived from SQuAD must be distributed under the same license. The source text is Wikipedia paragraphs.

SQuAD 1.1 assumes that every question has an answer in the paragraph. Models trained only on SQuAD 1.1 extract something even for questions without an answer, so using them as-is in a real question answering system returns plausible but wrong answers. For use cases where there may be no answer, train and evaluate on SQuAD 2.0.

Answers are only spans in the paragraph: Because answers are extracted from the paragraph, it can hardly measure reasoning across multiple paragraphs, computed values, or questions answered with words not in the paragraph, such as "yes/no."

A single paragraph is assumed to be given: The paragraph is provided in advance, so the ability to find the document containing the answer is not measured. For question answering over large document collections, the retrieval component is evaluated separately.

Do not mix v1.0 and v1.1 scores: The original paper's results are on v1.0, while v1.1 was widely used afterward. Human performance on the test set also differs: 86.8 F1 for v1.0 and 91.2 for v1.1. Match the version when comparing.

SQuAD 2.0 threshold: The original paper chooses the threshold for deciding "no answer" to maximize F1 on the dev set. The training set has about twice as many answerable questions, while the dev and test sets are roughly half and half, so scores change depending on how the threshold is chosen.

Comparison with similar benchmarks

Representative benchmarks for measuring language understanding and knowledge compare as follows from the same perspective.

BenchmarkQuestion formatWhat it measuresHow it is evaluatedBest suited for
SQuAD 1.1Extract an answer span from a paragraph; about 100,000 questionsReading comprehension (the answer is always in the paragraph)Exact match and F1Comparing extractive reading comprehension models
SQuAD 2.0Adds about 50,000 unanswerable questions to 1.1Reading comprehension and judging unanswerabilityExact match and F1 (abstaining is also scored)Question answering where there may be no answer
GLUESingle- and two-sentence classification in nine tasksSentence understanding (sentiment, paraphrase, inference)Average of per-task scoresComparing fine-tuning of pretrained models
MMLUFour choices across 57 subjectsBroad knowledge and problem-solving abilityFew-shot accuracyComparing the knowledge of large language models

Rough guidelines for choosing:

  • To compare extractive reading comprehension models under the same conditions as pretrained models such as BERT, report EM and F1 on the SQuAD 1.1 dev set.
  • To evaluate under conditions closer to real question answering, including cases with no answer, use SQuAD 2.0.
  • To broadly assess sentence classification ability, use GLUE; to assess the breadth of knowledge of large language models, use MMLU.

PyTorch example

Show code
python
import collections
import re
import string

import torch
from datasets import load_dataset
from transformers import AutoModelForQuestionAnswering, AutoTokenizer

"""
Read the SQuAD v1.1 validation set (dev), predict with a model that extracts answer spans from paragraphs,
and compute exact match (EM) and F1 the same way as the official evaluation script
One question = paragraph (context), question, answers (strings in the paragraph and start positions; dev has several per question)
"""


def normalize_answer(s):
  # lowercase and remove punctuation, articles (a, an, the), and extra whitespace (same as the official script)
  s = ''.join(ch for ch in s.lower() if ch not in set(string.punctuation))
  s = re.sub(r'\b(a|an|the)\b', ' ', s)
  return ' '.join(s.split())


def f1_score(pred, gold):
  p, g = normalize_answer(pred).split(), normalize_answer(gold).split()
  same = sum((collections.Counter(p) & collections.Counter(g)).values())  # number of shared words
  if same == 0:
    return 0.0
  precision, recall = same / len(p), same / len(g)
  return 2 * precision * recall / (precision + recall)


def exact_match(pred, gold):
  return float(normalize_answer(pred) == normalize_answer(gold))


@torch.no_grad()
def predict(model, tok, question, context, max_answer_len=30):
  enc = tok(question, context, truncation='only_second', max_length=384,
            return_offsets_mapping=True, return_tensors='pt')
  offsets = enc.pop('offset_mapping')[0]
  seq_ids = enc.sequence_ids(0)  # 0 = question tokens, 1 = paragraph tokens
  out = model(**enc)
  start, end = out.start_logits[0], out.end_logits[0]
  ctx = [i for i, s in enumerate(seq_ids) if s == 1]
  best, span = -1e9, (0, 0)
  for i in ctx:  # the answer is a span in the paragraph with start <= end, with a length limit
    for j in ctx:
      if i <= j < i + max_answer_len and start[i] + end[j] > best:
        best, span = start[i] + end[j], (i, j)
  return context[offsets[span[0]][0]:offsets[span[1]][1]]


def evaluate(model_name='model-name'):  # an extractive model fine-tuned on SQuAD
  tok = AutoTokenizer.from_pretrained(model_name)
  model = AutoModelForQuestionAnswering.from_pretrained(model_name)
  model.eval()  # evaluation, so disable Dropout
  dev = load_dataset('rajpurkar/squad', split='validation')
  em = f1 = 0.0
  for ex in dev:
    pred = predict(model, tok, ex['question'], ex['context'])
    golds = ex['answers']['text']  # there are several references; take the best-matching one
    em += max(exact_match(pred, g) for g in golds)
    f1 += max(f1_score(pred, g) for g in golds)
  return 100 * em / len(dev), 100 * f1 / len(dev)

FAQ

Q. Should I use SQuAD 1.1 or 2.0?
A.

It depends on your goal. Use 1.1 to compare answer-extraction ability under the same conditions as papers such as BERT, and 2.0 to also evaluate the decision to abstain when the answer is not in the paragraph. Version 2.0 contains all 1.1 questions and uses the same article split, so a model trained on 2.0 can also be evaluated on the 1.1 questions.

Q. How do EM and F1 differ?
A.

EM checks only whether the prediction is exactly the same as a reference, so an answer span off by a single word scores 0. F1 gives partial credit by the proportion of shared words, so it tolerates slight span differences. For example, answering "under gravity" when the reference is "gravity" gives an EM of 0 and an F1 of 2/3. It is customary to report both side by side.

Q. How do I use the test data?
A.

The test set is not public. When you submit your model weights and prediction code to CodaLab, the authors evaluate them on the test set and post the results on the leaderboard. In your own experiments, use dev-set scores, including for hyperparameter tuning, and state clearly in your paper whether scores are from the dev or test set.

References

  1. Rajpurkar, P., Zhang, J., Lopyrev, K., & Liang, P. (2016). SQuAD: 100,000+ Questions for Machine Comprehension of Text. EMNLP 2016.
  2. Rajpurkar, P., Jia, R., & Liang, P. (2018). Know What You Don't Know: Unanswerable Questions for SQuAD. ACL 2018.
  3. SQuAD Explorer (official page and leaderboard).
  4. Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. NAACL 2019.
  5. rajpurkar/squad (Hugging Face dataset card).