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 and project each token, or equivalently the matrix , into three different spaces: Here is the input embedding matrix, where is the input sequence length and is the embedding dimension. , and hold the queries, keys and values. The matrices have dimensions , and . Queries and keys live in a space of the same dimension, so . For token , the query is used to compare against keys from all allowed positions. The value is the information contributed by position . 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 wordslove 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 forI, 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.
Code
Code
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 decides what is averaged. In the simple mechanism the output 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 . 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 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.
Code
Code
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 is a convex combination of the values that token may attend to. With a causal mask, these are the values at positions up to .
This hull is small. With two tokens it is a line segment, and attention only decides how far 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, values of dimension span a region of dimension
A ten-token sentence in Qwen3.8-27B, with , 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 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 tokens, embedding dimension and query-key dimension . The next cell draws the embeddings and the three projection matrices.
Code
Code
Computation of the attention scores
Write the input matrix and the query weight matrix element by element (the key weight matrix is analogous): The product has dimensions . Each element of is Each column of is a set of weights over the 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 . Treat as a row of , a row vector. The query of token is and the key of token is , so where is a matrix of rank at most . Compared to the simple mechanism, the plain dot product becomes a learned bilinear form. The next cell checks both statements numerically.Code
Code

Scaling
The scores are divided by the square root of the key dimension, . 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.Code
Code
Code
Code
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 predicts token , and may see the input token at position . 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 before the softmax. The softmax output is then exactly 0 for those tokens. For query , only keys through are accessible, and every key with is masked. For four tokens the following matrix shows the masking pattern (the factor on finite scores is omitted for readability) 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.Code
Code
Softmax
The scores can be positive or negative. As in the simple mechanism, a softmax applied to each row, over the keys of each query , turns them into the attention weights . This is thedim=-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 betweenbears 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:
Notice that the attention weight is a scalar. It controls the contribution of the entire embedding , but cannot selectively amplify, suppress or combine its individual features.
We therefore introduce a third linear transformation,
which allows the model to construct a new set of features specifically for information exchange between tokens. The values live in a -dimensional space. Nothing requires , but the two are usually equal. The contextualized representation becomes
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:
- extracts features useful for identifying contextual needs.
- extracts features useful for determining contextual relevance.
- extracts features useful for constructing contextual representations.
A mathematical observation
Let be the matrix of attention weights . Since the value transformation is linear and shared across token positions, we can also write Attention therefore performs two different operations:- Left multiplication by mixes information across tokens.
- Right multiplication by mixes information across feature dimensions.
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.
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 mapsbears 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.
Code
Code
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.

