
The building blocks needed to build the GPT architecture. So far, we've completed the GPT backbone and layer normalization. Next, we'll focus on GELU activation and the feedforward network.
Next, we'll implement a small neural network submodule that will serve as part of the transformer block in LLMs. We'll start by implementing the GELU activation function, which plays a key role in this neural network submodule.
Historically, the ReLU activation function has been widely used in deep learning because of its simplicity and effectiveness across various neural network architectures. However, large language models (LLMs) use several other activation functions in addition to the traditional ReLU. Two notable examples are GELU (Gaussian error linear unit) and SwiGLU (Swish-gated linear unit).
GELU and SwiGLU are more complex, smoother activation functions that incorporate Gaussian and sigmoid gated linear units, respectively. Unlike the simpler ReLU, they offer better performance for deep learning models.
GELU activation
The GELU activation function can be implemented in several ways; the exact version is defined as GELU(x) = x⋅Φ(x), where Φ(x) is the cumulative distribution function of the standard Gaussian distribution. In practice, however, people usually implement a computationally cheaper approximation (the original GPT-2 model was also trained with this approximation, which was obtained through curve fitting):
class GELU(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(
torch.sqrt(torch.tensor(2.0 / torch.pi)) *
(x + 0.044715 * torch.pow(x, 3))
))
Next, to see what this GELU function looks like and how it compares with ReLU, let's plot the two functions side by side.
import matplotlib.pyplot as plt
gelu, relu = GELU(), nn.ReLU()
# Some sample data
x = torch.linspace(-3, 3, 100)
y_gelu, y_relu = gelu(x), relu(x)
plt.figure(figsize=(8, 3))
for i, (y, label) in enumerate(zip([y_gelu, y_relu], ["GELU", "ReLU"]), 1):
plt.subplot(1, 2, i)
plt.plot(x, y)
plt.title(f"{label} activation function")
plt.xlabel("x")
plt.ylabel(f"{label}(x)")
plt.grid(True)
plt.tight_layout()
plt.show()
As we can see in the resulting plot in Figure 4.8, ReLU (right) is a piecewise linear function: when the input is positive, it outputs the input value directly; otherwise, it outputs zero. GELU (left) is a smooth nonlinear function that approximates ReLU, but its gradient is nonzero for almost all negative values (except around x = –0.75).

Figure 4.8. Output plots of GELU and ReLU created with matplotlib. The x-axis shows the function input, and the y-axis shows the function output.
GELU's smoothness can lead to better optimization properties during training, because it allows for more subtle adjustments to the model parameters.
By contrast, ReLU has a sharp corner at zero (Figure 4.18, right), which can sometimes make optimization harder, especially in very deep networks or networks with complex architectures.
Moreover, unlike ReLU, which outputs zero for any negative input, GELU allows negative values to produce a small, nonzero output. This means that during training, neurons receiving negative inputs can still contribute to the learning process, though to a lesser extent than with positive inputs.
FeedForward Module
Next, let's implement the small neural network module FeedForward using the GELU function; it will be used later in the LLM transformer block.
class FeedForward(nn.Module):
def __init__(self, cfg):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]),
GELU(),
nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]),
)
def forward(self, x):
return self.layers(x)
print(GPT_CONFIG_124M["emb_dim"])
## output
768
As we can see, the FeedForward module is a small neural network made up of two linear layers and a GELU activation function. In the 124-million-parameter GPT model, it receives an input batch with an embedding size of 768 through the GPTCONFIG124M dictionary, where GPTCONFIG124M[emb_dim] = 768.

Figure 4.9. Overview of the connections between layers in the feedforward neural network.
This neural network can accommodate variable batch sizes and numbers of tokens in the input. However, the embedding size for each token is determined and fixed when the weights are initialized.
Following the example in Figure 4.9, let's initialize a new feedforward module with a token embedding size of 768 and feed it a batch input containing two samples with three tokens each:
ffn = FeedForward(GPT_CONFIG_124M)
# input shape: [batch_size, num_token, emb_size]
x = torch.rand(2, 3, 768)
out = ffn(x)
print(out.shape)
## output
torch.Size([2, 3, 768])
The FeedForward module plays a key role in enhancing the model's ability to learn from data and generalize. Although the module's input and output dimensions are the same, internally it expands the embedding dimension into a higher-dimensional space through the first linear layer.
Figure 4.10. Diagram of the expansion and contraction of layer outputs in the feedforward neural network.
As shown in Figure 4.10, the input is first expanded from 768 to 3,072 values, an expansion factor of 4. The second layer then compresses the 3,072 values back into a 768-dimensional representation. This expansion is followed by a nonlinear GELU activation and then a second linear transformation that contracts back to the original dimension. This design allows the model to explore a richer representation space.
In addition, keeping the input and output dimensions the same simplifies the architecture: it lets us stack multiple layers—as we'll do later—without adjusting dimensions between them, making the model more scalable.

Next Build