CSCE 471 Natural Language Processing · Spring 2027

Self-Attention

Kuan-Hao Huang · Course Website

Note: This page was created with the help of AI as a supplementary reading. It may contain errors or simplifications. The lecture slides are the primary reference for this course; please refer to them first.

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.

After reading this, you should be able to describe attention in terms of queries, keys, and values · explain what makes self-attention “self” · compute $q_i$, $k_i$, $v_i$ from $x_i$ with learned matrices · compute the attention weights and output for one word by hand · explain why scores are divided by $\sqrt{d_k}$ · write self-attention in matrix form and give the shape of every matrix

1Attention: query, keys, values

Attention, in its general form, has three ingredients:

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.

Example: encoder–decoder attention. In a recurrent encoder–decoder translation model with attention, the query is the decoder's current hidden state, and the encoder hidden states $h_1,\dots,h_n$ serve as both the keys (they are compared with the query) and the values (they are averaged). Nothing forces keys and values to be the same vectors, though; the general version separates them.

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:

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.

Query word
No projections: $q=k=x$
Learned $W^Q$, $W^K$
Figure 1 (interactive). Attention weights for a toy example with 3-dimensional word vectors whose dimensions roughly mean “noun-like”, “verb-like”, and “function word”. On the left, scores are plain similarities $x_i^\top x_j/\sqrt{3}$. On the right, the learned matrices let a verb's query match noun keys and a noun's query match verb keys. Click a word to make it the query.

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:

  1. Project. Compute $q_j = W^Q x_j$, $k_j = W^K x_j$, $v_j = W^V x_j$.
  2. Score. Compare word $i$'s query with every key: $\;s_{i,j} = q_i\cdot k_j$.
  3. Scale. Divide by $\sqrt{d_k}$, the square root of the query/key dimension: $\;s_{i,j}/\sqrt{d_k}$.
  4. 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$.
  5. 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$.

Query word
Figure 2 (interactive). Self-attention on I like cats a lot with $d=3$ and $d_k=d_v=2$, using the matrices shown at the top. Pick a query word and step through the five steps; the highlighted column is the one computed in the current step.

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.

Dimension $d_k$:
Without scaling: softmax$(q\cdot k_j)$
With scaling: softmax$(q\cdot k_j/\sqrt{d_k})$
Figure 3 (interactive). One query and six keys with random entries (mean 0, variance 1). As $d_k$ grows, unscaled weights collapse onto a single key, while scaled weights stay spread out. Try $d_k=512$ and resample a few times.

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.$$
A note on conventions. With words as rows, the projection matrices act from the right, so $W_Q\in\mathbb{R}^{d\times d_k}$ is the transpose of the $W^Q$ used in $q_i = W^Q x_i$. Both describe the same computation; references differ only in whether they write vectors as columns or rows.

Reading the formula piece by piece:

MatrixShapeIn 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$
Figure 4 (interactive). The full weight matrix softmax$(QK^\top/\sqrt{d_k})$ for the example in Figure 2 (rows: queries, columns: keys), with the output $Z$ on the right. Click a row to highlight it; it matches the weights you computed step by step. Then shuffle the words.

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

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

Scores: $q\cdot k_j = 1,\,0,\,1$. Scaled: $0.5,\,0,\,0.5$. Exponentials: $1.65,\,1,\,1.65$, sum $4.30$. Weights: $\hat\alpha\approx[0.38,\,0.23,\,0.38]$.
$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?

$W_Q$: $512\times 64$. $Q$: $10\times 64$. $QK^\top$: $10\times 10$. $Z$: $10\times 64$.
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}$?

The variance is $d_k=64$, so the standard deviation is $\sqrt{64}=8$. After dividing by $\sqrt{64}=8$, the standard deviation is 1.

Quick quiz

8Further reading