Training deep neural networks can sometimes be challenging because of issues such as vanishing or exploding gradients. These problems make training dynamics unstable, so the network struggles to adjust its weights effectively. That means the learning process has trouble finding a set of parameters (weights) that minimizes the neural network's loss function. In other words, the network has difficulty learning the underlying patterns in the data, which makes it hard for it to make accurate predictions or decisions.
Now let's implement layer normalization to improve the stability and efficiency of neural network training. The main idea behind layer normalization is to adjust the activations (outputs) of a neural network layer so that they have a mean of 0 and a variance of 1, also known as unit variance. This adjustment speeds up the model's convergence to effective weights and ensures consistent, reliable training.
Mean and Variance
In GPT-2 and modern transformer architectures, layer normalization is typically applied before and after the multi-head attention module.

An illustration of layer normalization, where six outputs of a layer—also called activations—are normalized to have a mean of 0 and a variance of 1.
torch.manual_seed(123)
# create 2 training examples with 5 dimensions (features) each
batch_example = torch.randn(2, 5)
layer = nn.Sequential(nn.Linear(5, 6), nn.ReLU())
out = layer(batch_example)
print(out)
## output
tensor([[0.2260, 0.3470, 0.0000, 0.2216, 0.0000, 0.0000],
[0.2133, 0.2394, 0.0000, 0.5198, 0.3297, 0.0000]],
grad_fn=<ReluBackward0>)
The neural network layer we've coded consists of a linear layer followed by a nonlinear activation function, ReLU (short for rectified linear unit), which is a standard activation function in neural networks. If you're not familiar with ReLU, it simply thresholds negative inputs to 0, ensuring that the layer's output contains only positive values. This also explains why the output of the resulting layer contains no negative values.
Before we apply layer normalization to these outputs, let's look at the mean and variance:
mean = out.mean(dim=-1, keepdim=True)
var = out.var(dim=-1, keepdim=True)
print("Mean:\n", mean)
print("Variance:\n", var)
## output
Mean:
tensor([[0.1324], # 第一行tensor均值
[0.2170]], grad_fn=<MeanBackward1>) # 第二行tensor均值
Variance:
tensor([[0.0231],
[0.0398]], grad_fn=<VarBackward0>)
Preserving Tensor Dimensions
Using keepdim=True when performing operations such as mean or variance calculations ensures that the output tensor retains the same number of dimensions as the input tensor, even when the operation reduces the tensor along the dimension specified by dim. For example, without keepdim=True, the returned mean tensor would be a vector of two elements [0.1324, 0.2170] instead of a 2 × 1 matrix [[0.1324], [0.2170]].

An illustration of the dim parameter when calculating the mean of a tensor.
For example, if we have a two-dimensional tensor (matrix) with dimensions [rows, columns], using dim=0 performs the operation across rows (vertically, as shown at the bottom), and the resulting output aggregates the data in each column. Using dim=1 or dim=-1 performs the operation across columns (horizontally, as shown at the top), and the resulting output aggregates the data in each row.
For a two-dimensional tensor (similar to a matrix), using dim=-1 for mean or variance calculations is the same as using dim=1. This is because -1 refers to the tensor's last dimension, which corresponds to the columns in a two-dimensional tensor. Later, when we add layer normalization to the GPT model, the model produces a three-dimensional tensor with shape [batchsize, numtokens, embedding_size]; we can still use dim=-1 to normalize the last dimension, avoiding a change from dim=1 to dim=2.
Layer Normalization
Next, let's apply layer normalization to the layer outputs we obtained earlier. This operation consists of subtracting the mean and dividing by the square root of the variance (also known as the standard deviation):
out_norm = (out - mean) / torch.sqrt(var)
print("Normalized layer outputs:\n", out_norm)
mean = out_norm.mean(dim=-1, keepdim=True)
var = out_norm.var(dim=-1, keepdim=True)
print("Mean:\n", mean)
print("Variance:\n", var)
## output
Normalized layer outputs:
tensor([[ 0.6159, 1.4126, -0.8719, 0.5872, -0.8719, -0.8719],
[-0.0189, 0.1121, -1.0876, 1.5173, 0.5647, -1.0876]],
grad_fn=<DivBackward0>)
Mean:
tensor([[-5.9605e-08],
[ 1.9868e-08]], grad_fn=<MeanBackward1>)
Variance:
tensor([[1.0000],
[1.0000]], grad_fn=<VarBackward0>)
Note that the value –5.9605e-08 in the output tensor is scientific notation for –5.9605 × 10⁻⁸, which in decimal form is –0.000000059605. This value is very close to 0, but it is not exactly equal to 0 because of the small rounding errors caused by the limited precision with which computers represent numbers.
To improve readability, we can also turn off scientific notation when printing tensor values by setting sci_mode to False:
So far, we've coded and applied layer normalization step by step. Now let's encapsulate this process in a PyTorch module that we can use later in the GPT model.
Applying Layer Normalization
- This particular layer normalization implementation operates on the last dimension of the input tensor x, which represents the embedding dimension (emb_dim).
- The variable eps is a small constant (epsilon) added to the variance to prevent division by zero during normalization.
- scale and shift are two trainable parameters (with the same dimensions as the input). If doing so is found to improve the model's performance on its training task, the LLM automatically adjusts them during training. This lets the model learn the appropriate scaling and shifting to best suit the data it processes.
[!NOTE] Biased Variance
In our variance calculation method, we use an implementation detail by setting unbiased=False. For those curious about what that means: in the variance calculation, we divide the total by the number of inputs n in the variance formula. This approach does not apply Bessel's correction, which typically uses n – 1 instead of n in the denominator to adjust for the bias in the sample variance estimate. This decision results in what is called a biased variance estimate. For LLMs, where the embedding dimension n is significantly large, the difference between using n and n – 1 is practically negligible. I chose this approach to ensure compatibility with the normalization layer of the GPT-2 model and because it reflects TensorFlow's default behavior, which was used to implement the original GPT-2 model. Using a similar setup ensures that our method is compatible with the pretrained weights we'll load later.
Now let's try the LayerNorm module in practice and apply it to a batch input:

The building blocks necessary to build the GPT architecture. So far, we have completed the GPT backbone and layer normalization. Next, we will focus on GELU activation and the feedforward network.