Introduction
Welcome to the first lesson in our course on the backbones of vision-language models. Our journey begins with the foundational component of the Transformer architecture: the attention mechanism. In this lesson, we will focus on a specific and crucial implementation known as scaled dot-product attention. Your goal for this session is to derive its formula and, more importantly, to understand the mathematical reasoning that necessitates its characteristic scaling factor.
Given your strong background in mathematics and machine learning, we will go beyond a surface-level description and delve into the statistical properties that make this scaling essential for stable and effective model training. Mastering this concept is paramount, as it forms the bedrock upon which modern architectures like the Vision Transformer (ViT), BERT, and GPT are built—the very models we'll be dissecting to understand VLMs like CLIP and LLaVA.
From Similarity to Attention Scores
At its core, an attention mechanism calculates a set of scores that determine how much focus, or "attention," one element in a sequence should pay to other elements. In self-attention, which is used within a single sequence, these scores are derived from the interactions between three representations of each input token:
- Query (Q): A representation of the current token, acting as a probe or a question about other tokens.
- Key (K): A representation of each token in the sequence that can be "matched" against a query. The similarity between a query and a key determines the attention score.
- Value (V): A representation of each token that contains the information to be passed forward. The attention scores are used to create a weighted average of the value vectors.
These three vectors for each token are not pre-defined; they are learned projections of the initial token embeddings. Given an input embedding matrix , we obtain Q, K, and V by multiplying with three distinct weight matrices, , , and , which are learned during training.
The most common way to calculate the similarity between a query vector and a key vector is the dot product. This leads us to the formula for scaled dot-product attention, as defined in the original "Attention Is All You Need" paper.

The formula is expressed as:
Let's break this down:
- : This matrix multiplication computes the dot product between every query vector in and every key vector in . The result is a matrix of raw "compatibility" scores.
- : Each element of the score matrix is divided by the square root of the dimension of the key vectors, . This is the scaling factor, and it is the central focus of our lesson.
- : The softmax function is applied to the scaled scores along each row. This normalizes the scores into a probability distribution, ensuring they sum to 1. The resulting values are the final attention weights.
- : The matrix of attention weights is multiplied by the value matrix . This produces the final output, where each output vector is a weighted sum of all value vectors, with weights determined by the attention scores.
The critical question is: why is the term not just helpful, but essential? To build an initial intuition, please watch the following video.
Why Scaling by the Square Root of Dimensions Matters in Attention | Transformers in Deep Learning
This video, from the channel Learn With Jay, provides a clear, intuitive explanation of the problem that arises without scaling and how it impacts the softmax function.
Please watch the section that explains the variance property, where the narrator demonstrates how the variance of dot products grows with the vector dimension, d_k. Then, watch the section on the problem with high variance, which explains how the softmax function's behavior with large inputs can cripple the model's ability to learn.
As the video explains, the magnitude of the dot products tends to increase as the dimension grows. These large values push the softmax function into regions where it produces extremely sharp distributions, which can cause gradients to vanish during training, effectively halting learning. Now, let's formalize this intuition with a mathematical derivation.
The Mathematical Rationale for Scaling
To prove why is the correct scaling factor, we need to analyze the statistical properties of the dot product . Let's consider the dot product between a single query vector and a single key vector , both of dimension .
We'll make a standard assumption that the components of and are independent random variables drawn from a distribution with a mean of 0 and a variance of 1. This is a reasonable assumption for the initial weights in a neural network, which are often initialized this way, and for inputs that have been normalized (e.g., via layer normalization, which we'll see later).
The following article provides a clear, step-by-step mathematical proof of why the variance of this dot product grows with , and why that necessitates the specific scaling factor.
Math behind √dₖ Scaling Factor in Attention
This article from Outcome School breaks down the mathematical justification for the scaling factor into manageable steps, moving from statistical first principles to the final solution.
Please read the following sections: Start with Understanding Variance of the Dot Product, which sets up the statistical assumptions. Next, follow the detailed proof in the section Proving It Step by Step. This is the core of the derivation, showing that the variance of the dot product is exactly d_k. Then, read What Large Dot Products Do to Softmax to see a concrete numerical example of how large scores lead to saturated outputs and vanishing gradients. Finally, read Why √dₖ is the Right Scaling Factor, which uses a fundamental property of variance to derive the solution.
Let's summarize the key mathematical steps from the article:
-
Variance of the Sum: The variance of a sum of independent random variables is the sum of their variances.
-
Variance of the Product: For independent random variables and with zero mean () and unit variance (), the variance of their product is:
Since , for a variable with zero mean, . Thus, and .
-
Total Variance: Combining these, the variance of the dot product is the sum of terms, each with a variance of 1.
This is the crucial result: the variance of the dot product scores grows linearly with the dimension .
-
The Solution: To counteract this, we need to scale the dot product. We use the property that for a random variable and a constant , . We want the new variance to be 1.
Setting the desired variance to 1:
This proves that dividing by is not a heuristic but the precise mathematical correction required to normalize the variance of the attention scores to 1. This prevents the scores from growing with the model's dimensionality, keeping the inputs to the softmax function in a well-behaved range and ensuring stable gradients for effective training.
The heatmaps below, from another excellent article on the topic, visually demonstrate this regularization effect. The unscaled dot products on the left have a much larger range of values compared to the scaled scores on the right, which are compressed into a more stable range before being passed to the softmax function.
Why is Self Attention divided by √dₖ: The Secret Behind ...
This article by Srivatsa Narasimha provides a helpful visualization.
Please examine Figure 2, which shows heatmaps of raw dot product scores versus scaled scores. Notice how the distribution of values on the right is much smoother and less extreme.
Conclusion
In this lesson, we have dissected the scaled dot-product attention formula and derived its scaling factor from first principles. This seemingly small detail is a cornerstone of the Transformer's success.
Here are the key takeaways:
- The scaled dot-product attention formula is .
- The dot products produce raw similarity scores. Without scaling, the variance of these scores is equal to the dimension of the key vectors, .
- As increases, the large variance pushes the dot product scores to extreme values. This forces the softmax function to produce near one-hot distributions, causing the vanishing gradient problem and hindering the model's ability to learn complex relationships.
- Dividing the scores by is a precise mathematical correction that normalizes the variance to 1. This stabilizes the inputs to the softmax function, ensuring smooth gradients and enabling the effective training of very deep and high-dimensional Transformer models.
In our next lesson, we will build upon this foundation to understand multi-head attention. We'll see how the model runs scaled dot-product attention multiple times in parallel to jointly attend to information from different representational subspaces at different positions.