Sub topic 12
Building Token-Level Training Labels
This chapter assumes you can read basic Python and PyTorch code and know what a fast tokenizer's offset mapping is. It also assumes you know how SQuAD stores answers and how a start/end span head produces logits. The question is how to turn a SQuAD record into the integer targets that those logits are trained against.
Why labels need conversion
A SQuAD record describes the answer in characters: the answer text and an answer_start character index into the context. The model works on tokens, and its head outputs one start logit and one end logit per token. Training with cross-entropy therefore needs two integers per training window: the index of the token where the answer starts and the index of the token where it ends.
The conversion has three obstacles:
- Tokens do not line up with characters. A word can split into several subword pieces, and the answer can begin or end in the middle of a word.
- The encoded input contains the question, special tokens, and padding. The labels must point only into the context.
- Long contexts are split into overlapping windows. The answer may be in one window, in several, or in none.
What a label looks like
For each window, the labels are start_positions and end_positions. Both are indices into that window's input_ids.
{"id": "q1", "start_positions": 7, "end_positions": 8}If the answer is not fully inside the window, both labels point to index 0, the [CLS] token. This is a deliberate convention, not a missing value. The model learns to put its probability mass on [CLS] when a window does not contain the answer. The same convention supports unanswerable questions in SQuAD v2 style data. At inference you can compare the best span score with the [CLS] score to decide whether to abstain.
The offset mapping and sequence IDs
Two outputs from a fast tokenizer make the conversion possible.
offset_mappinggives a(char_start, char_end)pair for every token. Special tokens and padding get(0, 0). The end is exclusive.sequence_ids(i)tells which input each token came from:0for the question,1for the context, andNonefor special tokens and padding.
Offsets for context tokens are measured in the original context string, not in the concatenated input. This is why a character index from the dataset can be compared directly with them.
Mapping characters to tokens
The function below walks inward from both edges of the context region. It stops at the tokens that cover the answer's start and end characters.
def char_to_token_span(offsets, sequence_ids, answer_start, answer_end):
"""Return (start_token, end_token) for an answer given by character positions.
Return (0, 0), which is the [CLS] position, if the answer is not inside this window."""
context_idx = [i for i, s in enumerate(sequence_ids) if s == 1]
first, last = context_idx[0], context_idx[-1]
if offsets[first][0] > answer_start or offsets[last][1] < answer_end:
return 0, 0
start = first
while start <= last and offsets[start][0] <= answer_start:
start += 1
start -= 1
end = last
while end >= first and offsets[end][1] >= answer_end:
end -= 1
end += 1
return start, endThe function works as follows:
- It collects the indices of context tokens. Their first and last positions bound the search, so question tokens can never become labels.
- It checks whether the window covers the whole answer. If the first context token begins after the answer starts, or the last context token ends before the answer ends, the answer is cut off, and the function returns
(0, 0). - For the start, it advances while a token still begins at or before
answer_start. It then steps back one token. The result is the last token whose start is not after the answer start, which is the token containing that character. - For the end, it moves backward while a token still ends at or after
answer_end. It then steps forward one token. The result is the first token whose end reaches the answer end.
You can check this without a model by writing the offsets by hand. The example encodes the question Who wrote it? and the context Ann wrote it. as a toy token sequence.
# Tokens: [CLS] Who wrote it ? [SEP] Ann wrote it . [SEP]
sequence_ids = [None, 0, 0, 0, 0, None, 1, 1, 1, 1, None]
offsets = [
(0, 0), (0, 3), (4, 9), (10, 12), (12, 13), (0, 0),
(0, 3), (4, 9), (10, 12), (12, 13), (0, 0),
]
# Answer "wrote it" occupies characters 4 to 12 of the context.
print(char_to_token_span(offsets, sequence_ids, 4, 12)) # (7, 8)
# An answer that lies beyond the characters this window covers.
print(char_to_token_span(offsets, sequence_ids, 20, 25)) # (0, 0)Note that the question's offsets also look like valid character ranges. The function ignores them because it only looks at tokens whose sequence ID is 1.
Applying it to a whole dataset
Real training data needs the tokenizer's windowing options from the long-contexts chapter. Each example can produce several windows, and overflow_to_sample_mapping tells which original example each window came from. The label function looks up the answer through that mapping.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased-distilled-squad")
def prepare_train_features(examples, max_length=384, stride=128):
questions = [q.strip() for q in examples["question"]]
enc = tokenizer(
questions,
examples["context"],
max_length=max_length,
truncation="only_second",
stride=stride,
return_overflowing_tokens=True,
return_offsets_mapping=True,
padding="max_length",
)
sample_map = enc.pop("overflow_to_sample_mapping")
offset_mapping = enc.pop("offset_mapping")
start_positions, end_positions = [], []
for i, offsets in enumerate(offset_mapping):
sequence_ids = enc.sequence_ids(i)
answer = examples["answers"][sample_map[i]]
if len(answer["answer_start"]) == 0: # unanswerable question
start_positions.append(0)
end_positions.append(0)
continue
answer_start = answer["answer_start"][0]
answer_end = answer_start + len(answer["text"][0])
s, e = char_to_token_span(offsets, sequence_ids, answer_start, answer_end)
start_positions.append(s)
end_positions.append(e)
enc["start_positions"] = start_positions
enc["end_positions"] = end_positions
return encWith the Hugging Face datasets library, you would call dataset.map(prepare_train_features, batched=True, remove_columns=dataset.column_names). The remove_columns argument is required. The original dataset has one row per question, while the output has one row per window. Without it, the two row counts would not match and map would fail.
The question.strip() call matters. Leading whitespace in a question can push the encoded length over the limit in a way that changes the windows.
Edge cases
| Situation | Label result | What to watch for |
|---|---|---|
| Answer entirely inside one window | Real start and end tokens | The normal case. |
| Answer split across a window boundary | `(0, 0)` for windows that hold only part of it | A window with a partial answer counts as a negative example. The overlapping stride exists so that some window holds the whole answer. |
| Answer in the overlap of two windows | Real labels in both windows | The same answer is a positive example twice. |
| Answer starts or ends mid-word | The whole subword token is labeled | The label covers a few extra characters. Decoding then returns the full word pieces. |
| Unanswerable (SQuAD v2) | `(0, 0)` in every window | The empty `answer_start` list must be handled, as in the code above. |
| Several reference answers | Only the first is used | The first answer is a common training choice. The metric uses all references. |
A stride that is too small is a quiet source of trouble. If the answer is longer than the overlap, no window may contain it whole, and every window then trains the model to predict [CLS].
Common errors
- Using the concatenated-string index. Offsets refer to the original context. If you build a string like
question + contextyourself, the character positions shift and every label is wrong. - Using a slow tokenizer. Only fast tokenizers return
offset_mapping. Calling the function with a slow tokenizer raisesNotImplementedError. - Forgetting that
endis exclusive in offsets.answer_end = answer_start + len(text)is exclusive too, which is why the comparisons use>=and<=in the way shown. - Padding on the left. Some models pad on the left. The code works because it searches by sequence ID and not by fixed positions, but any hard-coded
[CLS]index of 0 would break. Checktokenizer.cls_token_idand the padding side for non-BERT models. - Dataset answers that do not match the context. If
answer_startdoes not point at the answer text, the label is silently wrong. A quick check iscontext[a:a+len(t)] == tfor a sample of rows.
Checking your labels
Always decode some labels before training. For several windows, take input_ids[s : e + 1], decode them, and compare the result with the reference answer text. Differences in casing or spacing are expected. Missing words are not. Also count how many windows have (0, 0). A large share on a dataset where most questions are answerable suggests the stride or max_length is too small.
Exercise
A context is split into two windows with max_length=384 and stride=128. The answer lies only in the first window. What are the start and end labels for the second window, and why does the training code use that value?
Show answer
Both labels are 0, the [CLS] position. The second window does not contain the answer, so the check on the first and last context offsets fails and the function returns (0, 0). Training the model to point at [CLS] for windows without the answer teaches it to give a low span score there. The same value is also the null-answer target for unanswerable questions.
Exercise
Your fine-tuned model returns empty or very short answers on almost every example, and about 60% of windows in your processed training set have labels (0, 0) even though nearly all questions are answerable. Name two likely causes in the label code.
Show answer
The stride (or max_length) is too small, so windows rarely contain the whole answer. Or the offsets and character positions are mismatched, for example because the context was changed after the answer positions were computed, or because the offsets were taken from a concatenated string. Both make the containment check fail, so the function returns (0, 0) for most windows.