FullStack AI Hub
Studio
AI & LLM Systems · 01. Transformer Architecture
11 min
6 steps
Intermediate

Multi-Head Blocks, Residual Stream & SwiGLU

Inspect parallel attention head specialization, Pre-RMSNorm residual highways, and SwiGLU gated feed-forward layers.

AI & LLM Systems01. Transformer ArchitectureLesson 3 of 4
11 minIntermediate6 steps

Multi-Head Blocks, Residual Stream & SwiGLU

Inspect parallel attention head specialization, Pre-RMSNorm residual highways, and SwiGLU gated feed-forward layers.

ACTIVE HEAD
4 Heads Concat
NORM PATH
Pre-RMSNorm
FFN GATE
SwiGLU (8/3d)
GRAD VARIANCE
1.04×
Multi-Head · Residual Stream · SwiGLU Lab
1. Parallel Multi-Head Attention Subspaces (Click Head to Focus)
2. Residual Stream & Norm Path
x_in
x_out
RMSNorm(x) → Multi-Head Attention → + Δ_attn
RMSNorm(h) → SwiGLU FFN → + Δ_ffn
32-Layer Gradient Path:Stable (Direct Highway)
3. FFN Expansion & Gating
ch0 · subject
1.72
ch1 · tense
-0.26
ch2 · fact
2.92
ch3 · syntax
-0.31
ch4 · noise
0.16
ch5 · entity
2.32
ch6 · scope
-0.14
ch7 · idiom
0.94
d_model 4096 → d_ff 10,9230% gated off
In This LessonStep 1 of 6
What You Will Master
  • ✓Explain why splitting d_model into H parallel heads lets a single layer track syntax, coreference, and locality simultaneously
  • ✓Trace how the residual stream (+) acts as a shared memory bus and unbroken gradient highway across 32–128 layers
  • ✓Contrast modern Pre-RMSNorm stability and speed against classic 2017 Post-LayerNorm
  • ✓Understand how SwiGLU gated FFNs store factual associations more efficiently than classic ReLU MLPs

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Multi-Head Attention (MHA)Learning diverse parallel relationships (coreference, syntax, local bigrams) at onceSplits d_model into H heads of size d_k = d_model / H so total FLOPs stay constant
Residual Stream (+)Training deep 32–128 layer networks without vanishing gradientsEvery attention and FFN sublayer writes additive deltas (x + Δ) onto one shared bus
Pre-RMSNorm (Modern)Stable large-scale LLM pretraining without fragile learning-rate warmupDrops mean-centering subtraction (faster GPU kernel than LayerNorm) and keeps residual trunk untouched
SwiGLU FFN (8/3 d_model)Modern frontier LLMs (PaLM, Llama, Gemma, Mistral) needing higher quality per FLOPUses 3 weight matrices (W_gate, W_up, W_down) at 8/3 hidden width to match 4× ReLU parameter count

Step-by-Step Architectural Breakdown (6 Steps)

Full architectural walkthrough transcript and state transitions for Multi-Head Blocks, Residual Stream & SwiGLU.

STEP 01 · SETUPJump to step →

Why One Attention Head Isn’t Enough: Parallel Subspaces

At any token position, a language model needs to track multiple things simultaneously: **who** a pronoun refers to, **what** the preceding word was, and **which** verb governs the clause. One softmax distribution averages these conflicting signals into mush.

**Multi-Head Attention** slices $d_{\text{model}}$ into $H$ independent subspaces (e.g., 32 heads × 128 dims). Each head learns its own $W_Q, W_K, W_V$ projections in parallel, then concatenates all heads through $W_O$. Click the 4 head cards on the stage to see each head focus on a different token for the exact same word!

idea:Splitting 4,096 dims into 32 heads of 128 dims costs virtually the exact same FLOPs as one giant 4,096-dim head—yet unlocks 32 simultaneous reasoning patterns.

Multi-Head AttentionSubspace SpecializationOutput Projection W_O
STEP 02 · TECHNIQUEJump to step →

The Residual Stream: A Shared Information Highway

A common misconception is that Transformer layers overwrite token vectors one after another. Instead, every block sits off to the side of a continuous **Residual Stream** (`x_out = x_in + Sublayer(x_in)`).

Think of the residual stream as a **shared memory bus**: early heads write syntactic tags into unused subspaces, middle FFN layers read those tags and write factual knowledge, and the final unembedding head reads out the predicted next token.

good:Because addition has derivative 1, backpropagation flows straight from layer 96 back to layer 1 along the green residual highway without shrinking exponentially.

Residual StreamSkip ConnectionsGradient Highway
STEP 03 · PROBLEMJump to step →

Post-LayerNorm (2017) vs. Pre-RMSNorm (Modern LLMs)

The original 2017 Transformer placed **LayerNorm after the residual addition**: `LayerNorm(x + Sublayer(x))`. Putting normalization directly *on* the residual trunk distorts gradients across deep stacks—making 64+ layer models unstable without delicate learning-rate warmup.

Modern LLMs move normalization *inside* each branch (**Pre-Norm**) and swap LayerNorm for **RMSNorm**, which drops mean-centering and only divides by root-mean-square magnitude—giving identical accuracy with ~15% faster GPU normalization kernels.

watch:Toggle Post-LN (2017) below to see gradient variance jump from 1.04× to 3.85× when normalization sits directly on the residual trunk.

Pre-RMSNormPost-LayerNormTraining Stability
STEP 04 · TECHNIQUEJump to step →

The Feed-Forward Network: Where World Knowledge Lives

While Self-Attention routes information *between* tokens, the **Feed-Forward Network (FFN)** operates on each token independently—and holds roughly **two-thirds of all parameters** in a Transformer!

Mechanistic interpretability shows FFNs behave like giant **key-value neural memories**: the up-projection detects patterns (e.g., *"Eiffel Tower is located in"*), and the down-projection injects the factual answer (*"Paris"*) back onto the residual stream.

idea:Attention moves information across positions; the FFN thinks and recalls facts at each position.

Feed-Forward NetworkKey-Value MemoryParameter Budget
STEP 05 · SOLUTIONJump to step →

SwiGLU & Mixture-of-Experts (MoE) Scaling

**SwiGLU** replaces the 2-matrix ReLU MLP with a 3-matrix gated projection: `(SiLU(x W_gate) ⊙ x W_up) W_down`. To keep total parameter count identical to a `4 × d_model` ReLU block, modern LLMs shrink hidden width from `4d` to **`8/3 d`** (`10,923` for `d=4096`).

Notice on the right-hand neuron chart how many FFN channels are gated near zero per token. **Sparse Mixture-of-Experts (MoE)** models (Mixtral, DeepSeek) exploit this exact sparsity—routing each token to only the top 2 of 8+ SwiGLU FFN experts for massive capacity at constant FLOPs!

good:MoE scales the FFN parameter bank 4–8× while keeping per-token inference compute nearly flat—because attention stays shared and only 2 experts fire per token.

SwiGLUSiLU ActivationMixture of Experts
STEP 06 · RECAPJump to step →

Recap: One Modern Transformer Block, Repeated N Times

A frontier LLM is simply this single block—**Pre-RMSNorm → Multi-Head Attention → Residual `+` → Pre-RMSNorm → SwiGLU FFN → Residual `+`**—stacked 32 to 128 layers deep.

In our final Transformer lesson, we zoom out to compare **Classic Encoder-Decoder Cross-Attention** against **Modern Decoder-Only GQA stacks**, and watch the final hidden vector decode into **live next-token probabilities**.

good:Open the Math Inspector to inspect both the residual equations and exact [1, T, 4096] → [1, T, 10923] → [1, T, 4096] tensor shapes.

Transformer BlockLayer Stacking

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.