Sub topic 13
Fine-tuning a Model on Question Answering Data
This chapter assumes you know basic Python, tokenization, PyTorch-style tensors, and the difference between a pretrained language model and a neural network. It focuses on how training examples become token labels and how a transformer learns to predict answer spans.
From character answers to token labels
SQuAD-style data stores an answer as text plus its character position in the context:
{
"question": "What does the basin cover?",
"context": "Its drainage basin covers seven million square kilometres.",
"answers": {
"text": ["seven million square kilometres"],
"answer_start": [25]
}
}The model cannot train directly on character positions. After tokenization, it needs two integer labels:
start_positions: the token where the answer begins.end_positions: the token where the answer ends.
Offset mappings connect these representations. For each token, an offset contains the character range that produced it. The preprocessing code finds the first token covering the answer's start character and the last token covering its end character.
A long context may produce several overlapping features. If a feature does not contain the answer, both labels point to the [CLS] token. This teaches the model that the answer is absent from that window.
Fine-tuning objective
A question-answering model adds two classification heads above the transformer encoder. One head produces a start logit for every token, and the other produces an end logit for every token. A logit is an unnormalized score.
During fine-tuning, cross-entropy loss compares each head's scores with the correct start or end label. The total loss is usually the average of the two losses. Backpropagation then updates both the added heads and the pretrained encoder.
The following example loads a small part of SQuAD, creates overlapping features, aligns labels, and trains for one epoch.
from datasets import load_dataset
from transformers import (
AutoModelForQuestionAnswering,
AutoTokenizer,
Trainer,
TrainingArguments,
)
model_name = "distilbert-base-cased-distilled-squad"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForQuestionAnswering.from_pretrained(model_name)
dataset = load_dataset("squad", split="train[:2%]")
def prepare_features(examples):
encoded = tokenizer(
examples["question"],
examples["context"],
max_length=384,
truncation="only_second",
stride=128,
return_overflowing_tokens=True,
return_offsets_mapping=True,
padding="max_length",
)
offsets = encoded.pop("offset_mapping")
sample_map = encoded.pop("overflow_to_sample_mapping")
starts, ends = [], []
for feature_index, feature_offsets in enumerate(offsets):
sample_index = sample_map[feature_index]
sequence_ids = encoded.sequence_ids(feature_index)
context_tokens = [
i for i, sequence_id in enumerate(sequence_ids)
if sequence_id == 1
]
cls_index = encoded["input_ids"][feature_index].index(
tokenizer.cls_token_id
)
answer = examples["answers"][sample_index]
if not answer["answer_start"]:
starts.append(cls_index)
ends.append(cls_index)
continue
answer_start = answer["answer_start"][0]
answer_end = answer_start + len(answer["text"][0])
context_start = context_tokens[0]
context_end = context_tokens[-1]
if (
feature_offsets[context_start][0] > answer_start
or feature_offsets[context_end][1] < answer_end
):
starts.append(cls_index)
ends.append(cls_index)
continue
start = context_start
while (
start <= context_end
and feature_offsets[start][0] <= answer_start
):
start += 1
end = context_end
while end >= context_start and feature_offsets[end][1] >= answer_end:
end -= 1
starts.append(start - 1)
ends.append(end + 1)
encoded["start_positions"] = starts
encoded["end_positions"] = ends
return encoded
features = dataset.map(
prepare_features,
batched=True,
remove_columns=dataset.column_names,
)
training_args = TrainingArguments(
output_dir="qa-checkpoint",
learning_rate=3e-5,
per_device_train_batch_size=8,
num_train_epochs=1,
weight_decay=0.01,
report_to="none",
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=features,
)
trainer.train()The stride creates duplicate training features around window boundaries. That duplication is intentional: it gives the model multiple chances to see an answer that lies near a boundary.
Common training errors
- Using character positions as labels: the model expects token indices.
- Ignoring overflow windows: answers in truncated text become incorrectly labeled as missing.
- Keeping question tokens eligible: the model may select words from the question instead of the context.
- Swapping start and end labels: every valid span must satisfy
start_position <= end_position. - Training only the new heads unintentionally: freezing the encoder can be useful for experiments, but ordinary fine-tuning updates the encoder too.
- Overfitting a small dataset: training loss can fall while answers on new topics become worse. Use a validation split and evaluate exact match and F1.
Exercise
A feature contains the answer text, but its character range falls outside the feature's context offsets. What labels should preprocessing assign?
Show answer
Assign the feature's CLS token index to both startpositions and endpositions, marking that window as having no answer.