Initializing a model with pretrained weights

Figure 6.8 Three-stage process for fine-tuning an LLM for classification.
To begin preparing the model, we use the same configuration as when pretraining on unlabeled data:
Next, we import the downloadandloadgpt2 function from the gptdownload.py file and reuse the GPTModel class and loadweightsinto_gpt function from pretraining to load the downloaded weights into the GPT model.
After loading the model weights into GPTModel, we reuse the text-generation utility functions to confirm that the model generates coherent text.
Before we start fine-tuning the model as a spam classifier, let’s see whether it can already classify spam when given an instruction.
Based on the output, the model clearly struggles to follow instructions. That’s expected, since it has only been pretrained and lacks instruction tuning. So let’s prepare the model for classification fine-tuning.
Adding a classification head
We need to modify the pretrained large language model (LLM) to prepare it for classification fine-tuning. To do that, we replace the original output layer with a smaller one that maps the hidden representation to two classes: 0 (“not spam”) and 1 (“spam”), as shown in Figure 6.9. We use the same model as before, except for the replaced output layer.

Figure 6.9 Adapting the GPT model for spam classification by changing its architecture. Initially, the model’s linear output layer maps 768 hidden units to 50,257 vocabulary entries. To detect spam, we replace this layer with a new output layer that maps the same 768 hidden units to just two classes representing “spam” and “not spam”.
[!NOTE] Output layer nodes
Technically, we could use a single output node because we’re dealing with a binary classification task. However, that would require modifying the loss function. So we choose a more general approach in which the number of output nodes matches the number of classes. For example, for a three-class problem—such as classifying news articles as “technology,” “sports,” or “politics”—we would use three output nodes, and so on.
Before we try the modification shown in Figure 6.9, let’s print the model architecture with print(model):
As mentioned earlier, GPTModel consists of embedding layers followed by 12 identical transformer blocks (only the last block is shown for simplicity), and finally a LayerNorm and the output layer out_head.
Setting all layers
Next, we replace out_head with a new output layer (see Figure 6.9), which we’ll fine-tune.
To prepare the model for classification fine-tuning, we first freeze the model, which means setting all layers to non-trainable:
for param in model.parameters():
param.requires_grad = False
Then we replace the output layer (model.out_head), which initially maps its input to 50,257 dimensions—the size of the vocabulary (see Figure 6.9).
torch.manual_seed(123)
num_classes = 2
model.out_head = torch.nn.Linear(in_features=BASE_CONFIG["emb_dim"], out_features=num_classes)
To keep the code general, we use BASECONFIG["embdim"], which is 768 for the “gpt2-small (124 M)” model. That way, we can also use the same code for larger GPT-2 model variants.
The new model.outhead output layer’s requiresgrad attribute defaults to True, meaning it’s the only layer in the model that will be updated during training. Technically, training just the output layer we just added would be enough. However, as I found in my experiments, fine-tuning additional layers can significantly improve the model’s predictive performance. We’ll also configure the last transformer block and the final LayerNorm module that connects this block to the output layer as trainable, as shown in Figure 6.10.
Figure 6.10 The GPT model contains 12 repeated Transformer blocks. Alongside the output layer, we set the final LayerNorm and the last Transformer block to trainable. The remaining 11 Transformer blocks and the embedding layers remain non-trainable.
To make the final LayerNorm and the last transformer block trainable, we set their respective requires_grad to True:
for param in model.trf_blocks[-1].parameters():
param.requires_grad = True
for param in model.final_norm.parameters():
param.requires_grad = True
We can feed it the exact same example text we used earlier:
The printed output shows that the preceding code encodes the input into a tensor of four input tokens. We can then pass the encoded token IDs to the model as usual:
Fine-tuning
Remember that our goal is to fine-tune this model to return a class label indicating whether the model input is “spam” or “not spam.” We don’t need to fine-tune all four output rows; instead, we can focus on a single output token. Specifically, we’ll focus on the last row, which corresponds to the last output token, as shown in Figure 6.11.

Figure 6.11 Example input and output of four tokens for the GPT model. Because the output layer was modified, the output tensor consists of two columns. We’re only interested in the last row, which corresponds to the last token when fine-tuning the model for spam classification.
To extract the last output token from the output tensor, we use the following code:
print("Last output token:", outputs[:, -1, :])
## output
Last output token: tensor([[-3.5983, 3.9902]])
We still need to convert the values into class label predictions. But first, let’s understand why we’re focusing specifically on the last output token.
We’ve already explored the attention mechanism, which establishes relationships between each input token and every other input token, as well as the concept of a causal attention mask commonly used in GPT-like models. This mask restricts a token’s focus to information at its current position and before, ensuring that each token can only be influenced by itself and preceding tokens, as shown in Figure 6.12.
Figure 6.12 Causal attention mechanism, where attention scores between input tokens are shown in matrix format.
Under the causal attention mask setup in Figure 6.12, the last token in the sequence accumulates the most information, because it’s the only token that can access data from all preceding tokens. Therefore, in our spam classification task, we focus on this last token during fine-tuning.
We’re now ready to convert the last token into a class label prediction and calculate the model’s initial prediction accuracy. After that, we’ll fine-tune the model to perform the spam classification task.
Calculating the classification loss and accuracy
There’s just one small task to complete before we fine-tune the model: we need to implement the model evaluation function used during fine-tuning, as shown in Figure 6.13.

Figure 6.13 Three-stage process for classification fine-tuning of an LLM.
Before implementing the evaluation utility, let’s briefly discuss how to convert model outputs into class label predictions. Previously, we calculated the token ID of the next token generated by an LLM by passing the 50,257 outputs through a softmax function to convert them into probabilities, and then using an argmax function to return the position with the highest probability. We’ll use the same approach here to compute the model’s “spam” or “not spam” prediction for a given input, as shown in Figure 6.14. The only difference is that we’re using a 2-dimensional output instead of a 50,257-dimensional one.

Figure 6.14 The model output’s probability scores corresponding to the last token are converted into a classification label for each input text.
Let’s consider the last-token output for a concrete example:
print("Last output token:", outputs[:, -1, :])
## output
Last output token: tensor([[-3.5983, 3.9902]])
We can obtain the class label:
probas = torch.softmax(outputs[:, -1, :], dim=-1)
label = torch.argmax(probas)
print("Class label:", label.item())
## output
Class label: 1
In this case, the code returns 1, meaning the model predicts that the input text is “spam.” Using the softmax function here is optional, because the largest output directly corresponds to the highest probability score. So we can simplify the code by omitting softmax:
logits = outputs[:, -1, :]
label = torch.argmax(logits)
print("Class label:", label.item())
## output
Class label: 1
This concept can be used to calculate classification accuracy, which measures the percentage of correct predictions in a dataset.
Accuracy test
To determine classification accuracy, we apply the argmax-based prediction code to all examples in the dataset and calculate the proportion of correct predictions by defining a calcaccuracyloader function.
Let’s use this function to determine the classification accuracy of the different datasets, estimated from 10 batches each for efficiency:
Calculating the loss function
As we can see, the prediction accuracy is close to random guessing, which in this case would be 50%. To improve prediction accuracy, we need to fine-tune the model.
However, before we start fine-tuning the model, we must define the loss function to optimize during training. Our goal is to maximize the model’s spam classification accuracy, which means the preceding code should output the correct class label: 0 for not spam and 1 for spam.
Because classification accuracy is not a differentiable function, we use cross-entropy loss as a proxy for maximizing accuracy. Therefore, the calclossbatch function remains unchanged, with one adjustment: instead of optimizing all tokens, i.e., model(inputbatch), we focus on optimizing only the last token, i.e., model(inputbatch)[:, -1, :]:
We use the calclossbatch function to calculate the loss for a single batch obtained from the data loaders defined earlier. To calculate the loss for all batches in a data loader, we define the calclossloader function, as shown earlier.
Similar to calculating training accuracy, we now calculate the initial loss for each dataset:
Next, we’ll implement a training function to fine-tune the model, which means adjusting the model to minimize the training set loss. Minimizing the training set loss will help improve classification accuracy, which is our overall goal.