Transformers – Comprehensive Lecture 1 Notes Module 1.1 – Limitations of Sequential (RNN) Models Seq2Seq with RNN encoder–decoder Encoder produces hidden states h < e m > 0 , … , h < / e m > T h<em>0,\dots ,h</em>T h < e m > 0 , … , h < / e m > T for source sentence (e.g. “I enjoyed the movie transformers”). Final state h < e m > T h<em>T h < e m > T (a.k.a. concept/thought/context vector) passed to decoder as s < / e m > 0 = h T s</em>0=h_T s < / e m > 0 = h T . Decoder generates target sentence step-by-step using its own hidden states s 1 , … s_1,\dots s 1 , … . Problems Bottleneck: single vector h T h_T h T must encode all information, ignoring direct word alignment. Computation is inherently sequential → cannot parallelize across time steps during training. Susceptible to vanishing / exploding gradients. Attention Mechanism Refresher (RNN context) Idea: provide decoder direct access to every encoder hidden state h < e m > i {h<em>i} h < e m > i instead of only h < / e m > T h</em>T h < / e m > T .Context vector for decoder step t t t c < e m > t = ∑ < / e m > i = 1 n α < e m > t i h < / e m > i c<em>t = \sum</em>{i=1}^{n} \alpha<em>{ti} h</em>i c < e m > t = ∑ < / e m > i = 1 n α < e m > t i h < / e m > i Alignment scoresα < e m > t i = align ( y < / e m > t , h < e m > i ) = exp ( score ( s < / e m > t − 1 , h < e m > i ) ) ∑ < / e m > i ′ exp ( score ( s < e m > t − 1 , h < / e m > i ′ ) ) \alpha<em>{ti}=\text{align}(y</em>t,h<em>i)=\frac{\exp(\text{score}(s</em>{t-1},h<em>i))}{\sum</em>{i'}\exp(\text{score}(s<em>{t-1},h</em>{i'}))} α < e m > t i = align ( y < / e m > t , h < e m > i ) = ∑ < / e m > i ′ e x p ( score ( s < e m > t − 1 , h < / e m > i ′ )) e x p ( score ( s < / e m > t − 1 , h < e m > i )) Typical score function (Bahdanau):score ( s , h ) = V < e m > a ⊤ tanh ( U < / e m > a t t s + W a t t h ) \text{score}(s,h)=V<em>a^\top\,\tanh(U</em>{att}s + W_{att}h) score ( s , h ) = V < e m > a ⊤ tanh ( U < / e m > a tt s + W a tt h ) . Benefit: better translation via word-to-word correspondence.Still sequential: s t − 1 s_{t-1} s t − 1 required before we can compute row t t t of α \alpha α → no full parallelization.Desire for New Architecture Maintain attention’s alignment strengths. Enable full parallel computation across sentence positions (eliminate sequential recurrence). Address gradient problems. Replace RNNs with stacked attention + feed-forward blocks in both encoder & decoder. Key primitives:Self-Attention (within encoder or decoder).Encoder–Decoder (Cross) Attention (decoder queries encoder outputs).Position-wise Feed-Forward Networks (FFN). Self-Attention Mechanics Objective: for every input token, produce representation that aggregates information from all tokens weighted by contextual relevance.Inputs & linear projections Word embeddings H = [ h < e m > 1 , … , h < / e m > T ] ∈ R d < e m > m o d e l × T H=[h<em>1, \dots , h</em>T] \in \mathbb R^{d<em>{model}\times T} H = [ h < e m > 1 , … , h < / e m > T ] ∈ R d < e m > m o d e l × T (here d < / e m > m o d e l = 512 d</em>{model}=512 d < / e m > m o d e l = 512 ). Three learned matrices W < e m > Q , W < / e m > K , W < e m > V ∈ R d < / e m > k × d < e m > m o d e l W<em>Q, W</em>K, W<em>V \in \mathbb R^{d</em>k\times d<em>{model}} W < e m > Q , W < / e m > K , W < e m > V ∈ R d < / e m > k × d < e m > m o d e l (with d < / e m > k = d < e m > q = d < / e m > v = 64 d</em>k=d<em>q=d</em>v=64 d < / e m > k = d < e m > q = d < / e m > v = 64 in original base model). Compute matricesQ = W < e m > Q H , K = W < / e m > K H , V = W < e m > V H Q=W<em>Q H, \; K=W</em>K H, \; V=W<em>V H Q = W < e m > Q H , K = W < / e m > K H , V = W < e m > V H where Q , K , V ∈ R d < / e m > k × T Q,K,V \in \mathbb R^{d</em>k\times T} Q , K , V ∈ R d < / e m > k × T . Scaled Dot-Product Attention (vectorized) Z = softmax ! ( Q ⊤ K d < e m > k ) V ( Z ∈ R T × d < / e m > v ) Z = \text{softmax}!\left(\frac{Q^\top K}{\sqrt{d<em>k}}\right) V \quad (Z \in \mathbb R^{T\times d</em>v}) Z = softmax ! ( d < e m > k Q ⊤ K ) V ( Z ∈ R T × d < / e m > v ) Q ⊤ K Q^\top K Q ⊤ K → T × T T\times T T × T matrix of all pairwise scores q < e m > i ⋅ k < / e m > j q<em>i \cdot k</em>j q < e m > i ⋅ k < / e m > j .Division by d k \sqrt{d_k} d k prevents large dot products causing small gradients (stabilizes softmax). Softmax along keys axis ensures each row sums to 1. Parallelism: all rows computed in one matrix operation – no time-step dependency.Multi-Head Self-Attention Motivation: analogous to multiple convolutional kernels → capture diverse relation sub-spaces.Procedure for each head i i i head < e m > i = Attention ( Q < / e m > i , K < e m > i , V < / e m > i ) \text{head}<em>i = \text{Attention}(Q</em>i,K<em>i,V</em>i) head < e m > i = Attention ( Q < / e m > i , K < e m > i , V < / e m > i ) with separate W < e m > Q < / e m > i , W < e m > K < / e m > i , W < e m > V < / e m > i W<em>{Q</em>i},W<em>{K</em>i},W<em>{V</em>i} W < e m > Q < / e m > i , W < e m > K < / e m > i , W < e m > V < / e m > i .Concatenation & output projection MultiHead ( Q , K , V ) = Concat ( head < e m > 1 , … , head < / e m > h ) W < e m > O , \text{MultiHead}(Q,K,V)=\text{Concat}(\text{head}<em>1,\dots,\text{head}</em>h) W<em>O, MultiHead ( Q , K , V ) = Concat ( head < e m > 1 , … , head < / e m > h ) W < e m > O ,
where W < / e m > O ∈ R h d < e m > v × d < / e m > m o d e l W</em>O \in \mathbb R^{hd<em>v\times d</em>{model}} W < / e m > O ∈ R h d < e m > v × d < / e m > m o d e l (h=8 in base model → concat dimension 512).Learning is fully parallel across heads. Encoder Layer Structure Two sublayers per layer (stack of N=6):Multi-Head Self-Attention. Position-wise FFN: FFN ( z ) = W < e m > 2 ReLU ( W < / e m > 1 z + b < e m > 1 ) + b < / e m > 2 \text{FFN}(z)=W<em>2\,\text{ReLU}(W</em>1 z + b<em>1)+b</em>2 FFN ( z ) = W < e m > 2 ReLU ( W < / e m > 1 z + b < e m > 1 ) + b < / e m > 2 with W < e m > 1 ∈ R 2048 × 512 , W < / e m > 2 ∈ R 512 × 2048 W<em>1\in\mathbb R^{2048\times512},W</em>2\in\mathbb R^{512\times2048} W < e m > 1 ∈ R 2048 × 512 , W < / e m > 2 ∈ R 512 × 2048 . Residual connection plus LayerNorm after each sublayer.Parameter count (per layer, h=8): Attention projections: 3 × ( 8 ⋅ 64 × 512 ) = ≈ 2.6 × 10 5 3\times (8\cdot64\times512)=\approx\,2.6\times10^5 3 × ( 8 ⋅ 64 × 512 ) =≈ 2.6 × 1 0 5 each. Output W O W_O W O : 512 × 512 = 2.6 × 10 5 512\times512=2.6\times10^5 512 × 512 = 2.6 × 1 0 5 . FFN ≈ 2 × 10 6 2\times10^6 2 × 1 0 6 . ≈ 3 × 10 6 3\times10^6 3 × 1 0 6 total per layer → ≈ 18 M \approx18\;\text{M} ≈ 18 M for 6 layers. Decoder Layer Structure Three sublayers (stack of 6):Masked Multi-Head Self-Attention (prevents using future tokens during training).Multi-Head Cross-Attention where Q Q Q comes from decoder self-att output; K , V K,V K , V come from encoder outputs E E E . Position-wise FFN. Same residual + LayerNorm after each. Teacher Forcing & Masking During training, ground-truth target tokens shifted right ( + sentence) fed as inputs. Mask matrix M M M is upper-triangular with − ∞ -\infty − ∞ above diagonal → softmax zeroes future positions. Parameter cost per decoder layer: ~4 M (≈2 M FFN + 1 M masked self-attn + 1 M cross-attn).Positional Encoding Self-attention is permutation-invariant; need token order info. Sinusoidal encoding (fixed, no new parameters):
\text{PE}(j,i)=\begin{cases}\sin\left(\frac{j}{10000^{2i/d{model}}}\right), & i\text{ even}\[4pt]
\cos\left(\frac{j}{10000^{2i/d {model}}}\right), & i\text{ odd}\end{cases}j j j = position (0…T−1), i i i = dimension index (0…d m o d e l − 1 d_{model}-1 d m o d e l − 1 ).Produces unique, smooth patterns enabling model to learn relative distances (distance matrix symmetric property). Added element-wise to word embeddings.h < e m > j ′ = h < / e m > j + p j h<em>j' = h</em>j + p_j h < e m > j ′ = h < / e m > j + p j . Normalization & Residuals Layer Normalization preferred over BatchNorm in NLP:μ = 1 H ∑ < e m > i = 1 H x < / e m > i , σ 2 = 1 H ∑ ( x < e m > i − μ ) 2 \mu = \frac1H \sum<em>{i=1}^H x</em>i,\quad \sigma^2 = \frac1H \sum (x<em>i-\mu)^2 μ = H 1 ∑ < e m > i = 1 H x < / e m > i , σ 2 = H 1 ∑ ( x < e m > i − μ ) 2 x ^ < / e m > i = x < e m > i − μ σ 2 + ϵ , y < / e m > i = γ x ^ i + β \hat{x}</em>i = \frac{x<em>i-\mu}{\sqrt{\sigma^2+\epsilon}},\qquad y</em>i = \gamma \hat{x}_i + \beta x ^ < / e m > i = σ 2 + ϵ x < e m > i − μ , y < / e m > i = γ x ^ i + β .Applied after each sublayer alongside residual add. Ensures stable gradients and allows batch size 1 during inference. Training Details – Learning-Rate Warm-Up Standard decaying LR η ∝ step − 0.5 \eta \propto \text{step}^{-0.5} η ∝ step − 0.5 converges slowly early on. Growing LR only ((\eta \propto \text{step})) diverges later. Combined schedule (warm-up): η = d m o d e l − 0.5 ⋅ min ( step − 0.5 , step ⋅ warmup − 1.5 ) \eta = d_{model}^{-0.5} \cdot \min\left(\text{step}^{-0.5},\; \text{step}\;\cdot\text{warmup}^{-1.5}\right) η = d m o d e l − 0.5 ⋅ min ( step − 0.5 , step ⋅ warmup − 1.5 ) WarmupSteps = 4000 in original paper. Blue curve increases linearly then follows inverse-sqrt decay; always ≥ simple decay curve after warmup. Output Generation & Parameters Top decoder layer outputs S ∈ R T × 512 S \in \mathbb R^{T\times512} S ∈ R T × 512 . Linear projection W D ∈ R 512 × ∣ V ∣ W_D \in \mathbb R^{512\times|V|} W D ∈ R 512 × ∣ V ∣ followed by softmax → word distribution. Vocabulary ∣ V ∣ ≈ 37000 |V|\approx37000 ∣ V ∣ ≈ 37000 ⇒ ≈ 19 M \approx19\,\text{M} ≈ 19 M parameters, dominant share of overall ~65 M. Inference is autoregressive: previous decoded word fed back; teacher forcing not used. Full parallelization across sequence positions during training (both encoder & masked decoder self-attn computed with matrix ops). Multi-head attention captures diverse contextual relations. Residuals + LayerNorm → deep (=42 total sublayers) yet trainable network. Sinusoidal positional encodings allow unlimited length generalization without learned embeddings. Warm-up learning-rate schedule accelerates convergence. Ethical / Practical Notes Parameter counts (65 M) imply high compute & energy cost; scaling further magnifies this. Attention visualisations (Colab demos) reveal which words influence each other → interpretability aid. Masking strategy prevents information leakage during training yet allows efficient teacher forcing. Connections & Real-World Relevance CNN analogy: multi-head ≈ multiple kernels; FFN ≈ pointwise conv.Compared to RNN: eliminates sequential dependency, solves vanishing-gradient problem, achieves state-of-the-art in machine translation and many NLP tasks.Positional encoding ideas now reused in vision (ViT) & audio transformers. Numerical Recap (Base Model) d < e m > m o d e l = 512 , d < / e m > k = 64 , h = 8 , N = 6 d<em>{model}=512,\;d</em>k=64,\;h=8,\;N=6 d < e m > m o d e l = 512 , d < / e m > k = 64 , h = 8 , N = 6 encoder & decoder.Encoder params ≈ 18 M 18\,\text{M} 18 M , decoder core ≈ 24 M 24\,\text{M} 24 M , output head ≈ 19 M 19\,\text{M} 19 M → total ≈ 65 M 65\,\text{M} 65 M .