Skip to content

MLDay 41 of 50Deep Learning

Self-Attention from Scratch

7 min read

In "the river bank" and "the bank loan", an embedding table gives "bank" the same vector both times. A reader knows the two banks apart from the words around them. Self-attention gives a model that skill: each word's vector changes with its neighbours.

The idea

Self-attention rebuilds every token's vector as a weighted mix of all the tokens in the sequence, including itself. The weights say how relevant each token is. Each token gets three vectors, each made from its embedding (D40) by its own learned layer:

  • a query: what this token is looking for;
  • a key: what this token offers, to be matched against queries;
  • a value: what this token passes on when it's picked.

For one token, attention takes three steps:

  1. Score. Take the dot product of its query with every key: multiply matching entries and add them up. A big score means a good match.
  2. Weigh. Divide the scores by dk\sqrt{d_k}, the square root of the query length (the formula explains why), then softmax them (D33) into attention weights: all positive, adding up to 1.
  3. Mix. Add up the values, each times its weight. The total is the token's new vector.

Every token does this at once, so a 3-token sentence has 3 × 3 weights. Attention alone ignores word order; real models also add a position signal to each embedding, which this lesson leaves out.

A tiny example

Take "the river bank", with queries and keys of length 4 and values of length 2. Think of a value's two entries as (water, money). "The" means little, so its value is (0, 0). "River" is (1, 0). "Bank" alone is a coin flip, (0.5, 0.5). Here is the row for "bank", whose query is (1, 1, 0, 0):

Token Key Score q⋅kq \cdot k ÷ 2 escoree^{\text{score}} Weight Value
the (0, 0, 1, 0) 0 0 1.00 1.00 / 11.11 = 0.090 (0, 0)
river (2, 2, 0, 0) 4 2 7.39 7.39 / 11.11 = 0.665 (1, 0)
bank (1, 1, 0, 0) 2 1 2.72 2.72 / 11.11 = 0.245 (0.5, 0.5)

Mix the values: 0.090⋅(0,0)+0.665⋅(1,0)+0.245⋅(0.5,0.5)≈(0.79,0.12)0.090 \cdot (0, 0) + 0.665 \cdot (1, 0) + 0.245 \cdot (0.5, 0.5) \approx (0.79, 0.12). Next to "river", "bank" now leans heavily toward water.

The formula

Stack the queries, keys and values as rows of matrices QQ, KK and VV. Then every token's new vector comes from one line:

Attn(Q,K,V)=softmax(QK⊤dk)V\text{Attn}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V
Symbol Meaning
QQ the queries, one row per token
KK the keys, one row per token
VV the values, one row per token
QK⊤QK^\top every query's dot product with every key: one row of scores per token
dkd_k the length of each query and key
softmax applied to each row, so each token's weights add up to 1

Worked: dk=4d_k = 4, so the scores are divided by 4=2\sqrt{4} = 2, and "bank"'s scores 0, 4, 2 become 0, 2, 1. Without the division, softmax gives 0.016, 0.867 and 0.117, close to picking one token.

Why dk\sqrt{d_k}? A dot product adds up dkd_k products, so longer vectors give more spread-out scores. Real models use dk=64d_k = 64 or more, where raw scores spread about 64=8\sqrt{64} = 8 times wider than one product. Softmax would then put nearly all the weight on one token, and learning stalls. Dividing by dk\sqrt{d_k} keeps the spread steady at any length.

Try it

How much does bank attend to each word?

Move the scores. Softmax turns them into probabilities: each is e to the (score ÷ 2), divided by the sum of them all, so the bars always add up to 1.

most attention on river, p = 0.665scale 2

The sliders hold the raw scores q⋅kq \cdot k from the table, and the widget divides them by 2. Set all three scores to 3: each weight becomes 0.333, so "bank" turns into the plain average of the values, D40's mean pooling. Then press Reset and set river to 0 and bank to 5: bank's own weight jumps to 0.859, and its new vector, about (0.50, 0.43), stays close to its own value (0.5, 0.5).

In code

The three steps are three lines of PyTorch. PyTorch's built-in F.scaled_dot_product_attention checks them.

# script_id: day_041_self_attention/attention
import math
import os
from pathlib import Path

import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F

tokens = ["the", "river", "bank"]
Q = torch.tensor([[0., 0, 1, 1], [1, 0, 0, 0], [1, 1, 0, 0]])  # one query per token, d_k = 4
K = torch.tensor([[0., 0, 1, 0], [2, 2, 0, 0], [1, 1, 0, 0]])  # one key per token
V = torch.tensor([[0., 0], [1, 0], [0.5, 0.5]])                # one value per token: (water, money)

scores = Q @ K.T / math.sqrt(4)          # every query against every key, halved
weights = torch.softmax(scores, dim=-1)  # each row adds up to 1
out = weights @ V                        # each token's new vector: a weighted mix of the values
print("weights:\n", weights.round(decimals=3))
print("new vectors:\n", out.round(decimals=3))
print("same as PyTorch:", torch.allclose(out, F.scaled_dot_product_attention(Q, K, V)))
weights:
 tensor([[0.4520, 0.2740, 0.2740],
        [0.1860, 0.5060, 0.3070],
        [0.0900, 0.6650, 0.2450]])
new vectors:
 tensor([[0.4110, 0.1370],
        [0.6600, 0.1540],
        [0.7880, 0.1220]])
same as PyTorch: True

The last row is "bank", matching the table. In a model, Q, K and V come from three nn.Linear layers applied to the embeddings, and training sets their weights. People inspect attention as a heatmap:

# script_id: day_041_self_attention/attention
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
w = weights.numpy()
fig, ax = plt.subplots(figsize=(6, 4))
ax.imshow(w, cmap="Blues", vmin=0, vmax=1)
for i in range(3):
    for j in range(3):
        ax.text(j, i, f"{w[i, j]:.2f}", ha="center", va="center", color="white" if w[i, j] > 0.5 else "black")
ax.set(xticks=range(3), xticklabels=tokens, yticks=range(3), yticklabels=tokens,
       xlabel="attends to (key)", ylabel="token (query)", title='"bank" attends most to "river"')
fig.tight_layout()
fig.savefig(FIG_DIR / "attention_weights.png", dpi=120)
plt.close(fig)

"bank" attends most to "river"

Each row is one token's weights, so every row adds up to 1.

Quick check

Quick check

1. Queries and keys have length d_k = 16. What are the scores divided by?

2. Which scores decide how much 'bank' takes from 'river'?

3. All of a token's scores are equal. What is its new vector?

Next

D42: Self-Supervised Learning and Foundation Models trains models like this on raw text, by hiding a word and predicting it.

Next · Day 42 · 9 minSelf-Supervised Learning and Foundation Models← Previous: Day 40 · Embeddings: Tokens as Vectors
Not tapped yet