Start here if you're new

Transformer, step by step

Follow 3 tokens through a GPT. One tiny model, one running example (“the cat sat”), every number shown, from text to the next word.

Before you start

Prerequisites

  • Vectors, dot products, and matrix shapes: [3 × 4] · [4 × 4] → [3 × 4]
  • What an MLP is (weights, a nonlinearity) and that it is trained by backprop
  • No transformer knowledge needed. This page is the primer for Module 1.

Time: 60–90 minutes for the 20 steps, 5 minutes to run python step_by_step.py, plus the optional videos.

What you'll learn

  • Follow one GPT forward pass number by number, with the tensor shape at every step
  • Why each piece exists: normalization, queries/keys/values, the square-root scale, the causal mask, residuals, the FFN
  • How text is generated, and why the KV cache is valid
  • Count parameters, FLOPs and memory, for the toy and for a 7B-class model

🎬 Learn it visually

  1. Transformers, the tech behind LLMs, 3Blue1Brown (Deep Learning ch. 5, 27 min). The best picture of the whole pipeline: embeddings, the flow through the network, unembedding, softmax with temperature.
  2. Attention in transformers, step-by-step, 3Blue1Brown (ch. 6, 26 min). Queries, keys, values, masking and multiple heads, animated. Matches steps 6–12.
  3. How might LLMs store facts, 3Blue1Brown (ch. 7, 23 min). What the feed-forward block (step 15) does, with a toy example.
  4. The Illustrated GPT-2, Jay Alammar (blog post). A decoder-only model drawn one token at a time, including masked self-attention.
  5. Let's build GPT: from scratch, in code, spelled out., Andrej Karpathy (1 h 56 min). A code-along that builds the same block in PyTorch; watch it after this page.

The running example

  • 3 words (“the cat sat”), each turned into a list of 4 numbers.
  • Attention runs as 2 heads, each looking at 2 of those 4 numbers.
  • The feed-forward layer briefly widens each list to 8 numbers.
  • The vocabulary has 8 words.
  • One transformer block.

Each step introduces its own symbols in a “New symbols” box; open “Symbols so far” (in the bar above the steps) at any time.

4 numbers per token the cat sat 3 tokens × 4 numbers
The shape that flows through the whole page: one row per token.

Every weight is a multiple of 0.1, picked by a small random search (not by training) so that the model continues with “on the mat”. step_by_step.py builds this exact model and prints every number on this page, in the same order. Computed numbers are rounded to 2 decimals, so a sum you redo by hand from the rounded inputs can be off by 1 in the last digit (we mark those with ≈).

data (token vectors) learned weights mixing across tokens per-token compute, outputs cost
shape now: text
0

The big picture

A GPT is one function: text goes in, a probability for every possible next word comes out.

What to notice: steps 1–3 turn text into vectors, steps 4–16 are one block, step 17 turns the last vector into probabilities.
New symbols
  • idstoken IDs, one integer per token [3] computed from the text (step 1)
  • pprobability of each possible next word [8] computed softmax at the very end (step 17)
  • Lnumber of blocks stacked 1 here setting 12 in GPT-2 small, 32 in a 7B model
Formula
p = softmax(LM_head(blockL(… block1(embed(ids)))))
embed the 3 IDs into a [3 × 4] matrix, pass it through L blocks (the shape stays [3 × 4]), map the last row to 8 scores, and turn them into 8 probabilities.
Why this shape

Predicting the next token is the only training task of a GPT. Writing text is just repeating that prediction (step 18).

Keep in mind: every block keeps the shape [tokens × 4 numbers]. That is why blocks can be stacked 12, 32 or 96 times.

The numbers

Our toy: “the cat sat” → p(“on”) = 0.70. The weights were chosen so “on” wins; nothing here is trained.

Real models: GPT-2 small has 50,257 vocabulary words, 768 numbers per token and 12 blocks; our toy has 8 words, 4 numbers and 1 block.

logits = model(ids)             # [3, 8]
probs = logits[-1].softmax(-1)  # [8], sums to 1
shape: text → [8 probs]🎬 Watch this part: 3Blue1Brown ch. 5, “Inside a transformer” (from 3:03)
1

Text → token IDs

The model never sees letters: each token is replaced by its row number in a fixed vocabulary.

What to notice: an ID is only a row number; 7 is not “bigger” than 1 in any useful sense.
New symbols
  • Vvocabulary size: how many different tokens exist 8 setting fixed by the tokenizer (50,257 in GPT-2)
  • Nnumber of tokens in the input so far 3 computed from the prompt; +1 per generated token
Formula
ids = tokenize(“the cat sat”) = [7, 1, 6]
N = 3 tokens in, 3 integers out; each integer is a row number in the vocabulary of size V = 8.
Why this step

A network computes with numbers, so text must become integers first. Real tokenizers (BPE) split text into sub-word pieces, so rare words still get IDs.

Without it: nothing to compute with. With whole words only, every unseen word would be “unknown”.

The numbers

vocab = [“.”, “cat”, “dog”, “mat”, “on”, “ran”, “sat”, “the”] (alphabetical, IDs 0–7).

“the” → 7, “cat” → 1, “sat” → 6. GPT-2's real vocabulary has 50,257 tokens.

vocab = ". cat dog mat on ran sat the".split()
ids = torch.tensor([vocab.index(w) for w in
                    "the cat sat".split()])  # [7, 1, 6]
shape: [3 token IDs]
2

Embedding = picking rows from a table

Each ID picks one row of a learned table E; that row is the token's starting vector.

What to notice: no arithmetic happens here; rows 7, 1, 6 are copied, in prompt order.
New symbols
  • Eembedding table: one row per vocabulary word [8 × 4] learned weight
  • dmodel width (dmodel, also "hidden size"): how many numbers describe a token 4 setting 768 in GPT-2 small, 4096 in a 7B model
  • tokthe picked rows of E, one per token [3 × 4] computed from E and ids: E[ids]
  • onehota row per token: 1 in column “ID”, 0 elsewhere [3 × 8] computed from ids (picking rows is this matmul)
Formula
tok = E[ids] = onehot(ids) · E
E is [V × d] = [8 × 4], one row of d = 4 numbers per vocabulary word. Picking rows 7, 1, 6 gives tok [3 × 4]. It equals the [3 × 8] one-hot matrix times E.
Why this step

Vectors have geometry: training can move words that behave alike (“cat”, “dog”) close together, and the dot products of later steps can measure that.

Without it: an ID like 7 has no meaning to multiply with.

The numbers
tok[the] = E[7] = [−0.2, −0.8, −0.3, −0.4]

E is a learned weight (purple). In GPT-2 small it is [50,257 × 768], about 38.6 M numbers.

tok = E[ids]          # [3, 4]
# same as nn.Embedding(8, 4) with weight E
shape: [3 tokens × 4 dims]🎬 Watch this part: 3Blue1Brown ch. 5, “Word embeddings” (from 12:27)
3

Adding position information

Add a learned “position vector” to each token, so the model can tell “the cat sat” from “sat the cat”.

What to notice: row i always gets position row i, whatever the word is.
New symbols
  • Pposposition table, one row per position (P in the code) [8 × 4] learned weight
  • xthe block's input: token vector + position vector [3 × 4] computed from tok + Ppos[0:3]
Formula
x = tok + Ppos[0:3]
the position table Ppos (P in the code) is a learned [8 × 4] table, one row per position (max length 8). Row i of Ppos is added to the token at position i; x is [3 × 4].
Why this step

Attention (steps 6–12) weighs tokens by what they contain, not by where they are.

Without it: in the first block a token sees the tokens before it as an unordered bag of words; it cannot tell whether “dog” came before or after “bites”. Modern models (Llama, Qwen) use RoPE instead: they rotate q and k by an angle that depends on the position, so scores depend on the distance between tokens.

The numbers
x[the] = [−0.2, −0.8, −0.3, −0.4] + [−0.1, 0.2, 0.4, −0.3] = [−0.3, −0.6, 0.1, −0.7]

x is exact (sums of 1-decimal numbers). It is the input to the block, and the next step normalizes it.

x = E[ids] + P[:3]    # [3, 4]
shape: [3 tokens × 4 dims]
4

LayerNorm (LN₁): rescale each token before attention

The first thing a block does: shift each token's 4 numbers to mean 0 and scale them to spread 1, so attention always reads numbers of a similar size.

Reading the 2017 paper alongside? Its Figure 1 puts the norm after each sub-layer (“Add & Norm”). This page uses the order of GPT-2, Llama and almost every model since, with the norm before:
paper:attention → add → LNthis page:LN → attention → add
Same parts; only the norm moves. Step 16 draws both blocks side by side and explains why models switched. (The paper's figure also has an encoder and cross-attention; this page builds the decoder-only GPT part: the three families.)
What to notice: the bars keep their order (dim 2 highest, dim 0 lowest) but are centred on 0 and stretched to about ±1. Dim 3 (0.1) turns slightly negative because it is below the mean 0.15.
New symbols
  • LN1the LayerNorm in front of attention; works on each row (token) separately operation uses μ, σ, γ, β below
  • μmean of one token's 4 numbers 1 per token computed from x: sum ÷ 4
  • σ²variance: mean of the squared distances from μ 1 per token computed from x and μ
  • σspread (standard deviation) = √(σ² + ε) 1 per token computed from σ²
  • εtiny number that prevents ÷ 0 0.00001 setting PyTorch's default
  • γper-dimension scale [4] learned weight starts at 1 (1 here)
  • βper-dimension shift [4] learned weight starts at 0 (0 here)
  • ⊙multiply dimension by dimension operation
  • x̂normalized x: what attention reads [3 × 4] computed from x: LN1(x)
  • rmsRMSNorm's divisor: √(mean(x²) + ε) 1 per token computed from x (no μ)
Formula
x̂ = LN1(x) = γ ⊙ (x − μ) / √(σ² + ε) + β
μ = mean of the row's 4 numbers
σ² = mean of (row − μ)², σ = √(σ² + ε)
RMSNorm(x) = γ ⊙ x / rms, rms = √(mean(x²) + ε)
for each token (row) on its own: subtract the row's mean μ, divide by its spread σ, then scale by γ and shift by β (here γ = 1 and β = 0, their starting values). x [3 × 4] goes in, x̂ [3 × 4] comes out.
Why this step

Queries, keys and values (steps 5–6) are dot products with x̂. If one token's numbers were 10 times bigger than another's, its scores would be 10 times bigger too, whatever it means. After the norm every token arrives at the same scale, and the learned γ and β set the scale the model wants.

RMSNorm (Llama, Qwen) skips μ and β and only divides by the root mean square; it is a bit cheaper and works as well.

The numbers: row “sat” of x, by hand
  1. x[sat] = [−0.7, 0.5, 0.7, 0.1]
  2. mean: μ = (−0.7 + 0.5 + 0.7 + 0.1) / 4 = 0.60 / 4 = 0.15
  3. subtract: x − μ = [−0.85, 0.35, 0.55, −0.05]
  4. square, add, divide by 4: 0.7225 + 0.1225 + 0.3025 + 0.0025 = 1.1500; σ² = 1.1500 / 4 = 0.2875
  5. spread: σ = √(0.2875 + 0.00001) = 0.536
  6. divide: (x − μ) / σ = [−1.59, 0.65, 1.03, −0.09]
  7. γ = 1 and β = 0 leave it unchanged: that is x̂[sat].
  8. RMSNorm instead: x² = [0.49, 0.25, 0.49, 0.01], 1.24 / 4 = 0.31, rms = √(0.31 + ε) = 0.557; x / rms = [−1.26, 0.90, 1.26, 0.18]

Divide by d = 4, not d − 1 = 3. LayerNorm takes the plain average (PyTorch's unbiased=False). Dividing by 3, the “sample variance” of statistics, would give σ² = 0.383.

x̂ = LN₁(x) [3 × 4]
mu = x.mean(-1, keepdim=True)    # [3, 1]
var = x.var(-1, unbiased=False,
            keepdim=True)        # ÷ d, not d-1
xh = (x - mu) / (var + 1e-5).sqrt()
# same as F.layer_norm(x, (4,))
shape: x̂: [3 × 4]🎬 Watch this part: Karpathy, “layernorm” (from 1:32:51)
5

Matrix-multiply refresher (hover the cells)

Every output number of a matrix multiply is one dot product: a row of the left matrix with a column of the right one.

Hover or tap a cell of Q:
New symbols
  • WQquery weights [4 × 4] learned weight
  • Qqueries: “what am I looking for?”, one row per token [3 × 4] computed from x̂ WQ
  • i, j, krow, column, and the index that is summed over operation i = token, j = column of Q, k = 0…3
  • Σkadd up the terms for k = 0, 1, 2, 3 operation
  • FLOPsfloating-point operations: one multiply or one add operation [m × k]·[k × n] costs 2mkn
Formula
Q = x̂ WQ, Q[i, j] = Σk x̂[i, k] · WQ[k, j]
x̂ [3 × 4] times WQ [4 × 4] gives Q [3 × 4]. Cell (i, j) is the dot product of token i's row with column j of WQ.
Why this step

A linear layer is “each token's vector times the same weight matrix”. Stacking the 3 tokens as rows does all of them in one multiply. Matmuls are almost all the work in a transformer.

The input is x̂, not x: in a pre-norm block attention reads the normalized vectors from step 4. The residual path (step 13) still carries the un-normalized x.

The numbers
x̂[sat] = [−1.59, 0.65, 1.03, −0.09] (step 4: mean 0, spread 1)

Count the work: 3 rows × 4 columns × 4 multiply-adds = 48 multiply-adds = 96 FLOPs. In general an [m × k]·[k × n] matmul costs 2·m·k·n FLOPs (here 2 · 3 · 4 · 4).

xh = F.layer_norm(x, (4,))  # [3, 4], step 4
Q = xh @ W_Q    # [3, 4] @ [4, 4] -> [3, 4]
# nn.Linear(4, 4)(x) computes x @ weight.T
shape: [3 × 4] · [4 × 4] → [3 × 4]🎬 Watch this part: Karpathy, “matrix multiply as weighted aggregation” (from 47:11)
6

Q, K, V: three views of every token

Each token makes three vectors: a query (“what am I looking for?”), a key (“what do I contain?”) and a value (“what do I offer if picked?”).

What to notice: one input, x̂ from step 4, and three different weight matrices. Columns 0–1 belong to head 0, columns 2–3 to head 1 (step 12).
New symbols
  • WKkey weights [4 × 4] learned weight
  • WVvalue weights [4 × 4] learned weight
  • Kkeys: “what do I contain?” [3 × 4] computed from x̂ WK
  • Vvalues: “what do I pass on?” (a matrix; the vocabulary size V is a number) [3 × 4] computed from x̂ WV
Formula
Q = x̂ WQ, K = x̂ WK, V = x̂ WV
the same x̂ [3 × 4] times three different [4 × 4] weight matrices gives three [3 × 4] matrices: one query, key and value row per token.
Why this step

What a token is looking for is different from what it contains. Separate learned matrices let the model learn these roles separately.

Without it (using x̂ for Q, K and V): after normalization (with γ = 1, as here) every x̂ has the same length, so each token's best match would always be itself.

The numbers
WK [4 × 4]
WV [4 × 4]

WQ is in step 5. Each projection is 48 multiply-adds (96 FLOPs).

Q = xh @ W_Q        # [3, 4] each
K = xh @ W_K
V = xh @ W_V
shape: Q, K, V: [3 × 4] each
7

Scores = Q · Kᵀ

A score says how well query i matches key j: the dot product is large when the two vectors point the same way.

What to notice: in head 0, qsat and kcat both point right, so their dot product is positive and the largest in the row; the other two keys point away (negative scores).
New symbols
  • Qh, Khone head's 2 columns of Q and K; h numbers the head (0 or 1, step 12) [3 × 2] computed columns 2h, 2h+1 of Q, K
  • Sattention scores: how well query i matches key j [3 × 3] per head computed from Qh Khᵀ
  • qi, kjrow i of Qh, row j of Kh [2] each computed token i's query, token j's key
  • ᵀtranspose: rows become columns operation
Formula
S = Qh Khᵀ, S[i, j] = qi · kj
for one head, Qh is [3 × 2] and Khᵀ is [2 × 3], so S is [3 × 3]: row i is query token i, column j is key token j.
Why this step

The model needs a number for “how relevant is token j to token i”. A dot product is cheap, and one matmul gives all 9 pairs at once.

Without it: no way to decide which earlier tokens matter. Cost: S has N × N entries, so it grows with the square of the length.

The numbers
score(sat → cat) = qsat · kcat = 1.31 × 1.03 + 0.51 × (−0.45) ≈ 1.11
head 1 scores [3 × 3]

(≈: the shown q and k are rounded; the exact sum is 1.11.)

S = Q[:, 0:2] @ K[:, 0:2].T   # head 0: [3, 3]
shape: scores: [3 × 3] per head🎬 Watch this part: 3Blue1Brown ch. 6, “The attention pattern” (from 4:29)
8

Scale by √dk

Divide the scores by √dk so they stay in a range where softmax still gives smooth weights.

head size: scale:
Try it: pick d_k = 128 and turn scaling off: the softmax becomes one-hot (0, 1, 0).
New symbols
  • dkhead size: numbers per head 2 setting d ÷ number of heads (128 in big models)
  • S′scaled scores (masked in step 9) [3 × 3] per head computed from S ÷ √dk
Formula
S′ = S / √dk (√2 = 1.41)
divide every score by the square root of the head size dk = 2. The shape stays [3 × 3].
Why this step

If q and k have dk independent entries with variance 1, then q · k is a sum of dk terms with variance dk: its spread grows like √dk. Dividing by √dk brings the spread back to about 1, whatever the head size.

Without it: for big heads the softmax saturates to one-hot, the other weights get almost zero gradient, and training stalls.

The numbers
1.11 / 1.41 = 0.79

With dk = 128 the same row would have raw scores about √(128/2) = 8 times bigger: [−11.06, 8.92, −9.77]. Divided by √128 = 11.31, they give exactly the toy's scaled row back.

head 0, S / √2 [3 × 3]
S = S / math.sqrt(2)          # d_k = 2
shape: [3 × 3] per head
9

Causal mask: no peeking at the future

A token may only look at itself and earlier tokens, so every score to a later token is set to −∞.

mask:
What to notice: above the diagonal everything is −∞ before the softmax and exactly 0 after it.
New symbols
  • maskcausal mask: −∞ wherever key j comes after query i [3 × 3] setting fixed pattern, not learned
  • −∞minus infinity: a score whose weight becomes exactly 0 operation exp(−∞) = 0
Formula
S′[i, j] = −∞ if j > i (the causal mask)
in row i (query token i), every column j right of the diagonal (a later token) becomes minus infinity, so its weight after the softmax is exp(−∞) = 0.
Why this step

Training predicts token i+1 from tokens 0…i, for every position in one pass. If token i could see token i+1, it would just copy the answer.

Without it: training “cheats”, and at generation time the future does not exist yet, so the model would meet inputs unlike anything it trained on. The mask also makes the KV cache valid (step 18).

The numbers

Row “the” can only see itself: its masked row is [−0.10, −∞, −∞], so its weights are [1, 0, 0]. That is why the first row of every causal attention matrix is [1, 0, 0].

Mask off: “the” would put 0.67 of its attention on “cat” and “sat”, which come after it.

mask = torch.tril(torch.ones(3, 3)).bool()
S = S.masked_fill(~mask, float("-inf"))
shape: [3 × 3] per head🎬 Watch this part: 3Blue1Brown ch. 6, “Masking” (from 11:08)
10

Softmax: scores become weights

Softmax turns each row of scores into positive weights that add up to 1: a “soft” choice of which tokens to read.

Drag a score: raising one score takes weight from the others; the total stays 1.
New symbols
  • Aattention weights: each row positive, summing to 1 [3 × 3] per head computed softmax of each row of S′
  • expe to the power of: makes every score positive operation
  • j′runs over every key in the row (for the sum) operation
Formula
A[i, j] = exp(S′[i, j]) / Σj′ exp(S′[i, j′])
exponentiate each score in row i, then divide by the row's total. A is [3 × 3]; every row is positive and sums to 1.
Why this step

Exponentiating makes everything positive and lets big scores dominate; dividing by the sum makes the weights an average. Unlike argmax it is smooth, so gradients flow to every score.

Without it: weights could be negative or huge, and the output's scale would change with the number of tokens.

The numbers
exp(−0.98), exp(0.79), exp(−0.86) = 0.38, 2.20, 0.42; sum = 3.00
weights = exp / sum = 0.13, 0.73, 0.14
head 0, A [3 × 3]
head 1, A [3 × 3]
A = torch.softmax(S, dim=-1)  # rows sum to 1
shape: weights A: [3 × 3], rows sum to 1
11

Weighted sum of the values

Each token's output is a blend of the value vectors, mixed with its attention weights.

What to notice: “sat” takes most of its output (weight 0.73) from “cat”: information has moved from one token to another.
New symbols
  • Vhone head's 2 columns of V [3 × 2] computed columns 2h, 2h+1 of V
  • Ohone head's output: a blend of value rows [3 × 2] computed from A Vh
  • oi, vjrow i of Oh, row j of Vh [2] each computed
Formula
Oh = A Vh, oi = Σj A[i, j] · vj
A [3 × 3] times Vh [3 × 2] gives Oh [3 × 2]: output i is a weighted average of the value rows, with row i of A as the weights.
Why this step

This is the only place in the whole model where a token reads information from other tokens. Steps 7–10 only decided how much to read from each.

Without it: each token would be processed alone and could never use its context.

The numbers
osat = 0.13·[0.80, 0.39] + 0.73·[2.16, −0.24] + 0.14·[−1.34, 0.37] ≈ [1.50, −0.08]
head 0, O0 [3 × 2]
head 1, O1 [3 × 2]
O = A @ V[:, 0:2]   # [3, 3] @ [3, 2] -> [3, 2]
shape: Oh: [3 × 2] per head🎬 Watch this part: 3Blue1Brown ch. 6, “Values” (from 13:10)
12

Multi-head: several lookups side by side

Split the 4 columns of Q, K and V into 2 heads of 2 columns, run steps 7–11 in each head separately, glue the outputs back together and mix them with WO.

What to notice: the two heads read different tokens: in head 0 “sat” reads mostly “cat”; in head 1 it reads mostly itself and “the”.
New symbols
  • headsparallel attention lookups; head h owns dk = 2 of the 4 columns 2 setting 12 in GPT-2 small, 32 in a 7B model
  • [O0 | O1]the heads' outputs side by side (concatenated) [3 × 4] computed from O0, O1
  • WOoutput weights: mix the heads [4 × 4] learned weight
  • MHAmulti-head attention; its result is called attn_out [3 × 4] computed from [O0 | O1] WO
Formula
MHA(x̂) = [O0 | O1] WO
run steps 7–11 once per head on its own 2 columns, put the two [3 × 2] outputs side by side ([3 × 4]), then multiply by WO [4 × 4].
Why this step

One softmax row can only express one blend. With several heads a token can read different things at once (for example, one head the subject, another the previous word). It costs the same FLOPs as one head of size 4.

Nothing is cut off the token. The split happens after the projection: every column of Q is already a dot product with all 4 numbers of x̂ (step 6). Head 0's q[sat] = [1.31, 0.51] = x̂[sat] · (columns 0–1 of WQ). Those 2 columns are the paper's per-head matrix WQ(0) [4 × 2]; the [4 × 4] WQ is just the 2 per-head matrices side by side, with the same number of weights. One big matmul plus a reshape gives exactly the per-head projections, faster.

Without WO: each head's result would stay locked in its own 2 columns.

The numbers
WO [4 × 4]
attn_out = concat · WO [3 × 4]

Checked in step_by_step.py: equal to F.scaled_dot_product_attention(…, is_causal=True).

q, k, v = [t.view(3, 2, 2).transpose(0, 1) for t in (Q, K, V)]
o = F.scaled_dot_product_attention(q, k, v, is_causal=True)
attn_out = o.transpose(0, 1).reshape(3, 4) @ W_O  # [3, 4]
shape: concat [3 × 4] → WO → [3 × 4]🎬 Watch this part: 3Blue1Brown ch. 6, “Multiple heads” (from 19:19)
13

Residual connection: keep the original, add an edit

The attention result is not a replacement for x: it is an edit that gets added to x.

What to notice: x flows straight through; the attention branch only adds a change Δ.
New symbols
  • hresidual stream after attention (not the head number in Qh) [3 × 4] computed from x + MHA(x̂)
  • Δthe edit that attention adds (= attn_out) [3 × 4] computed from MHA(x̂)
Formula
h = x + MHA(LN1(x)) = x + Δ
the attention output [3 × 4] is added, element by element, to the block's own input x [3 × 4].
Why this step

The “+ x” path is a highway: the gradient reaches early layers through it unchanged (∂h/∂x = I + …), so stacks of 50–100 blocks still train. Each block only has to learn a small change.

Without it: deep stacks become very hard to train, and every block would have to re-create everything it does not change.

The numbers
h[sat] = [−0.7, 0.5, 0.7, 0.1] + [−0.15, −0.99, 2.29, 0.21] = [−0.85, −0.49, 2.99, 0.31]

The running sum x → h → y is called the residual stream. It is never normalized itself: each sub-layer normalizes its own copy (LN₁ in step 4, LN₂ next). The 2017 paper does normalize it: there h itself becomes LN(x + Δ) (step 16).

h = x + attn_out              # [3, 4]
shape: h: [3 × 4]🎬 Watch this part: Karpathy, “residual connections” (from 1:26:48)
14

LayerNorm again (LN₂): normalize h before the FFN

The same operation as step 4, now applied to h. Every sub-layer gets its own norm, with its own learned γ and β.

New symbols
  • LN2the LayerNorm in front of the FFN, with its own γ2, β2 operation same formula as LN1 (step 4)
  • ĥnormalized h: the FFN's input [3 × 4] computed from h: LN2(h)
Formula
ĥ = LN2(h) = γ2 ⊙ (h − μ) / √(σ² + ε) + β2
step 4's recipe, row by row, on h [3 × 4]: μ and σ are now the mean and spread of h's rows, and γ2, β2 are LN₂'s own weights (1 and 0 here).
Why normalize again

The residual stream drifts as edits pile up. Attention just added its edit to x, and each token's size changed by a different amount: the spread σ of (the, cat, sat) went from [0.31, 0.58, 0.54] in x to [1.05, 0.32, 1.50] in h. A 32-block model adds 64 such edits, so the scale keeps changing from sub-layer to sub-layer.

So each sub-layer normalizes its own input (LN₁ before attention, LN₂ before the FFN, LNf before the LM head in step 17) while the residual path itself is never normalized. Each norm has its own γ and β because each sub-layer wants its input at its own scale.

In the 2017 paper the same LN(h) is computed, but in another place: it runs after the add and replaces h on the residual path, so the FFN and the next add both see the normalized h (step 16).

Without it: activations and gradients blow up or shrink across layers, and training needs tiny learning rates.

The numbers: row “sat” of h
  1. h[sat] = [−0.85, −0.49, 2.99, 0.31]
  2. μ = 1.96 / 4 = 0.49
  3. h − μ = [−1.34, −0.98, 2.50, −0.18]
  4. 1.7956 + 0.9604 + 6.2500 + 0.0324 = 9.0384; σ² = 9.0384 / 4 = 2.26
  5. σ = √(2.26 + ε) = 1.50
  6. (h − μ) / σ ≈ [−0.89, −0.65, 1.66, −0.12]; γ2 = 1 and β2 = 0 leave it unchanged
  7. RMSNorm: rms = √(9.9988 / 4) = 1.58; h / rms ≈ [−0.54, −0.31, 1.89, 0.19]

≈ because σ is shown rounded: 2.50 / 1.50 gives 1.67; the unrounded result is 1.66.

ĥ = LN₂(h) [3 × 4]
hh = F.layer_norm(h, (4,))   # same op as step 4
# in a model: ln1, ln2 and ln_f are three separate
# nn.LayerNorm(4), each with its own gamma, beta
shape: ĥ: [3 × 4]
15

Feed-forward network (FFN): think about each token alone

A small MLP runs on every token separately: widen to 8 numbers, zero out the negatives, shrink back to 4.

What to notice: ReLU switches off 3 of the 8 hidden units for “sat”. The same W1, W2 run on “the” and “cat” too.
New symbols
  • W1FFN “expand” weights [4 × 8] learned weight
  • W2FFN “shrink” weights [8 × 4] learned weight
  • dffFFN hidden width 8 setting usually 4d
  • uhidden values before ReLU [3 × 8] computed from ĥ W1
  • ReLUmax(0, ·): negatives become 0 operation GELU or SwiGLU in real models
  • fthe FFN's output, FFN(ĥ) [3 × 4] computed from ReLU(u) W2
Formula
FFN(ĥ) = ReLU(ĥ W1) W2
ĥ [3 × 4] (from step 14) times W1 [4 × 8] gives u [3 × 8], the hidden width dff = 8; ReLU sets negatives to 0; times W2 [8 × 4] gives back [3 × 4]. Each row is processed on its own.
Why this step

Attention only moves and averages information. The FFN transforms it: in big models it holds about 2/3 of each block's weights and is thought to store much of the learned knowledge.

Why the nonlinearity: without ReLU, ĥ W1 W2 = ĥ (W1W2), a single [4 × 4] matrix, and the 8-wide layer adds nothing. GPT-2 uses GELU (a smooth ReLU); Llama uses SwiGLU.

The numbers
W1 [4 × 8]
W2 [8 × 4]
f = FFN(ĥ) [3 × 4], all three tokens
f = torch.relu(hh @ W1) @ W2  # [3,4]->[3,8]->[3,4]
shape: [3 × 4] → [3 × 8] → [3 × 4]🎬 Watch this part: 3Blue1Brown ch. 7, “Inside a multilayer perceptron” (from 6:07)
16

One full block, then stack L of them

A block is two “normalize, compute, add back” steps: attention, then FFN. The output has the input's shape, so blocks stack.

What to notice: read top to bottom and the step numbers go up in order: LN₁ (4), attention (5–12), add (13), LN₂ (14), FFN (15), add (16). Both blue side paths are residuals; the norms sit only on the branches.
New symbols
  • yblock output; the next block's x [3 × 4] computed from h + FFN(LN2(h))
Formula
h = x + MHA(LN1(x))
y = h + FFN(LN2(h))
two sub-layers, each “normalize, compute, add back”. Input x and output y are both [3 × 4], so x → block 1 → block 2 → … → block L works.
Why this order

This is the pre-norm block of GPT-2, Llama and transformer.py: the norm sits inside the side branch, so the residual highway stays a clean sum. After the last block one more norm, LNf, prepares y for the LM head (step 17).

Stacking: GPT-2 small has 12 blocks, Llama 2 7B has 32, GPT-3 175B has 96. Each has its own weights.

The numbers
y[sat] = h[sat] + f[sat] = [−0.85, −0.49, 2.99, 0.31] + [−0.18, −0.08, −0.60, 0.01] ≈ [−1.02, −0.57, 2.39, 0.32]
block output y [3 × 4]
h = x + attn(F.layer_norm(x, (4,)))   # steps 4-13
y = h + ffn(F.layer_norm(h, (4,)))    # steps 14-16
# L blocks: repeat with new weights, x = y

The 2017 paper's order: same parts, the norm moves

What to notice: the boxes and adds are on the same rows; only the red LN boxes move. In the paper (left) each LN sits on the blue residual path, after the add. On this page (right) the blue path skips every LN, so it is a plain sum, and one extra LNf is needed before the LM head.
Formula, both orders
paper (post-norm):
h = LN1(x + MHA(x))
y = LN2(h + FFN(h))

this page (pre-norm):
h = x + MHA(LN1(x))
y = h + FFN(LN2(h))
the same two sub-layers and the same two adds. In the paper the norm wraps the sum; here it wraps only the sub-layer's input.
Why models switched

Gradients. In the paper's order the learning signal reaches block 1 only by passing through every LN on the residual path, two per block. Early in training that makes the last layers' gradients large, so the paper needed a learning-rate warm-up (4,000 steps), and deep post-norm stacks are hard to train. In pre-norm the residual path is a plain sum, x + Δ₁ + Δ₂ + …, so the signal reaches block 1 directly (step 13's highway). Xiong et al. (2020) showed pre-norm trains without the warm-up.

The price: the pre-norm stream is never normalized, so its size drifts with depth. That is why step 17 starts with LNf.

Who uses which: post-norm: the 2017 Transformer, BERT, GPT-1. Pre-norm: GPT-2 and nearly everything since (GPT-3, Llama, Qwen, DeepSeek, ViT). A few recent models normalize both sides of each sub-layer (Gemma 2's “sandwich” norm).

The numbers: same weights, both orders
paper: y[sat] = [−1.70, 0.36, 0.89, 0.45]
this page: y[sat] = [−1.02, −0.57, 2.39, 0.32]

Spread σ of each token's row (the, cat, sat): paper [1.00, 1.00, 1.00], this page [0.98, 0.41, 1.31].

The paper's block ends in a norm, so its output always has mean 0 and spread 1 and can go straight into the next block or the LM head. This page's y keeps whatever size the edits gave it. The rows also differ because in the paper's order attention reads the raw x, not x̂, so Q, K and V change too.

# paper (post-norm): norm after the add
h = F.layer_norm(x + attn(x), (4,))
y = F.layer_norm(h + ffn(h), (4,))
# this page (pre-norm): norm on the branch
h = x + attn(F.layer_norm(x, (4,)))
y = h + ffn(F.layer_norm(h, (4,)))
shape: y: [3 × 4] (same as x)More: pre-norm vs post-norm in code, what changed since 2017
17

Final norm (LNf) → LM head (U) → next token

Two separate parts. LNf normalizes the last block's output; the LM head U then scores it against every vocabulary word. Softmax turns the 8 scores into probabilities, and a decoding rule picks one word.

Try it: low T sharpens the distribution toward “on”, high T flattens it. LNf and U do not change with T; only the softmax does.
New symbols
  • LNffinal LayerNorm after the last block (own γf, βf); not the LM head operation same formula as step 4
  • ŷnormalized y [3 × 4] computed from LNf(y)
  • ULM head: one column (a “fingerprint”) per vocabulary word [4 × 8] = [d × V] learned weight GPT-2 reuses Eᵀ
  • logitsone score per vocabulary word, for every position [3 × 8] computed from ŷ U
  • Ttemperature: logits are divided by T before softmax 1 setting chosen when generating
  • rrandom number that picks a word when sampling in [0, 1) computed drawn fresh for every pick
  • top-k, top-pkeep only the k likeliest words, or the fewest whose probabilities reach p setting chosen when generating
Formula
(1) ŷ = LNf(y)
(2) logits = ŷ U, p = softmax(logitslast / T)
(1) normalize y [3 × 4] once more; (2) multiply by the LM head U [4 × 8] to get one score per vocabulary word for every position ([3 × 8]). The last row predicts the next token; dividing by the temperature T (T = 1 changes nothing) and a softmax give p.
(1) Why LNf exists

LNf is the final LayerNorm: step 4's recipe with its own γf, βf (8 numbers). In a pre-norm block each sub-layer normalizes its input, but the block's output y = h + f is the raw residual stream: nothing normalizes the last block's output. LNf does, so U always sees vectors of a steady size. It does not score words. (The 2017 paper's post-norm block needs no LNf: its last operation is already a norm.)

(2) What the LM head does

The LM head U [d × V] = [4 × 8] has one column per vocabulary word: that word's “fingerprint” of 4 numbers. A logit is the dot product of ŷ[sat] with a fingerprint, large when the two point the same way. GPT-2 and transformer.py reuse the embedding table here (U = Eᵀ); our toy has its own U.

The numbers
(1) ŷ = LNf(y) [3 × 4]
(2) U, the LM head [4 × 8]: one column per word
logit(on) = ŷ[sat] · U[:, on] = −0.99 × (−1.0) + (−0.64) × (−0.7) + 1.61 × 1.0 + 0.03 × (−0.5) ≈ 3.04
logits [3 × 8]: row i predicts token i+1

p(on) = 0.97 at T = 0.5, 0.70 at T = 1, 0.38 at T = 2.

yh = F.layer_norm(y, (4,))       # (1) LN_f
logits = yh @ U                  # (2) [3, 8]
probs = torch.softmax(logits[-1] / T, -1)
next_id = probs.argmax()         # greedy, or
next_id = torch.multinomial(probs, 1)  # sample

Greedy vs sampling: how one word is picked

Lay the 8 probabilities end to end as segments of the line from 0 to 1, largest first. Greedy ignores the line and always takes the largest segment. Sampling draws a random number r between 0 and 1 and takes the word whose segment r lands in, so each word is picked with exactly its probability.

Press Sample: r lands mostly in “on”, sometimes in the small segments. Raise T and the small segments grow.

At T = 1 the segments are “on” [0.00, 0.70), “dog” [0.70, 0.78), “mat” [0.78, 0.84), “.” [0.84, 0.89), and four smaller ones up to 1. So r = 0.42 → “on”, r = 0.81 → “mat”.

GreedySampling
Picksthe largest p (argmax)the segment a random r lands in
Same prompt twicesame text every time (deterministic)different text (fix the random seed to repeat)
Temperature Tignored: dividing all logits by T does not change which is largestlow T → nearly greedy (T → 0 is greedy); high T → flatter, more surprises
Typical usesshort factual answers, code, math, testschat, stories, brainstorming
Riskrepetition: loops of the same phrase, bland textodd or wrong words from the long tail

Top-k and top-p trim the tail: keep only the k largest segments (top-k = 3 keeps “on”, “dog”, “mat”) or the fewest whose total reaches p (top-p), stretch them to fill 0 to 1 again, then sample. That removes the rare words where odd picks come from.

shape: logits [3 × 8] → last row → [8 probs]🎬 Watch this part: 3Blue1Brown ch. 5, “Unembedding” and “Softmax with temperature” (from 20:22)
18

Generating text: the loop and the KV cache

Pick a token, append it, run again. Old tokens' keys and values never change and every later token reads them, so we keep them in a cache and push only the new token through.

New symbols
  • next_idthe picked token's ID 1 integer computed pick(p): greedy or sampled
  • ttokens so far = rows in the cache 3, 4, 5, … computed +1 per generated token
  • K, V cacheevery key and value computed so far [t × 4] each computed one row appended per new token
  • q, k, vthe new token's query, key and value [1 × 4] each computed from its x̂ times WQ, WK, WV
Formula
repeat: p = model(ids); next_id = pick(p); ids = ids + [next_id]
run the model, pick a token (step 17), append it, repeat. With a KV cache each step sends only the new token through the block: its q, k, v are [1 × 4], and the K and V caches grow from [3 × 4] to [4 × 4] to [5 × 4]: [t × 4] after t tokens.
Why K and V can be cached

Thanks to the causal mask (step 9), a past token never looks at later tokens, so its K and V in every layer never change. Every future query reads all of them again: compute them once, keep them. (In our 1-block toy K and V depend only on each token's own embedding and position; in deeper models the mask is what keeps them fixed.)

Without the cache: every step re-runs the whole prefix, so the total work grows at least with the square of the length. Step 19 counts it: 384 FLOPs per new token with the cache, 1,536 without.

The numbers

Prefill “the cat sat” → “on” (p = 0.70). Decode “on” → “the” (p = 0.66). Decode “the” → “mat” (p = 0.65).

New key of “on”: k = [0.05, 0.85, −0.62, −0.35]. The first 3 cache rows are exactly the K and V of step 6.

step_by_step.py asserts that the cached logits equal a full recompute at every step. Result: “the cat sat on the mat”.

k_cache = torch.cat([k_cache, k_new[None]])  # [t+1, 4]
v_cache = torch.cat([v_cache, v_new[None]])
w = (q_new[:2] @ k_cache[:, :2].T / 2**0.5).softmax(-1)  # head 0
o = w @ v_cache[:, :2]   # q_new: used once, dropped

What about Q?

Q is used once by its own token; K and V are reused by every later token. Caching something you never read again saves nothing.

The queries of old tokens do not change either (the same causal argument). They are simply never needed again: a query is used only to make its own token's output row, while keys and values are read by every later token. The grid shows decode step 1 (“on” is new) for head 0.

What to notice: only the last row is computed: the new q against every cached k, then the weights times every cached v. The faded rows belong to old queries; their outputs were used when “cat”, “sat” and “on” were predicted, and they are never read again.

New row (head 0): qon · kj / √2 = [−0.76, 0.54, −0.64, 0.33] → weights [0.11, 0.42, 0.13, 0.34] → oon = [0.10, −0.08]. The other 3 rows are the prefill rows of step 9, unchanged.

shape: K, V cache: [t × 4], grows by 1 row📖 Read this part: Jay Alammar, The Illustrated GPT-2 (the section on processing one new token at a time)
19

Counting: parameters, FLOPs and memory

Count the weights once, and you can estimate the compute and the memory of any GPT.

What to notice: in the toy, the tables (embeddings, positions, LM head) are the biggest part; in a 7B model the blocks' matrices are over 96%, and the FFN alone is 2/3.
Symbols in this formula
  • Lnumber of blocks 1 here (seen in step 0)
  • Ntokens in the context (rows in the KV cache when decoding) 3 (seen in step 1)
  • Vvocabulary size 8 (seen in step 1)
  • dmodel width 4 (seen in step 2)
  • dffFFN hidden width 8 (seen in step 15)
  • paramshow many learned numbers the model has 248 here computed sum of all weight shapes
  • FLOPsfloating-point operations: one multiply or one add (seen in step 5)
  • bytesbytes per stored number 2 (FP16) setting 1 for INT8, 0.5 for INT4
Formula
params ≈ L·(4d² + 2·d·dff) + V·d
FLOPs/token ≈ 2 × params + 4·L·N·d
KV bytes/token = 2 · L · d · bytes
each block has 4d² attention weights (WQ, WK, WV, WO) and 2·d·dff FFN weights (= 8d² when dff = 4d); a forward pass does 2 FLOPs (multiply + add) per weight per token, plus attention over N context tokens; every token stores one K and one V vector of size d per layer.
Why it matters

Generating one token (at batch size 1) reads every weight once but does only about 2 FLOPs per weight, so on a GPU it is limited by memory bandwidth, not compute. Shrinking weight memory (quantization) and KV-cache memory (GQA, KV quantization, paging) is where inference optimization starts. These are explained in the full guide's §3 Decode and the cookbook cards b, c and e.

Next: Memory & inference efficiency cookbook and the prefill vs decode and memory sections of the full guide.

The numbers

Toy (d = 4, dff = 8, L = 1, V = 8): embedding 32 + positions 32 + attention 64 + FFN 64 + norms 24 + LM head 32 = 248 parameters. Forward pass over 3 tokens: 1104 FLOPs = 3 × 320 + 144 for attention. KV cache: 8 numbers per token.

7B-class (GPT-3 6.7B shape: d = 4096, L = 32, dff = 4d, V = 50,257, 2048 positions): 12d² = 201,326,592 per block × 32 = 6,442,450,944, + embeddings 205,852,672 + positions 8,388,608 = 6,656,692,224.

Compute: about 13.3 GFLOPs per token (+ 1.07 for attention at N = 2048). Weights in FP16: 13.3 GB. KV cache in FP16: 2 × 32 × 4096 × 2 B = 524,288 B = 512 KiB per token, 1.0 GiB at 2048 tokens, 2.0 GiB at 4096 (Llama 2 7B has the same d and L, so the same cache).

weights = (E, P, W_Q, W_K, W_V, W_O, W1, W2, U)
n_params = sum(t.numel() for t in weights) + 24  # + norms
kv_bytes_per_token = 2 * L * d * 2  # K + V, FP16

One decode step with the KV cache, counted

The new token “on” goes through alone; the cache already holds 4 rows (the, cat, sat, on). Rule: an [m × k]·[k × n] matmul costs 2·m·k·n FLOPs.

Operation (toy)ShapesFLOPs
Q, K, V projections[1×4]·[4×12]96
scores q·kᵀ, 2 heads2 × [1×2]·[2×4]32
weights × V, 2 heads2 × [1×4]·[4×2]32
WO[1×4]·[4×4]32
FFN up, W1[1×4]·[4×8]64
FFN down, W2[1×8]·[8×4]64
LM head, U[1×4]·[4×8]64
total320 weights + 64 attention over the cache384

Without the cache all 4 tokens go through again: 1,536 FLOPs (1,344 if the LM head runs only on the last row), 4 times the cached step, and the gap grows with every token.

Do the norms count? The table counts only matmuls. A LayerNorm costs about 7d FLOPs per token (mean, subtract, square, sum, divide, × γ, + β), an RMSNorm about 4d (square, sum, divide, × γ). In the toy step the 3 LayerNorms are 84 FLOPs, and all element-wise work (norms, the ÷√dk scale, softmaxes, ReLU, residual adds) adds 156, about 29% of the step. At d = 4096 it is under 1%, because matmuls grow with d² and norms only with d: the 65 LayerNorms of the 7B-class model below are 1.9 MFLOP, and all element-wise ops about 0.1% of the FLOPs. They still cost time: each one reads and writes whole vectors for a few FLOPs, so it is memory-bound and pays a kernel launch. That is why inference engines fuse them into neighbouring kernels (cookbook card h, kernel fusion).

Scale it to the 7B-class model (L = 32, d = 4096, N = 4096 cached tokens): 2 FLOPs per weight is 13.30 GFLOP, plus attention 4·L·N·d = 2.15 GFLOP, ≈ 15.44 GFLOP per new token. The step reads 13.31 GB of FP16 weights and 2.15 GB of cached K and V, 15.46 GB in all: about 1.0 FLOP per byte, so it is memory-bound. On a Jetson AGX Orin (204.8 GB/s) that caps decode at about 13 tokens/s, however many TFLOPS the GPU has. (The full guide's §3.3 gives the same 13 tokens/s; its roofline widget's ≈ 15.4 tokens/s counts the weights only, no cache.)

shape: params, FLOPs, bytes🎬 Watch this part: 3Blue1Brown ch. 6, “Counting parameters” (from 15:44)

Key takeaways

  • A GPT maps token IDs to next-token probabilities: embed + position → L blocks → final norm → LM head → softmax. The shape stays [tokens × d] through every block.
  • Every linear layer is a matmul, and every output number is one dot product of a token's row with a weight column, done for all tokens at once.
  • Attention = scores q·k → ÷√dk → causal mask → softmax → weighted average of the values. It is the only place where tokens exchange information.
  • Multi-head attention runs the same lookup on separate slices of the dims, then mixes the results with WO.
  • A pre-norm block runs LN₁ → attention → add, then LN₂ → FFN → add (the 2017 paper is post-norm: attention → add → LN; modern models moved the norm onto the branch so the residual path stays a plain sum). Residuals keep the input and add an edit; each sub-layer normalizes its own input to a steady scale (mean 0, spread 1, divided by d, not d − 1); the FFN transforms each token on its own and needs its nonlinearity.
  • The final norm LNf and the LM head U are two different things: LNf rescales the last vector, U scores it against every word. Greedy takes the largest probability; sampling lets a random r pick a segment of the probability line.
  • Generation is a loop. Because of the causal mask, old keys and values never change and every later token reads them, so they are cached; a query is used once by its own token, so it is not.
  • params ≈ 12·L·d² + V·d, FLOPs per token ≈ 2 × params + 4·L·N·d, KV cache = 2·L·d·bytes per token. A decode step does about 1 FLOP per byte it reads, so it is memory-bound: the starting point for inference optimization.

Self-check

Try each question before opening the answer.

1. In the toy, what are the shapes of Q, of one head's score matrix, and of the logits?

Answer

Q is [3 × 4] (3 tokens × d = 4 numbers). Each head's scores are [3 × 3] (query × key), and there are 2 heads. The logits are [3 × 8] (one row per position, one column per vocabulary word); only the last row is used to pick the next token.

2. Why is the first row of every causal attention matrix [1, 0, 0]?

Answer

Token 0 may only look at itself: the other scores in its row are −∞. A softmax over one finite score gives weight 1 to it and exp(−∞) = 0 to the rest.

3. A real model has dk = 128 and q, k entries with variance 1. What is the typical size (standard deviation) of a raw score, and what happens without the 1/√dk scale?

Answer

The variance of q·k is dk = 128, so the standard deviation is √128 ≈ 11.31. Softmax of numbers that far apart is almost one-hot (step 8's demo gives 0.00, 1.00, 0.00), so the other keys get almost no gradient and training stalls.

4. What goes wrong if we skip the projections and use x̂ itself as Q, K and V?

Answer

After LayerNorm (with γ = 1, as here) every x̂ has the same squared length d = 4, so by Cauchy–Schwarz x̂i·x̂j ≤ x̂i·x̂i: every token scores itself highest. The model also could not separate “what I look for” from “what I contain”, or choose what to pass on.

5. Why does the FFN need the ReLU between W1 and W2?

Answer

Without it, (ĥW1)W2 = ĥ(W1W2): two linear layers collapse into one [4 × 4] matrix, so the 8-wide hidden layer adds nothing a single linear map could not do.

6. During generation, why can K and V be cached, but not Q?

Answer

With a causal mask, a past token never attends to later tokens, so its K and V (in every layer) are fixed once computed, and every later query reads them. A query is only used to produce its own token's output, which is already done, so old queries are never needed again. In short: Q is used once by its own token; K and V are reused by every later token.

7. How many numbers does the toy's KV cache hold after “the cat sat on the” (5 tokens)? How big is the cache of the 7B-class model from step 19 for one 4096-token sequence in FP16?

Answer

Toy: 5 tokens × (4 for K + 4 for V) × 1 layer = 40 numbers (the last state of step 18). 7B-class: 2 × 32 layers × 4096 × 2 bytes = 512 KiB per token, × 4096 tokens = 2.0 GiB.

8. Most GPTs use dff = 4·d. How many parameters would the toy have with dff = 16 instead of 8?

Answer

The FFN goes from 2·4·8 = 64 to 2·4·16 = 128 weights; nothing else changes: 248 − 64 + 128 = 312.

9. LayerNorm the row [1, 2, 3, 6] by hand (γ = 1, β = 0, ignore ε). What would change if you divided by d − 1?

Answer

μ = 12 / 4 = 3; row − μ = [−2, −1, 0, 3]; squares 4 + 1 + 0 + 9 = 14, σ² = 14 / 4 = 3.5, σ = 1.87; result [−1.07, −0.53, 0.00, 1.60]. Dividing by d − 1 = 3 would give σ² = 4.67, a different σ and different outputs; LayerNorm uses d (step 4).

10. At T = 1, sampling draws r = 0.75. Which word is picked? What does greedy pick, and does T matter for greedy?

Answer

The segments, largest first, are “on” [0, 0.70) and then “dog” [0.70, 0.78), so r = 0.75 picks “dog”. Greedy always picks “on”, the largest probability, at every T: dividing all logits by the same T never changes which one is largest.

Next: the full guide, then build it yourself

You have seen every number. Read the full guide next; then write the code in labs 01–03 (each lab checks itself against PyTorch) and continue with Build an LLM.

Run python labs/check.py 1 from the repository root to check lab 1 (and so on). All labs: the labs hub.

Three warm-ups with step_by_step.py

1. Predict, then run (easy)

Change W_Q[0][0] from −0.2 to 0.5. Before running, write down which steps' numbers will change. Then diff the two printouts.

python step_by_step.py > before.txt   # edit W_Q, then:
python step_by_step.py > after.txt; diff before.txt after.txt
# x, x_hat, K and V must be unchanged; Q and everything after it may change

2. A wider FFN that changes nothing (medium)

Make dff = 16 by adding 8 columns of zeros to W1 and 8 rows of zeros to W2. Predict the outputs and the parameter count, then check.

python step_by_step.py --json > before.json   # then edit W1, W2 and DFF = 16
python step_by_step.py --json > after.json
# check: before["y"] == after["y"]  and  after["counts"]["total"] == 312

3. Break the cache (hard)

Add a second block (any weights) and remove the causal mask from forward. The KV-cache assertion now fails. Explain why it still passed with one block, then restore the mask and watch it pass.

# hint: block 2's K and V are computed from block 1's OUTPUT,
# which changes for old tokens once they can see new ones

References