Each token builds its own mix of the other tokens in three steps: score every key, turn the scores into weights, mix the values. Every modern variant keeps those steps and changes what goes around them.
Tap a token to make it the query. Then turn off Divide by √64 and watch one weight swallow the row. Then we build, piece by piece, the scores, the scale, the mask, the heads, the cache and the fast kernels.
You need vectors and the dot product, matrix multiplication and a little Python. We build the rest from zero.
Illustrative toy: we made up the raw scores at the size a dk = 64 head produces, so the divisor is √64 = 8. The page computes the softmax and the mask live.
Chapter 0
See how one fixed summary vector chokes on long inputs, and how a fresh weighted mix per step fixes it
It is 2014. You translate a 50 word German sentence with a recurrent network. One network reads the German word by word and ends with a single vector. A second network writes the English from that one vector.
Every noun, clause and negation must fit in that vector. Its size was fixed before the sentence arrived. A longer sentence gets no more room. Bahdanau, Cho and Bengio named this the bottleneck: one fixed summary for an input of any length.
Drag the source length. In One vector mode, watch each word's share of 64 numbers shrink. Switch to Attention and move the output step.
Illustrative toy: we made up the 64 number vector and the weight rows. The idea of a per-step weighted mix is Bahdanau et al. (2014).
Their fix: at each output step, build a new summary. Weight every source state by how relevant it is to what the decoder needs now. A learned score sets the weights. Longer input means more states to weigh, not less room for each.
That is attention: a weighted average of vectors, where the weights come from comparing vectors. In 2017 the Transformer (Vaswani et al., "Attention Is All You Need") made one form of it, scaled dot-product attention, the main way tokens exchange information. Everything after this chapter is that form.
Failure. Symptom: translation quality drops as sentences get longer. Measure: score quality in bins of source length. Fix: give the decoder attention over all encoder states, so the interface grows with the input.
Chapter 1
Score one query against three keys, soften the scores into weights, and mix three values by hand
Forget sequences. Take one query vector q and three pairs. Each pair has a key k, which decides how much the pair counts, and a value v, which is what the pair adds to the output. Keys and values are separate vectors with separate jobs.
Three steps, in order:
O equals the sum over j of a-j times v-j.
Multiply each value v-j by its weight a-j. Add the results. The sum o is a weighted average of the values.
q = [1, 1]; keys [1, 0], [0, 1], [1, 1]; values [1, 0], [0, 2], [3, 1]; dk = 2. Dot products 1, 1, 2, divided by √2 = 1.414: scores 0.707, 0.707, 1.414. Softmax: weights 0.248, 0.248, 0.504. So o = 0.248 × [1, 0] + 0.248 × [0, 2] + 0.504 × [3, 1] = [1.759, 1.000].
Key space holds the query and three keys. Value space holds the values, and the output always stays inside their purple triangle. Drag the query, then move v3.
The keys, values and starting query are the worked example of Chapter 5. Moving v3 changes what the head mixes; moving q changes how much.
Move v3: the weights do not change, but the triangle and the output move. Move q: the triangle stays and the output slides across it. Keys decide how much. Values decide what. The weights are positive and add to 1, so one head can only blend its values. It can never leave their triangle.
Failure. Symptom: code reads the weights aj as the layer's output. Measure: print the output shape; it should be the value width, not the number of keys. Fix: return the mix o, not a.
Chapter 2
Make three learned views of the same tokens, then track every dimension through the two matrix products
Chapter 1 had one query. A real layer has a matrix X of token vectors: one row per token, dmodel columns. It multiplies X by three learned weight matrices:
WQ and WK map each row to length dk. WV maps it to length dv. So the same token has a different query, key and value in every layer and every head. "bank" does not carry a fixed query. Layer 7 makes one from what its input holds.
Now name the lengths. L is the number of queries. S is the number of keys and values. Then the shapes follow:
| Tensor | Shape | Why |
|---|---|---|
| Q | L × dk | one query row per query position |
| K, V | S × dk, S × dv | one key and one value per source position |
| QKT | L × S | we transpose K so the dk sides meet; one score per pair |
| weights A | L × S | softmax keeps the shape |
| output AV | L × dv | the S side cancels; one value-width row per query |
Each box is one tensor of one head, drawn to scale. Pick a preset, then drag L to 1.
Head width dk = dv = 4 here so the boxes fit. Real heads are often 64 or 128 wide.
Three presets cover most calls. Self-attention over one sequence has L = S. Cross-attention, a decoder reading an encoder, has unrelated L and S. Decoding one new token has L = 1 against the whole prefix: one row of S scores. That last call is the one a language model runs for every token it writes.
Real kernels add batch and head axes in front: Q is (B, H, L, dk). PyTorch's scaled_dot_product_attention expects this layout.
Failure. Symptom: the loss is wrong but nothing crashes. Measure: print the score tensor's shape. A square grid during cached decode means the code rebuilt the prefix. Fix: feed one query row against the cache.
Chapter 3
Show that raw dot products grow with head width, and that big scores freeze softmax into one winner
The Transformer does not feed QKT to softmax. It divides by √dk first. The paper gives the reason in a footnote. Assume each part of q and of k is random, with mean 0 and variance 1. How big is their dot product?
The dot product adds dk products qrkr. Each product has mean 0 and variance 1. Independent terms add their variances. Call the variance of a number "Var".
The variance of q dot k equals d-k.
Each of the d-k products adds 1 to the variance. So the typical size of a raw score, the square root of the variance, is √d-k. Divide by √d-k and the variance is back to 1 at any width.
At dk = 64 a raw score has a standard deviation of √64 = 8. At dk = 1024 it is 32. After the divide, both are 1.
Why do big scores hurt? Take four raw scores from a dk = 64 head: 8.0, 0.1, −0.3 and 0.5. Softmax gives [0.9988, 0.0004, 0.0002, 0.0006]: one winner. Divide by 8 first: scores 1.0, 0.0125, −0.0375, 0.0625, weights [0.472, 0.176, 0.167, 0.185]. The first key still wins, and the others still count.
Hollow bars are raw scores. Solid bars are the same scores divided by √dk. Drag the width and watch only the hollow ones spread.
A real Monte Carlo in your browser: 2,000 queries against 4 keys, every part drawn with mean 0 and variance 1. Top weight is the largest softmax weight in a row of 4, averaged.
We ran numpy on 20,000 rows of 4 keys. Without the divide, the mean top weight climbs from 0.65 at dk = 4 to 0.98 at dk = 1024. With the divide it stays near 0.50 to 0.52 at every width.
Failure. Symptom: a head trains as if the learning rate were tiny. Measure: the mean top weight per row; near 1 means saturation. Fix: check the scale is 1/√dk of the head width, not of dmodel.
Chapter 4
Add minus infinity to forbidden scores before softmax, and see why zeroing after softmax shrinks every output
So far every query sees every key. Often that is wrong. A language model must not see its own future. A batch must not attend to padding. All such rules work the same way: add a mask M to the scores before softmax. M holds 0 for an allowed pair and minus infinity for a forbidden one.
A equals the row softmax of Q K-transpose over root d-k, plus M.
Scale the scores. Add M, so forbidden scores become minus infinity. In each row, take e to each score and divide by the row's total. e to minus infinity is 0. So forbidden pairs get weight 0, and the allowed pairs share all of it.
Row 2 of Chapter 5 has scaled scores 0, 0.707, 0.707, and key 3 is in its future. With M: e to each is 1, 2.028, 0, total 3.028, weights [0.330, 0.670, 0].
The tempting shortcut is softmax first, then set the forbidden weight to 0. Unmasked, that row is [0.198, 0.401, 0.401]. Zero the third entry and the row sums to 0.599. The output shrinks by 40% with no error. Renormalizing fixes it, but the mask before softmax never needs the fix.
Rows are queries, columns are keys. Grey cells are the masked pairs. Pick a mask, then turn on Zero after softmax and read the right margin.
The scores are the hero's toy scores divided by 8. The page computes the weights live.
| Mask | Rule | Purpose |
|---|---|---|
| Causal | key j ≤ query i | correct next-token training |
| Padding | key inside the real sequence | batches of mixed lengths |
| Local window | |i − j| ≤ w | less work on long inputs (Longformer) |
Failure. Symptom: NaN in the outputs. Measure: look for a row where the mask hides every key. Its softmax divides 0 by 0. Fix: make sure every query keeps at least one key.
Chapter 5
Run one causal head on three tokens from the scores to the output, and check every entry yourself
Put the pieces together. This is the formula from the Transformer paper, with the mask added:
O equals the softmax of Q K-transpose over root d-k plus M, times V.
Dot every query with every key. Divide by root d-k. Add the mask M. Softmax each row into weights. Multiply the weights by V, so each output row of O is a weighted average of value rows.
Q = K = [[1, 0], [0, 1], [1, 1]], V = [[1, 0], [0, 2], [3, 1]], dk = 2. The result is O = [[1, 0], [0.330, 1.340], [1.759, 1.000]]. The device below shows each step.
The big grid is the matrix the current step makes. Press Next, and pick a row to see its arithmetic below.
Q = K is a simplification so the keys are easy to read. We checked every number with numpy to 4 places.
Read the rows. Row 1 sees only key 1, so its weight is 1 and it copies v1. In a causal model the first token always attends only to itself. Row 2 splits 0.330 and 0.670 between keys 1 and 2. Row 3 gives about half to key 3, because k3 = [1, 1] matches q3 best.
Here are the same five steps in numpy. It prints the same A and O.
pythonimport numpy as np Q = K = np.array([[1., 0.], [0., 1.], [1., 1.]]) # (L=3, d_k=2) V = np.array([[1., 0.], [0., 2.], [3., 1.]]) # (S=3, d_v=2) S = Q @ K.T / np.sqrt(Q.shape[-1]) # (3, 3) scaled scores S = np.where(np.tril(np.ones_like(S)) == 1, S, -np.inf) # causal: keep j <= i S = S - S.max(axis=-1, keepdims=True) # stable softmax, same result A = np.exp(S) / np.exp(S).sum(axis=-1, keepdims=True) # (3, 3), rows sum to 1 O = A @ V # (3, 2) print(A.round(4)) # [[1. 0. 0.] [0.3302 0.6698 0.] [0.2483 0.2483 0.5035]] print(O.round(4)) # [[1. 0.] [0.3302 1.3395] [1.7587 1.]]
Subtracting the row maximum does not change the weights, because the same factor cancels above and below. It stops ex from overflowing.
Failure. Symptom: a new kernel disagrees with your reference. Measure: run both on these three tokens. A gap in the fourth decimal is precision. A gap in the first is a mask or axis bug. Fix: compare step by step against the grid above.
Chapter 6
Choose where Q, K and V come from, then split one wide head into many narrow ones and count the cost
The formula never says Q, K and V come from the same tokens. The layer around it decides. In self-attention all three come from one sequence X. In cross-attention Q comes from a decoder sequence Y, and K and V come from an encoder's output X. A text decoder reading image patches uses cross-attention. "Causal" is a separate choice: it is a mask, so self-attention can be causal (GPT) or not (BERT).
One head learns one pattern of scores. Multi-head attention runs H heads side by side, each with its own WQ, WK, WV. It joins their outputs and mixes them with one more matrix, WO.
MHA equals the concatenation of head-one through head-H, times W-O.
Run H small attentions. Put their outputs next to each other. Multiply by W-O so each output feature can draw on every head.
The base Transformer uses dmodel = 512 and H = 8, so each head is 512 / 8 = 64 wide. Eight outputs of width 64 join into 512, and WO maps 512 to 512.
dmodel stays 512. Drag the head count and watch which bar moves.
Counts are for QKT only, one sequence, self-attention with L = S = n.
The count surprises people. With dmodel fixed, the scores of H heads cost H × n × n × (512 / H) = n × n × 512 multiply-adds for any H. The paper says this keeps the cost close to one full-width head. But there are H score grids, so score memory grows with H.
Failure. Symptom: memory runs out after raising the head count, though the FLOPs did not change. Measure: H × L × S score entries per layer. Fix: use a fused kernel that never stores the grids (Chapter 9).
Chapter 7
Rotate queries and keys so scores depend on distance, then see why training runs in parallel and writing does not
Shuffle the input tokens of plain self-attention with no mask. The outputs shuffle the same way and keep their values. Attention alone has no idea of order. The original Transformer added position vectors to the inputs. Many current language models use RoPE (rotary position embedding, Su et al.). It turns each pair of query and key numbers by an angle that grows with position.
Call the position of a query m and of a key n. Call Rm the rotation by m times a step angle θ.
R-m q dot R-n k equals q dot R n-minus-m k.
Turn q by its position m and k by its position n, then take the dot product. The two turns cancel down to one turn by the gap n − m. So the score sees how far apart the tokens are, not where they sit.
q = [1, 0], k = [0, 1], θ = 30°. The score works out to sin(30° × (m − n)). At m = 2, n = 1 it is sin 30° = 0.5. At m = 7, n = 6 it is 0.5 again.
Left: the turned query and key. Right: the score against the gap m − n. Drag m and n by the same amount and watch the score stay put.
A two-number toy. Real RoPE turns many pairs of numbers, each pair at its own angle.
Now training against writing. A language model predicts each token from the ones before it. In training the model has the whole text, so the causal mask lets all positions run in one big matrix product. In generation, token t + 1 does not exist until the model picks token t. Serving systems split the work in two phases:
| Prefill | Decode | |
|---|---|---|
| Queries per call | the whole prompt | 1 new token |
| Past K and V | computed now | read from the cache |
| Bound by | matrix multiply speed | memory reads of weights and cache |
| Shows up as | time to first token | time between tokens |
Failure. Symptom: a model that reads 4,000 tokens well fails at 32,000. Measure: quality against position past the training length. Fix: RoPE gives an angle at any position, but working there needs long-context training or a RoPE base change (see Positional Encoding).
Chapter 8
Store past keys and values instead of recomputing them, size the store, and shrink it with MQA, GQA or MLA
In a causal model, a past token's key and value never change: no later token can affect them. So each layer stores them. This store is the KV cache. Each decode step computes the new token's q, k and v, appends k and v, and lets q attend over the whole cache. The step needs no mask: the cache holds only the past.
Run Chapter 5 this way, one token at a time. Step 1 sees one key: weights [1]. Step 2 sees two: [0.330, 0.670]. Step 3 sees three: [0.248, 0.248, 0.504]. The rows match Chapter 5 exactly. The cache is exact, not an approximation.
How big is it? Name the parts: the number of layers nlayers, the key-value heads per layer Hkv, the head width dh, and the bytes per number b.
Bytes per token equals two, times n-layers, times H-k-v, times d-h, times b.
For each layer, store a key and a value for each key-value head, each d-h numbers of b bytes. Multiply it out. Then multiply by the number of tokens in context.
32 layers, 32 KV heads, dh = 128, b = 2: 2 × 32 × 32 × 128 × 2 = 524,288 bytes = 512 KiB per token. For 8,192 tokens that is 4 GiB, before any weights.
Each line is cache size against context. Pick how many KV heads the 32 query heads share, then drag the context.
32 layers, 32 query heads, dh = 128, 16-bit numbers: the shape of Llama 3 8B, which uses 8 KV heads. Keys and values only; real servers also store metadata and waste some space.
MQA (multi-query attention, Shazeer 2019) keeps many query heads but one shared key head and value head. GQA (grouped-query attention, Ainslie et al. 2023) shares each KV head within a group of query heads. Llama 3 8B and Mistral 7B both use 32 query heads and 8 KV heads: a quarter of the MHA cache.
MLA (multi-head latent attention, DeepSeek-V2) caches a compressed vector per token instead: 512 numbers, plus a 64 number key part for RoPE kept outside the compression. That is 576 numbers per layer, where its 128 heads of width 128 would need 32,768 under MHA. The paper calls this equal to GQA with 2.25 groups.
Failure. Symptom: out of memory at a context the estimate said would fit. Measure: check which head count the formula used. Fix: use Hkv, not Hq; with 32 and 8 the wrong one is off by 4 times.
Chapter 9
Separate work, memory and traffic, then compute exact attention one tile at a time with a running softmax
"Attention is quadratic" hides three different costs. For self-attention over n tokens the paper's table gives O(n2 · d) work per layer.
| Cost | What it counts | Naive attention |
|---|---|---|
| Work | multiply-adds | grows with n2 |
| Memory | the stored n × n score grid | grows with n2 |
| Traffic | bytes moved between GPU memory (HBM) and the fast on-chip memory (SRAM) | often the real limit |
At n = 4,096 one head's grid holds 16.8 million scores, 32 MiB in 16-bit floats. A naive kernel writes it to HBM, reads it back for softmax, writes the weights, and reads them again. FlashAttention (Dao et al. 2022) never stores the grid. It loads tiles of Q, K and V into SRAM and builds each output row from the tiles.
The trick is a running softmax. Softmax needs the row maximum and the row total, which you do not know until the last tile. So keep a running maximum m, a running total l, and a running weighted sum of values. When a tile brings a bigger maximum m', shrink the old totals by em − m'.
L-prime equals l times e to the m minus m-prime, plus the sum over j in the tile of e to the s-j minus m-prime.
Find the new maximum m-prime. Rescale the old total l by e to the m minus m-prime, so it uses the new maximum. Add e to each new score minus m-prime. Do the same to the weighted sum of values. At the end, divide that sum by l.
With made-up scores [1, 2 | 3, 0] in two tiles and values 10, 20, 30, 40. Tile 1: m = 2, l = e−1 + 1 = 1.368. Tile 2: m' = 3, correction e−1 = 0.368, l' = 1.368 × 0.368 + 1 + e−3 = 1.553. The output is 26.209, the same as full softmax.
Pick a strategy and press Play. Three counters track work, peak score memory and score traffic. Only two of them change.
Simplified counts for one head, d = 64, 64 × 64 tiles. Score traffic counts the grid written and read twice; the Q, K, V reads both strategies share are left out.
Later versions keep the idea and fit new chips. FlashAttention-2 split the work better across GPU threads. FlashAttention-4 (2026) targets Blackwell GPUs, where matrix units outgrew the rest, so softmax and memory pipelines became the limit.
Sparse attention is a different deal. Longformer and BigBird skip most pairs, so work falls, but some tokens can no longer see each other in one layer. FlashAttention computes every pair.
Failure. Symptom: attention got slower after adding a custom float mask. Measure: profile which kernel PyTorch picked. Fix: use is_causal=True where you can, so the fused kernel stays eligible.
Chapter 10
Keep the terms, the numbers, the six-step checklist and the production call next to the keyboard
Attention scores each allowed key against a query, scales, masks, softmaxes each row and mixes the values. Heads, RoPE, caches, shared KV heads and fast kernels change what surrounds those steps.
| Term | Meaning | Number to remember |
|---|---|---|
| Score | q · k / √dk, before softmax | raw SD √dk: 8 at dk = 64 |
| Weights A | row softmax of the masked scores | each row adds to 1 |
| Shapes | QKT is L × S, output L × dv | decode: L = 1 |
| Causal mask | minus infinity on future keys, before softmax | zero after softmax lost 40% in Ch 4 |
| Multi-head | H narrow heads, joined, mixed by WO | 512 = 8 × 64 in the base Transformer |
| RoPE | turn q and k by position | score depends on the gap only |
| KV cache | stored past keys and values | 2 × layers × Hkv × dh × bytes |
| GQA, MQA, MLA | fewer KV heads, or a compressed cache | 8 of 32 heads: 4 times smaller |
| FlashAttention | exact attention, tiled, running softmax | same n2 work, no stored grid |
pythonimport torch, torch.nn.functional as F q = k = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])[None, None] # (B=1, H=1, L=3, d=2) v = torch.tensor([[1., 0.], [0., 2.], [3., 1.]])[None, None] out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # scale defaults to 1/sqrt(d) allowed = torch.tril(torch.ones(3, 3, dtype=torch.bool)) # True = this pair takes part same = F.scaled_dot_product_attention(q, k, v, attn_mask=allowed) print(out[0, 0]) # [[1, 0], [0.3302, 1.3395], [1.7587, 1.0]], the numbers of Chapter 5 # GQA: k, v with fewer heads than q, and enable_gqa=True (recent PyTorch)
Not by themselves. Jain and Wallace (2019) found cases where different weights gave the same predictions. Wiegreffe and Pinter (2019) replied that it depends on the test. A high weight is a clue to check, not proof that a token mattered.
Now press Present or Teach and work the three-token head from memory. Then go back to the hero, turn off the divide, and say why one weight takes the whole row.
Source: this lesson started from the handbook Understanding Attention: From Q, K, V to Modern Transformer Attention by @techNmak, whose worked example, shape discipline and six-step model it keeps. The explanations, numbers and devices here are our own and checked with numpy.