Transformers – Comprehensive Lecture 1 Notes

Module 1.1 – Limitations of Sequential (RNN) Models

  • Seq2Seq with RNN encoder–decoder
    • Encoder produces hidden states h<em>0,…,h</em>Th<em>0,\dots ,h</em>T for source sentence (e.g. “I enjoyed the movie transformers”).
    • Final state h<em>Th<em>T (a.k.a. concept/thought/context vector) passed to decoder as s</em>0=hTs</em>0=h_T.
    • Decoder generates target sentence step-by-step using its own hidden states s1,…s_1,\dots.
  • Problems
    • Bottleneck: single vector hTh_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<em>i{h<em>i} instead of only h</em>Th</em>T.
  • Context vector for decoder step ttc<em>t=∑</em>i=1nα<em>tih</em>ic<em>t = \sum</em>{i=1}^{n} \alpha<em>{ti} h</em>i
    • Alignment scores
      α<em>ti=align(y</em>t,h<em>i)=exp⁡(score(s</em>t−1,h<em>i))∑</em>i′exp⁡(score(s<em>t−1,h</em>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'}))}
    • Typical score function (Bahdanau):
      score(s,h)=V<em>a⊤ tanh⁡(U</em>atts+Watth)\text{score}(s,h)=V<em>a^\top\,\tanh(U</em>{att}s + W_{att}h).
  • Benefit: better translation via word-to-word correspondence.
  • Still sequential: st−1s_{t-1} required before we can compute row tt 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.

Transition to Transformers – “Attention Is All You Need”

  • Replace RNNs with stacked attention + feed-forward blocks in both encoder & decoder.
  • Key primitives:
    1. Self-Attention (within encoder or decoder).
    2. Encoder–Decoder (Cross) Attention (decoder queries encoder outputs).
    3. 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<em>1,…,h</em>T]∈Rd<em>model×TH=[h<em>1, \dots , h</em>T] \in \mathbb R^{d<em>{model}\times T} (here d</em>model=512d</em>{model}=512).
    • Three learned matrices W<em>Q,W</em>K,W<em>V∈Rd</em>k×d<em>modelW<em>Q, W</em>K, W<em>V \in \mathbb R^{d</em>k\times d<em>{model}} (with d</em>k=d<em>q=d</em>v=64d</em>k=d<em>q=d</em>v=64 in original base model).
    • Compute matrices
      Q=W<em>QH,  K=W</em>KH,  V=W<em>VHQ=W<em>Q H, \; K=W</em>K H, \; V=W<em>V H where Q,K,V∈Rd</em>k×TQ,K,V \in \mathbb R^{d</em>k\times T}.
  • Scaled Dot-Product Attention (vectorized)Z=softmax!(Q⊤Kd<em>k)V(Z∈RT×d</em>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})
    • Q⊤KQ^\top K → T×TT\times T matrix of all pairwise scores q<em>i⋅k</em>jq<em>i \cdot k</em>j.
    • Division by dk\sqrt{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 ii
    head<em>i=Attention(Q</em>i,K<em>i,V</em>i)\text{head}<em>i = \text{Attention}(Q</em>i,K<em>i,V</em>i) with separate W<em>Q</em>i,W<em>K</em>i,W<em>V</em>iW<em>{Q</em>i},W<em>{K</em>i},W<em>{V</em>i}.
  • Concatenation & output projection
    MultiHead(Q,K,V)=Concat(head<em>1,…,head</em>h)W<em>O,\text{MultiHead}(Q,K,V)=\text{Concat}(\text{head}<em>1,\dots,\text{head}</em>h) W<em>O, where W</em>O∈Rhd<em>v×d</em>modelW</em>O \in \mathbb R^{hd<em>v\times d</em>{model}} (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):
    1. Multi-Head Self-Attention.
    2. Position-wise FFN: FFN(z)=W<em>2 ReLU(W</em>1z+b<em>1)+b</em>2\text{FFN}(z)=W<em>2\,\text{ReLU}(W</em>1 z + b<em>1)+b</em>2 with W<em>1∈R2048×512,W</em>2∈R512×2048W<em>1\in\mathbb R^{2048\times512},W</em>2\in\mathbb R^{512\times2048}.
  • Residual connection plus LayerNorm after each sublayer.
  • Parameter count (per layer, h=8):
    • Attention projections: 3×(8⋅64×512)=≈ 2.6×1053\times (8\cdot64\times512)=\approx\,2.6\times10^5 each.
    • Output WOW_O: 512×512=2.6×105512\times512=2.6\times10^5.
    • FFN ≈ 2×1062\times10^6.
    • ≈ 3×1063\times10^6 total per layer → ≈18  M\approx18\;\text{M} for 6 layers.

Decoder Layer Structure

  • Three sublayers (stack of 6):
    1. Masked Multi-Head Self-Attention (prevents using future tokens during training).
    2. Multi-Head Cross-Attention where QQ comes from decoder self-att output; K,VK,V come from encoder outputs EE.
    3. 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 MM 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}
    • jj = position (0…T−1), ii = dimension index (0…dmodel−1d_{model}-1).
    • Produces unique, smooth patterns enabling model to learn relative distances (distance matrix symmetric property).
  • Added element-wise to word embeddings.
    h<em>j′=h</em>j+pjh<em>j' = h</em>j + p_j.

Normalization & Residuals

  • Layer Normalization preferred over BatchNorm in NLP:
    μ=1H∑<em>i=1Hx</em>i,σ2=1H∑(x<em>i−μ)2\mu = \frac1H \sum<em>{i=1}^H x</em>i,\quad \sigma^2 = \frac1H \sum (x<em>i-\mu)^2x^</em>i=x<em>i−μσ2+ϵ,y</em>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.
  • 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} converges slowly early on.
  • Growing LR only ((\eta \propto \text{step})) diverges later.
  • Combined schedule (warm-up):η=dmodel−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)
    • 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∈RT×512S \in \mathbb R^{T\times512}.
  • Linear projection WD∈R512×∣V∣W_D \in \mathbb R^{512\times|V|} followed by softmax → word distribution.
  • Vocabulary ∣V∣≈37000|V|\approx37000 ⇒ ≈19 M\approx19\,\text{M} parameters, dominant share of overall ~65 M.
  • Inference is autoregressive: previous decoded word fed back; teacher forcing not used.

Summary of Transformer Advantages

  • 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<em>model=512,  d</em>k=64,  h=8,  N=6d<em>{model}=512,\;d</em>k=64,\;h=8,\;N=6 encoder & decoder.
  • Encoder params ≈ 18 M18\,\text{M}, decoder core ≈ 24 M24\,\text{M}, output head ≈ 19 M19\,\text{M} → total ≈ 65 M65\,\text{M}.