Deep Learning Note 6: Why We Scale Dot-Product Attention
We can now return to the statistical behaviour of the compatibility scores themselves. This is where the first mathematical bridge becomes indispensable. Recall that an unscaled attention score is a dot product.
The quantity tells us how many coordinate-wise products participate in this sum. If , the score is a sum of two products.
If , the score is a sum of 128 products.
This immediately raises a question. What happens to the typical magnitude of these scores as the query and key dimension increases? Does the score remain on approximately the same numerical scale, or does summing more coordinate-wise products make it increasingly large? Before answering, we need to carefully understand the assumptions commonly made about the coordinates of queries and keys at initialization. When we say that a coordinate is a random variable, we are not saying that a trained model necessarily changes that coordinate randomly every time the same input is processed. Rather, we are describing its statistical behaviour across possible random initializations, inputs, token representations, or other specified sources of variation.
Imagine repeatedly initializing a neural network using randomly sampled parameter matrices and observing a particular query coordinate. On one initialization, it might be . On another, it might be . On another, it might be . Across many such observations, we can describe that coordinate using a probability distribution. For a coordinate , its expected value is denoted by
When we assume that this coordinate has zero mean, we are assuming
This means that the coordinate has no persistent positive or negative bias under the distribution we are considering. Positive and negative outcomes balance in expectation. It does not mean that the coordinate is always zero. For example, imagine a random variable that equals with probability one half and with probability one half. Its expected value is
Every individual observation is nonzero, but the average of the possible observations is zero. This distinction is particularly important in high-dimensional spaces. A vector can have coordinates drawn from zero-mean distributions while still possessing a substantial norm. Suppose
and every coordinate has zero mean. Then
However, the squared magnitude of the vector is
Squaring removes the signs. Consequently, positive and negative coordinates cannot cancel within the squared norm. If each coordinate also has unit variance, meaning
then because its mean is zero,
Therefore,
Hence,
The root-mean-square magnitude of the vector grows with the square root of its dimensionality. For a 128-dimensional query whose coordinates have unit variance,
This is a useful mental model. Zero mean does not mean small magnitude. It means that there is no persistent signed bias in the individual coordinates under the assumed distribution. A high-dimensional vector can be centred around zero statistically while having considerable length geometrically. What does unit variance mean? It means that the expected squared deviation of a coordinate from its mean equals one.
When the mean is zero, this simplifies to
Its standard deviation is consequently
This gives the coordinate a characteristic numerical scale of one. It does not mean that the coordinate is restricted to the interval . For example, a standard normal random variable,
has zero mean and unit variance, but it can take values greater than one, less than minus one, or even extremely large values with sufficiently small probability. Unit variance describes the overall spread of the distribution. It does not impose a hard bound on individual outcomes. Why do we use zero mean and unit variance when analysing attention? Firstly, they provide a useful mathematical starting point. We want to understand how the dimension of a query and key influences the magnitude of their dot product without introducing unnecessary complications from arbitrary means and variances. Secondly, neural networks are often initialized and normalized in ways intended to maintain reasonably controlled activation scales.
Although the actual distributions need not have exactly zero mean and unit variance, these assumptions provide a simple baseline for understanding their behaviour. Consider a query projection
An individual query coordinate is
Notice that this is itself a sum of many contributions. Suppose that the projection weights are independently initialized with zero mean and variance
For a fixed hidden representation , the expected value of the query coordinate over random projection initialization is
Assuming the projection weights are independent, its variance is
Now recall that the squared root mean square of a vector is
Therefore,
If the hidden representation has an RMS close to one, the resulting query coordinate has variance close to one under this simplified initialization scheme. This is a lovely connection between initialization, normalization, and the variance of linear transformations. The model first maintains a reasonably controlled scale in its hidden representations. The projection matrices can then be initialized with sufficiently small entries so that the sums involved in constructing queries and keys do not produce excessively large coordinate magnitudes. The assumptions of zero mean and unit variance are therefore not entirely arbitrary. They approximate the kind of statistical regime that well-scaled initialization and normalization often attempt to establish.
However, they should not be mistaken for guarantees. RMSNorm does not explicitly subtract the mean, learned scaling factors can alter coordinate magnitudes, different architectures use different initialization strategies, and learned queries and keys can develop substantial correlations or outliers during training. We are constructing a baseline model of their behaviour, not claiming that real trained representations satisfy these assumptions exactly. The next assumption is independence. What does it mean to say that the coordinates are independent? Imagine that we observe the first coordinate of a query vector. Suppose knowing that is positive tells us nothing about whether is likely to be positive or negative.
Suppose that knowing the exact value of does not alter the probability distribution of . Then the two coordinates are independent. More generally, two random variables and are independent if learning the value of one does not change the probability distribution of the other. For independent random variables, their joint probability factorizes into their individual probabilities. In the discrete case,
Consider two separate fair coin tosses. Let denote the outcome of the first toss and denote the outcome of the second toss, where heads is represented by and tails by . Knowing that the first coin landed heads does not change the probability of the second coin landing heads.
The two outcomes are independent. Consequently,
Now imagine that instead of tossing two coins independently, we toss one coin and copy its outcome twice.
If the first outcome is , we know with certainty that the second outcome is also .
The variables are no longer independent. Notice that the individual variables still have the same mean and variance as before. We have changed only the relationship between them. This is exactly the distinction we studied in our first bridge. When we assume that different query and key coordinates are independent, we are assuming that their random fluctuations do not systematically determine one another. For the simplified dot-product derivation, we will assume that the query and key coordinates are mutually independent, have zero mean, and have unit variance. This is stronger than what is strictly necessary.
For some parts of the derivation, zero correlation is sufficient. Nevertheless, independence provides an especially clear way of establishing the relevant relationships. It is also important not to confuse statistical independence with geometric orthogonality. Two coordinate axes can be perpendicular in the geometric coordinate system while the numerical values appearing along those axes are statistically dependent. For example, imagine repeatedly sampling a two-dimensional vector of the form
The horizontal and vertical axes are geometrically perpendicular. However, the two coordinates are perfectly dependent because they always contain the same value. The resulting vectors lie along the diagonal line . Statistical independence is a statement about how values vary together across observations. Geometric orthogonality is a statement about the angle between directions or vectors. They are different mathematical concepts. We should also distinguish independence from being uncorrelated. Two variables are uncorrelated if their covariance is zero.
Independent variables with finite second moments are uncorrelated, but uncorrelated variables need not be independent. For example, let be a standard normal random variable and define . Knowing completely determines , so the variables are clearly dependent. However,
The odd third moment of a symmetric standard normal distribution is zero. The variables are therefore uncorrelated despite being dependent. This distinction matters because the variance of a sum depends directly on covariance. Independence is one convenient condition that makes the covariance terms disappear, but it is not the only condition.
The variance of a dot product
Let us now use these ideas to analyse a single coordinate-wise product within an attention score. Define
For simplicity, we have dropped the token index from the key. We assume
and
We also assume that and are independent. What is the expected value of their product? One of the useful consequences of independence is that the expectation of a product factorizes.
Applying this property,
Therefore,
We can understand this intuitively using the coin-toss example. If and independently take values of either or , their product is positive when their signs agree and negative when their signs disagree. The four equally likely possibilities produce products
Their average is zero.
There is no persistent alignment between the two independently sampled coordinates. Sometimes they agree. Sometimes they disagree. Across repeated observations, their signed products cancel in expectation. Now let us calculate the variance of the product. Recall that
Since ,
Substituting ,
Because and are independent, their squares are also independent. Therefore,
Each coordinate has zero mean and unit variance, so
and
Consequently,
Thus,
This is an important intermediate result. Under our assumptions, each individual coordinate-wise product in the dot product has zero mean and unit variance. The product is not necessarily normally distributed, even when the individual coordinates are normally distributed. However, we do not need to know its entire probability distribution to establish its mean and variance. Now let us consider the complete attention score.
We have reduced the dot product to a sum of random quantities. We already know how to analyse such sums from our first mathematical bridge. The expectation of the sum is
Therefore,
But as we learned earlier, knowing that the mean is zero tells us very little about the typical magnitude of individual observations. A random walk can have zero expected displacement while still wandering a considerable distance from its starting point. Likewise, a dot product can have zero expected value while frequently producing substantially positive or negative scores. To understand its typical magnitude, we need to calculate its variance. The general variance formula for a sum is
Under our assumptions, the coordinate-wise products are independent across different coordinates, so the covariance terms vanish.
This leaves
Every product has variance one. Therefore,
Consequently,
Taking the square root gives
We have rediscovered the square-root accumulation law from our previous bridge. Every coordinate-wise product contributes a random positive or negative quantity. Because the contributions have no persistent alignment under our assumptions, they partially cancel. However, their cancellation is not perfect within each individual dot product. The typical magnitude of the remaining sum grows proportionally to the square root of the number of contributing coordinates. The attention score behaves statistically like a random walk through its coordinates. Imagine constructing a dot product between two independently sampled 128-dimensional vectors whose coordinates are either or . Each coordinate contributes either or to the score.
The complete dot product is equivalent to taking 128 unit steps along a number line. If the signs agree at 70 coordinates and disagree at 58 coordinates, the resulting score is
The dot product has accumulated 128 individual contributions, but its net value is only 12. If the signs agree at 59 coordinates and disagree at 69 coordinates, the score becomes
Different random queries and keys produce different net scores. Across repeated independent samples, the average score approaches zero, but their standard deviation is
This is precisely the random-walk behaviour we previously explored. What happens as the dimensionality increases? For ,
For ,
For ,
For ,
For ,
The number of coordinates has a substantial effect on the scale of the unnormalized compatibility scores. We can understand this result geometrically as well. Recall that
For independent isotropic Gaussian query and key vectors with unit-variance coordinates, their typical norms are approximately . The product of their norms is therefore approximately . Meanwhile, independently chosen directions in high-dimensional space tend to be almost perpendicular. For independent uniformly distributed unit directions, the cosine of their angle has mean zero and variance . Its characteristic magnitude is consequently
Putting these scales together,
This geometric argument leads to the same characteristic scale as our variance calculation. Although random high-dimensional vectors become increasingly close to perpendicular in angular terms, their growing norms mean that their raw dot products can still have substantial magnitudes. This distinction is particularly important. A large raw dot product does not necessarily imply a large cosine similarity. For example, imagine a 128-dimensional query and key whose norms are both approximately . Their product of norms is approximately 128. Even a cosine similarity of just produces
The vectors are nearly perpendicular, yet their dot product is already considerably larger than one. Now recall what softmax does with differences of this magnitude. A score advantage of 10 produces a probability ratio of
We have arrived at an important problem. Increasing the query-key dimension increases the characteristic spread of the raw compatibility scores. Softmax interprets large score differences as strong preferences. Therefore, even completely random compatibility scores can create extremely strong attention preferences when the dimensionality becomes sufficiently large. The model has not necessarily learned that one token is substantially more useful than another. The attention scores may simply have become widely spread because each score contains a sum of many random coordinate-wise products. Softmax cannot distinguish between a large score difference caused by meaningful learned alignment and a large score difference caused by the statistical scale of an unnormalized dot product.
It simply exponentiates the scores it receives. This is why the statistical properties of the dot product matter so much for attention. To make this concrete, suppose an attention head produces three unscaled scores:
The softmax probabilities are approximately
Almost the entire attention budget is allocated to the third value. This is not necessarily a problem if the model has genuinely learned that the third value is the only useful one. However, if these scores arise from random initial projections, this confidence may have no meaningful justification. Furthermore, because the distribution is already saturated, the attention weights can become relatively insensitive to small changes in the scores. We therefore want to remove the systematic growth in score magnitude caused by increasing the query-key dimension. How might we do this? Our first mathematical bridge has already given us the answer.
If the variance of an unscaled dot product is , its standard deviation is . We can divide the dot product by that characteristic scale. Define the scaled attention score as
What is the variance of this scaled score? We previously established that
Here, the scaling constant is
Therefore,
Consequently,
The mean remains zero.
We have transformed a collection of compatibility scores whose typical scale grows with the query-key dimension into scores whose variance is independent of that dimension under our assumptions. This is the mathematical motivation for the scaling factor in the Transformer. Let us return to our earlier example. Suppose and the raw attention scores are
Since
we divide the scores by eight.
The softmax distribution now becomes
Compare the two distributions. Before scaling, the third value received more than 99.9% of the attention. After scaling, it receives approximately 66.5%. The ranking has not changed. The third key is still preferred, followed by the second and then the first. What has changed is the strength of the competition. The scaling factor prevents the dimensionality of the query-key space from automatically translating random score differences into nearly absolute preferences. We can also understand this through the concept of temperature. Recall that
reduces competition when is large.
Scaling by as a fixed temperature
Scaled dot-product attention can therefore be interpreted as applying a fixed temperature
to the raw dot products. This temperature compensates for the characteristic growth of the unnormalized scores. It is important to understand that the Transformer is not trying to make attention uniformly distributed. It is trying to prevent query-key dimensionality from introducing an unnecessary source of saturation. During training, the model can still learn to produce strong score differences whenever selective retrieval is useful. The scaling factor establishes a more controlled starting regime from which these meaningful preferences can emerge. Why do we divide by the square root of the dimension rather than the dimension itself?
This follows directly from the distinction between variance and standard deviation. The variance of our score grows as , but the typical numerical magnitude of the score grows as . We want to control the scale of the score itself. If we divided by , we would obtain
Consequently,
As the dimension became larger, the compatibility scores would become increasingly concentrated near zero under our initialization assumptions. Softmax would consequently approach a uniform distribution. We would have overcorrected the dimensional growth. If we do not scale the dot product at all, its standard deviation grows as . If we divide by , its standard deviation shrinks as . If we divide by , its standard deviation remains one.
This is why the square root appears rather than the dimension itself. We are correcting the characteristic scale of an accumulation of uncorrelated contributions. The square root is not an arbitrary architectural constant. It is inherited from the statistical behaviour of sums. There is another question worth asking. Does dividing by turn the dot product into cosine similarity? The answer is no. Cosine similarity is defined as
It removes the magnitudes of both vectors and retains only their angular relationship. Scaled dot-product attention instead computes
This preserves the influence of query and key magnitudes while compensating for the expected growth with dimension. A model can therefore potentially use the magnitude of a query or key as another way of influencing the strength of compatibility scores.
What scaling does—and does not—guarantee
This also means that scaling by does not guarantee that attention scores remain well-behaved throughout training. It is based on a particular statistical assumption. What happens if those assumptions stop being valid? Suppose the query coordinates have zero mean and variance , while the key coordinates have zero mean and variance . Assuming independence,
Summing uncorrelated products gives
After standard attention scaling,
If both query and key coordinates grow in standard deviation, the resulting attention scores also grow. Dividing by compensates for the number of dimensions, but it does not compensate for arbitrary changes in the scale of the coordinates themselves. Now suppose the products across different coordinates become correlated. Let
and suppose each product has variance and every distinct pair of products has correlation . Using the result from our first mathematical bridge,
After dividing the sum by ,
Consequently,
This reveals an important limitation of the standard attention scaling rule. It is designed to compensate for square-root growth arising from uncorrelated contributions. If the coordinate-wise products become positively correlated, an additional contribution survives the scaling. For example, with , unit product variance, and a pairwise product correlation of just , we obtain
The standard deviation becomes
Our original scaling no longer produces unit variance. This is the same amplification of small correlations that we explored earlier. Even a relatively weak relationship between coordinate contributions can become significant when many of those contributions participate in the same sum. Real query and key vectors can also have nonzero means and correlations with one another. In general,
A coordinate-wise product can therefore have a nonzero expected value if the query and key coordinates possess shared biases or systematic alignment. When those expected contributions point consistently in the same signed direction, their sum can grow coherently rather than merely fluctuate around zero. This is not inherently undesirable. The purpose of training the query and key projections is precisely to create meaningful compatibility patterns. If a particular query systematically aligns with a useful key, their resulting score should become distinguishable from the scores of less useful keys. We should therefore distinguish uncontrolled growth caused by initialization or numerical scale from useful alignment learned by the model.
The factor compensates for a statistical baseline. It does not erase meaningful learned alignment. This is why the independence assumption is best understood as a starting point for analysing attention rather than a permanent property of its representations. Queries and keys in a trained model are produced from related token representations using learned projection matrices. Their coordinates can exhibit substantial dependencies, and the scores obtained from different keys share the same query. They are not generally independent samples from identical distributions. For example, if we hold a query fixed and sample a random key whose coordinates are independently drawn from a zero-mean, unit-variance distribution, the conditional variance of the dot product is
Thus,
The right-hand side is simply the squared RMS of the query vector. A query with a larger RMS can produce a wider distribution of compatibility scores, even when the key distribution remains unchanged. This helps us see why controlling query and key magnitudes can matter during training, and why some architectures introduce additional query-key normalization mechanisms. A normalization scheme can help separate angular compatibility from uncontrolled growth in vector magnitudes. The precise benefit depends on the architecture and training regime, but the underlying motivation follows directly from the relationship between dot-product variance and softmax selectivity.
We can now put the entire attention computation together. Suppose the hidden representations of a sequence are arranged as the rows of a matrix
Each row represents one token, and each column represents one hidden-state coordinate. For a single attention head, we construct query, key, and value matrices using learned projections. Using row-vector conventions,
The projection matrices have dimensions
Consequently,
and
This is the same linear projection we described earlier, written using matrices containing row vectors rather than individual column vectors. We now compare every query with every key. This can be performed efficiently using matrix multiplication.
Let us understand the dimensions. The query matrix has dimensions . The transposed key matrix has dimensions . Their product therefore has dimensions
Every entry of this matrix is a query-key dot product.
Row contains all the compatibility scores produced by the query belonging to token . Column contains the scores assigned to key by all the different queries. We now divide every entry by .
In a causal language model, a token should not be able to retrieve information from future tokens. We can implement this restriction by adding an attention mask to the scores.
For causal attention, the mask is typically defined by
Because in the limiting mathematical sense, future positions receive zero attention weight. The softmax normalization is then performed across the allowed keys. We apply softmax independently to each row of the score matrix.
The resulting attention matrix satisfies
For each query position ,
Each row represents a different probability distribution over the available keys. Each token independently distributes its attention budget according to the information it is looking for. The columns do not generally sum to one. This is an important distinction. There is no fixed total amount of attention that a particular key can receive across the entire sequence. Many different queries can attend strongly to the same key. The competition exists among the keys for a particular query's attention budget, not among every query in the sequence for access to a single global resource. Finally, we multiply the attention matrix by the value matrix.
The dimensions are
The -th row of the resulting matrix is
This is precisely the weighted combination of information with which we began our discussion. The attention matrix tells us how much information to retrieve from each position. The value matrix contains the information available to be retrieved. Their matrix product performs all of those weighted combinations simultaneously. Putting these operations together, we obtain
If no attention mask is required, we can omit and recover the familiar expression:
This is the scaled dot-product attention equation introduced in the original Transformer paper, Attention Is All You Need, published in 2017. Section 3.2.1 of the paper motivates the scaling factor using the same assumption we have explored: independent query and key coordinates with zero mean and unit variance produce dot products with variance . Scaling is intended to reduce the tendency of large dot products to push softmax into low-gradient regimes. What initially appears as a compact architectural equation now contains a considerable amount of meaning. The matrices and describe the learned search mechanism.
Their matrix product measures the compatibility between requests for information and the available sources of information. The factor compensates for the characteristic growth of a sum of coordinate-wise products. Softmax converts the resulting scores into positive relative shares of a fixed attention budget. The multiplication by combines the information associated with the available tokens according to those learned shares. Each operation addresses a different part of the information retrieval problem. There is one final consequence of this mathematical design worth carrying forward. Because softmax attention always distributes a total weight of one, it cannot directly express a distribution in which every available value receives zero attention.
Suppose a particular attention head has learned to retrieve a specific kind of information. What happens when that information is absent from the available context? Ideally, the head might want to contribute nothing to the residual stream. However, standard softmax still requires it to distribute its attention budget somewhere. The head could attempt to combine value vectors whose contributions cancel one another. But as we discovered earlier, averaging correlated information does not necessarily eliminate it. For example, under fixed weights and a common pairwise correlation , the variance of a uniform average of value coordinates is
As the number of values grows, the independent component becomes smaller, while the shared correlated component remains. A uniform mixture is therefore not guaranteed to be an empty or neutral representation. Another possible solution is for the model to develop a particular token position whose key is attractive to attention but whose value contributes very little useful information. Suppose there is a value that is approximately zero. If an attention head allocates almost all its probability to that value,
then its output can become approximately
The head has effectively found a way to avoid contributing substantial information without violating the simplex constraint. The first token is a convenient possible destination because, in ordinary causal attention, it is visible to subsequent positions throughout the sequence. This is one way of understanding attention sinks, which are positions that attract disproportionately large amounts of attention even when their semantic relevance appears limited. The paper Efficient Streaming Language Models with Attention Sinks documents this phenomenon and explores its implications for language-model inference. The subsequent study When Attention Sink Emerges in Language Models: An Empirical View investigates the relationship between attention normalization, training, and these sink behaviours.
We should not conclude that every attention head must develop a sink, that every sink has a zero value vector, or that an attention output cannot be zero without one. The important observation is that the normalization constraint creates a computational limitation, and models can learn internal mechanisms that compensate for it. This is where a seemingly simple mathematical choice begins to influence the internal organisation of a trained neural network. We started by asking how to combine several pieces of information without treating them as equally important. That question led us to weighted combinations, which led us to normalized proportions.
The desire to preserve ordering, support smooth selection, and express relative preferences led us to exponentiation and softmax. The normalization constraint gave us the geometry of the probability simplex and the competitive relationship between attention weights. The exponential function revealed why relative score differences matter and why the spread of those scores controls the strength of competition. Finally, our earlier understanding of mean, variance, independence, cancellation, and alignment explained why the dot products producing those scores need to be scaled. The two mathematical bridges have now become connected. Our first bridge taught us how the magnitude of a sum emerges from the relationships between its contributions.
Our second bridge teaches us how those accumulated quantities can be transformed into a distribution of influence, allowing a neural network to decide which information should participate in its next computation. The connection can be expressed particularly clearly through two equations.
and
The first equation describes how the numerical scale of compatibility scores emerges from the accumulation of many coordinate-wise contributions. The second describes how differences between those scores determine the relative influence of competing pieces of information. One concerns accumulation. The other concerns competition. Together, they explain why the mathematics of variance is inseparable from the mathematics of attention. Once we recognise this connection, the familiar Transformer attention equation no longer feels like a collection of arbitrary operations. Each operation follows naturally from a problem that we have already learned how to think about. We will carry these ideas forward when exploring attention sinks, massive activations, normalization, floating-point precision, optimization, and the algorithms that allow attention to operate efficiently across enormous collections of tokens.
What makes these connections interesting is that the same mathematical principles continue to appear, even as the computational problems surrounding them become increasingly complex.