Fine-tuning the model on supervised data
We need to define and use a training function to fine-tune the pretrained LLM and improve its spam classification accuracy. The training loop is shown in Figure 6.15 and is the same overall training loop we used for pretraining; the only difference is that we compute classification accuracy instead of generating sample text to evaluate the model.

Figure 6.15 A typical training loop for training a deep neural network in PyTorch consists of several steps, iterating over batches in the training set for multiple epochs.
The training function implements the concept shown in Figure 6.15 and closely corresponds to the trainmodelsimple function used for model pretraining. The only two differences are that we now track the number of training examples seen (examples_seen) rather than the number of tokens, and that we compute accuracy after each training epoch instead of printing sample text.
Next, we initialize the optimizer, set the number of training epochs, and start training with the trainclassifiersimple function. On an M3 MacBook Air laptop, training takes about 6 minutes, while on a V100 or A100 GPU it takes less than half a minute:
import time
start_time = time.time()
torch.manual_seed(123)
optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5,weight_decay=0.1)
num_epochs = 5
train_losses, val_losses, train_accs, val_accs, examples_seen = \
train_classifier_simple(
model, train_loader, val_loader, optimizer, device,
num_epochs=num_epochs, eval_freq=50,eval_iter=5)
end_time = time.time()
execution_time_minutes = (end_time - start_time) / 60
print(f"Training completed in {execution_time_minutes:.2f} minutes.")
## output

Output
We then use Matplotlib to plot the loss for the training and validation sets.

Figure 6.16 Training and validation loss of the model over five training epochs.
Based on the clear, steep downward trend in Figure 6.16, we can see that the model is learning well from the training data and shows almost no signs of overfitting; that is, there is no significant gap between the training and validation losses.
[!NOTE] Choosing the number of epochs
Earlier, when we started training, we set the number of training epochs to five. The number of epochs depends on the dataset and the difficulty of the task, and there is no universal solution or recommendation, although five epochs is usually a good starting point. If the model overfits after the first few epochs, as shown in the loss plot (see Figure 6.16), you may need to reduce the number of epochs. Conversely, if the trend line suggests that validation loss might improve with further training, you should increase the number of epochs. In this particular case, five epochs is a reasonable number because there are no signs of early overfitting and the validation loss is close to 0.
epochs_tensor = torch.linspace(0, num_epochs, len(train_accs))
examples_seen_tensor = torch.linspace(0, examples_seen, len(train_accs))
plot_values(epochs_tensor, examples_seen_tensor, train_accs, val_accs, label="accuracy")

Figure 6.17 Training accuracy (solid line) and validation accuracy (dashed line) improve significantly in the early epochs, then level off, nearly reaching a perfect accuracy score of 1.0.
When using the trainclassifiersimple function, this means our estimates of training and validation performance are based on only five batches to make training more efficient.
Now we need to compute performance metrics for the training, validation, and test sets across the entire dataset by running the following code, this time without setting eval_iter:
The performance on the training and test sets is almost identical. The small difference between training and test accuracy indicates little overfitting to the training data. Typically, validation accuracy is higher than test accuracy because model development often involves tuning hyperparameters to perform well on the validation set, which may not generalize effectively to the test set. This is common, but you can try to close the gap by adjusting model settings, such as increasing the dropout rate (droprate) or the weightdecay parameter in the optimizer configuration.
Using the LLM as a spam classifier

Figure 6.18 The three-stage process of classification fine-tuning our large language model.
After fine-tuning and evaluating the model, we're now ready to classify spam messages (see Figure 6.18). Let's use our fine-tuned GPT-based spam classification model.
The following classify_review function follows data preprocessing steps similar to those we used earlier in SpamDataset. Then, after converting the text into token IDs, the function uses the model to predict an integer class label and returns the corresponding class name.
Let's try this classify_review function on an example text:
Finally, we save the model so that if we want to reuse it in the future, we don't have to train it again. We can use the torch.save method. After saving, we can also load the model.
Summary
- There are different strategies for fine-tuning LLMs, including classification fine-tuning and instruction fine-tuning.
- Classification fine-tuning involves replacing the LLM’s output layer with a small classification layer.
- In the case of classifying text messages as “spam” or “not spam,” the new classification layer contains only two output nodes. Previously, the number of output nodes we used equaled the number of unique tokens in the vocabulary (that is, 50,256).
- Unlike pretraining, where the model predicts the next token in the text, classification fine-tuning trains the model to output the correct class label—for example, “spam” or “not spam.”
- The input to the fine-tuned model is text converted to token IDs, similar to pretraining.
- Before fine-tuning an LLM, we first need to load a pretrained base model.
- Evaluating a classification model involves computing classification accuracy (the proportion or percentage of correct predictions).
- Fine-tuning a classification model uses the same cross-entropy loss function as pretraining an LLM.