Sub topic 12
Building Token-Level Training Labels
Assume you know basic Python, tokenization, and how a pretrained transformer produces tensors. This chapter focuses on the step between SQuAD-style character annotations and the integer labels used to train a question-answering model.
A SQuAD example stores an answer like this:
- Context: a string of text.
- Question: a question about the context.
- Answer text: the expected span.
answer_start: the character index where that span begins.
A transformer does not predict character positions directly. After tokenization, it predicts token positions. The training pipeline must therefore translate character positions into a start-token index and an end-token index.
The alignment problem
Suppose the answer occupies characters [start, end) in the context. The end position is exclusive, so:
answer_end = answer_start + len(answer_text)The tokenizer returns an offset mapping. Each token receives a pair such as (35, 42), meaning that token covers characters 35 through 41 in the original context.
The labels are selected as follows:
| Input annotation | Training label |
|---|---|
| Answer begins at character 35 | Token whose offset contains character 35 |
| Answer ends at character 72 | Token whose offset contains the final answer character |
| Answer is outside this window | The `[CLS]` token index, usually 0 |
The question tokens and special tokens must not be considered. sequence_ids() identifies question tokens as sequence 0, context tokens as sequence 1, and special tokens as None.
Aligning one tokenized feature
The following function handles one question-context feature. It returns (0, 0) when the answer is not contained in that feature. This is necessary when a long context has been split into overlapping windows.
from transformers import AutoTokenizer
def find_token_labels(offsets, sequence_ids, answer_start, answer_text):
"""Return start and end token indices for one encoded feature."""
answer_end = answer_start + len(answer_text)
context_tokens = [
i for i, sequence_id in enumerate(sequence_ids)
if sequence_id == 1
]
if not context_tokens:
return 0, 0
first = context_tokens[0]
last = context_tokens[-1]
# This window does not contain the complete answer.
if offsets[first][0] > answer_start or offsets[last][1] < answer_end:
return 0, 0
start_token = next(
(i for i in context_tokens
if offsets[i][0] <= answer_start < offsets[i][1]),
None,
)
end_token = next(
(i for i in reversed(context_tokens)
if offsets[i][0] < answer_end <= offsets[i][1]),
None,
)
if start_token is None or end_token is None:
return 0, 0
return start_token, end_token
tokenizer = AutoTokenizer.from_pretrained(
"distilbert-base-cased-distilled-squad"
)
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."
)
answer = "seven million square kilometres"
answer_start = context.index(answer)
encoded = tokenizer(
question,
context,
return_offsets_mapping=True,
truncation="only_second",
max_length=384,
)
offsets = encoded["offset_mapping"]
sequence_ids = encoded.sequence_ids(0)
start_token, end_token = find_token_labels(
offsets,
sequence_ids,
answer_start,
answer,
)
print(start_token, end_token)The model receives these two integers as start_positions and end_positions. During training, the span head increases the start score for start_token and the end score for end_token.
Overflow windows
For a context longer than the model's maximum length, use return_overflowing_tokens=True and a stride. The tokenizer creates several features. Each feature contains the complete question and a different context window.
For every feature:
- Read its offset mapping.
- Check whether the complete answer is inside the context portion.
- Assign the matching start and end tokens if it is.
- Assign the
[CLS]index if it is not.
The same original example can therefore produce one positive feature and several negative features. Keep the mapping from each feature back to its original example with overflow_to_sample_mapping.
For SQuAD v2-style unanswerable questions, every feature receives the null label, usually (0, 0). The model learns that the best span is the [CLS] position when the context does not answer the question.
Exercise
An answer starts at character 100, but the current overflow window's last context token ends at character 84. What labels should this feature receive, and why?
Show answer
It should receive the CLS labels, usually start position 0 and end position 0, because the answer is not fully contained in this feature.