6 Fine-tuning for classification

Language Models · v1.0.5

2026-11-03 01:40:27

Where we are

Where this fits

Figure 6.1 Stage 3, step 8: fine-tuning a pretrained LLM as a classifier.

Built so far

  • the GPT architecture, implemented from scratch
  • pretraining on unlabeled text
  • OpenAI’s pretrained weights loaded into GPTModel

Still missing

  • the model completes text fluently and knows no task

This unit: a 124M-parameter model, ~1,000 labeled examples, five epochs, 95.67% test accuracy.

Outline of key topics

  • Two kinds of fine-tuning, and what each one buys.
  • Preparing a balanced, rectangular classification dataset.
  • Freezing most of the network and replacing the output head.
  • Reading the prediction from the last token position.
  • Cross-entropy to optimize, accuracy to report.
  • Fine-tuning, evaluating, and deploying the classifier.

Two kinds of fine-tuning

Classification against instruction

Figure 6.3 A classification fine-tuned model needs no instruction alongside the input, and answers only within its label set.

Instruction fine-tuning

  • trained on natural-language instructions
  • versatile; demands large data and compute

Classification fine-tuning

  • trained on a fixed, known set of labels
  • modest data and compute; confined to those classes

A classification fine-tuned model predicts only classes seen in training.

The spam dataset

Balance and splits

Figure 6.4 The three-stage process for classification fine-tuning.
  • SMS Spam Collection: 5,572 messages tagged ham or spam
  • the raw counts are 4,825 against 747 — a constant “ham” answer would score well and teach nothing
  • undersampling shrinks the majority class to 747, giving a balanced set of 1,494
  • labels map to integers: ham \(\to 0\), spam \(\to 1\)
  • shuffled, then split 70/10/20 into train, validation and test

A balanced set makes 50% the floor and the accuracy figure directly readable.

Rectangular batches

Figure 6.6 Shorter sequences padded with token ID 50256 to the length of the longest.

Figure 6.7 One training batch: eight messages of token IDs with their class labels.
  • messages vary in length; a batch must be a rectangular tensor
  • truncation is cheap but discards content; padding preserves it
  • the pad token is 50256 (<|endoftext|>), from the same GPT-2 tokenizer
  • the training split fixes the common length at 120 tokens, well inside GPT-2’s 1,024-token context
  • batch size 8 gives a \((8, 120)\) tensor of IDs beside an \((8,)\) tensor of labels

One integer target per example, not one target per position.

Adapting the pretrained model

Freezing and the new head

Figure 6.10 The final LayerNorm and the last transformer block train; the other eleven blocks and the embeddings stay frozen.
for p in model.parameters():
    p.requires_grad = False

model.out_head = nn.Linear(768, 2)
  • lower layers capture general language structure; upper layers are task-specific
  • the \(768 \rightarrow 50257\) vocabulary projection is replaced by a \(768 \rightarrow 2\) head
  • the head alone suffices; unfreezing the last block and final LayerNorm measurably improves results
  • fewer trainable parameters means faster training and less overfitting on ~1,000 examples

The last token position

Figure 6.12 The last token is the only position whose attention reaches every preceding token.
  • a four-token input now yields a \(4 \times 2\) tensor of logits
  • one prediction per example is wanted, so only the last row is kept

\[\text{logits}[:, -1, :]\]

  • the reason is the causal attention mask: each position attends to itself and what precedes it

The last token accumulates the most information, being the only one with access to all the others.

Loss and accuracy

Two metrics, one of them differentiable

Figure 6.14 The label is the index of the largest logit; before training the prediction is wrong.

\[\hat{y} = \arg\max_c \; \text{logits}[-1, c]\]

  • softmax is unnecessary — it does not move the largest position
  • cross-entropy on the last-position logits is what is optimized; accuracy is what is reported
  • before fine-tuning: 46.25% train, 45.00% validation, 48.75% test — the random-guess floor

Both metrics read the same single position. That restriction is the whole adaptation of the pretraining evaluation code.

Fine-tuning the classifier

The loop

for epoch in range(n_epochs):
  for x, y in train_loader:
    logits = model(x)[:, -1, :]
    loss = cross_entropy(logits, y)
    loss.backward()
    opt.step()
    opt.zero_grad()
    report(accuracy(model, val_loader))
  • the pretraining loop, with one change: each epoch reports classification accuracy rather than a text sample
  • the optimizer receives every parameter; frozen ones simply get no gradient
  • AdamW, learning rate \(5\times10^{-5}\), weight decay \(0.1\), five epochs
  • about six minutes on a laptop CPU

Results

Figure 6.16 Training and validation loss across five epochs.

Figure 6.17 Training and validation accuracy across five epochs.
  • epoch 1: 70.00% training accuracy
  • epoch 5: 100.00% training, 97.50% validation

Over the full loaders

  • 97.21% training
  • 97.32% validation
  • 95.67% test

No noticeable gap between the training and validation losses: little indication of overfitting.

Using the classifier

Inference mirrors training

def classify(text, model, tok, max_len):
    ids = tok.encode(text)
    ids = pad_or_cut(ids, max_len, EOT)
    out = model(as_batch(ids))[:, -1, :]
    return argmax(out) == 1   # 1 = spam
  • the preprocessing at inference repeats the preprocessing at training, step for step
  • a mismatch raises no error; it silently degrades accuracy.
  • persistence saves the weights only, never the architecture
  • reloading requires reconstructing the same configuration with the same replaced head

Summary

Summary

  • Classification fine-tuning replaces the vocabulary projection with a small class head; only the target changes, from the next token to a class label.
  • The prediction is read from the last token position, because causal masking gives that position access to every preceding token — an architectural property, not a convenience.
  • Most of the pretrained network stays frozen: the last transformer block, the final LayerNorm and the new head carry the adaptation.
  • Cross-entropy remains the training objective; accuracy is added for reporting, since accuracy is not differentiable.

One thing, done well

What this model is

  • a spam detector with 95.67% test accuracy
  • asked anything else, it has no answer
  • the head that could produce words is gone

Next: 7 Fine-tuning to follow instructions

  • keeps the language modeling head
  • trains on prompt–response pairs instead of labels
  • builds the generalist this unit declined to build

The dataset preparation, freezing and training-loop patterns all reappear; the target and the measure of success are what change.