Skip to content

Chapter 6 — Finetuning for Text Classification

At the end of Chapter 5, we loaded OpenAI’s pretrained GPT-2 weights and asked the model to continue a sentence. Here we keep what GPT-2 learned about language and change the question. Given a complete text message, can it decide whether the message is spam?

Book roadmap showing the pretrained model branching into a classifier and a personal assistant.

In Figure 6.1 we reach Stage 3 of Sebastian Raschka’s roadmap. Follow the upper branch to the classifier in Chapter 6. The instruction-following branch leads to Chapter 7.

We’ll prepare labeled messages, adapt GPT-2 to produce a score for each class, and fine-tune it on those examples. Then we’ll measure accuracy on held-out messages and use the classifier on a new SMS.

6.1 Different categories of fine-tuning

Imagine a text arrives saying “Claim your free cruise by midnight!” What would one training example look like? Figures 6.2 and 6.3 in the book show two ways to use a pretrained model. Here they are side by side with the same message.

Fine-tuning approach What goes into the model Target we train it to produce
Instruction “Is this spam? Answer yes or no.” + the cruise message The text Yes
Instruction “Translate this into Turkish.” + the cruise message The text Ücretsiz gemi seyahatinizi gece yarısına kadar talep edin!
Classification The cruise message alone The class spam

In instruction fine-tuning, each example pairs a prompt with a desired response. The instruction is part of the input. Changing just that instruction can turn a yes-or-no question into a translation task. The model learns by predicting the tokens of the desired response.

In classification fine-tuning, each example pairs a message with one label. The task stays the same across messages. “Can you meet me at the ferry?” would still go through the same two outputs, one score for spam and one for not spam. The higher score supplies the predicted label. If you’ve trained a CNN to identify plant species, this is the familiar part: it can recognize a new specimen, and its answer comes from the species you defined for training.

What makes this a yes-or-no decision?

Both systems could put the same message in a spam folder. In the instruction example, “answer yes or no” asks the model to express its decision in words. In the classifier, the two scores are built into the output layer. The application can act on the selected class directly.

Choosing the right approach

For a spam filter, labeled messages give us exactly the examples we need, and we can check predictions against known labels. For an assistant that must translate, summarize, and answer questions, instruction–response pairs let us teach each of those tasks. Covering that broader range generally takes more varied data and more training compute than specializing the same starting model for a single task.

6.2 Preparing the dataset

Figure 6.4 divides the work into three stages. First we prepare labeled examples and group them into batches. Then we set up pretrained GPT-2 with an output for each class. Finally we train, evaluate, and classify new messages. This section takes us from a downloaded archive to three CSV files. The same workflow applies to email if we supply labeled emails.

What is one example? Figure 6.5 previews a table with two columns. Each row holds one complete SMS and the label someone assigned to it. Ham is the dataset’s term for a legitimate message. Download and unzip the UCI SMS Spam Collection. The archive member SMSSpamCollection is already tab-separated text, even though its name has no extension. From the directory containing that file:

import pandas as pd

messages = pd.read_csv("SMSSpamCollection", sep="\t", header=None, names=["Label", "Text"])
print(messages.head())                   # Inspect the pairing before changing anything.
print(messages["Label"].value_counts())  # 4,825 ham and 747 spam.

Of the 5,572 messages, nearly 87% are ham. A filter that marked every message as ham would already be about 87% accurate here and miss every spam message. For this small teaching run we keep every spam example and draw an equal number of ham examples at random. This undersampling keeps training manageable, at the cost of leaving out 4,078 legitimate messages and changing how common spam looks.

spam = messages[messages["Label"] == "spam"]
ham = messages[messages["Label"] == "ham"].sample(n=len(spam), random_state=123)
balanced = pd.concat([ham, spam], ignore_index=True)
balanced["Label"] = balanced["Label"].map({"ham": 0, "spam": 1})

A class ID names the answer for the whole message. Mapping spam to 1 resembles a vocabulary lookup because a name gets a stable integer. The two lookups serve different jobs. GPT’s tokenizer will turn the text into a sequence of input IDs in §6.3. The label is already one integer, telling the loss function which of the two class scores should be higher.

# Mix the classes before taking slices. The seed makes this split reproducible.
rows = balanced.sample(frac=1, random_state=123).reset_index(drop=True)
train_end = int(0.70 * len(rows))
validation_end = train_end + int(0.10 * len(rows))

rows.iloc[:train_end].to_csv("train.csv", index=False)
rows.iloc[train_end:validation_end].to_csv("validation.csv", index=False)
rows.iloc[validation_end:].to_csv("test.csv", index=False)
File Messages What we use it for
train.csv 1,045 Update the model weights.
validation.csv 149 Compare training choices before settling on a model.
test.csv 300 Evaluate the chosen model on held-out examples.

The full pool contains 747 examples of each class. Shuffling and slicing gives approximate 70/10/20 splits without guaranteeing a perfect class balance inside each file. Since we balanced the pool before splitting, the test accuracy will describe a population with roughly equal numbers of spam and ham messages.

6.3 Creating data loaders

In Chapter 2, cutting a sliding window gave us equally long rows before batching. Here one SMS is one example, and its target is one class ID. One message might encode to three tokens and another to five. How do we stack both rows in one tensor without cutting off the end of the longer message?

Message Encoded input (illustrative IDs) Input padded to five positions Class ID
A 11 12 13 11 12 13 50256 50256 0 (ham)
B 21 22 23 24 25 21 22 23 24 25 1 (spam)

The inputs now have shape [2, 5] and the labels have shape [2]. Truncating both messages to three tokens would save computation but discard the last two tokens of B. Padding preserves them and spends two extra input positions on A. The book reuses GPT-2’s end-of-text ID, 50256, as the right-padding value. It sets the width from the longest encoded training message and reuses that width for validation and test, truncating any longer messages in those splits.

Think of letterboxing an image for object detection

Imagine fitting a wide photo onto a square canvas. Resizing changes the pixel grid. Letterboxing preserves the aspect ratio during resizing and fills the leftover space with a border. Adding padding IDs is like adding that border: the original token IDs stay in order, and the extra positions let PyTorch stack examples into a rectangular batch. The label still describes the whole message.

From text to equally long token rows

We can ask the tokenizer which ID represents the special token. The allowed_special argument explicitly allows tiktoken to interpret this spelling as a special token.

import tiktoken

tokenizer = tiktoken.get_encoding("gpt2")
print(tokenizer.encode("<|endoftext|>", allowed_special={"<|endoftext|>"}))
# [50256]

Once a message is encoded, we append the integer 50256 to its list of IDs. Each appended ID occupies one position and will receive an embedding when it enters the model.

Three messages encoded with GPT-2 and padded to five positions. Shorter messages receive orange padding cells.

Our version of Figure 6.6, using three new messages and verified GPT-2 token IDs. Blue cells hold message tokens, orange cells hold padding. The longest row already fills all five positions.

A dataset supplies one message and its label

The class below adapts Listing 6.4. It encodes messages once in its initializer. PyTorch later asks for individual examples through __getitem__ and the number of examples through __len__. Calling dataset[0] invokes __getitem__(0). Calling len(dataset) invokes __len__().

This listing uses pandas to read the CSV files, alongside PyTorch and tiktoken.

SpamDataset — prepare and retrieve one labeled SMS
from pathlib import Path

import pandas as pd
import torch
from torch.utils.data import Dataset


class SpamDataset(Dataset):
    """Return (token IDs [T], scalar class ID), both torch.long.

    T is max_length, the shared number of token positions per message.
    Labels are 0 for ham and 1 for spam. Each CSV must contain at least
    one message and have Text and Label columns.
    """

    def __init__(
        self,
        csv_file: str | Path,
        tokenizer: tiktoken.Encoding,
        max_length: int | None = None,
        pad_token_id: int = 50256,
    ) -> None:
        self.data = pd.read_csv(csv_file)
        # Each message starts as a separate list with its own token count.
        self.encoded_texts: list[list[int]] = [
            tokenizer.encode(text) for text in self.data["Text"]
        ]

        if max_length is None:
            # Training chooses its width from the longest encoded SMS.
            self.max_length = self._longest_encoded_length()
        else:
            # Validation/test can reuse the width chosen for training.
            self.max_length = max_length
            self.encoded_texts = [
                token_ids[:max_length] for token_ids in self.encoded_texts
            ]

        # A row already at max_length gets zero extra IDs.
        self.encoded_texts = [
            token_ids + [pad_token_id] * (self.max_length - len(token_ids))
            for token_ids in self.encoded_texts
        ]

    def __getitem__(self, index: int) -> tuple[torch.Tensor, torch.Tensor]:
        """Return one padded message [T] and its scalar label."""
        token_ids = self.encoded_texts[index]
        label = int(self.data.iloc[index]["Label"])
        return (
            torch.tensor(token_ids, dtype=torch.long),
            torch.tensor(label, dtype=torch.long),
        )

    def __len__(self) -> int:
        """Return the number of messages available to the data loader."""
        return len(self.data)

    def _longest_encoded_length(self) -> int:
        """Find the largest token count before padding."""
        return max(len(token_ids) for token_ids in self.encoded_texts)
train_dataset = SpamDataset("train.csv", tokenizer)
val_dataset = SpamDataset(
    "validation.csv", tokenizer, max_length=train_dataset.max_length
)
test_dataset = SpamDataset(
    "test.csv", tokenizer, max_length=train_dataset.max_length
)

print(train_dataset.max_length)  # 120 for the split from §6.2
token_ids, label = train_dataset[0]
print(token_ids.shape, label.shape)  # torch.Size([120]) torch.Size([])

Here 120 counts tokens after encoding. GPT-2 supports up to 1,024 positions. This dataset class has no knowledge of the model’s context limit, so we must choose a width that fits it. Setting max_length=None independently on validation or test chooses each split’s own longest row. Each split can still form rectangular batches, provided its chosen width fits the model.

Exercise 6.1 — Increasing the context length

The exercise asks us to pad to the model’s maximum supported length and observe predictive performance. We can prepare that comparison now by giving every split the same explicit width.

long_train_dataset = SpamDataset("train.csv", tokenizer, max_length=1024)
long_val_dataset = SpamDataset("validation.csv", tokenizer, max_length=1024)
long_test_dataset = SpamDataset("test.csv", tokenizer, max_length=1024)

short_ids, short_label = train_dataset[0]
long_ids, long_label = long_train_dataset[0]
assert len(long_ids) == 1024
assert torch.equal(short_ids, long_ids[:120])
assert short_label.item() == long_label.item()
assert torch.all(long_ids[120:] == 50256)

For our training split, this adds 904 padding positions per message, with the original message and label preserved. The input width grows by about 8.5 times. An ordinary dense attention score matrix grows with the square of that width, about 72.8 times here. Actual runtime and peak memory also depend on the attention implementation and other parts of the model.

Performance comparison to run after implementing fine-tuning: train a fresh copy of the same pretrained model at each width, keeping the split, seed, optimizer, batch size, and epochs fixed. Record training time and validation accuracy. Use validation to select the setting, then evaluate the chosen model on the test set. The data preparation and assertions above have been checked. Classification accuracy for these two settings has yet to be measured.

More padding supplies additional positions for computation. Its effect on classification depends on how the classifier uses those positions, which we will see when adding its output head.

From individual examples to batches

The dataset supplies one pair at a time. A data loader collects several pairs and stacks their input tensors and labels. With batch size 8, a full batch has inputs shaped [8, 120] and labels shaped [8]. Here B = 8 messages and T = 120 token positions per message. Each row has one class label.

Three SMS examples from an eight-message batch, with verified token IDs and one class label per row.

Companion to Figure 6.7. Follow the highlighted SMS across the page. GPT-2 encodes its exclamation mark as token ID 0. The separate 1 on the right labels the whole message as spam. These messages illustrate the layout of a batch.
Create the training, validation, and test data loaders
from torch.utils.data import DataLoader

torch.manual_seed(123)
batch_size = 8
num_workers = 0  # Load examples in the main process.

train_loader = DataLoader(
    train_dataset,
    batch_size=batch_size,
    shuffle=True,       # Draw a new order when we iterate over the dataset again.
    num_workers=num_workers,
    drop_last=True,     # Keep every training batch at eight messages.
)
val_loader = DataLoader(
    val_dataset,
    batch_size=batch_size,
    shuffle=False,
    num_workers=num_workers,
    drop_last=False,    # Evaluate the remaining messages in a smaller final batch.
)
test_loader = DataLoader(
    test_dataset,
    batch_size=batch_size,
    shuffle=False,
    num_workers=num_workers,
    drop_last=False,
)

A DataLoader is an iterable. Calling iter(train_loader) creates an iterator that remembers where it is in this pass. Calling next() on that iterator retrieves the next batch. Python’s for loop performs those steps for us and stops when the iterator raises StopIteration.

batches = iter(train_loader)
input_batch, target_batch = next(batches)
print(input_batch.shape)   # torch.Size([8, 120])
print(target_batch.shape)  # torch.Size([8])

The book checks the last training batch by consuming the whole loader. The variables retain the final pair after the loop ends.

for input_batch, target_batch in train_loader:
    pass  # Fetch each batch without training on it.

print(input_batch.shape)   # torch.Size([8, 120])
print(target_batch.shape)  # torch.Size([8])

With 1,045 training messages, 130 full batches use 1,040 messages. drop_last=True leaves five messages out of that pass. Since training shuffles, the omitted messages can change on the next pass. Validation and test keep their final partial batches.

Loader Messages Batches Last input shape Last label shape
Training 1,045 130 [8, 120] [8]
Validation 149 19 [5, 120] [5]
Test 300 38 [4, 120] [4]
print(len(train_loader), len(val_loader), len(test_loader))
# 130 19 38

These counts and shapes were verified with the CSV splits from §6.2. Creating another iterator starts another pass through the loader. Iterating retrieves data, and the training loop will later use that data to compute a loss and update weights.

6.4 Initializing a model with pretrained weights

We have batches of SMS messages and their labels. Before an optimizer sees any of them, we can check our starting point. Can the model still complete a sentence the way GPT-2 did at the end of Chapter 5?

The three stages of the spam project, with the current steps of building GPT-2 and loading its pretrained weights highlighted.

Companion to Figure 6.8. The highlighted steps give us a working text generator. The SMS labels prepared in stage 1 will supply the targets when we train it as a classifier.

Listing 6.6 reuses the book’s checkpoint loader and GPT implementation. The configuration gives the model its shape. Loading the checkpoint supplies the numbers learned during pretraining. We choose the small GPT-2 configuration with 12 blocks, 12 attention heads, and 768 coordinates per token. The checkpoint needs a position table with 1,024 rows even though our SMS batches use only 120 positions. Chapter 5 checkpoint walkthrough

Initialize GPT-2 small with the book’s Chapter 6 helper modules
from chapter05 import GPTModel, load_weights_into_gpt
from gpt_download import download_and_load_gpt2

config = {
    "vocab_size": 50257, "context_length": 1024,
    "emb_dim": 768, "n_layers": 12, "n_heads": 12,
    "qkv_bias": True,  # The checkpoint includes these projection biases.
    "drop_rate": 0.0,
}
_, params = download_and_load_gpt2(model_size="124M", models_dir="gpt2")
model = GPTModel(config)             # The layers start with random weights.
load_weights_into_gpt(model, params)  # Copy pretrained values into those layers.
model.eval()                         # Use evaluation behavior for generation.

The book then uses the same greedy generation helper twice. Both prompts go through the same tokenizer and model. What changes is the behavior we ask for.

Prompt What the book reports What we learn
“Every effort moves you” The model adds “forward.” and continues with a grammatical sentence about work. A plausible continuation is a quick smoke test for the loaded weights.
A cash-prize SMS with a request to answer yes or no about spam The model echoes the question and starts repeating the prize message. On this example, it continues the prompt without giving the requested decision.

Pretraining rewarded GPT-2 for predicting the next token. The question and the promised prize are just more text for it to continue. This one prompt illustrates the gap between fluent completion and following an instruction. To measure spam classification accuracy, we will need predictions for many labeled messages. Section 6.5 begins by giving the model two output scores for that task.

6.5 Adding a classification head

If you have adapted an image classifier to a new dataset, you have already made this change. Imagine a pretrained ResNet whose final layer scores 1,000 ImageNet classes. To classify cats and dogs, you keep the network that extracts features from pixels and replace its final linear layer with one that scores your two labels. Training on labeled photos teaches the new layer how to use those features.

GPT-2 small gives us a similar place to make the swap. Run print(model) on the model loaded in §6.4. Follow the token and position embeddings through 12 transformer blocks (same architecture, each with its own weights), then find the final LayerNorm and out_head. You can inspect just that last module:

print(model.out_head)
# Linear(in_features=768, out_features=50257, bias=False)

Before and after replacing the GPT-2 output head. A hidden vector of width 768 feeds either the vocabulary projection or its two-class replacement.

Companion to Figure 6.9. Trace the embeddings through the two residual additions in each of the 12 blocks and the final LayerNorm. On the right, each row of the output weight matrix reads all 768 features at one position and produces one logit. Labeled messages teach the new head which combinations suggest spam.

Fine-tuning selected layers vs. all layers

Think of a CNN used as a feature extractor. Earlier GPT layers have already learned patterns that can be useful across tasks. We can reuse those features and train a small head to recognize spam. We can also let later blocks adapt the features themselves. How much that helps is an empirical question. Freezing the early blocks still runs their forward pass, but saves the work of computing and storing gradients for their weights.

Listing 6.7 relies on the order of two operations. First freeze every parameter currently in the model. Then create a new output layer. The new layer has its own parameters, which PyTorch makes trainable by default.

for parameter in model.parameters():
    parameter.requires_grad = False

torch.manual_seed(123)  # Reproduce the starting values of the new head.
model.out_head = torch.nn.Linear(
    in_features=config["emb_dim"],  # 768 for GPT-2 small
    out_features=2,                 # ham and spam
)

print([name for name, p in model.named_parameters() if p.requires_grad])
# ['out_head.weight', 'out_head.bias']

PyTorch also offers model.requires_grad_(False) as a shorthand for the loop. Applying it before the swap freezes the existing parameters, including the old vocabulary head. Applying it after the swap would freeze the new head too. At this point the new head has 1,536 trainable weights (2 × 768) and two biases. Reading the width from the configuration lets the same code build a two-class head for a wider GPT-2 variant.

With only the head trainable, the classifier learns how to score the features GPT-2 already produces. Figure 6.10 shows the next choice. Let the last transformer block adapt those features to SMS messages, and let the final LayerNorm adapt its scale and shift before the head reads them.

# Blocks are indexed 0 through 11. Python's [-1] selects block 11.
for parameter in model.trf_blocks[-1].parameters():
    parameter.requires_grad = True

# This LayerNorm follows the whole stack. The last block has its own norms too.
for parameter in model.final_norm.parameters():
    parameter.requires_grad = True

After these loops the trainable path is block 11 → final LayerNorm → two-class head. The head was already trainable when we created it. The embeddings and blocks 0 through 10 still participate in every prediction with their pretrained weights fixed.

Appendix B (p. 295) points to Raschka’s comparison. With pretrained GPT-2 small, 120 positions, and the last position used for classification, training only the head gave 72% test accuracy (row 3). The last-block setup reached 95% (row 1). These measurements are from the author’s SMS experiment. They motivate trying this particular group of layers and measuring the result on the task at hand. Additional spam classification experiments

One detail matters when carrying the CNN analogy over. A typical ResNet pools its feature map to produce one vector per image. GPT-2 produces one vector per token position. With the batch from §6.3, applying the new head gives logits shaped [8, 120, 2]. We still need to choose which position supplies the two scores for each whole SMS. Replacing the layer and deciding which parameters to fine-tune are separate steps.

How many outputs does a binary classifier need?

The book uses two logits and a class ID (0 for ham, 1 for spam) with cross-entropy. The same pattern extends to three news categories by giving the head three outputs. A binary classifier can also use a single logit for spam with PyTorch’s BCEWithLogitsLoss and a floating-point 0/1 target. Applying sigmoid to that logit gives the predicted spam probability.

GPT-2 stages from embeddings through block 11 to the classifier. The final block, final LayerNorm and head are trainable in both runs. Only the full-model run also updates the embeddings and blocks 0–10.

Companion to Figure 6.10. Both configurations send the SMS through the entire stack. Read the brackets on the right to see where the optimizer can change a weight after the backward pass.

Exercise 6.2 — Fine-tune the whole model

Start each run from the same pretrained GPT-2 small checkpoint and the same freshly initialized classifier head. In the chapter run, train block 11, the final LayerNorm, and the head. In the exercise run, enable gradients everywhere before creating the optimizer:

model.requires_grad_(True)  # Includes the embeddings and all 12 blocks.
optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5, weight_decay=0.1)

We ran both configurations on the Mac GPU with the §6.2 splits. Each run used one epoch of 130 updates, eight messages per update, width 120, zero dropout, and the last position’s logits for cross-entropy. Seed 123 controlled both the new head and the shared shuffle order. We evaluated all 149 validation and 300 test messages in evaluation mode.

Trainable weights Validation accuracy Test accuracy
Last block, final LayerNorm, head 130/149 (87.2%) 255/300 (85.0%)
Whole model 145/149 (97.3%) 280/300 (93.3%)

These are single-seed, one-epoch results. The sign and size of the difference can change with training duration or seed. For comparison, the author’s separate experiments report 95.00% and 96.67% test accuracy for these configurations (rows 1 and 5). Author’s experiment table

One SMS through the new head

The input interface from Chapter 5 still works. Tokenize the SMS and add a batch axis so GPT receives one row.

ids = tokenizer.encode("Do you have time")   # [5211, 345, 423, 640]
inputs = torch.tensor(ids).unsqueeze(0)     # [1 message, 4 positions]
model.eval()
with torch.no_grad():
    logits = model(inputs.to(next(model.parameters()).device))
print(logits.shape)                         # torch.Size([1, 4, 2])

The four positions each get a ham score and a spam score. Changing which weights may learn affects the backward pass. Replacing the vocabulary head changes the last dimension of this forward pass. A single example can run at its actual length here; the exercise used padded rows when batching messages.

Which row represents the message?

Before the head swap, the output for “Do you have time” had shape [1, 4, 50257]. The classifier produces [1, 4, 2]. Each of the four rows still corresponds to an input position. Its two columns are raw class scores, or logits. The hidden vector feeding the head still has 768 coordinates.

Four pairs of ham and spam logits aligned with Do, you, have, and time. The time row is selected.

Companion to Figure 6.11. These are our forward-pass values before fine-tuning, rounded to four decimals. Even an ordinary question gets a higher spam score here because the new head still has its initial weights.
message_logits = logits[:, -1, :]  # Every message, final position, both classes.
print(message_logits.shape)        # torch.Size([1, 2])
# For this input: tensor([[-3.5983, 3.9902]]) to four decimal places.

Why choose “time”? Imagine two messages that both start with “Do”. At position zero the model sees the same token, at the same position, in both messages. With dropout off it must produce the same pair of scores there, even if one message goes on to offer a cash prize. By the time GPT processes the final position, every earlier word is available as evidence. Training supplies one label per SMS and computes the loss on the selected pair of scores. Gradients can flow through the earlier positions that helped produce those scores.

Causal attention mask for Do you have time. Each row can access its own token and all earlier ones.

Companion to Figure 6.12. The mask tells us which connections are allowed. The attention weights determine how much each allowed position contributes.

For this unpadded example, index -1 lands on “time”. In the chapter’s right-padded batches, it often lands on a padding ID at position 119. That position can still attend to the entire SMS. Selecting the last actual word in each padded row would be a different experiment.

Exercise 6.3 — First or last position?

Keep the last transformer block, final LayerNorm, and classifier head trainable in both runs. Change the position that supplies the logits to both the training loss and the evaluation prediction. Start each run from the same pretrained weights and identically initialized head.

position = 0  # Repeat with -1 on a fresh copy of the model.

# Inside each training step, before backward() and optimizer.step():
token_logits = model(input_batch)                   # [messages, positions, classes]
message_logits = token_logits[:, position, :]       # [messages, classes]
loss = torch.nn.functional.cross_entropy(message_logits, label_batch)

# During evaluation, use the same row selection on each held-out batch.
model.eval()
with torch.no_grad():
    predictions = model(eval_inputs)[:, position, :].argmax(dim=-1)

We ran one epoch per position on the Mac GPU with the §6.2 splits. Both runs used 130 updates, batch size 8, width 120, zero dropout, AdamW with learning rate 0.00005 and weight decay 0.1, and seed 123 for the head and the shuffle order.

Position used throughout Validation accuracy Test accuracy
First (0) 97/149 (65.1%) 197/300 (65.7%)
Last (-1) 130/149 (87.2%) 255/300 (85.0%)

Reading the last position gave 58 more correct test predictions on this split. The first token can carry a clue, which helps explain why first-position classification can work at all. The causal mask prevents it from using anything the sender writes afterward. The size of the accuracy gap is specific to this one-epoch comparison.

6.6 Calculating the classification loss and accuracy

Three-stage roadmap highlighting step 7, implementing loss and accuracy after attaching the classifier head.

Companion to Figure 6.13. Measuring the classifier before its first weight update gives us a baseline. Repeating those measurements during fine-tuning shows whether the updates help.

In Chapter 5 the question at each position was which token comes next? GPT-2 produced one score for each of its 50,257 vocabulary entries. Here the question is which class describes the whole SMS? We still tokenize the input with the full GPT-2 vocabulary. The replacement head learns two new sets of weights that read the same 768 features, one for ham and one for spam.

Consider the last row we measured in §6.5 for “Do you have time.” Index 0 means ham and index 1 means spam. Keeping that order lets us trace the prediction all the way from numbers back to a word.

Two logits for an ordinary SMS become probabilities. The higher score is at index 1, so the new head predicts spam.

Companion to Figure 6.14. Softmax preserves the order of the scores. This confidently wrong prediction on an ordinary message illustrates why replacing the head is only the setup for training.
message_logits = logits[:, -1, :]                 # [one message, two classes]
probabilities = message_logits.softmax(dim=-1)    # Normalize across ham and spam.
predicted_ids = probabilities.argmax(dim=-1)      # One winning index per SMS.
# message_logits.argmax(dim=-1) gives the same class IDs directly.

Fine-tuning is training with a pretrained starting point. For a labeled training batch, cross-entropy compares the two raw logits per message with its known class ID. Backpropagation computes gradients, and the optimizer updates the trainable weights. In the chapter setup those are the new head, final LayerNorm, and last transformer block. During evaluation we can compute that same loss and count correct predictions for accuracy, with the optimizer idle. Measuring both before the first update gives us a baseline.

Counting correct predictions across a loader

The last row for “Do you have time” contains [-3.5983, 3.9902]. The larger logit is at index 1, so the predicted label is spam. We can skip softmax when counting correct predictions because it preserves the ordering of the two scores. In a batch, dim=-1 makes this choice separately for each message.

Count correct SMS labels (adapted from Listing 6.8)
from itertools import islice

import torch
from torch.utils.data import DataLoader


@torch.no_grad()
def calc_accuracy_loader(
    data_loader: DataLoader,
    model: torch.nn.Module,
    device: torch.device,
    num_batches: int | None = None,
) -> float:
    """Return the fraction correct for the evaluated messages. None uses all batches."""
    model.eval()  # Use evaluation behavior, including disabling dropout.
    correct = 0
    seen = 0
    for inputs, targets in islice(data_loader, num_batches):
        # B = messages, T = token positions. Each position has two class logits.
        logits = model(inputs.to(device))           # [B, T, 2]
        predictions = logits[:, -1, :].argmax(-1)   # [B], one class ID per SMS
        correct += (predictions == targets.to(device)).sum().item()
        seen += targets.numel()  # Counts actual messages even in a short final batch.
    if seen == 0:
        raise ValueError("Accuracy requires at least one labeled message.")
    return correct / seen

Start from the pretrained model and the seed-123 classifier head from §6.5, before the first optimizer step. With the three loaders from §6.3, the following measures 10 batches of eight messages per split. Resetting the seed before evaluation reproduces the training loader’s shuffle for this check.

device = next(model.parameters()).device
torch.manual_seed(123)
for name, loader in [
    ("Training", train_loader), ("Validation", val_loader), ("Test", test_loader)
]:
    accuracy = calc_accuracy_loader(loader, model, device, num_batches=10)
    print(f"{name}: {accuracy:.2%}")
Split Correct / evaluated Accuracy before fine-tuning
Training 37/80 46.25%
Validation 36/80 45.00%
Test 39/80 48.75%

Our Mac GPU run reproduced the book’s three percentages. A fair coin would average 40 correct out of 80 across many trials. These scores are close to that reference. A randomly initialized head can consistently favor one class, so near-50% accuracy alone tells us little about its prediction pattern. The ten batches give us a quick baseline to compare against as training proceeds.

Measuring the loss before fine-tuning

Accuracy asks whether the correct class won. Imagine two training steps where the probability assigned to the correct label rises from 0.10 to 0.40. The prediction is still wrong both times, so accuracy gives the same answer. Cross-entropy falls from about 2.30 to 0.92. Accuracy changes in jumps when the winning label changes. Cross-entropy varies smoothly with the logits, so its gradient gives the optimizer a direction even before the winning class changes.

Chapter 5 scored a next-token target at every position. Here each SMS has one target. Selecting the final position gives cross-entropy exactly the pair of logits it needs for each label.

def calc_loss_batch(
    input_batch: torch.Tensor,
    target_batch: torch.Tensor,
    model: torch.nn.Module,
    device: torch.device,
) -> torch.Tensor:
    """Return scalar mean loss for long token IDs [B, T] and long class IDs [B].

    B counts messages and T counts padded token positions per message.
    """
    logits = model(input_batch.to(device))[:, -1, :]  # [B, 2]: ham and spam
    # Cross-entropy takes raw logits and uses the target ID to score the correct class.
    return torch.nn.functional.cross_entropy(logits, target_batch.to(device))

Listing 6.9 averages the batch losses. A batch limit lets us estimate loss quickly. Omitting it evaluates every batch. Each batch has equal weight in this average, including a short final batch if the loader returns one.

def calc_loss_loader(
    data_loader: DataLoader,
    model: torch.nn.Module,
    device: torch.device,
    num_batches: int | None = None,
) -> float:
    """Average the scalar batch losses. An empty selection yields NaN."""
    total_loss = 0.0
    count = 0
    for inputs, targets in islice(data_loader, num_batches):
        total_loss += calc_loss_batch(inputs, targets, model, device).item()
        count += 1
    return total_loss / count if count else float("nan")

The accuracy check above used ten batches per split. The book uses five batches per split for the loss baseline, or 40 messages each. Run this immediately after the accuracy example, with the same model and loaders. The training loader shuffles on each new pass.

model.eval()
with torch.no_grad():
    for name, loader in [
        ("Training", train_loader), ("Validation", val_loader), ("Test", test_loader)
    ]:
        loss = calc_loss_loader(loader, model, device, num_batches=5)
        print(f"{name} loss: {loss:.3f}")

On the Mac GPU, the initial losses were 2.453 on training, 2.583 on validation, and 2.322 on test. For comparison, predicting both classes with equal probability on every message gives a loss of about 0.693. A confident wrong prediction can push the average loss well above that value. In §6.7 the optimizer will use the training loss to update the trainable parameters.

6.7 Fine-tuning the model on supervised data

Figure 6.15 revisits the training loop from §5.2. For each batch, we clear the previous gradients, run the model, calculate cross-entropy, call loss.backward(), and take an optimizer step. In our classifier, that step updates the last transformer block, the final layer normalization, and the two-class output head.

What changes is the question each example asks. During pretraining, every position had a next-token target. Here, eight messages have eight labels. We take the two logits at the final position of each message and use the eight labels to compute one mean training loss.

What we monitor changes too. In Chapter 5 we tracked training and validation loss and generated a sample to see what the model had learned to write. We still track both losses. In place of the text sample, we now measure classification accuracy by counting how many messages the model labels correctly. Loss drives the update. Accuracy tells us how often the classifier gets the decision right.

Each epoch contains 130 batch updates, periodic loss checks, and one accuracy check at the end.

Companion to Raschka’s Figure 6.15. The indentation in Listing 6.10 follows the two boxes. Loss is checked inside the batch loop. Accuracy is checked once the loader is exhausted.

Follow one batch through Listing 6.10

The first batch contains 8 messages of 120 token positions each. In Chapter 5 that shape would give us 960 next-token targets. Here it gives us eight class labels, so the examples-seen counter advances by eight. With 130 full training batches per epoch, five epochs give us 650 optimizer updates and 5,200 message presentations, including repeat visits across epochs.

Reuse the body of Chapter 5’s evaluate_model with the calc_loss_loader defined in §6.6. It temporarily puts the model into evaluation mode, measures both splits with gradients disabled, and switches back to training mode. The helper stays the same because the choice of which logits to score lives inside calc_loss_batch.

Fine-tuning the SMS classifier
def train_classifier_simple(
    model: nn.Module, train_loader: DataLoader, val_loader: DataLoader,
    optimizer: torch.optim.Optimizer, device: torch.device,
    num_epochs: int, eval_freq: int, eval_iter: int,
) -> tuple[list[tuple[int, float, float]], list[tuple[float, float]]]:
    """Record (messages seen, train loss, validation loss) and epoch accuracies."""
    losses = []
    accuracies = []
    examples_seen = 0
    step = 0
    for epoch in range(1, num_epochs + 1):
        model.train()
        for inputs, labels in train_loader:
            optimizer.zero_grad()
            loss = calc_loss_batch(inputs, labels, model, device)
            loss.backward()   # Gradients for the parameters we unfroze in §6.5.
            optimizer.step()  # One update for the whole batch.
            examples_seen += labels.numel()  # One label per SMS.

            # Step 0 is the first completed update, as in the book.
            if step % eval_freq == 0:
                train_loss, val_loss = evaluate_model(
                    model, train_loader, val_loader, device, eval_iter
                )
                losses.append((examples_seen, train_loss, val_loss))
                print(f"Step {step}: loss {train_loss:.3f} / {val_loss:.3f}")
            step += 1

        # Outside the batch loop: measure accuracy once per epoch.
        train_acc = calc_accuracy_loader(train_loader, model, device, eval_iter)
        val_acc = calc_accuracy_loader(val_loader, model, device, eval_iter)
        accuracies.append((train_acc, val_acc))
        print(f"Epoch {epoch}: accuracy {train_acc:.1%} / {val_acc:.1%}")
    return losses, accuracies

Time the five-epoch fine-tune

Start with the pretrained backbone and fresh classifier head from §6.5. Rerunning this cell on an already fine-tuned model would give it another five epochs. On the Mac, move the model to the MPS device before creating AdamW. A monotonic wall clock measures the time a reader actually waits, including the scheduled evaluations. Synchronizing the GPU at the boundaries makes the end time include its queued work.

from time import perf_counter

torch.manual_seed(123)
optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5, weight_decay=0.1)
if device.type == "mps":
    torch.mps.synchronize()
start = perf_counter()
losses, accuracies = train_classifier_simple(
    model, train_loader, val_loader, optimizer, device,
    num_epochs=5, eval_freq=50, eval_iter=5,
)
if device.type == "mps":
    torch.mps.synchronize()  # Wait for queued GPU work before stopping the timer.
elapsed = perf_counter() - start
print(f"Five epochs took {elapsed:.1f} seconds")

Plot the losses where they were measured

Our adaptation of Listing 6.11 records the message count at each loss check. The first point is at 8 messages (step 0), and the last is at 4,808 (step 600). Training continues to 5,200. A second axis converts those same coordinates into epochs using 1,040 presentations per epoch. This keeps each point at its measured position.

Plotting training and validation measurements
import matplotlib.pyplot as plt
from matplotlib.figure import Figure


def plot_values(
    examples: tuple[int, ...], training: tuple[float, ...],
    validation: tuple[float, ...], examples_per_epoch: int, ylabel: str = "Mean cross-entropy loss",
) -> Figure:
    """Plot training and validation measurements against messages seen, with epochs on the upper axis."""
    fig, ax = plt.subplots(figsize=(7.4, 3.8), layout="constrained")
    ax.plot(examples, training, "o-", color="#18685d", label="Training", markersize=4)
    ax.plot(examples, validation, "s--", color="#a94b24", label="Validation", markersize=4)
    ax.set(xlabel="Training messages seen", ylabel=ylabel, ylim=(0, None))
    ax.grid(axis="y", alpha=0.2)
    ax.legend(frameon=False)
    top = ax.secondary_xaxis("top", functions=(
        lambda count: count / examples_per_epoch,
        lambda epochs: epochs * examples_per_epoch,
    ))
    top.set_xlabel("Epochs completed")
    return fig


examples, training, validation = zip(*losses)
# The training loader drops its short last batch: 130 full batches of eight.
fig = plot_values(examples, training, validation, len(train_loader) * train_loader.batch_size)
fig.savefig("sms-training-loss.svg")

Measured training and validation losses fall sharply at first, then track each other closely over five epochs.

Companion to Raschka’s Figure 6.16, plotted from our M5 MacBook Air run. Each marker averages five batches of eight messages. The first pair of markers already includes one optimizer update.

The five epochs took 103.5 seconds (1.72 minutes) with PyTorch 2.14.1 on the Mac GPU. This times training and monitoring with the model and data already loaded. The book reports about six minutes on an M3 Air. The two machines were measured separately, so these times give a ballpark comparison.

Our curves have the same shape as Figure 6.16. At the first loss check, training and validation loss were 2.153 and 2.392. At the last check they were 0.083 and 0.074. Both fell sharply early on and stayed close as training progressed. At the end of epoch five, accuracy was 100.0% on training and 97.5% on validation, measured on 40 messages per split. Recorded measurements for all 13 loss checks and five epoch-end accuracy checks.

Choosing the number of epochs

Five epochs was enough for this run. In Figure 6.16, training and validation loss dropped together, with little evidence of overfitting on the monitored batches. If training loss keeps falling while validation loss consistently rises, an earlier checkpoint is a better candidate. If validation loss is still improving, try a longer run and compare checkpoints on validation data. Reserve the test set for the final evaluation.

Accuracy at the end of each epoch

Reuse plot_values with the five accuracy measurements. The first point belongs at the end of epoch one (1,040 messages seen). Each validation check scores the same first 40 messages. The training loader shuffles, so its sample can change from one check to the next.

from matplotlib.ticker import PercentFormatter, MultipleLocator

per_epoch = len(train_loader) * train_loader.batch_size
messages = tuple(epoch * per_epoch for epoch in range(1, len(accuracies) + 1))
training, validation = zip(*accuracies)
fig = plot_values(messages, training, validation, per_epoch, ylabel="Classification accuracy")
ax = fig.axes[0]
ax.set_ylim(0.65, 1.025)
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.set_xticks(messages)
ax.child_axes[0].xaxis.set_major_locator(MultipleLocator(1))
fig.savefig("sms-training-accuracy.svg")

Training and validation accuracy climb from 70% and 72.5% at epoch one to 100% and 97.5% at epochs four and five.

Companion to Raschka’s Figure 6.17. At epochs four and five the classifier got 39 of the 40 validation messages right. A single decision moves this estimate by 2.5 percentage points.

Evaluate every message

Omit the optional batch limit from calc_accuracy_loader to visit every batch. There is one more detail for training data. Our training loader drops its short final batch, so build an evaluation loader over the same dataset that includes those remaining messages.

full_train_loader = DataLoader(train_loader.dataset, batch_size=8, shuffle=False, drop_last=False)
for name, loader in [("Training", full_train_loader), ("Validation", val_loader), ("Test", test_loader)]:
    accuracy = calc_accuracy_loader(loader, model, device)
    print(f"{name}: {accuracy:.2%} across {len(loader.dataset)} messages")

We repeated the five-epoch M5 run with seed 123 and the same settings to evaluate the final weights. All five epoch-end accuracy pairs matched the recorded run.

Split Correct / evaluated Accuracy
Training 1,016 / 1,045 97.22%
Validation 145 / 149 97.32%
Test 287 / 300 95.67%

The book reports 97.21% on training using the original loader, which evaluates 1,040 messages. Our training denominator includes all 1,045. The validation and test sets contain different messages, so a small gap can arise from the split alone. Repeatedly choosing settings on validation performance can also favor that split. If a persistent training–validation gap develops, compare dropout or weight decay settings using validation data.

6.8 Using the LLM as a spam classifier

During training we needed an SMS and its known label. Now someone can give us just the SMS. The saved weights and the preprocessing decisions from training supply everything else the classifier needs for a forward pass.

Three stages of classifier development, ending with predicting one label for a new SMS.

Companion to Raschka’s Figure 6.18. Steps 1–9 produced and tested the classifier. Step 10 uses it on a message whose label we want to predict.

From an SMS to a label

Listing 6.12 calls this function classify_review. Here the text is an SMS. Use the width we trained with (120), even for a short message. We trained the classifier to read the last padded position. Feeding just the unpadded tokens would ask it to read a different position.

Classifying one message
@torch.inference_mode()
def classify_review(
    text: str, model: GPTModel, tokenizer: tiktoken.Encoding, max_length: int,
) -> str:
    """Map one SMS to a class name using the padded width from training."""
    model.eval()
    if not 1 <= max_length <= model.pos_emb.num_embeddings:
        raise ValueError("Choose a width within the model's position table.")
    ids = tokenizer.encode_ordinary(text)[:max_length]
    ids += [tokenizer.eot_token] * (max_length - len(ids))

    # One message of T token IDs. The outer list supplies the batch dimension.
    inputs = torch.tensor([ids], dtype=torch.long, device=model.pos_emb.weight.device)
    # [1, T, 2] → [1, 2]. Training scored this same final padded position.
    scores = model(inputs)[:, -1, :]
    return ("not spam", "spam")[scores.argmax(dim=-1).item()]

The output head already has a score for each class. Taking the index of the larger score gives the label ID. Run these two messages through the trained model:

max_length = train_dataset.max_length
messages = [
    "You are a winner! You have been specially selected to receive a cash award.",
    "Hey, just wanted to check if we're still on for dinner tonight. Let me know.",
]
labels = [classify_review(text, model, tokenizer, max_length) for text in messages]
print(labels)

Our run printed ["not spam", "not spam"]. The dinner invitation was correct. The shorter prize offer was a false negative. We also checked both exact messages from Listing 6.12 with the restored model: it labeled the book’s prize offer (with the two dollar amounts) spam and its dinner invitation not spam. Several words and punctuation marks changed in our paraphrase, so these examples alone cannot identify which change flipped the label.

Keep the classifier for the next session

model.state_dict() includes the pretrained backbone, its fine-tuned layers, the new output head, and registered buffers. Saving the architecture settings, tokenizer name, and training width alongside those tensors makes it possible to reconstruct the same prediction path. This checkpoint is for inference. The model class, the two-label mapping, and the preprocessing function travel with the application code.

Saving and restoring the SMS classifier
torch.save({
    "config": config,
    "weights": model.state_dict(),
    "max_length": max_length,
    "tokenizer": tokenizer.name,
}, "sms-classifier.pth")

# A fresh process needs the GPTModel class and the same two-output head.
saved = torch.load("sms-classifier.pth", map_location="cpu", weights_only=True)
restored = GPTModel(saved["config"])
restored.out_head = torch.nn.Linear(saved["config"]["emb_dim"], 2)
restored.load_state_dict(saved["weights"])
encoding = tiktoken.get_encoding(saved["tokenizer"])
print([classify_review(text, restored, encoding, saved["max_length"]) for text in messages])

The restored CPU model returned the same two labels as the fine-tuned GPU model for our examples. The checkpoint can now be used without another training run.

The common idea is to start with a capable model and supply examples or feedback that reward the behavior a product needs. Our target is one class ID per message. A legal agent’s target can be a sequence of actions and a written answer. For example, given a question about a settlement, it may need to find the agreement, read the relevant clause, and use it in the answer.

Mercor reports a legal experiment with Harvey using NVIDIA Nemotron 3.5 Super. They used supervised fine-tuning on examples of model-generated work that passed a grader’s selection. That is close to instruction fine-tuning: the demonstration includes how to work through the assignment as well as what to answer. On held-out APEX-Agents legal tasks, average rubric criteria met rose from 45.1% to 51.8%. Full-credit attempts rose from 19.8% to 25.0%. Those percentages measure different things from SMS classification accuracy. Mercor’s experiment and worked example

Harvey has also reported training a GLM-5.1 legal agent with Applied Compute using reinforcement learning. The agent attempts a task and a grader scores the result, giving training a reward signal. Harvey’s product uses multiple model providers. Each research result describes a particular model, method, and evaluation. Harvey’s training report · Harvey’s product FAQ

Chapter 6 in seven points

  1. Choose the output the task needs. Classification produces one of a fixed set of labels. Instruction fine-tuning teaches a model to generate a response to a request.
  2. Keep the text input pipeline. Each SMS becomes GPT-2 token IDs. Truncating and padding to a shared width lets the loader batch messages alongside their class labels.
  3. Start with pretrained weights. GPT-2 brings the language representations it learned through next-token prediction.
  4. Replace the vocabulary head. Each position’s 768 features now produce two class scores in place of 50,257 vocabulary scores.
  5. Train on one label per SMS. The final position can attend to the whole message. Cross-entropy on its two logits updates the head, final layer normalization, and last transformer block.
  6. Count correct decisions on held-out messages. Five-batch checks tracked progress during training. The final test counted 287 correct predictions across 300 messages.
  7. Package what inference needs. Restore the classifier weights and architecture, apply the same tokenizer and padding rule, and map the winning score to the same class name.