QuiddityML

By · 8 November 2026 · 13 min read

Question answering in NLP: extractive vs generative

The difference between copying an answer from a passage and writing one, and how an extractive QA model predicts start and end positions, picks a span and gets scored with exact match and F1, with runnable PyTorch.

Question answering (QA) is the NLP task of returning a readable answer to a question, usually with some text to answer from. A support bot answering from a help page, a search tool pulling one line out of a contract and an assistant answering from a document you uploaded are all doing QA. Language models read text as tokens, which can be whole words or pieces of words, and this post says "word" in a few places to keep the examples simple.

What goes in and what comes out

The input is a question plus evidence. The evidence might be one passage, several passages found by a search step or a table, and some systems get no evidence at all. The output is the answer a person reads.

For example, the question "Who wrote the novel 1984?" with a passage that says "1984 is a novel by George Orwell, published in 1949" should produce the answer "George Orwell".

The question Who wrote the novel 1984? and a passage about George Orwell go into a model, which outputs the answer George Orwell. The answer can be a copied span or written text.

Extractive vs generative QA

There are two common ways to produce that answer.

Extractive QA copies the answer out of the passage. The model points at the first and last token of the answer, and the system returns the text between them. If the passage says "The treaty was signed in Vienna in 1815" and the question is "Where was the treaty signed?", the answer is the span "Vienna" or "in Vienna".

Generative QA writes the answer as new text, one token at a time, the way a chatbot does. It can answer from a passage or from documents a search step found. It can also answer only from what the model learned during training. That makes it more flexible, since the answer does not have to appear word for word anywhere. It also means the answer has to be checked against a source, because the model can write words no source supports.

A second split is about what the model can read. Answering with a passage supplied at question time is called open-book QA. Answering from the question alone, with nothing to consult, is closed-book QA. Extractive QA is open-book by definition, since there has to be a passage to copy from.

Side by side: extractive QA copies the span George Orwell from the passage into the answer box, while generative QA writes George, Orwell and an end token step by step, with a note to check the evidence.

Generative QA runs on the same machinery as any text generation. The rest of this post is about extractive QA, because its mechanics are specific to QA.

Why copy a span?

Extractive QA fits when the answer should come from a specific source. A help center can answer from a policy page, a legal search tool from a contract, and a medical assistant can point to the sentence in a note that supports its answer.

The restriction is the benefit. The model cannot invent wording that is not in the passage, so every answer has a location in the source text, and a person can check it quickly.

The question Who wrote the novel 1984?, the passage with George Orwell highlighted, and the answer George Orwell linked back to its source span.

Copying does not make an answer correct. The model can still point at the wrong span, take too many words or too few, or answer a question the passage never supports. The span head, the rule for picking a span and the metrics below each deal with one of those problems.

How extractive QA is set up

One training example holds a question, a passage and the answer's position in that passage. The answer is stored as two token indices, start_position and end_position.

For the passage "The treaty was signed in Vienna in 1815 ." split into 9 tokens numbered 0 to 8, "Vienna" is token 5. If the labeled answer is "Vienna", the target is start 5 and end 5. If the label is "in Vienna", the target is start 4 and end 5.

The model never outputs answer text directly. It outputs two lists of scores, one start score and one end score for every passage token. These raw scores are called logits: any real number, where a higher logit means the model rates that position more likely. The answer text is recovered after the start and end positions are chosen.

The question Where was the treaty signed? above the passage tokens 0 to 8, with Vienna at position 5. The start logits and end logits rows both peak at position 5 with 0.9.

How it differs from token classification

Extractive QA scores every passage token, so it looks a lot like token classification, the task where every token gets its own label. In named entity recognition, for example, "Jordan works at Nike in Chicago" gets one tag per token: B-PER, O, O, B-ORG, O, B-LOC.

Extractive QA needs only two positions, one start token and one end token. The tokens between them become the answer. The model still reads every token, but its output is two boundary choices instead of a label at every position.

Top: token tags for Jordan works at Nike in Chicago, one tag per token. Bottom: the same tokens with a start marker on Nike and an end marker on Chicago, giving the answer span Nike in Chicago.

The QA head

The question and the passage are joined into one sequence and run through an encoder, a network that reads the sequence and returns one hidden vector per token. A hidden vector is a list of numbers describing that token in its context.

Write $h_t$ for the hidden vector at position $t$. A QA head turns each $h_t$ into two scores. The start score $s_t$ uses a weight vector $w_s$ and a bias $b_s$, and the end score $e_t$ uses its own weights $w_e$ and bias $b_e$:

$$s_t = w_s^T h_t + b_s$$

$$e_t = w_e^T h_t + b_e$$

$w_s^T h_t$ is a dot product: multiply matching entries and add them up. For example, with $h_t = [1, 2]$, $w_s = [0.5, -1]$ and $b_s = 0.3$, the start score is $0.5 \cdot 1 + (-1) \cdot 2 + 0.3 = -1.2$:

1import torch
2 
3h_t = torch.tensor([1.0, 2.0])    # hidden vector for one passage token
4w_s = torch.tensor([0.5, -1.0])   # start weights
5b_s = 0.3                         # start bias
6 
7s_t = w_s @ h_t + b_s
8print(round(s_t.item(), 2))
1-1.2

The same weights are applied at every position, so the head produces one start score and one end score per token. In code, one linear layer with two outputs does both at once.

Token hidden states h1 to h4 feed one linear QA head, which outputs start logits -1.2, 0.3, 1.1, 2.7 and end logits -0.7, 1.6, -0.1, 2.3, with position 4 highest in both.

A small extractive QA model in PyTorch

The model needs an embedding layer, a recurrent network (RNN) and the linear head. The embedding layer turns each token id into a vector. The RNN reads the vectors in order and keeps one hidden state per token, and the head maps each hidden state to two logits.

1import torch
2import torch.nn as nn
3 
4 
5class ExtractiveQARNN(nn.Module):
6    def __init__(self, vocab_size, emb_dim, hidden_size, pad_id=0):
7        super().__init__()
8        self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=pad_id)
9        self.rnn = nn.RNN(emb_dim, hidden_size, batch_first=True)
10        self.qa_head = nn.Linear(hidden_size, 2)
11 
12    def forward(self, input_ids):
13        x = self.emb(input_ids)
14        output, hn = self.rnn(x)
15        logits = self.qa_head(output)        # (batch, seq_len, 2)
16        start_logits = logits[:, :, 0]       # (batch, seq_len)
17        end_logits = logits[:, :, 1]         # (batch, seq_len)
18        return start_logits, end_logits
19 
20 
21torch.manual_seed(0)
22model = ExtractiveQARNN(vocab_size=1000, emb_dim=32, hidden_size=64)
23input_ids = torch.randint(1, 1000, (2, 12))   # 2 question-passage sequences, 12 tokens each
24start_logits, end_logits = model(input_ids)
25print(start_logits.shape, end_logits.shape)
1torch.Size([2, 12]) torch.Size([2, 12])

The shape change happens at the head. output has shape (batch, seq_len, hidden_size), here (2, 12, 64), and self.qa_head(output) has shape (2, 12, 2). Splitting the last dimension gives start_logits and end_logits, each with one score per token.

Input ids of shape B x T go through an embedding (B x T x E) and an RNN encoder (B x T x H). A linear QA head outputs B x T x 2, which splits into start logits and end logits, each B x T.

Training with two cross-entropy losses

Cross-entropy is the loss used for picking one class out of several: it is small when the model gives the correct class a high score compared with the others. In extractive QA the classes are token positions. A sequence with 200 token positions gives the start prediction 200 choices and the end prediction 200 choices.

The start logits are trained against the correct start index and the end logits against the correct end index, and the two losses are averaged:

$$L = \frac{CE(s, y_{start}) + CE(e, y_{end})}{2}$$

Here $s$ and $e$ are the start and end logits, and $y_{start}$ and $y_{end}$ are the labeled positions.

1import torch
2import torch.nn.functional as F
3 
4torch.manual_seed(0)
5start_logits = torch.randn(2, 12)   # 2 examples, 12 token positions
6end_logits = torch.randn(2, 12)
7start_positions = torch.tensor([3, 7])
8end_positions = torch.tensor([5, 7])
9 
10start_loss = F.cross_entropy(start_logits, start_positions)
11end_loss = F.cross_entropy(end_logits, end_positions)
12loss = (start_loss + end_loss) / 2
13print(round(start_loss.item(), 3), round(end_loss.item(), 3), round(loss.item(), 3))
13.118 3.662 3.39

The logits here are random, so both losses sit above $\ln 12 \approx 2.48$, the loss of a model that gives all 12 positions the same score. Training pushes the score at each labeled position up and the other scores down, and the loss falls.

A B x T start logits table and the gold start index 3 feed a start cross-entropy, a B x T end logits table and the gold end index 5 feed an end cross-entropy, and the two scalars are averaged into one loss.

Masking the question and the padding

The model reads the question and the passage as one sequence, so the question tokens get start and end scores too. They help the model decide what to look for, but they should never be returned as the answer. Padding tokens, the filler tokens added so every sequence in a batch has the same length, should not be returned either.

The usual fix sets the logits of every position outside the passage to $-\infty$ before picking a span, so those positions can never win. Without that mask the code still runs and returns a span from the wrong part of the input, which looks like a normal answer.

The question tokens and padding tokens are marked not eligible and their start and end logits are pushed down below the line, while the passage tokens stay eligible.

Turning logits into a span

The simplest rule takes the highest start logit and the highest end logit separately. The two can disagree: the best end might come before the best start, or the pair might cover half the passage. A better rule scores every start and end pair $(i, j)$ together:

$$score(i, j) = s_i + e_j$$

It keeps only pairs where $i \le j$, both positions are in the passage and the span is not too long, then returns the valid pair with the highest score.

The code below runs that search on the question "What does the fox jump over?" joined to the passage "The quick brown fox jumps over the lazy dog .", with logits written by hand. One question token, "What", has the highest start logit of all, 2.9.

1import torch
2 
3tokens = ["[CLS]", "What", "does", "the", "fox", "jump", "over", "?", "[SEP]",
4          "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog", ".", "[SEP]"]
5# passage tokens sit between the first [SEP] (position 8) and the last one
6passage_mask = torch.zeros(len(tokens), dtype=torch.bool)
7passage_mask[9:19] = True
8 
9start_logits = torch.tensor([0.5, 2.9, 0.3, 0.2, 1.9, 0.4, 0.1, 0.0, 0.0,
10                             0.2, 0.1, 0.3, 0.6, 0.2, 0.4, 2.4, 1.1, 0.3, 0.0, 0.0])
11end_logits = torch.tensor([0.4, 0.2, 0.1, 0.3, 2.2, 0.1, 0.3, 0.0, 0.0,
12                           0.1, 0.2, 0.4, 0.9, 0.3, 0.1, 0.2, 0.8, 2.6, 0.5, 0.0])
13 
14 
15def best_span(start_logits, end_logits, max_len=4):
16    """Highest start + end score over spans with start <= end and at most max_len tokens."""
17    best, best_score = None, float("-inf")
18    for i in range(len(start_logits)):
19        for j in range(i, min(i + max_len, len(end_logits))):
20            score = start_logits[i] + end_logits[j]
21            if score > best_score:
22                best, best_score = (i, j), score
23    return best, best_score
24 
25 
26(i, j), score = best_span(start_logits, end_logits)
27print("no mask:  ", " ".join(tokens[i:j + 1]), round(score.item(), 2))
28 
29start_logits = start_logits.masked_fill(~passage_mask, float("-inf"))
30end_logits = end_logits.masked_fill(~passage_mask, float("-inf"))
31(i, j), score = best_span(start_logits, end_logits)
32print("with mask:", " ".join(tokens[i:j + 1]), round(score.item(), 2))
1no mask:   What does the fox 5.1
2with mask: the lazy dog 5.0

Without the mask the search copies part of the question back as the answer. With it, the answer is "the lazy dog". [CLS] and [SEP] are special tokens the tokenizer adds at the start, between the two texts and at the end.

The grid below shows the same search on the passage alone, numbered 0 to 9. Pairs where the end comes before the start are ruled out, and so are spans longer than 4 tokens. The best valid pair is start 6 and end 8.

A grid of start positions against end positions for the passage The quick brown fox jumps over the lazy dog. Cells with the end before the start and spans longer than 4 tokens are ruled out, and the best cell is start 6, end 8, giving the answer the lazy dog.

When the passage has no answer

Some questions have no answer in the passage. A model that always returns a span will still copy something, and that wrong answer comes with a location in the source, so it looks trustworthy.

One way to let the model abstain is a no-answer score. A common version uses the [CLS] position at the start of the sequence: $s_0 + e_0$ is the score for "no answer". At inference, the best valid span score is compared with it, and the system answers only when the span wins by more than a threshold $\tau$. The training data needs unanswerable examples, labeled with [CLS] as their start and end, so the model learns to raise that score when the passage does not support the question.

1import torch
2 
3start_logits = torch.tensor([3.1, 0.2, 0.4, 1.0, 0.3])   # position 0 is [CLS]
4end_logits = torch.tensor([2.8, 0.1, 0.9, 0.6, 0.2])
5passage_mask = torch.tensor([False, True, True, True, True])
6 
7score_null = start_logits[0] + end_logits[0]             # read before masking
8start_logits = start_logits.masked_fill(~passage_mask, float("-inf"))
9end_logits = end_logits.masked_fill(~passage_mask, float("-inf"))
10 
11best_span_score = max(start_logits[i] + end_logits[j]
12                      for i in range(5) for j in range(i, 5))
13tau = 0.0
14answer = "span" if best_span_score - score_null > tau else None
15print(round(score_null.item(), 2), round(best_span_score.item(), 2), answer)
15.9 1.6 None

The no-answer score has to be read before masking, because the mask sets the [CLS] position to $-\infty$. Here no answer scores 5.9 against 1.6 for the best span, so the system returns nothing. Raising $\tau$ makes the system answer less often.

An answerable question about Pride and Prejudice where the best span scores 2.31 against 0.42 for no answer, and an unanswerable question about the theory of relativity where the best span scores 0.28 against 1.67, so the system chooses no answer.

Extractive QA with a Hugging Face pipeline

The Hugging Face transformers library wraps all of these steps in one call. A question-answering pipeline tokenizes the question and the context, runs a model that already has a QA head, picks a span and converts its token positions back to character positions in the context.

1from transformers import pipeline
2 
3qa = pipeline(
4    "question-answering",
5    model="distilbert-base-cased-distilled-squad",
6)
7 
8context = "The treaty was signed in Vienna in 1815."
9result = qa(question="Where was the treaty signed?", context=context)
10 
11print(result["answer"])                           # the copied span
12print(context[result["start"]:result["end"]])     # the same text, cut out by character offsets
13print(result["score"])                            # the model's confidence in that span

result["start"] and result["end"] are character offsets into the context, and the end is exclusive, the same as Python slicing. For "Vienna" in this context they are 25 and 31:

1context = "The treaty was signed in Vienna in 1815."
2start = context.index("Vienna")
3end = start + len("Vienna")
4print(start, end, context[start:end])
125 31 Vienna

The pipeline in four steps: the question and context, the tokenizer turning [CLS], Where, was, the, treaty into ids 101, 2777, 1108, 1103, 7274, the encoder producing start and end logits, and the answer Vienna with start 25 and end 31, end exclusive.

Evaluating extractive QA: exact match and F1

Two metrics are common for extractive QA.

Exact match (EM) checks whether the predicted answer string equals the labeled answer after light normalization, such as lowercasing and removing punctuation. A match scores 1 and anything else scores 0. It is hard to game with almost-right spans, and it is harsh, because one extra word wipes out the score.

A table with the gold answer Vienna: the prediction Vienna scores 1, while in Vienna and in 1815 both score 0.

Token F1 gives partial credit. It compares the predicted tokens with the labeled tokens. Precision is the share of predicted tokens that appear in the labeled answer, and recall is the share of labeled tokens the prediction recovered. With $p$ for precision and $r$ for recall:

$$F1 = \frac{2pr}{p + r}$$

For the gold answer "Vienna" and the prediction "in Vienna", one token is shared. Precision is $1/2$, recall is $1/1$, and F1 is $2 \cdot 0.5 \cdot 1/(0.5 + 1) \approx 0.67$.

1from collections import Counter
2 
3 
4def exact_match(pred, gold):
5    return int(pred.strip().lower() == gold.strip().lower())
6 
7 
8def token_f1(pred, gold):
9    pred_tokens, gold_tokens = pred.lower().split(), gold.lower().split()
10    shared = sum((Counter(pred_tokens) & Counter(gold_tokens)).values())
11    if shared == 0:
12        return 0.0
13    precision = shared / len(pred_tokens)
14    recall = shared / len(gold_tokens)
15    return 2 * precision * recall / (precision + recall)
16 
17 
18for pred in ["Vienna", "in Vienna", "in 1815"]:
19    print(f"{pred:10} EM={exact_match(pred, 'Vienna')}  F1={token_f1(pred, 'Vienna'):.2f}")
1Vienna     EM=1  F1=1.00
2in Vienna  EM=0  F1=0.67
3in 1815    EM=0  F1=0.00

Reporting both is the usual practice. EM says how often the span is exactly right, and F1 says how often the model at least found the right words. Over a test set, each number is the average over all questions.

Token F1 for the gold answer Vienna and the prediction in Vienna: precision 1/2 = 0.50, recall 1/1 = 1.00, F1 = 0.67.

Extractive QA in seven questions

A useful way to describe an NLP task is to answer seven questions about it. The first four are the input, the target, the prediction and the data. The last three are training, inference and evaluation. The post on NLP tasks walks through that checklist, and for extractive QA the answers are the pieces above.

The QA checklist: input is a question plus passage, target is start and end, prediction is two score vectors, data is labeled spans, training raises the gold positions, inference copies the best span, and evaluation uses EM and F1.

When to use extractive QA, and common mistakes

Extractive QA is a good fit when the answer is a short piece of a document you already have and someone needs to see where it came from. Examples are support answers from a policy page, facts pulled from contracts and a search box over internal documentation. Generative QA is the better fit when the answer has to combine facts from several places, rephrase them, or be longer than a phrase.

Mistakes that come up often:

Token classification, covered in named entity recognition and part-of-speech tagging, labels every token. Extractive QA runs a similar head over the same token states but predicts only two positions. Retrieval finds which passages to read in the first place, and it is explained in retrieval and text ranking. A search step that feeds its top passages into a QA model is how many document question-answering systems are built. Text classification, explained in text classification explained, returns one label for a whole text instead of a span.

QuiddityML teaches extractive question answering as its own concept in the Intro to NLP track, and the exercises on it include turning the two-loss equation into code, filling in the RNN model with its two-output head and tracing the shapes from the head's output to start and end logits.