We’ve already covered several aspects of the LLM architecture, such as input tokenization, embeddings, and the masked multi-head attention module. Now we’ll implement the core structure of the GPT model, including its transformer blocks, and later train it to generate human-like text.

GPT model. In addition to the embedding layer, it consists of one or more transformer blocks, which contain the masked multi-head attention module we implemented earlier.
For example, in a neural network layer represented by a 2,048 × 2,048-dimensional weight matrix (or tensor), every element of that matrix is a parameter. Since there are 2,048 rows and 2,048 columns, the layer has a total of 2,048 times 2,048—that is, 4,194,304—parameters.
GPT-2 Config
GPT_CONFIG_124M = {
"vocab_size": 50257,
"context_length": 1024,
"emb_dim": 768,
"n_heads": 12,
"n_layers": 12,
"drop_rate": 0.1,
"qkv_bias": False
}
- vocab_size refers to a 50,257-word vocabulary used by the BPE tokenizer (see Chapter 2).
- context_length is the maximum number of input tokens the model can handle through positional embeddings.
- emb_dim is the embedding size, which turns each token into a 768-dimensional vector.
- n_heads is the number of attention heads in the multi-head attention mechanism.
- n_layers specifies the number of transformer blocks in the model, which we’ll cover in the upcoming discussion.
- drop_rate is the strength of the dropout mechanism (0.1 means randomly dropping 10% of hidden units) to prevent overfitting.
- qkv_bias determines whether to include bias vectors for the query, key, and value computations in the linear layers of multi-head attention. We’ll initially disable it to follow modern LLM conventions, but we’ll revisit this later when we load pretrained GPT-2 weights from OpenAI into the model.
Build Step 1: GPTModel

https://picbed.fjhdream.cn/202502101612315.png
import torch
import torch.nn as nn
class DummyGPTModel(nn.Module):
def __init__(self, cfg):
super().__init__()
self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
self.drop_emb = nn.Dropout(cfg["drop_rate"])
# Use a placeholder for TransformerBlock
self.trf_blocks = nn.Sequential(
*[DummyTransformerBlock(cfg) for _ in range(cfg["n_layers"])])
# Use a placeholder for LayerNorm
self.final_norm = DummyLayerNorm(cfg["emb_dim"])
self.out_head = nn.Linear(
cfg["emb_dim"], cfg["vocab_size"], bias=False
)
def forward(self, in_idx):
batch_size, seq_len = in_idx.shape
tok_embeds = self.tok_emb(in_idx)
pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
x = tok_embeds + pos_embeds
x = self.drop_emb(x)
x = self.trf_blocks(x)
x = self.final_norm(x)
logits = self.out_head(x)
return logits
class DummyTransformerBlock(nn.Module):
def __init__(self, cfg):
super().__init__()
# A simple placeholder
def forward(self, x):
# This block does nothing and just returns its input.
return x
class DummyLayerNorm(nn.Module):
def __init__(self, normalized_shape, eps=1e-5):
super().__init__()
# The parameters here are just to mimic the LayerNorm interface.
def forward(self, x):
# This layer does nothing and just returns its input.
return x
The DummyGPTModel class in this code defines a simplified GPT-like model using PyTorch’s neural network module (nn.Module). The model architecture in DummyGPTModel consists of token and positional embeddings, dropout, a series of transformer blocks (DummyTransformerBlock), a final layer normalization (DummyLayerNorm), and a linear output layer (outhead). Configuration is passed in through a Python dictionary, such as the GPTCONFIG_124M dictionary we created earlier.
The forward method describes how data flows through the model: it computes token and positional embeddings for the input indices, applies dropout, passes the data through the transformer blocks, applies normalization, and finally generates logits through the linear output layer.
Build Step 2: tiktoken
Next, we’ll prepare the input data and initialize a new GPT model to demonstrate how it’s used. Building on our tokenizer code (see Chapter 2), let’s now take a high-level look at how data goes into and out of the GPT model.
To implement these steps, we use the tiktoken tokenizer from Chapter 2 to tokenize a batch containing two text inputs for the GPT model:
import tiktoken
tokenizer = tiktoken.get_encoding("gpt2")
batch = []
txt1 = "Every effort moves you"
txt2 = "Every day holds a"
batch.append(torch.tensor(tokenizer.encode(txt1)))
batch.append(torch.tensor(tokenizer.encode(txt2)))
batch = torch.stack(batch, dim=0)
print(batch)
## output
tensor([[6109, 3626, 6100, 345], #The first row corresponds to the first text,
[6109, 1110, 6622, 257]]) #The second row corresponds to the second text.

Shows how input data is tokenized, embedded, and fed into the GPT model. Note that in the DummyGPTClass we coded earlier, token embeddings are handled inside the GPT model. In LLMs, the embedding dimension of input tokens typically matches the output dimension. The output embeddings here represent context vectors.
Run the 124-Million Model
Next, we initialize a new DummyGPTModel instance with 124 million parameters and feed it the tokenized batch:
torch.manual_seed(123)
model = DummyGPTModel(GPT_CONFIG_124M)
logits = model(batch)
print("Output shape:", logits.shape)
print(logits)
## output
Output shape: torch.Size([2, 4, 50257])
tensor([[[-1.2034, 0.3201, -0.7130, ..., -1.5548, -0.2390, -0.4667],
[-0.1192, 0.4539, -0.4432, ..., 0.2392, 1.3469, 1.2430],
[ 0.5307, 1.6720, -0.4695, ..., 1.1966, 0.0111, 0.5835],
[ 0.0139, 1.6754, -0.3388, ..., 1.1586, -0.0435, -1.0400]],
[[-1.0908, 0.1798, -0.9484, ..., -1.6047, 0.2439, -0.4530],
[-0.7860, 0.5581, -0.0610, ..., 0.4835, -0.0077, 1.6621],
[ 0.3567, 1.2698, -0.6398, ..., -0.0162, -0.1296, 0.3717],
[-0.2407, -0.7349, -0.5102, ..., 2.0057, -0.3694, 0.1814]]],
grad_fn=<UnsafeViewBackward0>)
The output tensor has two rows, corresponding to the two text samples. Each text sample consists of four tokens; each token is a 50,257-dimensional vector, which matches the size of the tokenizer vocabulary.
The embeddings have 50,257 dimensions because each of these dimensions represents a unique token in the vocabulary. When we implement the post-processing code, we’ll convert these 50,257-dimensional vectors back into token IDs, which can then be decoded into words.
Now that we’ve looked at the GPT architecture as a whole, along with its inputs and outputs, we’ll start filling in the placeholders, beginning with the actual layer normalization class that will replace DummyLayerNorm in the earlier code.