Sub topic 1
Why fine-tune a pretrained transformer
This chapter explains why we start from a pretrained model, how raw text becomes model input, how a classification head sits on top of the encoder, and how to split a labeled dataset before training.
Prerequisites
You should be comfortable with Python functions and dictionaries, know the difference between training and test sets, and have seen PyTorch tensors. You should also have a rough idea of what an embedding is. Install the libraries with pip install transformers datasets.
Why start from a pretrained model
A pretrained transformer has already learned language patterns from a very large text corpus. Training one from scratch on a few thousand labeled reviews would waste that signal and usually overfit. Fine-tuning reuses the pretrained weights and adjusts them slightly for your task, which typically needs far less data and compute.
Turning text into model inputs
A tokenizer splits text into tokens and maps each token to an integer ID. Truncation caps long texts at a fixed length, and padding makes a batch rectangular. The following code loads the IMDB dataset and tokenizes it.
from datasets import load_dataset
from transformers import AutoTokenizer
checkpoint = "distilbert-base-uncased"
raw = load_dataset("imdb")
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True, max_length=256)
tokenized = raw.map(tokenize, batched=True)Adding a classification head
The encoder outputs a vector for each input. A classification head is a small layer on top of it that turns that vector into one score per label. AutoModelForSequenceClassification attaches this head for you.
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=2)Preparing and splitting the dataset
Keep three splits. The training split updates the weights. The validation split guides choices such as the learning rate and the best epoch. The test split is used once, at the end, to report results. The code below carves a validation set from the training data and leaves the test set untouched.
split = raw["train"].train_test_split(test_size=0.1, seed=42)
train_ds = split["train"]
val_ds = split["test"]
test_ds = raw["test"]Setting a seed makes the split repeatable, so results can be compared across runs.
Exercise
Why should the validation split come from the training data instead of the test set?
Show answer
The test set must stay unused until the final evaluation. If you tune settings against it, the reported score becomes optimistic. The validation split lets you make those decisions safely.