GPT Model
Before we assemble the GPT-2 model in code, let's look at its overall structure, as shown in Figure 4.15, which brings together all the concepts we've covered so far. As we can see, the Transformer Block repeats multiple times in the GPT model architecture. In the 124-million-parameter GPT-2 model, it repeats 12 times, specified by the nlayers entry in the GPTCONFIG_124M dictionary. In the largest GPT-2 model, with 1,542 million parameters, this Transformer Block repeats 48 times.
The final Transformer Block output passes through a final layer normalization step and then reaches a linear output layer. This layer maps the transformer's output into a high-dimensional space (in this case, 50,257 dimensions, corresponding to the model's vocabulary size) to predict the next token in the sequence.

Figure 4.15 Overview of the GPT model architecture, showing how data flows through the GPT model.
[!NOTE] Title
The init constructor of this GPTModel class initializes the token and positional embedding layers using the configuration passed in through the Python dictionary cfg. These embedding layers convert input token indices into dense vectors and add positional information.
Next, the init method creates a sequential stack of TransformerBlock modules equal to the number of layers specified in cfg. After the transformer blocks, a LayerNorm layer is applied to normalize the output of the transformer blocks and stabilize the learning process. Finally, it defines a bias-free linear output head that projects the transformer's output into the tokenizer's vocabulary space, producing logits for each token in the vocabulary.
The FeedForward method accepts a batch of input token indices, computes their embeddings, applies positional embeddings, passes the sequence through the transformer blocks, normalizes the final output, and then computes logits representing the unnormalized probabilities of the next token. In the next section, we'll convert these logits into tokens and text output.
Now let's initialize the 124-million-parameter GPT model using the GPTCONFIG124M dictionary we pass to the cfg parameter, and feed it the batch of text input we created earlier:
Before we continue coding the function that turns the model output into text, let's spend a little more time on the model architecture itself and analyze its size. Using the numel() method—short for “number of elements”—we can collect the total number of parameters in the model's parameter tensors:
Earlier, we said we were initializing a GPT model with 124 million parameters, so why is the actual parameter count 163 million? The reason is a concept called weight tying, which was used in the original GPT-2 architecture. This means the original GPT-2 architecture reused the weights from the token embedding layer in its output layer. To understand this better, let's look at the shapes of the token embedding layer and linear output layer we initialized earlier via GPTModel:
As you can see from the printed output, the weight tensors of these two layers have the same shape. Because the tokenizer's vocabulary has 50,257 rows, the token embedding and output layers are very large. With weight tying, let's remove the output layer's parameter count from the total GPT-2 model count:
As we can see, the model now has only 124 million parameters, matching the original size of the GPT-2 model.
Weight tying reduces the model's overall memory footprint and computational complexity. However, in my experience, using separate token embedding and output layers leads to better training and model performance; therefore, we use separate layers in our GPTModel implementation. Modern large language models do the same.
Finally, let's calculate the memory requirements for the 163 million parameters in our GPTModel object:
Now that we've implemented the GPTModel architecture and seen that it outputs a numeric tensor of shape [batchsize, numtokens, vocab_size], let's write the code to convert these output tensors into text.
Generating Text
We'll now implement the code that converts the GPT model's tensor output back into text. Before we start, let's briefly review how a generative model like an LLM produces text one word (or token) at a time.

Figure 4.16 The step-by-step process by which an LLM generates text, one token at a time.
Figure 4.16 shows the step-by-step process by which a GPT model generates text from an input context such as “Hello, I am.” With each iteration, the input context grows, enabling the model to generate coherent, context-appropriate text. At the sixth iteration, the model has constructed a complete sentence: “Hello, I am a model ready to help.” We've already seen that our current GPTModel implementation outputs a tensor of shape [batchsize, numtoken, vocab_size].
So the question is: how does the GPT model generate text from these output tensors?

Figure 4.17 shows the mechanism of text generation in a GPT model by illustrating a single iteration in the token generation process.
The next-word generation process is shown in Figure 4.17, which illustrates a single step in which the GPT model generates the next word given an input.
At each step, the model outputs a matrix whose vectors represent potential next words. The vector corresponding to the next word is extracted and converted into a probability distribution via the softmax function. In the vector containing the resulting probability scores, the index with the highest value is found, and that index corresponds to the word's ID. The word ID is then decoded back into text, producing the next word in the sequence. Finally, that word is added to the previous input to form the new input sequence for the next sub-iteration.
This step-by-step process lets the model generate text sequentially, building coherent phrases and sentences from the initial input context.
This code demonstrates a simple implementation of a generation loop for a language model using PyTorch. It iteratively generates the specified number of new tokens, crops the current context to fit the model's maximum context size, computes predictions, and then selects the next token based on the highest-probability prediction.
To code the generatetextsimple function, we use the softmax function to convert logits into a probability distribution and then use torch.argmax to determine the position with the highest value. The softmax function is monotonic, meaning it preserves the order of its inputs when producing outputs. So in practice, the softmax step is redundant, because the position with the highest score in the softmax output tensor is the same as the position in the logits tensor.
In other words, we could apply torch.argmax directly to the logits tensor and get the same result. However, I included the conversion code to illustrate the full process of turning logits into probabilities, which can add intuition that the model is generating the most likely next token—a method known as greedy decoding.
In the next chapter, when we implement the GPT training code, we'll use additional sampling techniques to modify the softmax output so that the model doesn't always choose the most likely token. This introduces variability and creativity into the generated text.

Figure 4.18 Six iterations of the token prediction cycle, in which the model takes the sequence of initial token IDs as input, predicts the next token, and appends that token to the input sequence for the next iteration.
This process of generating token IDs one at a time and appending them to the context with the generatetextsimple function is further illustrated in Figure 4.18. (The token ID generation process for each iteration is detailed in Figure 4.17.)
We generate token IDs iteratively. For example, in iteration 1, the model is given the tokens corresponding to “Hello, I am,” predicts the next token (ID 257, which is “a”), and appends it to the input. This process repeats until the model has generated the complete sentence “Hello, I am a model ready to help” after six iterations.
Now let's try calling the generatetextsimple function with “Hello, I am” as the model input context. First, we encode the input context into token IDs:
Next, we put the model into .eval() mode. This disables stochastic components such as dropout, which are used only during training, and then we call the generatetextsimple function on the encoded input tensor:
As we can see, the model generated gibberish. What happened? The reason the model can't produce coherent text is that we haven't trained it yet. So far, we've only implemented the GPT architecture and initialized a GPT model instance with random initial weights.
Summary
- Layer normalization stabilizes training by ensuring that each layer's output has a consistent mean and variance.
- Shortcut connections are connections that skip one or more layers by passing a layer's output directly to deeper layers; this helps mitigate the vanishing gradient problem when training deep neural networks, especially large language models (LLMs).
- The Transformer Block is the core structural component of the GPT model, combining a masked multi-head attention module with a fully connected feedforward network that uses the GELU activation function.
- GPT models are LLMs with a large number of parameters, built from multiple repeated Transformer Blocks, with parameter counts ranging from millions to billions.
- GPT models come in different sizes—for example, 124 million, 345 million, 762 million, and 1,542 million parameters—and we can implement all of them using the same GPTModel Python class.
- The text generation capability of GPT-like LLMs involves decoding output tensors into readable text by predicting one token at a time based on a given input context.
- Without training, a GPT model generates incoherent text, highlighting how important training is for producing coherent text.