The Training Loop and Optimization
Implementation of the training cycle, computation of the loss function (cross-entropy), backpropagation, and configuration of the AdamW optimizer.
The “heart” of any deep learning system is the training loop. It is in this iterative cycle that the model’s parameters (weights and biases) are mathematically adjusted to minimize the error between the model’s predictions and the real data.
In this chapter, we dissect the architecture of the training cycle, the mathematics behind the cross-entropy loss function, the mechanics of backpropagation, and the rationale for using the AdamW optimizer in Transformer-based architectures.
10.1 Overview of the Training Cycle
In self-supervised pre-training, the texts themselves provide the labels: each input sequence is shifted to create the target tokens. This makes it possible to learn from large corpora without manual annotation, but it passes on to the model the patterns, gaps, and biases present in the sources. Deduplication, normalization, removal of personal data, and balancing across domains are part of the modeling problem, not just cleaning.
Quality and diversity matter as much as volume. A corpus should represent languages, genres, and knowledge relevant to the application, while respecting licenses and privacy. Datasets contaminated by evaluation examples make later metrics unreliable.
Training a neural network is a stochastic optimization process. The goal is to find a set of parameters that minimizes a cost function .
The data flow occurs in two directions:
- Forward pass (propagation): Data flows from input to output, generating predictions (logits).
- Backward pass (backpropagation): The error flows from output to input, computing the gradient of the loss with respect to each parameter.
10.1.1 Training Flow Diagram
The diagram below illustrates the interaction between the data, the model, the loss function, and the optimizer.

10.2 The Loss Function: Cross-Entropy
For language models (LLMs), the goal is to predict the next token in a sequence. This is treated as a multiclass classification problem, where the number of classes equals the vocabulary size ().
The standard loss function is cross-entropy. It measures the divergence between two probability distributions:
- (true distribution): A one-hot distribution representing the true token.
- (predicted distribution): The probabilities generated by the model (after applying softmax to the logits).
The mathematical formula for a single example is:
In PyTorch, the nn.CrossEntropyLoss class combines two operations for numerical stability: LogSoftmax and NLLLoss (Negative Log Likelihood Loss).
Why cross-entropy? It strongly penalizes confident but wrong predictions. If the model assigns a low probability to the correct token, the logarithm of that probability yields a large negative value, dramatically increasing the loss.
10.3 The Optimizer: AdamW
Although Stochastic Gradient Descent (SGD) is the foundation, modern models (especially Transformers) use adaptive variants. The current industry standard is AdamW.
10.3.1 Adam vs. AdamW
- Adam (Adaptive Moment Estimation): Computes adaptive learning rates for each parameter. It stores exponential moving averages of past gradients (, first moment) and of squared gradients (, second moment).
- The problem with Adam: The original Adam implementation applied L2 regularization (weight decay) together with the adaptive gradient computation. This coupled the regularization to the magnitude of the gradients, which often led to suboptimal generalization.
- The AdamW solution (decoupled weight decay): AdamW decouples weight decay from the gradient update. Weight decay is applied directly to the parameters after the main optimization step.
The parameter update in AdamW follows this logic:
- Update parameters based on the adaptive gradients (classic Adam).
- Apply weight decay: (where is the decay factor).
This allows more aggressive weight decay rates without harming learning, resulting in models that generalize better.
10.4 Technical Implementation
Below we present a robust implementation of the training loop using PyTorch.
10.4.1 Code Structure
import torch
import torch.nn as nn
from torch.optim import AdamW
from torch.utils.data import DataLoader
def train_epoch(
model: nn.Module,
dataloader: DataLoader,
optimizer: torch.optim.Optimizer,
device: torch.device,
clip_grad: float = 1.0
) -> float:
"""
Runs one training epoch.
Args:
model: The Transformer model.
dataloader: Iterator of batched data.
optimizer: Configured optimizer (AdamW).
device: CPU or CUDA.
clip_grad: Value for gradient clipping.
Returns:
Mean loss over the epoch.
"""
model.train() # Puts the model in training mode (enables Dropout, etc.)
total_loss = 0.0
# Loss function definition
# ignore_index is used to ignore padding tokens in the loss computation
criterion = nn.CrossEntropyLoss(ignore_index=0)
for batch_idx, (inputs, targets) in enumerate(dataloader):
# 1. Move data to the device (GPU/TPU)
inputs = inputs.to(device)
targets = targets.to(device)
# 2. Zero the accumulated gradients
# Essential: PyTorch accumulates gradients by default.
optimizer.zero_grad(set_to_none=True)
# 3. Forward pass
# The model returns logits of shape (Batch, Seq_Len, Vocab_Size)
logits = model(inputs)
# 4. Reshape for the loss computation
# CrossEntropy expects (N, C) or (N, C, d1...)
# We flatten Batch and Seq_Len to treat each token as an instance
B, T, C = logits.shape
logits = logits.view(B * T, C)
targets = targets.view(B * T)
# 5. Loss computation
loss = criterion(logits, targets)
# 6. Backward pass (backpropagation)
# Computes dLoss/dWeights for all parameters
loss.backward()
# 7. Gradient clipping
# Crucial in Transformers to avoid exploding gradients
torch.nn.utils.clip_grad_norm_(model.parameters(), clip_grad)
# 8. Optimizer step
# Updates the weights: w = w - lr * grad
optimizer.step()
total_loss += loss.item()
# (Optional) Intra-epoch logging
if batch_idx % 100 == 0:
print(f"Batch {batch_idx} | Loss: {loss.item():.4f}")
return total_loss / len(dataloader)
# Optimizer configuration example
# model = MyTransformer(...)
# optimizer = AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
10.5 Critical Architecture Details
10.5.1 Gradient Accumulation
If the GPU memory cannot support the desired batch size (e.g., 512), we use gradient accumulation. We run the forward and backward passes several times with smaller micro-batches, but only call optimizer.step() after steps.
10.5.2 Gradient Clipping
Transformers are deep and sensitive. Gradients can grow exponentially (exploding gradients), destabilizing training. clip_grad_norm_ rescales the global gradient vector if its norm exceeds a threshold (usually 1.0), keeping the direction but limiting the magnitude.
10.5.3 set_to_none=True
When zeroing gradients, using optimizer.zero_grad(set_to_none=True) is slightly more memory-efficient than setting the tensors to zero, since it avoids unnecessary memory read/write operations.
10.6 Chapter Summary
The success of training an LLM depends on a delicate balance between the model architecture and the optimization algorithm. We use cross-entropy to guide the model probabilistically and AdamW to navigate the complex error surface efficiently, decoupling regularization from step adaptation. A correct implementation of the loop, including safeguards such as gradient clipping, is mandatory for the model to converge.
10.7 Instrumentation and Debugging
Record loss, learning rate, gradient norm, tokens processed per second, and memory usage. A loss that becomes NaN may indicate a high learning rate, overflow in reduced precision, invalid data, or an incorrect mask. The gradient norm helps distinguish gradient explosion from a problem in the input.
An effective batch with accumulation is micro_batch × accumulation_steps × number_of_devices. Divide the loss by the number of accumulation steps before backward() to keep the gradient scale equivalent to the mean over the larger batch.
Order of operations
With mixed precision, unscale the gradients before clipping. Only then run the optimizer step, update the scaler, and zero the gradients.
10.8 Scale of Model, Data, and Compute
Empirical results show predictable relationships between loss, amount of data, parameters, and compute, but increasing only one dimension can waste resources. Planning should balance model capacity and the number of tokens, while also considering inference, energy, and evaluation cost. Capabilities observed at scale need to be measured directly; they should not be presumed from the parameter count alone.
10.9 Overfitting, Underfitting, and Regularization
Underfitting occurs when the model or the training procedure cannot adequately reduce even the training loss. It may indicate insufficient capacity, too few steps, an inadequate learning rate, or difficult data. Overfitting appears when training performance improves but validation stops following or worsens.
Regularization is not a single technique. Weight decay discourages excessive weights; dropout perturbs activations during training; early stopping chooses a checkpoint before validation degradation; data diversity reduces dependence on narrow patterns. In LLMs, deduplication and control of the proportion among sources also act as corpus regularization.
training loss: 3.2 -> 2.4 -> 1.8 -> 1.3
validation loss: 3.3 -> 2.6 -> 2.5 -> 2.8
^ best checkpoint
Training longer can make things worse
A lower training loss does not compensate for a loss of generalization. Stopping criteria and checkpoint selection should be defined before observing the test set.
10.10 Hyperparameter Tuning
Grid search evaluates predetermined combinations, but grows exponentially with the number of dimensions. Random search usually explores better when a few hyperparameters dominate the result. Bayesian methods use previous results to suggest new trials, which is useful when each training run is expensive.
Start with logarithmic ranges for learning rate and weight decay. Run short trials, eliminate unstable configurations, and only then invest in long runs. Compare under the same token budget and record configuration, code, seed, and hardware.
10.11 Scaling Laws as a Planning Tool
Scaling curves fit empirical relationships between loss and resources. They help estimate whether the next increment should go to data, parameters, or steps, but they are valid in the measured regime. Changes in architecture, data quality, and objective can shift the curve. Extrapolation is a quantitative hypothesis, not a promise of new capabilities.