Sub topic 11
Fine-tuning a model on your own data
Pretrained summarisation and translation models work well on general text. They often fall short on your own domain, house style, or vocabulary. Fine-tuning continues training a pretrained encoder-decoder model on your own source-target pairs, so it picks up your conventions without learning language from scratch.
This chapter assumes you know the following:
- The encoder-decoder architecture and teacher forcing from earlier chapters.
- The Hugging Face
transformerstokeniser andgenerateAPIs. - Basic PyTorch training ideas such as batches, epochs and learning rate.
The code assumes transformers 4.46 or later, plus datasets, evaluate, rouge_score and accelerate.
When fine-tuning is worth it
Try the pretrained model first. Fine-tune when one of these applies:
- Domain vocabulary. Legal, medical or product text contains terms the model mistranslates or paraphrases badly.
- Output format. You need summaries of a fixed length, a fixed structure, or a particular tone.
- A language pair or task with no good public model. Here you start from a multilingual model such as mBART.
- Consistency. Prompting or decoding tweaks do not give stable enough output.
Fine-tuning needs pairs of (input, desired output). A few hundred clean pairs can shift style and terminology. Thousands are better for new content skills. Quality matters more than quantity, because the model copies whatever pattern the targets show, including their errors.
The workflow
The steps are the same for summarisation and translation. Only the data and the metric change.
Preparing the data
Store the data as JSON Lines, one example per line. This chapter uses the field names document and summary. For translation you would use fields such as en and de.
{"document": "The city council voted on Tuesday to expand the bike lane network by 40 kilometres over three years.", "summary": "The council approved 40 km of new bike lanes."}Make the validation split before you do anything else. Keep it free of near-duplicates of training items, because leaked duplicates inflate scores and hide overfitting.
The tokenisation step turns each pair into input_ids, attention_mask and labels. The code below fine-tunes t5-small, so it adds the summarize: prefix that T5 was pretrained with.
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, DataCollatorForSeq2Seq
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
raw = load_dataset(
"json",
data_files={"train": "train.jsonl", "validation": "valid.jsonl"},
)
PREFIX = "summarize: "
MAX_SOURCE = 512
MAX_TARGET = 64
def preprocess(batch):
inputs = [PREFIX + doc for doc in batch["document"]]
model_inputs = tokenizer(inputs, max_length=MAX_SOURCE, truncation=True)
labels = tokenizer(
text_target=batch["summary"], max_length=MAX_TARGET, truncation=True
)
model_inputs["labels"] = labels["input_ids"]
return model_inputs
tokenized = raw.map(
preprocess, batched=True, remove_columns=raw["train"].column_names
)
collator = DataCollatorForSeq2Seq(tokenizer, model=model)Three details matter here.
- Truncation lengths.
MAX_SOURCEandMAX_TARGETset the longest input and target the model sees. Inputs longer thanMAX_SOURCEare cut, so the model never sees the end of long documents. Check the length distribution of your data before choosing these numbers. Memory use grows quickly with source length. text_target. The tokeniser encodes the target as a target sequence. For some models, such as mBART and Marian, this uses the target-language tokeniser setup. Encoding targets as ordinary inputs is a common source of subtly wrong results.- The collator.
DataCollatorForSeq2Seqpads each batch to its longest example. It padslabelswith-100, the index that PyTorch's cross-entropy loss ignores. If you passmodel=model, it also buildsdecoder_input_idsby shifting the labels right. This is the teacher forcing setup from the earlier chapter.
Training with Seq2SeqTrainer
Seq2SeqTrainer extends Trainer with generation during evaluation. With predict_with_generate=True, validation runs generate, not just a teacher-forced forward pass. This matters because validation loss does not tell you how good the generated text is. The metric function below scores the generated text with ROUGE.
import numpy as np
import evaluate
from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments
rouge = evaluate.load("rouge")
def compute_metrics(eval_pred):
preds, labels = eval_pred
if isinstance(preds, tuple):
preds = preds[0]
preds = np.where(preds != -100, preds, tokenizer.pad_token_id)
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
scores = rouge.compute(
predictions=decoded_preds, references=decoded_labels, use_stemmer=True
)
return {k: round(v * 100, 2) for k, v in scores.items()}
args = Seq2SeqTrainingArguments(
output_dir="t5-small-summariser",
eval_strategy="epoch",
save_strategy="epoch",
learning_rate=3e-4,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
num_train_epochs=3,
weight_decay=0.01,
predict_with_generate=True,
generation_max_length=64,
generation_num_beams=4,
load_best_model_at_end=True,
metric_for_best_model="rougeL",
save_total_limit=2,
logging_steps=20,
report_to="none",
)
trainer = Seq2SeqTrainer(
model=model,
args=args,
train_dataset=tokenized["train"],
eval_dataset=tokenized["validation"],
data_collator=collator,
processing_class=tokenizer,
compute_metrics=compute_metrics,
)
trainer.train()
trainer.save_model("t5-small-summariser/final")
tokenizer.save_pretrained("t5-small-summariser/final")The np.where lines in compute_metrics matter. The trainer pads predictions and labels with -100, and the tokeniser cannot decode that value. Without the replacement you get an OverflowError or garbage text.
On older transformers versions, eval_strategy is called evaluation_strategy, and processing_class is called tokenizer.
Using the fine-tuned model
Load the saved folder like any other model. Add the same prefix you trained with.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
path = "t5-small-summariser/final"
tokenizer = AutoTokenizer.from_pretrained(path)
model = AutoModelForSeq2SeqLM.from_pretrained(path)
text = "summarize: The city council voted on Tuesday to expand the bike lane network by 40 kilometres over three years."
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
output_ids = model.generate(**inputs, num_beams=4, max_new_tokens=64)
print(tokenizer.decode(output_ids[0], skip_special_tokens=True))Choosing settings
These starting points work for small and medium models. Tune them against the validation score, not the training loss.
| Setting | Typical value | Notes |
|---|---|---|
| Learning rate, T5 | 1e-4 to 3e-4 | T5 tolerates larger rates with AdamW. |
| Learning rate, BART, mBART, Marian | 2e-5 to 5e-5 | Higher rates can destroy pretrained knowledge. |
| Epochs | 2 to 5 | Small datasets overfit fast. Watch the validation score. |
| Batch size | 8 to 32 | Use `gradient_accumulation_steps` if memory is short. |
| Source length | 512 to 1024 | Limited by the model's position handling and your GPU. |
| Beams at evaluation | 4 | Match the beams you plan to use in production. |
Model-specific points
- T5 needs its task prefix, both in training and at inference. Leave it out in one place and quality drops without any error.
- Marian models are bilingual and need no prefix. Fine-tune the model for your exact language pair and direction.
- mBART needs language codes. Set
tokenizer.src_langandtokenizer.tgt_langbefore tokenising. At generation time passforced_bos_token_id=tokenizer.lang_code_to_id[target_code](or the equivalent for your tokeniser version) so the decoder starts in the right language.
Common errors and edge cases
- Loss is NaN with T5 and
fp16=True. T5 activations overflow in half precision. Usebf16=Trueon supported hardware, or train in full precision. - Validation loss falls but ROUGE or BLEU stalls. Loss measures teacher-forced token accuracy. Generation quality depends on decoding. Track the generation metric and select the best checkpoint by it, as the code above does.
- Outputs copy the input or are too short. Check that the targets in your data have the length you want. The model learns the length distribution of your labels. Then set
min_lengthorlength_penaltyat generation time. - Catastrophic forgetting. Training for many epochs on a narrow dataset can make the model worse on general text. Use a lower learning rate, fewer epochs, or mix in some general data.
- Noisy targets. Summaries that contain facts missing from the source teach the model to hallucinate. Filter such pairs before training.
- Truncated targets. If
MAX_TARGETis shorter than many real targets, the model never learns to finish those outputs. Check how many examples hit the limit. - Overfitting on small data. If training loss drops while validation ROUGE drops too, stop earlier or add data. Early stopping through
load_best_model_at_endhelps.
You can also reduce memory use by freezing the embeddings or using parameter-efficient methods such as LoRA through the peft library. These train a small set of added weights and are a good option when the full model does not fit on your GPU. The workflow above stays the same.
Summary
Fine-tuning a sequence-to-sequence model means tokenising source and target pairs, padding labels with -100, training with teacher forcing, and evaluating by generating text. Use a learning rate suited to the model family, keep the same prefix or language codes in training and inference, and select checkpoints by a generation metric. The data matters most, because the model copies the patterns in your targets.
Exercise
During fine-tuning, the collator pads labels with -100 instead of the tokeniser's pad token ID. Why? What goes wrong in compute_metrics if you skip replacing -100 before decoding?
Show answer
The cross-entropy loss ignores positions whose label is -100, so padding does not contribute to the loss or push the model to predict pad tokens. Pad token IDs would be counted as real targets. The tokeniser has no vocabulary entry for -100, so batchdecode fails with an OverflowError or produces wrong text. Replacing -100 with tokenizer.padtokenid before decoding fixes this, and skipspecial_tokens=True then removes the padding from the decoded strings.
Exercise
You fine-tune t5-small for summarisation. Training loss keeps falling, but validation ROUGE-L peaks after epoch 2 and then declines. Name two settings in the chapter's code that handle this, and explain what each does.
Show answer
loadbestmodelatend=True with metricforbestmodel="rougeL" restores the checkpoint with the best validation ROUGE-L, which is the epoch 2 checkpoint, when training ends. Together with evalstrategy="epoch" and savestrategy="epoch", which evaluate and save once per epoch, it prevents the overfitted later epochs from being kept. Lowering numtrain_epochs to 2 or lowering the learning rate also addresses the cause directly, because the model overfits the small training set after epoch 2.