Skip to content
LearnAI
PART 2 · HOW LANGUAGE MODELS WORK/ Inside the Transformer

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.

⏱ 13 minIntermediate

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:

settingvalue
vocabulary size50,257 tokens
context length1,024 tokens
model width dmodeld_\text{model}768
blocks (layers)12
attention heads12 (each 64 wide)
MLP hidden width3,072 (4×7684 \times 768)
total parameters124,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.

ANALOGY· A newsroom with twelve floors

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.

INTERACTIVEFollow one token through GPT-2 small
Transformer block × 12TokenizeToken embedding+ Position embeddingLayerNormMulti-head attention+ residualLayerNormMLP (768→3072→768)+ residualFinal LayerNormUnembed (× W_Eᵀ)SoftmaxNext token"The capital of France is"23 characters → ? tokens
1/15 · Raw text
Start: a string of characters

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.

tensor shape
"The capital of France is"
parameters in this step
0
no parameters
running total
0
of 124,439,808 (GPT-2 small)
Step through a full forward pass. The highlighted row is the token ' is', whose final vector predicts the next token. Token ids are GPT-2's real ids; vector values, attention weights and probabilities are illustrative.

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 WEW_E, 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:

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 WEW_E 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 dmodel2d_\text{model}^2 while embeddings grow only with dmodeld_\text{model}.

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 ”6N6N 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:

GPT-2 (2019)Typical modern LLM
learned absolute positionsRoPERotary position embedding (RoPE)Encodes position by rotating query and key vectors by angles proportional to their position, so attention depends on relative distance. inside attention
LayerNormRMSNormRMSNormA simpler LayerNorm that only divides a vector by its root-mean-square and multiplies by a learned gain, skipping the mean subtraction and bias. Used by most modern LLMs.
GELU MLP, 4× widegated MLP (SwiGLU), with a different width ratio
every head has its own K and Vgrouped-query attentionGrouped-query attention (GQA)Attention in which groups of query heads share one key/value head, shrinking the KV cache. MQA is the extreme case of one shared KV head. or MLA to shrink the KV cache
dense: every parameter used for every tokenoften mixture of expertsMixture of Experts (MoE)An architecture in which each token is routed to a few of many 'expert' sub-networks, so total parameters can be huge while compute per token stays small.
biases everywhere, tied embeddingsbiases usually dropped; large models often untie embeddings
1,024-token contexttens or hundreds of thousands of tokens

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 d=768d = 768, vocabulary V=50,257V = 50{,}257, context nctx=1,024n_\text{ctx} = 1{,}024, L=12L = 12 blocks, MLP width 4d4d.

One block. Attention: WQKVW_{QKV} is d×3dd \times 3d and WOW_O is d×dd \times d, so 4d24d^2 weights. MLP: d×4dd \times 4d up and 4d×d4d \times d down, so 8d28d^2. Total

weights per block=4d2+8d2=12d2=12×7682=7,077,888.\text{weights per block} = 4d^2 + 8d^2 = 12d^2 = 12 \times 768^2 = 7{,}077{,}888 .

Biases and norms add 13d13d: 3d+d3d + d (attention biases) +4d+d+ 4d + d (MLP biases) +4d+ 4d (two LayerNorms with γ\gamma and β\beta) =9,984= 9{,}984. So one block has 7,087,8727{,}087{,}872 parameters.

Whole model.

partformulaparameters
token embedding WEW_EV×dV \times d38,597,376
position embedding WPW_Pnctx×dn_\text{ctx} \times d786,432
12 blocks12×7,087,87212 \times 7{,}087{,}87285,054,464
final LayerNorm2d2d1,536
unembeddingtied to WEW_E0
total124,439,808

That’s the “124M” in GPT-2 small’s name. Note that the rough rule N≈12Ld2N \approx 12 L d^2 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 a×ba \times b matrix costs about 2ab2ab 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):

Cforward≈2N+2L nctx d.C_\text{forward} \approx 2N + 2 L\, n_\text{ctx}\, d .

With N≈85.0M+38.6M≈123.7MN \approx 85.0\text{M} + 38.6\text{M} \approx 123.7\text{M} matrix weights, 2N≈0.2472N \approx 0.247 GFLOPs. The attention-score term at full context is 2×12×1,024×768≈0.0192 \times 12 \times 1{,}024 \times 768 \approx 0.019 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: ≈6N\approx 6N.

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
COMMON MISCONCEPTIONS
  • “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 (8d28d^2 vs 4d24d^2). In small models with big vocabularies, the embedding table is also a large share.

Check your understanding

0/5 answered
  1. 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?

  2. Q2.Using the 12·d² rule, roughly how many weights does one block of a model with d_model = 4096 have?

  3. Q3.Which step is the only place where the vector for ' is' can receive information from the vector for ' France'?

  4. 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)?

  5. Q5.What distinguishes a decoder-only model like GPT from the original encoder-decoder Transformer?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.