So far, we've implemented data sampling and the attention mechanism and coded the LLM architecture. Now it's time to implement a training function and pretrain the LLM.
We'll learn basic model evaluation techniques to measure the quality of generated text, which is a requirement for optimizing the LLM during training.
We'll also discuss how to load pretrained weights to give our LLM a solid starting point for fine-tuning.
Figure 5.1 The three main stages of coding an LLM. This chapter focuses on stage 2: pretraining the LLM (step 4), including implementing the training code (step 5), evaluating performance (step 6), and saving and loading model weights (step 7).
[!NOTE] Weight parameters
In the context of large language models (LLMs) and other deep learning models, weights refer to the trainable parameters adjusted during the learning process. These weights are also called weight parameters, or simply parameters. In frameworks like PyTorch, these weights are stored in linear layers; we used them in Chapter 3 to implement the multi-head attention module and in Chapter 4 to implement GPTModel. After initializing a layer (newlayer = torch.nn.Linear(...)), we can access its weights through the .weight attribute, i.e., newlayer.weight. For convenience, PyTorch also lets us access all of a model's trainable parameters, including weights and biases, directly through the model.parameters() method, which we'll use later when implementing model training.

Figure 5.2 Overview of the topics covered in this chapter. We first review text generation (step 1), then discuss basic model evaluation techniques (step 2) and training and validation loss (step 3).
Using GPT to generate text
Let's set up the LLM and briefly review the text generation process we implemented in Chapter 4. We'll start by initializing the GPT model, which we'll later evaluate and train using the GPTModel class and the GPTCONFIG124M dictionary.
Given the GPTCONFIG124M dictionary, our only change from the previous chapter is to reduce the context length (context_length) to 256 tokens. This modification lowers the computational requirements for training the model, making it possible to train on a standard laptop.
Originally, the 124-million-parameter GPT-2 model was configured to handle up to 1,024 tokens. After the training process, we'll update the context size setting and load pretrained weights to use a model configured with a 1,024-token context length.
Using the GPTModel instance, we'll use the earlier generatetextsimple function and introduce two convenience functions: texttotokenids and tokenidstotext. These functions make it easy to convert between text and token representations, a technique we'll use throughout this chapter.
Figure 5.3 Generating text involves encoding text into token IDs, which the LLM then processes into a vector of logits. The logits are then converted back into token IDs and detokenized into a text representation.
Figure 5.3 shows the three-step text generation process using a GPT model. First, the tokenizer converts the input text into a sequence of token IDs. Second, the model takes these token IDs and produces the corresponding logits, which are vectors representing the probability distribution over each token in the vocabulary. Finally, these logits are converted back into token IDs, which the tokenizer decodes into human-readable text, completing the cycle from text input to text output.
We can implement the text generation process as follows.
Clearly, the model isn't generating coherent text yet because it hasn't been trained. To define what counts as “coherent” or “high-quality” text, we need to implement a numerical method for evaluating the generated content. This approach will let us monitor and improve the model's performance throughout training.
Next, we'll calculate a loss metric for the generated output. This loss serves as a progress and success indicator during training. In later chapters, when we fine-tune our LLM, we'll also revisit other ways to evaluate model quality.
Calculating the text generation loss
Let's explore some techniques for numerically evaluating the quality of generated text during training by calculating the text generation loss.
We'll walk through this topic step by step and use a practical example to make the concepts clear and applicable, starting with a brief review of how data is loaded and how text is generated through the generatetextsimple function.

Figure 5.4 For the three input tokens shown on the left, we calculate a vector containing probability scores corresponding to each token in the vocabulary. The index position of the highest probability score in each vector represents the most likely next token ID. These token IDs associated with the highest probability scores are selected and mapped back to text representing the model-generated text.
Figure 5.4 shows the overall flow from input text to LLM-generated text using a five-step procedure. This text generation process illustrates how the generatetextsimple function works internally. Later in this section, we'll need to perform these same initial steps before we can calculate a loss to measure the quality of the generated text.
Figure 5.4 outlines the text generation process using a small seven-token vocabulary so the image fits on a single page. However, our GPTModel uses a much larger vocabulary containing 50,257 words; therefore, the token IDs in the following code will range from 0 to 50,256 rather than from 0 to 6.
In addition, Figure 5.4 shows only one text example (“every effort moves you”) to simplify the illustration.
GPT generate compare example
Note that the targets are the inputs shifted forward by one position, a concept we covered when implementing the data loader in Chapter 2. This shifting strategy is essential for training the model to predict the next token in a sequence.
Now we'll feed the input data into the model to calculate the logits vectors for the two input examples, each consisting of three tokens. Then we'll apply the softmax function to convert these logits into probability scores (probas; Figure 5.4, step 2):
After converting the logits into probabilities with the softmax function, the generatetextsimple function converts the resulting probability scores back into text (Figure 5.4, steps 3–5). We can complete steps 3 and 4 by applying the argmax function to the probability scores to obtain the corresponding token IDs:
Finally, step 5 converts the token IDs back into text:
When we decode these tokens, we find that the output tokens are quite different from the target tokens we want the model to generate.
The random text generated by the model differs from the target text because it hasn't been trained yet. We now want to evaluate the model's text generation performance numerically using loss (Figure 5.5).
This not only helps measure the quality of the generated text but also provides the foundation for implementing the training function we'll use to update the model's weights and improve the generated text.
Text Evaluation

Figure 5.5 Overview of the topics covered in this chapter. We've completed step 1. Now we're ready to implement the text evaluation function (step 2).
Part of the text evaluation process we'll implement, as shown in Figure 5.5, is measuring the “distance” between the generated tokens and the correct predictions (targets). The training function we implement later will use this information to adjust the model weights so it generates text that is more similar to—or ideally matches—the target text.

Figure 5.6 Before training, the model produces random next-token probability vectors. The goal of model training is to ensure that the probability values corresponding to the highlighted target token IDs are maximized.
The goal of model training is to increase the softmax probability at the index position corresponding to the correct target token ID, as shown in Figure 5.6. This softmax probability will also be used in the evaluation metric we implement next to numerically assess the model's generated output: the higher the probability at the correct position, the better.
Figure 5.6 shows the softmax probabilities for a compact seven-token vocabulary to fit everything into one figure. This means the initial random values will hover around 1/7, roughly 0.14. However, the vocabulary we use for the GPT-2 model has 50,257 tokens, so most initial probabilities will hover around 0.00002 (1/50,257).
For each input text, we can use the following code to print the initial softmax probability scores corresponding to the target tokens:
The goal of training an LLM is to maximize the likelihood of the correct token, which involves increasing its probability relative to the other tokens. In this way, we ensure that the LLM consistently selects the target token—essentially the next word in the sentence—as the next token it generates.
Loss Explained
[!NOTE] Backpropagation
How do we maximize the softmax probability values corresponding to the target tokens?The general idea is to update the model's weights so that the model outputs higher values for the corresponding token IDs we want to generate. Weight updates are performed through a process called backpropagation, a standard technique for training deep neural networks.
Backpropagation requires a loss function that calculates the difference between the model's predicted output (here, the probabilities corresponding to the target token IDs) and the actual desired output. This loss function measures how far the model's predictions deviate from the target values.

Figure 5.7 Calculating the loss involves several steps. Steps 1 through 3, already completed, calculate the token probabilities corresponding to the target tensor. These probabilities are then transformed with a logarithm and averaged in steps 4 through 6.
Next, we'll calculate the loss for the probability scores of the two example batches, targetprobas1 and targetprobas2.
The main steps are shown in Figure 5.7. Since we've already applied steps 1 through 3 to obtain targetprobas1 and targetprobas2, we'll proceed to step 4 and apply a logarithm to the probability scores:
log_probas = torch.log(torch.cat((target_probas_1, target_probas_2)))
print(log_probas)
## output
tensor([ -9.5042, -10.3796, -11.3677, -11.4798, -9.7764, -12.2561])
In mathematical optimization, working with the logarithm of probability scores is more manageable than working with the scores directly.
Next, we combine these log probabilities into a single score by calculating the mean. The resulting average log probability score is:
avg_log_probas = torch.mean(log_probas)
print(avg_log_probas)
## output
tensor(-10.7940)
The goal is to make the average log probability as close to 0 as possible by updating the model's weights during training.
However, in deep learning, the common practice is not to push the average log probability up to 0 but rather to bring the negative average log probability down to 0. The negative average log probability is simply the average log probability multiplied by -1, which corresponds to step 6 in Figure 5.7:
neg_avg_log_probas = avg_log_probas * -1
print(neg_avg_log_probas)
## output
tensor(10.7940)
In deep learning, the term for turning this negative value of –10.7940 into 10.7940 is cross entropy loss.
PyTorch is very convenient here because it already includes a cross_entropy function that can handle all six steps in Figure 5.7 for us.
[!NOTE] Cross Entropy Loss
At its core, cross entropy loss is a common metric in machine learning and deep learning that measures the difference between two probability distributions—usually the true distribution of labels (here, the tokens in the dataset) and the predicted distribution from the model (for example, the token probabilities generated by the LLM).In machine learning, especially in frameworks like PyTorch, the cross_entropy function calculates this metric for discrete outcomes. It is equivalent to the negative average log probability of the target tokens given the model-generated token probabilities, so the terms “cross entropy” and “negative average log probability” are related and often used interchangeably in practice.
Before we apply the cross entropy function, let's briefly review the shapes of the logits and target tensors:
As we can see, the logits tensor has three dimensions: batch size, number of tokens, and vocabulary size. The targets tensor has two dimensions: batch size and number of tokens.
For PyTorch's cross entropy loss function, we need to flatten these tensors by combining them along the batch dimension:
Keep in mind that the targets are the token IDs we want the LLM to generate, while the logits are the unscaled model outputs before they go through the softmax function to obtain probability scores.
Earlier, we applied the softmax function, selected the probability scores corresponding to the target IDs, and calculated the negative average log probability. PyTorch's cross_entropy function will handle all of these steps for us:
loss = torch.nn.functional.cross_entropy(logits_flat, targets_flat)
print(loss)
## output
tensor(10.7940)
The resulting loss is the same as the loss we obtained earlier when manually applying the individual steps in Figure 5.7.
[!NOTE] Perplexity
Perplexity is a common metric often used alongside cross entropy loss to evaluate a model's performance on tasks such as language modeling. It can provide a more interpretable way to understand the model's uncertainty when predicting the next token in a sequence.
Perplexity measures how well the probability distribution predicted by the model matches the actual distribution of words in the dataset. Like loss, lower perplexity indicates that the model's predictions are closer to the actual distribution.
Perplexity can be calculated as perplexity = torch.exp(loss), which, when applied to the loss calculated earlier, returns tensor(48725.8203).
Perplexity is often considered more interpretable than the raw loss value because it represents the model's uncertainty over the effective vocabulary size at each step. In the given example, this means the model is uncertain about the next token among 48,725 tokens from the vocabulary.
We've now calculated the loss for two small text inputs for illustration. Next, we'll apply the loss calculation to the entire training and validation sets.
Calculating the training and validation set losses
We first need to prepare the training and validation datasets to use for training the LLM.

Figure 5.8 After completing steps 1 and 2, including calculating the cross entropy loss, we can now apply this loss calculation to the entire text dataset we'll use for model training.
To calculate the loss on the training and validation datasets, we'll use a very small text dataset: the short story “The Verdict” by Edith Wharton.
[!NOTE] The Cost of Pretraining Large Language Models
To put the scale of our project into perspective, consider training the 7-billion-parameter Llama 2 model, a relatively popular openly available large language model. The model spent 184,320 GPU hours on expensive A100 GPUs processing 2 trillion tokens. At the time of writing, running an 8 × A100 cloud server on AWS costs about 690,000 (calculated by dividing 184,320 hours by 8 and multiplying by $30).
Next, we'll split the dataset into a training set and a validation set and use the data loader from Chapter 2 to prepare batches for large language model training.

Figure 5.9 When preparing the data loaders, we split the input text into training and validation portions. Then we tokenize the text (for simplicity, only the tokenization of the training portion is shown) and divide the tokenized text into chunks of a user-specified length (here, 6). Finally, we shuffle the order of the rows and organize the chunked text into batches (here, batch size 2) so we can use them for model training.
This process is visualized in Figure 5.9. Due to space constraints, we use maxlength=6. However, for the actual data loaders, we'll set maxlength to the 256-token context length supported by the large language model so that the LLM can see longer text during training.
We're training the model with training data presented in similarly sized chunks for simplicity and efficiency. However, in practice, training an LLM with variable-length inputs can also be beneficial, helping the LLM generalize better to different types of input when in use.
Preparing the Training Data
To split and load the data, we first define a train_ratio that uses 90% of the data for training and the remaining 10% as validation data for model evaluation during training:
We used a relatively small batch size to reduce computational requirements because we're working with a very small dataset. In practice, it's not uncommon to use batch sizes of 1024 or larger when training large language models (LLMs).
As an optional check, we can iterate through the data loaders to make sure they were created correctly:
Based on the preceding code output, we have nine training batches, each with two samples and 256 tokens. Because we allocated only 10% of the data for validation, there is only one validation batch, consisting of two input examples. As expected, the input data (x) and target data (y) have the same shape (batch size times the number of tokens per batch) because the targets are the inputs shifted one position to the right.
How to Calculate Loss
Next, we'll implement a utility function to calculate the cross entropy loss for a given batch returned by the training and validation loaders:
By default, the calclossloader function iterates over all batches in the given data loader, accumulates the loss in the totalloss variable, and then calculates and averages the loss over the total number of batches. Alternatively, we can specify a smaller number of batches via numbatches to speed up evaluation during model training.
Now let's see the calclossloader function in action by applying it to the training and validation set loaders:
The loss values are relatively high because the model hasn't been trained yet. For comparison, if the model learned to generate the next token in the training and validation sets, the loss value would approach 0.
Next, we'll focus on pretraining the LLM. After the model is trained, we'll implement alternative text generation strategies and save and load the pretrained model weights.