2.9The full Transformer: follow one token
Put every piece together. Watch "The capital of France is" flow through a GPT-2-sized model, with real tensor shapes and parameter counts, until "Paris" comes out.
All the pieces, in one machine
Over the last few lessons you’ve met every part of a TransformerTransformerThe neural network architecture behind modern LLMs: stacked blocks of self-attention and feed-forward layers with residual connections. separately: tokens, embeddings, self-attention, multiple heads, positional encodings, and normalization with residual connections. This lesson assembles them and runs one real-shaped forward pass from start to finish.
Our specimen is GPT-2 small, released by OpenAI in 2019. It’s tiny by today’s standards, but it’s the ancestor of almost every modern LLM, it’s fully documented, and its numbers are small enough to check by hand. Its configuration:
| setting | value |
|---|---|
| vocabulary size | 50,257 tokens |
| context length | 1,024 tokens |
| model width | 768 |
| blocks (layers) | 12 |
| attention heads | 12 (each 64 wide) |
| MLP hidden width | 3,072 () |
| total parameters | 124,439,808 |
Our prompt is “The capital of France is”, and we want to know what the model thinks comes next. We’ll follow the vector of the last token, ” is”, because its final state is what predicts the next token.
Picture five reporters, one per word, riding an elevator up a twelve-floor newsroom. Each carries a clipboard. On every floor there are two rooms. In the first, the meeting room, each reporter can glance at the clipboards of reporters who arrived before them and copy useful notes. In the second, the archive room, each reporter alone looks things up in a huge reference library and adds what they find. Nobody ever erases their clipboard; they only add notes.
The clipboard is the token’s vector (the residual stream). The meeting room is attention, the only place where information moves between tokens. The archive is the MLP, which works on each token separately. The twelve floors are the twelve blocks. At the top, the last reporter’s clipboard is compared with every word in the dictionary, and the best matches become the prediction.
The journey, step by step
Press Play, or step through with Next. The panel under the diagram gives the tensor shape after each step and the parameters involved, with a running total that should end at exactly 124,439,808.
The model never sees letters directly. Our prompt is 23 characters; the goal of this forward pass is a probability for every possible next token.
Here’s the same journey in words, with the shape of the data at each stage. “[5, 768]” means 5 rows (one per token) of 768 numbers each.
1. Tokenize. The tokenizerTokenizerThe component that splits text into tokens and maps them to integer IDs (and back). splits the text into 5 tokens with ids 464, 3139, 286, 4881, 318. Shape: [5] integers. No learned parameters, just a fixed vocabulary.
2. Embed. Each id selects a row of the embeddingEmbeddingA learned vector representing a token, word, image or document, arranged so that similar meanings get nearby vectors. matrix , which has 50,257 rows and 768 columns: 38.6 million parameters, almost a third of the whole model. Shape: [5, 768].
3. Add positions. GPT-2 adds a learned position vector to each row (positions 0 to 4), from a 1,024 × 768 table. That table is why its context window is 1,024 tokens. Shape stays [5, 768].
4–9. Block 1. Each block does two things, each wrapped in a pre-norm residual connection:
- LayerNorm, then multi-head attentionMulti-head attention (MHA)Running several attention operations (heads) in parallel, each with its own projections, then combining their outputs.: one matrix multiply produces queries, keys and values ([5, 2304], i.e. 3 × 768), which are split into 12 heads of 64. Each head computes a 5 × 5 grid of causal attention weights and mixes values; the heads are concatenated and projected back to 768. The output is added to the stream. This is the only step where ” is” can learn anything about ” France”.
- LayerNorm, then the MLPMLP (feed-forward network)A multi-layer perceptron: linear layers with nonlinear activations between them. Each Transformer block contains one.: each row is expanded to 3,072 numbers, passed through the GELU activationActivation functionA nonlinear function (ReLU, GELU, sigmoid…) applied after a weighted sum. Without it, stacked layers would collapse into one linear map., and projected back to 768, then added to the stream. The MLP sees each position separately.
A block has 7,087,872 parameters: about 2.36M in attention and 4.72M in the MLP. In and out, the shape is [5, 768], which is exactly what lets blocks stack.
10. Eleven more blocks. Same structure, different weights. With each block, the ” is” vector accumulates more context. Interpretability probes such as the “logit lens” suggest the prediction often sharpens gradually through the upper layers rather than appearing all at once, though how this plays out varies between models.
11. Final LayerNorm. One last normalization, required by the pre-norm design.
12. Unembed. Take only the last row (768 numbers) and compute its dot product with every token’s embedding vector. GPT-2 reuses for this (weight tyingWeight tyingReusing the input embedding matrix as the output (unembedding) matrix, which saves vocab × d_model parameters. GPT-2 does this.), so the unembeddingUnembedding (LM head)The final matrix that turns a token's d_model-dimensional vector into one logit per vocabulary entry. Often tied to (shared with) the input embedding matrix. adds no parameters. Shape: [50,257] logitsLogitsRaw, unnormalized scores a model outputs, one per class or token. Softmax turns them into probabilities., one score per vocabulary token.
13. Softmax. SoftmaxSoftmaxA function that turns a vector of scores into probabilities by exponentiating each score and dividing by the total. turns logits into probabilities that sum to 1.
14. Pick and repeat. A sampler chooses a token, the subject of the next lesson, here ” Paris”. It is appended, and the process runs again on 6 tokens to produce the 7th. This loop is what autoregressiveAutoregressive generationGenerating one token at a time, appending each output to the input before predicting the next. generation means.
Where the parameters and compute go
Two numbers summarize a model’s cost: how many parameters it stores and how much arithmetic it does per token.
Parameters. In GPT-2 small, the embedding table is a surprisingly large slice (31%), because the vocabulary is big relative to the width. The 12 blocks hold the remaining 68%, and within each block the MLP holds twice as many weights as attention. In much bigger models the blocks dominate, because block parameters grow with while embeddings grow only with .
Compute. Almost all of the work is matrix multiplication, and multiplying a vector by a weight matrix costs one multiply and one add per weight. So a forward pass costs about 2 FLOPs per parameter per token, plus a smaller attention term that grows with context length. Training costs roughly three times that (the backward pass is about twice the forward), the familiar ” FLOPs per token” used in scaling laws.
Decoder-only vs encoder-decoder
The 2017 Transformer was built for translation and had two stacks. An encoder read the whole source sentence with bidirectional attention (every word sees every other word), and a decoder generated the translation with causal self-attention plus cross-attention into the encoder’s output. That’s an encoder-decoder model, the design later used by T5. BERT kept only the encoder, which is great for understanding tasks (classification, search) but can’t generate text naturally.
GPT took only the decoder, without cross-attention: one stack, causal masking, next-token prediction. That is a decoder-onlyDecoder-only TransformerA Transformer made of a single stack of causally masked blocks that predicts the next token. GPT, Llama, Qwen and DeepSeek are decoder-only; the original Transformer and T5 are encoder-decoder. Transformer, and it’s what essentially every major chat LLM uses today. The appeal is simplicity: one architecture, one training objective that applies to any text, and a single stream in which prompt and answer live together. Encoder-decoder models are still used in places, for example in some speech-recognition systems like Whisper.
What modern models changed
A 2025-era open model looks like GPT-2 with a set of upgrades, most of which you’ve already met:
The skeleton (embed → N × [norm, attention, add, norm, MLP, add] → norm → unembed) is unchanged. If you understand GPT-2’s forward pass, you can read the architecture diagram of nearly any current LLM. Part 5 does exactly that for DeepSeek, Qwen and others.
MATH CORNER · optionalCounting GPT-2 small's parameters and FLOPs
Let , vocabulary , context , blocks, MLP width .
One block. Attention: is and is , so weights. MLP: up and down, so . Total
Biases and norms add : (attention biases) (MLP biases) (two LayerNorms with and ) . So one block has parameters.
Whole model.
| part | formula | parameters |
|---|---|---|
| token embedding | 38,597,376 | |
| position embedding | 786,432 | |
| 12 blocks | 85,054,464 | |
| final LayerNorm | 1,536 | |
| unembedding | tied to | 0 |
| total | 124,439,808 |
That’s the “124M” in GPT-2 small’s name. Note that the rough rule gives 84.9M: it counts only block weights, the “non-embedding” parameters used in scaling-law papers.
FLOPs per token. A matrix-vector product with an matrix costs about FLOPs (a multiply and an add per weight). Summing over all weight matrices used per token (blocks plus the unembedding matmul; the embedding lookup is free):
With matrix weights, GFLOPs. The attention-score term at full context is GFLOPs, under 10% here. So each generated token costs about a quarter of a billion floating-point operations, and training costs about three times that per token: .
For a sense of scale, the same formula says a 70B dense model needs about 140 GFLOPs per generated token.
In code
You can verify the parameter count with Hugging Face transformers, and the forward pass is short enough to read in one screen. This is a minimal GPT-2-style model (reusing the Block idea from the previous lesson):
import torch, torch.nn as nn
class GPT(nn.Module):
def __init__(self, V=50257, ctx=1024, d=768, L=12, make_block=None):
super().__init__()
self.wte = nn.Embedding(V, d) # token embeddings W_E
self.wpe = nn.Embedding(ctx, d) # position embeddings W_P
self.blocks = nn.ModuleList([make_block(d) for _ in range(L)])
self.ln_f = nn.LayerNorm(d) # final norm
def forward(self, ids): # ids: [B, T]
T = ids.shape[1]
x = self.wte(ids) + self.wpe(torch.arange(T)) # [B, T, d]
for blk in self.blocks: # x = x + attn(ln(x)); x = x + mlp(ln(x))
x = blk(x)
x = self.ln_f(x)
return x @ self.wte.weight.T # tied unembedding -> [B, T, V] logits
# Check the real thing:
from transformers import GPT2LMHeadModel
m = GPT2LMHeadModel.from_pretrained("gpt2")
print(sum(p.numel() for p in m.parameters())) # 124439808
- “The model processes the prompt one word at a time.” The whole prompt goes through each layer in parallel as a [5, 768] matrix. Only generation is sequential, one new token per forward pass.
- “Each layer produces a new representation that replaces the old one.” Each sublayer adds to the residual stream; information from the embedding and early layers is still present (in superposition with everything else) at the top.
- “Only the last token’s computation matters.” Only the last row is unembedded at generation time, but the earlier rows’ keys and values at every layer are what the last token attends to. Their computation is essential, which is exactly what the KV cache stores.
- “Most parameters are in attention.” In a standard dense block, the MLP has twice as many weights as attention ( vs ). In small models with big vocabularies, the embedding table is also a large share.
Check your understanding
Q1.In GPT-2 small, the input to block 1 has shape [5, 768] for a 5-token prompt. What shape comes out of block 12?
Q2.Using the 12·d² rule, roughly how many weights does one block of a model with d_model = 4096 have?
Q3.Which step is the only place where the vector for ' is' can receive information from the vector for ' France'?
Q4.A 7-billion-parameter dense model generates one token. Roughly how many FLOPs does the forward pass need (ignoring the attention-over-context term)?
Q5.What distinguishes a decoder-only model like GPT from the original encoder-decoder Transformer?
Further reading
- paperLanguage Models are Unsupervised Multitask Learners (GPT-2 paper) — Radford et al., 2019; describes the architecture changes, including pre-norm.
- codenanoGPT — Andrej Karpathy's compact, readable GPT-2 implementation and training code.
- videoLet's build GPT: from scratch, in code, spelled out — Karpathy's two-hour video building a GPT step by step.
- blogLLM Visualization — Brendan Bycroft's 3D walkthrough of a small GPT's forward pass.
- paperScaling Laws for Neural Language Models — Kaplan et al.; Section 2.1 derives the ≈2N FLOPs-per-token forward cost.
- paperAttention Is All You Need — The original encoder-decoder Transformer.