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.
Three roles for one input
Let have one token per row. The query, key, and value projections are learned matrices shared across positions:
With and , the shapes are , , and . 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 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, and , the first query produces logits and the second . The first output is a mixture of the two basis vectors with weights proportional to . 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 , scores and weights remain the same while the output changes.
Before normalization, entry is if each row is read as a column vector. Thus the bilinear matrix determines the scores; it does not identify the two projections separately. For any invertible matrix of size , replacing by and by preserves their product. This symmetry does not imply identical optimization or regularization dynamics for the parameters.
Multiplication costs , mixing costs , and projections cost . A materialized 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 follows from a probabilistic model, not an identity for every trained network. Let all and be independent, with zero mean and unit variance. Then and . By independence between pairs and the variance of sums,
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.
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 . 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 . 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 : the Jacobian matrix is
It is symmetric, its rows sum to zero, and for any we have : this is the variance of the values under . The constant vector belongs to its null space, consistent with translation invariance. If one weight tends to one, tends to zero: small changes in logits have little effect. The derivative with respect to a score before scaling also includes .
To interpret the simulator readout, expand . Grouping terms gives . If is uniform over keys, has one zero eigenvalue and eigenvalues of , so . 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 instead of produces variance under the preceding model, bringing rows closer to uniformity as 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?
Let be a permutation matrix. On permuting rows of , the three projections become , , , and the scores become . Row-wise softmax commutes with permutations of rows and columns: . Therefore
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.
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])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.
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)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
Step 1 of 2. What is the variance of one product q_i k_i?
Step 1 of 2. How do the scores change?
import numpy as np
def softmax_jacobian(p):
pass