Xinheng Ding

Math Foundations for ML › Probability & Statistics · Note 1

Expectation and Variance

Oct 18, 2026

Most "why is there a constant here?" questions in deep learning come down to the same four facts about means and variances. These include initialization schemes, normalization layers, and the \(1/\sqrt{d_k}\) in attention. This note collects the definitions and those four rules, with proofs. It then uses them, step by step, to explain why scaled dot-product attention divides by \(\sqrt{d_k}\).

Expectation

A random variable \(X\) is a quantity whose value is decided by chance. Its expectation (mean) is the probability-weighted average of its values:

\[ \mathbb{E}[X] = \sum_x x\,P(X = x) \quad\text{(discrete)}, \qquad \mathbb{E}[X] = \int x\,f(x)\,dx \quad\text{(continuous, with density } f\text{)}. \]

For a fair die, \(\mathbb{E}[X] = \tfrac{1}{6}(1+2+3+4+5+6) = 3.5\). The expectation of a function of \(X\) is computed the same way: \(\mathbb{E}[g(X)] = \sum_x g(x)\,P(X=x)\). We write \(\mu = \mathbb{E}[X]\).

Variance

The variance measures how far \(X\) typically lands from its mean. It is the expected squared deviation:

\[ \operatorname{Var}(X) = \mathbb{E}\big[(X-\mu)^2\big]. \]

Expanding the square gives the form used in almost every calculation:

\[ \operatorname{Var}(X) = \mathbb{E}[X^2 - 2\mu X + \mu^2] = \mathbb{E}[X^2] - 2\mu\,\mathbb{E}[X] + \mu^2 = \mathbb{E}[X^2] - \mu^2 . \]

The second step uses linearity, which is Rule 1 below. Rearranged, this gives a fact we will need later:

\(\mathbb{E}[X^2] = \operatorname{Var}(X) + \mathbb{E}[X]^2.\) In particular, if \(\mathbb{E}[X]=0\) and \(\operatorname{Var}(X)=1\), then \(\mathbb{E}[X^2]=1\).

The standard deviation \(\sigma = \sqrt{\operatorname{Var}(X)}\) has the same units as \(X\). It is the natural answer to "how big is a typical fluctuation?" For a fair die, \(\mathbb{E}[X^2] = 91/6\), so \(\operatorname{Var}(X) = 91/6 - 3.5^2 \approx 2.92\) and \(\sigma \approx 1.71\).

Four rules

Rule 1 · Linearity of expectation

\(\mathbb{E}[aX + bY + c] = a\,\mathbb{E}[X] + b\,\mathbb{E}[Y] + c\) for any constants \(a, b, c\).

Holds for any \(X, Y\). Independence is not required.

Proof (discrete). Sum over the joint distribution: \(\mathbb{E}[aX+bY] = \sum_{x,y}(ax+by)P(x,y) = a\sum_x x\sum_y P(x,y) + b\sum_y y\sum_x P(x,y) = a\,\mathbb{E}[X] + b\,\mathbb{E}[Y]\), because summing the joint probability over one variable leaves the marginal of the other. Constants pass through since \(\sum P = 1\). ∎

Rule 2 · Product of independent variables

If \(X\) and \(Y\) are independent, then \(\mathbb{E}[XY] = \mathbb{E}[X]\,\mathbb{E}[Y]\).

Requires independence. It also applies to \(g(X)\) and \(h(Y)\), since functions of independent variables are independent.

Proof. Independence means \(P(x,y) = P(x)P(y)\), so the double sum factors: \(\mathbb{E}[XY] = \sum_{x,y} xy\,P(x)P(y) = \big(\sum_x x P(x)\big)\big(\sum_y y P(y)\big)\). ∎

Rule 3 · Variance of a sum

\(\operatorname{Var}(X+Y) = \operatorname{Var}(X) + \operatorname{Var}(Y) + 2\operatorname{Cov}(X,Y)\), where \(\operatorname{Cov}(X,Y) = \mathbb{E}[XY] - \mathbb{E}[X]\,\mathbb{E}[Y]\).

If \(X_1,\dots,X_n\) are independent, then \(\operatorname{Var}\big(\sum_i X_i\big) = \sum_i \operatorname{Var}(X_i)\).

Proof. Apply \(\operatorname{Var}(Z) = \mathbb{E}[Z^2] - \mathbb{E}[Z]^2\) to \(Z = X+Y\):

\[ \begin{aligned} \operatorname{Var}(X+Y) &= \mathbb{E}[X^2] + 2\,\mathbb{E}[XY] + \mathbb{E}[Y^2] \\ &\quad - \big(\mathbb{E}[X]^2 + 2\,\mathbb{E}[X]\mathbb{E}[Y] + \mathbb{E}[Y]^2\big) \\ &= \operatorname{Var}(X) + \operatorname{Var}(Y) + 2\big(\mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y]\big). \end{aligned} \]

Under independence, Rule 2 makes the covariance zero. For \(n\) terms, expand the square of the sum. Every cross term is a covariance between two different variables, and each one is zero. ∎

Rule 4 · Scaling by a constant

\[ \begin{aligned} \mathbb{E}[aX + b] &= a\,\mathbb{E}[X] + b \\ \operatorname{Var}(aX + b) &= a^2\operatorname{Var}(X) \\ \sigma_{aX+b} &= |a|\,\sigma_X \end{aligned} \]

Dividing by a constant \(c\) is the case \(a = 1/c\): the mean is divided by \(c\), and the variance by \(c^2\).

Proof. The mean follows from Rule 1. For the variance, the shift \(b\) cancels against the mean: \(\operatorname{Var}(aX+b) = \mathbb{E}\big[(aX + b - a\mu - b)^2\big] = \mathbb{E}\big[a^2(X-\mu)^2\big] = a^2\operatorname{Var}(X)\). ∎

Variance is quadratic, so constants come out squared. A useful special case is standardization: \(Z = (X-\mu)/\sigma\) always has mean 0 and variance 1. That is exactly what normalization layers do to activations.

Common traps: variance is not linear, since \(\operatorname{Var}(X+X) = 4\operatorname{Var}(X)\), not \(2\operatorname{Var}(X)\). Differences add variance too: \(\operatorname{Var}(X-Y) = \operatorname{Var}(X)+\operatorname{Var}(Y)\) for independent \(X, Y\). And \(\mathbb{E}[XY] \ne \mathbb{E}[X]\mathbb{E}[Y]\) in general.

Application: why attention divides by \(\sqrt{d_k}\)

Scaled dot-product attention (Vaswani et al., 2017) computes \(\operatorname{softmax}(QK^\top/\sqrt{d_k})\,V\). The Annotated Transformer implements it in one line:

python
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)

The paper justifies the constant in a short paragraph. Paraphrased, it makes three claims. First, without scaling, dot-product attention does worse than additive attention once \(d_k\) is large, although the two are similar for small \(d_k\). Second, the likely cause is that large dot products push the softmax

"into regions where it has extremely small gradients" Vaswani et al., 2017, §3.2.1

Third, to see why dot products grow, assume the components of \(q\) and \(k\) are independent with mean 0 and variance 1. Then \(q\cdot k\) has mean 0 and variance \(d_k\), so the authors scale it by \(1/\sqrt{d_k}\). The rest of this note derives each step using the four rules.

Why assume mean 0 and variance 1?

The assumption is not a particular distribution. A standard normal, a uniform on \([-\sqrt3,\sqrt3]\) and a fair \(\pm1\) coin all qualify. The derivation uses only means, variances and independence, so the shape does not matter. The scale is chosen because it is the natural reference point, and it is roughly what the network sees at initialization: the inputs to attention are layer-normalized, and the projection weights are initialized (e.g. Xavier) to preserve variance. The question being asked is therefore: if every component has an ordinary size, how big is their dot product?

Step 1 · One term \(q_i k_i\)

By Rule 2, using the independence of \(q_i\) and \(k_i\):

\[ \mathbb{E}[q_i k_i] = \mathbb{E}[q_i]\,\mathbb{E}[k_i] = 0 \cdot 0 = 0. \]

For the variance, use \(\operatorname{Var} = \mathbb{E}[\,\cdot^2] - \mathbb{E}[\,\cdot\,]^2\). Then apply Rule 2 to \(q_i^2\) and \(k_i^2\), which are also independent:

\[ \operatorname{Var}(q_i k_i) = \mathbb{E}[q_i^2 k_i^2] - 0^2 = \mathbb{E}[q_i^2]\,\mathbb{E}[k_i^2] = 1 \cdot 1 = 1, \]

where \(\mathbb{E}[q_i^2] = \operatorname{Var}(q_i) + \mathbb{E}[q_i]^2 = 1\) comes from the identity in the variance section.

Step 2 · Sum of \(d_k\) terms

The dot product is \(q\cdot k = \sum_{i=1}^{d_k} q_i k_i\). Different terms use different components, so the \(d_k\) terms are independent. Linearity gives the mean, and Rule 3 gives the variance:

\[ \mathbb{E}[q\cdot k] = \sum_{i=1}^{d_k} \mathbb{E}[q_i k_i] = 0, \qquad \operatorname{Var}(q\cdot k) = \sum_{i=1}^{d_k} \operatorname{Var}(q_i k_i) = d_k . \]

The typical size of a dot product is therefore \(\sigma = \sqrt{d_k}\). For the paper's \(d_k = 64\), that is 8. Each term is a random-sign number of size about 1. Summing \(d_k\) of them, the signs partly cancel, so the total grows like \(\sqrt{d_k}\), not \(d_k\). This is the same law as a random walk.

dk = 4std ≈ 2.0dk = 64std ≈ 8.0dk = 512std ≈ 22.6-60-300+30+60q · k (20,000 samples per row)
Figure 1: Dot products spread out as \(\sqrt{d_k}\). Each row shows 20,000 samples of \(q\cdot k\) with i.i.d. standard-normal components. Brackets mark \(\pm\) one standard deviation. Measured variances: 4.00, 63.73 and 516.07, against the predicted 4, 64 and 512.

Step 3 · Divide by \(\sqrt{d_k}\)

Apply Rule 4 with \(a = 1/\sqrt{d_k}\):

\[ \mathbb{E}\!\left[\frac{q\cdot k}{\sqrt{d_k}}\right] = \frac{0}{\sqrt{d_k}} = 0, \qquad \operatorname{Var}\!\left(\frac{q\cdot k}{\sqrt{d_k}}\right) = \frac{1}{d_k}\cdot d_k = 1 . \]

The variance of a score is now 1 regardless of \(d_k\). In simulation, it measures 1.000, 0.996 and 1.008 for \(d_k\) = 4, 64 and 512. The constant is \(\sqrt{d_k}\) and not \(d_k\) because Rule 4 squares it. Dividing by \(d_k\) would give variance \(1/d_k\), which squeezes all scores toward 0 and makes every attention row nearly uniform.

Step 4 · Why large scores starve the gradient

Strictly speaking, the problem is not \(d_k\) itself but the size of the scores, whose standard deviation is \(\sqrt{d_k}\). The paper's claim is that large scores push the softmax into a region where its gradient nearly vanishes. To see what that region is, start with the smallest case.

Two keys. Softmax only depends on differences between scores, because adding a constant to every \(z_j\) cancels in the ratio. With two keys and gap \(\Delta = z_1 - z_2\),

\[ p_1 = \frac{e^{z_1}}{e^{z_1} + e^{z_2}} = \frac{1}{1 + e^{-\Delta}} = \sigma(\Delta), \qquad \frac{dp_1}{d\Delta} = p_1(1 - p_1). \]

So a two-key softmax is a sigmoid of the gap. A sigmoid is steep in the middle and flat at both ends. The "region with extremely small gradients" is those flat ends. There, \(p_1\) is already close to 0 or 1, and moving the scores barely changes the output.

saturatedsaturated-12-8-40+4+8+1200.51score gap Δ = z₁ − z₂p₁ = sigmoid(Δ)slope p₁(1−p₁), ×40.250.1050.00034scaled: |Δ| ≈ 1–2unscaled, dk = 64: |Δ| ≈ 8–16
Figure 2: A two-key softmax is a sigmoid of the score gap. The slope \(p_1(1-p_1)\) (blue, drawn ×4) is 0.25 at \(\Delta = 0\) and decays by roughly a factor of \(e\) for each unit of gap. Scaled scores keep typical gaps of 1–2, near the steep middle. Unscaled scores with \(d_k = 64\) produce gaps of 8–16, deep in the flat tails.
Gap \(\Delta\)\(p_1\)\(p_2\)Slope \(p_1(1-p_1)\)
00.5000.5000.25
10.7310.2690.197
20.8810.1190.105
40.9820.0180.018
80.999670.000340.00034
16≈ 11.1 × 10⁻⁷1.1 × 10⁻⁷

Going from a gap of 0 to a gap of 8 shrinks the slope about 750 times. For large \(\Delta\), \(p_1(1-p_1) \approx e^{-\Delta}\), so the decay is exponential in the gap.

Many keys. With \(m\) keys, the derivative is a Jacobian matrix. Write \(p_i = e^{z_i}/S\) with \(S = \sum_j e^{z_j}\), and note that \(\partial S/\partial z_j = e^{z_j}\). The quotient rule gives

\[ \begin{aligned} \frac{\partial p_i}{\partial z_i} &= \frac{e^{z_i} S - e^{z_i} e^{z_i}}{S^2} = p_i(1-p_i), \\[4pt] \frac{\partial p_i}{\partial z_j} &= \frac{0 - e^{z_i} e^{z_j}}{S^2} = -\,p_i\,p_j \quad (i \ne j). \end{aligned} \]

When one score is far above the rest, \(p\) is nearly one-hot. Every entry of the Jacobian then contains a factor that is close to 0. On the diagonal, the winner has \(1 - p_i \approx 0\) and every loser has \(p_i \approx 0\). Off the diagonal, at least one of \(p_i, p_j\) is close to 0. The whole matrix is close to zero: this is the many-key version of the flat tails.

without scaling0-1.040-6.830-7.020.004+3.251.00+8.74zmax p(1−p) = 0.004divided by √64 = 80.14-0.130.07-0.850.07-0.880.24+0.410.48+1.09zmax p(1−p) = 0.250
Figure 3: The same five scores, before and after scaling (one draw with \(d_k = 64\)). Unscaled, softmax puts 99.6% of the weight on one key and the largest Jacobian entry is 0.004. Scaled, the weights are spread out and the largest entry is 0.250, about 60× larger.

A temperature view. Dividing every score by a constant \(T\) is the same as running softmax at temperature \(T\). Low temperature (scores effectively multiplied up) makes softmax sharp and close to argmax. High temperature makes it smooth and close to uniform. Without scaling, the effective temperature of attention falls as \(1/\sqrt{d_k}\) when \(d_k\) grows. Dividing by \(\sqrt{d_k}\) fixes the temperature at a value that does not depend on \(d_k\).

What it does to training. The loss reaches the query and key projections only through the softmax:

\[ \frac{\partial L}{\partial z} = J^\top \frac{\partial L}{\partial p}, \qquad J = \operatorname{diag}(p) - p\,p^\top, \]

and \(\partial L/\partial W_Q\), \(\partial L/\partial W_K\) are computed from \(\partial L/\partial z\). If \(J \approx 0\), those gradients are close to 0 too. At initialization, the random projections make each query attend almost entirely to one arbitrary key. If that key is wrong, the loss has almost no way to say "look elsewhere", because the signal is crushed as it passes back through the softmax. This is a local saturation of one function, not the layer-by-layer shrinking usually called vanishing gradients, but the effect is similar: attention learns slowly or not at all.

This is the whole argument. Rules 2 and 3 show that the scores grow like \(\sqrt{d_k}\). Rule 4 shows that dividing by \(\sqrt{d_k}\) undoes this exactly. The softmax Jacobian shows why it matters: without the constant, attention would start out nearly one-hot, with almost no gradient to move it.

Summary

FactStatementNeeds
Variance identity\(\operatorname{Var}(X) = \mathbb{E}[X^2] - \mathbb{E}[X]^2\)Nothing
Linearity\(\mathbb{E}[aX+bY] = a\mathbb{E}[X] + b\mathbb{E}[Y]\)Nothing
Product\(\mathbb{E}[XY] = \mathbb{E}[X]\mathbb{E}[Y]\)Independence
Sum\(\operatorname{Var}(\sum X_i) = \sum \operatorname{Var}(X_i)\)Independence (zero covariance)
Scaling\(\operatorname{Var}(aX+b) = a^2\operatorname{Var}(X)\)Nothing
Attention\(\operatorname{Var}(q\cdot k) = d_k\), so \(\operatorname{Var}(q\cdot k/\sqrt{d_k}) = 1\)i.i.d. components, mean 0, variance 1

Appendix: the simulation

Pure Python, no dependencies. It produces every number quoted above.

dot_product_sim.py
python
"""Simulate q·k for q, k with i.i.d. N(0, 1) components, before and after dividing by sqrt(d_k)."""
import math
import random
import statistics as st

random.seed(0)
N = 20000


def dot(d):
    return sum(random.gauss(0, 1) * random.gauss(0, 1) for _ in range(d))


print(f"{'d_k':>5} {'mean':>8} {'var':>9} {'std':>7} {'scaled var':>11}")
for d in (4, 64, 512):
    xs = [dot(d) for _ in range(N)]
    scaled = [x / math.sqrt(d) for x in xs]
    print(f"{d:>5} {st.mean(xs):>+8.3f} {st.pvariance(xs):>9.2f} {st.pstdev(xs):>7.2f} {st.pvariance(scaled):>11.3f}")


def softmax(z):
    m = max(z)
    e = [math.exp(v - m) for v in z]
    s = sum(e)
    return [v / s for v in e]


random.seed(1)
d = 64
z = [dot(d) for _ in range(5)]
for name, scores in (("raw", z), ("scaled", [v / math.sqrt(d) for v in z])):
    p = softmax(scores)
    print(f"\n{name:>6} scores : {[round(v, 2) for v in scores]}")
    print(f"{name:>6} softmax: {[round(v, 3) for v in p]}")
    print(f"{name:>6} max p(1-p) = {max(v * (1 - v) for v in p):.4f}")
output
  d_k     mean       var     std  scaled var
    4   +0.008      4.00    2.00       1.000
   64   -0.006     63.73    7.98       0.996
  512   +0.018    516.07   22.72       1.008

   raw scores : [-1.04, -6.83, -7.02, 3.25, 8.74]
   raw softmax: [0.0, 0.0, 0.0, 0.004, 0.996]
   raw max p(1-p) = 0.0042

scaled scores : [-0.13, -0.85, -0.88, 0.41, 1.09]
scaled softmax: [0.142, 0.069, 0.067, 0.242, 0.481]
scaled max p(1-p) = 0.2496

Related: Attention Masks in the Transformer.

机器学习中的数学基础 › 概率论与统计 · 第 1 篇

期望与方差

2026 年 10 月 18 日

深度学习里很多"这里为什么要乘一个常数"的问题,比如初始化方法、归一化层、attention 里的 \(1/\sqrt{d_k}\), 最后都归结到关于均值和方差的同样四条规则。这篇笔记先整理定义和这四条规则,并给出证明; 然后用它们一步一步推导:为什么 scaled dot-product attention 要除以 \(\sqrt{d_k}\)。

期望

随机变量 \(X\) 是一个取值由随机性决定的量。它的期望(均值)是按概率加权的平均值:

\[ \mathbb{E}[X] = \sum_x x\,P(X = x) \quad\text{(离散)}, \qquad \mathbb{E}[X] = \int x\,f(x)\,dx \quad\text{(连续,}f\text{ 为概率密度)}. \]

例如掷一个均匀的骰子,\(\mathbb{E}[X] = \tfrac{1}{6}(1+2+3+4+5+6) = 3.5\)。\(X\) 的函数的期望也用同样的方法计算: \(\mathbb{E}[g(X)] = \sum_x g(x)\,P(X=x)\)。下文记 \(\mu = \mathbb{E}[X]\)。

方差

方差衡量 \(X\) 通常偏离均值多远,定义为偏差平方的期望:

\[ \operatorname{Var}(X) = \mathbb{E}\big[(X-\mu)^2\big]. \]

把平方展开,就得到几乎所有计算中都会用到的形式:

\[ \operatorname{Var}(X) = \mathbb{E}[X^2 - 2\mu X + \mu^2] = \mathbb{E}[X^2] - 2\mu\,\mathbb{E}[X] + \mu^2 = \mathbb{E}[X^2] - \mu^2 . \]

其中第二步用到了期望的线性性(下面的规则 1)。把它移项,得到一个后面会用到的结论:

\(\mathbb{E}[X^2] = \operatorname{Var}(X) + \mathbb{E}[X]^2\)。特别地,若 \(\mathbb{E}[X]=0\)、\(\operatorname{Var}(X)=1\),则 \(\mathbb{E}[X^2]=1\)。

标准差 \(\sigma = \sqrt{\operatorname{Var}(X)}\) 与 \(X\) 的单位相同,可以直接回答"典型的波动有多大"。 对骰子来说,\(\mathbb{E}[X^2] = 91/6\),所以 \(\operatorname{Var}(X) = 91/6 - 3.5^2 \approx 2.92\),\(\sigma \approx 1.71\)。

四条规则

规则 1 · 期望的线性性

对任意常数 \(a, b, c\),有 \(\mathbb{E}[aX + bY + c] = a\,\mathbb{E}[X] + b\,\mathbb{E}[Y] + c\)。

对任意 \(X, Y\) 都成立,不需要独立。

证明(离散情形):对联合分布求和, \(\mathbb{E}[aX+bY] = \sum_{x,y}(ax+by)P(x,y) = a\sum_x x\sum_y P(x,y) + b\sum_y y\sum_x P(x,y) = a\,\mathbb{E}[X] + b\,\mathbb{E}[Y]\)。 这是因为联合概率对一个变量求和,就得到另一个变量的边缘分布。常数可以直接提出来,因为 \(\sum P = 1\)。 ∎

规则 2 · 独立变量乘积的期望

若 \(X\) 与 \(Y\) 独立,则 \(\mathbb{E}[XY] = \mathbb{E}[X]\,\mathbb{E}[Y]\)。

需要独立。它也适用于 \(g(X)\) 和 \(h(Y)\),因为独立变量的函数仍然独立。

证明:独立意味着 \(P(x,y) = P(x)P(y)\),所以二重求和可以拆开: \(\mathbb{E}[XY] = \sum_{x,y} xy\,P(x)P(y) = \big(\sum_x x P(x)\big)\big(\sum_y y P(y)\big)\)。∎

规则 3 · 和的方差

\(\operatorname{Var}(X+Y) = \operatorname{Var}(X) + \operatorname{Var}(Y) + 2\operatorname{Cov}(X,Y)\),其中 \(\operatorname{Cov}(X,Y) = \mathbb{E}[XY] - \mathbb{E}[X]\,\mathbb{E}[Y]\) 是协方差。

若 \(X_1,\dots,X_n\) 相互独立,则 \(\operatorname{Var}\big(\sum_i X_i\big) = \sum_i \operatorname{Var}(X_i)\)。

证明:对 \(Z = X+Y\) 使用 \(\operatorname{Var}(Z) = \mathbb{E}[Z^2] - \mathbb{E}[Z]^2\):

\[ \begin{aligned} \operatorname{Var}(X+Y) &= \mathbb{E}[X^2] + 2\,\mathbb{E}[XY] + \mathbb{E}[Y^2] \\ &\quad - \big(\mathbb{E}[X]^2 + 2\,\mathbb{E}[X]\mathbb{E}[Y] + \mathbb{E}[Y]^2\big) \\ &= \operatorname{Var}(X) + \operatorname{Var}(Y) + 2\big(\mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y]\big). \end{aligned} \]

独立时,由规则 2 可知协方差为 0。推广到 \(n\) 项:把和的平方展开,每个交叉项都是两个不同变量的协方差,全部为 0。∎

规则 4 · 乘以(除以)常数

\[ \begin{aligned} \mathbb{E}[aX + b] &= a\,\mathbb{E}[X] + b \\ \operatorname{Var}(aX + b) &= a^2\operatorname{Var}(X) \\ \sigma_{aX+b} &= |a|\,\sigma_X \end{aligned} \]

除以常数 \(c\) 就是 \(a = 1/c\) 的情形:均值除以 \(c\),方差除以 \(c^2\)。

证明:均值由规则 1 直接得到。方差中,平移 \(b\) 和均值里的 \(b\) 相互抵消: \(\operatorname{Var}(aX+b) = \mathbb{E}\big[(aX + b - a\mu - b)^2\big] = \mathbb{E}\big[a^2(X-\mu)^2\big] = a^2\operatorname{Var}(X)\)。∎

方差是二次的,所以常数提出来时要平方。一个常用的特例是标准化:\(Z = (X-\mu)/\sigma\) 的均值一定是 0,方差一定是 1。 归一化层对激活值做的就是这件事。

几个常见的坑:方差不是线性的,\(\operatorname{Var}(X+X) = 4\operatorname{Var}(X)\),而不是 \(2\operatorname{Var}(X)\); 相减也会让方差相加,独立时 \(\operatorname{Var}(X-Y) = \operatorname{Var}(X)+\operatorname{Var}(Y)\); 一般情况下 \(\mathbb{E}[XY] \ne \mathbb{E}[X]\mathbb{E}[Y]\)。

应用:attention 为什么要除以 \(\sqrt{d_k}\)

Scaled dot-product attention(Vaswani et al., 2017)计算的是 \(\operatorname{softmax}(QK^\top/\sqrt{d_k})\,V\)。The Annotated Transformer 里用一行代码实现:

python
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k)

论文用一小段话说明了这个常数的来由,大意有三点。第一,\(d_k\) 较小时,点积注意力和加性注意力效果相近; \(d_k\) 较大时,不缩放的点积注意力不如加性注意力。第二,作者推测原因是点积数值太大,把 softmax 推进了

"into regions where it has extremely small gradients"(梯度极小的区域) Vaswani et al., 2017, §3.2.1

第三,为了说明点积为什么会变大,假设 \(q\) 和 \(k\) 的各个分量相互独立,均值为 0,方差为 1; 那么 \(q\cdot k\) 的均值是 0,方差是 \(d_k\),所以作者把它乘以 \(1/\sqrt{d_k}\)。下面用四条规则逐步推导这几个结论。

为什么假设均值 0、方差 1?

这个假设并不是指某个特定的分布:标准正态分布、\([-\sqrt3,\sqrt3]\) 上的均匀分布、等概率取 \(\pm1\) 的分布,都满足它。 推导只用到均值、方差和独立性,分布的具体形状不重要。选这个尺度,是因为它是最自然的基准,也大致符合网络初始化时的真实情况: attention 的输入经过了 LayerNorm,投影矩阵也用 Xavier 等方法初始化,使方差保持不变。所以这里真正要问的是: 如果每个分量都只是正常大小,它们的点积会有多大?

第 1 步 · 单独一项 \(q_i k_i\)

\(q_i\) 与 \(k_i\) 独立,由规则 2:

\[ \mathbb{E}[q_i k_i] = \mathbb{E}[q_i]\,\mathbb{E}[k_i] = 0 \cdot 0 = 0. \]

方差用 \(\operatorname{Var} = \mathbb{E}[\,\cdot^2] - \mathbb{E}[\,\cdot\,]^2\),再对同样独立的 \(q_i^2\) 和 \(k_i^2\) 使用规则 2:

\[ \operatorname{Var}(q_i k_i) = \mathbb{E}[q_i^2 k_i^2] - 0^2 = \mathbb{E}[q_i^2]\,\mathbb{E}[k_i^2] = 1 \cdot 1 = 1, \]

其中 \(\mathbb{E}[q_i^2] = \operatorname{Var}(q_i) + \mathbb{E}[q_i]^2 = 1\),来自方差一节的恒等式。

第 2 步 · \(d_k\) 项求和

点积是 \(q\cdot k = \sum_{i=1}^{d_k} q_i k_i\)。不同的项用的是不同的分量,所以这 \(d_k\) 项相互独立。 由线性性得到均值,由规则 3 得到方差:

\[ \mathbb{E}[q\cdot k] = \sum_{i=1}^{d_k} \mathbb{E}[q_i k_i] = 0, \qquad \operatorname{Var}(q\cdot k) = \sum_{i=1}^{d_k} \operatorname{Var}(q_i k_i) = d_k . \]

所以点积的典型大小是 \(\sigma = \sqrt{d_k}\),论文中 \(d_k = 64\),即 8。直观地说:每一项都是一个正负随机、大小约为 1 的数; \(d_k\) 个这样的数相加,正负会部分抵消,总和以 \(\sqrt{d_k}\) 而不是 \(d_k\) 的速度增长。这和随机游走是同一个规律。

dk = 4std ≈ 2.0dk = 64std ≈ 8.0dk = 512std ≈ 22.6-60-300+30+60q · k (20,000 samples per row)
图 1:点积的分散程度按 \(\sqrt{d_k}\) 增长。每一行是 \(q\cdot k\) 的 20000 个样本,各分量独立服从标准正态分布; 括号标出 \(\pm\) 一个标准差。实测方差为 4.00、63.73、516.07,理论值为 4、64、512。

第 3 步 · 除以 \(\sqrt{d_k}\)

取 \(a = 1/\sqrt{d_k}\),使用规则 4:

\[ \mathbb{E}\!\left[\frac{q\cdot k}{\sqrt{d_k}}\right] = \frac{0}{\sqrt{d_k}} = 0, \qquad \operatorname{Var}\!\left(\frac{q\cdot k}{\sqrt{d_k}}\right) = \frac{1}{d_k}\cdot d_k = 1 . \]

现在打分的方差是 1,与 \(d_k\) 无关;模拟中 \(d_k\) = 4、64、512 时分别测得 1.000、0.996、1.008。 常数取 \(\sqrt{d_k}\) 而不是 \(d_k\),是因为规则 4 会把它平方。如果除以 \(d_k\),方差会变成 \(1/d_k\), 所有打分都挤向 0,每一行的注意力都接近均匀分布。

第 4 步 · 打分太大为什么会让梯度消失

严格来说,问题不在 \(d_k\) 本身,而在打分的大小:打分的标准差是 \(\sqrt{d_k}\)。 论文说,打分太大会把 softmax 推进一个梯度几乎为 0 的区域。要看清楚这个区域是什么,先从最简单的情况说起。

两个 key。softmax 只依赖打分之间的差距:给每个 \(z_j\) 加上同一个常数,分子分母会相互抵消。 只有两个 key、差距为 \(\Delta = z_1 - z_2\) 时,

\[ p_1 = \frac{e^{z_1}}{e^{z_1} + e^{z_2}} = \frac{1}{1 + e^{-\Delta}} = \sigma(\Delta), \qquad \frac{dp_1}{d\Delta} = p_1(1 - p_1). \]

也就是说,两个元素的 softmax 就是差距的 sigmoid。sigmoid 中间陡、两端平。论文说的"梯度极小的区域"指的就是这两端平坦的部分: 那里 \(p_1\) 已经接近 0 或 1,打分再怎么变,输出也几乎不变。

saturatedsaturated-12-8-40+4+8+1200.51score gap Δ = z₁ − z₂p₁ = sigmoid(Δ)slope p₁(1−p₁), ×40.250.1050.00034scaled: |Δ| ≈ 1–2unscaled, dk = 64: |Δ| ≈ 8–16
图 2:两个 key 的 softmax 就是打分差距的 sigmoid。斜率 \(p_1(1-p_1)\)(蓝色,放大 4 倍绘制)在 \(\Delta = 0\) 时为 0.25, 差距每增加 1,大约缩小为原来的 \(1/e\)。缩放后,典型差距是 1–2,处在中间陡峭的区域; \(d_k = 64\) 且不缩放时,差距是 8–16,深入两端的平坦区。
差距 \(\Delta\)\(p_1\)\(p_2\)斜率 \(p_1(1-p_1)\)
00.5000.5000.25
10.7310.2690.197
20.8810.1190.105
40.9820.0180.018
80.999670.000340.00034
16≈ 11.1 × 10⁻⁷1.1 × 10⁻⁷

差距从 0 增加到 8,斜率缩小了约 750 倍。\(\Delta\) 较大时 \(p_1(1-p_1) \approx e^{-\Delta}\),所以衰减是关于差距的指数衰减。

多个 key。有 \(m\) 个 key 时,导数是一个雅可比矩阵。记 \(p_i = e^{z_i}/S\),其中 \(S = \sum_j e^{z_j}\),并注意 \(\partial S/\partial z_j = e^{z_j}\)。用商的求导法则:

\[ \begin{aligned} \frac{\partial p_i}{\partial z_i} &= \frac{e^{z_i} S - e^{z_i} e^{z_i}}{S^2} = p_i(1-p_i), \\[4pt] \frac{\partial p_i}{\partial z_j} &= \frac{0 - e^{z_i} e^{z_j}}{S^2} = -\,p_i\,p_j \quad (i \ne j). \end{aligned} \]

当某个打分远大于其他打分时,\(p\) 接近 one-hot,雅可比矩阵的每一项都含有一个接近 0 的因子:对角线上,胜出的那项 \(1 - p_i \approx 0\), 其余各项 \(p_i \approx 0\);非对角线上,\(p_i\)、\(p_j\) 至少有一个接近 0。整个矩阵都接近 0,这就是多维情况下的"平坦区"。

without scaling0-1.040-6.830-7.020.004+3.251.00+8.74zmax p(1−p) = 0.004divided by √64 = 80.14-0.130.07-0.850.07-0.880.24+0.410.48+1.09zmax p(1−p) = 0.250
图 3:同样五个打分,缩放前后对比(\(d_k = 64\) 的一次采样)。不缩放时,softmax 把 99.6% 的权重给了一个 key, 雅可比矩阵最大的一项只有 0.004;缩放后权重分散开,最大的一项是 0.250,约大 60 倍。

温度的视角。把所有打分除以一个常数 \(T\),等价于以温度 \(T\) 做 softmax。温度低(相当于打分被放大)时,softmax 尖锐,接近 argmax; 温度高时,softmax 平滑,接近均匀分布。不缩放时,随着 \(d_k\) 增大,attention 的等效温度按 \(1/\sqrt{d_k}\) 下降; 除以 \(\sqrt{d_k}\),就把温度固定在一个与 \(d_k\) 无关的值上。

对训练的影响。loss 只能经过 softmax 才能传到 query 和 key 的投影矩阵:

\[ \frac{\partial L}{\partial z} = J^\top \frac{\partial L}{\partial p}, \qquad J = \operatorname{diag}(p) - p\,p^\top, \]

而 \(\partial L/\partial W_Q\)、\(\partial L/\partial W_K\) 都由 \(\partial L/\partial z\) 计算得到。如果 \(J \approx 0\),这些梯度也接近 0。 初始化时,随机的投影矩阵会让每个 query 几乎把全部注意力压在某个随机的 key 上;如果这个 key 选错了,loss 几乎无法告诉模型"应该看别处", 因为信号在经过 softmax 回传时被压没了。这是单个函数的局部饱和,不同于常说的"梯度逐层变小"的梯度消失,但效果相似:attention 学得很慢,甚至学不动。

整个论证就是这样:规则 2 和规则 3 说明打分按 \(\sqrt{d_k}\) 增长;规则 4 说明除以 \(\sqrt{d_k}\) 正好抵消它; softmax 的雅可比矩阵说明这件事为什么重要。如果没有这个常数,attention 一开始就接近 one-hot,几乎没有梯度能调整它。

总结

结论公式条件
方差恒等式\(\operatorname{Var}(X) = \mathbb{E}[X^2] - \mathbb{E}[X]^2\)无
线性性\(\mathbb{E}[aX+bY] = a\mathbb{E}[X] + b\mathbb{E}[Y]\)无
乘积\(\mathbb{E}[XY] = \mathbb{E}[X]\mathbb{E}[Y]\)独立
求和\(\operatorname{Var}(\sum X_i) = \sum \operatorname{Var}(X_i)\)独立(协方差为 0)
缩放\(\operatorname{Var}(aX+b) = a^2\operatorname{Var}(X)\)无
attention\(\operatorname{Var}(q\cdot k) = d_k\),所以 \(\operatorname{Var}(q\cdot k/\sqrt{d_k}) = 1\)分量独立同分布,均值 0,方差 1

附录:模拟代码

纯 Python,不依赖任何库,可以复现上文引用的所有数字。

dot_product_sim.py
python
"""Simulate q·k for q, k with i.i.d. N(0, 1) components, before and after dividing by sqrt(d_k)."""
import math
import random
import statistics as st

random.seed(0)
N = 20000


def dot(d):
    return sum(random.gauss(0, 1) * random.gauss(0, 1) for _ in range(d))


print(f"{'d_k':>5} {'mean':>8} {'var':>9} {'std':>7} {'scaled var':>11}")
for d in (4, 64, 512):
    xs = [dot(d) for _ in range(N)]
    scaled = [x / math.sqrt(d) for x in xs]
    print(f"{d:>5} {st.mean(xs):>+8.3f} {st.pvariance(xs):>9.2f} {st.pstdev(xs):>7.2f} {st.pvariance(scaled):>11.3f}")


def softmax(z):
    m = max(z)
    e = [math.exp(v - m) for v in z]
    s = sum(e)
    return [v / s for v in e]


random.seed(1)
d = 64
z = [dot(d) for _ in range(5)]
for name, scores in (("raw", z), ("scaled", [v / math.sqrt(d) for v in z])):
    p = softmax(scores)
    print(f"\n{name:>6} scores : {[round(v, 2) for v in scores]}")
    print(f"{name:>6} softmax: {[round(v, 3) for v in p]}")
    print(f"{name:>6} max p(1-p) = {max(v * (1 - v) for v in p):.4f}")
output
  d_k     mean       var     std  scaled var
    4   +0.008      4.00    2.00       1.000
   64   -0.006     63.73    7.98       0.996
  512   +0.018    516.07   22.72       1.008

   raw scores : [-1.04, -6.83, -7.02, 3.25, 8.74]
   raw softmax: [0.0, 0.0, 0.0, 0.004, 0.996]
   raw max p(1-p) = 0.0042

scaled scores : [-0.13, -0.85, -0.88, 0.41, 1.09]
scaled softmax: [0.142, 0.069, 0.067, 0.242, 0.481]
scaled max p(1-p) = 0.2496

相关笔记:Transformer 中的 Attention Mask。