DEEP LEARNING / 7. TRANSFORMERS
Transformers From Scratch
Attention Is All You Need — the architecture behind everything
EXPLANATION
The Transformer (2017) replaced RNNs entirely for sequence tasks. Key insight: you don't need recurrence if you have attention. Process the entire sequence in parallel. A Transformer block = Multi-Head Attention + Feed Forward + Layer Norm + Residual connections. Encoder block (BERT-style): x → [LayerNorm → MHA → +residual] → [LayerNorm → FFN → +residual] Decoder block (GPT-style): Same but with causal (masked) attention — each token can only see previous tokens. Positional Encoding: attention has no sense of order. We add position information via sinusoidal encodings (original) or learned embeddings (modern models). The FFN is 4× wider than d_model: this is where most of the model's "knowledge" is stored. MHA finds relationships, FFN processes them.
DATA FLOW
TRANSFORMER ENCODER BLOCK: ┌──────────────────────────────────────────────┐ │ x ──→ LayerNorm ──→ MultiHeadAttention │ │ └──────────────────────── + x (residual)│ │ x ──→ LayerNorm ──→ FeedForward │ │ └──────────────────────── + x (residual)│ └──────────────────────────────────────────────┘ FeedForward: x → Linear(d_model → 4·d_model) → GELU → Linear(4·d_model → d_model) Stack N of these blocks → encoder (BERT uses 12, GPT-3 uses 96)
CODE