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)
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
- Motivation: attention without recurrence
- Scaled dot-product attention (full derivation)
- Multi-head attention
- Transformer block
- Positional encoding
- The full Transformer (Vaswani et al., 2017)
- Masking
- BERT (encoder)
- GPT (decoder)
- T5 (encoder-decoder)
- Efficient transformers
- Vision Transformer (ViT)
- Parameter-efficient fine-tuning (LoRA)
1. Motivation: attention without recurrence
1.1 Problems with RNNs for long sequences
- Sequential computation: depends on → cannot parallelize across the sequence. Training on long sequences is slow.
- Long-range dependencies: gradient path from position to position 1 is steps long → vanishing gradients even with LSTM.
- 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: memory and compute for attention (vs 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 (T tokens, d-dimensional), project to:
where and are learned projection matrices.
Intuition:
- (Query): what am I looking for?
- (Key): what do I contain?
- (Value): what do I actually provide?
2.2 Attention computation
Step 1 — Raw attention scores:
Entry = dot product between query and key = similarity between position 's query and position 's key.
Step 2 — Scale:
Why scale by ? For random with unit-normal components:
Large → large variance → extreme dot products → softmax saturates → tiny gradients. Dividing by keeps variance at 1.
Step 3 — Softmax over keys:
Row of this matrix = attention distribution of position over all positions.
Step 4 — Weighted sum of values:
Complete formula:
2.3 Complexity
- Time: for the matrix product .
- Memory: to store the attention matrix.
For : attention weights per head — manageable. For (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 heads, each with dimension :
where , , .
Parameters: attention heads, total params = (since ): three projection matrices each , plus output .
3.3 Cross-attention (encoder-decoder)
In the encoder-decoder Transformer, decoder queries attend to encoder keys and values:
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
│
Output4.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):
, (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: (4 for attention, 8 for FFN). For : params per block.
4.4 Gated FFN variants
SwiGLU (used in LLaMA, PaLM):
where .
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 and dimension (out of ):
Added to token embeddings: .
Properties:
- Each position has a unique encoding.
- The encoding for position is a linear function of the encoding at position (enables relative attention).
- Fixed (not learned); generalizes to sequences longer than training.
5.3 Learned positional embeddings
Learn a separate embedding 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 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 identical blocks):
Input tokens → Embedding + PE
→ [Self-Attention → Add&Norm → FFN → Add&Norm] × N_E
→ Encoder output (T × d)Decoder (stack of 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 probabilities6.2 Original hyperparameters (base model)
- , , .
- .
- encoder layers, 6 decoder layers.
- Total parameters: .
6.3 Training
Loss: cross-entropy over target tokens (teacher forcing):
Optimizer: Adam with warmup + inverse square root decay:
where = warmup steps (e.g., 4000).
7. Masking
7.1 Padding mask
Prevents attending to padding tokens. Set attention scores for padding positions to (→ softmax → 0).
7.2 Causal (autoregressive) mask
For decoder self-attention: position should only attend to positions (no future leakage).
Mask matrix : upper triangle = , lower triangle + diagonal = 0.
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). : , 110M params. : , 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).
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 () 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.logits9. 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)
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):
- Fine-tune on demonstrations (supervised fine-tuning / SFT).
- Train reward model on human preference comparisons.
- 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 bottleneck
Standard attention has memory for the attention matrix. For (16K tokens): values per head — multiple GB for a single layer.
11.2 Sparse attention
Sliding window attention (Longformer): each token attends to a window of neighbors. 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 -th position. Combine with local to cover full range.
11.3 Linear attention
Rewrite attention without explicit matrix. Kernel-based: approximate . Reduces to via associativity:
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; 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.
- Split image into non-overlapping patches of size .
- Number of tokens: . For , : patches.
- Linearly project each flattened patch to : .
- Prepend [CLS] token; add positional embeddings.
- Apply standard Transformer encoder.
- 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 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 , instead of learning , constrain it to be low rank:
where , , and rank .
Initialization: (random), (so at start — same as pretrained model).
Parameters: vs . For : vs ( 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 into — no extra latency:
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
| Method | Idea | Params |
|---|---|---|
| LoRA | Low-rank weight update | Very few () |
| Prefix Tuning | Learn soft tokens prepended to each layer | Few |
| Prompt Tuning | Learn soft tokens in input space only | Fewer |
| Adapter | Small bottleneck layers inserted between layers | Moderate |
| BitFit | Fine-tune only bias terms | Very few |
*File: notes/15_transformers.md — next: notes/16_generative_models.md*