Sub topic 3
Handling contexts longer than the model limit
This chapter assumes you know Python, have used Hugging Face transformers and its tokenizers, and understand the question-answering span logic from the previous chapter. A transformer encoder such as DistilBERT accepts at most 384 tokens per input here, so longer documents need special handling.
Splitting long contexts into windows
Pass return_overflowing_tokens=True and a stride to the tokenizer. It cuts the context into overlapping windows, and each window repeats the question.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased-distilled-squad")
question = "What is the topic?"
long_context = "word " * 2000
enc = tokenizer(
question, long_context,
max_length=384,
truncation="only_second",
stride=128,
return_overflowing_tokens=True,
return_offsets_mapping=True,
)
print(len(enc["input_ids"])) # number of windows
print([len(ids) for ids in enc["input_ids"]]) # each at most 384 tokensScore each window separately, then keep the answer with the highest score across all windows.
Questions with no answer
Some questions have no answer in the text. In SQuAD 2.0 style data, the start and end scores at the [CLS] position (index 0) form a null answer score. Compare the null score with the best real span score. Return an empty answer when the null score wins by more than a threshold you tune on validation data.
Measuring quality with exact match and F1
Exact match (EM) gives 1 only when the normalized prediction equals a reference answer exactly. F1 gives partial credit by comparing the tokens shared between prediction and reference. Report both, because a prediction of "seven million" against the reference "about seven million square kilometres" scores 0 on EM but earns partial F1.
Building token-level labels
Training data gives answers as character positions. Use the offset mapping to find the first and last tokens inside each window that cover those characters. If the answer lies outside the window, label the position as 0, the [CLS] index.
Fine-tuning on question answering data
Load a pretrained encoder with a span head, then train it on SQuAD-style examples using the token labels above. Use a small learning rate, such as 3e-5, and evaluate with EM and F1 after each epoch.
Common failure modes
- Windows that cut the answer in half, so no window contains the full span.
- Null thresholds tuned on the wrong data.
- Inflated scores from comparing against too few reference answers.
- Questions that need reasoning across distant parts of a long document.
Exercise
A 1,000-token context is split with max_length=384 and stride=128. Why do the windows overlap, and what would go wrong with no overlap?
Show answer
The overlap keeps answers that sit near a window boundary fully inside at least one window. Without overlap, an answer split across two windows could never be predicted whole.