Fall 2026
  • Discord
  • Gradescope
  • Syllabus
  • Spring 2026

On this page

  • Queries, Keys, and Values
  • Score Scaling
  • Permutation Equivariance

Self-Attention

A convolution combines nearby inputs using the same weights at every position. In a sentence, the relevant word might be far away, and which word matters depends on the sentence. To interpret “it,” for example, we may need to connect it to an object mentioned earlier. We’d like the network to choose which representations to combine from the current input.

Self-attention does this by comparing every token with the other tokens. It turns the comparisons into weights and uses them to form a new embedding at each position. The learned parameters determine how to make the comparisons, while the input determines the weights for this particular sequence.

How does attention choose which tokens contribute to an output?


We’ll construct those weights from inner products, explain their scaling, and see what information this operation still leaves out.

Queries, Keys, and Values

A tokenizer turns a sequence into token identities, and a learned embedding table turns those identities into vectors \(\mathbf x_1,\ldots,\mathbf x_n\in\mathbb R^d\). Stack them as the rows of \(\mathbf X\in\mathbb R^{n\times d}\). At this first layer, each row describes one token without using the others. Later layers can apply the same operation to embeddings that already contain context.

Each token produces three vectors through shared learned projections: \(\mathbf q_i,\mathbf k_i\in\mathbb R^{d_k}\) and \(\mathbf v_i\in\mathbb R^{d_v}\). The query represents what this position will compare against. Each key supplies a representation for that comparison, and its corresponding value supplies the information to combine. We learn separate maps because being useful to a query and deciding what information to pass along are different tasks. Queries and keys need the same dimension for comparison, while values may have a different dimension.

These names describe the roles of learned vectors. We do not assign a query a rule such as “find the subject.” Training adjusts the projections so that the resulting combinations help with the model’s loss.

For query position \(i\in\{1,\ldots,n\}\), compare it with each key position \(j\in\{1,\ldots,n\}\) by a scaled inner product, \[ s_{ij}=\frac{\langle\mathbf q_i,\mathbf k_j\rangle}{\sqrt{d_k}}. \] As in contrastive learning, an inner product measures a match. Here we do not require unit vectors, so the score depends on their lengths as well as their angle. We will explain the factor \(\sqrt{d_k}\) in the next section.

Softmax across \(j\) turns arbitrary scores into nonnegative attention weights that sum to one, \[ a_{ij}=\frac{e^{s_{ij}}}{\sum_{k=1}^n e^{s_{ik}}}, \] and the output is the weighted value sum \[ \mathbf o_i=\sum_{j=1}^n a_{ij}\mathbf v_j. \] The output has the same dimension as a value vector. It is a weighted average of the values because the weights are nonnegative and sum to one. A high score makes a value contribute more, but the value’s coordinates determine what it contributes.

The figure uses fixed illustrative vectors. Changing their order moves each token’s query, key, and value together.

A query scores every key, softmax normalizes the scores, and those probabilities weight the value vectors. Reordering all token representations together preserves the corresponding output.

For all tokens together, collect the projected vectors in row-stacked matrices: \[ \mathbf Q=\mathbf X\mathbf W_Q,\qquad \mathbf K=\mathbf X\mathbf W_K,\qquad \mathbf V=\mathbf X\mathbf W_V, \] where \(\mathbf W_Q,\mathbf W_K\in\mathbb R^{d\times d_k}\) and \(\mathbf W_V\in\mathbb R^{d\times d_v}\). The projections are shared across positions, but the mixing weights are recomputed from the current input.

All rows together give the standard formula \[ \operatorname{Attention}(\mathbf X) =\operatorname{softmax}\!\left( \frac{\mathbf Q\mathbf K^\top}{\sqrt{d_k}} \right)\mathbf V, \] where softmax acts row by row. Every output can use every value in one layer, regardless of distance.

The score matrix \(\mathbf Q\mathbf K^\top\) is \(n\times n\), with one query-key comparison per entry. Softmax makes each row a distribution, and multiplication by \(\mathbf V\) produces \(n\times d_v\) outputs. Attention is therefore a data-dependent mixing matrix applied to the input’s values.

This is a nonlinear operation on \(\mathbf X\), even though the query, key, and value projections are linear. Changing an input changes both the values and the weights used to combine them. Backpropagation passes through both routes, learning the projections together.

Computing all pairwise comparisons has a cost: the score matrix has \(n^2\) entries. Attention allows distant tokens to interact in one layer, but the work of these comparisons grows quadratically with sequence length at fixed head width.

The weights specify each value vector’s contribution to this layer’s sum. Explaining their effect on the final output also requires accounting for later layers and residual paths.

Score Scaling

We would like increasing the head width to give us more coordinates for a comparison without automatically making softmax more decisive. But an unscaled dot product adds more terms as the width grows.

To estimate the effect, suppose all coordinates of a query and key are independent, with mean zero and variance one. This is a simplified model of initialization, not an assumption about trained representations. Under this model, we can calculate the score variance exactly.

Claim: Under these assumptions, the unscaled dot product has mean zero and variance \(d_k\), while division by \(\sqrt{d_k}\) gives variance one.

Proof

For \(\mathbf q,\mathbf k\in\mathbb R^{d_k}\), write the dot product as \[ \langle\mathbf q,\mathbf k\rangle=\sum_{j=1}^{d_k}q_jk_j. \] For each coordinate \(j=1,\ldots,d_k\), let \(Z_j=q_jk_j\). Independence of \(q_j\) and \(k_j\) gives \[ \mathbb E[Z_j]=\mathbb E[q_j]\mathbb E[k_j]=0 \] and \[ \operatorname{Var}(Z_j) =\mathbb E[q_j^2k_j^2]-\mathbb E[Z_j]^2 =\mathbb E[q_j^2]\mathbb E[k_j^2]=1. \] For \(j\ne k\), the coordinate pairs are independent, so \(\operatorname{Cov}(Z_j,Z_k)=0\). The variance-of-a-sum identity therefore gives \[ \mathbb E[\langle\mathbf q,\mathbf k\rangle]=0, \qquad \operatorname{Var}(\langle\mathbf q,\mathbf k\rangle) =\sum_{j=1}^{d_k}\operatorname{Var}(Z_j)=d_k. \] Finally, variance scales quadratically with a constant, so \[ \operatorname{Var}\!\left( \frac{\langle\mathbf q,\mathbf k\rangle}{\sqrt{d_k}} \right) =\frac1{d_k}\operatorname{Var}(\langle\mathbf q,\mathbf k\rangle)=1. \] This proves the score-scale statements using only the earlier sum rule.

The typical unscaled score magnitude therefore grows like \(\sqrt{d_k}\).

Unscaled dot-product scores grow with head width, while scaled scores remain at a stable scale.

Large score gaps can make softmax nearly one-hot before the model has learned useful comparisons. Recall that \(\partial a_{ij}/\partial s_{ij}=a_{ij}(1-a_{ij})\). This derivative is small when the weight is close to either zero or one, making the weighted average less responsive to changes in those scores.

Dividing by \(\sqrt{d_k}\) keeps score variance at one under our initialization model. It gives different head widths a comparable starting scale. Training can still produce sharp attention when that helps the task.

Permutation Equivariance

The construction compares content, but none of the projections receives a position. Moving a token to another place moves its query, key, and value together. Its comparisons are therefore the same comparisons in a different order.

We saw a related property for convolution: shifting the input shifts the output. Content-only attention has a stronger symmetry. We can reorder the inputs in any way, and the outputs follow the same reordering.

Claim: For every permutation matrix \(\mathbf P\in\mathbb R^{n\times n}\), content-only self-attention is permutation-equivariant: \[ \operatorname{Attention}(\mathbf P\mathbf X) =\mathbf P\operatorname{Attention}(\mathbf X). \]

Proof

Write \(\mathbf X'=\mathbf P\mathbf X\), and let \(\rho\) be the permutation of \(\{1,\ldots,n\}\) such that \(\mathbf x'_i=\mathbf x_{\rho(i)}\). Shared projections permute each token’s query, key, and value together, so \(s'_{ij}=s_{\rho(i),\rho(j)}\) and \(\mathbf v'_j=\mathbf v_{\rho(j)}\). For \(i,j\in\{1,\ldots,n\}\), softmax gives \[ a'_{ij} =\frac{e^{s_{\rho(i),\rho(j)}}} {\sum_{k=1}^n e^{s_{\rho(i),\rho(k)}}} =a_{\rho(i),\rho(j)}, \] because the denominator contains the same terms in a different order. Reindexing the weighted value sum by \(k=\rho(j)\) now gives \[ \mathbf o'_i=\sum_{j=1}^n a_{\rho(i),\rho(j)}\mathbf v_{\rho(j)}=\sum_{k=1}^n a_{\rho(i),k}\mathbf v_k=\mathbf o_{\rho(i)}. \] Thus each token receives the same weighted combination after reordering. This proves permutation equivariance.

If we reverse the tokens, the output associated with a particular token is unchanged and moves to that token’s new position. That is useful when the input is a set. For language, it leaves out a distinction we need: “dog bites man” and “man bites dog” use the same words in different roles.

The result assumes that we supply no position information and allow all pairs to interact. A position-dependent mask changes which pairs are available, and positional embeddings change their comparisons. We will use both when building a language model.

Attention chooses contributors by comparing learned queries and keys, then averages the associated values. This gives each token a representation informed by the others. We can now use those contextual embeddings to predict what comes next.