Now it’s finally time to implement the code for pretraining our GPTModel. To do that, we’ll focus on a simple training loop to keep the code concise and easy to read.

Figure 5.11 A typical training loop for training a deep neural network in PyTorch consists of several steps, iterating over batches of the training set for multiple epochs. In each loop, we compute the loss for each training batch to determine the loss gradients, then use those gradients to update the model weights, minimizing the training set loss.
The flowchart in Figure 5.11 depicts a typical PyTorch neural network training workflow, which we’ll use to train an LLM. It outlines eight steps: starting by iterating over each epoch, processing batches, resetting gradients, computing the loss and new gradients, updating the weights, and ending with monitoring steps such as printing the loss and generating text samples.
def train_model_simple(model, train_loader, val_loader, optimizer, device, num_epochs,
eval_freq, eval_iter, start_context, tokenizer):
# Initialize lists to track losses and tokens seen
train_losses, val_losses, track_tokens_seen = [], [], []
tokens_seen, global_step = 0, -1
# Main training loop
for epoch in range(num_epochs):
model.train() # Set model to training mode
for input_batch, target_batch in train_loader:
optimizer.zero_grad() # Reset loss gradients from previous batch iteration
loss = calc_loss_batch(input_batch, target_batch, model, device)
loss.backward() # Calculate loss gradients
optimizer.step() # Update model weights using loss gradients
tokens_seen += input_batch.numel()
global_step += 1
# Optional evaluation step
if global_step % eval_freq == 0:
train_loss, val_loss = evaluate_model(
model, train_loader, val_loader, device, eval_iter)
train_losses.append(train_loss)
val_losses.append(val_loss)
track_tokens_seen.append(tokens_seen)
print(f"Ep {epoch+1} (Step {global_step:06d}): "
f"Train loss {train_loss:.3f}, Val loss {val_loss:.3f}")
# Print a sample text after each epoch
generate_and_print_sample(
model, tokenizer, device, start_context
)
return train_losses, val_losses, track_tokens_seen
def evaluate_model(model, train_loader, val_loader, device, eval_iter):
model.eval()
with torch.no_grad():
train_loss = calc_loss_loader(train_loader, model, device, num_batches=eval_iter)
val_loss = calc_loss_loader(val_loader, model, device, num_batches=eval_iter)
model.train()
return train_loss, val_loss
The evaluate_model function corresponds to step 7 in Figure 5.11. It prints the training and validation losses after each model update so we can assess whether training is improving the model.
More specifically, when computing the training and validation losses, the evaluate_model function ensures the model is in evaluation mode and disables gradient tracking and dropout while calculating the loss.
def generate_and_print_sample(model, tokenizer, device, start_context):
model.eval()
context_size = model.pos_emb.weight.shape[0]
encoded = text_to_token_ids(start_context, tokenizer).to(device)
with torch.no_grad():
token_ids = generate_text_simple(
model=model, idx=encoded,
max_new_tokens=50, context_size=context_size
)
decoded_text = token_ids_to_text(token_ids, tokenizer)
print(decoded_text.replace("\n", " ")) # Compact print format
model.train()
Similar to evaluatemodel, the generateandprintsample function is a convenience function we use to track whether the model is improving during training. Specifically, generateandprintsample takes a text snippet (startcontext) as input, converts it to token IDs, and then feeds it to the LLM to generate a text sample using the generatetextsimple function we used earlier.
Whereas the evaluatemodel function gives a numerical estimate of the model’s training progress, the generateandprintsample function provides a concrete text sample generated by the model so we can judge its capabilities during training.
[!NOTE] AdamW
The Adam optimizer is a popular choice for training deep neural networks. However, in our training loop we use the AdamW optimizer. AdamW is a variant of Adam that improves the weight decay method, aiming to minimize model complexity and prevent overfitting by penalizing large weights. This adjustment enables AdamW to achieve more effective regularization and better generalization; as a result, AdamW is widely used for training LLMs.
Let’s see how this works in practice by training a GPTModel instance for 10 epochs using the AdamW optimizer and the trainmodelsimple function we defined earlier:
# Note:
# Uncomment the following code to calculate the execution time
# import time
# start_time = time.time()
torch.manual_seed(123)
model = GPTModel(GPT_CONFIG_124M)
model.to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=0.0004, weight_decay=0.1)
num_epochs = 10
train_losses, val_losses, tokens_seen = train_model_simple(
model, train_loader, val_loader, optimizer, device,
num_epochs=num_epochs, eval_freq=5, eval_iter=5,
start_context="Every effort moves you", tokenizer=tokenizer
)
# Note:
# Uncomment the following code to show the execution time
# end_time = time.time()
# execution_time_minutes = (end_time - start_time) / 60
# print(f"Training completed in {execution_time_minutes:.2f} minutes.")
As we can see, the training loss improves substantially, starting at 9.781 and converging to 0.391. The model’s language ability improves considerably. At first, the model can only append commas to the starting context ((Every effort moves you,,,,,,,,,,,,) or repeat the word “and.” By the end of training, it can generate grammatically correct text.
Similar to the training loss, we can see that the validation loss starts high (9.933) and decreases during training. However, it never becomes as low as the training loss, remaining at 6.452 after the 10th epoch.
Before discussing the validation loss in more detail, let’s create a simple plot that shows the training and validation losses side by side for comparison:

image.png
The resulting training and validation loss plot is shown in Figure 5.12. We can see that both training and validation loss begin improving in the first epoch. However, the losses start to diverge after the second epoch. This divergence, along with the fact that the validation loss is much larger than the training loss, indicates that the model is overfitting the training data.
We can confirm that the model has memorized the training data verbatim by searching the generated text snippets—for example, in the “verdict” text file, its grasp of irony comes across as completely flat.
This memorization is expected because we’re using a very, very small training dataset and training the model for multiple epochs. Normally, you’d train for only a single epoch on a much larger dataset.