Transformer Architecture
The architecture that revolutionized AI: understanding how transformers combine attention, feed-forward networks, and residual connections to achieve state-of-the-art performance across virtually every AI domain.
Learning Objectives
- Understand the complete transformer architecture
- Explain the role of each component: attention, FFN, normalization, residuals
- Distinguish encoder-only, decoder-only, and encoder-decoder architectures
- Understand positional encoding and why it's necessary
- Connect transformers to specific applications (BERT, GPT, etc.)
"Attention Is All You Need"
The transformer, introduced by Vaswani et al. in "Attention Is All You Need," replaced recurrent and convolutional layers entirely with attention mechanisms. This enabled massive parallelization and unprecedented scale.
RNNs process sequences step-by-step—slow and prone to forgetting. CNNs have fixed receptive fields. Transformers let every position attend to every other position directly, in parallel.
This direct global connectivity, combined with massive parallelization on GPUs, enabled training on internet-scale data—giving us GPT, BERT, and the current AI revolution.
Every architecture embeds an inductive bias—assumptions about data structure that guide learning:
- CNNs: Assume spatial locality (nearby pixels are related) and translation invariance (a cat is a cat anywhere in the image).
- RNNs: Assume sequential dependence (earlier tokens causally affect later ones) and recency (recent tokens matter most).
- Transformers: Make minimal assumptions—every position can attend to every other. The model learns which positions matter.
This weaker inductive bias requires more data but enables greater flexibility. Given internet-scale training, transformers learn the "right" biases from data rather than having them hard-coded.
The transformer stacks self-attention and feed-forward layers, using residual connections and layer normalization for stable training. The architecture is remarkably simple—mostly attention and MLPs—yet scales to billions of parameters.
Transformer Block: The Building Block
A transformer is a stack of identical blocks. Each block has two main components: multi-head self-attention and a position-wise feed-forward network, each wrapped in residual connections and layer normalization.
🎯 Data Flow: Follow One Token Through
Let's trace the word "cat" through a transformer block:
- "cat" enters as a 768-dimensional vector (its embedding)
- Attention: "cat" looks at ALL other tokens → "What's relevant to me?" → Gets updated with context
- Add & Normalize: Add original "cat" back (residual) + normalize values
- Feed-Forward: "cat" gets transformed alone (no mixing with others) → Expand → Contract
- Add & Normalize: Add previous version back + normalize
- "cat" exits as a richer 768-dimensional vector, now carrying context from the sentence
Key insight: Attention = "mix information between tokens" • FFN = "process each token individually"
Multi-Head Self-Attention
Each position attends to all positions. Multiple heads capture different relationship types. This is where global context mixing happens.
Feed-Forward Network (FFN)
Applied independently to each position. Typically expands dimension 4× then projects back. This is where per-position computation happens.
Layer Normalization
Normalizes activations across features (not batch). Stabilizes training and enables higher learning rates.
Residual Connections
Adds input directly to output of each sub-layer. Enables gradient flow through very deep networks (50+ layers).
Positional Encoding
The Position Problem
Self-attention treats input as a set—it has no notion of order. "The cat sat" and "sat cat the" produce identical attention patterns. We must explicitly inject position information.
Sinusoidal Positional Encoding
The original transformer uses sine and cosine functions of different frequencies:
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))
Each dimension has a different frequency, creating a unique "fingerprint" for each position. The sinusoidal form allows the model to learn relative positions through simple linear combinations.
Learned Positional Embeddings
Modern models (GPT, BERT) often learn position embeddings directly—a matrix of shape (max_seq_len, d_model) trained with the rest of the network.
Trade-off: Learned embeddings can capture position patterns specific to the training data but don't extrapolate to longer sequences.
Architecture Variants
Encoder-Only
Bidirectional attention: Each token attends to all tokens in both directions. Best for understanding tasks (classification, NER, question answering).
Training: Masked language modeling—predict masked tokens from context.
Decoder-Only
Causal attention: Each token attends only to previous tokens (left-to-right). Best for generation tasks.
Training: Next-token prediction—predict each token from all previous tokens.
Encoder-Decoder
Cross-attention: Decoder attends to encoder outputs. Best for sequence-to-sequence tasks (translation, summarization).
The Causal Mask
In decoder models, we prevent positions from attending to future tokens using a causal mask—ensuring the model can only "see" the past when predicting the next token.
Causal mask: ✓ = can attend, ✗ = masked (set to -∞ before softmax)
Common Misconceptions
"Transformers understand language like humans"
Transformers are pattern-matching machines optimized to predict tokens. They have no grounded understanding of meaning, only statistical correlations learned from text.
The accurate framing: Transformers capture useful patterns that often align with semantic meaning, but this emerges from prediction objectives, not understanding.
"More layers always means better performance"
Beyond a certain depth, adding layers provides diminishing returns and increases training instability. The optimal depth depends on task and data.
The accurate framing: Modern scaling laws suggest balancing depth, width, and data. Very deep models need careful initialization and may still underperform wider, shallower alternatives.
Interactive Lab: Transformer Explorer
Explore the transformer architecture interactively. See how data flows through layers and understand the role of each component.
Visualization of sinusoidal positional encodings. Each row is a position, each column is a dimension. Notice the different frequencies across dimensions.
Understanding tensor shapes is crucial for implementing transformers. Follow the data through each operation with concrete dimensions.
Here's how to implement a transformer from scratch in PyTorch. This is production-quality code used as a foundation for real LLMs.
Key Observations
- Residual connections create "highways" for gradients, enabling deep networks.
- Layer norm appears after each sub-layer, stabilizing training.
- FFN expands and contracts: d_model → 4×d_model → d_model.
Check Your Understanding
Why do transformers need positional encoding?
What is the purpose of the feed-forward network in each transformer block?
How does GPT differ from BERT architecturally?
Why are residual connections important in transformers?
What does the causal mask do in GPT-style models?
Multi-Head Attention
Transformer Block
Full GPT-style Model