In the next article, we will take a look inside a GPT model and then build a small-scale version of it using Python.
What does a GPT look like on the inside?
Suppose we provide the model with the following sentence:
“The cyclist started the race.”
The text will go through the stages we discussed earlier: tokenization, converting tokens into their corresponding IDs, and creating token and positional embeddings.
What happens next?
The Transformer Block
A transformer block is a set of neural network layers that work together.
It utilizes an attention mechanism but also includes several other components:
Multi-head attention — analyzes the relationships between tokens.
FeedForward — processes the representation of each token.
LayerNorm — helps maintain an appropriate scale for values within the model.
Residual connections — allow information from earlier stages to be passed forward, alongside subsequent transformations.
A transformer block takes token representations as input, processes them, and returns new representations. The number of tokens and the dimensionality of their representations do not necessarily change, which allows us to stack several such blocks one after another.
What is the purpose of the FeedForward component?
As we learned in previous articles, the attention mechanism allows tokens to access information about other tokens.
However, we also need additional processing for the information gathered within these representations. This is the role of the FeedForward network—also known as an MLP (Multi-Layer Perceptron). In simple terms, it consists of two linear layers and an activation function.
It performs transformations on the numerical data received from the earlier part of the block.
GPT models, for instance, often use the GELU activation function.
Without getting bogged down in formulas or technical complexities, it introduces a degree of non-linearity into the network, enabling the model to learn more complex relationships. Let’s take a breath…
Things were getting a bit intense, weren’t they?
Normalization and residual connections
Don’t worry—there are only two components left…
The first is LayerNorm, or layer normalization.
As data is processed through a neural network, the resulting numerical values can vary significantly. Normalization helps keep their scale under control, which makes training easier.
The second component is residual connections.
Imagine a layer that receives input data $x$ and transforms it using a function $F$.
Instead of returning only the result of that transformation, we can add the original input to it:
result = $x + F(x)$
Why do this?
This allows information to flow through subsequent blocks without necessarily having to pass through every single transformation. It also helps in training deeper networks.
Transformer block in Python
import torch
from torch import nn
class TransformerBlock(nn.Module):
def __init__(self, emb_dim, n_heads):
super().__init__()
self.norm1 = nn.LayerNorm(emb_dim)
self.att = nn.MultiheadAttention(
embed_dim=emb_dim,
num_heads=n_heads,
batch_first=True
)
self.norm2 = nn.LayerNorm(emb_dim)
self.ff = nn.Sequential(
nn.Linear(emb_dim, 4 * emb_dim),
nn.GELU(),
nn.Linear(4 * emb_dim, emb_dim)
)
def forward(self, x):
seq_len = x.shape[1]
mask = torch.triu(
torch.ones(
seq_len,
seq_len,
device=x.device,
dtype=torch.bool
),
diagonal=1
)
y = self.norm1(x)
att_out, _ = self.att(
y, y, y,
attn_mask=mask,
need_weights=False
)
x = x + att_out
x = x + self.ff(self.norm2(x))
return x
self.att is a multi-head attention mechanism.
self.ff is a feed-forward network.
self.norm1 and self.norm2 handle normalization.
The operations that add x implement residual connections.
Within the forward() method, we also prepare a causal mask. This ensures that tokens cannot access future positions.
And there you have it—the first transformer block.
Combining blocks into a GPT model
Now, we need a complete model.
It will consist of:
Token and positional embeddings.
Several transformer blocks.
A final normalization layer.
An output layer for token prediction.
Let’s use the pre-existing GPT-2 tokenizer. It features a vocabulary containing 50,257 token IDs.
Keep this number in mind; we will return to it several times: 50,257.
Now, let’s define the model class:
class MiniGPT(nn.Module):
def __init__(
self,
vocab_size=50257,
emb_dim=64,
context_length=64,
n_layers=2,
n_heads=4
):
super().__init__()
self.context_length = context_length
self.token_emb = nn.Embedding(
vocab_size, emb_dim
)
self.pos_emb = nn.Embedding(
context_length, emb_dim
)
self.blocks = nn.Sequential(
*[
TransformerBlock(emb_dim, n_heads)
for _ in range(n_layers)
]
)
self.norm = nn.LayerNorm(emb_dim)
self.out_head = nn.Linear(
emb_dim, vocab_size,
bias=False
)
def forward(self, idx):
batch_size, seq_len = idx.shape
if seq_len > self.context_length:
raise ValueError(
"Przekroczono długość kontekstu"
)
positions = torch.arange(
seq_len,
device=idx.device
)
x = (
self.token_emb(idx)
+ self.pos_emb(positions)
)
x = self.blocks(x)
x = self.norm(x)
logits = self.out_head(x)
return logits
We have set emb_dim=64, meaning each token will be represented by a vector of 64 numbers.
The model will have only two transformer blocks, with four attention heads in each block. This is significantly less than the original GPT-2 Small. After all, we don’t intend to compete with the language models created by OpenAI! 😉
The parameter context_length=64 means that the model can process sequences consisting of up to 64 tokens.
Let’s check if the model works.
First, we will create the model:
torch.manual_seed(123)
model = MiniGPT()
print("Liczba parametrów:",
sum(p.numel() for p in model.parameters()))
Result:
Liczba parametrów: 6537088
So, in round numbers, we can say that our model has approximately 6.6 million parameters.
Now, we will check whether the model accepts text.
import tiktoken
tokenizer = tiktoken.get_encoding("gpt2")
tekst = "Kolarz rozpoczął wyścig."
ids = tokenizer.encode(tekst)
x = torch.tensor([ids])
model.eval()
with torch.no_grad():
logits = model(x)
print("Tokeny wejściowe:", len(ids))
print("Kształt wyjścia:", logits.shape)
The final dimension of the output tensor will be 50,257.
These results are called logits. We can now convert them into probabilities using the softmax function.
Let’s check which token the model identifies as the most likely next token:
ostatni_token = logits[0, -1]
next_id = torch.argmax(ostatni_token).item()
print("Przewidywany token:",
repr(tokenizer.decode([next_id])))
What will we see?
Some random piece of text.
Why?
Although we have built a model that takes text as input and attempts to predict the next token—and is even capable of performing all the necessary calculations—there is a problem: the model hasn’t learned anything yet. In other words, it hasn’t been trained!
The parameter values assigned during the model’s creation are, for the most part, still just their initial, random values. They have not yet been adjusted to reflect the patterns and relationships inherent in the Polish language. The model doesn’t simply pick a token at random from the vocabulary; instead, it selects the one for which it has calculated the highest score. At this stage, however, there is no reason to expect that the chosen token will actually fit the context of the sentence.
So, let’s not expect anything spectacular just yet.
What’s next, then?
We already have all the essential components. We know how to convert text into tokens, and we understand how the attention mechanism works. We have also built a GPT model that takes token IDs as input and computes prediction scores.
There is only one thing missing: training.
