VivaPrep
← Jaber Notes

Jaber Notes · 15 of 16

Transformers

Scaled attention, multi-head, positional encoding, BERT/GPT/T5, LoRA.

The architecture behind modern AI: the full scaled dot-product attention derivation (and why the √d_k scale), multi-head and cross-attention, positional encodings (sinusoidal/RoPE/ALiBi), BERT/GPT/T5 objectives, and LoRA.

Visual reference

Self-attention (simplified)

Thebankraisedrates
While encoding "bank," the model looks at every other token and weighs how relevant each is — here, "raised" and "rates" matter most, correctly hinting at the financial sense of "bank."
The architecture that unified NLP (and now vision, audio, and multimodal AI). Full derivation of self-attention, positional encoding, and the Transformer block. Then: BERT, GPT, T5, and beyond.

Table of contents

  1. Motivation: attention without recurrence
  2. Scaled dot-product attention (full derivation)
  3. Multi-head attention
  4. Transformer block
  5. Positional encoding
  6. The full Transformer (Vaswani et al., 2017)
  7. Masking
  8. BERT (encoder)
  9. GPT (decoder)
  10. T5 (encoder-decoder)
  11. Efficient transformers
  12. Vision Transformer (ViT)
  13. Parameter-efficient fine-tuning (LoRA)

1. Motivation: attention without recurrence

1.1 Problems with RNNs for long sequences

  1. Sequential computation: ht\mathbf{h}_t depends on ht1\mathbf{h}_{t-1} → cannot parallelize across the sequence. Training on long sequences is slow.
  2. Long-range dependencies: gradient path from position TT to position 1 is TT steps long → vanishing gradients even with LSTM.
  3. Fixed context vector: seq2seq bottleneck, even with attention (attention is add-on; RNN still processes sequentially).

1.2 The transformer idea (Vaswani et al., "Attention is All You Need", 2017)

Remove recurrence entirely. Process all positions simultaneously with self-attention.

Self-attention allows every position to directly attend to every other position — path length 1 regardless of sequence length. No vanishing gradient across positions.

Tradeoff: O(T2)O(T^2) memory and compute for attention (vs O(T)O(T) for RNNs). For very long sequences this is costly.


2. Scaled dot-product attention (full derivation)

2.1 Queries, Keys, and Values

Given an input sequence XRT×d\mathbf{X} \in \mathbb{R}^{T \times d} (T tokens, d-dimensional), project to:

Q=XWQ,K=XWK,V=XWV,\mathbf{Q} = \mathbf{X}\mathbf{W}^Q, \quad \mathbf{K} = \mathbf{X}\mathbf{W}^K, \quad \mathbf{V} = \mathbf{X}\mathbf{W}^V,

where WQ,WKRd×dk\mathbf{W}^Q, \mathbf{W}^K \in \mathbb{R}^{d \times d_k} and WVRd×dv\mathbf{W}^V \in \mathbb{R}^{d \times d_v} are learned projection matrices.

Intuition:

  • Q\mathbf{Q} (Query): what am I looking for?
  • K\mathbf{K} (Key): what do I contain?
  • V\mathbf{V} (Value): what do I actually provide?

2.2 Attention computation

Step 1 — Raw attention scores:

Araw=QKRT×T.\mathbf{A}_\text{raw} = \mathbf{Q}\mathbf{K}^\top \in \mathbb{R}^{T \times T}.

Entry AijA_{ij} = dot product between query ii and key jj = similarity between position ii's query and position jj's key.

Step 2 — Scale:

Ascaled=QKdk.\mathbf{A}_\text{scaled} = \frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}.

Why scale by dk\sqrt{d_k}? For random q,kRdk\mathbf{q}, \mathbf{k} \in \mathbb{R}^{d_k} with unit-normal components:

E[qk]=0,Var(qk)=dk.\mathbb{E}[\mathbf{q}^\top\mathbf{k}] = 0, \quad \text{Var}(\mathbf{q}^\top\mathbf{k}) = d_k.

Large dkd_k → large variance → extreme dot products → softmax saturates → tiny gradients. Dividing by dk\sqrt{d_k} keeps variance at 1.

Step 3 — Softmax over keys:

attni,j=exp(Ascaled,ij)jexp(Ascaled,ij).\text{attn}_{i,j} = \frac{\exp(A_{\text{scaled},ij})}{\sum_{j'}\exp(A_{\text{scaled},ij'})}.

Row ii of this matrix = attention distribution of position ii over all positions.

Step 4 — Weighted sum of values:

Z=softmax ⁣(QKdk)VRT×dv.\mathbf{Z} = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V} \in \mathbb{R}^{T \times d_v}.

Complete formula:

Attention(Q,K,V)=softmax ⁣(QKdk)V.\boxed{\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}.}

2.3 Complexity

  • Time: O(T2dk)O(T^2 d_k) for the matrix product QK\mathbf{Q}\mathbf{K}^\top.
  • Memory: O(T2)O(T^2) to store the T×TT \times T attention matrix.

For T=512T = 512: 262K\approx 262K attention weights per head — manageable. For T=100KT = 100K (long documents): impractical with standard attention.


3. Multi-head attention

3.1 Motivation

A single attention head computes one set of attention patterns. Different heads can attend to different aspects:

  • Head 1: local patterns (adjacent tokens).
  • Head 2: syntactic dependencies (subject-verb agreement).
  • Head 3: coreference (pronouns → nouns).

3.2 Definition

With HH heads, each with dimension dk=dv=dmodel/Hd_k = d_v = d_\text{model}/H:

headh=Attention(QWhQ,KWhK,VWhV),\text{head}_h = \text{Attention}(\mathbf{Q}\mathbf{W}^Q_h, \mathbf{K}\mathbf{W}^K_h, \mathbf{V}\mathbf{W}^V_h),
MultiHead(Q,K,V)=Concat(head1,,headH)WO,\text{MultiHead}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{Concat}(\text{head}_1, \ldots, \text{head}_H)\mathbf{W}^O,

where WhQ,WhKRdmodel×dk\mathbf{W}^Q_h, \mathbf{W}^K_h \in \mathbb{R}^{d_\text{model} \times d_k}, WhVRdmodel×dv\mathbf{W}^V_h \in \mathbb{R}^{d_\text{model} \times d_v}, WORHdv×dmodel\mathbf{W}^O \in \mathbb{R}^{Hd_v \times d_\text{model}}.

Parameters: HH attention heads, total params = 4dmodel24d_\text{model}^2 (since Hdk=dmodelHd_k = d_\text{model}): three projection matrices WQ,WK,WV\mathbf{W}^Q, \mathbf{W}^K, \mathbf{W}^V each dmodel×dmodeld_\text{model} \times d_\text{model}, plus output WO\mathbf{W}^O.

3.3 Cross-attention (encoder-decoder)

In the encoder-decoder Transformer, decoder queries attend to encoder keys and values:

headh=Attention(QdecWhQ,KencWhK,VencWhV).\text{head}_h = \text{Attention}(\mathbf{Q}^\text{dec}\mathbf{W}^Q_h, \mathbf{K}^\text{enc}\mathbf{W}^K_h, \mathbf{V}^\text{enc}\mathbf{W}^V_h).

This is the generalization of seq2seq attention.


4. Transformer block

4.1 Standard block (Post-LN, original)

Input x
  │
  ▼
Multi-Head Attention(x, x, x)   ← self-attention
  │
  + x  ← residual connection
  │
  ▼
LayerNorm
  │
  ▼
Feed-Forward Network (FFN)
  │
  + x  ← residual connection
  │
  ▼
LayerNorm
  │
Output

4.2 Pre-LN variant (more stable training)

Apply LayerNorm before each sub-layer (inside the residual branch):

x + MultiHead(LayerNorm(x), ...)
x + FFN(LayerNorm(x))

Pre-LN allows larger learning rates and is used in GPT-2, GPT-3, LLaMA.

4.3 Feed-Forward Network (FFN)

Two linear layers with a nonlinearity (ReLU or GELU):

FFN(x)=W2σ(W1x+b1)+b2.\text{FFN}(\mathbf{x}) = \mathbf{W}_2\, \sigma(\mathbf{W}_1 \mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2.

W1Rdff×dmodel\mathbf{W}_1 \in \mathbb{R}^{d_\text{ff} \times d_\text{model}}, dff=4dmodeld_\text{ff} = 4d_\text{model} (standard expansion ratio).

FFN operates position-wise (same weights applied to each token independently). It is where most of the model's knowledge storage happens.

Parameters per block: 12d2\approx 12d^2 (4 for attention, 8 for FFN). For d=768d=768: 7M\approx 7M params per block.

4.4 Gated FFN variants

SwiGLU (used in LLaMA, PaLM):

SwiGLU(x,W,V)=Swish(xW)(xV),\text{SwiGLU}(\mathbf{x}, \mathbf{W}, \mathbf{V}) = \text{Swish}(\mathbf{x}\mathbf{W}) \odot (\mathbf{x}\mathbf{V}),

where Swish(z)=zσ(z)\text{Swish}(z) = z \cdot \sigma(z).

Empirically outperforms standard RELU FFN.


5. Positional encoding

5.1 Why needed

Self-attention is permutation-equivariant: the output of attention does not depend on token order (only on which tokens attend to which). Without positional information, "cat sat on mat" and "mat sat on cat" give the same output.

5.2 Sinusoidal positional encoding (original Transformer)

For position tt and dimension ii (out of dmodeld_\text{model}):

PE(t,2i)=sin ⁣(t100002i/dmodel),\text{PE}(t, 2i) = \sin\!\left(\frac{t}{10000^{2i/d_\text{model}}}\right),
PE(t,2i+1)=cos ⁣(t100002i/dmodel).\text{PE}(t, 2i+1) = \cos\!\left(\frac{t}{10000^{2i/d_\text{model}}}\right).

Added to token embeddings: e~t=et+PE(t)\tilde{\mathbf{e}}_t = \mathbf{e}_t + \text{PE}(t).

Properties:

  • Each position has a unique encoding.
  • The encoding for position t+kt + k is a linear function of the encoding at position tt (enables relative attention).
  • Fixed (not learned); generalizes to sequences longer than training.

5.3 Learned positional embeddings

Learn a separate embedding pt\mathbf{p}_t for each position up to a maximum length. Used in BERT, GPT-2.

Limitation: cannot extrapolate to longer sequences than seen in training.

5.4 Relative positional encoding (RoPE, ALiBi)

RoPE (Rotary Positional Encoding): encode relative position by rotating query and key vectors. Used in LLaMA, PaLM, many modern LLMs. Naturally handles longer sequences.

ALiBi (Attention with Linear Biases): add a linearly decaying bias mij-m|i-j| to attention scores (no trainable position parameters). Generalizes well beyond training length.


6. The full Transformer (Vaswani et al., 2017)

6.1 Architecture

Encoder (stack of NEN_E identical blocks):

Input tokens → Embedding + PE
  → [Self-Attention → Add&Norm → FFN → Add&Norm] × N_E
  → Encoder output (T × d)

Decoder (stack of NDN_D identical blocks):

Output tokens (shifted right) → Embedding + PE
  → [Masked Self-Attention → Add&Norm
     → Cross-Attention(encoder output) → Add&Norm
     → FFN → Add&Norm] × N_D
  → Linear → Softmax → Output probabilities

6.2 Original hyperparameters (base model)

  • dmodel=512d_\text{model} = 512, H=8H = 8, dk=dv=64d_k = d_v = 64.
  • dff=2048d_\text{ff} = 2048.
  • N=6N = 6 encoder layers, 6 decoder layers.
  • Total parameters: 65M\approx 65M.

6.3 Training

Loss: cross-entropy over target tokens (teacher forcing):

L=t=1TlogP(yty<t,X).\mathcal{L} = -\sum_{t=1}^T \log P(y_t | y_{<t}, \mathbf{X}).

Optimizer: Adam with warmup + inverse square root decay:

η=dmodel0.5min(t0.5,tW1.5),\eta = d_\text{model}^{-0.5} \cdot \min(t^{-0.5}, t \cdot W^{-1.5}),

where WW = warmup steps (e.g., 4000).


7. Masking

7.1 Padding mask

Prevents attending to padding tokens. Set attention scores for padding positions to -\infty (→ softmax → 0).

7.2 Causal (autoregressive) mask

For decoder self-attention: position tt should only attend to positions t\leq t (no future leakage).

Mask matrix M\mathbf{M}: upper triangle = -\infty, lower triangle + diagonal = 0.

Masked Attention(Q,K,V)=softmax ⁣(QKdk+M)V.\text{Masked Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}} + \mathbf{M}\right)\mathbf{V}.

8. BERT (encoder)

8.1 Architecture

Bidirectional Encoder Representations from Transformers (Devlin et al., 2018).

Encoder-only Transformer. Sees the full sequence (no causal mask). BERTbase\text{BERT}_\text{base}: L=12,H=768,A=12L=12, H=768, A=12, 110M params. BERTlarge\text{BERT}_\text{large}: L=24,H=1024,A=16L=24, H=1024, A=16, 340M params.

8.2 Pre-training objectives

Masked Language Modeling (MLM): randomly mask 15% of tokens; predict them. Of masked tokens: 80% replaced with [MASK], 10% with random token, 10% unchanged (prevents mismatch from [MASK] token not appearing at fine-tuning).

LMLM=iMlogP(xix~).\mathcal{L}_\text{MLM} = -\sum_{i \in \mathcal{M}} \log P(x_i | \tilde{\mathbf{x}}).

Next Sentence Prediction (NSP): predict if sentence B follows sentence A. (Later shown to be less useful; RoBERTa drops it.)

8.3 Fine-tuning

Add a task-specific head on top of BERT's [CLS] token embedding (for classification) or token embeddings (for token-level tasks). Fine-tune with small learning rate (2×1052\times10^{-5}) for few epochs.

from transformers import BertForSequenceClassification, BertTokenizer
import torch

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)

inputs = tokenizer("Hello, how are you?", return_tensors='pt')
outputs = model(**inputs, labels=torch.tensor([1]))
loss = outputs.loss
logits = outputs.logits

9. GPT (decoder)

9.1 Architecture

Decoder-only Transformer with causal mask (left-to-right autoregressive language model). Trained to predict the next token.

GPT-1 (2018): 117M params. GPT-2 (2019): 1.5B. GPT-3 (2020): 175B. GPT-4 (2023): unknown scale.

9.2 Training objective (language modeling)

L=t=1TlogPθ(xtx<t).\mathcal{L} = -\sum_{t=1}^T \log P_\theta(x_t | x_{<t}).

Trained on massive corpora (books, web). Next-token prediction is a simple objective that forces the model to learn grammar, facts, reasoning, and world knowledge.

9.3 In-context learning (ICL)

GPT-3's key finding: large models can perform tasks without gradient updates by showing examples in the prompt:

Example: "Translate English to French: sea otter → loutre de mer"
Example: "translate cheese → fromage"
Test: "steak → "

Zero-shot / few-shot / many-shot: 0, few, or many examples in prompt. Performance improves with scale.

9.4 Instruction following (GPT-3.5, GPT-4)

Reinforcement Learning from Human Feedback (RLHF):

  1. Fine-tune on demonstrations (supervised fine-tuning / SFT).
  2. Train reward model on human preference comparisons.
  3. RL fine-tuning (PPO) to maximize reward while not deviating from SFT model (KL penalty).

10. T5 (encoder-decoder)

10.1 Architecture

Text-to-Text Transfer Transformer (Raffel et al., 2019). Encoder-decoder Transformer where every task is framed as text-to-text:

  • Translation: "translate English to German: The house is wonderful."
  • Summarization: "summarize: ..."
  • Classification: "mnli premise: ... hypothesis: ... entailment/contradiction/neutral"

Unified objective: standard language modeling cross-entropy loss for all tasks.

10.2 Span corruption pre-training

Mask contiguous spans of tokens (avg span length 3, 15% of tokens) and predict them. More efficient than MLM.


11. Efficient transformers

11.1 The O(T2)O(T^2) bottleneck

Standard attention has O(T2)O(T^2) memory for the attention matrix. For T=16384T = 16384 (16K tokens): 163842=268M16384^2 = 268M values per head — multiple GB for a single layer.

11.2 Sparse attention

Sliding window attention (Longformer): each token attends to a window of ww neighbors. O(Tw)O(Tw) complexity. Plus global tokens that attend everywhere (for [CLS]).

Local + global (BigBird): combines local attention, global tokens, and random attention. Provably as expressive as full attention.

Strided attention: attend to every ss-th position. Combine with local to cover full range.

11.3 Linear attention

Rewrite attention without explicit T×TT\times T matrix. Kernel-based: approximate exp(qk/d)ϕ(q)ϕ(k)\exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d}) \approx \phi(\mathbf{q})^\top\phi(\mathbf{k}). Reduces to O(T)O(T) via associativity:

Attention(Q,K,V)=ϕ(Q)(ϕ(K)V)ϕ(Q)(ϕ(K)1).\text{Attention}(Q,K,V) = \frac{\phi(Q)(\phi(K)^\top V)}{\phi(Q)(\phi(K)^\top\mathbf{1})}.

11.4 FlashAttention

FlashAttention (Dao et al., 2022): exact attention, reordered to minimize HBM (memory bandwidth) access via tiling. Uses on-chip SRAM. Same output as standard attention; 24×2\text{–}4\times faster; sub-quadratic memory.

FlashAttention-2/3: further optimizations, now standard in modern LLM training.


12. Vision Transformer (ViT)

12.1 Patching images

Dosovitskiy et al. (2020): apply a pure Transformer to images by treating image patches as tokens.

  1. Split image H×W×CH \times W \times C into non-overlapping patches of size P×PP \times P.
  2. Number of tokens: T=HW/P2T = HW/P^2. For 224×224224\times224, P=16P=16: T=196T = 196 patches.
  3. Linearly project each flattened patch to dmodeld_\text{model}: et=Weflatten(patcht)\mathbf{e}_t = \mathbf{W}_e \text{flatten}(\text{patch}_t).
  4. Prepend [CLS] token; add positional embeddings.
  5. Apply standard Transformer encoder.
  6. Use [CLS] token embedding for classification.

12.2 Key observations

  • ViT needs large pre-training data (ImageNet-21K or JFT-300M) to match CNNs. CNNs have stronger inductive biases (translation equivariance, locality) that help with small data.
  • With enough data, ViT surpasses CNNs. Modern architectures (DeiT, Swin) close the data gap.

12.3 Swin Transformer

Hierarchical ViT: computes attention within local windows (reducing T2T^2 cost), then shifts windows between layers for cross-window connectivity. Produces feature maps at multiple scales (like CNNs) → useful for detection/segmentation.


13. Parameter-efficient fine-tuning (LoRA)

13.1 Motivation

Fine-tuning all 175B parameters of GPT-3 for each downstream task is expensive. PEFT methods adapt pretrained models with far fewer trainable parameters.

13.2 LoRA (Low-Rank Adaptation)

Hu et al. (2021): for a pretrained weight matrix W0Rd×k\mathbf{W}_0 \in \mathbb{R}^{d \times k}, instead of learning ΔW\Delta\mathbf{W}, constrain it to be low rank:

W=W0+ΔW=W0+BA,\mathbf{W} = \mathbf{W}_0 + \Delta\mathbf{W} = \mathbf{W}_0 + \mathbf{B}\mathbf{A},

where BRd×r\mathbf{B} \in \mathbb{R}^{d \times r}, ARr×k\mathbf{A} \in \mathbb{R}^{r \times k}, and rank rmin(d,k)r \ll \min(d,k).

Initialization: AN(0,σ2)\mathbf{A} \sim \mathcal{N}(0, \sigma^2) (random), B=0\mathbf{B} = 0 (so ΔW=0\Delta\mathbf{W} = 0 at start — same as pretrained model).

Parameters: r(d+k)r(d+k) vs dkdk. For d=k=768,r=8d=k=768, r=8: 8×1536=122888 \times 1536 = 12288 vs 589824589824 (48×\approx 48\times reduction).

Why low rank? Weight updates during fine-tuning have low intrinsic dimensionality — the task-relevant changes lie in a low-dimensional subspace of the weight space.

At inference: merge BA\mathbf{B}\mathbf{A} into W0\mathbf{W}_0 — no extra latency:

y=Wx=(W0+BA)x.y = \mathbf{W}x = (\mathbf{W}_0 + \mathbf{B}\mathbf{A})x.
from peft import get_peft_model, LoraConfig, TaskType

config = LoraConfig(
    task_type=TaskType.CAUSAL_LM,
    r=16,               # rank
    lora_alpha=32,      # scaling factor alpha/r
    target_modules=["q_proj", "v_proj"],
    lora_dropout=0.1,
)
model = get_peft_model(base_model, config)
model.print_trainable_parameters()
# trainable params: ~4M || all params: ~7B || trainable%: 0.057%

13.3 Other PEFT methods

MethodIdeaParams
LoRALow-rank weight updateVery few (r(d+k)r(d+k))
Prefix TuningLearn soft tokens prepended to each layerFew
Prompt TuningLearn soft tokens in input space onlyFewer
AdapterSmall bottleneck layers inserted between layersModerate
BitFitFine-tune only bias termsVery few

*File: notes/15_transformers.md — next: notes/16_generative_models.md*