Sub topic 8
Turning Logits into an Answer String
This chapter assumes that you know basic Python, have seen tokenization, and understand that a transformer produces tensors of numbers. The goal is to turn a question-answering model's token scores into text copied from the context.
From token scores to a span
An extractive question-answering model does not generate new words. It selects a continuous span from the context. The model produces two scores, called logits, for every input token:
- A start logit estimates how likely a token is to begin the answer.
- An end logit estimates how likely a token is to finish the answer.
A logit is an unnormalized score. Larger values indicate stronger preferences, but the values are not probabilities. To score a possible answer, add its start and end logits:
span_score = start_logit[start] + end_logit[end]The decoder must also enforce basic rules:
- Both tokens must belong to the context, not the question or special tokens.
- The start position must be before or equal to the end position.
- The answer should not exceed a reasonable maximum length.
Character offsets recover the original text
Token positions do not always match character positions. A tokenizer may split a word into subword tokens, so token 12 does not mean character 12. With return_offsets_mapping=True, each token receives a pair such as (45, 52). This pair identifies the character range in the original input.
After selecting token positions s and e, extract:
answer = context[offsets[s][0]:offsets[e][1]]The end offset is exclusive, so this slice includes all characters through the end of token e.
The sequence_ids method identifies where each token came from. For a question-context pair, sequence ID 0 usually marks question tokens and sequence ID 1 marks context tokens. Special tokens have no sequence ID.
Decode a span by hand
The following example loads a model fine-tuned on SQuAD. It masks every non-context token, searches candidate start and end positions, and uses offsets to recover the answer.
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():
outputs = model(**inputs)
not_context = torch.tensor(
[sequence_id != 1 for sequence_id in sequence_ids],
dtype=torch.bool,
)
start_logits = outputs.start_logits[0].masked_fill(not_context, -1e9)
end_logits = outputs.end_logits[0].masked_fill(not_context, -1e9)
best_score = float("-inf")
best_span = None
start_ids = start_logits.topk(20).indices.tolist()
end_ids = end_logits.topk(20).indices.tolist()
for start in start_ids:
for end in end_ids:
if start <= end and end - start < 30:
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 decoder searches only the top candidate starts and ends instead of testing every pair. It still checks every combination among those candidates, rejects reversed spans, and limits answer length.
Common decoding errors
A decoder can fail even when the model's logits look reasonable:
- It may select a question token if sequence IDs are not used.
- It may produce an answer with reversed boundaries.
- It may cut a word incorrectly if offsets are ignored.
- It may select a long, low-quality span when no maximum length is applied.
- It may choose a plausible span from the wrong part of a long context.
For long contexts, decode each overlapping window separately and compare their span scores. The highest-scoring valid span across all windows becomes the final answer.
Exercise
Why does the decoder need offset mappings instead of using token positions as character positions?
Show answer
Subword tokenization means token indices and character indices refer to different coordinate systems. Offset mappings connect each selected token to its character range in the original context.