TExcelTAD
Home › Math for Deep Learning & LLMs › Scaled Dot-Product Attention

Scaled Dot-Product Attention

Attention lets every position of a sequence gather information from every other position in a single step, with weights computed from the data. It is a soft, differentiable dictionary lookup: each query is compared with all keys, the similarities become a probability distribution by a softmax, and the output is the correspondingly weighted average of the values. The linear-algebra view is in Attention as Linear Algebra.

The formula

For nn positions with queries Q∈Rn×dkQ \in \mathbb{R}^{n \times d_k}, keys K∈Rm×dkK \in \mathbb{R}^{m \times d_k} and values V∈Rm×dvV \in \mathbb{R}^{m \times d_v}:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QKTdk)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^T}{\sqrt{d_k}}\right)V

The softmax is taken along each row, so row ii of the weight matrix A=softmax⁡(QKT/dk)A = \operatorname{softmax}(QK^T/\sqrt{d_k}) is a distribution over the mm keys, and output ii is ∑jAijvj\sum_j A_{ij}\mathbf{v}_j. In self-attention, Q=XWQQ = XW_Q, K=XWKK = XW_K, V=XWVV = XW_V all come from the same sequence XX.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
n, d_model, d_k = 4, 8, 4
X = rng.normal(size=(n, d_model))
WQ, WK, WV = (rng.normal(0, d_model**-0.5, (d_model, d_k)) for _ in range(3))
Q, K, V = X @ WQ, X @ WK, X @ WV
S = Q @ K.T / np.sqrt(d_k)
A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True)
out = A @ V
print("attention weights (rows sum to 1):\n", np.round(A, 3))
print("output shape:", out.shape)
print("output row 0 = weighted average of value rows:", np.allclose(out[0], sum(A[0, j] * V[j] for j in range(n))))
attention weights (rows sum to 1):
 [[0.276 0.242 0.283 0.2  ]
 [0.212 0.137 0.287 0.364]
 [0.398 0.133 0.296 0.173]
 [0.19  0.27  0.236 0.305]]
output shape: (4, 4)
output row 0 = weighted average of value rows: True

Why divide by the square root of the key dimension

If the entries of q\mathbf{q} and k\mathbf{k} are independent with mean 0 and variance 1, then qTk=∑i=1dkqiki\mathbf{q}^T\mathbf{k} = \sum_{i=1}^{d_k}q_ik_i has variance dkd_k. For dk=128d_k = 128 the scores have standard deviation about 11, the softmax becomes nearly one-hot, and its gradient vanishes (the Jacobian diag⁡(p)−ppT\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^T is almost zero for a one-hot p\mathbf{p}, see Softmax Gradient). Dividing by dk\sqrt{d_k} restores unit variance.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
for d_k in (4, 64, 512):
    q = rng.normal(size=(2000, d_k)); k = rng.normal(size=(2000, d_k))
    raw = np.sum(q * k, axis=1)
    scores = rng.normal(size=(1000, 16)) * np.sqrt(d_k)              # 16 keys, unscaled score spread
    p = np.exp(scores - scores.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
    print(f"d_k={d_k:3d}: std of q.k = {raw.std():6.2f} (sqrt d_k = {np.sqrt(d_k):5.2f}); "
          f"unscaled softmax max weight {p.max(1).mean():.3f}, scaled std {np.std(raw / np.sqrt(d_k)):.2f}")
d_k=  4: std of q.k =   2.01 (sqrt d_k =  2.00); unscaled softmax max weight 0.467, scaled std 1.01
d_k= 64: std of q.k =   8.02 (sqrt d_k =  8.00); unscaled softmax max weight 0.845, scaled std 1.00
d_k=512: std of q.k =  22.33 (sqrt d_k = 22.63); unscaled softmax max weight 0.947, scaled std 0.99

Properties

  • Permutation equivariance: permuting the rows of XX permutes the output rows the same way. Attention alone has no notion of order, hence positional encodings.
  • Cost: the score matrix is n×nn \times n, so time and memory grow as O(n2d)O(n^2d) and O(n2)O(n^2) in the sequence length. FlashAttention avoids storing it by computing the softmax in blocks with a running maximum (Overflow and a Stable Softmax).
  • Content-based routing: the weights depend on the input, unlike a convolution's fixed kernel. One layer can connect any two positions.

The gradient

With S=QKT/dkS = QK^T/\sqrt{d_k}, A=softmax⁡(S)A = \operatorname{softmax}(S) and O=AVO = AV, backprop gives ∂L/∂V=ATG\partial\mathcal{L}/\partial V = A^T G, ∂L/∂A=GVT\partial\mathcal{L}/\partial A = GV^T, then through each row's softmax ∂L/∂Si=Ai⊙(∂L/∂Ai−Ai⋅∂L/∂Ai)\partial\mathcal{L}/\partial S_{i} = A_i \odot (\partial\mathcal{L}/\partial A_i - A_i \cdot \partial\mathcal{L}/\partial A_i), and finally ∂L/∂Q=(∂L/∂S)K/dk\partial\mathcal{L}/\partial Q = (\partial\mathcal{L}/\partial S)K/\sqrt{d_k}, ∂L/∂K=(∂L/∂S)TQ/dk\partial\mathcal{L}/\partial K = (\partial\mathcal{L}/\partial S)^TQ/\sqrt{d_k}.

In software

  • torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True) dispatches to FlashAttention or memory-efficient kernels.
  • Tensors are shaped (batch, heads, seq, head_dim); einsum("bhqd,bhkd->bhqk", q, k) computes all score matrices at once (Einsum and Broadcasting).
  • Cross-attention (decoder queries over encoder keys and values) uses m≠nm \ne n.

Go further: Attention from Scratch adds batches with padding masks and checks the result against PyTorch.

Exercises

Exercise 1: Attention by hand

One query q=(1,0)\mathbf{q} = (1, 0), keys k1=(1,0)\mathbf{k}_1 = (1, 0), k2=(0,1)\mathbf{k}_2 = (0, 1), values v1=10v_1 = 10, v2=20v_2 = 20, dk=2d_k = 2. Compute the output.

Answer

About 13.313.3.

Solution

Scores 1/2=0.7071/\sqrt{2} = 0.707 and 00. Weights e0.707e0.707+1=0.670\frac{e^{0.707}}{e^{0.707} + 1} = 0.670 and 0.3300.330. Output 6.70+6.60=13.306.70 + 6.60 = 13.30.

Exercise 2: Memory of the score matrix

For a sequence of 32,768 tokens, 32 heads and fp16 scores, how much memory would materialized score matrices need for one layer and one sequence?

Answer

About 68.7 GB.

Solution

32,7682⋅32⋅2=6.87×101032{,}768^2 \cdot 32 \cdot 2 = 6.87 \times 10^{10} bytes. This is why long-context attention never materializes them.

Exercise 3: Permutation equivariance (code)

Check numerically that permuting the input rows of self-attention permutes the output rows in the same way.

Answer

The outputs match after permutation.

Solution
python · try it yourself
import numpy as np
rng = np.random.default_rng(2)
X = rng.normal(size=(5, 4)); W = [rng.normal(size=(4, 4)) for _ in range(3)]
def attn(X):
    Q, K, V = (X @ w for w in W); S = Q @ K.T / 2
    A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True); return A @ V
perm = np.array([3, 0, 4, 1, 2])
print(np.allclose(attn(X[perm]), attn(X)[perm]))
True

Test yourself

Each row of the attention weight matrix is…

  1. a one-hot vector
  2. a probability distribution over the keys
  3. a value vector
  4. a key vector

Why are the scores divided by dk\sqrt{d_k}?

  1. To save memory
  2. So that dot products have roughly unit variance and the softmax does not saturate
  3. To make the weights sum to 1
  4. To add position information

Self-attention's time cost grows with sequence length nn as…

  1. O(n)O(n)
  2. O(nlog⁡n)O(n\log n)
  3. O(n2)O(n^2)
  4. O(1)O(1)