Sub topic 6
Start and end logits: the span prediction head
This chapter assumes you know basic PyTorch (tensors, nn.Linear, softmax, cross-entropy) and that you have seen how a question and context are encoded as one sentence pair. Here we open the last layer of a question-answering model. We look at what it computes, how it is trained, and why decoding needs more than two argmax calls.
From hidden states to two scores per token
A transformer encoder turns a sequence of seq tokens into a tensor of hidden states with shape (batch, seq, hidden). Each token has one vector that already reflects the question, the context, and the tokens around it.
The span prediction head is a single linear layer that maps each hidden vector to two numbers:
- A start logit: how strongly this token looks like the first token of the answer.
- An end logit: how strongly this token looks like the last token of the answer.
A logit is a raw, unnormalized score. It can be negative or larger than 1, and it is not a probability. The same weights are applied to every position, so the head is a per-token classifier with two output channels. Because every token has already attended to the question, the head can tell whether a context token is relevant without seeing the question directly.
The head in code
Hugging Face models for this task name the layer qa_outputs. The following module reproduces it.
import torch
from torch import nn
class SpanHead(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.qa_outputs = nn.Linear(hidden_size, 2)
def forward(self, hidden_states):
logits = self.qa_outputs(hidden_states) # (batch, seq, 2)
start_logits, end_logits = logits.split(1, dim=-1) # two (batch, seq, 1)
return start_logits.squeeze(-1), end_logits.squeeze(-1)
torch.manual_seed(0)
batch, seq, hidden = 2, 8, 16
hidden_states = torch.randn(batch, seq, hidden)
head = SpanHead(hidden)
start_logits, end_logits = head(hidden_states)
print(start_logits.shape, end_logits.shape) # torch.Size([2, 8]) torch.Size([2, 8])The head has hidden * 2 + 2 parameters. For a 768-dimensional encoder that is 1,538 parameters, a tiny layer on top of tens of millions of encoder parameters. Nearly all the reading ability lives in the encoder. Fine-tuning mostly teaches the encoder to arrange its hidden states so that a linear read-out can find answer boundaries.
You can confirm the shapes on a real model:
import torch
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
name = "distilbert-base-cased-distilled-squad"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForQuestionAnswering.from_pretrained(name)
print(model.qa_outputs) # Linear(in_features=768, out_features=2, bias=True)
inputs = tokenizer("Who wrote it?", "It was written by Ada.", return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
print(inputs["input_ids"].shape) # (1, number_of_tokens)
print(outputs.start_logits.shape) # same shape: one score per token
print(outputs.end_logits.shape)The logits have the same length as the input. Position i in the logits is token i in input_ids, and that correspondence is what lets offset mappings turn a position into characters later.
Softmax goes across positions
To read the logits as probabilities, apply softmax over the sequence dimension, separately for start and for end:
start_probs = torch.softmax(start_logits, dim=-1) # sums to 1 over the seq positions
end_probs = torch.softmax(end_logits, dim=-1)
print(start_probs.sum(dim=-1)) # tensor([1., 1.])The model is asking "which one of these seq positions is the start?", which is a classification problem with seq classes. It is not asking "is this token a start, yes or no?" for each token. Softmax over dim=1 of the (batch, seq, 2) tensor, which would normalize start against end within a token, is a common bug and produces meaningless numbers.
Training: two cross-entropy problems
Each training example carries a start index and an end index into the token sequence. The loss treats these as two classification targets and averages them:
loss_fn = nn.CrossEntropyLoss()
start_positions = torch.tensor([3, 0])
end_positions = torch.tensor([5, 0])
loss = (loss_fn(start_logits, start_positions) +
loss_fn(end_logits, end_positions)) / 2
print(loss.item())CrossEntropyLoss accepts logits of shape (batch, seq) and integer targets of shape (batch,), so the sequence positions act as classes. The second example above uses position 0. In BERT-style models this is the [CLS] token, and the convention is to point both labels there when the answer is not in the window. The chapters on unanswerable questions and label alignment cover this in detail.
The two losses are independent. Nothing in training forces the predicted start to be before the predicted end. The model only learns two separate distributions, so ordering must be enforced when decoding.
Why decoding needs a joint search
The simplest decoder takes argmax of the start logits and argmax of the end logits. Because the two heads are scored independently, this can produce an invalid span:
import torch
start = torch.tensor([0.0, 0.5, 0.0, 0.2, 3.0])
end = torch.tensor([0.1, 2.5, 0.3, 0.2, 1.0])
print(start.argmax().item(), end.argmax().item()) # 4 1 -> the end is before the startThe fix is to score every (start, end) pair as start[i] + end[j] and keep only pairs that obey two constraints:
i <= j, so the span is not backwards.j - i < max_answer_len, so the span is not absurdly long.
Adding logits is equivalent to multiplying the two softmax probabilities, because the softmax denominators are constants for a given example and do not change which pair wins. This vectorized version does the search with a mask:
import torch
def best_span(start, end, max_answer_len=30):
n = start.shape[0]
scores = start[:, None] + end[None, :] # scores[i, j] = start[i] + end[j]
ones = torch.ones(n, n, dtype=torch.bool)
valid = torch.triu(ones) & torch.tril(ones, diagonal=max_answer_len - 1)
scores = scores.masked_fill(~valid, float("-inf"))
flat = scores.argmax().item()
i, j = divmod(flat, n)
return i, j, scores[i, j].item()
start = torch.tensor([0.0, 0.5, 0.0, 0.2, 3.0])
end = torch.tensor([0.1, 2.5, 0.3, 0.2, 1.0])
print(best_span(start, end)) # (4, 4, 4.0)
print(best_span(start, end, max_answer_len=1)) # (4, 4, 4.0): single-token answers onlytriu keeps pairs where j >= i. tril with diagonal=max_answer_len - 1 keeps pairs where j - i <= max_answer_len - 1. Together they leave a band along the diagonal.
This search is O(seq²), which is cheap for 384 tokens. The topk shortcut used in the earlier decoding example does the same job with fewer candidates, and it assumes the best span uses a top-scoring start and a top-scoring end.
Masks that the head does not apply for you
The head scores every position, including positions that can never be answers. Three groups need masking before the search:
| Positions | Why they must be excluded |
|---|---|
| Question tokens | The answer must be copied from the context. |
| Padding tokens | They carry no content, but they still receive logits. |
| Special tokens such as `[SEP]` | They are not part of the context text, and their offsets are `(0, 0)`. |
The sequence_ids method of a fast tokenizer marks context tokens with 1, so s != 1 selects everything that must be masked. Set masked logits to a large negative number such as -1e9, or to -inf, not to zero. Zero is a plausible logit and would let a masked position win.
The exception is the [CLS] position. When you want a null answer, you keep it and compare its score against the best span. That comparison is the subject of a later chapter.
Common errors
- Softmax over the wrong dimension. Normalize over the sequence axis for start and end separately.
- Forgetting the mask. The best span is sometimes inside the question, and the offsets then point to the wrong text.
- Skipping the
start <= endcheck. The result is an empty or reversed slice of the context string. - No length cap. An unconstrained search can select a span of hundreds of tokens, because adding two high logits far apart still beats a short, correct span with moderate logits.
- Treating the sum of logits as a confidence. The sum is only a ranking score. The pipeline's
scorefield uses probabilities, and these are not calibrated: a high score does not mean a correct answer. - Mixing token and character positions. The head outputs token positions. Only the offset mapping converts them to character positions.
Exercise
A batch of logits start_logits and end_logits has shape (4, 384), and a window's token 0 is [CLS]. A teammate computes torch.softmax(logits, dim=-1) on the raw (4, 384, 2) output tensor and treats the result as start probabilities. What is wrong, and what should they do instead?
Show answer
Softmax over the last dimension of the (4, 384, 2) tensor normalizes the start score against the end score within each token, so every token gets "probabilities" that sum to 1 across only two channels. These say nothing about which token is the start. They should split the two channels into start and end logits, each of shape (4, 384), and apply softmax over the sequence dimension (dim=-1 of the 2D tensors) separately for each. Each row then sums to 1 across the 384 positions.
Exercise
In best_span, the answer is always (4, 4) for the toy logits. Change the logits so that the best valid span is (1, 2) with max_answer_len=3, and explain which constraint decides the result if you also set start[4] very high and end[0] very high.
Show answer
Example: start = [0.0, 3.0, 0.0, 0.0, 0.0] and end = [0.0, 0.0, 3.0, 0.0, 0.0] give (1, 2) with score 6.0. If start[4] and end[0] are also very high, the pair (4, 0) has the largest raw sum but is removed by the i <= j constraint (the triu mask). The pair (4, 4) is valid and is then compared against (1, 2). The ordering constraint, not the length cap, rules out the backwards pair.