Sub topic 6
Start and End Logits: the Span Prediction Head
This chapter assumes that you know basic Python, tokenization, and the idea of a pretrained transformer encoder. You will work with PyTorch tensors and a SQuAD-style extractive question-answering model.
From encoded text to answer spans
An extractive question-answering model does not generate new words. It selects a continuous span from the context. For example, given this context:
The Amazon River has the largest drainage basin in the world.the answer might be the largest drainage basin in the world.
After tokenization, the model receives the question and context as one sequence. A pretrained transformer produces one hidden vector for every input token. A span prediction head reads these vectors and produces two scores for each token:
- A start logit estimates how likely the token is the first token of the answer.
- An end logit estimates how likely the token is the last token of the answer.
A logit is an unnormalized score. Larger values indicate stronger evidence, but logits are not probabilities until they are normalized.
How the span head works
The simplest span head applies a linear layer to each hidden vector and returns two numbers. One number belongs to the start position, and the other belongs to the end position.
For a sequence of length n, the output shapes are usually:
| Output | Shape | Meaning |
|---|---|---|
| Start logits | `(batch_size, n)` | Score for each possible start token |
| End logits | `(batch_size, n)` | Score for each possible end token |
During training, the dataset supplies a correct start index and end index. The model uses a separate cross-entropy loss for each prediction:
total loss = start loss + end lossThe two predictions are learned separately, but decoding must combine them. A valid answer requires the end position to be at or after the start position.
Decoding the best span
A basic decoder chooses the highest-scoring start and end positions independently. This can produce an invalid span, such as an end before the start. A better decoder considers candidate pairs and maximizes:
span score = start_logit[start] + end_logit[end]subject to constraints such as:
- Both positions belong to the context, not the question or special tokens.
start <= end.- The span does not exceed a chosen maximum length.
The following example performs this process and uses offset mappings to recover the original characters:
import torch
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
name = "distilbert-base-cased-distilled-squad"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForQuestionAnswering.from_pretrained(name)
question = "What does the Amazon basin cover?"
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."
)
encoded = tokenizer(
question,
context,
return_tensors="pt",
return_offsets_mapping=True,
truncation="only_second",
max_length=384,
)
offsets = encoded.pop("offset_mapping")[0].tolist()
sequence_ids = encoded.sequence_ids(0)
with torch.no_grad():
output = model(**encoded)
is_context = torch.tensor([item == 1 for item in sequence_ids])
start_logits = output.start_logits[0].masked_fill(~is_context, -1e9)
end_logits = output.end_logits[0].masked_fill(~is_context, -1e9)
best_score = float("-inf")
best_span = (0, 0)
for start in range(len(start_logits)):
for end in range(start, min(start + 30, len(end_logits))):
score = (start_logits[start] + end_logits[end]).item()
if score > best_score:
best_score = score
best_span = (start, end)
start, end = best_span
answer = context[offsets[start][0]:offsets[end][1]]
print(answer)The offset mapping connects each token to its character interval in the original context. Without it, joining subword tokens can produce spacing and punctuation errors.
Common errors
A decoder can fail when it includes question tokens, special tokens, or padding as answer candidates. It can also select an answer that is too long or crosses an unrelated sentence. Masking non-context tokens and applying a span-length limit reduce these errors.
Exercise
If a candidate has a start logit of 4.2 and an end logit of 1.8, while another candidate has logits 3.5 and 3.0, which candidate has the higher combined span score?
Show answer
The first candidate scores 6.0. The second scores 6.5, so the second candidate is preferred if both spans are valid.