Sub topic 13
Fine-tuning a model on question answering data
This chapter assumes you have read the earlier chapters on the span prediction head and on building token-level labels. You should also be comfortable with Hugging Face datasets, Trainer, and PyTorch tensors. Here you put those pieces together and train a model that answers questions about passages.
What fine-tuning changes
A pretrained encoder such as DistilBERT knows language but has no idea what an answer span is. Fine-tuning adds a small linear layer on top of the encoder. This layer maps each token's hidden vector to two numbers, a start logit and an end logit. The whole network then trains on SQuAD-style examples.
The loss is the average of two cross-entropy terms:
- one over the start logits, with the labeled start token as the target
- one over the end logits, with the labeled end token as the target
Each window of tokens is treated as a classification problem with one class per token position. This is why the labels must be token indices, not character positions.
The training and validation sides need different preprocessing. Training needs labels. Validation needs the offset mappings kept, so predictions can be mapped back to the original text.
Step 1: Load the data and the model
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
checkpoint = "distilbert-base-cased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForQuestionAnswering.from_pretrained(checkpoint)
raw = load_dataset("squad")
train_raw = raw["train"].select(range(4000)) # small subset for a quick run
val_raw = raw["validation"].select(range(500))
print(train_raw[0]["answers"])We start from distilbert-base-cased, not from the SQuAD-tuned checkpoint used earlier. The base checkpoint has an untrained span head, and the warning "Some weights ... newly initialized" is expected. The subsets keep the run short. Remove select to train on the full 88k examples.
Step 2: Build training features
This step uses the label-alignment logic from the previous chapter. The helper below is that logic, included so the script runs on its own.
def char_to_token_span(offsets, sequence_ids, answer_start, answer_end):
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, end
MAX_LEN, STRIDE = 384, 128
def prepare_train_features(examples):
questions = [q.strip() for q in examples["question"]]
enc = tokenizer(
questions, examples["context"],
max_length=MAX_LEN, truncation="only_second", stride=STRIDE,
return_overflowing_tokens=True, return_offsets_mapping=True,
padding="max_length",
)
offset_mapping = enc.pop("offset_mapping")
sample_map = enc.pop("overflow_to_sample_mapping")
start_positions, end_positions = [], []
for i, offsets in enumerate(offset_mapping):
answer = examples["answers"][sample_map[i]]
start_char = answer["answer_start"][0]
end_char = start_char + len(answer["text"][0])
s, e = char_to_token_span(offsets, enc.sequence_ids(i), start_char, end_char)
start_positions.append(s)
end_positions.append(e)
enc["start_positions"] = start_positions
enc["end_positions"] = end_positions
return enc
train_ds = train_raw.map(
prepare_train_features, batched=True, remove_columns=train_raw.column_names
)
print(len(train_raw), "examples ->", len(train_ds), "training windows")Three details matter here:
- One example can become several windows. The tokenizer's
overflow_to_sample_mappingtells you which original example each window came from. You must use it to look up the right answer. - Windows without the answer get label (0, 0). The model learns to point at
[CLS]when the answer is not in that window. This is the same convention used for unanswerable questions in SQuAD v2. remove_columnsis required.mapwould otherwise return the old columns next to the new ones. The lengths no longer match, so the call fails.
Step 3: Build validation features
Validation windows keep their offsets and an example_id. Offsets for tokens outside the context are set to None, so the decoder can never select them.
def prepare_val_features(examples):
questions = [q.strip() for q in examples["question"]]
enc = tokenizer(
questions, examples["context"],
max_length=MAX_LEN, truncation="only_second", stride=STRIDE,
return_overflowing_tokens=True, return_offsets_mapping=True,
padding="max_length",
)
sample_map = enc.pop("overflow_to_sample_mapping")
enc["example_id"] = []
for i in range(len(enc["input_ids"])):
enc["example_id"].append(examples["id"][sample_map[i]])
seq_ids = enc.sequence_ids(i)
enc["offset_mapping"][i] = [
o if seq_ids[k] == 1 else None
for k, o in enumerate(enc["offset_mapping"][i])
]
return enc
val_ds = val_raw.map(
prepare_val_features, batched=True, remove_columns=val_raw.column_names
)Step 4: Train
import torch
from transformers import TrainingArguments, Trainer, default_data_collator
args = TrainingArguments(
output_dir="distilbert-squad-demo",
learning_rate=3e-5,
num_train_epochs=2,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
weight_decay=0.01,
warmup_ratio=0.1,
fp16=torch.cuda.is_available(),
save_strategy="no",
report_to="none",
)
trainer = Trainer(
model=model,
args=args,
train_dataset=train_ds,
data_collator=default_data_collator, # inputs are already padded to MAX_LEN
)
trainer.train()default_data_collator is enough because every window has the same length, so no dynamic padding is needed. If you pad dynamically instead, use DataCollatorWithPadding and drop padding="max_length". Dynamic padding is faster on short contexts. Fixed padding is simpler to debug.
The settings in the table are good starting points for SQuAD.
| Setting | Typical value | Why |
|---|---|---|
| Learning rate | 2e-5 to 5e-5 | Larger values often destabilize a pretrained encoder |
| Epochs | 2 to 3 | SQuAD overfits after a few passes |
| Max length | 384 | Covers most SQuAD contexts in one window |
| Stride | 128 | Overlap large enough that an answer is whole in at least one window |
| Warmup | about 10% of steps | Protects the new, randomly initialized head early on |
Step 5: Predict and post-process
Training loss is not a useful quality number for this task. You need answer strings, so you must decode predictions and score them.
import collections
import numpy as np
import evaluate
def postprocess(examples, features, start_logits, end_logits,
n_best=20, max_answer_len=30):
windows_of = collections.defaultdict(list)
for idx, ex_id in enumerate(features["example_id"]):
windows_of[ex_id].append(idx)
predictions = []
for ex in examples:
best_text, best_score = "", float("-inf")
for w in windows_of[ex["id"]]:
offsets = features[w]["offset_mapping"]
sl, el = start_logits[w], end_logits[w]
for s in np.argsort(sl)[-n_best:][::-1]:
for e in np.argsort(el)[-n_best:][::-1]:
if offsets[s] is None or offsets[e] is None:
continue
if e < s or e - s + 1 > max_answer_len:
continue
score = sl[s] + el[e]
if score > best_score:
best_score = score
best_text = ex["context"][offsets[s][0]:offsets[e][1]]
predictions.append({"id": ex["id"], "prediction_text": best_text})
return predictions
model_inputs = val_ds.remove_columns(["example_id", "offset_mapping"])
output = trainer.predict(model_inputs)
start_logits, end_logits = output.predictions
preds = postprocess(val_raw, val_ds, start_logits, end_logits)
refs = [{"id": ex["id"], "answers": ex["answers"]} for ex in val_raw]
metric = evaluate.load("squad")
print(metric.compute(predictions=preds, references=refs))The post-processor scores every window of an example and keeps the best-scoring span across all of them. This is how overlapping windows are combined. Because the logits come from separate forward passes, the scores are comparable only approximately. This approximation works well in practice.
With 4,000 training examples and two epochs, expect an F1 in the range of 60 to 75. Training on the full set for two to three epochs should reach roughly 85 or higher for DistilBERT.
Common errors
- Metric near zero. Check that the
idvalues in predictions match the references exactly. The metric matches on them. - Every prediction is an empty string. The model is picking
[CLS], or all spans are filtered out. In SQuAD v1 every question has an answer, so this usually means the labels are wrong. Print a few(start_positions, end_positions)pairs and decode the tokens between them. They should spell out the answer. - Many (0, 0) labels. Some windows legitimately have no answer. If most do,
STRIDEmay be too small, ormax_lengthtoo short for your contexts. - Shape mismatch inside
map. You returned fewer or more rows than the inputs without removing the old columns. - Out-of-memory. Lower the batch size, lower
MAX_LEN, or use gradient accumulation (gradient_accumulation_steps).
Training on SQuAD v2
SQuAD v2 adds questions with no answer. The recipe barely changes:
- For an unanswerable example,
answers["text"]is empty. Guard your label code so that it assigns (0, 0) instead of readinganswer["text"][0]. - At decoding time, compare the best span score with the null score
start_logits[0] + end_logits[0]. Return an empty string when the null score wins by more than a threshold. Tune that threshold on validation data. - Load the
squad_v2metric, which also needs ano_answer_probabilityfield in each prediction.
Exercise
A SQuAD context is split into three windows. The answer lies entirely in window 2. What labels do windows 1 and 3 receive, and why does this not hurt the model?
Show answer
Windows 1 and 3 receive start and end positions of (0, 0), the [CLS] position, because the answer is not inside them. This teaches the model to signal "no answer here" for such windows. At prediction time the post-processor skips [CLS] in SQuAD v1 style decoding and keeps the best span over all windows, so the confident span from window 2 wins.
Exercise
After training, exact match is 0.0 although the training loss decreased. List two checks you would run before changing the learning rate.
Show answer
First, confirm that the prediction ids match the reference ids and that prediction_text holds strings, not token ids. Second, decode the tokens between a few labeled start and end positions to see if they reproduce the gold answer text. If the labels are misaligned, the loss can still fall while the model learns the wrong spans.