3. The Attention Mechanism
How models learn what to focus on
Language models need to understand relationships between words. The word "it" in "The cat sat on the mat because it was tired" could refer to the cat or the mat — you need to have read the whole sentence to know which. For a long time, the dominant approach to handling this was recurrent neural networks, and for a long time, they struggled.
The Problem with Recurrence
A recurrent neural network (RNN) processes a sentence one token at a time, left to right. At each step it updates a hidden state — a fixed-size vector that's supposed to summarize everything seen so far. By the time you've read "tired" at the end of that sentence, the hidden state has to encode everything about "the cat", "the mat", and all the words in between.
This creates two serious problems.
The first is the sequential bottleneck. You can't process position 8 until you've finished position 7. On modern hardware that can execute billions of operations in parallel, forcing a sequential dependency throws away most of that power. Training on long documents becomes painfully slow.
The second is vanishing gradients. When you train a neural network, you update weights by propagating error signals backwards through the computation graph. In an RNN, this signal has to travel back through every time step. After 50 or 100 steps of multiplication, the gradient signal has either shrunk to nearly zero (vanished) or exploded to infinity. The network forgets early context because the learning signal that would reinforce those early connections simply never arrives.
The Core Limitation
In an RNN, two words that are far apart in a sentence are separated by many computational steps. The model has to route information about the first word all the way through every intermediate step to reach the second word. Long-range dependencies — "it" referring to "cat" three clauses earlier — are exactly what RNNs find hardest to learn.
The 2017 paper "Attention Is All You Need" proposed a radical alternative: throw out recurrence entirely. Let every position in the sequence look directly at every other position in a single step. No bottleneck. No vanishing gradients over distance. Just direct connections.
The Library Analogy
Before diving into the math, here's an intuition that makes the machinery concrete.
Imagine you're in a library. You arrive with a query — say, "I want a book about the history of computing." The library has shelves of books, each with a key on the spine: a short summary of what that book is about. You scan the spines, comparing your query against each key. Some keys are a close match; others are irrelevant. For the books whose keys match well, you pull them off the shelf and look at their contents — the actual values you care about.
Attention works exactly like this. For each word in a sequence:
- The Query (Q) is what this word is "looking for" — what kind of context would help it?
- The Key (K) is what each word "advertises" — what information does it offer?
- The Value (V) is what each word actually contributes when selected.
The model computes how well each query matches each key, turns those match scores into weights, and returns a weighted sum of values. A word whose key strongly matches the query contributes heavily to the output; a word whose key is a poor match contributes almost nothing.
Dot-Product Attention
Now let's be precise. Given a sequence of n tokens, we compute three matrices:
- Q (queries): shape n × d_k
- K (keys): shape n × d_k
- V (values): shape n × d_v
Each row of Q, K, V corresponds to one token's query, key, or value vector. We compute attention in a single formula:
Attention(Q, K, V) = softmax( Q·Kᵀ / √d_k ) · V
Breaking this down step by step:
-
Compute raw scores
Multiply Q by K transposed. This gives an n × n matrix of dot products — one score for every (query, key) pair. A high score means this query and key are a strong match; the query word is very interested in what the key word has to say.
-
Scale by 1/√d_k
Divide every score by the square root of the key dimension. This keeps the scores in a numerically stable range. Without scaling, large dot products push softmax into saturation (near-zero gradients), which would stall training.
-
Apply softmax row-wise
Convert each row of scores into a probability distribution. Every row sums to 1. The highest-scoring keys get the most weight; low-scoring keys get close to zero. This is the attention distribution for one query word.
-
Weighted sum of values
Multiply the attention weights by V. Each output token is a weighted combination of all value vectors, where the weights came from step 3. Tokens that matched the query strongly contribute more to the output.
Why the Scaling Factor Matters
The dot product Q·K is a sum of d_k multiplied pairs. If the components of Q and K are drawn from distributions with variance 1, the dot product will have variance d_k. For typical embedding dimensions of 64, 128, or 512, this means scores can be very large.
The Saturation Problem
The softmax function is ex / Σex. When one input is much larger than the others, ex for that input swamps all the others, and softmax outputs something close to [0, 0, ..., 1, ..., 0]. The gradient of softmax at saturation is nearly zero — the model receives almost no learning signal. Dividing by √d_k keeps the typical score magnitude around 1, regardless of embedding dimension, which keeps softmax in its informative regime.
A Worked Numeric Example
Let's compute attention by hand with small 3-dimensional vectors and a tiny 4-word sentence: "the cat chases mice".
Attention for the word "chases"
Suppose (after projection through WQ, WK, WV) we have the following query for "chases" and keys for all four words. Vectors are 3-dimensional for readability (real models use 64–128 dimensions per head).
Query for "chases":
q = [1.0, 0.5, -0.2]
Keys:
k_the = [ 0.1, 0.3, 0.9]
k_cat = [ 0.9, 0.4, -0.1]
k_chases = [ 1.0, 0.5, -0.2] (itself)
k_mice = [ 0.7, -0.2, 0.3]
Step 1 — Raw dot products (q · ki):
score_the = (1.0)(0.1) + (0.5)(0.3) + (-0.2)(0.9) = 0.10 + 0.15 - 0.18 = 0.07
score_cat = (1.0)(0.9) + (0.5)(0.4) + (-0.2)(-0.1) = 0.90 + 0.20 + 0.02 = 1.12
score_chases = (1.0)(1.0) + (0.5)(0.5) + (-0.2)(-0.2) = 1.00 + 0.25 + 0.04 = 1.29
score_mice = (1.0)(0.7) + (0.5)(-0.2) + (-0.2)(0.3) = 0.70 - 0.10 - 0.06 = 0.54
Step 2 — Scale by 1/√3 ≈ 0.577:
scaled = [0.040, 0.647, 0.745, 0.312]
Step 3 — Softmax:
e^0.040 = 1.041, e^0.647 = 1.910, e^0.745 = 2.106, e^0.312 = 1.366
sum = 6.423
weights = [0.162, 0.297, 0.328, 0.213]
Interpretation: "chases" attends most strongly to itself (0.328) and to "cat" (0.297) — the subject doing the chasing — and least to "the" (0.162).
Step 4 — Weighted sum of values:
output = 0.162 · v_the + 0.297 · v_cat + 0.328 · v_chases + 0.213 · v_mice
The output vector for "chases" is now enriched with context from "cat" and "mice" — the subject and object of the action — exactly the words a verb needs to know about.
The Attention Score Matrix
Running this process for every query word in parallel produces a full n × n score matrix. Row i shows how word i distributes attention across all positions. The diagonal (a word attending to itself) is often strong, but the interesting signal is in the off-diagonal entries — cross-word attention.
What Softmax Actually Does
It's worth pausing on the softmax function since it's the heart of the attention distribution.
Given a vector of scores z = [z₁, z₂, ..., zₙ], softmax converts them to probabilities:
softmax(z)ᵢ = e^(zᵢ) / Σⱼ e^(zⱼ)
Two properties matter here. First, all outputs are positive and sum to 1 — it's a valid probability distribution. Second, softmax is sharp: a score difference of 2 or 3 leads to one output dominating the others due to the exponential. This is desirable — we want the model to focus, not spread attention equally across all words all the time.
When you read an attention heatmap and see one cell glowing bright while the rest of the row is dark, you're seeing softmax doing its job.
Everything in Parallel
The beautiful thing about this formulation is that Q, K, and V are entire matrices — we compute all queries and all keys at once. The n × n score matrix Q·Kᵀ is one matrix multiplication. The final output is another matrix multiplication. All n positions are processed in parallel with no sequential dependencies.
Compare this to an RNN: to compute the output at position 8, you must first finish positions 1 through 7. Attention has no such constraint. On a GPU with thousands of cores, the whole sequence is processed in roughly the same time regardless of length (up to memory limits). This is a large part of why Transformers train so much faster than RNNs.
Key Takeaways
- RNNs struggle with long-range dependencies because information must travel through every intermediate step, and gradients vanish over long chains.
- Attention lets every position look directly at every other position in a single step, eliminating the sequential bottleneck.
- Each token produces three vectors — Query (what it's looking for), Key (what it offers), Value (what it contributes) — via learned linear projections.
- Scores are dot products of queries with keys, scaled by 1/√d_k to prevent softmax saturation, then normalized with softmax.
- The output at each position is a weighted sum of all value vectors, weighted by the attention distribution.
- The full computation is two matrix multiplications — entirely parallel, with no sequential dependency on sequence length.
Try It — Attention Heatmap
Enter a sentence below and click Compute Attention to see a simulated attention matrix. The weights are generated using positional proximity and simple syntactic heuristics (pronouns attend to nouns, articles attend to the following word), plus a touch of noise for realism. Click any row label to highlight that word's full attention pattern.
A single attention head is powerful, but it can only learn one way of relating tokens at a time. A verb might want to find its subject for one purpose and its object for another. The next article looks at how multi-head attention runs several attention operations in parallel — each free to specialize in a different kind of relationship — and combines the results.