Sub topic 9
Handling Contexts Longer Than the Model Limit
Why one context becomes several windows
Prerequisites: you should know basic Python, tokenization, PyTorch tensors, and how a question-answering model predicts start and end positions.
A transformer has a maximum input length. For many BERT-style models, the limit is 384 or 512 tokens. The limit counts both the question and the context. A long document therefore cannot be passed as one complete input.
The usual solution is a sliding window. The tokenizer creates several shorter inputs. Each input contains the complete question and a different section of the context. Neighboring sections overlap by a chosen number of tokens called the stride.
The overlap matters when an answer crosses a window boundary. With no overlap, one window might contain the beginning of an answer while the next contains its ending. A stride gives the model another window where the full answer appears.
Creating overflowing windows
Hugging Face tokenizers support this directly:
from transformers import AutoTokenizer
name = "distilbert-base-cased-distilled-squad"
tokenizer = AutoTokenizer.from_pretrained(name)
question = "What is the topic?"
context = "word " * 2000
features = tokenizer(
question,
context,
max_length=384,
truncation="only_second",
stride=128,
return_overflowing_tokens=True,
return_offsets_mapping=True,
)
print(len(features["input_ids"]))truncation="only_second" tells the tokenizer to truncate the context, not the question. return_overflowing_tokens=True requests all windows instead of only the first one. return_offsets_mapping=True records the character range for each token in the original context.
The stride should be large enough to cover expected answers but not so large that it creates unnecessary computation.
| Setting | Effect | Typical concern |
|---|---|---|
| `max_length` | Maximum tokens per window | Larger values use more memory |
| `stride` | Tokens repeated between windows | Larger values create more windows |
| `truncation="only_second"` | Keeps the question intact | Required for question-context pairs |
Scoring every window
Each window produces start and end logits. To combine windows, generate candidate spans in every window, convert each span to text with its offsets, and compare their scores.
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."
)
features = tokenizer(
question,
context,
max_length=384,
truncation="only_second",
stride=128,
padding="max_length",
return_overflowing_tokens=True,
return_offsets_mapping=True,
return_tensors="pt",
)
offsets = features.pop("offset_mapping")
features.pop("overflow_to_sample_mapping", None)
model_inputs = {
key: value for key, value in features.items()
if key in tokenizer.model_input_names
}
with torch.no_grad():
outputs = model(**model_inputs)
best = None
for window in range(len(model_inputs["input_ids"])):
sequence_ids = features.sequence_ids(window)
context_tokens = [i for i, sid in enumerate(sequence_ids) if sid == 1]
starts = sorted(
context_tokens,
key=lambda i: float(outputs.start_logits[window, i]),
reverse=True,
)[:20]
ends = sorted(
context_tokens,
key=lambda i: float(outputs.end_logits[window, i]),
reverse=True,
)[:20]
for start in starts:
for end in ends:
if start <= end and end - start + 1 <= 30:
score = (
outputs.start_logits[window, start]
+ outputs.end_logits[window, end]
).item()
span_offsets = offsets[window].tolist()
answer = context[
span_offsets[start][0]:span_offsets[end][1]
]
if best is None or score > best[0]:
best = (score, answer)
print(best[1])This code compares spans across all windows. The best score is only meaningful among the candidate spans produced by the same model and decoding method. In production, also remove empty answers, limit answer length, and keep the window index for error analysis.
Choosing the window size
A small stride is faster but increases the chance that an answer is split across windows. A large stride improves coverage but repeats more tokens and increases latency. Start with a stride between one-quarter and one-half of the maximum length, then measure accuracy and runtime on representative documents.
Exercise
A model accepts 384 tokens, the question uses 24 tokens, and the context needs 900 tokens. With a stride of 100, why should you score multiple windows instead of using only the first window?
Show answer
The first window cannot contain the entire context. Later overlapping windows cover tokens that were truncated from the first window, so the answer may appear only in one of those later windows.