Step 4 of 6

Attention & the transformer

Self-attention as a learned routing mechanism: queries, keys, values, multi-head attention, positional encoding, and the full encoder-decoder architecture from 'Attention Is All You Need.'

20 min read

The transformer is the architecture behind every modern large language model - GPT, Claude, Gemini, LLaMA, and their descendants. It replaced recurrence with attention, a mechanism that lets each token look at every other token directly. Understanding attention is understanding how these models think.

3Blue1Brown's visual explanation of how attention lets tokens communicate, with the query-key-value mechanism animated step by step.

The problem attention solves#

RNNs process tokens sequentially - token 50 can only reach token 1 through 49 intermediate hidden states. Information decays, training is slow (no parallelism), and long-range dependencies are hard to learn.

Attention lets any token attend to any other token directly, in one step. The computational cost is quadratic in sequence length (every token looks at every other), but the representational power is immense - and the parallelism makes GPUs happy.

Queries, keys, and values#

Attention works like a soft lookup table. Each token produces three vectors:

VectorRoleAnalogy
Query (Q)"What am I looking for?"A search query
Key (K)"What do I contain?"A document title
Value (V)"What information do I provide?"The document's content

The attention score between two tokens is the dot product of one's query with the other's key. High score = high relevance = more of that token's value flows through:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

Scaled dot-product attention: compute compatibility (Q·Kᵀ), scale to prevent softmax saturation, apply softmax for weights, and aggregate values.

The √dₖ scaling prevents the dot products from growing too large as the dimension increases, which would push softmax into regions where gradients vanish.

Multi-head attention#

A single attention head can only focus on one type of relationship at a time. Multi-head attention runs several attention heads in parallel, each with its own learned Q, K, V projections:

  1. 01Project input into h separate (Q, K, V) triples - one per head
  2. 02Each head computes attention independently
  3. 03Concatenate all head outputs
  4. 04Project concatenation back to model dimension

Different heads learn different relationships: one might track syntactic dependencies (subject-verb agreement), another semantic similarity, another positional patterns. The concatenation combines all these perspectives.

The transformer block#

A transformer is a stack of identical blocks, each containing two sub-layers with residual connections and layer normalization:

  1. 01Multi-head self-attention (each token attends to all tokens)
  2. 02Add & LayerNorm (residual connection)
  3. 03Feed-forward MLP (two linear layers with activation)
  4. 04Add & LayerNorm (residual connection)

The attention layer handles token interaction - letting tokens exchange information. The MLP handles token computation - processing each token's representation independently. Together, they alternate between "communicate" and "compute" across the depth of the network.

Positional encoding#

Attention is permutation-equivariant - it treats tokens as a set, not a sequence. Without positional information, "the cat sat on the mat" and "mat the on sat cat the" produce identical outputs.

Positional encodings inject position information:

MethodHow it worksUsed in
SinusoidalFixed sine/cosine functions of positionOriginal transformer
LearnedTrainable embedding per positionBERT, GPT-2
RoPERotary embeddings in the Q/K spaceLLaMA, modern LLMs
ALiBiLinear bias added to attention scoresBLOOM, MPT

RoPE (Rotary Position Embedding) has become dominant: it encodes relative position by rotating the query and key vectors, so the dot product naturally depends on the distance between tokens. This enables length generalization - the model can handle longer sequences than it was trained on.

RoPE
Rotary Position Embedding - encodes position by rotating query and key vectors, so attention scores naturally depend on relative distance between tokens.
ALiBi
Attention with Linear Biases - adds a position-dependent penalty to attention scores so nearby tokens are favored, enabling length generalization without learned embeddings.
Length generalization
A model's ability to handle sequences longer than those it was trained on - critical for deploying LLMs with flexible context windows.

Encoder vs. decoder#

The original transformer (Vaswani et al., 2017, "Attention Is All You Need") has both an encoder and a decoder. Modern architectures typically use one or the other:

ArchitectureAttention typeUse caseExamples
Encoder-onlyBidirectional (see all tokens)Classification, embeddingsBERT, RoBERTa
Decoder-onlyCausal (see only past tokens)Text generationGPT, Claude, LLaMA
Encoder-decoderBothTranslation, summarizationT5, BART, original transformer

Causal masking in decoder models prevents each token from attending to future tokens - enforcing the autoregressive property that makes generation possible. The attention mask is a triangular matrix that zeros out future positions.

Autoregressive
Generating one token at a time, where each new token depends on all previously generated tokens - the core mechanism behind GPT-style text generation.
Causal masking
A triangular mask applied to attention scores that prevents each token from seeing future tokens - enforces the left-to-right generation order.
KV cache
Stores the Key and Value vectors from all previously generated tokens so they don't need to be recomputed at each generation step - essential for efficient inference.

The KV cache - why generation is expensive#

During generation, each new token requires attending to all previous tokens. Naively, this means recomputing Q, K, V for every previous token at every step.

The KV cache stores the K and V vectors from all previous tokens. At each generation step, only the new token's Q, K, V are computed; the cached K and V are reused. This turns generation from O(n²) to O(n) per token - but the cache grows linearly with sequence length, which is why long-context models need so much memory.

Where it shows up in ML#

Self-attention is the core of LLMs

Every token attending to every other token is what gives transformers their power - and their quadratic cost. The entire field of efficient attention aims to reduce this.

Multi-head attention = multiple views

Heads specialize: some track syntax, some semantics, some copy patterns. Interpretability research studies what each head learns.

The KV cache dominates serving cost

GQA (grouped query attention) shares K/V heads across query heads, cutting cache size 4-8× with minimal quality loss. Used in LLaMA 2+, Mistral.

Vision transformers use the same mechanism

ViT patches an image into tokens and runs standard transformer attention. The same architecture works for images, audio, video, and protein structures.

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.