Sub topic 3
Adding a Classification Head
Assume you know Python, PyTorch tensors, tokenization, and the difference between training, validation, and test data. This chapter focuses on how an encoder turns a sequence of hidden vectors into class predictions.
From an Encoder to a Classifier
A pretrained transformer encoder reads tokens and produces a contextual representation for each token. For an input with 20 tokens and a hidden size of 768, its output has a shape like:
(batch_size, 20, 768)
Each token vector includes information about that token and its surrounding words. A text classifier needs one vector for the whole input, followed by a small prediction layer called a classification head.
A classification head is usually a linear layer:
\text{logits} = hW + bHere, h is the sequence representation, W contains learned weights, and b is a bias. The output is a vector with one value for each class. These values are called logits. A larger logit means the model favors that class, but logits are not probabilities yet.
For binary sentiment classification, the head might output two logits:
| Class | Logit |
|---|---|
| NEGATIVE | -1.2 |
| POSITIVE | 2.4 |
The positive class has the larger logit. During training, cross-entropy loss compares these logits with the correct label.
Choosing the Sequence Representation
The encoder produces one vector per token, so the model must select or combine them. Common strategies include:
- Use the special
[CLS]vector. BERT-style encoders place this vector at the beginning of the sequence and train it to summarize the input. - Use mean pooling. Average the vectors for all non-padding tokens.
- Use an architecture-specific pooled output.
The exact strategy depends on the encoder. AutoModelForSequenceClassification knows the appropriate structure for many pretrained checkpoints and attaches a compatible head automatically.
import torch
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
)
checkpoint = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForSequenceClassification.from_pretrained(
checkpoint,
num_labels=2,
id2label={0: "NEGATIVE", 1: "POSITIVE"},
label2id={"NEGATIVE": 0, "POSITIVE": 1},
)
texts = [
"The story was warm and funny.",
"The movie was confusing and dull.",
]
batch = tokenizer(texts, padding=True, truncation=True, return_tensors="pt")
with torch.no_grad():
output = model(**batch)
print(output.logits.shape)
print(output.logits)For two inputs and two classes, output.logits.shape is:
torch.Size([2, 2])The model starts with a pretrained encoder, but the classification head is newly initialized. Its initial predictions are therefore not useful. Fine-tuning updates the head and usually updates at least some encoder weights as well.
Labels and Loss
A label is normally an integer from 0 through num_labels - 1. For the example above:
0meansNEGATIVE.1meansPOSITIVE.
When you pass a labels tensor to a sequence-classification model, Transformers can calculate the loss:
labels = torch.tensor([1, 0])
output = model(**batch, labels=labels)
print(output.loss.item())The loss is a single number summarizing how far the predictions are from the correct labels. The training loop uses its gradients to update the classification head and the selected encoder parameters.
The number of labels must match the task. Use one output per class for ordinary single-label classification. For multi-label classification, where one text can have several independent labels, use a different loss setup and usually one sigmoid score per label.
Full Fine-Tuning and Frozen Encoders
In full fine-tuning, gradients update both the classification head and the encoder. This often gives the best accuracy when you have enough labeled data and computing resources.
You can also freeze the encoder and train only the head. This is faster and uses less memory, but the fixed representations may not fit your task well. Parameter-efficient methods such as LoRA provide another option: they keep most original weights frozen and train small adapter parameters.
Exercise
A model returns logits with shape (32, 4) for a batch of 32 examples. What does the 4 represent, and which class is predicted for one example?
Show answer
The 4 represents four possible classes. For one example, the predicted class is the index of its largest logit.