Sub topic 10
Questions with no answer in the text
This chapter assumes you can run the pipeline from the earlier chapters and decode start and end logits by hand. You also need to know what offset mappings and sequence_ids are.
Why a span model needs a way to say "no"
A basic extractive model always answers. The softmax over positions has to put its probability somewhere, so the model returns the best-looking span even when the passage says nothing relevant. Ask "Who discovered penicillin?" about a paragraph on the Amazon River and a SQuAD v1.1 model will return some noun phrase with a plausible score.
Real documents often lack the answer. A search system, a support bot, or a contract reader needs a third outcome: "the passage does not say." SQuAD v2.0 added this by mixing about 50,000 unanswerable questions into the data. They were written by crowdworkers to look like answerable ones.
How the data marks an unanswerable question
In SQuAD v2 each question has an is_impossible flag. For an unanswerable question the answers list is empty. In the Hugging Face datasets version, answers["text"] and answers["answer_start"] are empty lists.
{
"id": "q2",
"question": "Who discovered penicillin?",
"context": "The Amazon River in South America is the largest river ...",
"answers": {"text": [], "answer_start": []},
}Checking len(example["answers"]["text"]) == 0 is the reliable test for "no answer."
The null answer lives at the [CLS] position
The model has no extra output for "no answer." It reuses the start and end logits. During training, an unanswerable question gets the label start = 0, end = 0. Position 0 is the special first token ([CLS] in BERT-style models, <s> in RoBERTa). Because the context never starts at position 0, that position is free to act as a "no answer here" marker.
This is the same convention used in the label-alignment function from the earlier chapter, which returns (0, 0) when the answer is outside a window. The model learns to put high start and end scores on position 0 when the question cannot be answered from the text.
At inference time you compute two numbers:
- Null score:
start_logits[0] + end_logits[0]. - Best span score: the highest
start_logits[s] + end_logits[e]over valid context spans, as in the decoding chapter.
You predict the empty answer when the null score beats the best span score by more than a threshold:
null_score - best_span_score > threshold -> predict ""With a threshold of 0, the model's own comparison decides. A positive threshold makes the system answer more often. A negative one makes it abstain more often.
Use a model trained on SQuAD v2
The model from the earlier chapters, distilbert-base-cased-distilled-squad, was trained only on SQuAD v1.1. It never saw a label of (0, 0) for a question, so its scores at position 0 mean nothing. The null-answer logic needs a model trained with unanswerable examples. This chapter uses deepset/roberta-base-squad2.
Abstaining with the pipeline
The pipeline exposes the behaviour through one argument.
from transformers import pipeline
qa = pipeline("question-answering", model="deepset/roberta-base-squad2")
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."
)
for question in ["What does the Amazon basin cover?", "Who discovered penicillin?"]:
result = qa(question=question, context=context, handle_impossible_answer=True)
print(question, "->", repr(result["answer"]), round(result["score"], 3))With handle_impossible_answer=True, the pipeline compares the null score with the best span. If the null score wins, it returns {"answer": "", "start": 0, "end": 0, "score": ...}. Without the argument, the pipeline ignores position 0 and always returns a span, even from a SQuAD v2 model. This is the most common reason a "SQuAD v2" model seems unable to abstain.
Doing it by hand with a tunable threshold
The following function is the decoding code from the earlier chapter, extended with the null score and a threshold.
import torch
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
name = "deepset/roberta-base-squad2"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForQuestionAnswering.from_pretrained(name)
def answer_or_null(question, context, threshold=0.0, max_answer_len=30, top_k=20):
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)
start_logits = outputs.start_logits[0]
end_logits = outputs.end_logits[0]
# Null score is read BEFORE masking, because position 0 is not a context token.
null_score = (start_logits[0] + end_logits[0]).item()
not_context = torch.tensor([s != 1 for s in sequence_ids])
start_masked = start_logits.masked_fill(not_context, -1e9)
end_masked = end_logits.masked_fill(not_context, -1e9)
best_score, best_span = float("-inf"), None
for s in start_masked.topk(top_k).indices.tolist():
for e in end_masked.topk(top_k).indices.tolist():
if s <= e and e - s < max_answer_len:
score = (start_masked[s] + end_masked[e]).item()
if score > best_score:
best_score, best_span = score, (s, e)
diff = null_score - best_score
if best_span is None or diff > threshold:
return "", diff
s, e = best_span
return context[offsets[s][0]:offsets[e][1]], diff
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."
)
for q in ["What does the Amazon basin cover?", "Who discovered penicillin?"]:
print(q, "->", answer_or_null(q, context))The order of operations matters. The mask sets position 0 to -1e9, so the null score must be read from the unmasked logits first. If you mask first, null_score is about -2e9 and the model never abstains.
The returned diff is useful beyond the yes/no decision. A large positive value means the model is confident that no answer exists. Values near zero mean it is unsure.
Long contexts: one null score per window
When a context is split into overlapping windows, each window gets its own null score and its own best span. A window that does not contain the answer will have a high null score, so you cannot compare the null score of any single window against the global best span. The standard rule (used in the Hugging Face QA example scripts and the original BERT code) is:
- Take the minimum null score over all windows. The window that is most willing to answer sets the document's null score.
- Take the best non-null span score over all windows.
- Compare them with the same threshold rule.
Using the average or the maximum null score would make long documents look unanswerable, because most windows do not contain the answer.
Choosing the threshold
A threshold of 0 is rarely best. Domain shift, calibration, and the mix of answerable and unanswerable questions in your data all move the optimum. Tune it on a held-out set by maximizing F1.
def best_threshold(diffs, gold_has_answer, answer_f1):
"""diffs[i]: null_score - best_span_score for example i.
gold_has_answer[i]: True if the reference has an answer.
answer_f1[i]: F1 of the best span against the reference (0 if no answer).
Returns (threshold, mean_score)."""
best_t, best_mean = None, -1.0
for t in sorted(set(diffs)):
total = 0.0
for d, has, f1 in zip(diffs, gold_has_answer, answer_f1):
if d > t: # predict empty answer
total += 0.0 if has else 1.0
else: # predict the span
total += f1 if has else 0.0
mean = total / len(diffs)
if mean > best_mean:
best_t, best_mean = t, mean
return best_t, best_mean
print(best_threshold(
diffs=[-4.0, -1.0, 2.5, 6.0],
gold_has_answer=[True, True, False, False],
answer_f1=[0.9, 0.4, 0.0, 0.0],
))Use d > t consistently with the rule in the decoder. In this toy set, the threshold -1.0 gives the perfect mean of 0.65 only if the second example is answered and the third is not. Run it and check the number against the loop.
Measuring abstention
The v1 metric has no way to score an empty answer. The squad_v2 metric takes a no_answer_probability per prediction and reports extra fields.
import evaluate
metric = evaluate.load("squad_v2")
predictions = [
{"id": "q1", "prediction_text": "seven million square kilometres", "no_answer_probability": 0.0},
{"id": "q2", "prediction_text": "", "no_answer_probability": 1.0},
]
references = [
{"id": "q1", "answers": {"text": ["about seven million square kilometres"], "answer_start": [88]}},
{"id": "q2", "answers": {"text": [], "answer_start": []}},
]
print(metric.compute(predictions=predictions, references=references))| Field | Meaning |
|---|---|
| `exact`, `f1` | Overall scores using the predicted text, where an empty answer is correct only for unanswerable questions |
| `HasAns_exact`, `HasAns_f1` | Scores on answerable questions only |
| `NoAns_exact`, `NoAns_f1` | Share of unanswerable questions where the model correctly abstained |
| `best_exact`, `best_f1` | Scores after choosing the best `no_answer_probability` threshold |
| `best_exact_thresh`, `best_f1_thresh` | The threshold that achieved them |
Read HasAns_* and NoAns_* together. A model that always abstains gets a NoAns of 100 and a HasAns of 0. Overall f1 can hide this, because it averages the two groups.
Common mistakes
- Using a v1.1 model for abstention. Position 0 has no learned meaning.
- Forgetting
handle_impossible_answer=Truein the pipeline. - Masking before reading the null score in manual decoding.
- Averaging null scores across windows instead of taking the minimum.
- Evaluating only overall F1. Always check the answerable and unanswerable splits.
- Treating "no answer" as proof the fact is false. The model only says that this passage does not state it.
Exercise
A long document is split into 5 windows. The window null scores (start0 + end0) are 8.1, 7.4, -1.2, 9.0, 6.8. The best non-null span scores per window are 2.0, 1.5, 5.3, 0.9, 1.1. With a threshold of 0, what does the system return, and why?
Show answer
The document null score is the minimum, -1.2. The best span score is the maximum, 5.3. The difference is -1.2 - 5.3 = -6.5, which is not greater than 0, so the system returns the best span from the third window. The third window is the one that contains the answer, and its low null score shows it. Averaging the null scores would give 6.0 and wrongly make the document look unanswerable.
Exercise
You call the same model in manual decoding, but it never returns an empty answer, even for clearly unrelated questions. Name two likely causes.
Show answer
First, the null score may be computed after the masked_fill step, so it equals about -2e9 and never exceeds the best span score. Second, the checkpoint may have been fine-tuned on SQuAD v1.1 only, so position 0 carries no learned "no answer" signal. A third cause is a threshold set too high.