Sub topic 11
Fine-tuning a Model on Your Own Data
Assume you know basic Python, PyTorch tensors, Transformer attention, and loss functions. You should also understand that an encoder-decoder model reads a source sequence and generates a target sequence one token at a time.
Fine-tuning adapts a pretrained model to a narrower task or writing style. For summarisation, each training example contains a document and a reference summary. For translation, it contains a source sentence and its human translation.
Prepare paired data
A dataset for sequence-to-sequence fine-tuning has two text fields:
source: the input document or sentence.target: the desired output.
Keep training, validation, and test examples separate. The validation set helps you choose settings during training. The test set should remain untouched until the final evaluation.
| Task | Source | Target |
|---|---|---|
| Summarisation | A news article | Its reference summary |
| Translation | An English sentence | Its German translation |
Remove examples with missing targets, accidental duplicates, or badly aligned pairs. A source and target that do not describe the same content teach the model an incorrect mapping.
Tokenise inputs and targets
Tokenisation converts text into integer token IDs. The tokenizer must use the same vocabulary and special tokens as the pretrained model. Input and target lengths should be limited to fit the model's context window.
The following example fine-tunes t5-small on a small summarisation dataset. The dataset is intentionally tiny so the script is easy to run. A real model needs many more varied examples.
from datasets import Dataset
from transformers import (
AutoModelForSeq2SeqLM,
AutoTokenizer,
DataCollatorForSeq2Seq,
Seq2SeqTrainer,
Seq2SeqTrainingArguments,
)
model_name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
data = Dataset.from_dict({
"source": [
"summarize: The council approved a plan to add 40 kilometres of bike lanes over three years.",
"summarize: The library will close on Monday for renovations and reopen with new study rooms in June.",
"summarize: The airline added two evening flights between the cities for the summer schedule.",
],
"target": [
"The council approved 40 km of new bike lanes.",
"The library will close for renovations and reopen in June.",
"The airline added two evening flights for summer.",
],
})
splits = data.train_test_split(test_size=1, seed=42)
def tokenize_batch(batch):
return tokenizer(
batch["source"],
text_target=batch["target"],
max_length=256,
truncation=True,
)
tokenized = splits.map(tokenize_batch, batched=True, remove_columns=data.column_names)
collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=model)
args = Seq2SeqTrainingArguments(
output_dir="t5-summary-checkpoint",
per_device_train_batch_size=2,
learning_rate=5e-5,
num_train_epochs=3,
predict_with_generate=True,
save_strategy="no",
logging_steps=1,
report_to="none",
)
trainer = Seq2SeqTrainer(
model=model,
args=args,
train_dataset=tokenized["train"],
eval_dataset=tokenized["test"],
tokenizer=tokenizer,
data_collator=collator,
)
trainer.train()
trainer.save_model("t5-summary-finetuned")
tokenizer.save_pretrained("t5-summary-finetuned")The data collator pads examples in each batch. For labels, padding is normally replaced with -100. PyTorch's cross-entropy loss ignores those positions, so padding does not affect the update.
What happens during training
The encoder processes the source text. During training, the decoder receives the correct previous target tokens through teacher forcing and predicts the next token. Cross-entropy measures the difference between those predictions and the reference target. Backpropagation updates the model weights.
Important settings include:
learning_rate: how far each update moves the weights. A rate that is too high can damage pretrained knowledge.num_train_epochs: how many passes the model makes over the training data.max_length: the maximum number of tokens retained for an input or target.per_device_train_batch_size: examples processed together on each device.
Watch for overfitting. If training loss falls while validation quality worsens, stop earlier, add data, or reduce the learning rate. For translation, choose a checkpoint trained for the required language pair. For multilingual models such as mBART, configure the source and target language codes as required by that model.
Exercise
Why should the test set not be used to choose the learning rate or number of epochs?
Show answer
Repeatedly making decisions from test results makes the test set part of training indirectly. A separate validation set should guide those decisions, while the test set measures final generalisation.