Sub topic 5
Feeding the question and context together
This chapter covers how a question and a passage become one input sequence for a transformer encoder. It assumes you know basic Python, can read PyTorch tensors, and know roughly what a pretrained language model and a tokenizer are. The previous chapters introduced SQuAD-style data, subword tokens and pretrained encoders. This chapter joins them: the encoder receives a question and a context together, and the next chapter's span head reads that encoding.
Why the model needs both texts in one sequence
An extractive QA model answers by picking a span of the context. To judge whether a token could start an answer, the model must compare that token with the question. A separate encoding of each text would not allow this comparison.
The encoder solves this by reading both texts as one sequence. Self-attention lets every context token attend to every question token, and the reverse. The hidden state of a context token therefore depends on what was asked. The word "seven" gets a different representation under "What does the basin cover?" than under "How long is the river?".
This pairing is the same input format that BERT-style models use for sentence-pair tasks such as entailment. QA models reuse it unchanged.
The layout of a sentence pair
A BERT-style tokenizer builds the pair like this:
[CLS] question tokens [SEP] context tokens [SEP][CLS]is a special token at position 0. Its position matters later, because it is also where models without an answer point.[SEP]separates the two segments and closes the sequence.- The question always comes first and the context second. Swapping them breaks the
truncation="only_second"setting and puts the labels in the wrong segment.
Besides input_ids, the tokenizer returns other fields:
| Field | Meaning | Notes |
|---|---|---|
| `input_ids` | Vocabulary index of each token | Always present |
| `attention_mask` | 1 for real tokens, 0 for padding | Tells the model to ignore padding |
| `token_type_ids` | 0 for the first segment, 1 for the second | Returned by BERT. DistilBERT does not use it, so its tokenizer omits it |
| `offset_mapping` | `(start_char, end_char)` of each token in its source text | Requires a fast tokenizer and `return_offsets_mapping=True` |
Do not use token_type_ids to find the context in your own code. Not every model has them, and they do not mark special tokens. Use sequence_ids() instead.
Inspecting a pair
Run this to see the layout for yourself. It uses the same DistilBERT checkpoint as the rest of the tutorial.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased-distilled-squad")
question = "What is the capital of France?"
context = "Paris is the capital of France."
enc = tokenizer(question, context, return_offsets_mapping=True)
tokens = tokenizer.convert_ids_to_tokens(enc["input_ids"])
sequence_ids = enc.sequence_ids(0)
for token, seq, (start, end) in zip(tokens, sequence_ids, enc["offset_mapping"]):
print(f"{token:10} sequence_id={seq!s:5} offsets=({start}, {end})")
print(list(enc.keys()))The output has 17 rows. Each row shows a token, its sequence id and its offsets. The expected pattern is:
[CLS]has sequence idNoneand offsets(0, 0).- The seven question tokens have sequence id
0. Their offsets point into the question string. [SEP]has sequence idNoneand offsets(0, 0).- The seven context tokens have sequence id
1. Their offsets point into the context string. - The final
[SEP]has sequence idNone.
Three details matter for the rest of the chapter.
- Offsets restart for each segment. The first context token has offsets starting at
0, not at the length of the question. An offset is only meaningful together with its sequence id. - Special tokens have
(0, 0)offsets and sequence idNone. They cannot be sliced out of any text. sequence_idsis the reliable way to find the context. The tutorial's decoding code masks every position where the sequence id is not1.
Truncation: protect the question
Encoders have a maximum input length, often 512 tokens. The tutorial uses max_length=384, the value common in SQuAD examples. If the pair is longer than the limit, the tokenizer must cut something. The truncation argument decides what.
| Setting | Behavior | Use for QA? |
|---|---|---|
| `"only_second"` | Cuts only the context | Yes |
| `"only_first"` | Cuts only the question | No |
| `"longest_first"` (the default when `truncation=True`) | Removes tokens one at a time from whichever text is currently longer | No |
| `False` | No cutting. The model may fail on an over-length input | Only for short inputs |
With "longest_first", a long context shrinks first, but a long question can also lose tokens. A truncated question can change its meaning, and the answer would be wrong without any error message. "only_second" never touches the question. If the question alone exceeds max_length, the tokenizer raises an error. That is the right behavior, because such an input is not valid.
Plain truncation throws away the end of the context, and the answer may be in that part. The chapter on long contexts replaces it with overlapping windows. For now, treat "only_second" as the safe default.
Padding and batching
The model takes a rectangular tensor. When you encode several pairs at once, shorter sequences need padding up to a common length.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased-distilled-squad")
questions = ["What is the capital of France?", "Who wrote Hamlet?"]
contexts = [
"Paris is the capital of France.",
"Hamlet is a tragedy written by William Shakespeare around 1600.",
]
batch = tokenizer(
questions,
contexts,
return_tensors="pt",
padding=True,
truncation="only_second",
max_length=384,
)
print(batch["input_ids"].shape)
print(batch["attention_mask"])Here padding=True pads to the longest sequence in the batch. The attention_mask has zeros where the padding is. The shapes are (batch_size, sequence_length), so the first pair gets padding tokens after its final [SEP].
Padding has one consequence for decoding. Padding positions have sequence id None, the same as special tokens. A mask that keeps only positions where the sequence id is 1 therefore excludes them automatically.
Common errors
- Passing one string instead of two arguments. Writing
tokenizer(question + " " + context)produces one segment. The model has no[SEP]between the texts and no way to tell them apart. - Reversing the order.
tokenizer(context, question)makes the context the first segment. With"only_second", the tokenizer would then cut the question. - Using a slow tokenizer. Without a fast tokenizer,
return_offsets_mapping=Trueraises aNotImplementedError.AutoTokenizerloads a fast one by default for most models, so the error appears mainly when you requestuse_fast=False. - Slicing the wrong string. Offsets from a context token slice the context, not the concatenated input. Slicing the question with them gives text from the wrong place.
- Forgetting that
offset_mappingis not a model input. Pop it before callingmodel(**inputs), as the decoding example in the tutorial does. Otherwise the model receives an unexpected keyword argument. - Assuming the answer is always in the window. After truncation, the answer span may lie in the discarded part. Training code must handle that case, which a later chapter covers.
Check your understanding
Exercise
You call tokenizer(question, context, truncation="longest_first", max_length=64) on a short question and a very long context. Name one situation where this loses information that truncation="only_second" would keep, and say how to detect which tokens belong to the context after encoding.
Show answer
If the question is also long, "longest_first" can remove question tokens once the context has shrunk to a similar length, which can change what is being asked. "only_second" leaves the question intact. After encoding, call enc.sequence_ids(0): positions with value 1 are context tokens, positions with 0 are question tokens, and None marks special tokens and padding.
Exercise
For the pair in the inspection example, the first context token "Paris" has offsets (0, 5). A colleague says this is a bug because the question is 30 characters long, so the offsets should start at 31. Explain why the offsets are correct.
Show answer
Offsets are character positions within the text each token came from, not within a concatenation. "Paris" begins at character 0 of the context string, so its offsets are (0, 5). The sequence id (1 for context) says which string to slice. This is why decoding uses context[offsets[s][0]:offsets[e][1]].