Module contents
Lesson 2 of 22Core 100 min

Self-attention and scaled dot-product attention

Derive self-attention from query, key, and value projections of the same sequence. Study dot-product scaling, softmax invariance and saturation, and permutation equivariance. Implement the forward pass in NumPy and compare it with PyTorch.

After this lesson you can

  • Derive scaled dot-product attention from the query, key, and value projections of one sequence.
  • Derive the variance of independent unit-variance dot products and justify the scaling factor.
  • Calculate the softmax Jacobian and relate its norm to attention saturation.
  • Prove permutation equivariance of self-attention and explain the need for positional information.
  • Implement self-attention in NumPy and verify it against the PyTorch scaled-dot-product function.

Before you start

Each token queries the others

In recurrent attention, the decoder queried encoder states. In self-attention, queries, keys, and values come from the same sequence. To represent “cat”, a position can combine information from “looks” and “moon” without waiting for an RNN to traverse the intervening positions. The mechanism assigns learned compatibility scores; it does not guarantee that they correspond to a linguistic explanation.

The figure uses six two-dimensional embeddings and takes the embeddings themselves as values. Change a point or the projections: each cell of the first matrix shows a score and each row of the second its normalized distribution. The selected output is a mixture of values. The initial data are an explicit example, not embeddings from a trained model.

InteractiveBuild QK transpose
Scores QKᵀ / √2
Thecatseesthemoon.The
1.1
1.3
0.4
−1.0
−1.1
−0.2
cat
0.2
1.1
0.9
−0.1
−1.0
−1.0
sees
−0.6
0.1
0.5
0.6
−0.2
−0.8
the
−1.1
−1.2
−0.4
1.0
1.0
0.1
moon
0.0
−0.9
−0.8
0.0
0.9
1.0
.
1.0
0.3
−0.5
−1.0
−0.1
1.0
Weights by row
Thecatseesthemoon.The
0.3
0.4
0.2
0.0
0.0
0.1
cat
0.2
0.4
0.3
0.1
0.0
0.0
sees
0.1
0.2
0.3
0.3
0.1
0.1
the
0.0
0.0
0.1
0.3
0.4
0.1
moon
0.1
0.1
0.1
0.1
0.3
0.3
.
0.3
0.2
0.1
0.0
0.1
0.3
0.00
0.60
1.0
1.0
Selected q(−1.20, 0.60)
Selected k(−1.33, −0.18)
Selected output(−0.46, 0.66)
Choose and move a token, rotate and stretch Q and K. Each matrix row corresponds to a query and each column to a key; compare scores with weights.

Three roles for one input

Let X∈RT×dmodel\mat{X}\in\R^{T\times d_{\text{model}}} have one token per row. The query, key, and value projections are learned matrices shared across positions:

Q=XWQ,K=XWK,V=XWV.\mat{Q}=\mat{X}\mat{W}_Q,\quad \mat{K}=\mat{X}\mat{W}_K,\quad \mat{V}=\mat{X}\mat{W}_V.

With WQ,WK∈Rdmodel×dk\mat{W}_Q,\mat{W}_K\in\R^{d_{\text{model}}\times d_k} and WV∈Rdmodel×dv\mat{W}_V\in\R^{d_{\text{model}}\times d_v}, the shapes are T×dkT\times d_k, T×dkT\times d_k, and T×dvT\times d_v. The query determines what the position looks for; the key, how it presents itself to others; the value, what content it provides. This separation extends the previous lesson’s soft lookup: keys and values no longer need to coincide.

In the figure, the handles represent the image of the first axis under each projection, restricted to rotations and uniform scaling. The second image is determined by the first: the transformation is a rotation followed by the same scaling in both directions. The interactive therefore shows a small family of 2×22\times2 matrices, not all possible matrices. Real layers need not impose that restriction. Rows and columns of both tables are labeled with the same six tokens; each row has its own denominator.

For example, with two tokens, Q=K=V=I2Q=K=V=I_2 and dk=2d_k=2, the first query produces logits (1/2,0)(1/\sqrt{2},0) and the second (0,1/2)(0,1/\sqrt{2}). The first output is a mixture of the two basis vectors with weights proportional to (e1/2,1)(e^{1/\sqrt{2}},1). Even when the query and first key coincide exactly, the result is not the first value alone: softmax assigns positive weight to both keys. If you change only VV, scores and weights remain the same while the output changes.

Before normalization, entry (i,j)(i,j) is xi⊤WQWK⊤xj/dk\vb{x}_i\T\mat{W}_Q\mat{W}_K\T\vb{x}_j/\sqrt{d_k} if each row is read as a column vector. Thus the bilinear matrix WQWK⊤\mat{W}_Q\mat{W}_K\T determines the scores; it does not identify the two projections separately. For any invertible matrix R\mat{R} of size dkd_k, replacing WQ\mat{W}_Q by WQR\mat{W}_Q\mat{R} and WK\mat{W}_K by WKR−⊤\mat{W}_K\mat{R}^{-\T} preserves their product. This symmetry does not imply identical optimization or regularization dynamics for the parameters.

Multiplication QK⊤QK\T costs O(T2dk)O(T^2d_k), mixing AVAV costs O(T2dv)O(T^2d_v), and projections cost O(Tdmodel(2dk+dv))O(Td_{\text{model}}(2d_k+d_v)). A materialized T×TT\times T matrix also uses quadratic memory. Row calculations can run in parallel, although autoregressive generation and real hardware add other dependencies and costs.

Why divide by the square root?

Scaling by dk\sqrt{d_k} follows from a probabilistic model, not an identity for every trained network. Let all qiq_i and kik_i be independent, with zero mean and unit variance. Then E[qiki]=0\E[q_i k_i]=0 and Var⁡(qiki)=E[qi2]E[ki2]=1\Var(q_i k_i)=\E[q_i^2]\E[k_i^2]=1. By independence between pairs and the variance of sums,

Var⁡(q⊤k)=∑i=1dkVar⁡(qiki)=dk,Var⁡ ⁣(q⊤kdk)=1.\Var(\vb{q}\T\vb{k})=\sum_{i=1}^{d_k}\Var(q_i k_i)=d_k,\qquad \Var\!\left(\frac{\vb{q}\T\vb{k}}{\sqrt{d_k}}\right)=1.

Independence and second moments are essential assumptions. With correlation, nonzero means, or different variances, covariance terms appear and the conclusion can change. Scaling controls the initial scale under these assumptions; trained projections can change it. Vaswani et al. motivate the factor this way to avoid large scores that saturate softmax.

InteractiveWithout the square root, softmax concentrates
6
d64
Mean entropy (nats)2.103
Mean Jacobian Frobenius norm0.330
Change the dimension and toggle scaling. The histogram comes from 32 queries and 12 Gaussian keys per query with a fixed seed; observe entropy and Jacobian norm.

The histogram uses actual products of independent vectors generated in the browser. The seed is reset for each dimension; toggling scaling uses exactly the same sample. Mean entropy is expressed in nats, and its maximum for 12 keys is log⁡12\log 12. The displayed norm is the Frobenius norm of the Jacobian, averaged across rows. A finite sample does not prove a universal law; it illustrates the mechanism under the stated assumptions.

Softmax: invariance and sensitivity

Attention softmax takes pi=ezi/∑jezjp_i=e^{z_i}/\sum_j e^{z_j}. Adding a constant to all logits in a row multiplies numerator and denominator by the same factor, leaving the distribution unchanged. This is why the maximum of each row is subtracted before exp, as in the log-sum-exp trick. This subtraction prevents overflow for finite inputs, but does not solve a row with no valid keys.

Differentiate each quotient with respect to zjz_j: the Jacobian matrix is

Jij=pi(δij−pj),J=diag⁡(p)−pp⊤.J_{ij}=p_i(\delta_{ij}-p_j),\qquad \mat{J}=\diag(\vb{p})-\vb{p}\vb{p}\T.

It is symmetric, its rows sum to zero, and for any u\vb{u} we have u⊤Ju=∑ipiui2−(∑ipiui)2≥0\vb{u}\T\mat{J}\vb{u}=\sum_i p_i u_i^2-(\sum_i p_i u_i)^2\ge0: this is the variance of the values uiu_i under p\vb{p}. The constant vector belongs to its null space, consistent with translation invariance. If one weight tends to one, JJ tends to zero: small changes in logits have little effect. The derivative with respect to a score before scaling also includes 1/dk1/\sqrt{d_k}.

To interpret the simulator readout, expand ∥J∥F2=∑ijJij2\norm{J}_F^2=\sum_{ij}J_{ij}^2. Grouping terms gives ∑ipi2−2∑ipi3+(∑ipi2)2\sum_i p_i^2-2\sum_i p_i^3+(\sum_i p_i^2)^2. If pp is uniform over nn keys, JJ has one zero eigenvalue and n−1n-1 eigenvalues of 1/n1/n, so ∥J∥F=n−1/n\norm{J}_F=\sqrt{n-1}/n. At the one-hot extreme the norm is zero. A small norm indicates low local sensitivity, but does not by itself measure the complete loss gradient: that also depends on the values and the gradient arriving from the output.

Multiplying all scores by a positive constant amounts to reducing the effective temperature: it normally concentrates the distribution, apart from cases such as ties. In contrast, adding a different constant to each column changes differences within each row and generally changes the weights. Dividing by dkd_k instead of dk\sqrt{d_k} produces variance 1/dk1/d_k under the preceding model, bringing rows closer to uniformity as dkd_k grows.

Additive attention uses a network to score each pair. Vaswani et al. note that, although theoretical complexities are similar, dot products benefit from optimized matrix multiplication; they also describe additive attention’s better behavior compared with unscaled dot products for large dimensions. These are observations from that comparison, not proof that one mechanism always dominates in expressiveness or quality.

Where is the order?

InteractiveShuffle in, shuffle out

Each tile shows its two-dimensional output. The tile order is the input order.

Maximum difference from each token’s original output0.0000
Swap tokens by dragging or selecting two. Without position, each token keeps its output; add position by slot and compare outputs associated with the same token.

Let P\mat{P} be a permutation matrix. On permuting rows of XX, the three projections become PQP Q, PKP K, PVP V, and the scores become P(QK⊤)P⊤P(QK\T)P\T. Row-wise softmax commutes with permutations of rows and columns: softmax⁡(PSP⊤)=Psoftmax⁡(S)P⊤\softmax(P S P\T)=P\softmax(S)P\T. Therefore

SA⁡(PX)=Psoftmax⁡(S)P⊤PV=PSA⁡(X).\operatorname{SA}(P X)=P\softmax(S)P\T P V=P\operatorname{SA}(X).

This permutation equivariance means that the output is reordered with the input, not that each row is invariant. The proof assumes shared projections and no fixed mask or positional signal. If a mask is also permuted on both axes, symmetry is preserved; a causal mask fixed by position generally breaks it. Without additional information, the layer cannot distinguish sequence order: positional encodings provide that information.

NumPy lab

First implement stable softmax, attention, and projections. We use fixed seeds and small sizes suitable for Pyodide. The permutation test compares the reordered output, not just its shape.

[ ]Self-attention from scratchBrowser
import numpy as np
def softmax_rows(z):
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)
def attention(q, k, v):
    return softmax_rows(q @ np.swapaxes(k, -1, -2) / np.sqrt(q.shape[-1])) @ v
def self_attention(x, wq, wk, wv):
    return attention(x @ wq, x @ wk, x @ wv)
rng = np.random.default_rng(18)
x = rng.normal(size=(6, 4))
wq, wk, wv = [rng.normal(size=(4, 3)) for _ in range(3)]
y = self_attention(x, wq, wk, wv)
order = np.array([2, 5, 0, 4, 1, 3])
yp = self_attention(x[order], wq, wk, wv)
print('forma salida:', y.shape, 'error de permutación:', np.max(np.abs(yp-y[order])))
assert np.allclose(yp, y[order])
[ ]Variance and entropyBrowser
rng = np.random.default_rng(1802)
for d in [2, 8, 32, 128, 512]:
    q = rng.normal(size=(128, d))
    k = rng.normal(size=(128, 12, d))
    scores = np.einsum('bd,bkd->bk', q, k)
    def mean_entropy(z):
        p = softmax_rows(z)
        return np.mean(-np.sum(p * np.log(np.maximum(p, 1e-300)), axis=-1))
    print(d, 'varianza/d:', np.var(scores)/d,
          'entropías sin/con:', mean_entropy(scores), mean_entropy(scores/np.sqrt(d)))

Variances and entropies are estimates from a finite sample, not exact values. Under this model, unscaled entropy tends to decrease as dimension grows; the particular sample may fluctuate. This lab’s calculation uses the same query for the 12 keys in each row, as in real attention.

Local comparison with PyTorch and GPU

Run the following cell in the local CUDA lab. Compare NumPy in float32 with inputs quantized to each type and the PyTorch function without dropout. For bfloat16 the reference starts with the same quantized values but accumulates in float32; this is why a wider absolute tolerance is used. Times are measured after warm-up and synchronization. They are measurements of your machine and its workload, not a speed promise for other configurations.

[ ]Equivalence and time versus TLocal GPU
import time
import numpy as np
import torch
import torch.nn.functional as F
assert torch.cuda.is_available(), 'Se necesita CUDA para este experimento'
torch.manual_seed(18)
q = torch.randn(2, 4, 64, 32, device='cuda')
k = torch.randn_like(q); v = torch.randn_like(q)
def numpy_attention(q, k, v):
    s = q @ np.swapaxes(k, -2, -1) / np.sqrt(q.shape[-1])
    e = np.exp(s - s.max(axis=-1, keepdims=True))
    return (e / e.sum(axis=-1, keepdims=True)) @ v
def torch_attention(q, k, v):
    return torch.softmax(q @ k.transpose(-2, -1) / q.shape[-1]**0.5, dim=-1) @ v
for dtype, tol in [(torch.float32, 1e-4), (torch.bfloat16, 0.03)]:
    a, b, c = (x.to(dtype) for x in (q, k, v))
    qa, ka, va = [x.float().cpu().numpy() for x in (a, b, c)]
    ref = torch.from_numpy(numpy_attention(qa, ka, va)).to('cuda')
    result = F.scaled_dot_product_attention(a, b, c, dropout_p=0.0)
    err = (result.float() - ref).abs().max().item()
    print(dtype, 'error máximo:', err, 'tolerancia:', tol)
    assert err < tol
for T in [64, 128, 256, 512, 1024, 2048]:
    q = torch.randn(1, 4, T, 32, device='cuda')
    k = torch.randn_like(q); v = torch.randn_like(q)
    for fn in [torch_attention, F.scaled_dot_product_attention]:
        for _ in range(3): fn(q, k, v)
        torch.cuda.synchronize(); start = time.perf_counter()
        for _ in range(10): fn(q, k, v)
        torch.cuda.synchronize()
        print('T', T, fn.__name__, 'segundos:', (time.perf_counter()-start)/10)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The optimized function may choose different kernels depending on device, shape, and type. Do not attribute a time to a particular kernel without checking which backend was selected. Disable dropout for a deterministic comparison. If the GPU does not support bfloat16, the experiment requires another compatible device; do not turn a CPU result into a GPU measurement.

Exercises

Proof
Prove: Under complete independence, zero means, and unit variances, the variance of q dot k is d.
0
Write the product as a sum of d component products.

Step 1 of 2. What is the variance of one product q_i k_i?

Proof
Prove: Without position or a fixed mask, SA(PX) = P SA(X).
0
P permutes rows and is orthogonal.

Step 1 of 2. How do the scores change?

Numeric
For scores (0, 8, 16), calculate the entropy in nats before scaling.
Numeric
For the same scores with d_k=64, calculate the entropy after division by the square root.
Quiz
Which operation always preserves the weights of every row?
Code
Implement softmax_jacobian(p) for a probability vector p. Return diag(p) minus the outer product of p with itself.
import numpy as np
def softmax_jacobian(p):
  pass
Shift+Enter to run
Key idea
A self-attention layer projects each token into a query, key, and value, normalizes compatibilities per query, and mixes values. The square-root factor controls scale under explicit assumptions; without an order signal, the calculation is permutation equivariant.