Take the sentence “I like cats a lot.” To understand like, it helps to know who does the liking (I) and what is liked (cats). Self-attention is the mechanism that lets each word gather this kind of information from the rest of the sentence: every word builds a new vector as a weighted average of information from all words, with weights that it computes itself.
This reading walks through exactly how those weights are computed: queries, keys, and values; dot-product scores; scaling and softmax; the weighted sum; and finally the compact matrix form that makes self-attention fast.
1Attention: query, keys, values
Attention, in its general form, has three ingredients:
- a query $q$: the vector that is “asking” for information;
- a set of keys $k_1,\dots,k_n$: one per item, used to decide how well each item matches the query;
- a set of values $v_1,\dots,v_n$: one per item, the information that actually gets passed on.
The computation has three steps:
$$\underbrace{\alpha_i = k_i^\top q}_{\text{attention scores}}\qquad \underbrace{\hat\alpha_i = \frac{\exp(\alpha_i)}{\sum_{j=1}^{n}\exp(\alpha_j)}}_{\text{normalized scores (softmax over } i)}\qquad \underbrace{z = \sum_{i=1}^{n}\hat\alpha_i\, v_i}_{\text{weighted sum of values}}$$The weights $\hat\alpha_i$ are all positive and sum to 1, so the output $z$ is a weighted average of the values: items whose keys match the query well contribute more.
2From attention to self-attention
Self-attention is attention from a sequence to itself: the queries, keys, and values all come from the same sequence of word vectors $x_1,\dots,x_n$. Every word plays all three roles at once:
- as a query, it asks: what am I looking for?
- as a key, it answers: how should others match me?
- as a value, it provides: what do I pass on if someone attends to me?
An analogy: searching a library. The query is your search request. The key is each book's title and tags, used to decide what matches. The value is the book's content, which is what you take home.
Each word gets its three vectors by multiplying its word vector by three learned matrices, shared by all positions:
$$q_i = W^Q x_i,\qquad k_i = W^K x_i,\qquad v_i = W^V x_i.$$If $x_i\in\mathbb{R}^{d}$ and the queries and keys have dimension $d_k$, then $W^Q, W^K \in \mathbb{R}^{d_k\times d}$. The values have dimension $d_v$ (often equal to $d_k$), so $W^V\in\mathbb{R}^{d_v\times d}$.
Why not just use $x_i$ for all three?
If we skipped the matrices and set $q_i=k_i=v_i=x_i$, the score between words $i$ and $j$ would be $x_i^\top x_j$, which only measures how similar the two words are. A word is most similar to itself and to words like it, so it would mostly attend to those. But relevant is not the same as similar: a verb needs its subject and object, which are nouns, not other verbs. Separate learned $W^Q$ and $W^K$ let the model learn who should attend to whom, and the relation can be asymmetric. A separate $W^V$ lets a word be matched on one aspect but pass on different information.
3Computing self-attention, one word at a time
Here is the full computation for word $i$ (the query). For every word $j$ in the sentence, including $i$ itself:
- Project. Compute $q_j = W^Q x_j$, $k_j = W^K x_j$, $v_j = W^V x_j$.
- Score. Compare word $i$'s query with every key: $\;s_{i,j} = q_i\cdot k_j$.
- Scale. Divide by $\sqrt{d_k}$, the square root of the query/key dimension: $\;s_{i,j}/\sqrt{d_k}$.
- Softmax over $j$. $\;\displaystyle\hat\alpha_{i,j} = \frac{\exp(s_{i,j}/\sqrt{d_k})}{\sum_{j'=1}^{n}\exp(s_{i,j'}/\sqrt{d_k})}$, so that $\sum_j \hat\alpha_{i,j} = 1$.
- Weighted sum. $\;z_i = \sum_{j=1}^{n}\hat\alpha_{i,j}\, v_j$.
The output $z_i$ is the new, context-aware vector for word $i$. Repeating this with each word as the query gives $z_1,\dots,z_n$: one output per input word, all with dimension $d_v$.
Two things to notice in Figure 2. First, like puts most of its weight on I and cats, the words a verb most needs. Second, a has a query of $[0,0]$, so all its scores are 0 and its weights are uniform: it has no preference and simply averages everything.
4Why scale the scores?
A dot product $q\cdot k = \sum_{m=1}^{d_k} q_m k_m$ adds up $d_k$ terms. If the entries of $q$ and $k$ are roughly independent with mean 0 and variance 1, each term has variance 1, so the dot product has variance $d_k$ and a typical size of about $\sqrt{d_k}$. With $d_k=64$, scores of $\pm 8$ or more are common.
Large scores are a problem for softmax: the exponential exaggerates differences, so one weight becomes almost 1 and the rest almost 0. The word then attends to only one other word, and the gradients through softmax become tiny, which slows learning. Dividing by $\sqrt{d_k}$ brings the scores back to a typical size of about 1, no matter how large $d_k$ is.
5Matrix form
Computing one word at a time is good for understanding but slow in practice. Notice that no word's computation depends on another word's output: every $z_i$ uses only the original $q$, $k$, $v$ vectors. So all words can be computed at once with matrix multiplications, which GPUs are very good at.
Stack the word vectors as the rows of a matrix $X\in\mathbb{R}^{n\times d}$ (row $i$ is $x_i^\top$). Then the rows of $Q$, $K$, $V$ are the query, key, and value vectors:
$$Q = X W_Q,\qquad K = X W_K,\qquad V = X W_V,$$ $$\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V = Z.$$Reading the formula piece by piece:
- $QK^\top$ is an $n\times n$ matrix whose entry $(i,j)$ is $q_i\cdot k_j$: all the scores at once.
- The softmax is applied to each row separately, so row $i$ holds the weights $\hat\alpha_{i,1},\dots,\hat\alpha_{i,n}$ and sums to 1.
- Multiplying by $V$ makes row $i$ of $Z$ equal to $\sum_j \hat\alpha_{i,j} v_j^\top$, i.e., $z_i^\top$.
| Matrix | Shape | In Figure 2 |
|---|---|---|
| $X$ (input) | $n\times d$ | $5\times 3$ |
| $W_Q$, $W_K$ | $d\times d_k$ | $3\times 2$ |
| $W_V$ | $d\times d_v$ | $3\times 2$ |
| $Q$, $K$ | $n\times d_k$ | $5\times 2$ |
| $V$ | $n\times d_v$ | $5\times 2$ |
| $QK^\top$ and the attention weights | $n\times n$ | $5\times 5$ |
| $Z$ (output) | $n\times d_v$ | $5\times 2$ |
The shuffle in Figure 4 reveals an important property: if you reorder the input words, the outputs are reordered in exactly the same way, but each word's output vector does not change. Self-attention on its own sees the sentence as a set of words, not a sequence, so “dog bites man” and “man bites dog” would give bites the same output. Models that use self-attention therefore add information about each word's position to its input vector.
The $n\times n$ score matrix also shows the cost: the number of scores grows with the square of the sentence length. Doubling the length means four times as many scores.
6Summary
- Attention compares a query with keys to get weights, then returns a weighted sum of values.
- In self-attention, queries, keys, and values all come from the same sequence, via learned matrices: $q_i=W^Qx_i$, $k_i=W^Kx_i$, $v_i=W^Vx_i$.
- For word $i$: scores $q_i\cdot k_j$, divide by $\sqrt{d_k}$, softmax over $j$, then $z_i=\sum_j\hat\alpha_{i,j}v_j$.
- Scaling by $\sqrt{d_k}$ keeps the scores from growing with dimension, so the softmax does not saturate.
- In matrix form, $Z=\text{softmax}(QK^\top/\sqrt{d_k})\,V$ computes every word's output in parallel.
- Self-attention ignores word order on its own, and its cost grows with $n^2$.
7Practice
Exercise 1: compute by hand
A query $q=[1,0]$ attends to three words with keys $k_1=[1,0]$, $k_2=[0,1]$, $k_3=[1,1]$ and values $v_1=[2,0]$, $v_2=[0,2]$, $v_3=[2,2]$. Suppose $d_k=4$ (so divide by 2). Compute the weights and the output $z$. (Use $e^{0.5}\approx 1.65$.)
$z \approx 0.38[2,0]+0.23[0,2]+0.38[2,2] = [1.53,\,1.23]$.
Exercise 2: shapes
A sentence has $n=10$ words with $d=512$, and $d_k=d_v=64$. Give the shapes of $W_Q$, $Q$, $QK^\top$, and $Z$. How many learnable parameters do $W_Q$, $W_K$, $W_V$ have in total?
Parameters: $3\times 512\times 64 = 98{,}304$. Note that this does not depend on $n$: the same matrices are used at every position.
Exercise 3: scaling
If the entries of $q$ and $k$ have mean 0 and variance 1, what is the typical size (standard deviation) of $q\cdot k$ when $d_k=64$? After dividing by $\sqrt{d_k}$?
Quick quiz
8Further reading
- Alammar. The Illustrated Transformer. (See the sections “Self-Attention in Detail” and “Matrix Calculation of Self-Attention”.)
- 3Blue1Brown. Attention in Transformers, Visually Explained. (A visual explanation of queries, keys, values, and the attention pattern.)
- Jurafsky & Martin. Speech and Language Processing (3rd ed. draft), chapter on Transformers, section on self-attention.
- Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser & Polosukhin (2017). Attention Is All You Need. NeurIPS. (Section 3.2 defines scaled dot-product attention.)