Knowledge Sprint SeriesMT24 Learning

Phase 11 · Sprint 34/90 · Transformers & Vector SpacesBahdanau · Luong · Vaswani · Jain · Wiegreffe

How Attention Works

Each word asks every other word a question, then keeps a weighted average of the answers.

In short. Queries, keys and values, attention before 2017, why scores are divided by √dₖ, and why attention weights are clues rather than explanations.

Sprint 34 of 90 infographic: How Attention Works. Each word asks every other word a question, then keeps a weighted average of the answers. The full text of the image is on this page.
Full resolution2160 × 2700 PNGPhase summary

The part of the image you are reading lights up. Tap a part to jump to its text.

Fig. 1 in words

One formula, four views · GloVe vectors and random keys · same data as code 05

  1. 1 Bank looks around

    • we .04 · sat .01 · on .06 · the .06 · river .05 · bank .78
    • she .02 · took .02 · a .04 · loan .13 · from .05 · the .05 · bank .68
    • weights of “bank” · ring = to itself
  2. 2 Context moves it

    • “river” · river sentence: 2 353 → 1 475
    • “river” · loan sentence: 2 353 → 2 278
    • “loan” · loan sentence: 12 ← 52
    • “loan” · river sentence: 52 → 87
    • scale 10 · 100 · 1 000
    • rank among bank’s neighbours · left = closer
  3. 3 Why ÷ √dₖ

    • top softmax weight, 10 keys
    • dₖ 4 · var 4.0: raw 0.49 · ÷ √dₖ 0.30
    • dₖ 64 · var 63.7: raw 0.86 · ÷ √dₖ 0.32
    • dₖ 512 · var 505.5: raw 0.95 · ÷ √dₖ 0.32
    • raw · ÷ √dₖ
  4. 4 No peeking ahead

    • rows and columns 1–6 · the cells above the diagonal are crossed out
    • 21 of 36 scores kept
    • row = query · shade = weight

01 Query, Key, Value Lookup

  • Each token sends a query; every token offers a key and a value
  • Scores = query · key ÷ √dₖ; softmax turns them into weights that sum to 1
  • Output = the weighted average of the values: a soft dictionary lookup

In real models Q, K and V come from learned matrices (Vaswani et al. 2017).

02 Older Than 2017 History

  • Bahdanau et al. (2015): replace the fixed-length “bottleneck” with a soft search over the source
  • Luong, Pham & Manning (2015): simpler dot-product scores
  • Vaswani et al. (2017) dropped recurrence, kept attention

2017 made attention the engine; it did not invent it.

03 Why Divide by √dₖ Scale

  • For random q, k with unit variance, q · k has variance dₖ: my run gives 505.5 at dₖ 512
  • Large scores push softmax into “extremely small gradients” (Vaswani et al.)
  • Top weight at dₖ 512: 0.95 raw, 0.32 scaled

One square root keeps every head trainable.

04 Weights Are Clues Explain

  • Jain & Wallace (2019): weights often disagree with gradient importance; other weights give the same output
  • Wiegreffe & Pinter (2019): it “depends on one’s definition of explanation”
  • A heat map shows where mixing happened, not why

A bright cell is a clue, never a proof.

05 Try It Yourself PYTHON 3.13.16

sprint34_how_attention_works.py

import numpy as np, gensim.downloader as api
wv = api.load("glove-wiki-gigaword-50")
V, ix = wv.vectors, wv.key_to_index
E = V / np.linalg.norm(V, axis=1)[:, None]
def softmax(z):
    e = np.exp(z - z.max(-1, keepdims=True))
    return e / e.sum(-1, keepdims=True)
def attention(Q, K, Vv, mask=None):  # Vaswani et al.
    S = Q @ K.T / np.sqrt(K.shape[1])
    if mask is not None: S = np.where(mask, S, -np.inf)
    W = softmax(S)
    return W @ Vv, W
def rank(v, t):  # words closer to v than t is
    s = E @ (v / np.linalg.norm(v))
    return int((s > s[ix[t]]).sum())
b0 = V[ix["bank"]]
print("bank alone  | river", rank(b0, "river"),
      "loan", rank(b0, "loan"))
S2 = [("river", "we sat on the river bank"),
      ("loan", "she took a loan from the bank")]
for tag, s in S2:
    w = s.split(); X = V[[ix[t] for t in w]]
    Y, W = attention(X, X, X)  # Q = K = V = X
    b = w.index("bank")
    r, l = rank(Y[b], "river"), rank(Y[b], "loan")
    print(f"{tag:5} sent. | river {r} loan {l} "
          f"| self {W[b, b]:.2f}")
rng = np.random.default_rng(34)  # why divide by sqrt(dk)
for dk in [4, 64, 512]:
    q = rng.normal(size=(2000, dk))
    K = rng.normal(size=(2000, 10, dk))  # 10 keys each
    S = np.einsum("nd,ntd->nt", q, K)
    a = softmax(S).max(1).mean()  # unscaled
    z = softmax(S / np.sqrt(dk)).max(1).mean()  # scaled
    print(f"dk {dk:3}: var {S.var():5.1f} | top weight "
          f"{a:.2f} -> {z:.2f}")
M = np.tril(np.ones((6, 6), bool))  # no peeking ahead
X = rng.normal(size=(6, 8))
_, W = attention(X, X, X, M)
print("mask keeps", M.sum(), "of 36 scores")
print("token 1 sees", W[0].round(2))

Output, as printed on the image

Output printed on the image:
bank alone  | river 2353 loan 52
river sent. | river 1475 loan 87 | self 0.78
loan  sent. | river 2278 loan 12 | self 0.68
dk   4: var   4.0 | top weight 0.49 -> 0.30
dk  64: var  63.7 | top weight 0.86 -> 0.32
dk 512: var 505.5 | top weight 0.95 -> 0.32
mask keeps 21 of 36 scores
token 1 sees [1. 0. 0. 0. 0. 0.]

Run it. sprint34_how_attention_works.py · versions, data and steps

Check: 6 × 6 = 36 · 6 × 7 ÷ 2 = 21 · 505.5 ÷ 512 = 0.99 ≈ 1 · 0.95 ÷ 0.32 = 3.0× sharper · numpy 2.5.3 · gensim 4.4.0

06 General Notes Practice

  • Cost grows with n²: 6 tokens make 36 scores, 1 000 tokens make 1 000 000 per head
  • A causal mask lets token i see tokens 1…i only; decoders use it
  • Several heads attend in parallel, each with its own Q, K, V

Next: the whole layer built around attention.

07 Mini Project Hands-on

  • Put the mask on the bank sentences: does bank still move?
  • Drop the √dₖ and print the weights at dₖ 512
  • Learn WQ and WK by gradient descent on a toy copy task

Check: every row of weights sums to 1.

R Trusted Sources

  1. Bahdanau, Cho & Bengio (2015) Neural Machine Translation by Jointly Learning to Align and Translate, ICLR
  2. Luong, Pham & Manning (2015) EMNLP, 1412–1421
  3. Vaswani et al. (2017) Attention Is All You Need, NeurIPS 30
  4. Jain & Wallace (2019) Attention is not Explanation, NAACL, 3543–3556
  5. Wiegreffe & Pinter (2019) Attention is not not Explanation, EMNLP-IJCNLP, 11–20
  6. Pennington, Socher & Manning (2014) GloVe, EMNLP, 1532–1543

Cite this phase

Tahri, M. (2026). MT24 Learning — Knowledge Sprint Series, Phase 11: Transformers & Vector Spaces (Version 1.0) [Educational resource]. Zenodo. https://doi.org/10.5281/zenodo.23500512

Version DOI 10.5281/zenodo.23500512 · all versions 10.5281/zenodo.23500511 · first published 12 October 2026