Sub topic 8
Turning logits into an answer string
This chapter covers the step between the model's raw output and the text a user reads. It assumes you can run a Hugging Face model in PyTorch and know what a tokenizer does. You should also know that the question and the context are encoded together as one sequence, as covered in the previous chapters.
What the model gives you
A question-answering model does not return text. For an input of N tokens it returns two vectors of N numbers each:
start_logits[i]is the score for the answer beginning at tokeni.end_logits[i]is the score for the answer ending at tokeni.
A logit is an unnormalized score. A higher value means the model considers that position more likely. Logits can be negative, and they do not sum to one.
Decoding has to answer three questions:
- Which token positions are allowed to be part of an answer?
- Which (start, end) pair is best?
- Which characters of the original context does that pair correspond to?
Step 1: Mask everything that is not context
The model sees [CLS] question [SEP] context [SEP]. It produces logits for every position, including the question tokens and the special tokens. An answer must come from the context, so the other positions have to be excluded.
The fast tokenizer's sequence_ids() method tells you which part each token belongs to. It returns None for special tokens, 0 for question tokens and 1 for context tokens. Setting the logits of every position that is not 1 to a very large negative number keeps those positions out of the search.
This is not cosmetic. The offset mapping of a question token points into the question string, not the context. If a question token won, you would slice the context at the wrong characters and get plausible-looking nonsense.
Step 2: Search for the best span
The obvious approach is argmax on the start logits and argmax on the end logits. It fails because the two choices are made independently. The best start may sit after the best end, and the span may be hundreds of tokens long.
Instead, score pairs. The score of a span is start_logits[s] + end_logits[e]. Adding logits is the same as multiplying the two probabilities, because a softmax is an exponential of the logit divided by a constant. Checking every pair costs N² operations, so the usual shortcut is to take only the top n start candidates and the top n end candidates (n is often 20) and test those n² pairs. Each pair must satisfy two constraints:
s <= e, so the span is not backwards.e - s < max_answer_len, so the span is not unreasonably long. Thirty tokens is a common limit for SQuAD-style data.
Step 3: Map tokens back to characters
Subword tokenization breaks words into pieces, and the tokenizer may normalize text. You cannot decode token ids back to a string and expect the original text, because spacing and casing can change. The offset mapping avoids this. For each token it gives (char_start, char_end) in the original input string. The answer is then the slice from the first character of the start token to the last character of the end token.
A complete decoder
The function below does all three steps and also returns a confidence value and the character positions. It reuses the model from the earlier pipeline example.
import torch
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
name = "distilbert-base-cased-distilled-squad"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForQuestionAnswering.from_pretrained(name)
model.eval()
def answer(question, context, n_best=20, max_answer_len=30):
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)
# Positions that are not context tokens may never be part of the answer.
not_context = torch.tensor([s != 1 for s in sequence_ids])
start_logits = outputs.start_logits[0].masked_fill(not_context, -1e9)
end_logits = outputs.end_logits[0].masked_fill(not_context, -1e9)
# Probabilities over context tokens only.
start_probs = torch.softmax(start_logits, dim=0)
end_probs = torch.softmax(end_logits, dim=0)
best = None
for s in start_logits.topk(n_best).indices.tolist():
for e in end_logits.topk(n_best).indices.tolist():
if sequence_ids[s] != 1 or sequence_ids[e] != 1:
continue
if s > e or e - s >= max_answer_len:
continue
score = (start_logits[s] + end_logits[e]).item()
if best is None or score > best["logit_score"]:
best = {
"logit_score": score,
"prob": (start_probs[s] * end_probs[e]).item(),
"start": offsets[s][0],
"end": offsets[e][1],
}
if best is None:
return None
best["answer"] = context[best["start"]:best["end"]]
return best
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."
)
print(answer("What does the Amazon basin cover?", context))The returned dictionary has the same shape as the pipeline's output: the answer text, character start and end, and a score. The prob value is the product of the softmax probabilities of the chosen start and end. Because the softmax is computed over context tokens only, it is easier to interpret than the raw logit sum. It is still not a calibrated probability that the answer is correct.
The function returns None when no valid span exists. That can happen if the context is empty or every candidate fails the constraints. Handle that case in calling code instead of assuming a string.
Why the details matter
| Choice | What goes wrong if you skip it | What you see |
|---|---|---|
| Mask question and special tokens | A question token wins the search and its offsets point into the question | Answers that are random fragments of the context |
| Require `start <= end` | The best end comes before the best start | An empty or reversed slice |
| Limit answer length | Start and end each pick a strong but distant token | A span covering a whole paragraph |
| Use offsets, not `decode` | Lowercasing, spacing and unknown tokens alter the text | An answer that is not a substring of the context |
| Compare logit sums, not separate argmax values | Each end is chosen without regard to its start | A pair that is individually likely but jointly unlikely |
Two further points come up often.
- Offsets are half-open.
offsets[e][1]is the index one past the last character of the end token, socontext[start:end]is correct without adding one. - Logit scores are not comparable across inputs. A sum of 12 on one question and 9 on another does not mean the first answer is better. Scores are only meaningful for ranking candidates within a single question and context. The same limit applies to windows of a long document, which a later chapter handles with a shared scoring rule.
Checking your decoder against the pipeline
The pipeline("question-answering") call in the earlier chapter does this same work internally, with additional handling for long inputs. For a short context that fits in one window, your function and the pipeline should agree on the answer text and positions. When they disagree, check these in order:
- Is the mask applied to both start and end logits?
- Are you using the same
max_answer_lenandn_bestas the pipeline? Its defaults are 15 for the maximum answer length in tokens and 20 for the number of candidates considered, and a smaller limit can cut off a legitimately long answer. - Is
truncation="only_second"set, so a long context is cut and not the question?
A useful habit is to print the top five candidate spans with their scores. Often the model's second choice is the correct answer with a slightly different boundary, such as including or excluding a unit word. Seeing this tells you the model is uncertain about the boundary, which is a different problem from not finding the answer at all.
Exercise
Suppose you replace the pair search with s = start_logits.argmax() and e = end_logits.argmax() and slice context[offsets[s][0]:offsets[e][1]]. Name two distinct ways this can return a wrong or invalid result, even when the model is accurate.
Show answer
First, the start and end are chosen independently, so s can be greater than e. The slice is then empty or reversed. Second, without masking, the argmax can land on a question token or [CLS], whose offsets do not refer to the context. Without a length limit, the two argmax positions can also be far apart and give an answer much longer than intended.
Exercise
A context has 12 tokens, and you call start_logits.topk(20). What error or behavior do you expect, and how should the code deal with it?
Show answer
topk fails with a "selected index k out of range" error when k is larger than the number of elements. Here the logits cover the whole sequence including the question and special tokens, so the sequence is usually longer than 12 tokens, but a very short question and context can still be shorter than 20. Use k = min(n_best, len(start_logits)). Masked positions will still appear among the candidates, so also skip any candidate whose sequence_ids value is not 1, as the decoder above does.