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.
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.
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.
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!
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!
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.
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!'
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)?
- 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
d_k = D / H)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
Click Head 1 / Head 2 / Head 3 below to see how different heads learn completely different linguistic roles simultaneously!
The Exact 4-Step Multi-Head Tensor Dance
- Project: → each shape .
- Split Heads:
.view(B, T, H, d_k).transpose(1, 2)→ shape . - Parallel Attention: Batched matmul computes all heads simultaneously → .
- Concat & Mix:
.transpose(1, 2).contiguous().view(B, T, D)then multiply by → !
Multi-Head Specialization Switcher
Links pronouns back to the semantic subject across long clauses.
2. The Modern Decoder-Only Block: Pre-Norm RMSNorm + SwiGLU FFN
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 LLaMA / Gemma Block Equations
where .
Quick Parameter Rule of Thumb: ~12 · D² per Layer!
- Attention (
W_Q, W_K, W_V, W_O): parameters. - FFN (2 matrices of or 3 SwiGLU matrices of ): parameters (2/3 of the entire LLM!).
- Total per layer: (e.g., 32 layers at + embeddings !).
Params_layer ≈ 4D² (Attention) + 8D² (FFN) = 12D²
W_Q, W_K, W_V, and W_O — handles cross-token communication.
12 × L × D² + 2 × V × D in 5 seconds!3. Encoder-Only vs. Decoder-Only vs. Encoder–Decoder Families
Why did Decoder-only models (GPT, LLaMA, Claude, Gemini) win general AI, while Encoder-only models (BERT, BGE) still dominate RAG embedding search?
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.
Worked Example: Checking Tensor Shapes Inside Multi-Head Attention
Input x has shape (B=2, T=16, D=512) with H=8 heads.
.
In a standard dense Transformer block, roughly what fraction of the layer's parameters live in the FFN (MLP/SwiGLU) vs. Attention?
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?
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!
(B, T, D) → (B, H, T, d_k) → (B, T, D)!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.
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.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.
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
d_k = D / H, total projection params remain 4D² regardless of H!.view(B, T, D) right after .transpose(1, 2) without .contiguous()..transpose(1, 2).reshape(B, T, D) or .contiguous().view(...).d_model = 512 and H = 8 heads, how many total weights are in W_Q, W_K, W_V, W_O combined (no bias)?x + F(RMSNorm(x)))?(8/3)·D instead of 4·D?Q, K, V have right before calling F.scaled_dot_product_attention?