Reads, Shreejal Trivedi
Series: Transformers in Vision, part 2 of 12
S. Trivedi
6 Oct 2026

Query, Key, Value — Dot-Product Attention from Scratch

  1. 1Attention Before Transformers — Score, Squash, Multiply
  2. 2Query, Key, Value — Dot-Product Attention from Scratch
  3. 3Attention Is All You Need — The Transformer, Block by Block
  4. 4Attention Meets Pixels — Windows, Axes and the First Fully Attentional Networks
  5. 5DETR — Detection as Set Prediction, No Anchors and No NMS
  6. 6An Image Is Worth 16×16 Words — ViT, Patch by Patch
  7. 7DeiT — Training a Vision Transformer on ImageNet Alone
  8. 8Swin Transformer — Windows, Shifts and a Pyramid for Dense Prediction
  9. 9Convolutions Strike Back — Was It the Attention or the Recipe?
  10. 10Masked Autoencoders — Hide 75 %, Encode the Rest
  11. 11CLIP — Learning Pictures From the Words Next to Them
  12. 12Vision Transformers Today — May 2022 to October 2026, Year by Year

Summary

Section 3.2 of the transformer paper, taken apart one token at a time: where the query, key and value come from, why the softmax is a soft lookup, why the scores are divided by √d_k, what eight heads buy for the same parameter count, and why the cost is n². After this read you can write scaled dot-product attention from memory and read an attention map.

Table of Contents

  1. 1. Three Names for the Same Input2
  2. 2. One Token, Step by Step2
  3. 3. All Tokens at Once2
  4. 4. Why Divide by √d_k?3
  5. 5. Multi-Head Attention4
  6. 6. What It Costs4
  7. 7. The Attention Map as a Picture5
  8. 8. Where the Three Roles Come From5
  9. 9. What Came Next5
  10. 10. References5
  11. 11. Connections5
TrivediInformational[Page 1]
S. TrivediOct 2026

The last read ended on a formula the non-local paper wrote in one line, y=softmax(x⊤Wθ⊤Wϕx)g(x), and called "the self-attention form" of the transformer [WANG17]. This read takes that line apart. The definition we are after is the paper's own, §3.2 of [VASW17]: "An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key."

Three steps, the same three as before: score (query · key), normalise (softmax), average (weights × values). Everything in this read is a name, a scale or a repetition of those three steps.

tokens Xkeys Kk_j = x_j W^Kscorese_ij = q_i·k_j/√d_kweightssoftmax_j(e_ij)values Vv_j = x_j W^Voutputx_1k_1W^Kα_i1v_1x_2k_2W^Kα_i2v_2x_ik_iW^Kα_iiv_ix_mk_mW^Kα_imv_mq_iW^Qthe same q_i meets every k_jsoftmax down the column, Σ_j α_ij = 1o_i
Fig. 1 One token's trip through attention. Its query q_i meets every key k_j; the scores are softmaxed down the column into weights α_ij that sum to 1; the weights average the values v_j into the output o_i.

Brush up on Attention Before Transformers — Score, Squash, Multiply first, Eq. 3 of it in particular: Bahdanau's three lines are reused below for a side-by-side. Softmax itself I assume you know; what it does to a dot product you may not, and that is Section 4.

1. Three Names for the Same Input

The paper's vocabulary is a lookup table. A dictionary takes a query, finds the one key that matches exactly, and returns its value. Attention is the soft version: every key matches a little, and what comes back is a blend of all the values, weighted by how well each key matched. The new idea compared with the last read is where the three vectors come from. In self-attention they all come from the same input X∈ℝn×dmodel, one row per token, through three different learned matrices:

Q=XWQ,K=XWK,V=XWVX∈ℝn×dmodel,WQ,WK∈ℝdmodel×dk,WV∈ℝdmodel×dv(1)
  • Query qi, one row of Q: what token i is looking for.
  • Key kj, one row of K: what token j advertises that it contains. Same width dk as the query, so the two can be dotted.
  • Value vj, one row of V: what is actually copied out if j is chosen. Width dv, which need not equal dk.

In the last read I called these "the thing being compared" and "the things being averaged". The trick that turns two things into three is that the token being averaged advertises itself with one projection (the key) and delivers itself with another (the value).

NOTE: WQ≠WK. If they were the same matrix, QK⊤ would be symmetric: "it" would match "cat" exactly as much as "cat" matches "it", and a token could not ask for something it is not. The two projections are what let "it" look for "cat" without "cat" looking back for "it".

2. One Token, Step by Step

Let's devise it for a single query i against m keys (m=n in self-attention):

eij=qi·kjdkαij=exp(eij)∑l=1mexp(eil)oi=∑j=1mαijvj(2)
  • Score. A dot product between the query and each key, divided by dk. Why the division is Section 4; park it.
  • Normalise. Softmax across the m scores: the weights are positive and sum to 1.
  • Average. The output is the weighted average of the value rows. Nothing else happens.

Now put Bahdanau's version from the last read next to it (Eqs. 5–6 of [BAHD14]):

eij=va⊤tanh(Wasi−1+Uahj)αij=exp(eij)∑k=1Txexp(eik)ci=∑j=1Txαijhj(3)

Lines two and three are identical. Only the first line changed: a one-hidden-layer MLP became a dot product, as Luong had already tried [LUON15], plus a scale. That is the whole story of "from additive to dot-product attention". The paper's reason for preferring the dot product is practical: the two "are similar in theoretical complexity", but the dot product "is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code" [VASW17].

Let's watch it on eight tokens. Pick a query row and turn the temperature:

71
Who attends to whom. Rows are queries, columns are keys, both in sentence order: the, cat, sat, on, the, mat, because, it. The marked row is the chosen query; darker is more weight. The weights are from toy embeddings and hand-picked projections, not a trained model, so read the pattern, not the digits.

In the figure, the row for "it" puts its largest weight on "cat": the pronoun's query matched the animate noun's key, because I built the toy projections to do so. Change the query index and read the other rows; turn the temperature down and every row becomes an arg-max, turn it up and every row flattens to 1/8. That knob is exactly what Section 4 is about.

3. All Tokens at Once

Stack the n queries as rows and the three lines of Eq. 2 become Eq. 1 of the paper:

Attention(Q,K,V)=softmax(QK⊤dk)V(4)
  • QK⊤∈ℝn×m holds every query's score against every key; row i is the eij of Eq. 2.
  • The softmax runs per row, so each row of the result is a probability over the keys.
  • Multiplying by V∈ℝm×dv averages the values, one output row per query: the result is n×dv.

Two matrix multiplications and a row-wise softmax. The non-local block of the last read is this exact formula on pixels, minus the dk, with Wθ,Wϕ,Wg playing WQ,WK,WV [WANG17].

TrivediInformational[Page 1]
S. TrivediOct 2026

4. Why Divide by √d_k?

The paper says it in one sentence: "for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients" [VASW17]. Footnote 4 gives the reason, and it deserves to be written out. Assume the components of q and k are independent with mean 0 and variance 1:

q·k=∑i=1dkqiki𝔼[qiki]=𝔼[qi]𝔼[ki]=0Var(qiki)=𝔼[qi2]𝔼[ki2]−0=1Var(q·k)=∑i=1dkVar(qiki)=dk⇒std(q·k)=dkVar(q·kdk)=dkdk=1(5)
  • Line 1: a score is a sum of dk terms.
  • Lines 2–3: each term has mean 0 and variance 1 (independent factors).
  • Line 4: variances of independent terms add, so the score's spread grows like dk.
  • Line 5: dividing by dk puts the spread back to 1 whatever the width.

Why does spread matter? Softmax is exp-then-normalise, so it exaggerates differences before dividing, and its derivative for a weight p is p(1−p). Take dk=64, where a raw score has std 8:

  • Two keys, raw scores 8 and 0 → softmax (0.9997, 0.0003). Scaled by 8 → scores 1 and 0 → (0.731, 0.269).
  • Four keys, raw (16, 0, 0, 0) → (0.9999997, 10⁻⁷, …). Scaled → (2, 0, 0, 0) → (0.711, 0.096, 0.096, 0.096).
  • The gradient factor p(1−p) at the top weight of the two-key case: 0.0003 raw against 0.197 scaled, almost 600× larger after scaling. That is the "extremely small gradients" sentence in numbers.

Now let the figure run the same experiment at every width, with random queries and keys:

106
Why divide by √d_k. Random queries and keys with unit-variance components. Without the scale the largest weight climbs to 1 as the vectors get wider and the entropy collapses: an arg-max before any learning. With the scale the softness stays put at every width. The marker reads off the values at one d_k.

Unscaled, the mean largest weight climbs from 0.49 at dk=4 to 0.86 at 64 and 0.97 at 1024 while the entropy collapses towards zero: the layer turns into a hard arg-max before any learning has happened. Scaled, both curves are flat at every width (0.32 and 1.93 nats for 10 keys). Temperature, if you like, is a volume knob between "ask everyone equally" and "ask only the loudest"; dk sets the knob to the same place regardless of how many dimensions are shouting.

NOTE: Footnote 4 assumes independent, zero-mean, unit-variance components. That is true at initialisation and false after training, so dk is the right scale to start from, not a law. Also, dk is the per-head key width, 64 in the base model, not dmodel=512.

The paper cites an earlier study (its ref. [3]) for the observation that additive attention beats unscaled dot-product attention at large dk [VASW17]; the scale is what closes the gap. One more thing the paper is careful about: its author notes credit Noam Shazeer with the scaled version and with multi-head attention; the dot product itself goes back to Luong [LUON15].

TrivediInformational[Page 2]
S. TrivediOct 2026

5. Multi-Head Attention

One head produces one n×n weighting and then averages the values under it. The paper's complaint (§2) is that a single head suffers "reduced effective resolution due to averaging attention-weighted positions": if "it" should look at "cat" for one reason and at "sat" for another, one softmax has to split the difference. Multi-head attention runs the formula several times in parallel, each time in a narrower slice with its own projections, so that each copy can hold a different opinion of who is relevant to whom. The paper's words: it lets the model "jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this." [VASW17]. Eight people reading the same sentence with different questions in mind, then a meeting where their notes are merged:

MultiHead(Q,K,V)=Concat(head1,…,headh)WOheadi=Attention(QWiQ,KWiK,VWiV)WiQ∈ℝdmodel×dk,WiK∈ℝdmodel×dk,WiV∈ℝdmodel×dv,WO∈ℝhdv×dmodelh=8,dk=dv=dmodel/h=64(6)
  • Each head is Eq. 4 in a 64-wide slice, with its own three projection matrices.
  • The eight 64-wide outputs are concatenated back to 512 and mixed by WO; that is the meeting.
  • What one head computes: an n×n weight matrix and an n×64 output. Eight heads give eight n×n pictures of the same sentence.
Xn × 512head 1W_i^Q W_i^K W_i^VAttention(·)head 2W_i^Q W_i^K W_i^VAttention(·)head 8W_i^Q W_i^K W_i^VAttention(·)each head: d_k = d_v = 512 / 8 = 64cconcat8 × 64 = 512W^O512 × 512outn × 5128 heads × 3 × (512 × 64) = 786,432 weights, the same as one 512-wide head
Fig. 2 Multi-head attention: the same X goes through h = 8 heads of width 64, the outputs are concatenated to 512 and mixed by W^O. The parameter count is the same as one 512-wide head.

Let's split the toy layer of Section 2 into heads. Change h and compare the slices with the full-width head on the left:

2
One sentence, several heads. Each grid is one head's 8×8 weight picture for 'the cat sat on the mat because it' (rows = queries, columns = keys, sentence order). The leftmost grid is a single head using all 16 dimensions; the others split the same 16 columns of W^Q, W^K into h slices. In the toy, slice 1 matches identical words, slice 2 sends 'it' to 'cat', slice 3 sends verbs and prepositions to nouns, slice 4 is random.

With h = 4 the slices disagree on purpose: one matches identical words, one sends "it" to "cat", one sends verbs and prepositions to nouns. The full-width head's dot products are the sums of the slices' dot products, so it can only show their average, which is the paper's complaint in one picture.

5.1 The Numbers

  • Parameters do not grow with h. 8 heads × 3 projections × (512 × 64) = 786,432, exactly 3 × 512² for one full-width head; plus WO at 512² = 262,144. Total 1,048,576 = 4dmodel2 (bias-free), for any h. The paper: "due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality" [VASW17].
  • More heads is not monotonically better. Table 3 row (A) of the paper, dev BLEU on newstest2013: h = 1 → 24.9, 4 → 25.5, 8 → 25.8, 16 → 25.8, 32 → 25.4. "Single-head attention is 0.9 BLEU worse than the best setting, quality also drops off with too many heads."
  • Narrow keys hurt. Row (B): dk = 16 → 25.1, 32 → 25.4, 64 → 25.8. "Reducing the attention key size dk hurts model quality."

NOTE: "Multi-head = more parameters" is the common misreading. Same count for any h; what changes is how many independent n × n weightings the layer can form at once.

6. What It Costs

Count the multiply-adds in Eq. 4 for n queries and m keys (Table 1 of the paper, first row):

scores QK⊤:n·m·dkmultiply-adds,average AV:n·m·dvper layer, m=n:O(n2·d);memory for the weights: h·n2(7)
  • The pairs cost n2d in compute and hn2 numbers in memory. The projections cost 4nd2 and do not depend on pairs at all.
  • A ViT-sized input, n = 196 tokens, d = 768 (the number An Image Is Worth 16×16 Words — ViT, Patch by Patch inherits): QK⊤ is 196² × 768 = 29.5 M multiply-adds, AV another 29.5 M, and the four projections 4 × 196 × 768² = 462 M. At n = 196 the projections cost 8× more than the pairs. The weight matrix is 196² = 38,416 numbers per head, × 12 heads = 1.8 MB in fp32 per image per layer.
  • At pixel resolution, n = 224² = 50,176, the same two lines give the 10 GB per head of the last read; Attention Meets Pixels — Windows, Axes and the First Fully Attentional Networks starts from that number.
Layer typeComplexity per layerSequential opsMax path lengthn = 196, d = 768n = 50,176
Self-attentionO(n² · d)O(1)O(1)29.5 M1.9 T
RecurrentO(n · d²)O(n)O(n)116 M30 G
Convolution, k = 3O(k · n · d²)O(1)O(log_k n)347 M89 G

Table. 1 The first three rows of Table 1 in [VASW17], with the per-layer term evaluated at two sequence lengths.

Self-attention is cheaper than a recurrent layer "when the sequence length n is smaller than the representation dimensionality d" (§4 of [VASW17]), and a convolution costs k times a recurrent layer again; that holds for sentences and for 14 × 14 patch grids. At 50,176 tokens the order flips completely.

NOTE: Attention has O(n²) activations and compute, not O(n²) parameters. The parameters are 4d², independent of n.

TrivediInformational[Page 3]
S. TrivediOct 2026

7. The Attention Map as a Picture

Every head's softmax(QK⊤/dk) is an n×n matrix of numbers between 0 and 1 whose rows sum to 1, so it can be drawn as a heat map, exactly like Bahdanau's alignment matrices. The paper's appendix (Figs. 3–5) draws several heads of layer 5 of the encoder. Heads attend from "making" to "more difficult", completing the phrase making … more difficult; two other heads resolve its to the noun it refers to. The toy figures above imitate this: the row for "it" lands on "cat".

NOTE: The map is the weights, not an explanation. The appendix captions say the heads are "apparently involved in" and "seem related to" those tasks. Keep the paper's hedge when you read one.

8. Where the Three Roles Come From

§3.2.3 of the paper uses the same formula in three places, and the difference is only where Q, K and V are taken from:

  • Encoder self-attention. Q,K,V all from the previous encoder layer: every token looks at every token.
  • Decoder self-attention. Same, but a token may not look at tokens after it; how those keys are hidden is in Attention Is All You Need — The Transformer, Block by Block.
  • Encoder-decoder attention. Q from the decoder, K and V from the encoder output. That is Bahdanau's cross-attention of the last read, written in Q/K/V form.

So cross-attention between two sequences and self-attention within one, the two cases the last read kept apart, are the same formula with different inputs. The formula does not know the difference.

9. What Came Next

The paper did not stop at the formula. It built a whole network out of it: eight heads, a small feed-forward layer per token, a residual connection and a normalisation around each, stacked six times in an encoder and six in a decoder, plus a trick to tell the model where each word sits, since nothing in Eq. 4 knows about order. That network, its numbers and its training recipe are Attention Is All You Need — The Transformer, Block by Block.

10. References

  1. [VASW17] Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin. Attention Is All You Need. NIPS 2017.
  2. [BAHD14] Bahdanau, Cho, Bengio. Neural Machine Translation by Jointly Learning to Align and Translate. ICLR 2015.
  3. [LUON15] Luong, Pham, Manning. Effective Approaches to Attention-based Neural Machine Translation. EMNLP 2015.
  4. [WANG17] Wang, Girshick, Gupta, He. Non-local Neural Networks. CVPR 2018.

11. Connections

What this page builds on, cites or links to, and what points back at it. A plain box is a “builds on”; “cited” and “linked in the text” are the lighter links. Hover a box for a preview.

POINTS AT THIS PAGEPAPERAttention Is All You Need — TheTransformer, Block by BlockREAD · LINKED IN THE TEXTAttention Before Transformers — Score,Squash, MultiplyREAD · LINKED IN THE TEXTAttention Meets Pixels — Windows, Axesand the First Fully Attentional NetworksREAD · LINKED IN THE TEXTConvolutions Strike Back — Was It theAttention or the Recipe?READ · LINKED IN THE TEXTVision Transformers Today — May 2022 toOctober 2026, Year by YearPAPER · LINKED IN THE TEXTAn Image Is Worth 16×16 Words — ViT,Patch by PatchPAPER · LINKED IN THE TEXTDeiT — Training a Vision Transformer onImageNet AlonePAPER · LINKED IN THE TEXTSwin Transformer — Windows, Shifts and aPyramid for Dense PredictionPAPER · LINKED IN THE TEXTMasked Autoencoders — Hide 75 %, Encodethe RestPAPER · LINKED IN THE TEXTCLIP — Learning Pictures From the WordsNext to ThemPAPER · LINKED IN THE TEXTRT-DETRv3 — More Positives WithoutPaying at InferenceThis pageTHIS PAGE POINTS ATREADAttention Before Transformers — Score,Squash, MultiplyPAPER · CITEDAttention Is All You Need — TheTransformer, Block by BlockREFERENCE · CITEDNeural Machine Translation by JointlyLearning to Align and TranslateREFERENCE · CITEDEffective Approaches to Attention-basedNeural Machine TranslationREFERENCE · CITEDNon-local Neural NetworksREAD · LINKED IN THE TEXTAttention Meets Pixels — Windows, Axesand the First Fully Attentional NetworksPAPER · LINKED IN THE TEXTAn Image Is Worth 16×16 Words — ViT,Patch by Patch

Related

Go deeper

  1. Start with
    Read
  2. Paper
  3. Paper
  4. Paper
  5. Paper
  6. Read
  7. You are here
    Query, Key, Value — Dot-Product Attention from Scratch
    Read
  8. Then
    Paper
  9. Read
  10. Paper
  11. Paper
  12. Paper
  13. Paper
  14. Read
  15. Paper
  16. Paper
  17. Read
  18. Paper
  19. Paper
  20. Paper
  21. Paper
  22. Paper
  23. Paper
  24. Paper
  25. Paper

Go broader

<- Older [Page 5] Newer ->