Inside the block: residuals, LayerNorm, FFN and embeddings
The residual stream, the key–value memory, and how to count every parameter
Attention gets the headlines, but two thirds of a transformer's parameters live in the feed-forward networks, and the residual stream that threads through every block is the key to understanding both training stability (4.6 Initialization and normalization) and interpretability (8.11 Interpretability: what is happening inside). Being able to count parameters and FLOPs from a config file is the practical skill behind scaling laws (7.9 Scaling laws and compute-optimal training), memory planning for inference (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization) and parameter-efficient fine-tuning (8.2 Fine-tuning and PEFT).
You'll be able to
- Write a pre-norm transformer block as two residual updates and explain the residual-stream view
- Compare LayerNorm and RMSNorm, and GELU-FFN and SwiGLU, with their equations and parameter counts
- Derive the ≈12d² parameters-per-layer rule and reproduce the parameter counts of GPT-2 small and Llama 2 7B
- Explain the key–value-memory interpretation of the FFN and where compute goes in a forward pass
Key ideas
- A pre-norm block is two residual updates: x ← x + MHA(LN(x)); x ← x + FFN(LN(x)). The residual stream is the model's shared working memory.
- Pre-norm keeps the identity path clean and trains stably at depth; post-norm (2017) needs careful warmup.
- LayerNorm standardizes across features per token; RMSNorm drops the mean and bias and is the modern default.
Show 4 more key ideas
- The FFN (d → 4d → d, or SwiGLU with 8d/3) processes positions independently and acts as a key–value memory storing learned associations.
- Parameters per layer ≈ 12d² (4d² attention + 8d² FFN); total ≈ 12Ld² + Vd. GPT-2 small → 124M, Llama 2 7B → 6.74B.
- A forward pass costs ≈ 2 FLOPs per parameter per token in the weight matrices, plus ≈ 4nd per layer for attention over n tokens.
- Embeddings map ids to vectors; the unembedding maps the final stream to logits; tying them saves Vd parameters.
Suggested path through this lesson
The residual stream
Write one transformer layer (pre-norm, as in GPT-2 and everything since) as two updates to a running vector per token:
The vector that flows straight through, untouched except for additions, is the residual stream. Each sub-layer reads from it (after normalization) and writes back by adding. This view, popularized by interpretability research (8.11 Interpretability: what is happening inside), explains a lot: gradients reach early layers through the identity path (4.6 Initialization and normalization, 5.3 Architectures: LeNet → AlexNet → VGG → Inception → ResNet → EfficientNet → ConvNeXt); layers can specialize because each only has to add a correction; and the stream is a shared communication bus of width that attention heads and FFN neurons use to pass information to later layers — the model's working memory.
The original paper used post-norm (), which normalizes the residual path itself. Deep post-norm stacks are hard to train without careful warmup; pre-norm keeps the identity path clean and is now universal, with one final LayerNorm before the output head.
Normalization: LayerNorm and RMSNorm
LayerNorm standardizes each token's vector across its features (4.6 Initialization and normalization):
Unlike BatchNorm it needs no batch statistics, so it behaves identically in training and inference and works for variable-length sequences. RMSNorm (used by Llama, Gemma, Qwen) drops the mean subtraction and the bias:
It is cheaper, equally effective in practice, and keeps the stream's direction while fixing its scale — a direct application of normalizing a vector to the unit sphere (1.1 Vectors, dot products and norms).
The feed-forward network: a key–value memory
Attention moves information between positions; the FFN processes each position independently with the same weights:
The original was ReLU; GPT-2 switched to GELU (4.2 Activation functions). Llama uses SwiGLU, a gated variant with so that its three matrices hold the same parameters as the two-matrix version.
Intuition. Read the rows of as keys: each neuron fires when the token's vector matches its pattern. Read the columns of as values: a firing neuron adds its value vector to the residual stream. With the layer stores thousands of such pattern→update pairs — this is where factual associations like "Michael Jordan → basketball" are believed to live (3Blue1Brown's chapter 7 walks through exactly this picture).
Embeddings in and out
Token ids enter through an embedding matrix ; after the last layer, the unembedding maps each position back to vocabulary logits, and a softmax gives next-token probabilities (7.6 Decoder-only: GPT and autoregressive generation). GPT-2 ties (saving parameters and acting as a regularizer); Llama keeps them separate. Dropout, when used, is applied to embeddings, attention weights and sub-layer outputs; models trained for a single epoch over trillions of tokens generally use none (4.7 Regularization in deep nets).
Counting parameters
Per layer, attention contributes (7.2 Scaled dot-product and multi-head attention, fully derived) and the FFN , so
LayerNorm gains and biases add only per layer. Two worked counts:
- GPT-2 small: , , , . Layers: M. Token embeddings (tied): M. Positions: M. Total M — the reported 124M.
- Llama 2 7B: , , (SwiGLU), , untied embeddings, RoPE (no position table). Attention M; FFN M; per layer M; B; embeddings B. Total B — matching the published figure.
The llm-calculator demo does this arithmetic for any configuration, and also estimates training FLOPs and inference memory (7.9 Scaling laws and compute-optimal training, 7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization).
Where the compute goes
A matrix–vector product with a -parameter matrix costs about FLOPs (one multiply and one add per weight). So a token passing through one layer costs roughly FLOPs in the weight matrices, plus about for the attention scores and value mixing over a context of tokens. For (GPT-2: , ) the weights dominate; at 128k-token contexts the attention term takes over — which is why long context is expensive (7.12 Beyond vanilla attention: state space models, long context and hybrids). Summed over the forward and backward passes this becomes the rule of 7.9 Scaling laws and compute-optimal training.
A block in code
import torch.nn as nn
class Block(nn.Module):
def __init__(self, d, n_heads, d_ff=None, dropout=0.0):
super().__init__()
d_ff = d_ff or 4 * d
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.attn = MultiHeadAttention(d, n_heads) # from lesson 7.2
self.ffn = nn.Sequential(nn.Linear(d, d_ff), nn.GELU(),
nn.Linear(d_ff, d), nn.Dropout(dropout))
def forward(self, x):
x = x + self.attn(self.ln1(x)) # read, write back
x = x + self.ffn(self.ln2(x))
return x
Stack of these between an embedding and an unembedding and you have a GPT (7.8 Build GPT from scratch (nanoGPT walkthrough)).
Where this shows up later
- Pre-norm blocks with RMSNorm/SwiGLU are the Llama recipe — 7.6 Decoder-only: GPT and autoregressive generation; replacing the FFN with routed experts gives MoE — 7.11 Mixture of Experts.
- The parameter and FLOP counts feed scaling laws (7.9 Scaling laws and compute-optimal training) and memory planning for inference (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization, 4.12 Compute, hardware and scale basics).
- The residual stream, the FFN key–value view and the unembedding ("logit lens") are the vocabulary of mechanistic interpretability — 8.11 Interpretability: what is happening inside.
- LoRA adapts exactly these weight matrices with low-rank updates — 8.2 Fine-tuning and PEFT.
Common pitfalls (4)
- Assuming attention holds most of the parameters — the FFN has twice as many (8d² vs 4d²).
- Forgetting the embedding matrix when counting parameters; for small models with large vocabularies it can be a third of the total.
- Mixing up LayerNorm (normalizes across the features of one token) with BatchNorm (normalizes across the batch).
- Treating SwiGLU's three matrices as 50% more parameters — d_ff is shrunk to 8d/3 precisely to keep the parameter count fixed.
Recap: all 7 key points
- A pre-norm block is two residual updates: x ← x + MHA(LN(x)); x ← x + FFN(LN(x)). The residual stream is the model's shared working memory.
- Pre-norm keeps the identity path clean and trains stably at depth; post-norm (2017) needs careful warmup.
- LayerNorm standardizes across features per token; RMSNorm drops the mean and bias and is the modern default.
- The FFN (d → 4d → d, or SwiGLU with 8d/3) processes positions independently and acts as a key–value memory storing learned associations.
- Parameters per layer ≈ 12d² (4d² attention + 8d² FFN); total ≈ 12Ld² + Vd. GPT-2 small → 124M, Llama 2 7B → 6.74B.
- A forward pass costs ≈ 2 FLOPs per parameter per token in the weight matrices, plus ≈ 4nd per layer for attention over n tokens.
- Embeddings map ids to vectors; the unembedding maps the final stream to logits; tying them saves Vd parameters.
Watch
The FFN as a key–value memory, animated — the clearest explanation of what the MLP layers do.
Read
Try it live
Interactive demo
runs in your browserExercises
- Count a model from its config
Take the Hugging Face config of
gpt2-medium(, , , ) and ofmeta-llama/Llama-3.2-1B(, , , , 32 heads / 8 KV heads, tied embeddings) and compute their parameter counts by hand, then verify withsum(p.numel() for p in model.parameters()). Expected: ≈355M and ≈1.24B. Note how GQA (7.10 Efficient inference: KV cache, GQA, FlashAttention, speculative decoding, quantization) shrinks the K/V projections. - Pre-norm vs post-norm
Train the tiny GPT from 7.8 Build GPT from scratch (nanoGPT walkthrough) for 2,000 steps in both configurations with the same learning rate and no warmup. Expected: post-norm diverges or trains noticeably slower at 6+ layers; pre-norm is stable.
- FFN neurons as detectors
Using GPT-2 small, record the activations of layer 6's FFN hidden units on 1,000 sentences and find the top-activating tokens for five neurons. Expected: several neurons respond to interpretable patterns (numbers, code, names), though many are polysemantic (8.11 Interpretability: what is happening inside).
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →