Skip to main content
Open In Colab

Scaled dot-product self-attention

The simple attention mechanism compares input vectors directly. Its compatibility function has no trainable parameters, although its input embeddings may already have been learned. Consider “I love bears”, “She bears the pain” and “Bears won the game”. The word plays different grammatical and semantic roles. How can the model learn which information to exchange between tokens? We separate the problem into deciding which tokens to read from and deciding what information to retrieve from them.

Linear transformation of the input embeddings

Instead of comparing the input vectors directly, we learn three feature maps. These are not necessarily invertible changes of coordinates; they can reduce dimension and discard information. The purpose of these maps is to learn features that make contextually relevant tokens compatible, even when their original embeddings are dissimilar. We define three trainable matrices Wq,Wk,WvW^q, W^k, W^v and project each token, or equivalently the matrix XX, into three different spaces: Q=XWqK=XWkV=XWv\begin{aligned} Q &= XW^q \\ K &= XW^k \\ V &= XW^v \end{aligned} Here XX is the T×dT \times d input embedding matrix, where TT is the input sequence length and dd is the embedding dimension. QQ, KK and VV hold the queries, keys and values. The matrices Wq,Wk,WvW^q, W^k, W^v have dimensions d×dqd \times d_q, d×dkd \times d_k and d×dvd \times d_v. Queries and keys live in a space of the same dimension, so dq=dkd_q = d_k. For token ii, the query qiq_i is used to compare against keys kjk_j from all allowed positions. The value vjv_j is the information contributed by position jj. A large query-key dot product gives a larger relative weight, all else equal. It is not necessarily a small Euclidean distance. Consider “I love bears”. The words love and bears are not semantically similar, but they participate in a verb-object relationship. Imagine a head whose query features express a request for a governing verb and whose key features indicate the ability to supply that information. The query of bears and the key of love could then align in the query-key space, even if their original embeddings were nearly orthogonal. In “She bears the pain”, a different pattern could be useful: the verb bears can receive information from its subject She or, in bidirectional attention, its object pain. These are linguistic analogies for learned features, not a claim that individual coordinates are labeled with grammatical roles. A head may learn such relationships through training, without explicit grammatical supervision. The value projection determines which features of the matched token are actually passed on.

Moving the weight off the token itself

In the simple mechanism a token usually puts most of its weight on itself, because its score with itself is its squared norm. The query and key maps can change that. Take three orthogonal unit embeddings for I, love and bears. Under simple attention, bears has a score of 0 with love and a score of 1 with itself. The two maps below send the query of bears and the key of love along the same direction of a two-dimensional query-key space. They send the keys of I and bears along the orthogonal direction. The matrices are written by hand to show what the maps can do. Training finds such matrices from data.
Output from cell 2 With simple attention, bears keeps 0.58 of its weight on itself. With the two maps it puts 0.83 of its weight on love. A trained head learns many such directions at once, and one relationship can spread over many coordinates of the query-key space. The query and key maps decide the weights. The value map WvW^v decides what is averaged. In the simple mechanism the output x^i\hat x_i is a weighted average of the input tokens, so it stays in their convex hull. With the value map, the output is a weighted average of the values vj=xjWvv_j = x_j W^v. It stays in the convex hull of the values, which need not lie inside the hull of the inputs. The embeddings here are the three unit vectors, so the coordinates of a point are its weights on I, love and bears. A point lies in the convex hull of the three tokens when its coordinates are non-negative and sum to one. The value map below moves all three values. Each row of WvW^v sums to one, so the values stay in the plane of the tokens and the figure can draw them there. The value of love lands past love, on the side away from I. The values of I and bears move outward too.
Output from cell 4 The plane of the three tokens. Each thin orange arrow takes a token to its value. Both thick arrows start at bears. Under simple attention the output stays in the blue triangle. With the learned maps the output is an average of the values, and it leaves the blue triangle. The output with the learned maps has a negative weight on I, so it lies outside the hull of the input tokens. It is still inside the hull of the values, shown dashed. For a single head, the output always lies in the convex hull of the values. Whatever the query and key maps compute, the weights of each row are non-negative and sum to one. So x^i=∑jαijvj\hat x_i = \sum_j \alpha_{ij} v_j is a convex combination of the values that token ii may attend to. With a causal mask, these are the values at positions up to ii. This hull is small. With two tokens it is a line segment, and attention only decides how far xix_i moves along the segment toward the other token. Three tokens give at most a triangle, and four tokens give at most a tetrahedron. In general, TT values of dimension dvd_v span a region of dimension dim⁡conv⁡{v1,…,vT}≤min⁡(T−1, dv).\dim \operatorname{conv}\{v_1, \ldots, v_T\} \le \min(T-1,\, d_v). A ten-token sentence in Qwen3.8-27B, with d=5120d=5120, has a hull of at most nine dimensions. The value map does not enlarge it. A linear map sends the hull of the inputs onto the hull of the values, so it can move, rotate, scale or flatten the region, but it cannot raise its dimension. The other parts of the layer lift these limits. Each head of multi-head attention computes its own weights and its own values, and the layer combines the head outputs, so the result is no longer confined to the hull of one set of values. The residual connection adds the attention output to xix_i as an update. The MLP then applies a nonlinear map to each token on its own. The rest of this section works with a random context of T=8T=8 tokens, embedding dimension d=16d=16 and query-key dimension dk=4d_k=4. The next cell draws the embeddings and the three projection matrices.

Computation of the attention scores

Write the input matrix XX and the query weight matrix WqW^q element by element (the key weight matrix is analogous): X=[x1,1x1,2⋯x1,dx2,1x2,2⋯x2,d⋮⋮⋱⋮xT,1xT,2⋯xT,d],Wq=[w1,1⋯w1,dk⋮⋱⋮wd,1⋯wd,dk]X = \begin{bmatrix} x_{1,1} & x_{1,2} & \cdots & x_{1,d} \\ x_{2,1} & x_{2,2} & \cdots & x_{2,d} \\ \vdots & \vdots & \ddots & \vdots \\ x_{T,1} & x_{T,2} & \cdots & x_{T,d} \end{bmatrix}, \qquad W^q = \begin{bmatrix} w_{1,1} & \cdots & w_{1,d_k} \\ \vdots & \ddots & \vdots \\ w_{d,1} & \cdots & w_{d,d_k} \end{bmatrix} The product Q=XWqQ = XW^q has dimensions T×dkT \times d_k. Each element qi,jq_{i,j} of QQ is qi,j=∑l=1dxi,l wl,j.q_{i,j} = \sum_{l=1}^{d} x_{i,l} \, w_{l,j}. Each column jj of WqW^q is a set of weights over the dd features of the input embedding. So the projection can weigh some features of a token more than others when it computes the token’s query, and the same holds for the key. The dot product now happens in the query-key space of dimension dkd_k. Treat xix_i as a row of XX, a 1×d1 \times d row vector. The query of token ii is qi=xiWqq_i = x_i W^q and the key of token jj is kj=xjWkk_j = x_j W^k, so qikjT=xiWq(Wk)TxjT=xiWxjT,W=Wq(Wk)T,\begin{aligned} q_i k_j^T &= x_i W^q (W^k)^T x_j^T = x_i W x_j^T, \\ W &= W^q (W^k)^T, \end{aligned} where WW is a d×dd \times d matrix of rank at most dkd_k. Compared to the simple mechanism, the plain dot product xixjTx_i x_j^T becomes a learned bilinear form. The next cell checks both statements numerically.
Geometrically you can picture it as shown below. Queries and keys in the query-key space The diagram illustrates a possible alignment. The dot product depends on both vector norms and the angle between them. The query and keys only decide the attention weights. What is added to the token’s output comes from the value vectors of the tokens it attends to. In matrix form, the scores are S=QKT.S = QK^T.

Scaling

The scores are divided by the square root of the key dimension, dk\sqrt{d_k}. Without this division, large score differences can cause the softmax to saturate: the largest score takes almost all of the weight and the weights of the other tokens shrink toward zero. The experiment below shows this behavior. It applies the softmax to a vector of 8 scores, and then to the same vector multiplied by 100.
Output from cell 8 With the original scores the weights are spread over all eight tokens. With the scores multiplied by 100, the token with the largest score takes most of the weight and the rest are close to zero. Under independent zero-mean unit-variance components, the score standard deviation grows as dk\sqrt{d_k}. Scaling controls this growth; it does not guarantee that softmax never saturates. The attention scaling section derives why dk\sqrt{d_k} is the right factor, with a variance analysis and experiments. The code for scaled dot-product attention is short. It works on batched queries and keys of shape B×T×dkB \times T \times d_k and values of shape B×T×dvB \times T \times d_v. The optional mask is covered next.

Masking and causal attention

A decoder generates one token at a time, so at inference a token never sees the tokens after it. During next-token training, the output at position ii predicts token i+1i+1, and may see the input token at position ii. Training has to respect this constraint. Otherwise the model would learn to use future tokens, which are ground truth that is not available during inference. To prevent this, we mask the scores of the future tokens by setting them to −∞-\infty before the softmax. The softmax output is then exactly 0 for those tokens. For query qiq_i, only keys k1k_1 through kik_i are accessible, and every key kjk_j with j>ij > i is masked. For four tokens the following matrix shows the masking pattern (the factor 1/dk1/\sqrt{d_k} on finite scores is omitted for readability) k1k2k3k4q1q1k1T−∞−∞−∞q2q2k1Tq2k2T−∞−∞q3q3k1Tq3k2Tq3k3T−∞q4q4k1Tq4k2Tq4k3Tq4k4T\begin{array}{c|cccc} & k_1 & k_2 & k_3 & k_4 \\ \hline q_1 & q_1 k_1^T & -\infty & -\infty & -\infty \\ q_2 & q_2 k_1^T & q_2 k_2^T & -\infty & -\infty \\ q_3 & q_3 k_1^T & q_3 k_2^T & q_3 k_3^T & -\infty \\ q_4 & q_4 k_1^T & q_4 k_2^T & q_4 k_3^T & q_4 k_4^T \end{array} The mask is a lower-triangular matrix of ones. The next cell applies it to the 8-token context and compares the result with PyTorch’s built-in causal attention.
The first token can only attend to itself, so its row is a single 1. Every row still sums to 1, and every entry above the diagonal is 0.

Softmax

The scores can be positive or negative. As in the simple mechanism, a softmax applied to each row, over the keys jj of each query ii, turns them into the attention weights αij\alpha_{ij}. This is the dim=-1 in the code above.

Weighting the values

The value transformation

The query and key transformations allow us to determine which tokens contain information relevant to the token we are contextualizing. However, identifying a relevant token does not imply that all the information contained in its embedding is equally useful. Consider the sentence “I love bears.” Suppose that the query and key transformations establish a strong compatibility between bears and love. The embedding of love may contain information about tense, grammatical function, affection, preference and other semantic properties acquired during training. Which of these features should participate in the construction of a contextualized representation? Without a value transformation, the attention mechanism would compute a weighted average of the original embeddings: x^i=∑j=1Tαijxj.\hat x_i = \sum_{j=1}^{T} \alpha_{ij} x_j. Notice that the attention weight αij\alpha_{ij} is a scalar. It controls the contribution of the entire embedding xjx_j, but cannot selectively amplify, suppress or combine its individual features. We therefore introduce a third linear transformation, vj=xjWv,v_j = x_j W^v, which allows the model to construct a new set of features specifically for information exchange between tokens. The values live in a dvd_v-dimensional space. Nothing requires dv=dkd_v = d_k, but the two are usually equal. The contextualized representation becomes x^i=∑j=1Tαijvj=∑j=1TαijxjWv.\hat x_i = \sum_{j=1}^{T} \alpha_{ij} v_j = \sum_{j=1}^{T} \alpha_{ij} x_j W^v. The query and key transformations learn features useful for establishing linguistic relationships, whereas the value transformation learns features useful for exploiting those relationships. For example, an attention head may establish a relationship between a noun and its governing verb. Another head may establish a relationship between a noun and its modifier. These two relationships may require different kinds of information to be extracted from the same token embedding. This gives us three complementary feature transformations:
  • WqW^q extracts features useful for identifying contextual needs.
  • WkW^k extracts features useful for determining contextual relevance.
  • WvW^v extracts features useful for constructing contextual representations.
All three transformations are learned jointly during training.

A mathematical observation

Let AA be the T×TT \times T matrix of attention weights αij\alpha_{ij}. Since the value transformation is linear and shared across token positions, we can also write X^=AV=A(XWv)=(AX)Wv.\begin{aligned} \hat X &= AV \\ &= A(XW^v) \\ &= (AX)W^v. \end{aligned} Attention therefore performs two different operations:
  • Left multiplication by AA mixes information across tokens.
  • Right multiplication by WvW^v mixes information across feature dimensions.
These two operations act along different axes of the input matrix X∈RT×dX \in \mathbb{R}^{T \times d}. Attention determines how information flows between tokens, while the value transformation determines the feature representation in which that information is exchanged. The separation matters most in multi-head attention, where each head learns not only a different pattern of linguistic relationships but also a different feature transformation of the information exchanged through those relationships. For a single attention head, however, WvW^v is not strictly necessary to implement contextual information exchange. Its justification is the additional flexibility in learning feature representations. Indeed, in purely linear single-head attention with an output projection, the value and output projection matrices can be combined. It is in multi-head attention that the head-specific value transformations acquire particular architectural significance. As an example, take the context “The hiking trail led us through bear country”. Suppose the query of country assigns a large weight to the key of bear. The value of bear then contributes to the output of country. That contribution is a learned vector, not necessarily an explicit representation of an animal or a noun. The residual connection and subsequent layers further transform the representation. Block diagram of a single self-attention head: X is projected by W^q, W^k and W^v into Q, K and V; Q times K transpose gives the T by T scores, which are divided by the square root of d_k, optionally masked, and passed through a row-wise softmax to give the weights A; A times V gives the output A single self-attention head. The causal mask applies only in a decoder. The full equation of scaled dot-product self-attention is X^=Attention(Q,K,V)=softmax(QKTdk)V,\hat X = \mathtt{Attention}(Q, K, V) = \mathtt{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V, and the output has dimensions T×dvT \times d_v, where TT is the number of tokens in the input sequence and dvd_v is the dimension of the values. With batching, every tensor gets a leading batch dimension.
Self-attention differs from a dense layer in where its weights come from. If a dense layer learns a very small weight for an input, it applies that weight to every example fed into the layer. In self-attention, a very small attention weight comes from the specific tokens present in that input, and a different input gives different weights.

Example: contextual representations in BERT

We now return to the motivating example using a pretrained bidirectional encoder. Compare “I love bears”, “She bears the pain” and “Bears won the game”. The uncased BERT tokenizer maps bears to the same ID in all three sentences, and the code checks this. The token sits at a different position in each sentence, so its input embeddings already differ through the position embedding. We compare its hidden states across layers; these include attention, residual connections, normalization and feed-forward transformations.
Output from cell 12 At the input the three representations differ only through the position embedding, so their similarity starts between 0.93 and 0.97. Differences in later layers demonstrate contextualization, not proof that a specific semantic sense has been isolated. Similarity need not decrease monotonically. The next figure shows attention weights averaged across heads; these are not a measure of causal importance. Output from cell 13 Inspect the maps for differences across contexts and layers. Averaging heads can hide distinct patterns; a large weight on a special token does not by itself establish its importance.

PyTorch reference

Key references: (Vaswani et al., 2017; Luong et al., 2015)

References

  • Luong, M., Pham, H., Manning, C. (2015). Effective Approaches to Attention-based Neural Machine Translation. arXiv [cs.CL]. Link
  • Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., et al. (2017). Attention Is All You Need. arXiv [cs.CL]. Link

Found an error on this page? Report an issue.