Mathematical Prerequisites for the Attention Series
Building the math foundations for the attention series — the tanh function, dot products as similarity measures, the standard normal distribution, variance, independence of random variables, and why the variance of a dot product equals the vector dimension — all derived step by step with one consistent 2-dimensional example.
Before diving into the attention series, we need four tools that have not appeared in any earlier prerequisite post: the tanh function, the dot product, the standard normal distribution, and variance. The most important is the last. In From Soft Alignment to Queries, Keys, and Values, we derive why the attention score matrix must be divided by before the softmax. The entire argument rests on one result: when each component of and is independently drawn from a standard normal distribution, the variance of their dot product equals . Everything in this post builds toward that one identity.
Expected value and linearity of expectation were fully derived in Mathematical Prerequisites for Reinforcement Learning. We will use both without re-deriving them.
The Running Example
Two 2-dimensional vectors:
These four numbers — , , , — came from drawing each component independently at random. We will use them in every concrete calculation in this post. In the attention blogs, the vectors will be 64-dimensional rather than 2-dimensional, but the structure is identical.
1. The tanh Function
In What Attention is Really Doing, the first step is computing an alignment score between a decoder state and an encoder annotation . The alignment model used by Bahdanau et al. applies the hyperbolic tangent to the sum of two projected vectors. We need to know what tanh is, what values it can take, and how to compute it.
The hyperbolic tangent is defined as:
The numerator is positive when , zero when , and negative when . The denominator is always strictly positive. The ratio therefore carries the sign of the numerator.
Range. The denominator always exceeds the numerator in absolute value: for all real , because the larger of and always appears on both sides. Dividing, we get . So for every real input.
Boundary behaviour. As , , so
As , , so
At : . The function passes through the origin, approaches from below as grows large, and approaches from above as grows large and negative.
Numerical check
We compute the alignment score between and from our running example: .
The result lies in as required. In the blog What Attention is Really Doing, alignment scores for source words , , are computed exactly this way — each one is a of a sum of two values, producing a score between and before softmax normalisation.
2. The Dot Product
In From Soft Alignment to Queries, Keys, and Values, the tanh-based alignment model is replaced by a simpler function: the dot product. Every attention score is the dot product of query vector with key vector . We need a precise definition.
The dot product (also called the inner product) of two -dimensional vectors and is the sum of their component-wise products:
Each pair contributes one scalar to the total. The output is a single number, not a vector.
What does it measure? When and point in the same direction, their components tend to share the same sign, each product is positive, and the sum is a large positive number. When they point in opposite directions, the products are negative and the sum is a large negative number. When they are perpendicular, positive and negative contributions cancel and the sum is near zero. The dot product is therefore a measure of directional similarity — large and positive when vectors align, near zero when perpendicular, large and negative when opposite.
For unit-length vectors, , where is the angle between them. This is the cosine similarity. For general vectors the magnitude matters too, but the directional interpretation remains.
Numerical check
The first component pair contributes (same sign, so positive contribution), and the second contributes (opposite signs, so negative contribution). The net dot product is .
In Part 2, this computation is done for every pair of query and key vectors simultaneously via the matrix product . For our 2-dimensional, 3-token example in that blog, this produces a matrix of alignment scores — each entry computed as we just did.
3. The Standard Normal Distribution
The scaling in attention is justified by a probabilistic argument. We need to model the typical size of each vector component. The assumption used in Part 2 is that each component of and is drawn independently from the standard normal distribution, written .
A random variable distributed as has two defining properties:
- Mean zero: . The distribution is symmetric around zero — is equally likely to be positive or negative.
- Variance one: . The typical distance from zero is about 1.
We define variance precisely in the next section. For now, treat these as the defining numbers.
One key consequence. For , the expected value of is:
This uses the computational formula for variance, which we derive in Section 4. The result — — will be our workhorse in Sections 5 and 6.
Why this assumption? Before training, the linear projections that produce and are initialised with small random weights, and inputs are typically normalised. In this regime, each output component behaves approximately like a draw from . The analysis is clean and the conclusion is exact under this assumption; in practice, it holds approximately.
Numerical check
Our running example has , , , — four draws from . Their sample mean is , not exactly zero. That is expected: with only 4 samples, the sample mean will not match the theoretical mean of zero. The law of large numbers guarantees convergence to zero as the sample count grows.
4. Variance
We need a precise measure of how spread out a random variable is around its mean. Variance answers: on average, how far does land from ?
If , a natural measure of spread is the average squared deviation from the mean:
We square the deviation so that positive and negative deviations do not cancel each other out.
Computational formula. We expand using the binomial expansion :
By linearity of expectation (derived in the RL prerequisites), expectation distributes over the sum:
Since , the last two terms combine: . Therefore:
This is the computational formula for variance. It separates the second moment from the squared first moment .
Numerical check for
For : and (by definition). Plugging into the formula:
This confirms the fact stated in Section 3: the expected square of a standard normal variable is exactly 1. We will use this in Sections 5 and 6.
Interpretation
Variance is not the typical deviation — it is the typical squared deviation. The typical deviation is the standard deviation , which has the same units as . For : . Values of typically fall within 1 unit of zero.
5. Independence and the Expected Value of a Product
Two random variables and are independent if knowing the value of one gives no information about the other. For our vectors, the components are all independent of each other because each was drawn by a separate random process.
For independent random variables, the expected value of their product factors:
This is the multiplication rule for independent expectations.
Derivation. For discrete random variables, expectation is a weighted sum over all outcomes. For a joint pair :
Independence means . Substituting:
Since the sums are over independent indices, we factor the double sum using the distributive law:
Consequence for independently
Since and is independent of :
Each component product has mean zero. The dot product therefore has mean zero too, by linearity of expectation. On average across many random draws, the dot product is centred at zero.
Numerical check
Our values: and . These are two particular values of the random variable . Their sample mean is , not zero. With only two samples, this is expected. The formula tells us that with many such pairs, the average converges to zero.
6. Variance of a Product of Two Independent Standard Normals
We now compute when .
We apply the computational formula from Section 4:
From Section 5, . The second term vanishes:
Since and are independent, and are also independent — any function of independent variables remains independent. Applying the multiplication rule for independent expectations:
From Section 4, for . Therefore:
Each component product has variance exactly 1.
Numerical check
The two component products in our running example are and . Their sample mean is and their sample variance is:
The theoretical value is 1. With only 2 samples, the sample variance is unreliable — we need many draws for convergence. The derivation above gives the exact theoretical value.
7. Additivity of Variance for Independent Variables
When two independent random variables are added, their variances add. This is the additivity of variance (also known as the Bienaymé formula):
Derivation. Let and . By definition:
Write and expand the square using :
By linearity of expectation:
For the middle term: since and are independent, so are and — subtracting a constant does not affect independence. By the multiplication rule:
since . The cross term vanishes exactly, leaving:
By induction — applying the formula repeatedly to each new summand — this extends to any finite number of independent terms:
Numerical check with
In our running example, . Both terms and are independent (they involve separate draws of and components). Additivity gives:
We can verify the formula directly: . Our observed dot product is about standard deviations from zero — a perfectly ordinary draw.
8. The Variance of a Dot Product
We now have every piece. Let us put them together.
The dot product of two -dimensional vectors is a sum of independent component products:
The terms are independent of each other, because all components are drawn independently. Applying the Bienaymé formula:
From Section 6, each . There are terms in the sum:
The standard deviation is .
Numerical check with
. Our running example gave , which is one draw from a distribution with mean 0 and standard deviation . ✓
Why this matters: the scaling
At the head dimension used in the Transformer — — the standard deviation of each dot product is . The inputs to the softmax span a range of roughly (three standard deviations on either side of zero). When and , the softmax concentrates all weight on the single largest score — it degenerates to a near-hard argmax. The gradient of the softmax is nearly zero in this regime, and training stalls. This is the vanishing gradient problem in the softmax.
Dividing by before the softmax fixes this. The scaled score is . When a constant divides a random variable, its variance is scaled by — this is the scaling rule for variance. Applying it:
The scaled scores have exactly unit variance and unit standard deviation. The softmax inputs are well-conditioned, gradients are healthy, and training proceeds.
Numerical check of the scaling rule
With : scaled score . Variance of scaled scores . Standard deviation . The value is now standard deviations from zero — comfortably in the softmax’s well-conditioned regime. ✓
Summary
All seven tools were built from the same two vectors and .
The tanh function maps any real input to the interval ; we computed as a representative alignment score. The dot product is a scalar measure of directional similarity; our two vectors gave . The standard normal distribution has mean zero and variance one, with the key property . Variance measures squared spread around the mean — a result derived in three lines from the binomial expansion and linearity of expectation. For independent random variables, the multiplication rule gives , which combined with yields for each component product. Finally, the Bienaymé formula (additivity of variance for independent variables) chains these single-component results together: , so the standard deviation is , so we divide by to restore unit variance at the softmax input.
With these tools in hand, we are ready for What Attention is Really Doing, where attention is built from scratch starting from the failure of fixed-length context vectors, and From Soft Alignment to Queries, Keys, and Values, where the scaling is derived using exactly the results established in Sections 3–8.
Previous: Mixture of Experts from Scratch — Part 3
Next: What Attention is Really Doing
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.