Sub topic 3
Adding a classification head
This chapter assumes you know Python, have seen PyTorch tensors, and understand what an embedding and a loss function are. You should also have read the previous chapter, where the tokenizer turned text into input_ids and attention_mask.
A pretrained encoder produces one vector per token. It does not produce a label. The classification head is the small set of new layers that turns those vectors into one score per class. This chapter covers what the head contains, how it is attached, what the model returns, and the mistakes that most often go wrong at this step.
What the encoder gives you
For a batch of B texts padded to T tokens, a DistilBERT encoder returns hidden states of shape [B, T, 768]. Each token position has a 768-dimensional vector that depends on every other token in the sequence. Classification needs one vector per text, so the head must pick or combine positions.
The standard choice for BERT-style encoders is to use the vector at position 0. The tokenizer puts the special [CLS] token there. During pretraining and fine-tuning, attention lets that position gather information from the whole sequence. Mean-pooling over all non-padding tokens is a common alternative, but the Hugging Face sequence-classification classes use the first token.
Loading a model with a head
AutoModelForSequenceClassification loads the pretrained encoder weights and adds a head on top. The from_pretrained call picks the right class from the checkpoint's config, so the same line works for BERT, RoBERTa, and DistilBERT.
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
checkpoint = "distilbert-base-uncased"
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {v: k for k, v in id2label.items()}
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForSequenceClassification.from_pretrained(
checkpoint, num_labels=2, id2label=id2label, label2id=label2id
)
print(type(model).__name__)
print(model.pre_classifier)
print(model.classifier)You will see a warning that some weights "were not initialized from the model checkpoint" and are "newly initialized". The warning is expected. The checkpoint was pretrained with a masked-language-modeling objective, so it has no weights for pre_classifier or classifier. Those layers start with random values, and fine-tuning is what trains them.
What the head is made of
The exact layers depend on the architecture:
| Model family | Head layers on the first-token vector |
|---|---|
| DistilBERT | `pre_classifier` (Linear 768 to 768), ReLU, dropout, `classifier` (Linear 768 to `num_labels`) |
| BERT | Pooler (Linear 768 to 768 with tanh, pretrained), dropout, `classifier` (Linear 768 to `num_labels`) |
| RoBERTa | Dense (768 to 768), tanh, dropout, output projection (768 to `num_labels`) |
For DistilBERT with two labels, the head has about 592,000 parameters. The encoder has about 66 million. The head is under 1% of the model, and it is the only part that starts from random values.
The forward pass: logits, probabilities, loss
The model returns logits, which are raw unnormalized scores, one per class. A logit can be any real number. To get probabilities you apply softmax across the class dimension.
texts = ["A warm, funny film with a great cast.", "Two hours I will never get back."]
batch = tokenizer(texts, padding=True, return_tensors="pt")
model.eval()
with torch.no_grad():
out = model(**batch)
print(out.logits.shape) # torch.Size([2, 2]): batch size x number of labels
probs = torch.softmax(out.logits, dim=-1)
print(probs) # each row sums to 1
labels = torch.tensor([1, 0])
with torch.no_grad():
out = model(**batch, labels=labels)
print(out.loss) # a scalar; close to ln(2) = 0.693 for an untrained headWhen you pass labels, the model also computes the loss. For ordinary single-label classification the loss is cross-entropy, which combines softmax and negative log-likelihood in one numerically stable operation. This is why the head outputs logits and not probabilities. Applying softmax yourself before the loss would be a bug, because cross-entropy would apply it a second time.
The Trainer relies on this behavior. It calls the model with labels included and reads loss from the output. That is why your dataset column must end up named labels. If your dataset has a column named label, the default data collator renames it for you. A column with any other name is silently ignored, and the model then returns no loss.
Label count and label names
Two arguments define the head's output layer.
num_labelssets the output size of the final linear layer.id2labelandlabel2idstore the mapping between integer ids and names in the model config.
The names do not affect training. They matter later, because the inference pipeline reads id2label to show POSITIVE instead of LABEL_1. Setting them now means the saved model carries its own label names.
The label ids must be integers from 0 to num_labels - 1. A dataset with labels 1 and 2, or with string labels, will fail with an index error in the loss, or on a GPU with an unhelpful device-side assert. Convert string labels to ids before training.
Problem types
The same class handles three tasks. The loss is chosen from config.problem_type, which the library infers if you do not set it.
| Task | `num_labels` | Label format | Loss |
|---|---|---|---|
| Single-label classification | 2 or more | Integer class id | Cross-entropy |
| Multi-label classification | Number of tags | Float vector of 0 and 1 per tag | Binary cross-entropy with logits |
| Regression | 1 | Float | Mean squared error |
The inference rule is: num_labels == 1 means regression, integer labels mean single-label, and anything else means multi-label. Because the guess can be wrong, set it explicitly for multi-label work.
multi = AutoModelForSequenceClassification.from_pretrained(
checkpoint,
num_labels=3,
problem_type="multi_label_classification",
)For multi-label models, labels must be floats. A common failure is passing integer labels, which raises a dtype error in the loss.
Controlling what trains
By default every parameter trains, including the encoder. The pretrained weights are the reason fine-tuning works with little data, and a small learning rate keeps them from drifting far. Two alternatives exist.
- Full fine-tuning updates the encoder and the head. It usually gives the best accuracy and is what the next chapters use.
- Head-only training freezes the encoder and trains just the new layers. It is faster and uses less memory, but it is usually less accurate because the encoder's features were not shaped for your task.
Freezing is done by turning off gradients on the encoder parameters:
for param in model.base_model.parameters():
param.requires_grad = False
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(f"trainable: {trainable:,} of {total:,}")base_model is the encoder without the head, whatever the architecture. The head stays trainable because its parameters are not part of base_model. Chapter 12 covers LoRA, which sits between these two options.
Common errors
- Mismatched head size. Loading a checkpoint that already has a 3-class head with
num_labels=2raises a size-mismatch error. Passignore_mismatched_sizes=Trueto discard the old head and create a new one. - Treating the warning as an error. The "newly initialized" message is normal for the head only.
- Double softmax. Do not apply softmax to the logits before computing your own loss. Use softmax only to read probabilities.
- Wrong
num_labelsfor your data. If the dataset has 5 classes andnum_labels=2, training fails when a label of 4 reaches the loss. - Padding included in the vector. The first-token vector is not affected by padding at the end of the sequence, provided the
attention_maskis passed. Calling the model withinput_idsonly on a padded batch lets attention see the pad tokens and shifts the outputs. - Evaluating before training. An untrained head gives roughly uniform probabilities. Compare your first loss against
ln(num_labels). A first-step loss far above that suggests a bug in labels or learning rate.
Exercise
You load distilbert-base-uncased with num_labels=4 and run a batch of 8 texts through it with labels. What shape are the logits, roughly what loss do you expect before any training, and why is applying torch.softmax to the logits before passing them to your own torch.nn.functional.cross_entropy call a mistake?
Show answer
The logits have shape [8, 4]. With a randomly initialized head the classes are nearly equally likely, so the loss is close to ln(4), about 1.39. cross_entropy already applies log-softmax internally, so softmaxing first applies the normalization twice. That flattens the scores, gives wrong gradients, and the model trains poorly.
Exercise
A teammate fine-tunes for a tagging task where each review can have any of five tags at once. They set num_labels=5 and give integer labels [0, 1, 0, 0, 1], and the loss raises a dtype error. What two changes does the model need?
Show answer
Set problem_type="multi_label_classification" so the loss is binary cross-entropy with logits, and give the labels as float vectors, for example [0.0, 1.0, 0.0, 0.0, 1.0]. Without the explicit problem type, the library can mistake the labels for a single-label task.