Chapter 5 of 40 · ~26 min read & lab+85 XP
Chapter 5 · Generative AI

Multi-Head Attention, Pre-Norm RMSNorm & SwiGLU Transformer Blocks

Why splitting d_model into H parallel attention heads unlocks rich specialization at zero extra FLOPs, how Pre-Norm RMSNorm + SwiGLU FFN form the modern LLaMA/GPT block, and Encoder vs. Decoder families.

What Is It?

A modern Transformer Block pairs Multi-Head Attention (several parallel attention heads tracking grammar, entities, and logic simultaneously) with Pre-Norm RMSNorm and a SwiGLU feed-forward network.

Why Is It Required?

A single attention head averages all relationships into one blur; stacking Multi-Head Pre-Norm residual blocks enables stable training of 100-layer frontier LLMs.

Everyday Analogy: A committee of specialists reading the same document in parallel—one tracking dates, one tracking names, one tracking tone—then merging their notes.
Why ML Engineers & Data Scientists Actually Need This

Every frontier LLM — LLaMA 3, Gemma 2, DeepSeek, Mistral, Qwen — is simply 32 to 128 stacked copies of THIS exact Pre-Norm RMSNorm + MHA + SwiGLU block!

ML / AI Engineer

Knowing the exact 4-line .view(B, T, H, d_k).transpose(1, 2) tensor dance and the 12 · D² parameter rule per Transformer layer lets you architect, debug, and size any LLM from memory!

Data Scientist

Understanding that Attention is token-mixing (communication) while the SwiGLU FFN is channel-mixing (storing ~2/3 of the model's factual knowledge!) gives deep intuition for interpretability and LoRA targeting.

Interview & Debug Edge

Classic LLM architecture interview question: 'Implement Multi-Head Attention in PyTorch, prove its FLOPs match single-head attention, and explain why Pre-Norm beat Post-Norm!'

Step 0 · Test Your Gut Before Any Math!

In a standard Multi-Head Attention layer (d_model = D, H heads, d_k = D / H), how many total parameters are in the four projection matrices W_Q, W_K, W_V, W_O (excluding bias)?

What You Will Master in This Chapter
  • Trace exact tensor reshaping (B, T, D) → (B, H, T, d_k) → (B, T, D) in Multi-Head Attention
  • Prove why Multi-Head Attention with d_k = D / H uses the EXACT same FLOPs as single-head attention of width D
  • Explain why modern LLMs switched from Post-Norm LayerNorm + ReLU to Pre-Norm RMSNorm + SwiGLU FFN
  • Compare Encoder-only (BERT), Decoder-only (GPT/LLaMA), and Encoder-Decoder (T5/Whisper) architectures
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
H, d_kSay aloud:“num heads & head dim”
Plain-English Meaning
Number of parallel attention subspaces and width of each head (d_k = D / H)
Everyday Example
LLaMA-8B: D=4096, H=32, d_k=128
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

A single attention head is like having 1 spotlight — it can focus on either grammar or pronoun references, but not both cleanly at once. Multi-Head Attention gives the Transformer 32 independent colored spotlights shining in parallel: Head 1 tracks who did what, Head 2 tracks code indentation, Head 3 tracks rhymes — then W_O blends all 32 perspectives back onto the shared Residual Stream conveyor belt!

1. Multi-Head Attention: Parallel Subspaces at Zero Extra Parameter Cost

Everyday Story First (Zero Math Yet!)

Click Head 1 / Head 2 / Head 3 below to see how different heads learn completely different linguistic roles simultaneously!

Multi-Head Attention: Split d_model Into H Parallel Specialist SubspacesHead 1 (Syntax)dim = d_k = D/HHead 2 (Pronouns)dim = d_k = D/HHead 3 (Context)dim = d_k = D/HHead H (Local)dim = d_k = D/HConcat(Head₁…Head_H) · W_O → (B, T, D)
Multi-Head Attention splits d_model into H parallel subspaces (d_k = d_model / H) so Head 1 tracks syntax, Head 2 tracks pronoun coreference, and Head 3 tracks local phrasing simultaneously!

The Exact 4-Step Multi-Head Tensor Dance

  1. Project: Q,K,V=XWQ,XWK,XWVQ, K, V = XW_Q, XW_K, XW_V → each shape (B,T,D)(B, T, D).
  2. Split Heads: .view(B, T, H, d_k).transpose(1, 2) → shape (B,H,T,dk)(B, H, T, d_k).
  3. Parallel Attention: Batched matmul computes all HH heads simultaneously → (B,H,T,dk)(B, H, T, d_k).
  4. Concat & Mix: .transpose(1, 2).contiguous().view(B, T, D) then multiply by WOW_O → (B,T,D)(B, T, D)!
Animated Mini-Lab • 1.4

Multi-Head Specialization Switcher

Head 1: Pronoun Coreference
Peak Attention: 'it' → 'animal' (0.86)

Links pronouns back to the semantic subject across long clauses.

2. The Modern Decoder-Only Block: Pre-Norm RMSNorm + SwiGLU FFN

Everyday Story First (Zero Math Yet!)

Original 2017 Transformers placed LayerNorm after the residual add (Post-Norm), which caused exploding gradients at 50+ layers without delicate warmup. Modern LLMs moved RMSNorm inside the branch (Pre-Norm) and upgraded ReLU FFN to SwiGLU!

Modern Decoder-Only Block (LLaMA / Gemma): Pre-Norm Residual StreamUnblocked Residual Highway (+x)RMSNorm → Causal MHACross-token communication+RMSNorm → SwiGLU FFNPer-token factual memory+Pre-Norm keeps the residual highway identity-clean → trains stably at 80–120+ layers without warmup crashes!
Modern LLMs (LLaMA, GPT, Gemma) use Pre-Norm RMSNorm + SwiGLU FFN on an unblocked residual stream x + Attn(Norm(x)) + FFN(Norm(·)), keeping gradients healthy across 80+ layers.

Modern LLaMA / Gemma Block Equations

h=x+MHA(RMSNorm1(x))h = x + \text{MHA}(\text{RMSNorm}_1(x)) y=h+SwiGLU(RMSNorm2(h))y = h + \text{SwiGLU}(\text{RMSNorm}_2(h)) where SwiGLU(u)=(SiLU(uWgate)⊙(uWup))Wdown\text{SwiGLU}(u) = \big(\text{SiLU}(u W_{\text{gate}}) \odot (u W_{\text{up}})\big) W_{\text{down}}.

Quick Parameter Rule of Thumb: ~12 · D² per Layer!

  • Attention (W_Q, W_K, W_V, W_O): 4D24 D^2 parameters.
  • FFN (2 matrices of 4D4D or 3 SwiGLU matrices of 83D\frac{8}{3}D): 8D28 D^2 parameters (2/3 of the entire LLM!).
  • Total per layer: ≈12D2\approx 12 D^2 (e.g., 32 layers at D=4096  ⟹  32×12×40962≈6.4BD = 4096 \implies 32 \times 12 \times 4096^2 \approx 6.4\text{B} + embeddings ≈7B\approx 7\text{B}!).
Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of the 12·D² Transformer Layer Parameter Budget

Params_layer ≈ 4D² (Attention) + 8D² (FFN) = 12D²

Attention Projections

W_Q, W_K, W_V, and W_O — handles cross-token communication.

In our example: 33% of layer weights
Put it together with real numbers: Need to estimate any dense LLM's parameter count in an interview? Just compute 12 × L × D² + 2 × V × D in 5 seconds!

3. Encoder-Only vs. Decoder-Only vs. Encoder–Decoder Families

Everyday Story First (Zero Math Yet!)

Why did Decoder-only models (GPT, LLaMA, Claude, Gemini) win general AI, while Encoder-only models (BERT, BGE) still dominate RAG embedding search?

The 3 Transformer Families: Encoder-Only vs. Decoder-Only vs. Enc-DecEncoder-Only (BERT)Bidirectional (Full)Embeddings, Rerankers, NERDecoder-Only (GPT/LLaMA)Causal (Lower Triangle)Chat, Code, Reasoning LLMs ✓Encoder-Decoder (T5/Whisper)Bidirectional + CausalAudio ASR & Translation
Encoder-only (BERT) uses bidirectional attention for embeddings/classification; Decoder-only (GPT/LLaMA) uses causal attention for generation; Encoder-Decoder (T5/Whisper) bridges both via Cross-Attention.

Choosing the Right Transformer Family

  • Encoder-Only (BERT, RoBERTa, ModernBERT): Bidirectional attention sees the entire sentence at once → ideal for dense embeddings, Cross-Encoder rerankers, and classification.
  • Decoder-Only (GPT, LLaMA, Gemma, DeepSeek): Unified causal next-token objective scales effortlessly to trillions of tokens and handles chat, code, RAG, and reasoning in one architecture!
  • Encoder–Decoder (T5, Whisper): Dedicated bidirectional encoder for audio/source + causal decoder for text generation.
Walk Through With Me · Interactive Worked Example

Worked Example: Checking Tensor Shapes Inside Multi-Head Attention

Input x has shape (B=2, T=16, D=512) with H=8 heads.

11. Compute head dimension d_kStep 1 / 3

dk=D/H=512/8=64d_k = D / H = 512 / 8 = 64.

Teacher's Note: D must always be evenly divisible by H.
Pause & Check · Quick Intuition Pulse

In a standard dense Transformer block, roughly what fraction of the layer's parameters live in the FFN (MLP/SwiGLU) vs. Attention?

Try It YourselfStandard

Why do we need .contiguous() before .view(B, T, D) (or use .reshape(B, T, D)) right after .transpose(1, 2) in PyTorch Multi-Head Attention?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Classic ReLU FFN has 2 matrices (2 × D × 4D = 8D²). SwiGLU has 3 matrices (W_gate, W_up, W_down). Setting hidden width to (8/3)D keeps total parameters at 3 × D × (8/3)D = 8D² — identical parameter budget with significantly lower perplexity!

Interactive Visual Lab
Lab Challenge: Step through all 7 tensor stages in the Decoder-Only Transformer Block Animator below to trace exact shapes (B, T, D) → (B, H, T, d_k) → (B, T, D)!
Interactive Animation • 1.4 Deep Lab

Decoder-Only Transformer Block Tensor-Flow Animator

Trace a token batch (B, T, D) step-by-step through Pre-Norm RMSNorm, Causal Multi-Head Attention, Residual Add, and SwiGLU FFN.

Input Residual x
(B, T, D)
RMSNorm₁
(B, T, D)
Causal Multi-Head Attn
(B, H, T, d_k) → (B, T, D)
Residual Add₁ (+x)
(B, T, D)
RMSNorm₂
(B, T, D)
SwiGLU FFN (3× Proj)
(B, T, 8/3·D) → (B, T, D)
Residual Add₂ (+h)
(B, T, D)
0%
Stage 1/7: Input Residual x
Intuition Takeaway: Multi-Head Attention splits D into H specialist subspaces (d_k = D/H) at 4D² params, while Pre-Norm RMSNorm + SwiGLU (8D²) forms the exact 12D² building block of modern frontier LLMs.
Where This Powers Real ML, Deep Learning & Generative AI

LLaMA 3 / Gemma 2 / Mistral / DeepSeek

All stack Pre-Norm RMSNorm + Multi-Head/GQA Attention + SwiGLU blocks.

Encoder Rerankers & Embedding Models

ModernBERT & BGE use bidirectional Multi-Head Attention blocks for dense vector search.

Production NumPy & PyTorch Code Patterns
import torch
import torch.nn as nn
import torch.nn.functional as F

# Complete Modern Pre-Norm Decoder-Only Block (LLaMA / Gemma Style)
class ModernTransformerBlock(nn.Module):
    def __init__(self, d_model: int = 512, n_heads: int = 8):
        super().__init__()
        assert d_model % n_heads == 0
        self.n_heads, self.d_k = n_heads, d_model // n_heads
        self.norm1 = nn.RMSNorm(d_model)
        self.qkv = nn.Linear(d_model, 3 * d_model, bias=False)
        self.wo = nn.Linear(d_model, d_model, bias=False)

        self.norm2 = nn.RMSNorm(d_model)
        d_ff = int(8 * d_model / 3)
        self.w_gate = nn.Linear(d_model, d_ff, bias=False)
        self.w_up = nn.Linear(d_model, d_ff, bias=False)
        self.w_down = nn.Linear(d_ff, d_model, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        B, T, D = x.shape
        # 1. Pre-Norm Causal Multi-Head Attention
        q, k, v = self.qkv(self.norm1(x)).chunk(3, dim=-1)
        q = q.view(B, T, self.n_heads, self.d_k).transpose(1, 2)  # (B, H, T, d_k)
        k = k.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
        v = v.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
        attn = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        x = x + self.wo(attn.transpose(1, 2).reshape(B, T, D))

        # 2. Pre-Norm SwiGLU FFN
        h = self.norm2(x)
        x = x + self.w_down(F.silu(self.w_gate(h)) * self.w_up(h))
        return x
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Thinking 32 heads means 32× more parameters than 1 head.
Best Practice: Because d_k = D / H, total projection params remain 4D² regardless of H!
Trap #2: Calling .view(B, T, D) right after .transpose(1, 2) without .contiguous().
Best Practice: Use .transpose(1, 2).reshape(B, T, D) or .contiguous().view(...).
Chapter Mastery Check (+85 XP)
Score: 0 / 5
1If d_model = 512 and H = 8 heads, how many total weights are in W_Q, W_K, W_V, W_O combined (no bias)?
2Why did modern LLMs switch from Post-Norm to Pre-Norm (x + F(RMSNorm(x)))?
3Why does SwiGLU set intermediate width to (8/3)·D instead of 4·D?
4Which Transformer family is best suited for building a dense semantic text embedding model?
5In PyTorch Multi-Head Attention, what shape do Q, K, V have right before calling F.scaled_dot_product_attention?

Apply What You Learned — Solve Matching Coding Problems