Step 2 of 5

Transformers Deep Dive

Queries, keys, and values; multi-head attention; positional encodings; and why decoder-only won for generation.

16 min read

In 2017, a Google paper titled Attention Is All You Need replaced the recurrent networks that dominated language modeling with an architecture built almost entirely from attention. Every frontier model since is a descendant. This guide opens the box: how queries, keys, and values work, why there are multiple heads, how a model knows word order, and why the decoder-only variant won.

The transformer architecture#

Why attention replaced recurrence#

Before transformers, RNNs and LSTMs read text one token at a time, carrying a hidden state forward. Two problems followed:

  • No parallelism. Token 500 can't be processed until token 499 is done, so training on GPUs was slow.
  • Long-range forgetting. Information from early tokens had to survive hundreds of sequential updates to influence later ones.

Attention solves both. Every token can look at every other token directly, in one step, and all positions are computed in parallel. The cost: comparing every token with every other token is O(n²) in sequence length - a trade that turned out to be overwhelmingly worth it.

Queries, keys, and values#

Each token's vector is projected by three learned matrices into three roles:

Query (Q)

x · W_Q

What this token is looking for. 'I'm a pronoun - who do I refer to?'

Key (K)

x · W_K

What this token offers to others. 'I'm a singular animal noun.'

Value (V)

x · W_V

The information this token passes along if someone attends to it.

A good mental model is a soft dictionary lookup. The query is compared against every key; the better the match, the more of that key's value flows into the result. Unlike a real dictionary, you get a weighted blend of all values rather than exactly one.

Scaled dot-product attention#

The whole mechanism fits in one line:

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

Compare queries with keys (QKᵀ), scale, turn scores into weights with softmax, then take the weighted sum of values.

Step by step for a single token:

  1. Score: dot its query with every key. High dot product = high relevance.
  2. Scale: divide by √dₖ (the key dimension). Without this, dot products grow with dimension, softmax saturates into near one-hot outputs, and gradients vanish.
  3. Mask: in a decoder, set scores for future positions to −∞ so they get zero weight. This is the causal mask.
  4. Normalize: softmax turns scores into weights that sum to 1.
  5. Mix: the output is the weighted sum of value vectors.
Query tokenIlovegreentea
I1.00···
love0.400.60··
green0.100.300.60·
tea0.050.350.450.15
A causal attention pattern (illustrative). 'tea' draws most heavily on 'green' and 'love' - the words that tell it what kind of tea and why it's there.

Multi-head attention#

One attention computation can only focus on one kind of relationship at a time. Multi-head attention runs several in parallel - commonly 8 to 128 heads - each with its own smaller Q, K, V projections. Their outputs are concatenated and projected back to the model dimension.

In trained models, different heads specialize: some track the previous token, some link pronouns to nouns, some attend to matching brackets in code. You get many "views" of context for roughly the cost of one full-size head.

Token representationd_model = 4096 (example)
  • Head 1Syntax / previous token
  • Head 2Coreference
  • Head 3Long-range topic
  • ... Head hConcatenate → project
Each head attends independently in a lower-dimensional subspace; results are concatenated and mixed by an output projection.

The transformer block#

A full layer wraps attention with a few more pieces, and a model stacks dozens of identical layers:

InputToken embeddings (+ positional information)
Norm → AttentionLayerNorm/RMSNorm, then masked multi-head self-attention
Residual addAdd the attention output back to the input - the 'residual stream'
Norm → MLPA position-wise feed-forward network, typically ~4× wider than d_model
Residual addAdd again; pass to the next block
A modern pre-norm decoder block, repeated N times (e.g., 32 layers in a 7B-class model).

The residual connections matter more than they look: they give gradients a straight path through dozens of layers and let each layer add information to a shared stream rather than replace it. The MLP is where much of a model's factual knowledge appears to be stored.

Residual connection
Adds a layer's input directly to its output, creating a shortcut that helps gradients flow through deep networks without vanishing.
RMSNorm
Root Mean Square Normalization - a simpler, faster alternative to LayerNorm that normalizes by the root-mean-square of activations, skipping the mean subtraction.
MLP (feed-forward)
A position-wise network inside each transformer block - typically expands ~4×, applies a nonlinearity, and projects back. Stores much of the model's factual knowledge.

Positional encoding#

Attention by itself is order-blind: "dog bites man" and "man bites dog" produce the same set of pairwise scores. Models inject position in one of three main ways:

MethodHow it worksUsed by
SinusoidalAdd fixed sine/cosine waves of different frequencies to each positionThe original transformer
Learned absoluteLearn one vector per position index, up to a maximum lengthBERT, GPT-2
Rotary (RoPE)Rotate query and key vectors by an angle proportional to position, so their dot product depends on relative distanceLlama, Mistral, Qwen, and most modern open models

RoPE is popular because relative position is what language mostly cares about, and it extends to longer contexts more gracefully (with scaling tricks) than a fixed table of learned positions.

RoPE (Rotary Position Embedding)
Encodes position by rotating query and key vectors - their dot product then depends on relative distance, enabling better length generalization.
Causal mask
Sets attention scores for future positions to −∞ so a token can only attend to earlier tokens - enforces the left-to-right autoregressive property.
Cross-attention
Queries come from one sequence (decoder), keys and values from another (encoder) - how encoder-decoder models condition output on input.

Encoder, decoder, or both#

The original transformer had two halves. Later models kept one or the other:

Encoder-only

BERT

Bidirectional: every token sees the whole input. Trained by masking words and predicting them. Excellent for classification, NER, and embeddings - not for generating text.

Decoder-only

GPT, Claude, Llama

Causal: each token sees only the past. Trained on next-token prediction. Generates text naturally, and scales cleanly.

Encoder-decoder

T5, original transformer

Encoder reads the input; decoder generates while attending to it via cross-attention. Strong for translation and summarization.

Why decoder-only won for generation: one simple objective (predict the next token) works on any raw text with no labels, the same model handles every task through prompting, and the architecture scales predictably. Encoder-only models remain the workhorse for embeddings and classification, where seeing both directions helps.

The O(n²) bottleneck#

Every token attends to every earlier token, so the attention score matrix is n × n. Doubling the context quadruples attention compute and (naively) memory. That single fact drives a whole research area:

  • FlashAttention computes exact attention in tiles that fit in fast on-chip memory, never materializing the full n × n matrix - a large speedup with identical results.
  • KV caching avoids recomputing past keys and values during generation.
  • Grouped-query and multi-query attention share key/value heads across query heads to shrink the cache.
  • Sparse and sliding-window attention restrict which positions each token can see.

Transformer interview questions#

The questions that come up again and again. Try answering out loud before expanding each one.

Why divide by √dₖ in attention?

Dot products of random vectors grow in magnitude with dimension (variance ≈ dₖ). Large scores push softmax into a near one-hot regime where gradients are tiny. Dividing by √dₖ keeps the variance around 1 so training stays stable.

What's the difference between causal and masked attention?

Causal (autoregressive) attention masks future positions so token t only sees tokens ≤ t - used in decoders. 'Masked language modeling' is a different thing: BERT hides random input tokens and predicts them, while attention itself stays bidirectional. People mix these up; name which one you mean.

Self-attention vs cross-attention?

In self-attention, Q, K, and V all come from the same sequence. In cross-attention, queries come from one sequence (the decoder) and keys/values from another (the encoder output) - that's how an encoder-decoder model conditions its output on its input.

Why do transformers need positional encodings?

Attention is permutation-invariant: shuffling the input tokens shuffles the outputs the same way, so the model can't tell order. Positional information (sinusoidal, learned, or rotary) breaks that symmetry.

What is the time and memory complexity of self-attention?

O(n² · d) compute and O(n²) memory for the score matrix, where n is sequence length and d the model dimension. The MLP is O(n · d²), so for short sequences the MLP dominates and for long ones attention does.

Why multiple heads instead of one big head?

Each head can learn a different relationship in its own subspace (syntax, coreference, position). One big head would average these into a single attention pattern. Multi-head gives many patterns for roughly the same compute.

What do residual connections and layer norm do?

Residuals add each sublayer's output to its input, giving gradients a direct path through deep stacks and letting layers refine a shared representation. Normalization keeps activations in a stable range; modern models use pre-norm (normalize before each sublayer), often RMSNorm.

BERT vs GPT - when would you use each?

BERT-style encoders for understanding tasks where you have the whole input: classification, NER, retrieval embeddings, reranking. GPT-style decoders for generation and anything you want to steer with prompts. Many production systems use both: an encoder for retrieval and a decoder for answers.

What is the KV cache and why does it matter?

During generation, the keys and values of past tokens never change, so they're cached instead of recomputed each step. It turns decoding from quadratic to linear work per token, but the cache grows with context length and is often the main memory cost of serving.

How does RoPE encode position?

It rotates each pair of dimensions in the query and key vectors by an angle proportional to the token's position. The dot product of two rotated vectors then depends on their relative offset, which gives the model relative-position awareness without a learned position table.

What does the feed-forward (MLP) layer contribute?

It processes each position independently after attention has mixed in context - typically expand ~4×, apply a nonlinearity (GELU/SwiGLU), project back. It holds most of the parameters and, per interpretability research, much of the model's stored knowledge.

How would you make attention work on very long inputs?

Exact but efficient kernels (FlashAttention); fewer KV heads (GQA/MQA); sliding-window or sparse attention; KV-cache quantization or paging; RoPE scaling to extend trained context; or avoid it entirely with retrieval so only relevant chunks enter the context.

Papers behind this guide

Further reading

Search Data Science After Dark

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