Attention Is All You Need
The Transformer Architecture
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez,
8
Concepts
14
Formulas
7
Demos
Paper Overview
The Transformer architecture, introduced in "Attention Is All You Need" (2017), is the foundation of virtually all modern language models (GPT, BERT, LLaMA, etc.) and has since transformed computer vision (ViT), speech, and multimodal AI.
The core insight: self-attention can replace recurrence and convolutions entirely. Instead of processing tokens one-by-one (RNNs) or through local windows (CNNs), self-attention computes relationships between every pair of positions in a single operation — enabling full parallelization and O(1) path length between any two tokens.
The architecture follows an encoder-decoder design for sequence-to-sequence tasks (e.g., translation). Both encoder and decoder are stacks of identical layers, each containing multi-head self-attention, feed-forward networks, and residual connections with layer normalization. The decoder additionally has cross-attention to the encoder output and causal masking to prevent attending to future tokens.
Model configurations from the paper:
| Base | Big | |
|---|---|---|
| Layers (N) | 6 | 6 |
| d_model | 512 | 1024 |
| Heads (h) | 8 | 16 |
| d_k = d_v | 64 | 64 |
| d_ff | 2048 | 4096 |
| Parameters | 65M | 213M |
The base model achieved 27.3 BLEU on English-to-German translation (WMT 2014) and 41.0 BLEU on English-to-French — state-of-the-art at the time — while training in just 3.5 days on 8 GPUs, far faster than any competing model.
Chapter Roadmap
Click any topic to jump in
Self-Attention (Scaled Dot-Product Attention)
Scaled dot products with $\sqrt{d_k}$ normalization — constant path length between any two tokens.
Multi-Head Attention
$h$ parallel attention subspaces at $1/h$ cost each — a cheap ensemble where heads specialize.
Positional Encoding
Sinusoids at exponential wavelengths — any relative offset is a linear transform of absolute positions.
Encoder-Decoder Architecture
Cross-attention lets the decoder query any encoder position — no sequential bottleneck.
Feed-Forward Networks (FFN)
Position-wise 2-layer MLPs with 4× hidden dimension — key-value memories holding most of the parameters.
Residual Connections & Layer Normalization
Residuals provide a gradient highway; LayerNorm keeps activations stable across depth.
Causal Masking (Autoregressive Attention)
Upper-triangular $-\infty$ mask turns bidirectional attention into a parallelizable language model.
Training Strategy & Key Results
Warmup + Adam + shared dropout — 10× less compute than RNN seq2seq for better BLEU.
Concept by concept
8 sections, in reading order.
Self-attention is the core operation of the Transformer. It allows every token in a sequence to directly attend to every other token, computing context-aware representations in a single matrix operation.
The Problem
Previous sequence models had fundamental limitations in how they connected distant tokens:
- RNNs/LSTMs: Process tokens left-to-right sequentially. To connect token 1 to token 100, information must flow through 99 intermediate steps — causing vanishing gradients and making parallelization impossible. Training time grows linearly with sequence length.
- CNNs (ConvS2S): Use local receptive fields (e.g., kernel size 3). Connecting distant tokens requires O(n/k) layers of convolutions stacked on top of each other, where k is the kernel width. A 512-token sequence with kernel 5 needs ~100 layers.
- Both approaches create a bottleneck: the longer the sequence, the harder it is to learn long-range dependencies.
For the sentence "The cat that sat on the mat was hungry," connecting "cat" to "was hungry" (separated by 6 tokens) requires an RNN to propagate information through 6 timesteps. In a Transformer, this connection is direct — computed in a single attention step.
The Solution
Self-attention computes a weighted combination of all positions, where the weights are learned based on content similarity. Here's exactly how it works:
Step 1: Create Q, K, V matrices
Each input token has an embedding vector xi∈Rdmodel (e.g., 512-dimensional). We project this into three separate vectors using learned weight matrices:
- Query: Q=XWQ where WQ∈Rdmodel×dk (e.g., 512 × 64)
- Key: K=XWK where WK∈Rdmodel×dk (e.g., 512 × 64)
- Value: V=XWV where WV∈Rdmodel×dv (e.g., 512 × 64)
For a sequence of n tokens: X∈Rn×dmodel, Q,K∈Rn×dk, V∈Rn×dv
Step 2: Compute attention scores
scores=QKT∈Rn×n
Each entry scores[i][j] is the dot product between query i and key j, measuring how much token i should attend to token j. This produces an n×n matrix — every token compared to every other token.
Step 3: Scale
scaled_scores=dkQKT
Why scale? Without scaling, when dk is large (e.g., 64), dot products grow proportionally to dk (each is a sum of dk terms). Large dot products push softmax into regions with extremely small gradients (saturation), making learning near-impossible. Dividing by dk keeps the variance at ~1 regardless of dimension. The authors specifically tested this: without scaling, performance degraded significantly for large dk.
Step 4: Softmax → attention weights
α=softmax(scaled_scores)
Each row sums to 1, creating a probability distribution over which tokens to attend to. High scores become high weights; low scores become near-zero weights.
Step 5: Weighted sum of values
output=αV∈Rn×dv
Each output token is a weighted combination of all value vectors, where the weights are the attention probabilities. Token i's output is dominated by the value vectors of tokens it attends to most strongly.
Concrete example with n=4, dk=64:
- Input: 4 tokens, each 512-dim → X∈R4×512
- After projection: Q,K,V∈R4×64
- Scores: QKT∈R4×4 (16 pairwise similarities)
- After softmax: α∈R4×4 (each row sums to 1)
- Output: αV∈R4×64
The entire operation is a single matrix multiplication chain — fully parallelizable on GPUs.
Key Points
- 1
Every token attends to every other token in O(1) path length — no information bottleneck
- 2
Q, K, V are separate learned projections of the same input: Q = XW^Q, K = XW^K, V = XW^V. Queries ask "what am I looking for?", keys advertise "what do I contain?", values provide "what information do I give?"
- 3
Scaling by 1/dk is critical — without it, softmax saturates for large dk and gradients vanish. The paper empirically confirmed this degradation
- 4
Computational complexity is O(n2⋅d) — quadratic in sequence length. This is the main bottleneck for long sequences (addressed by later work like FlashAttention, Linformer, etc.)
- 5
Self-attention is permutation-equivariant: reordering inputs produces the same reordered outputs. This is why positional encodings are necessary
- 6
Unlike convolutions, attention has no inductive bias for locality — it must learn all spatial relationships from data, which requires more training data but is ultimately more flexible
Mathematical Formulation
Scaled Dot-Product Attention
Attention(Q,K,V)=softmax(dkQKT)V
Q ∈ ℝ^(n×d_k), K ∈ ℝ^(n×d_k), V ∈ ℝ^(n×d_v). The output is ℝ^(n×d_v). Each row of the output is a weighted average of V rows, where weights come from softmax of scaled dot products between Q and K rows.
Why Dot-Product (not Additive) Attention?
Additive: score(q,k)=vTtanh(W1q+W2k)vsDot-product: score(q,k)=q⋅k
Both have similar theoretical power, but dot-product attention is much faster in practice because it can be implemented with optimized matrix multiplication (BLAS). Additive attention requires a feed-forward network per pair.
Mathematical Intuition
Attn(Q,K,V)=softmax(QK⊤/dk)V. The division by dk prevents dot products from growing with dimension: for random q,k∈Rdk with unit variance, Var(q⋅k)=dk, so softmax would saturate without the scale. Complexity is O(N2d) — constant path length between any two tokens, unlike RNNs which need O(N) sequential steps.
Multi-head attention runs multiple self-attention operations in parallel on different learned projections of the input, allowing the model to jointly capture different types of relationships (syntactic, semantic, positional) simultaneously.
The Problem
A single attention head has a critical limitation: it produces a single set of attention weights per position. This means each token can only focus on one "aspect" of the input at a time.
Consider the sentence: "The animal didn't cross the street because it was too tired."
To understand this sentence, we need to resolve multiple relationships simultaneously:
- Coreference: "it" → "animal" (not "street") — requires semantic reasoning
- Syntax: "didn't" modifies "cross" — requires syntactic structure
- Proximity: "too tired" relates to "it" — requires positional awareness
- Negation scope: "didn't cross" — requires understanding modifier scope
A single attention head would be forced to compromise between these patterns, mixing syntactic and semantic signals into one weighted average. The result is a blurred, less useful representation.
Furthermore, with dk=dmodel=512, a single head's attention scores are computed from 512-dimensional dot products. This high dimensionality means that many unrelated features contribute to every attention decision, making it harder to learn focused patterns.
The Solution
Multi-Head Attention solves this by splitting the representation space into h independent subspaces, running attention in each, then recombining.
Dimension splitting — the key insight:
Instead of one attention with dk=512, use 8 heads each with dk=64:
dk=dv=dmodel/h=512/8=64
Step-by-step with concrete dimensions (base model):
1. Project into h subspaces: For each head i=1,...,8:
- Qi=XWiQ where WiQ∈R512×64
- Ki=XWiK where WiK∈R512×64
- Vi=XWiV where WiV∈R512×64
Each head has its own WiQ, WiK, WiV — 24 separate weight matrices total (8 heads × 3 matrices).
2. Compute attention independently: headi=Attention(Qi,Ki,Vi)∈Rn×64
Each head produces a 64-dimensional output per token.
3. Concatenate all heads: Concat(head1,...,head8)∈Rn×512
Stacking 8 heads of 64 dims = 512 dims = dmodel. No information is lost.
4. Final linear projection: MultiHead(Q,K,V)=Concat(...)WO where WO∈R512×512
WO mixes information across heads, allowing the model to learn combinations of the different attention patterns.
Computational cost:
Total parameters per multi-head attention layer:
- Projections: h×3×(dmodel×dk) = 8×3×(512×64) = 786,432
- Output: dmodel×dmodel = 512×512 = 262,144
- Total: ~1M parameters — same as a single-head with dk=dmodel
The magic: multi-head costs the same as single-head attention (since h×dk=dmodel), but captures richer patterns.
What different heads learn (empirically observed):
Research has shown that different heads tend to specialize:
- Positional heads: Attend to adjacent tokens (local context)
- Syntactic heads: Follow dependency parse structure (subject → verb)
- Rare token heads: Pay attention to infrequent/important words
- Separator heads: Attend to punctuation and sentence boundaries
- Coreference heads: Link pronouns to their referents
Key Points
- 1
Each head operates on a dk=dmodel/h dimensional subspace. Base model: 8 heads × 64 dims = 512. Big model: 16 heads × 64 dims = 1024
- 2
Total computation is identical to single-head attention: h heads × dk dimensions = dmodel dimensions
- 3
The output projection WO∈Rdmodel×dmodel is crucial — it lets the model learn to combine patterns across heads
- 4
Heads are not explicitly assigned roles — specialization emerges naturally from training. Head pruning research shows some heads can be removed with minimal impact
- 5
Multi-head attention is used in 3 places in the Transformer: (1) encoder self-attention, (2) decoder masked self-attention, (3) decoder cross-attention to encoder
Mathematical Formulation
Multi-Head Attention
MultiHead(Q,K,V)=Concat(head1,...,headh)WO
Each head_i = Attention(QW_i^Q, KW_i^K, VW_i^V). W_i^Q, W_i^K ∈ ℝ^(d_model × d_k), W_i^V ∈ ℝ^(d_model × d_v), W^O ∈ ℝ^(hd_v × d_model).
Parameter Count per Multi-Head Attention
Params=h(dmodel⋅dk+dmodel⋅dk+dmodel⋅dv)+(h⋅dv)⋅dmodel=4⋅dmodel2
For h=8, d_model=512, d_k=d_v=64: 3×8×(512×64) + 512×512 = 786,432 + 262,144 = 1,048,576 ≈ 1M parameters per attention layer.
Mathematical Intuition
Instead of one d-dim attention, run h attentions with d/h each: MHA=[head1;…;headh]WO. The parameter count stays the same (h⋅d/h⋅d/h=d2/h per projection), but each head can specialize — one learns syntax, another learns coreference, another positional adjacency. It's an ensemble with shared cost.
Self-attention is permutation-equivariant — it treats the input as a set, not a sequence. Positional encodings inject order information by adding position-dependent signals to token embeddings.
The Problem
Self-attention has no notion of position. Formally, if you permute the input sequence, the output is permuted in exactly the same way — the attention weights don't change.
This means:
- "The cat sat on the mat" and "mat the on sat cat The" would produce identical attention patterns (just reordered)
- The model cannot distinguish "dog bites man" from "man bites dog"
- Word order, which is fundamental to meaning in most languages, is completely invisible
Why this happens: The attention score qi⋅kj depends only on the content of tokens i and j, not their positions. Permuting the input just permutes which dot products are computed — the values remain the same.
This is by design (it makes attention flexible), but we need a mechanism to inject positional information without breaking the architecture.
The Solution
Sinusoidal Positional Encodings add fixed, position-dependent vectors to token embeddings:
inputi=embeddingi+PEi
where PE∈Rn×dmodel encodes each position as a unique vector.
The encoding formula:
- Even dimensions: PE(pos,2i)=sin(pos/100002i/dmodel)
- Odd dimensions: PE(pos,2i+1)=cos(pos/100002i/dmodel)
Understanding the frequencies:
Each pair of dimensions (2i,2i+1) forms a sinusoidal wave with a specific wavelength (period):
λi=2π⋅100002i/dmodel
- Dimension 0-1: wavelength = 2π≈6.28 positions (high frequency, changes every ~3 positions)
- Dimension 254-255: wavelength = 2π⋅10000254/512≈61,600 positions (very low frequency)
- This creates a spectrum from fine-grained to coarse-grained position signals
Why sinusoids enable relative position attention:
The key mathematical property: for any fixed offset k, PEpos+k can be expressed as a linear transformation of PEpos:
PEpos+k=Mk⋅PEpos
where Mk is a rotation matrix that depends only on the offset k, not on pos. This means the model can learn to attend to "3 positions to the right" through a simple linear function — regardless of absolute position.
Why not learned embeddings?
The paper tested learned positional embeddings and found nearly identical results to sinusoidal. However, sinusoidal has two advantages:
- Extrapolation: Can handle sequences longer than those seen in training (the waves continue naturally)
- No extra parameters: The positional encoding requires zero learned parameters
Modern alternatives:
- RoPE (Rotary Positional Embedding): Used in LLaMA, Mistral. Encodes relative position directly into the attention computation via rotation matrices, rather than adding to embeddings. Better for extrapolation.
- ALiBi (Attention with Linear Biases): Used in BLOOM. Adds a linear distance penalty to attention scores: closer tokens get higher scores.
- Learned absolute embeddings: Used in GPT-2, BERT. Simple but cannot extrapolate beyond training length.
Key Points
- 1
Added (element-wise sum, not concatenated) to input embeddings: input=Embed(x)+PE. Both are dmodel-dimensional
- 2
Wavelengths form a geometric progression from 2π to 10000⋅2π — lower dimensions encode fine position, higher dimensions encode coarse position
- 3
The sin/cos pair at each frequency creates a 2D rotation, giving each position a unique "angle" in that subspace. The model can learn to compute relative positions via dot products
- 4
Sinusoidal encodings are deterministic (not learned) — they use zero parameters. The paper showed learned embeddings gave similar results
- 5
Each position's encoding is a 512-dimensional vector — the model has rich positional information across multiple scales simultaneously
Mathematical Formulation
Sinusoidal Positional Encoding
PE(pos,2i)=sin(100002i/dmodelpos),PE(pos,2i+1)=cos(100002i/dmodelpos)
For d_model=512, this creates 256 sin/cos pairs with wavelengths from 2π ≈ 6.3 to 62,832 positions. Each position gets a unique 512-dim vector.
Relative Position via Linear Transform
PEpos+k=[cos(kωi)−sin(kωi)sin(kωi)cos(kωi)]PEpos
For each frequency ω_i, the offset k corresponds to a rotation by angle k·ω_i. The model can learn this linear relationship to attend to relative positions.
Mathematical Intuition
Sinusoidal encoding: PE(pos,2i)=sin(pos/100002i/d), PE(pos,2i+1)=cos(…). Different wavelengths mean different frequencies: low i encodes fine position, high i encodes coarse. Critically, PE(pos+k) can be written as a linear function of PE(pos), so the model can easily learn 'attend to the token 3 steps back'.
The Transformer follows an encoder-decoder structure where the encoder builds rich bidirectional representations of the input, and the decoder generates output tokens autoregressively while attending to the encoder's representations via cross-attention.
The Problem
Sequence-to-sequence tasks like translation require two fundamentally different capabilities:
-
Encoding (understanding): Process the full input sentence and build a representation that captures all relationships. The encoder can (and should) look at the entire input — knowing the last word helps understand the first word.
-
Decoding (generation): Produce output tokens one at a time, left-to-right. At step t, the decoder can only see tokens 1,...,t−1 (the tokens it has already generated). It must also access the encoder's representation of the input.
RNN seq2seq limitations:
- Encoder compresses the entire input into a single fixed-size vector (the final hidden state). For long sentences, this bottleneck loses information catastrophically.
- Bahdanau attention (2014) partially addressed this by letting the decoder attend to all encoder hidden states, but the encoder itself was still sequential.
- Training was inherently sequential: each timestep depends on the previous one, making GPU parallelization impossible.
The Solution
The Transformer architecture cleanly separates encoding and decoding into two stacks of layers, connected by cross-attention.
Complete data flow through the architecture (base model dimensions):
Input Processing:
- Tokenize input text → token IDs (vocabulary size ~37,000 for WMT English-German)
- Embed token IDs → Xembed∈Rn×512 via learned embedding matrix E∈RV×512
- Scale embeddings by dmodel (prevents positional encodings from dominating small embedding values)
- Add positional encoding: X0=dmodel⋅Xembed+PE∈Rn×512
- Apply dropout (p=0.1) to the sum
Encoder (6 identical layers):
Each encoder layer l applies two sub-layers:
Encoder Layer(X)=FFN(SelfAttn(X))
With residual connections and layer normalization around each:
- Zl=LayerNorm(Xl−1+MultiHeadSelfAttn(Xl−1))
- Self-attention: Q,K,V all come from the previous layer's output
- Bidirectional: every token attends to every other token (no masking)
- Xl=LayerNorm(Zl+FFN(Zl))
- Position-wise FFN: 512→2048→512
The output of the final encoder layer is EncoderOut∈Rn×512, which is passed to every decoder layer.
Decoder (6 identical layers):
Each decoder layer applies three sub-layers:
-
Masked Self-Attention: Q,K,V from previous decoder output
- Uses causal mask to prevent attending to future positions
- At training: processes all positions in parallel (teacher forcing)
- At inference: processes one new token at a time (autoregressive)
-
Cross-Attention: Q from decoder, K,V from encoder output
- This is how the decoder "reads" the input sequence
- The decoder queries the encoder: "given what I've generated so far, what part of the input is relevant for the next token?"
- K and V are the same encoder output for all decoder layers — computed once, reused 6 times
- Not masked: the decoder can attend to the entire input
-
Feed-Forward Network: Same structure as encoder (512 → 2048 → 512)
Output Processing:
- Final decoder output ∈Rm×512 (where m = output sequence length)
- Linear projection Wout∈R512×V maps to vocabulary logits
- Softmax → probability distribution over vocabulary
- The output embedding matrix Wout is shared with the input embedding matrix — this weight tying reduces parameters and improves performance
Training vs. Inference:
- Training: Both encoder and decoder process full sequences in parallel (teacher forcing — ground truth is fed as decoder input). The causal mask simulates autoregressive behavior.
- Inference: Encoder runs once. Decoder runs m times (one per output token), each time extending the output sequence by one token. Each step reuses cached K,V from previous steps (KV-cache).
Key Points
- 1
Encoder self-attention is bidirectional — every input token sees all other input tokens. Decoder self-attention is causal — each output token only sees previous output tokens
- 2
Cross-attention is the bridge: the decoder's queries come from its own hidden states, but the keys and values come from the encoder output. This lets each decoder position selectively "look at" the input
- 3
The encoder output (Rn×512) is computed once and reused by all 6 decoder layers. This is why the encoder can be run independently
- 4
Weight tying: The input embedding, output embedding, and pre-softmax linear all share the same weight matrix (RV×512), reducing parameters by ~37M
- 5
Embedding scaling: Embeddings are multiplied by dmodel before adding positional encodings. This is because embedding weights are typically initialized small (~0.01), while PE values range from -1 to 1
- 6
Modern decoder-only models (GPT, LLaMA) drop the encoder entirely — they use only causal self-attention, treating both input and output as a single sequence
Mathematical Intuition
Encoder stacks produce a context C∈RN×d. The decoder's cross-attention uses Q from decoder state and K,V from C: CrossAttn(Qdec,Kenc,Venc). This cleanly separates 'understanding the source' from 'generating the target' — the decoder can query any encoder position at any step, unlike RNN seq2seq which had to compress into a bottleneck.
Architecture
Three types of attention in the Transformer:
- Encoder self-attention: Q, K, V all from encoder. Bidirectional. Builds rich input representations.
- Decoder masked self-attention: Q, K, V all from decoder. Causal mask prevents future peeking. Models the output sequence structure.
- Encoder-decoder cross-attention: Q from decoder, K and V from encoder output. This is the only connection between encoder and decoder — it's how generated tokens access input information.
How these connect across layers:
- Encoder layer 1 processes raw embeddings → encoder layer 2 processes layer 1's output → ... → encoder layer 6 produces final representations
- Decoder layer 1 processes output embeddings (with mask) → then cross-attends to encoder layer 6's output → then FFN → decoder layer 2 takes this output → cross-attends to the same encoder output → ... → decoder layer 6 → linear → softmax
Each encoder and decoder layer maintains the same dimensionality: Rn×512 (encoder) and Rm×512 (decoder). The residual connections enforce this — you can't change the dimension within a residual block.
Comparison
Before / Traditional
RNN Seq2Seq (2014):
- Encoder: sequential (each step depends on prior)
- Bottleneck: full input compressed to one vector
- Attention: Bahdanau additive attention as add-on
- Path length: O(n) between distant tokens
- Training: cannot parallelize across positions
- Memory: hidden state grows linearly
After / This Paper
Transformer (2017):
- Encoder: fully parallel (all positions at once)
- No bottleneck: full attention to all positions
- Attention: core mechanism, not add-on
- Path length: O(1) between any two tokens
- Training: fully parallelizable
- Memory: O(n²) attention matrix (tradeoff)
Each Transformer layer includes a position-wise feed-forward network — two linear transformations with a non-linearity in between. The FFN processes each token independently and contains the majority of the model's parameters, acting as the Transformer's "memory bank."
The Problem
Self-attention computes context-aware representations by mixing information across positions, but it has a subtle limitation: the mixing is linear.
The attention output for each token is a weighted average of value vectors: outi=∑jαijvj. While the weights αij are non-linear functions of the input (through softmax), the combination itself is linear — it's just a weighted sum.
This means attention alone can only represent functions that are linear combinations of the input values. Complex per-token transformations — like detecting whether a token is a noun, computing whether a number is greater than a threshold, or mapping between representation spaces — require non-linear processing.
Additionally, attention has relatively few parameters per layer (~1M for base model). The model needs a larger parameter capacity to store the knowledge required for language understanding.
The Solution
Feed-Forward Network (FFN) adds non-linear, per-token processing capacity:
FFN(x)=ReLU(xW1+b1)W2+b2
Concrete dimensions (base model):
For each token independently (same weights, applied to each position):
- Expand: xW1+b1 where W1∈R512×2048, b1∈R2048 — projects from 512 to 2048 dimensions (4x expansion)
- Activate: ReLU (or GELU/SwiGLU in modern variants) — introduces non-linearity. After ReLU, approximately half the neurons are zeroed out, creating a sparse intermediate representation
- Contract: ⋅W2+b2 where W2∈R2048×512, b2∈R512 — projects back to 512 dimensions
Parameter count per FFN layer:
- W1: 512×2048 = 1,048,576
- b1: 2,048
- W2: 2048×512 = 1,048,576
- b2: 512
- Total: ~2.1M parameters per FFN layer
- Compare to attention: ~1M parameters per attention layer
- FFN contains ~2/3 of each layer's parameters
Across all 6 encoder + 6 decoder layers: 12×2.1M≈ 25M FFN parameters (of 65M total in the base model)
Why the 4x expansion?
The expansion creates a higher-dimensional intermediate space where the model can represent more complex features. Recent research ("Transformer Feed-Forward Layers Are Key-Value Memories", Geva et al. 2021) suggests that each row of W1 acts as a pattern detector (key) and the corresponding column of W2 stores the associated information (value). The FFN essentially functions as a learned lookup table — a compressed knowledge base.
Modern FFN variants:
- GELU (used in GPT, BERT): Smoother than ReLU, GELU(x)=x⋅Φ(x) where Φ is the Gaussian CDF
- SwiGLU (used in LLaMA, PaLM): SwiGLU(x)=(xW1⊙Swish(xWg))W2 — adds a gating mechanism with a third weight matrix Wg. Typically uses dff=38dmodel (instead of 4x) to keep parameter count comparable
- MoE (Mixture of Experts): Replaces single FFN with multiple "expert" FFNs + a router. Only 2-4 experts activate per token, enabling massive parameter count with fixed compute (used in Mixtral, Switch Transformer)
Key Points
- 1
Position-wise: The same FFN weights are applied to each token independently — no cross-token interaction in the FFN. Cross-token mixing happens only in attention
- 2
Parameter dominant: 2×dmodel×dff≈2.1M per layer vs ~1M for attention. FFN is where most knowledge is stored
- 3
The expand-contract bottleneck forces the model to learn compressed representations: 512 → 2048 → 512. The expanded space allows representing complex features; contracting back forces distillation
- 4
ReLU creates sparsity: ~50% of the 2048 intermediate neurons are zeroed out by ReLU for any given input, making the FFN behave like a sparse associative memory
- 5
Dropout (p=0.1) is applied after the activation (between the two linear layers) for regularization
Mathematical Formulation
Feed-Forward Network (Original)
FFN(x)=max(0,xW1+b1)W2+b2
W₁ ∈ ℝ^(512×2048), W₂ ∈ ℝ^(2048×512). Input and output are both d_model=512. The 4x expansion is a hyperparameter; the paper found this ratio worked best.
SwiGLU FFN (Modern Variant)
FFNSwiGLU(x)=(Swish(xWg)⊙xW1)W2
Used in LLaMA, PaLM. ⊙ is element-wise multiplication. W_g is an additional gating matrix. d_ff is typically (8/3)d_model to maintain parameter count.
Mathematical Intuition
FFN(x)=max(0,xW1+b1)W2+b2 with inner dimension 4d. Despite being applied position-wise, FFN holds ~2/3 of the Transformer's parameters. Recent work shows it behaves like a key-value memory: W1 detects patterns, W2 writes predictions — attention moves information between tokens, FFN processes it per-token.
Residual connections and layer normalization are the structural components that make it possible to train deep Transformers. Without them, stacking 6+ layers of attention and FFN would lead to vanishing gradients, unstable training, and non-convergence.
The Problem
The Transformer base model has 12 layers (6 encoder + 6 decoder), each containing attention and FFN sub-layers. Training such a deep network faces serious challenges:
Vanishing gradients: During backpropagation, gradients are multiplied by the Jacobian of each layer. If each layer's Jacobian has eigenvalues < 1, gradients shrink exponentially with depth: after L layers, gradients can be O(λL) where λ<1. For L=12 with λ=0.9: 0.912=0.28 — gradients reach the first layer at only 28% strength.
Exploding activations: Without normalization, the variance of activations can grow unbounded through layers. If each layer multiplies the variance by a factor c>1: after 12 layers, variance is c12 — potentially causing numerical overflow.
Internal covariate shift: Each layer's input distribution changes as parameters in previous layers update during training, forcing each layer to continuously re-adapt.
Loss landscape complexity: Deep networks without residual connections have highly non-convex loss landscapes with many saddle points, making optimization extremely difficult.
The Solution
Two complementary techniques solve these problems:
1. Residual (Skip) Connections:
xout=x+SubLayer(x)
Instead of learning the full mapping f(x), the network learns the residual Δx=f(x)−x. This is strictly easier — if the optimal transformation is close to identity, the network just needs to learn a small residual.
Why they fix gradient flow:
The gradient of the output w.r.t. the input is:
∂x∂xout=I+∂x∂SubLayer(x)
The identity matrix I guarantees that gradients flow directly from the loss to any layer. Even if the sub-layer's gradient vanishes, the skip connection preserves the signal. Through 12 layers, the gradient always has a direct path with no multiplicative decay.
2. Layer Normalization:
LayerNorm(x)=γ⊙σ2+ϵx−μ+β
For each token independently (across the dmodel=512 features):
- μ=dmodel1∑i=1dmodelxi (mean of the 512 features)
- σ2=dmodel1∑i=1dmodel(xi−μ)2 (variance)
- γ,β∈Rdmodel are learnable scale and shift (512 params each)
- ϵ=10−5 prevents division by zero
LayerNorm vs. BatchNorm:
- BatchNorm normalizes across the batch dimension (statistics over B examples for each feature) — depends on batch size, doesn't work well for variable-length sequences
- LayerNorm normalizes across the feature dimension (statistics over dmodel features for each token) — independent of batch size and sequence length
Parameters per LayerNorm: Just 2×dmodel=1024 (γ and β). There are 2 LayerNorms per layer × 12 layers = 24 LayerNorms total = 24,576 parameters — negligible compared to attention and FFN.
Pre-LN vs Post-LN placement:
The original paper used Post-LN: xout=LN(x+SubLayer(x))
Modern Transformers use Pre-LN: xout=x+SubLayer(LN(x))
Why Pre-LN is better:
- Post-LN: The residual path passes through LayerNorm, which can distort the gradient signal. Requires learning rate warmup (the paper used 4000 warmup steps). Without warmup, training diverges.
- Pre-LN: The residual path is clean (no normalization on the skip connection). Gradients flow unimpeded. Can often train without warmup. Used in GPT-2, GPT-3, LLaMA, and most modern Transformers.
Complete sub-layer pattern (Pre-LN): xout=x+Dropout(SubLayer(LayerNorm(x)))
Key Points
- 1
Residual connections ensure O(1) gradient path length — gradients from the loss reach the first layer without multiplicative decay, regardless of model depth
- 2
LayerNorm normalizes per-token across features — computes mean and variance over the 512 dimensions of each token independently. This makes it invariant to batch size and sequence length
- 3
Pre-LN (modern standard) keeps the residual path clean: no normalization on the skip connection. Post-LN (original paper) normalizes the residual sum, which can hurt gradient flow and requires warmup
- 4
Each Transformer layer has 2 residual connections: one around attention, one around FFN. Each residual connection has its own LayerNorm (2 LayerNorms per layer)
- 5
Dropout (p=0.1) is applied to the sub-layer output before adding the residual. This regularizes the learned transformation while keeping the skip connection clean
Mathematical Formulation
Post-LN (Original Paper)
xout=LayerNorm(x+SubLayer(x))
Used in the original Transformer. Requires careful learning rate warmup. The LayerNorm is applied to the sum of the residual and sub-layer output.
Pre-LN (Modern Standard)
xout=x+SubLayer(LayerNorm(x))
Used in GPT-2/3, LLaMA, etc. The clean residual path provides better gradient flow. An additional final LayerNorm is applied after the last layer.
Layer Normalization
LN(x)=γ⊙σ2+ϵx−μ+β
μ, σ² computed per-token across d_model features. γ, β ∈ ℝ^(d_model) are learnable. Only 2×512 = 1024 parameters per LayerNorm.
Mathematical Intuition
Each sublayer computes x+Sublayer(LN(x)) (pre-LN) or LN(x+Sublayer(x)) (post-LN). Residuals ensure ∂xl∂L always has a +1 term, preventing gradient vanishing over dozens of layers. LayerNorm normalizes across the feature dim, making training invariant to input scale — critical since attention outputs vary wildly.
Causal masking prevents the decoder from attending to future tokens, enforcing the autoregressive property: each output token is generated based only on previously generated tokens and the encoder's representation of the input.
The Problem
During generation, we face a fundamental causality constraint:
At time step t, the decoder is generating token t. Tokens t+1,t+2,... don't exist yet — they haven't been generated. Standard self-attention would attend to all positions, including these non-existent future positions.
During training, the situation is even more subtle. We use teacher forcing: the decoder receives the ground-truth output sequence as input. All output tokens are available simultaneously, so the decoder could trivially "cheat" by looking at the next token and copying it.
Without masking, the model would learn to copy rather than predict, and would be useless at inference time (when future tokens are truly unavailable).
The problem is that we want the parallelism benefits of processing all positions simultaneously (unlike RNNs), but we also need the causal property of never looking ahead.
The Solution
Causal Masking applies a lower-triangular mask to the attention scores before softmax, setting future positions to −∞:
MaskedAttention(Q,K,V)=softmax(dkQKT+M)V
where Mij=0 if j≤i (can attend), Mij=−∞ if j>i (blocked).
Step-by-step with a 5-token sequence:
M=00000−∞0000−∞−∞000−∞−∞−∞00−∞−∞−∞−∞0
Why −∞ works:
- softmax(−∞)=∑e⋅e−∞=∑e⋅0=0
- The masked positions get exactly zero attention weight
- The remaining weights are renormalized to sum to 1
- Gradients through masked positions are also zero — the model cannot learn to use future information
Effective attention pattern:
Token 1 attends to: [1] (only itself)
Token 2 attends to: [1, 2] (itself + one prior)
Token 3 attends to: [1, 2, 3] (itself + two prior)
Token 4 attends to: [1, 2, 3, 4] (itself + three prior)
Token 5 attends to: [1, 2, 3, 4, 5] (all tokens)
Where masking is used (and not used):
| Component | Masked? | Why |
|---|---|---|
| Encoder self-attention | No | Input is fully available; bidirectional helps |
| Decoder self-attention | Yes | Must not see future outputs |
| Cross-attention (dec→enc) | No | Decoder can see the entire input |
KV-Cache optimization at inference:
During autoregressive generation, the decoder processes one new token at a time. Recomputing attention over all previous tokens at every step would be O(n2) per token. The KV-cache stores previously computed keys and values, so only the new token's Q,K,V need to be computed:
- Step t: compute Qt,Kt,Vt for the new token
- Append Kt to cached keys, Vt to cached values
- Attend Qt to all cached K values → O(n) per step instead of O(n2)
This reduces total generation complexity from O(n3) to O(n2).
Key Points
- 1
The mask is a lower-triangular matrix added to attention scores before softmax. Mij=0 for j≤i, Mij=−∞ for j>i
- 2
Only used in decoder self-attention — encoder self-attention is bidirectional, cross-attention is unmasked (decoder should see all of the input)
- 3
During training, masking enables parallel processing: all output positions are computed simultaneously, with each position seeing only its predecessors via the mask. This gives the parallelism of attention with the causality of autoregressive generation
- 4
During inference, the KV-cache stores past keys and values, so each new token only computes a single row of the attention matrix. This reduces per-token cost from O(n⋅d) to O(d) for the new token
- 5
Decoder-only models (GPT, LLaMA) use causal masking as their only attention type — the "input" and "output" are treated as a single causally-masked sequence. There is no separate encoder or cross-attention
Mathematical Formulation
Masked Scaled Dot-Product Attention
Attention(Q,K,V)=softmax(dkQKT+M)V
M is the mask matrix. M[i][j] = 0 if j ≤ i (allow), -∞ if j > i (block). The -∞ values become 0 after softmax, completely blocking information flow from future positions.
Mathematical Intuition
To prevent looking ahead, apply mask Mij=−∞ if j>i, else 0, before softmax: softmax(QK⊤/dk+M). The −∞ becomes 0 after softmax, so future tokens contribute nothing. This single change turns bidirectional self-attention into a language model that can be trained in parallel — at step t, all positions ≤t compute simultaneously.
The paper's training recipe — including the learning rate schedule, regularization choices, and label smoothing — was as influential as the architecture itself. These details are critical for reproducing the results and understanding why the Transformer trains well.
The Problem
Training a deep attention-based model from scratch presented several open questions in 2017:
- Learning rate: Too high → divergence. Too low → slow convergence. The model is sensitive to LR especially in early training, before LayerNorm statistics stabilize.
- Regularization: With 65M parameters and training sets of ~4.5M sentence pairs, overfitting is a real risk. How much dropout, where to apply it?
- Label smoothing: Standard cross-entropy training encourages the model to be "overconfident" — predicting one token with probability ~1.0 and all others ~0.0. This hurts generalization.
- Optimizer: Adam was standard, but the Transformer required specific hyperparameter choices to train well.
The Solution
Learning Rate Schedule (Warmup + Inverse Square Root Decay):
lr=dmodel−0.5⋅min(step−0.5,step⋅warmup−1.5)
This schedule has two phases:
- Linear warmup (first 4000 steps): LR increases linearly from 0 to peak. This is critical for Post-LN Transformers — without it, early gradients through LayerNorm are too large and training diverges. Peak LR at step 4000: 512−0.5⋅4000−0.5≈0.0014
- Inverse square root decay (after 4000 steps): LR decreases proportionally to 1/step. This is gentler than cosine or step decay, giving the model a long, slow annealing phase.
Optimizer:
- Adam with β1=0.9, β2=0.98, ϵ=10−9
- The unusually high β2=0.98 (vs typical 0.999) makes the second moment estimate adapt faster, which works well with the warmup schedule
Regularization (three types):
-
Residual Dropout (p=0.1): Applied to:
- The output of each sub-layer (attention, FFN) before adding to the residual
- The sum of embeddings + positional encodings
- Total: applied at every sub-layer in every layer
-
Attention Dropout (p=0.1): Applied to the attention weights (after softmax). This randomly drops attention connections, forcing the model to build redundant attention patterns.
-
Label Smoothing (ϵls=0.1): Instead of training with one-hot targets [0,0,1,0,...], uses smoothed targets: [ϵ/V,ϵ/V,1−ϵ,ϵ/V,...] where V is vocabulary size. This:
- Hurts perplexity (the model is less confident, so perplexity increases by ~0.5)
- Improves BLEU and translation quality — the model learns that multiple tokens can be reasonable next predictions, leading to better beam search diversity
Training Setup:
- Hardware: 8 NVIDIA P100 GPUs
- Training time: Base model 12 hours (100K steps), Big model 3.5 days (300K steps)
- Batch size: ~25,000 source + target tokens per batch (sentences batched by approximate length)
- Gradient accumulation used to achieve effective large batch sizes
Key Results (WMT 2014):
| Model | EN-DE BLEU | EN-FR BLEU | Training Cost |
|---|---|---|---|
| Previous SOTA (ensemble) | 26.4 | 41.0 | — |
| Transformer Base | 27.3 | 38.1 | 12 hours × 8 GPUs |
| Transformer Big | 28.4 | 41.0 | 3.5 days × 8 GPUs |
| Transformer Big (ensemble) | — | 41.8 | — |
The Transformer Big achieved SOTA on both benchmarks as a single model, while training in a fraction of the time of competing approaches (some required weeks of training).
Ablation insights from the paper:
- Reducing dk without compensating heads hurts quality (total attention dimension matters)
- Bigger models don't always help — quality saturates around 6 layers for this dataset
- Learned positional embeddings perform nearly identically to sinusoidal
- Replacing attention with average pooling or convolutions significantly degrades performance — attention is genuinely necessary
Key Points
- 1
Warmup is essential for Post-LN: The learning rate must increase linearly for ~4000 steps before decaying. Without warmup, training diverges immediately due to unstable LayerNorm gradients. Pre-LN models are more forgiving
- 2
Label smoothing (ϵ=0.1) trades perplexity for BLEU: The model becomes less confident but more accurate in practice. This insight has been adopted widely — most modern LLMs use some form of label smoothing
- 3
Three separate dropout mechanisms prevent overfitting: residual dropout (sub-layer outputs), attention dropout (attention weights), and embedding dropout (input representations). All use p=0.1
- 4
Training efficiency was revolutionary: The base Transformer trained in 12 hours on 8 GPUs while exceeding models that took weeks. This directly enabled the scaling experiments that led to GPT, BERT, and modern LLMs
- 5
The paper's ablations proved attention is necessary: Replacing attention with fixed averages or convolutions degraded quality significantly. The attention mechanism itself, not just the architecture, is the key innovation
Mathematical Formulation
Learning Rate Schedule
lr=dmodel−0.5⋅min(step_num−0.5,step_num⋅warmup_steps−1.5)
Linear warmup for the first 4000 steps, then inverse square root decay. Peak LR ≈ 0.0014 for d_model=512. The d_model^(-0.5) scaling ties the LR to model size.
Label Smoothing
q(k)=(1−ϵ)⋅1[k=y]+Vϵ
With ε=0.1 and V=37000: correct token gets probability 0.9, each wrong token gets 0.1/37000 ≈ 0.0000027. Prevents overconfident predictions and improves beam search diversity.
Mathematical Intuition
Transformer uses Adam with warmup: lr=d−0.5⋅min(step−0.5,step⋅warmup−1.5). The warmup is critical because early attention is near-uniform and gradients are noisy. Achieves 28.4 BLEU on EN-DE (new SOTA) with 10× less compute than prior RNN-based models — training in ∼3.5 days on 8 GPUs instead of weeks.
Keep reading
Related Papers
Go deeper