Sub topic 9
Handling contexts longer than the model limit
This chapter assumes you can run a question-answering model with the Hugging Face pipeline and decode start and end logits by hand with offset mappings, as in the earlier chapters. You should also know what max_length and truncation do in a tokenizer.
Why the limit exists
A transformer encoder accepts only a fixed number of positions. BERT-style models, including DistilBERT, have 512 position embeddings, and many QA recipes use a smaller max_length such as 384 to save memory. The question, the context and the special tokens ([CLS], [SEP]) must all fit in that budget.
A news article, a contract or a wiki page is often several thousand tokens long. If you cut it at the limit, the answer may be in the part you discarded, and the model returns a wrong span from the text it did see. The model has no way to report that anything was lost.
Cutting is the wrong fix. Instead, split the context into overlapping windows. Run the model on each window, then pick the best answer across all windows.
Windows with stride
The tokenizer can do the splitting for you. Three arguments work together:
| Argument | Effect |
|---|---|
| `truncation="only_second"` | Only the context is shortened. The question is kept whole in every window. |
| `stride=128` | Consecutive windows overlap by 128 context tokens. |
| `return_overflowing_tokens=True` | The text that would be truncated becomes extra windows instead of being dropped. |
Each window has the form [CLS] question [SEP] context piece [SEP]. The question is repeated in every window, so each one is a complete, valid input.
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 overlapping windows
print([len(ids) for ids in enc["input_ids"]]) # each window is at most 384 tokensEach window holds at most max_length - len(question tokens) - 3 context tokens. A new window starts stride tokens before the end of the previous one. With a 5-token question, a window holds 376 context tokens and the start advances by 376 - 128 = 248 tokens. The 2000-token context therefore needs about 8 windows.
Why the overlap matters
Suppose the answer is "seven million square kilometres". If a window boundary falls in the middle of those words, neither window sees the whole span. The model can only choose a start and end that both lie inside one window, so it would fail on both.
The overlap fixes this. Any answer shorter than the stride is guaranteed to fit entirely inside at least one window. This gives a practical rule: stride should be larger than the longest answer you expect, and also large enough that the model sees some surrounding words next to the answer. A value of 128 is common, and the value is a trade-off:
- A larger stride means more overlap and more windows, so inference costs more.
- A smaller stride is cheaper but risks splitting answers and gives less surrounding context.
Mapping windows back to the example
When you pass several questions at once, windows from different examples are mixed in one list. The tokenizer returns overflow_to_sample_mapping, a list in which entry i gives the index of the original example that window i came from. For one question and one context it is all zeros. You need it for batches, so that you compare windows only against other windows of the same example.
Offsets are also relative to the original context string, not to the window. That is why you can cut the answer straight out of the full text, whichever window produced it.
Scoring every window and combining
The next function does the whole job for one question and one long context. It tokenizes with overflow, scores every window, and returns the span with the highest start_logit + end_logit.
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_long(question, context, max_length=384, stride=128,
n_best=20, max_answer_len=30):
enc = tokenizer(
question, context,
max_length=max_length,
truncation="only_second",
stride=stride,
return_overflowing_tokens=True,
return_offsets_mapping=True,
padding=True,
return_tensors="pt",
)
offset_mapping = enc.pop("offset_mapping")
enc.pop("overflow_to_sample_mapping")
with torch.no_grad():
out = model(**enc)
best = {"score": float("-inf"), "text": "", "window": None}
for i in range(out.start_logits.shape[0]):
sequence_ids = enc.sequence_ids(i)
offsets = offset_mapping[i].tolist()
# Keep only context tokens. Question, special and padding tokens are excluded.
not_context = torch.tensor([s != 1 for s in sequence_ids])
start_logits = out.start_logits[i].masked_fill(not_context, -1e9)
end_logits = out.end_logits[i].masked_fill(not_context, -1e9)
for s in start_logits.topk(n_best).indices.tolist():
for e in end_logits.topk(n_best).indices.tolist():
if s <= e and e - s < max_answer_len:
score = (start_logits[s] + end_logits[e]).item()
if score > best["score"]:
best = {
"score": score,
"text": context[offsets[s][0]:offsets[e][1]],
"window": i,
}
return best
filler = "The harbour town is quiet in winter. " * 80
context = filler + "The lighthouse was built in 1858 by the engineer Mara Voss. " + filler
print(len(tokenizer(context)["input_ids"])) # well above 384
print(answer_long("Who built the lighthouse?", context))The context is about 1000 tokens, so the answer sits in a later window. If you tokenized with plain truncation, the model would see only the first 384 tokens, which are all filler. With windows, the sentence about the lighthouse appears in one of them and the model should return the engineer's name. The exact score will vary by library version.
The window field is useful for debugging. If the answer is wrong, check which window won and whether the true answer was visible in any window.
Edge cases
- Overlapping duplicates. A span inside the overlap zone is scored twice, once per window, with slightly different logits. Taking the maximum handles this, and the answer text is the same either way.
- Question longer than the budget. With
truncation="only_second", the tokenizer raises an error if the question alone fillsmax_length. Shorten the question or raisemax_length. Do not switch to"longest_first", which would cut the question. - Stride too large.
stridemust be smaller than the number of context tokens per window. If it is not, the tokenizer raises an error, or the windows barely advance. Keep a wide margin. - Padding tokens. With
padding=True, the last window is padded. Thesequence_idsfor padding areNone, so the mask above already excludes them. - Offsets outside the context. For question and special tokens the offset mapping is
(0, 0). If you forget the mask, a span could start at one of these tokens and return garbage text. - Unanswerable questions. A model trained on SQuAD v2 also scores a null answer at
[CLS], one per window. The usual rule compares the best span against the null score. For a long context, use the smallest null score across windows, because a null answer is only correct if every window agrees there is no answer.
What the pipeline does for you
The question-answering pipeline performs these same steps. You control the windowing with two arguments:
from transformers import pipeline
qa = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
filler = "The harbour town is quiet in winter. " * 80
context = filler + "The lighthouse was built in 1858 by the engineer Mara Voss. " + filler
print(qa(
question="Who built the lighthouse?",
context=context,
max_seq_len=384, # window size in tokens
doc_stride=128, # overlap between windows
))max_seq_len corresponds to max_length and doc_stride corresponds to stride. The pipeline returns character positions in the original context, so they are valid for the full text.
Writing the loop yourself is worth it when you need per-window scores, a custom rule for combining windows, or batched inference over many documents.
Summary of the decisions
- Use
truncation="only_second"so the question is never cut. - Choose
stridelarger than the longest expected answer. Increase it if answers are split, and decrease it if inference is too slow. - Keep
return_offsets_mapping=Trueand map the winning span back into the original string. - Mask out every token that is not context before searching for spans.
- Compare spans across windows of the same example only, using
overflow_to_sample_mappingwhen you batch.
Exercise
A context has 1000 tokens, the question has 10 tokens, and you use max_length=384 and stride=128. Roughly how many context tokens does each window hold, and how many tokens does each new window advance? Then explain what could go wrong if you set stride=0 and the answer is 40 tokens long.
Show answer
Each window has 3 special tokens and 10 question tokens, so it holds 384 - 13 = 371 context tokens. Each new window starts 128 tokens before the end of the previous one, so it advances 371 - 128 = 243 tokens. With stride=0 the windows do not overlap. A 40-token answer that crosses a window boundary is cut in two, and neither window contains the whole span. The model can only pick a start and an end inside one window, so it cannot return the correct answer. The overlap guarantees that any answer shorter than the stride fits whole in at least one window.
Exercise
In the answerlong function, what happens if you remove the maskedfill step that sets non-context logits to -1e9, and why does the question appear in the output?
Show answer
The search can then choose a start or end index that belongs to the question, a special token, or padding. For those tokens the offset mapping is (0, 0) or points into the question, so the slice of the context string is empty or wrong. Question tokens can also receive high logits, so the best-scoring span may lie there. Masking gives non-context positions a very low score, so they can never win.