Attention and Transformers
The architecture behind GPT, BERT, ViT and Whisper. Queries, keys and values; scaled dot-product attention; masks; multi-head attention; positional encodings; and how the Transformer block is assembled.
In 2017, Vaswani et al. proposed a sequence model with no recurrence and no convolution — only Attention — in a paper titled “Attention Is All You Need”[1]. The Transformer trains in parallel over all positions, scales remarkably well with data and compute, and now underlies nearly every frontier model: GPT-style LLMs, BERT, Vision Transformers (Vision Transformer (ViT)), Whisper for speech and DiT-style diffusion models. Understanding one equation — softmax(QKᵀ/√d)V — gets you most of the way.
From RNN bottleneck to attention
Seq2seq RNNs compressed a whole sentence into one vector. Bahdanau et al. (2014) let the decoder, at each output step, score every encoder state, normalize the scores with a Softmax, and use the weighted average as context[2] — the model learned soft word alignments between languages on its own. Two problems remained: RNNs still process tokens one after another (slow to train), and information between distant words still had to travel through many steps. The Transformer removed the RNN entirely: every token attends directly to every other token, in one step, in parallel.
Scaled dot-product attention
- X
- input token vectors, one row per token (n × d_model)
- W_Q
- learned projection to queries (d_model × d_k); W_K and W_V likewise for keys and values
- Q
- queries (n × d_k)
- K
- keys (n × d_k)
- V
- values (n × d_v)
- QKᵀ
- all query–key dot products at once: an n × n score matrix (ᵀ = transpose)
- √d_k
- square root of the key dimension; dividing by it keeps scores from growing with d_k and saturating the softmax
- softmax
- Softmax applied to each row: positive weights that sum to 1
- Attention(Q, K, V)
- the output: for each token, a weighted mix of all value vectors (n × d_v)
▸Worked example
- Scores: QKᵀ is an n × n matrix: entry (i, j) is the Dot product of token i's query with token j's key — how relevant j is to i.
- Scale: divide by √d_k. If query and key components have unit variance, their dot product has variance d_k; for d_k = 64 scores would have std ≈ 8, pushing softmax into saturation (one weight ≈ 1, tiny gradients). Dividing by √d_k brings the std back to ≈ 1[1].
- Softmax each row → attention weights that are positive and sum to 1.
- Mix values: each token's output is the weighted average of all value vectors.
Tiny worked example (d_k = 2): query q = (1, 0); keys k₁ = (1, 0), k₂ = (0, 1), k₃ = (1, 1); scalar values 10, 20, 30. Scores q·k = (1, 0, 1), scaled by 1/√2 → (0.71, 0, 0.71). Softmax → (0.40, 0.20, 0.40). Output = 0.40·10 + 0.20·20 + 0.40·30 = 20. The query “prefers” tokens 1 and 3 equally and still takes a little from token 2.
Self-attention and masks
In Self-attention, Q, K and V all come from the same sequence, so every token gathers information from every other token of the same sentence. In “The animal didn't cross the street because it was too tired”, the representation of “it” can pull information directly from “animal”, one step away instead of eight. A causal mask sets scores for future positions to −∞ before the softmax, so token i only sees tokens ≤ i — required for a Decoder that generates text left to right. A padding mask hides padding tokens. Cross-attention takes Q from the decoder and K, V from the Encoder — exactly Bahdanau's idea.
Multi-head attention
- headᵢ
- output of attention head i (n × d_k)
- W_Qⁱ
- head i's own query projection (d_model × d_k); W_Kⁱ and W_Vⁱ likewise
- Concat(head₁, …, head_h)
- place the h head outputs side by side: n × (h · d_k) = n × d_model
- W_O
- output projection (d_model × d_model) that mixes information across heads
- MultiHead
- the result of Multi-head attention (n × d_model)
▸Worked example
One attention pattern can only express one kind of relationship at a time. Multi-head attention runs several attention operations in parallel on smaller projections, so different heads can specialise — one tracks the previous token, another links pronouns to nouns, another follows syntax. Because each head is d_model/h wide, the total cost is about the same as one full-width head[1][3].
Positional encoding
Attention by itself is order-blind: shuffle the input tokens and each output is the same, just shuffled. “Dog bites man” and “man bites dog” would look identical. A Positional encoding injects order. The original paper added fixed sinusoids of different frequencies to the embeddings; BERT and GPT-2 learn a position vector per index; many modern LLMs use RoPE (rotary embeddings, Su et al.), which rotates queries and keys by a position-dependent angle so that attention scores depend on relative distance[5]; ALiBi adds a distance-based penalty to scores (Press et al., 2021).
- PE(pos, 2i)
- value of the Positional encoding at position pos, even dimension 2i
- PE(pos, 2i+1)
- value at the neighbouring odd dimension 2i + 1
- pos
- token position in the sequence: 0, 1, 2, …
- i
- index of the dimension pair: 0 … d_model/2 − 1
- d_model
- model width (512 in the base Transformer)
- 10000^(2i/d_model)
- wavelength factor: 1 for the first pair, up to 10,000 for the last
- sin
- sine (angles in radians)
- cos
- cosine
▸Worked example
The Transformer block
- x
- the residual stream: one vector per token (n × d_model)
- ←
- update: replace x by the right-hand side
- LayerNorm
- Layer normalization: rescale each token vector to mean 0 and variance 1, then apply a learned scale and shift
- MultiHeadAttention
- Multi-head attention (with a causal mask in a decoder)
- FFN(x)
- position-wise feed-forward network (a 2-layer MLP (Multilayer Perceptron))
- W₁
- first FFN weight matrix (d_model × d_ff), expands e.g. 512 → 2048
- b₁
- first FFN bias
- W₂
- second FFN weight matrix (d_ff × d_model), projects back 2048 → 512
- b₂
- second FFN bias
- GELU
- smooth ReLU-like activation: GELU(z) = z · Φ(z), where Φ is the standard normal CDF
▸Worked example
A block has two sub-layers: attention (tokens exchange information) and a position-wise feed-forward MLP (each token processes what it gathered). Each sub-layer is wrapped in a residual connection and Layer normalization — the same tricks that made ResNets trainable. Stack N blocks (6 in the original, 12 in BERT-base, 96 in GPT-3) and you have a Transformer. Moving LayerNorm before each sub-layer (Pre-LN) makes deep stacks much more stable to train (Xiong et al., 2020).
| Variant | Attention | Trained to | Examples |
|---|---|---|---|
| Encoder-only | Bidirectional (sees all tokens) | Fill in masked tokens; produce representations | BERT, RoBERTa, ViT |
| Decoder-only | Causal (sees only the past) | Predict the next token | GPT, LLaMA, Claude-style LLMs |
| Encoder–decoder | Bidirectional encoder + causal decoder + cross-attention | Map one sequence to another | Original Transformer, T5, Whisper |
- Coreference: pick “The animal didn't cross the street because it was too tired”, select the coreference head and click “it”. The thickest line should go to “animal”.
- Different heads, different jobs: switch to the previous-token head — the heatmap becomes a diagonal band just below the main diagonal. Same sentence, completely different pattern.
- Causal mask: toggle encoder → decoder. The upper triangle of the heatmap turns to zero: “it” can no longer see “tired”. Every row still sums to 1.
- Scaling / temperature: turn off the √d scaling or lower the temperature — the weights become sharp, nearly one-hot. Raise it — they flatten toward uniform. This is why the √d_k factor matters for gradients.
- Indonesian sentence: switch to the Indonesian example and check whether the heads behave the same way across languages.
- What it is
- How many parallel attention operations each layer runs (each of width d_model / h).
- ↑ If you increase it
- More distinct relationship patterns per layer; but each head gets narrower (smaller d_k), and too-narrow heads lose expressiveness. Compute stays roughly constant.
- ↓ If you decrease it
- Wider heads but fewer patterns; a single head must average over different kinds of relationships.
- Typical values
- d_k = 64–128 per head; e.g. 8 heads at d_model 512, 12 at 768, 32+ in large LLMs.
- What it is
- Size of every token's representation vector throughout the network.
- ↑ If you increase it
- More capacity per token; parameters grow ≈ quadratically (≈ 12·d_model² per layer), as do compute and memory. Larger models typically need a smaller learning rate.
- ↓ If you decrease it
- Cheaper and faster, but less able to represent nuanced information.
- Typical values
- 512 (original), 768 (BERT-base), 4096+ (7B-class LLMs).
- What it is
- How many Transformer blocks are stacked.
- ↑ If you increase it
- More steps of reasoning/composition and more parameters; deeper stacks need Pre-LN, warmup and careful initialization to train stably. Inference latency grows linearly.
- ↓ If you decrease it
- Faster and simpler; may underfit complex tasks.
- Typical values
- 6 (original), 12 (BERT-base), 32 (7B LLMs), 96 (GPT-3).
- What it is
- Maximum number of tokens the model attends over at once.
- ↑ If you increase it
- Can use longer documents and conversations; attention compute and memory grow ∝ n² (the KV cache ∝ n), and quality may drop beyond lengths seen in training.
- ↓ If you decrease it
- Much cheaper; text beyond the window must be truncated, chunked or retrieved (RAG).
- Typical values
- 512 (BERT), 2,048 (GPT-3), 8k–1M+ in modern LLMs.
- What it is
- Hidden width of the feed-forward MLP inside each block.
- ↑ If you increase it
- More per-token processing capacity (the FFN holds about ⅔ of a block's parameters); more memory and compute.
- ↓ If you decrease it
- Smaller, faster model with less capacity to store knowledge.
- Typical values
- 4 × d_model; about 8/3 × d_model for SwiGLU FFNs.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def attention(q, k, v, causal=False):
# q, k, v: (batch, heads, seq_len, d_k)
scores = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1)) # (b, h, n, n)
if causal:
n = q.size(-2)
future = torch.triu(torch.ones(n, n, dtype=torch.bool), diagonal=1)
scores = scores.masked_fill(future, float("-inf")) # hide future tokens
weights = scores.softmax(dim=-1) # rows sum to 1
return weights @ v, weights
q, k, v = (torch.randn(1, 8, 10, 64) for _ in range(3))
out, w = attention(q, k, v, causal=True)
ref = F.scaled_dot_product_attention(q, k, v, is_causal=True) # fused kernel, PyTorch >= 2.0
print(torch.allclose(out, ref, atol=1e-5)) # True
# A full Pre-LN encoder block from PyTorch's building blocks
block = nn.TransformerEncoderLayer(d_model=512, nhead=8, dim_feedforward=2048,
dropout=0.1, activation="gelu",
batch_first=True, norm_first=True)
x = torch.randn(2, 10, 512) # (batch, seq_len, d_model)
print(block(x).shape) # torch.Size([2, 10, 512])scaled_dot_product_attention[6], plus a ready-made encoder block.- Forgetting the causal mask when training a decoder: the model “cheats” by looking at the token it should predict — training loss collapses, generation is garbage.
- Forgetting the padding mask: real tokens attend to padding.
- Memory blow-up with long sequences: the n × n matrix grows quadratically; use fused/Flash attention kernels.
- No positional information: without positional encodings, word order is invisible.
- Reading attention maps as explanations: high attention weight ≠ causal importance (Jain & Wallace, 2019).
- Post-LN without warmup on deep models often diverges early.
▸Go deeper: complexity, the original training recipe, and further reading
| Layer type | Compute per layer | Sequential steps | Max path length |
|---|---|---|---|
| Self-attention | O(n² · d) | O(1) | O(1) |
| Recurrent | O(n · d²) | O(n) | O(n) |
| Convolutional | O(k · n · d²) | O(1) | O(logₖ n) |
The original model was trained with Adam (β₂ = 0.98), 4,000 warmup steps followed by inverse-square-root decay, dropout 0.1 and label smoothing 0.1[1]. For step-by-step visuals, read Jay Alammar's “Illustrated Transformer”[3]; for runnable code, the Transformer chapter of “Dive into Deep Learning”[4].
Quiz
References
- [1]Attention Is All You NeedPaperVaswani et al.2017arxiv.org
- [2]Neural Machine Translation by Jointly Learning to Align and TranslatePaperBahdanau, Cho & Bengio2014arxiv.org
- [3]The Illustrated TransformerArticleAlammar2018jalammar.github.io
- [4]Dive into Deep Learning — The Transformer ArchitectureBookZhang, Lipton, Li & Smolad2l.ai
- [5]RoFormer: Enhanced Transformer with Rotary Position EmbeddingPaperSu et al.2021arxiv.org
- [6]torch.nn.functional.scaled_dot_product_attentionDocsPyTorchdocs.pytorch.org