Attention & Transformers
The architecture behind modern AI — queries, keys and values, scaled dot-product attention, self-attention, multi-head attention, positional encodings, the transformer block (residuals, layer norm, feed-forward), encoder vs decoder models, causal masking, and the cost of attention.
The transformer (Vaswani et al., 2017, "Attention Is All You Need") is the architecture behind GPT, Claude, Gemini, LLaMA, BERT, Whisper, vision transformers and protein models. Its core operation — attention — lets every position in a sequence directly gather information from every other position, in parallel.
The intuition
In "The animal didn't cross the street because it was too tired", what does "it" refer to? To build a good representation of "it", the model should pull in information from "animal". Self-attention does this: each token computes how relevant every other token is, then takes a weighted mix of their information.
Queries, keys and values
Each token's vector is projected into three vectors with learned matrices:
| Vector | Role | Analogy |
|---|---|---|
| Query | What this token is looking for | A search query |
| Key | What each token offers to be matched on | Document titles |
| Value | The information each token passes on if attended to | Document contents |
The attention weight from token i to token j is the (scaled) dot product of and , normalised with softmax across j. The output for token i is the weighted sum of values.
Scaled dot-product attention
In matrix form for a whole sequence:
- : an n × n matrix of scores — every query against every key.
- Divide by so scores don't grow with dimension and saturate the softmax.
- Softmax each row → attention weights that sum to 1.
- Multiply by V: each output row is a weighted average of value vectors.
import torch
import torch.nn.functional as F
def attention(Q, K, V, mask=None):
d_k = Q.size(-1)
scores = Q @ K.transpose(-2, -1) / d_k ** 0.5 # (…, n, n)
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
weights = F.softmax(scores, dim=-1)
return weights @ V, weightsMulti-head attention
One attention pattern can't capture everything (syntax, coreference, nearby words, topic). Multi-head attention runs h attention operations in parallel, each with its own smaller (dimension ), then concatenates and projects the results:
Different heads learn different relationships. (Efficient variants used in LLMs: multi-query and grouped-query attention share keys and values across heads to shrink the inference cache.)
Positional information
Attention is permutation-invariant: shuffle the tokens and each gets the same output. Order must be injected:
- Sinusoidal or learned absolute position embeddings added to token embeddings (original transformer, BERT, GPT-2).
- Rotary position embeddings (RoPE): rotate query and key vectors by position-dependent angles, so attention scores depend on relative distance — used by most modern LLMs; extendable to longer contexts.
- ALiBi: a distance-based bias added to attention scores.
The transformer block
- Attention mixes information across positions.
- The feed-forward network (two linear layers with GELU or SwiGLU, ~4× wider) transforms each position independently — it's where much of the model's knowledge is stored.
- Residual connections and layer normalisation (pre-norm, often RMSNorm) keep deep stacks trainable (Neural networks).
from torch import nn
class Block(nn.Module):
def __init__(self, d_model=768, n_heads=12):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
self.ln2 = nn.LayerNorm(d_model)
self.mlp = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Linear(4 * d_model, d_model))
def forward(self, x, causal_mask):
h = self.ln1(x)
x = x + self.attn(h, h, h, attn_mask=causal_mask, need_weights=False)[0] # residual
x = x + self.mlp(self.ln2(x)) # residual
return xEncoders, decoders and both
| Type | Attention | Pretraining task | Examples | Good for |
|---|---|---|---|---|
| Encoder-only | Bidirectional: every token sees all tokens | Masked language modelling (fill in blanks) | BERT, RoBERTa, embedding models | Classification, search embeddings, NER |
| Decoder-only | Causal: each token sees only earlier tokens | Next-token prediction | GPT, Claude, LLaMA, Gemini | Text generation, chat — today's LLMs |
| Encoder–decoder | Encoder bidirectional; decoder causal + cross-attention to encoder outputs | Span corruption, translation | Original Transformer, T5, Whisper | Translation, summarisation, speech recognition |
Causal masking
For generation, a token must not see the future during training (otherwise predicting the next token is trivial). A causal mask sets scores above the diagonal to −∞ before the softmax, so position i attends only to positions ≤ i. This lets the model train on every position of a sequence in parallel while learning to predict each next token.
Why transformers won
- Parallelism: all positions are processed at once — training saturates GPUs, unlike sequential RNNs (RNNs).
- Direct long-range connections: any two tokens interact in one step.
- Scaling: performance improves predictably with more parameters, data and compute (scaling laws), which justified building ever-larger models (LLMs).
- Generality: the same block works for text, images (ViT), audio, video, code, proteins — and combinations (multimodal models).
The cost of attention
The n × n score matrix makes attention O(n²) in sequence length for compute and (naively) memory. Doubling context quadruples attention cost. Solutions:
| Technique | Idea |
|---|---|
| FlashAttention | Exact attention computed in tiles in fast on-chip SRAM, never materialising the full matrix — far less memory traffic |
| KV cache | During generation, store past keys and values so each new token costs O(n), not O(n²) |
| Sparse / sliding-window attention | Attend to a local window plus selected global tokens |
| Grouped-query attention | Fewer key/value heads → a smaller KV cache |
| State-space and linear-attention hybrids | Sub-quadratic sequence mixing for very long contexts |
- Attention computes softmax(QKᵀ/√d)V: each token takes a weighted mix of all tokens' values based on query–key similarity.
- Multi-head attention learns several relationship types in parallel.
- Positions are injected with position embeddings, now mostly RoPE.
- A transformer block = attention + feed-forward MLP, each with layer norm and a residual connection, stacked N times.
- Encoder-only (BERT) for understanding, decoder-only with causal masks (GPT-style LLMs) for generation, encoder–decoder for translation and speech.
- Transformers parallelise and scale well; attention is quadratic in length, mitigated by FlashAttention, KV caches and sparse variants.
QWhy is the dot product divided by the square root of d_k in attention?hard
For random vectors with unit-variance components, the dot product of two d_k-dimensional vectors has variance d_k, so scores grow with dimension. Large scores push the softmax into a near one-hot regime where its gradients are tiny, slowing or stalling learning. Dividing by √d_k keeps the scores' variance around 1 regardless of head size, so the softmax stays in a range with useful gradients.
QWhat is the KV cache and why does it matter?medium
In autoregressive generation, each new token attends to all previous tokens. Recomputing keys and values for the whole prefix at every step would be wasteful, so the model caches the keys and values of past tokens for every layer and only computes them for the new token. This makes each step linear in context length, but the cache grows with batch size, sequence length, layers and heads, so it often limits how many requests and how much context a server can handle — motivating grouped-query attention, quantised caches and paged memory management.