Sub topic 2
Start and end logits: the span prediction head
This chapter assumes you know basic Python, have used PyTorch tensors, and understand that a transformer encoder turns tokens into vectors. You also know that a tokenizer splits text into subword tokens and can return character offsets for each token.
The span prediction head
The encoder produces one vector per token. A small linear layer, the span prediction head, maps each vector to two numbers: a start logit and an end logit. A logit is a raw, unnormalized score. Higher means more likely. The start logit scores how likely a token is to begin the answer, and the end logit scores how likely it is to finish the answer.
Because the head outputs one start score and one end score per token, the model never generates text. It only points to a span in the input.
Your first answer with the pipeline
The pipeline function wraps tokenization, the model, and decoding in one call.
from transformers import pipeline
name = "distilbert-base-cased-distilled-squad"
qa = pipeline("question-answering", model=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."
)
result = qa(question=question, context=context)
print(result["answer"], result["score"])The result holds the answer text, its character positions, and a confidence score between 0 and 1.
Turning logits into an answer string
The pipeline hides the decoding step. You can do it yourself. Mask out tokens that are not part of the context, then search for the valid start and end pair with the highest combined score. A valid pair has start at or before end, and a short length.
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."
)
inputs = tokenizer(question, context, return_tensors="pt",
return_offsets_mapping=True, truncation="only_second", max_length=384)
offsets = inputs.pop("offset_mapping")[0].tolist()
sequence_ids = inputs.sequence_ids(0)
with torch.no_grad():
out = model(**inputs)
not_context = torch.tensor([s != 1 for s in sequence_ids])
start = out.start_logits[0].masked_fill(not_context, -1e9)
end = out.end_logits[0].masked_fill(not_context, -1e9)
best_score, best_s, best_e = -1e18, 0, 0
for s in range(len(start)):
for e in range(s, min(s + 30, len(end))):
score = start[s].item() + end[e].item()
if score > best_score:
best_score, best_s, best_e = score, s, e
# Offsets map token positions back to character positions in the original context.
print(context[offsets[best_s][0]:offsets[best_e][1]])Common errors:
- Forgetting the mask, so the answer can include question tokens.
- Slicing the context with token indices instead of offsets, which gives wrong text.
- Allowing end before start.
Exercise
Why does the decoding code use offsets instead of the token indices when it slices the context?
Show answer
Token indices refer to positions in the model input, not characters in the original context. The offset mapping gives each token's character start and end, so the slice recovers the exact answer text.