Chapter 10: The Full GPT Architecture¶
Figure 10.1: We connect everything to output a prediction.
We have built all the core components of a Transformer model in previous chapters, so we can now assemble them (Figure 10.1). In this chapter you will:
- Build the full GPT model from end to end.
- See how data flows through the entire pipeline.
- Understand the final raw scores, called logits.
Words to Know
- LM Head: The model's last step, which turns each token's internal numbers into one score for every character in the vocabulary.
- Logits: The raw scores the model outputs for each possible next token.
Theory¶
The Final Assembly¶
The complete GPT model is simple once you have the pieces.
Figure 10.2: The full forward pass of the GPT model.
It flows like a production assembly line (Figure 10.2):
- Turn text into a list of numbers (Token IDs).
- Look up the meaning and position vectors (Embeddings).
- Process them through a stack of Transformer blocks.
- Tidy up the numbers one last time (Final LayerNorm).
- Map the internal 128 numbers back to the 65 possible characters (LM Head).
Tracing the Flow¶
Let's follow a specific example. Imagine we give the model the word "ROMEO" (5 tokens).
Step 1: Input
The input is [30, 27, 25, 17, 27]. Each of those is the token ID of an individual character in "ROMEO". 30 is token 'R', 27 is 'O', 25 is 'M', and 17 is 'E' in our vocabulary.
Step 2: Embeddings The model converts these 5 IDs into 5 rich vectors (128 numbers each), combining both meaning and position.
Step 3: Transformer Blocks
That information will be passed through 4 blocks. By the time it passes through all 4 blocks, the token O will have some knowledge of every other letter preceding it. Those 128 numbers will encode information such as "I am the final letter of a name in a famous play."
Step 4 & 5: Final Output One more LayerNorm helps stabilize those numbers. And then the LM Head (Language Model Head) takes those 128 numbers and transforms them into 65 numbers. Why 65? Because there are 65 unique characters in our Shakespeare dataset.
Figure 10.3: The LM Head projects internal data back to our vocabulary.
The model predicts 65 scores per token in the sequence (see Figure 10.3). Positions in the sequence independently predict the next character. The token with the largest score in the final position is the predicted character following "ROMEO".
What Are Logits?¶
Those 65 numbers that our LM Head gives us are known as logits.
A logit is a technical term for "raw score" (see Figure 10.4). They can be negative, zero, or very large. They also don't sum to equal 1 so we cannot call them probabilities. We will turn these raw scores into percentages later in Chapter 11 when we learn how to generate text. But just remember a bigger logit equals a higher chance of that character being chosen.
Figure 10.4: Logits are the raw scores for the next character.
We have coded everything from Text down to Next-Token Scores on the big picture map in Figure 10.1. Our model is complete, but it just makes random guesses at this point and we must train it.
Code¶
Run the script to see the parameter breakdown and a test run.
$ python src/ch09_gpt_model.py
Model parameter breakdown:
Token embedding : 8,320
Position embedding: 16,384
4 Transformer blocks: 791,552
LM head : 8,320
LayerNorm (final): 256
---
TOTAL : 824,832
Input shape: torch.Size([2, 10]) (B, T)
Output shape: torch.Size([2, 10, 65]) (B, T, vocab_size)
At each position, model outputs 65 scores.
The highest score = best guess for next character.
First position logits (top 5 scores):
token 26: 1.861
token 21: 1.195
token 44: 1.118
token 57: 1.071
token 34: 0.972
Note: these are random (untrained model).
What just happened:
- Line 1 assembles the complete GPT class.
- Line 12 actually instantiates the four blocks. These account for 791,552 of the 824,832 parameters (weights) in the entire model. The original GPT-2 Small had 117 million parameters. Same architecture, just smaller.
- Line 38 finishes the forward pass, where the model outputs 65 logits (scores) for each position.
Shape Check:
- Input token IDs:
[Batch, Time] - Output logits:
[Batch, Time, 65](Vocab size is 65)
Try It¶
Try It
Open src/ch09_gpt_model.py. Locate the line config = GPTConfig() and insert a new line underneath it: config.n_layers = 6. Execute the script once more. The parameter count grows, and most of the parameters are in the blocks.
In Business
Think of building our final GPT model as building a pipeline out of Lego bricks. You've got your data reader (embeddings), processor (your blocks) and output (the LM head). You can upgrade your house-style GPT's processor by stacking more layers on without having to replace any other parts of your pipeline.
Key Takeaways¶
- The full model stacks embeddings, Transformer blocks, and a final LM head.
- The LM head is the last step, which turns each token's internal numbers into one score for every character in the vocabulary.
- The model outputs logits, which are raw scores for the next token and are not probabilities yet.
- Our complete model has ~825K parameters, so this architecture can be built at a small scale.
Check Your Understanding¶
- If the input sequence has 10 tokens, how many predictions does the model make?
- Why does the LM head output exactly 65 numbers per token?
- What is a logit?
Assignment¶
Assignment 10: Shorter text, same model
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch09_gpt_model.pyas it is. Copy three lines: theTOTALline and the two shape lines,Input shapeandOutput shape. - Change one number. Near the bottom of the file, find the line
B, T = 2, 10.Bis how many test sequences the script feeds in, andTis how many tokens each one holds. Change10to5, the length ofROMEO, and run the script again. - Compare. Which numbers in the two shape lines changed, and which did not? Did the
TOTALline change? How many sets of 65 scores does the model now give for each sequence? The five scores at the bottom shift too. They come from an untrained model, so set them aside. - Explain it. In two or three sentences a manager could follow, say what the model hands back when it reads a five-character input such as
ROMEO, and why a shorter input does not make the model itself any smaller.
Hand in: both sets of three lines, your answers to step 3, and your sentences.
Further Reading¶
One model, many jobs, no retraining. The researchers wanted to know if a model trained exclusively to predict the next word would learn capabilities nobody had trained it for. Because it was trained on such a broad, diverse swath of web pages, it started answering questions, summarizing, and translating with zero task-specific training when given a prompt that made those tasks obvious. That answered the architectural question of how to build a system for text generation in favor of a decoder architecture that predicts the next token. That's the model we cover in Chapter 10.
Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language models are unsupervised multitask learners [Technical report]. OpenAI. https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf
Next up: Chapter 11: Causal Language Modeling