The complete transformer
What is inside an LLM, block by block?
Lesson complete
If you like:
You already know the pieces: tokens, embeddings, attention, and next-word prediction. Today we put them together into one machine: the transformer, the one inside GPT.
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Follow the full path of a sentence inside a transformer: tokens, numbers, embeddings, blocks, scores, softmax, and the next word.
- Explain what each piece of a block does (attention, network, residual connection, and layer normalization) and why positional encoding and the causal mask are needed.
- Calculate how many parameters each part of a small transformer has and recognize where almost all the size of a real model like GPT-3 lives.
Key ideas
- A transformer always follows the same path: tokens, numbers, embeddings plus position, a stack of blocks, and, from the last token’s list, one score per word that softmax turns into probabilities.
- Each block has two parts: attention, the only path by which a token receives information from the others, and a network that processes each token separately.
- No part replaces a token’s list: it adds its contribution (residual connection). Before each part, layer normalization subtracts the list’s average and divides it by its standard deviation.
- Attention alone does not know order, so a positional encoding is added. The causal mask blocks looking at the future; without it, the model learns to copy and is useless for writing.
- Parameters are counted table by table. In a large model almost all of them are in the blocks’ attention and network: in GPT-3, the embedding is less than one percent.
What many people believe
Common belief A transformer reads the text from left to right, word by word, like a person.
What is true All the tokens go in at once and each block processes them in parallel. Order comes from the positional encoding, and it is the causal mask that stops each token from looking ahead. What does go word by word is the writing: one full pass for each new token.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
The full pass, equation by equation
For a sequence of tokens with numbers , an embedding table (one row of numbers per vocabulary word), and blocks, in GPT-2’s “pre-normalization” variant, which is the one our toy uses (, ):
and, in each block, with the layer normalization:
Those two sums are the residual connections: each part adds its contribution to . At the exit of the last block, the last token’s list gives the scores (logits) and softmax the probabilities:
“Comparing with every vocabulary word” is exactly this: a dot product with each row of , the same table as at the input. Reusing it saves parameters; the 2017 paper already did it (section 3.4), and the technique is studied in Press and Wolf (2017). In training all positions are used at once: each one predicts the next token.
Masked attention
With , , and as in lesson 21 and the mask if and if :
Since , the future gets zero weight. That is how the original paper describes the decoder: every softmax input that corresponds to an “illegal” connection is set to to preserve the auto-regressive property (section 3.2.3). Our toy has two heads of numbers per block; the table in the scene is one head of the second block.
The experiment. We trained two identical models (same seed, same data, 4,000 steps) and removed the mask from one. On new sentences, the masked model has a loss of 0.527 nats per word, almost the grammar’s entropy (0.526, the lowest possible). The unmasked model drives its training loss down to 0.059 by copying, but used the way it is used when writing (masked, with no future) it scores 3.088, worse than spreading evenly over twelve words: .
Each block’s network
, with of and of , the same for every position in the block (“applied to each position separately and identically,” section 3.3 of the paper). The original paper used ReLU; GPT-1 and GPT-2 use GELU (Hendrycks and Gimpel, 2016), a smooth ReLU: , with the normal cumulative distribution.
Layer normalization
Over the numbers of a list (Ba, Kiros, and Hinton, 2016):
and are the “two adjustments that are also learned” (gain and bias, parameters per normalization). The 2017 paper normalized after adding, ; GPT-2 moved it to the input of each part and added one more after the last block. Xiong and colleagues (2020) show that with pre-normalization the gradients are well behaved from the start, so the learning-rate warm-up stage can be dropped. In the scene, the list for “eats” entering the second block has an average of 1.10 and a standard deviation of 0.78.
Positional encoding
The 2017 paper’s (section 3.5), with the place and the index of the pair of numbers:
The wavelengths run from to . The authors also tried learned positions and got nearly identical results; GPT-1 learns its own. “Attention alone does not know order” is exact for unmasked attention: if the tokens are permuted, their outputs are permuted the same way. With a causal mask it is subtler: Haviv and colleagues (2022) show that a causal language model without positional encoding learns an implicit notion of position, thanks to the mask itself. Even so, almost every model uses one. In the scene, the “no position” calculation uses a real head of our model on the embeddings alone, without the mask.
Counting parameters
With words, numbers per list, blocks, learned positions, and a network:
| Part | Parameters | Toy (, , ) |
|---|---|---|
| Embeddings (and learned positions) | 96 (wave positions: 0) | |
| Attention | 576 | |
| Network | 1,104 | |
| Normalizations | 80 | |
| Total | when is large | 1,856 |
The approximation is Kaplan and colleagues’ (2020, equation 2.1), not counting embeddings. With GPT-2’s vocabulary (50,257) and , the table gives 125,226,240 for 12 blocks with and 174,604,259,328 for 96 blocks with ; the GPT-3 paper (table 2.1) lists 125 million for “GPT-3 Small” and 175.0 billion for GPT-3. The split by parts in the scene is our calculation with this table. For the smallest GPT-2 (context 1,024) it gives 124,439,808, the same count as the Hugging Face Transformers library (checked in train_tiny.py); the GPT-2 paper said 117 million.
In code
import numpy as np
def softmax(z):
e = np.exp(z - z.max(-1, keepdims=True))
return e / e.sum(-1, keepdims=True)
def causal_attention(Q, K, V):
T, d = Q.shape
scores = Q @ K.T / np.sqrt(d)
scores[np.triu_indices(T, k=1)] = -np.inf # causal mask: no peeking at the future
w = softmax(scores)
return w, w @ V
def layer_norm(x, g, b, eps=1e-5):
return g * (x - x.mean(-1, keepdims=True)) / np.sqrt(x.var(-1, keepdims=True) + eps) + b
def n_params(d, L, V, ctx, ff=None):
ff = ff or 4 * d
return V*d + ctx*d + L*(4*d*d + 4*d) + L*(2*d*ff + ff + d) + (4*L + 2)*d
rng = np.random.default_rng(0)
Q = K = V = rng.normal(size=(3, 4))
w, out = causal_attention(Q, K, V)
print(np.round(w, 2))
x = rng.normal(2.0, 3.0, size=8)
y = layer_norm(x, np.ones(8), np.zeros(8))
print(round(y.mean(), 3), round(y.std(), 3))
print(n_params(8, 2, 12, 0), n_params(12288, 96, 50257, 2048))
# [[1. 0. 0. ]
# [0.25 0.75 0. ]
# [0.17 0.13 0.7 ]]
# 0.0 1.0
# 1856 174604259328
The lesson’s model is complete in model.ts and is trained with train_tiny.py (PyTorch, on CPU, under a minute): both live next to this lesson, and verify-forward.mts checks that the TypeScript pass matches PyTorch (maximum difference 7·10⁻⁶).
What comes next
A model with this architecture starts with random parameters. Lesson 23 shows what it learns when trained to predict the next word on internet-scale text, and lesson 24 what that costs. How it is served (the KV cache, which avoids recomputing the earlier tokens) arrives in lesson 26.
Decision lens
What this idea means if your job is to decide, not to code.
- Almost all general-purpose language models share this skeleton. Saying “we use a transformer” tells you very little: ask about size (number of blocks and length of the lists), how much text it can read at once, and the data it was trained on.
- Size grows with the square of the list length and with the number of blocks: doubling the length quadruples each block’s parameters. Compare both numbers, not just the total.
- Every token the model writes requires a pass through all the blocks. Long answers cost more time and money, and a deeper model takes longer per token.
- There are models that write (decoder-only, like GPT) and models that only read (encoder-only, like BERT). To classify or search documents you do not always need one that writes: it can be cheaper and easier to evaluate.
Terms in this lesson
- Token A piece of text (a word, a word fragment, a symbol, or a basic code) taken from the vocabulary. It is the unit the model reads and generates, and the unit you are billed for.
- Vocabulary The list of all the pieces (tokens) a tokenizer can produce, each with its number. Real ones have from about thirty-two thousand to about two hundred thousand; the lesson’s toy one, 656.
- Embedding A vector of numbers, learned from data, that represents something (a word, a sentence, an image) so that similar things end up close. Each word has a row in an embedding table.
- Language model A model that, given some text (the context), gives a probability to every word or piece that can come next. It writes by adding one piece at a time.
- Autoregression Writing one piece at a time using what has already been written as input: each word produced becomes part of the context for the next.
- Softmax A function that turns any scores into positive probabilities that add up to one: it applies the exponential to each score and divides by the sum.
- Attention A mechanism by which each token decides how much to look at the others: it compares its query with everyone’s keys, turns the scores into weights with softmax, and builds its new vector as the blend of the values with those weights.
- Query, key, and value (Q, K, V) The three vectors each token produces: the query says what it is looking for, the key how it gets found, and the value what it hands over. They come from multiplying its vector by three learned weight matrices.
- Self-attention Attention in which queries, keys, and values come from the same sequence: each token looks at the other tokens of its own text, and at itself.
- Multi-head attention Several attentions in parallel, each one (a head) with its own matrices for Q, K, and V and its own map. Their results are joined and combined with a final matrix.
- Layer A group of neurons that receive the same inputs and compute at the same time. A network is a chain of layers: input, one or more hidden ones, and output.
- ReLU Rectified linear unit: an activation function that returns zero if the sum is negative and the sum itself if it is positive, max(0, z). A hinge with a single corner.
- Nonlinearity The property of a function that is not a straight line. It stops stacked layers from collapsing into one and lets a network fold space.
- Forward pass Computing a network’s output: the numbers move on layer by layer, from input to output.
- Residual connection (shortcut) Adding a block’s input to its output: y = x + F(x). It gives the gradient a direct path backward and made it possible to stack many more layers.
- Parameter Each of the numbers a model adjusts while training and in which it stores what it learned.
- Weight (w) In a linear model, the number that multiplies the input: the slope of the line. It tells how much the prediction rises for each unit the input grows.
- Bias (b) The term added at the end of the model: the prediction when the input is zero, that is, the height at which the line crosses the vertical axis. It is not the bias of data or of an unfair model, which is a different concept.
- Loss function A single number that summarizes how wrong a model is on its data. Training is the search for the parameters that make it as small as possible.
Full transcript
Sources
- Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., Polosukhin, I. (2017). Attention Is All You Need
- Radford, A., Narasimhan, K., Salimans, T., Sutskever, I. (2018). Improving Language Understanding by Generative Pre-Training (GPT-1)
- Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., Sutskever, I. (2019). Language Models are Unsupervised Multitask Learners (GPT-2)
- Brown, T. B., Mann, B., Ryder, N., Subbiah, M., et al. (2020). Language Models are Few-Shot Learners (GPT-3)
- Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B., et al. (2020). Scaling Laws for Neural Language Models
- Ba, J. L., Kiros, J. R., Hinton, G. E. (2016). Layer Normalization
- He, K., Zhang, X., Ren, S., Sun, J. (2015). Deep Residual Learning for Image Recognition
- Xiong, R., Yang, Y., He, D., Zheng, K., et al. (2020). On Layer Normalization in the Transformer Architecture
- Hendrycks, D., Gimpel, K. (2016). Gaussian Error Linear Units (GELUs)
- Press, O., Wolf, L. (2017). Using the Output Embedding to Improve Language Models
- Haviv, A., Ram, O., Press, O., Izsak, P., Levy, O. (2022). Transformer Language Models without Positional Encodings Still Learn Positional Information
- Touvron, H., Martin, L., Stone, K., et al. (2023). Llama 2: Open Foundation and Fine-Tuned Chat Models
- Devlin, J., Chang, M.-W., Lee, K., Toutanova, K. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub