Prerequisites
Before diving into Transformers, you should be comfortable with:
- Neural Network Fundamentals: Forward/backward pass, activation functions, backpropagation (see Tutorial 21)
- RNNs and LSTMs: Sequential processing, vanishing gradients, attention motivation (see Tutorial 23)
- Linear Algebra: Matrix multiplication, softmax, dot-product similarity
- PyTorch: nn.Module, batch processing, mask operations
- NLP Basics: Tokenization, embeddings, sequence-to-sequence tasks
Deep Learning
Transformers — The Architecture That Changed Everything
Master the Transformer architecture that powers GPT, BERT, and all modern language models.
- Self-attention mechanism — process all tokens simultaneously
- Parallel processing — much faster than sequential RNNs
- Foundation of LLMs — powers ChatGPT, Claude, and more
Attention is all you need.
Learning Objectives
By the end of this tutorial, you will be able to:
- Implement scaled dot-product self-attention from scratch
- Explain why multi-head attention captures different relationship types
- Compare sinusoidal, learned, and rotary positional encodings
- Differentiate encoder (BERT) vs decoder (GPT) architectures
- Understand the quadratic complexity bottleneck and its solutions
- Build a Transformer block in PyTorch with proper masking
- Explain why Transformers replaced RNNs for most NLP tasks
Transformers — Attention Is All You Need
Transformers (Vaswani et al., 2017) replaced RNNs as the dominant architecture for sequence processing. They achieve sequential operations (vs for RNNs), enabling massive parallelism on GPUs.
Self-Attention
The core mechanism: each token attends to every other token to compute a weighted representation.
Multi-Head Attention
Multiple attention heads capture different types of relationships simultaneously:
where
Positional Encoding
Since self-attention is permutation-invariant, we must inject position information:
Transformer Block
Encoder vs Decoder
- Encoder (BERT): Bidirectional self-attention — every token attends to every other token. Good for understanding tasks (classification, NER, QA).
- Decoder (GPT): Masked self-attention — each token attends only to previous tokens. Good for text generation, completion.
PyTorch Implementation
Real-World Applications
1. Large Language Models (LLMs) GPT-4, Claude, LLaMA, and Gemini are all Transformer-based. GPT-4 reportedly uses ~96 Transformer layers with trillions of parameters, powering ChatGPT's conversational abilities.
2. Machine Translation Transformer-based models (mBART, NLLB) translate between 200+ languages. They handle long-range dependencies that RNNs miss, achieving state-of-the-art BLEU scores.
3. Code Generation GitHub Copilot, Codex, and Code Llama use decoder Transformers trained on code repositories. They understand programming context and generate functional code from natural language descriptions.
4. Vision Transformers (ViT) ViT splits images into patches and processes them as token sequences. When pre-trained on large datasets, ViT matches or exceeds CNN performance on ImageNet and other vision benchmarks.
5. Scientific Discovery AlphaFold2 uses Transformers to predict protein 3D structures from amino acid sequences, solving a 50-year grand challenge in biology. The same architecture is being applied to drug discovery and materials science.
6. Multi-Modal AI GPT-4V, Gemini, and LLaVA process text and images together. CLIP aligns text and image embeddings for zero-shot classification. These models understand content across modalities using cross-attention.
Common Mistakes & How to Avoid Them
Key Formulas Reference
| Formula | Expression | Use Case |
|---|---|---|
| Self-Attention | softmax(QK^T / sqrt(d_k)) V | Core mechanism |
| Multi-Head | Concat(head_1,...,head_h) W_O | Multiple relationship types |
| FFN | W_2 * GELU(W_1 x + b_1) + b_2 | Position-wise processing |
| Sinusoidal PE | sin(pos / 10000^{2i/d}) | Position information |
| Attention Complexity | O(n^2 * d) per layer | Compute budget |
| Causal Mask | mask[i,j] = 0 if j <= i else -inf | Autoregressive generation |
Interview Questions
Practice Exercise
import torch
import torch.nn as nn
import math
# Task 1: Implement scaled dot-product attention
def scaled_dot_product_attention(Q, K, V, mask=None):
# Compute attention scores
# Apply mask if provided
# Apply softmax and scale
# Return weighted sum of values
pass
# Task 2: Implement multi-head attention
class MultiHeadAttention(nn.Module):
def __init__(self, d_model=512, n_heads=8):
super().__init__()
# Create Q, K, V projection layers
# Create output projection layer
pass
def forward(self, Q, K, V, mask=None):
# Split into heads
# Apply attention per head
# Concatenate and project
pass
# Task 3: Implement positional encoding
class SinusoidalPositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super().__init__()
# Create sinusoidal encoding matrix
pass
def forward(self, x):
# Add positional encoding to input
pass
# Task 4: Assemble full Transformer encoder
class TransformerEncoder(nn.Module):
def __init__(self, d_model=512, n_heads=8, n_layers=6):
super().__init__()
# Stack of Transformer blocks
pass
# Task 5: Train on a language modeling task
# - Use WikiText-2 dataset
# - Autoregressive (next token prediction)
# - Adam optimizer with warmup schedule
Success criteria: Implement all components and achieve perplexity <40 on WikiText-2 validation set.
Key Takeaways
What to Learn Next
-> BERT Learn about bidirectional language understanding.
-> GPT Architecture Explore how GPT generates text.
-> Attention Deep Dive Master attention mechanisms in detail.
-> Vision Transformers Apply Transformers to computer vision.
-> Transfer Learning Leverage pre-trained Transformer models.
-> Training Deep Networks Master optimizers and regularization for Transformers.
Advanced Topics
Efficient Attention Mechanisms
Standard self-attention has O(n^2) complexity. Several methods address this:
- Sparse Attention (Longformer, BigBird): Attend to local windows (e.g., 512 tokens) + a few global tokens. Complexity: O(n * window_size).
- Linear Attention (Performer): Approximate softmax with kernel functions to avoid materializing the full n x n matrix.
- Flash Attention (Dao et al.): Compute attention in tiles on GPU SRAM, using O(n) memory instead of O(n^2). 2-4x speedup with zero approximation.
- Sliding Window (Mistral): Each token attends only to a fixed window of neighbors, reducing complexity to O(n * w).
Scaling Laws
Kaplan et al. (2020) discovered power law relationships:
where is loss, is parameters, is data tokens, is compute FLOPs.
Key insight: Optimal performance requires balancing all three. Doubling parameters gives diminishing returns without proportional data/compute increases. This led to Chinchilla's compute-optimal training: for a given budget, train a smaller model on more data.
Transformer Variants
- BERT (Encoder-only): Bidirectional attention, masked language modeling. Good for understanding.
- GPT (Decoder-only): Causal attention, next-token prediction. Good for generation.
- T5 (Encoder-decoder): Text-to-text framework. Any task as text generation.
- Vision Transformer (ViT): Treats image patches as tokens. ViT-L/14 achieves 87.8% on ImageNet.
- Perceiver: Processes arbitrary modalities (text, images, audio, point clouds) through a learned latent space.
- State Space Models (Mamba): Linear-time alternative to Transformers for very long sequences (100K+ tokens).
KV Cache in Inference
During autoregressive generation, previously computed Key and Value matrices are cached to avoid recomputation. Without KV cache, generating tokens requires total computation. With KV cache, each new token requires only computation (for the new token's Q against all cached KVs).
Comparison Table
| Model | Type | Params | Context | Best For |
|---|---|---|---|---|
| BERT-base | Encoder | 110M | 512 | Classification, NER, QA |
| GPT-2 | Decoder | 1.5B | 1024 | Text generation |
| T5-11B | Enc-Dec | 11B | 512 | Text-to-text tasks |
| GPT-4 | Decoder | ~1.8T (est.) | 128K | General AI assistant |
| LLaMA-3 70B | Decoder | 70B | 8K | Open-source LLM |
| ViT-L/14 | Encoder | 307M | N/A (patches) | Computer vision |
Further Reading
- Vaswani, A. et al. (2017). "Attention Is All You Need." — The original Transformer paper, one of the most influential in ML history.
- Devlin, J. et al. (2018). "BERT: Pre-training of Deep Bidirectional Transformers." — Bidirectional encoder for language understanding.
- Radford, A. et al. (2018/2019). "Improving Language Understanding by Generative Pre-Training." — GPT-1 and GPT-2.
- Kaplan, J. et al. (2020). "Scaling Laws for Neural Language Models." — Power law relationships between compute, data, and performance.
- Dao, T. et al. (2022). "FlashAttention: Fast and Memory-Efficient Exact Attention." — Hardware-aware attention algorithm.
- Su, J. et al. (2021). "RoFormer: Enhanced Transformer with Rotary Position Embedding." — RoPE for long-context models.
Quick Reference Cheat Sheet
| Component | PyTorch | Key Parameters |
|---|---|---|
| Multi-Head Attention | nn.MultiheadAttention() | d_model, n_heads, dropout |
| Positional Encoding | nn.Embedding(max_len, d_model) | or sinusoidal (fixed) |
| FFN | nn.Sequential(Linear, GELU, Linear) | d_ff = 4 * d_model typically |
| Layer Norm | nn.LayerNorm() | d_model |
| Causal Mask | torch.triu(torch.ones(n,n)) == 0 | Fill with -inf for masked positions |
Model Comparison: Encoder vs Decoder vs Encoder-Decoder
| Property | Encoder (BERT) | Decoder (GPT) | Enc-Dec (T5) |
|---|---|---|---|
| Attention type | Bidirectional | Causal (masked) | Both + cross-attention |
| Pre-training | MLM + NSP | Next token prediction | Span corruption / denoising |
| Inference | Parallel (all tokens) | Autoregressive (one at a time) | Encode parallel, decode auto |
| Fine-tuning | Add task head | Prompt/in-context learning | Text-to-text format |
| Modern examples | BERT, RoBERTa, DeBERTa | GPT-4, LLaMA, Mistral | T5, BART, mBART |