Understanding Attention

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.

Make one token the query

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

Why Attention Appeared

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.

Squeeze a sentence, then let it breathe

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.

6
2

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.

The road

  1. One query, many keys: score, weight, mix, by hand.
  2. Q, K, V and their shapes: three projections and an L × S grid.
  3. Why divide by √dk: the hero's scale toggle.
  4. Masks: the hero's causal toggle, and why the mask goes before softmax.
  5. Every number: one causal head on three tokens.
  6. Self, cross and many heads: where Q, K, V come from, and what heads cost.
  7. Position and decoding: RoPE, prefill and decode.
  8. The KV cache: its size, and MQA, GQA and MLA.
  9. Quadratic and FlashAttention: exact attention with less memory traffic.
  10. Field guide: terms, traps, the code, where to go next.
What did attention add to the 2014 encoder-decoder?

Chapter 1

One Query, Many Keys

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:

  1. Score. Take the dot product of q with each key kj. Divide by √dk, where dk is the length of q and k. Chapter 3 explains the divide.
  2. Weight. Softmax turns the scores into weights aj that are positive and add to 1.
  3. Mix. Add the values, each times its weight. The sum is the output o.
score sj = q · kj / √dk   →   weight aj = softmax(s)j   →   output o
Say it aloud

O equals the sum over j of a-j times v-j.

o
o the output: a vector the same length as a value.
Σj
the sum over j one term for each key-value pair j.
aj
a-j the weight of pair j: the softmax of the scores. From 0 to 1, and all of them add to 1.
vj
v-j the value vector of pair j.
In plain words

Multiply each value v-j by its weight a-j. Add the results. The sum o is a weighted average of the values.

With numbers

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].

Move the query, watch the mix move

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.

1.00
1.00
1.0

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.

You change only v2. What happens?

Chapter 2

Where Q, K and V Come From, and Their Shapes

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:

Q = X WQ    K = X WK    V = X WV

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:

TensorShapeWhy
QL × dkone query row per query position
K, VS × dk, S × dvone key and one value per source position
QKTL × Swe transpose K so the dk sides meet; one score per pair
weights AL × Ssoftmax keeps the shape
output AVL × dvthe S side cancels; one value-width row per query

Change L and S, watch the grid

Each box is one tensor of one head, drawn to scale. Pick a preset, then drag L to 1.

6
6

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.

One new token attends over a 4,000 token prefix in a model with 32 query heads of width 128. What is the score tensor's shape for one sequence?

Chapter 3

Why Divide by √dk

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".

Say it aloud

The variance of q dot k equals d-k.

Var
the variance of the average squared distance from the mean, over many random draws.
q
q a query with dk random parts, each with mean 0 and variance 1.
k
k a key built the same way, independent of q.
dk
d-k the head width: how many numbers are in q and in k.
In plain words

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.

With numbers

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.

gradient of a weight on its own score = a(1 − a):   0.9988 × 0.0012 = 0.0012   vs   0.472 × 0.528 = 0.249, about 213 times larger

Sample dot products at any width

Hollow bars are raw scores. Solid bars are the same scores divided by √dk. Drag the width and watch only the hollow ones spread.

64

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.

Why does the Transformer divide scores by √dk?

Chapter 4

Masks Decide Which Pairs Count

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.

Say it aloud

A equals the row softmax of Q K-transpose over root d-k, plus M.

A
A the weights: L × S, each row adds to 1.
softmaxrow
row softmax e to each entry, divided by the sum of e to every entry in the same row.
QKT
Q K-transpose every query dotted with every key: the L × S scores.
√dk
root d-k the square root of the head width.
M
M the mask: 0 for an allowed pair, minus infinity for a forbidden one.
In plain words

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.

With numbers

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.

Paint a mask, check the row sums

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.

MaskRulePurpose
Causalkey j ≤ query icorrect next-token training
Paddingkey inside the real sequencebatches of mixed lengths
Local window|i − j| ≤ wless 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.

A colleague runs softmax, then sets the forbidden weights to 0 and does not renormalize. What happens?

Chapter 5

The Worked Example, Every Number

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:

Say it aloud

O equals the softmax of Q K-transpose over root d-k plus M, times V.

O
O the output: one value-width row per query, L × dv.
softmax
softmax taken along each row, over the keys.
QKT
Q K-transpose all query-key dot products.
√dk
root d-k here √2 = 1.414.
M
M the causal mask: minus infinity above the diagonal.
V
V the values, one row per key.
In plain words

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.

With numbers

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.

Step through one head

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.

With row 3's weights [0.2483, 0.2483, 0.5035] and V above, what is the first coordinate of output row 3?

Chapter 6

Self, Cross and Many Heads

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.

Say it aloud

MHA equals the concatenation of head-one through head-H, times W-O.

MHA
M-H-A the multi-head layer's output, L × dmodel.
Concat
the concatenation of the head outputs laid side by side along the feature axis.
headh
head-h one attention run with its own projections: an L × dv output.
WO
W-O the output matrix, dmodel × dmodel. The one place the heads mix.
In plain words

Run H small attentions. Put their outputs next to each other. Multiply by W-O so each output feature can draw on every head.

With numbers

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.

Split 512 into heads, count the cost

dmodel stays 512. Drag the head count and watch which bar moves.

8
512

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).

dmodel = 512. You change H from 8 to 16. What happens?

Chapter 7

Position, Then Prefill and Decode

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 θ.

Say it aloud

R-m q dot R-n k equals q dot R n-minus-m k.

Rmq
R-m q the query turned by m × θ, for a query at position m.
Rnk
R-n k the key turned by n × θ, for a key at position n.
q
q the query before turning: two numbers in this toy.
Rn−m
R n-minus-m one turn by the gap between the two positions.
k
k the key before turning.
In plain words

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.

With numbers

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.

Move both positions, keep the gap

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.

2
1
30°

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:

PrefillDecode
Queries per callthe whole prompt1 new token
Past K and Vcomputed nowread from the cache
Bound bymatrix multiply speedmemory reads of weights and cache
Shows up astime to first tokentime 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).

With RoPE, a query at 10 and a key at 8 give score 0.6. What does a query at 25 and a key at 23 give, same vectors?

Chapter 8

The KV Cache and Shared Heads

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.

Say it aloud

Bytes per token equals two, times n-layers, times H-k-v, times d-h, times b.

bytes/token
bytes per token the cache added by one more token of context.
2
two one key and one value.
nlayers
n-layers every attention layer keeps its own cache.
Hkv
H-k-v the key-value heads, not the query heads.
dh
d-h the width of one head.
b
b bytes per number: 2 for 16-bit floats.
In plain words

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.

With numbers

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.

Size the cache, then share heads

Each line is cache size against context. Pick how many KV heads the 32 query heads share, then drag the context.

8,192

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.

32 query heads, 8 KV heads, 32 layers, dh = 128, 2-byte numbers. Cache per token?

Chapter 9

What "Quadratic" Means, and FlashAttention

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.

CostWhat it countsNaive attention
Workmultiply-addsgrows with n2
Memorythe stored n × n score gridgrows with n2
Trafficbytes 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'.

Say it aloud

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.

l'
l-prime the running total after this tile.
l
l the running total before this tile, measured against the old maximum m.
em − m'
e to the m minus m-prime the correction: 1 if the maximum did not grow, smaller if it did.
Σj ∈ tile
the sum over j in the tile one term for each key in the new tile.
sj − m'
s-j minus m-prime a new score, measured against the new maximum m'.
In plain words

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 numbers

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.

Materialize, or tile

Pick a strategy and press Play. Three counters track work, peak score memory and score traffic. Only two of them change.

4,096

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.

Which pair of statements about FlashAttention is right?

Chapter 10

Field Guide

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.

TermMeaningNumber to remember
Scoreq · k / √dk, before softmaxraw SD √dk: 8 at dk = 64
Weights Arow softmax of the masked scoreseach row adds to 1
ShapesQKT is L × S, output L × dvdecode: L = 1
Causal maskminus infinity on future keys, before softmaxzero after softmax lost 40% in Ch 4
Multi-headH narrow heads, joined, mixed by WO512 = 8 × 64 in the base Transformer
RoPEturn q and k by positionscore depends on the gap only
KV cachestored past keys and values2 × layers × Hkv × dh × bytes
GQA, MQA, MLAfewer KV heads, or a compressed cache8 of 32 heads: 4 times smaller
FlashAttentionexact attention, tiled, running softmaxsame n2 work, no stored grid

The checklist: six steps, six bugs

  1. Project X into Q, K, V. Bug: Q and K of different widths.
  2. Compare with QKT. Bug: a missing transpose that still runs on square inputs.
  3. Scale by 1/√dk of the head width. Bug: saturated rows.
  4. Mask before softmax, with the library's alignment when L ≠ S. Bug: future leaks or NaN rows.
  5. Softmax over the key axis. Bug: softmax over queries, rows that do not add to 1.
  6. Mix with AV, then WO. Bug: returning the weights as the output.

The production call

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)

Are attention weights explanations?

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.

Keep going

The takeaway. Score, scale, mask, softmax by rows, mix. Count shapes as L × S, size caches with Hkv, and keep work, memory and traffic apart.

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.

References

  1. Bahdanau, Cho, Bengio. Neural Machine Translation by Jointly Learning to Align and Translate. 2014. arXiv:1409.0473
  2. Vaswani et al. Attention Is All You Need. NeurIPS 2017. arXiv:1706.03762
  3. Shazeer. Fast Transformer Decoding: One Write-Head is All You Need. 2019. arXiv:1911.02150
  4. Beltagy, Peters, Cohan. Longformer. 2020. arXiv:2004.05150; Zaheer et al. Big Bird. 2020. arXiv:2007.14062
  5. Su et al. RoFormer: Rotary Position Embedding. 2021. arXiv:2104.09864
  6. Dao et al. FlashAttention. 2022. arXiv:2205.14135; Dao. FlashAttention-2. 2023. arXiv:2307.08691
  7. Ainslie et al. GQA. 2023. arXiv:2305.13245
  8. DeepSeek-AI. DeepSeek-V2. 2024. arXiv:2405.04434
  9. Zadouri et al. FlashAttention-4. 2026. arXiv:2603.05451
  10. Jain, Wallace. Attention is not Explanation. NAACL 2019; Wiegreffe, Pinter. Attention is not not Explanation. EMNLP 2019.

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.

An attention layer's output rows have length equal to the number of keys. Which checklist step went wrong?
Understanding Attention
Attention Is All You Need · FlashAttention · Back to Gleams