Phase 7 · Transformers/
Lesson 7.4core3 h⚡ live demo

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

  1. 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.
  2. Pre-norm keeps the identity path clean and trains stably at depth; post-norm (2017) needs careful warmup.
  3. LayerNorm standardizes across features per token; RMSNorm drops the mean and bias and is the modern default.
Show 4 more key ideas
  1. The FFN (d → 4d → d, or SwiGLU with 8d/3) processes positions independently and acts as a key–value memory storing learned associations.
  2. Parameters per layer ≈ 12d² (4d² attention + 8d² FFN); total ≈ 12Ld² + Vd. GPT-2 small → 124M, Llama 2 7B → 6.74B.
  3. A forward pass costs ≈ 2 FLOPs per parameter per token in the weight matrices, plus ≈ 4nd per layer for attention over n tokens.
  4. Embeddings map ids to vectors; the unembedding maps the final stream to logits; tying them saves Vd parameters.

Suggested path through this lesson