Transformers and Attention Questions
The transformer architecture behind modern language models. Covers queries, keys and values, scaled dot-product and multi-head attention (including why scores are scaled and worked numeric examples), masking, positional encoding (sinusoidal, learned, relative with bucketed biases, rotary, and 2D schemes for image patches), encoder-only, decoder-only and encoder-decoder variants, residual connections, layer normalization placement and the feed-forward block, parameter, memory and compute accounting, why transformers scale better than recurrent models, efficient and long-context attention variants (sparse, local window with global tokens, hashing-based, linear, low-rank, FlashAttention, multi-query), and what attention heads learn and what raw attention weights do and do not explain. Includes implementing attention and its components from scratch. Distributed training, serving and quantization, fine-tuning, pretraining objectives, and general optimizer practice are covered elsewhere.
Raw attention weights are often shown as explanations of a Transformer's prediction. What do individual heads in multi-head attention tend to learn, why can raw attention weights be a misleading explanation of the output, and what complementary methods (head ablation, gradient-based attribution, causal interventions, probing) would you use to check an interpretation?
Sample Answer
Direct answer
Individual attention heads in a trained Transformer often specialise: some track position (attend to the previous or next token), some track syntax (a verb attending to its subject), some copy or match earlier tokens, and some do almost nothing useful. Raw attention weights are a poor explanation of the output because they describe only where a head reads from, not how much that read changes the prediction. Treat a heat map as a hypothesis, then test it with four complementary checks (each is explained in the table below, with a first-use gloss in the cells): ablate the head, attribute with gradients, intervene causally (activation patching), and probe the hidden states.
What individual heads tend to learn
A head is one of several parallel attention computations inside a layer, each with its own query, key and value projections (learned matrices that turn each token vector into a query, a key and a value). Studies of trained models report recurring roles, offered here as examples of patterns, not guarantees for any given model:
- Positional heads: attend to a fixed offset such as the previous token or the first token.
- Syntactic or relational heads: link tokens that stand in a grammatical relation, such as a verb and its object.
- Copy and match heads: find an earlier occurrence of the current token and read what followed it (the building block often called an induction pattern).
- Delimiter or "sink" heads: put most of their weight on a separator or the first token. The softmax (the step that turns scores into weights summing to 1) must put its weight somewhere, so a head with nothing relevant to read parks its weight on a harmless token.
- Redundant or prunable heads: removing them barely changes quality, which is why head pruning is possible in some models.
Roles differ by layer and by training run, so a role is something you verify on your own model, not something you assume.
Why raw attention weights can mislead
For head h and token i, with αijh the attention weight from token i to token j (each row sums to 1), the head's output is
headh(i)=j∑αijhWVhxj,layer output=xi+h∑WOhheadh(i)where xj is the token vector, WVh the value projection of head h and WOh the slice of the output projection that head h writes through. The weights α are only one factor. Several things sit between a weight and the prediction:
- Value size and direction. A weight of 0.9 on a token whose value vector is small, or points in a direction later layers ignore, moves the output very little. Weight times value matters, not weight alone.
- Redundancy. Another head can carry the same information, so a head that looks decisive can be removable, and a head that looks decisive may be overruled by a stronger one.
- The residual path. The token's own vector reaches the output through the skip connection (the xi+ term) without passing through any attention weight at all. The residual stream is this running vector at each position: every layer reads it and adds its output back into it, so each head "writes" into it.
- Mixing across layers. After the first layer, the vector at position j already contains information gathered from other positions, so "the head attended to token j" no longer means "the model used the word at j".
- Sinks. High weight on a delimiter can be a no-op, not evidence of importance.
Published debates on this point (for example the paper titled "Attention is not Explanation" and the reply titled "Attention is not not Explanation") are best read as: attention weights are sometimes informative, but they are not a faithful attribution by themselves, and the answer depends on how "explanation" is defined and tested.
The four checks
| Check | Question it answers | What it cannot see |
|---|---|---|
| Head ablation (zero a head's output, or replace it with its average value over many inputs, which is mean-replacement) | Is the head necessary (does removing it break the behaviour)? | Redundant backup heads (other heads that can do the same job) hide necessity; zeroing is an out-of-distribution intervention: it feeds later layers an input they never saw in training |
| Gradient-based attribution (gradient times input) | Which input tokens does the output respond to? The logit is the model's raw score for a class before the softmax turns scores into probabilities; the gradient says how fast that score changes if an input changes slightly | Saturated gradients (the output is already at its limit, so small changes show no response even for an important input) and noise; says nothing about which head or layer did the work |
| Causal intervention (activation patching: copy a head's activation from a run on a corrupted input into a run on the clean input) | Does the head's message decide the output (does changing only this head's activation change the prediction)? Does it carry the information that decides the output? | Needs a well-chosen corrupted input (a minimal pair: two inputs that differ in exactly one property, such as one token); only tests the pieces you patch |
| Probing (train a small classifier on hidden states to predict a property) | Is the property linearly decodable at this layer (can a straight-line classifier read it off the hidden vectors)? | Decodable does not mean used: the model may never read it |
Probing uses a linear probe: a logistic regression (a simple classifier that draws a straight-line boundary between classes) trained on frozen hidden vectors (vectors recorded from the model; the model itself is not changed). A good probe needs a control task: give every token type a fixed random label and train the same probe on that. If it scores as well on the random relabelling as on the real property, the probe is memorising and its accuracy says little about the representation (this is the idea of a control task with selectivity, accuracy on the real property minus accuracy on the control).
Worked example
A one-layer Transformer with two heads, width 32 (16 per head) and 8 token types is trained for 500 steps on a task where the label is the token at position 2 of a 6-token input (positions counted from 0). A seventh read-out token is appended and the prediction is read from it. The model is a stand-in for a real language model, small enough that every check can be run and compared; its attention code is written out so each quantity is visible. Read the code in sections. The class Tiny is the model: sp splits the width into heads, att is the softmax attention, z is each head's output, and r = h + self.o(z) adds the heads back into the residual stream; head_mask multiplies a head's output by 0 (ablation) and patch=(head, replacement) overwrites that head's output at the read-out row. Training then fits it for a few hundred steps. The sections after training are: (1) the write size is the length of the vector a head adds at the read-out row. (2) Gradient times input asks how the true-class logit would change if each token's embedding were changed slightly: the code multiplies that gradient by the embedding itself, sums over the width, and averages the absolute value per position. (3) Patching builds a corrupted input xc whose token at position 2 is replaced by a different token, records the head's output on it, then runs the clean input with that one head's output swapped in; it counts how often the prediction becomes the corrupted token. (4) The probe fits a logistic regression to the position-4 residual vector, and a control task gives each token type a fixed random label and trains the same probe on it. The program prints, in order: the mean attention each head gives from the read-out position to each position; accuracy with each head zeroed; the size of each head's write into the residual stream at the read-out position; gradient times input per position; activation patching per head; and the probe and its control task.
import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0); torch.set_num_threads(1)
V, T, D, H = 8, 6, 32, 2 # vocab of ordinary tokens, ordinary positions, model width, heads
CLS = V # extra token appended at position T; its output is read
dh = D // H
class Tiny(nn.Module):
def __init__(self):
super().__init__()
self.emb = nn.Embedding(V + 1, D); self.pos = nn.Embedding(T + 1, D)
self.q = nn.Linear(D, D); self.k = nn.Linear(D, D); self.v = nn.Linear(D, D)
self.o = nn.Linear(D, D); self.out = nn.Linear(D, V)
def forward(self, x, head_mask=None, patch=None, emb_override=None):
h = emb_override if emb_override is not None else self.emb(x)
h = h + self.pos(torch.arange(x.shape[1]))
B, L, _ = h.shape
sp = lambda t: t.view(B, L, H, dh).transpose(1, 2) # (B, H, L, dh)
q, k, v = sp(self.q(h)), sp(self.k(h)), sp(self.v(h))
att = torch.softmax(q @ k.transpose(-1, -2) / dh ** 0.5, dim=-1) # (B, H, L, L)
z = att @ v # (B, H, L, dh): per-head output
if patch is not None: # (head, replacement z for CLS row)
hd, zr = patch; z = z.clone(); z[:, hd, -1, :] = zr
if head_mask is not None: z = z * head_mask.view(1, H, 1, 1)
z = z.transpose(1, 2).reshape(B, L, D)
r = h + self.o(z)
self.last_r = r
return self.out(r[:, -1]), att, z
def batch(n, g):
x = torch.randint(0, V, (n, T), generator=g)
y = x[:, 2] # the label is the token at position 2
return torch.cat([x, torch.full((n, 1), CLS)], 1), y
g = torch.Generator().manual_seed(0)
m = Tiny(); opt = torch.optim.Adam(m.parameters(), 1e-2)
for s in range(500):
x, y = batch(128, g); loss = F.cross_entropy(m(x)[0], y)
opt.zero_grad(); loss.backward(); opt.step()
xt, yt = batch(2000, torch.Generator().manual_seed(1))
acc = lambda **kw: (m(xt, **kw)[0].argmax(-1) == yt).float().mean().item()
print("test accuracy", round(acc(), 3))
with torch.no_grad():
_, att, _ = m(xt)
print("mean attention from CLS row, per head, over positions 0..5 and CLS")
for h in range(H): print(" head", h, [round(a, 2) for a in att[:, h, -1].mean(0).tolist()])
for h in range(H):
mk = torch.ones(H); mk[h] = 0
print("zero head", h, "-> accuracy", round(acc(head_mask=mk), 3))
print("zero both heads -> accuracy", round(acc(head_mask=torch.zeros(H)), 3))
# 1) size of each head's write into the residual stream at the CLS row (norm of o applied to that head's slice)
with torch.no_grad():
_, _, z = m(xt)
zc = z[:, -1, :]
for h in range(H):
sl = torch.zeros_like(zc); sl[:, h*dh:(h+1)*dh] = zc[:, h*dh:(h+1)*dh]
print("head", h, "mean norm of write at CLS row", round((m.o(sl) - m.o.bias).norm(dim=-1).mean().item(), 2))
# 2) gradient x input: d(true-class logit)/d(embedding), times embedding, summed over width, mean |.| per position
e = m.emb(xt).detach().requires_grad_(True)
lg = m(xt, emb_override=e)[0]
lg.gather(1, yt[:, None]).sum().backward()
gxi = (e.grad * e).sum(-1).abs().mean(0)
print("grad x input per position", [round(v, 2) for v in gxi.tolist()])
# 3) activation patching: run on x, but give head h at the CLS row the output it had on a corrupted input
# whose position-2 token is different; count how often the prediction moves to the corrupted token
with torch.no_grad():
xc = xt.clone(); xc[:, 2] = (xt[:, 2] + 1 + torch.randint(0, V - 1, (len(xt),), generator=torch.Generator().manual_seed(2))) % V
_, _, zc2 = m(xc)
for h in range(H):
pred = m(xt, patch=(h, zc2[:, -1, h*dh:(h+1)*dh]))[0].argmax(-1)
print("patch head", h, "-> follows corrupted token", round((pred == xc[:, 2]).float().mean().item(), 3),
"| still original", round((pred == yt).float().mean().item(), 3))
# 3b. Is head 1 sufficient but outvoted? Zero head 0, then patch head 1 with the corrupted run's output.
with torch.no_grad():
pred = m(xt, head_mask=torch.tensor([0.0, 1.0]), patch=(1, zc2[:, -1, dh:2*dh]))[0].argmax(-1)
print("head 0 zeroed, patch head 1 -> follows corrupted token", round((pred == xc[:, 2]).float().mean().item(), 3))
# 4) linear probe for the token at position 4 (never needed for the label), read from the residual at position 4
from sklearn.linear_model import LogisticRegression
with torch.no_grad():
m(xt); r = m.last_r.clone()
xtr, _ = batch(2000, torch.Generator().manual_seed(3)); m(xtr); rtr = m.last_r.clone()
t4, tr4 = xt[:, 4].numpy(), xtr[:, 4].numpy()
p = LogisticRegression(max_iter=3000).fit(rtr[:, 4].numpy(), tr4)
print("probe x[4] from position 4 residual, test acc", round(p.score(r[:, 4].numpy(), t4), 3))
cmap = torch.randperm(V, generator=torch.Generator().manual_seed(4)) # control task: a fixed random label for each token type
ctrl = LogisticRegression(max_iter=3000).fit(rtr[:, 4].numpy(), cmap[tr4].numpy())
print("control task (random label per token type), test acc", round(ctrl.score(r[:, 4].numpy(), cmap[t4].numpy()), 3))
print("accuracy when the token at position 4 is replaced by a random one",
round((m(torch.cat([xt[:, :4], torch.randint(0, V, (2000, 1), generator=torch.Generator().manual_seed(6)), xt[:, 5:]], 1))[0].argmax(-1) == yt).float().mean().item(), 3))
Output:
test accuracy 1.0
mean attention from CLS row, per head, over positions 0..5 and CLS
head 0 [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]
head 1 [0.0, 0.01, 0.89, 0.03, 0.0, 0.03, 0.04]
zero head 0 -> accuracy 0.596
zero head 1 -> accuracy 0.879
zero both heads -> accuracy 0.126
head 0 mean norm of write at CLS row 19.36
head 1 mean norm of write at CLS row 8.51
grad x input per position [0.01, 0.09, 19.32, 0.22, 0.0, 0.13, 0.71]
patch head 0 -> follows corrupted token 0.854 | still original 0.052
patch head 1 -> follows corrupted token 0.052 | still original 0.846
head 0 zeroed, patch head 1 -> follows corrupted token 0.615
probe x[4] from position 4 residual, test acc 1.0
control task (random label per token type), test acc 1.0
accuracy when the token at position 4 is replaced by a random one 1.0
How to read it (numbers are from this run):
- Attention alone cannot separate the heads. Both heads put most of their weight on position 2 (1.00 and 0.89). A heat map would present them as similarly important.
- Ablation separates them. Zeroing head 1 leaves accuracy at 0.879, zeroing head 0 drops it to 0.596, and zeroing both drops it to 0.126, close to the 0.125 expected from guessing among 8 tokens. So each head helps, head 0 more, and each is partly a backup for the other: neither alone reaches the full 1.0.
- Patching shows who decides. Giving the read-out position head 0's output from a run with a different token at position 2 moves the prediction to that different token 85.4% of the time; doing the same with head 1 moves it only 5.2% of the time (the prediction stays the original token 84.6% of the time). Head 0's write is also larger (mean length 19.36 against 8.51).
- Why both facts are true at once. Ablation asks "can the model do without this head?" and patching asks "if this head says something different, whose message wins?". Head 1 does carry the token: with head 0 zeroed, patching head 1 moves the prediction to the corrupted token 61.5% of the time, close to the 0.596 accuracy head 1 gets alone. But when head 0 is present and disagrees, its larger write dominates the output layer, so head 1 is outvoted. Ablation alone would call head 1 modest and patching alone would call it irrelevant; the two together say it is a weaker backup. In the follow-up case "ablation changed nothing but patching changed the prediction" the same two-question logic applies, with the roles reversed: the ablated head was redundant, yet its message, when changed, was the one that decided. Trust each result for the question it answers, and report both.
- Gradient times input finds the token, not the head. Position 2 dominates (19.32, against 0.22 at position 3 and 0.13 at position 5), so the model's output depends on the token at position 2. Position 6 (0.71) is the read-out token itself, which is the same fixed token in every input; its small value means the read-out token's own embedding has a little influence on the output, far less than the token at position 2. The result agrees with the attention map about where, and is silent about which head.
- Probing shows decodable is not the same as used. A probe recovers the token at position 4 from the position-4 residual vector with accuracy 1.0, yet replacing that token with a random one leaves model accuracy at 1.0. The information is present and the model never reads it. This probe is not selective: it scores just as well (1.0) on the control task, a fixed random label per token type, because with only 8 token types a linear probe can fit any relabelling, so its accuracy is no evidence about the model. The position-4 residual is mostly its own token embedding plus a position vector, so decoding it is nearly guaranteed; the replacement test is what shows the information is unused. In a deep layer of a real model (such as layer 6 of a deep stack) the vector has been mixed through many layers, so accuracy well above the control is informative. A convincing probe result there is high selectivity (accuracy on the real property well above accuracy on the control task) and accuracy clearly above the same probe run on the earliest layer's vectors, followed by a causal test (patch or edit the direction and see whether behaviour changes).
Limits of this example: it is one small model trained from one seed on a synthetic task (500 training steps, not a trained language model), zeroing a head is an out-of-distribution intervention, and the head-0-versus-head-1 split is a fact about this trained model, not a general law. Retraining with other seeds changes which head is bigger and by how much (in some seeds one head barely attends to position 2); what repeated across 24 other seeds is that zeroing both heads fell to near chance every time and that the head with the larger write won the patching comparison in 22 of them. Whether real language models show the same pattern of redundant, outvoted heads has to be measured on those models. The lesson is the method: each check answers a different question and the checks disagree in informative ways.
Recommended workflow
Start from the attention map to generate a hypothesis ("this head reads the subject"). Then test necessity (does removing it break the behaviour? ablation, preferably with mean-replacement as well as zeroing, because it keeps activations closer to the training distribution), test whether the head's message decides the output and in which direction (activation patching, run in the direction you state, with a minimal pair of inputs that differ in exactly the property under study), confirm input-level evidence with attribution, and use probing only to ask what information is present at a layer, with a control task. Report a claim only if it survives the checks that apply; if ablation and patching disagree, explain which redundancy or backup mechanism accounts for it.
Common mistakes
- Presenting an attention heat map as the explanation without any intervention.
- Averaging attention over heads or layers, which blends heads with different roles.
- Concluding a head is unimportant because zeroing it changed nothing, when a backup head compensated (here, ablating head 1 alone leaves 0.879 accuracy while ablating both heads leaves 0.126).
- Reading probe accuracy as proof that the model uses the property.
- Using a corrupted input that differs from the clean one in several ways, so a patching result cannot be pinned on one property.
Self-attention costs O(n^2) in time and memory. Explain why, then lay out the main ways to reduce that cost for long sequences and the accuracy trade-off of each.
Sample Answer
Why attention is O(n^2)
For a sequence of n tokens, each head has queries Q and keys K, each n by d_k (d_k is the size of one head). The score matrix is Q times K transposed, shape n by n: every query is compared with every key, and each comparison is a dot product costing d_k multiply-adds. So the time is n times n times d_k, i.e. O(n^2 d). The softmax normalizes each row over all n keys, so a row cannot be finished until all n scores exist, and the weighted sum with V (n by d_k) costs another n^2 d_k. If the n by n matrix is stored, memory is O(n^2) per head, and backpropagation needs it again. Doubling the length quadruples both.
The main ways to cut the cost, with their trade-offs
| Method | Idea | Cost | Exact? | What you give up |
|---|---|---|---|---|
| Tiled exact kernel (FlashAttention idea) | compute attention block by block with a running ("online") softmax, never storing n by n | time still O(n^2 d), memory O(n) | yes | nothing in accuracy; does not reduce FLOPs (floating-point operations, the count of arithmetic steps) |
| Local / sliding window | each token attends only to the w tokens on each side | O(n w d) | no | direct access to far tokens; information must hop across layers |
| Sparse patterns (strided, global tokens, block) | window plus a few designated global tokens (positions every token can read and that can read every token) or strided positions (every s-th token, to reach far) | about O(n w d) | no | whatever the pattern misses; global tokens are a hand-chosen bottleneck |
| Low-rank projection | project keys and values from length n down to a fixed length k (so the n by n table is replaced by an n by k one) | O(n k d) | no | the rank of the attention map (roughly, how many independent patterns it can express) is capped by k; awkward for causal generation |
| Linear (kernel) attention | replace softmax(QK^T) with a feature-map product (a feature map is a function applied to each query and key so that their similarity becomes a plain dot product) so the product can be reordered: first K^T V (d by d), then Q times that | O(n d^2) | no | the sharp, peaky behaviour of softmax; quality drops on tasks needing precise lookup |
| Retrieval or chunk-and-summarize | split into chunks, attend to retrieved or summarized parts | depends | no | recall depends on the retriever or summarizer |
The rows run from exact to increasingly approximate; the order to try them in is under "How to choose". Orthogonal but often confused: multi-query attention (all heads share one set of keys and values) and grouped-query attention (groups of heads share one) shrink the key-value cache that decoding reads, not the n^2 score computation.
The online softmax on four numbers
Softmax needs the sum over all keys, which seems to force all scores to exist at once. The trick is to keep a running maximum m, a running denominator l and a running numerator, and to rescale the old totals by exp(old m - new m) whenever a later tile raises the maximum; subtracting the maximum is the usual guard against overflow, and the rescaling keeps every earlier tile consistent with it, which is why the result is exact. Here is one query with four given scores and values, processed two keys at a time.
import numpy as np
# One query, four keys, one number per value. Scores are given directly.
scores = np.array([1.0, 3.0, 2.0, 5.0])
values = np.array([10.0, 20.0, 30.0, 40.0])
p = np.exp(scores - scores.max())
print("full softmax-weighted value:", round(float((p / p.sum()) @ values), 4))
# Online version: two tiles of two keys; keep a running max m, denominator l and numerator acc.
m, l, acc = -np.inf, 0.0, 0.0
for tile in (slice(0, 2), slice(2, 4)):
s, v = scores[tile], values[tile]
m_new = max(m, s.max())
scale = np.exp(m - m_new) # shrinks what was accumulated under the old max
e = np.exp(s - m_new)
l = l * scale + e.sum()
acc = acc * scale + e @ v
m = m_new
print(f"after keys {tile.start}-{tile.stop - 1}: max m = {m:.1f}, scale = {scale:.4f}, denominator l = {l:.4f}, numerator = {acc:.4f}")
print("tiled result acc / l:", round(float(acc / l), 4))
Output:
full softmax-weighted value: 36.8806
after keys 0-1: max m = 3.0, scale = 0.0000, denominator l = 1.1353, numerator = 21.3534
after keys 2-3: max m = 5.0, scale = 0.1353, denominator l = 1.2034, numerator = 44.3835
tiled result acc / l: 36.8806
Reading it: after the first tile the maximum is 3 and there was nothing to rescale (the scale printed for it is exp(-inf) = 0, which just wipes the empty start). The second tile contains a score of 5, which raises the maximum from 3 to 5, so the old denominator and numerator are multiplied by exp(3 - 5) = 0.1353 before the new terms are added; every term is again measured against the new maximum. That rescaling is why the final acc / l is exactly the full softmax-weighted value, while only two scores were held at a time.
Code: one exact and two approximate methods
On a synthetic 64-token input with d_k = 16, the program (1) implements tiled attention with an online softmax and checks it equals full attention, (2) implements a window mask, and (3) implements linear attention with the feature map elu(x) + 1, checking that the reordered computation equals the quadratic-order one. It reports relative error (the length of the difference between an approximation's output and full attention's output, divided by the length of full attention's output: 0 means identical, 1 means the error is as large as the output itself, and above 1 means the approximation is further from the right answer than an all-zero output would be) on two inputs: a random one with no locality, and one built as a random walk, so neighbouring tokens are similar and nearby keys get large scores. "Attention mass inside window" is the average share of each row's softmax weight that falls inside the window. A last block repeats the comparison on 20 other seeds and prints the median error, so no conclusion rests on one draw.
import torch
import torch.nn.functional as F
torch.set_num_threads(1)
torch.manual_seed(0)
n, d, blk = 64, 16, 16
q, k, v = (torch.randn(n, d) for _ in range(3))
full = F.softmax(q @ k.T / d ** 0.5, dim=-1) @ v
# 1. Exact: tiled attention with an online softmax (the FlashAttention idea), never builds n x n.
def tiled(q, k, v, blk):
out = torch.zeros_like(q)
m = torch.full((n, 1), float("-inf")) # running max of scores
l = torch.zeros(n, 1) # running softmax denominator
for s in range(0, n, blk):
sc = q @ k[s:s + blk].T / d ** 0.5 # only an n x blk tile at a time
m_new = torch.maximum(m, sc.amax(dim=-1, keepdim=True))
p = torch.exp(sc - m_new)
scale = torch.exp(m - m_new)
l = l * scale + p.sum(dim=-1, keepdim=True)
out = out * scale + p @ v[s:s + blk]
m = m_new
return out / l
print("tiled == full (exact):", torch.allclose(tiled(q, k, v, blk), full, atol=1e-5))
# 2. Approximate: sliding window of w keys on each side.
def window(q, k, v, w):
idx = torch.arange(n)
allowed = (idx[:, None] - idx[None, :]).abs() <= w
sc = (q @ k.T / d ** 0.5).masked_fill(~allowed, float("-inf"))
return F.softmax(sc, dim=-1) @ v, int(allowed.sum())
# 3. Approximate: kernelized linear attention with feature map phi(x) = elu(x) + 1.
def linear(q, k, v):
pq, pk = F.elu(q) + 1, F.elu(k) + 1
kv = pk.T @ v # (d, d), cost O(n d^2)
z = pq @ pk.sum(dim=0, keepdim=True).T
return (pq @ kv) / z
pq, pk = F.elu(q) + 1, F.elu(k) + 1
quad = ((pq @ pk.T) @ v) / (pq @ pk.T).sum(dim=-1, keepdim=True)
print("linear (reordered) == linear (quadratic order):", torch.allclose(linear(q, k, v), quad, atol=1e-5))
def rel_err(a, ref):
return ((a - ref).norm() / ref.norm()).item()
def report(name, q, k, v):
ref = F.softmax(q @ k.T / d ** 0.5, dim=-1) @ v
print(f"--- {name} input (full attention scores computed: {n * n})")
print(f"tiled : scores per tile {n * blk}, relative error {rel_err(tiled(q, k, v, blk), ref):.4f}")
idx = torch.arange(n)
p = F.softmax(q @ k.T / d ** 0.5, dim=-1)
for w in (4, 16):
out, cnt = window(q, k, v, w)
mass = (p * ((idx[:, None] - idx[None, :]).abs() <= w)).sum(-1).mean().item()
print(f"window w={w:<2}: scores computed {cnt}, attention mass inside window {mass:.2f}, relative error {rel_err(out, ref):.4f}")
print(f"linear : state size {d * d} numbers, relative error {rel_err(linear(q, k, v), ref):.4f}")
report("random", q, k, v)
x = torch.randn(n, d).cumsum(0) # a random walk: neighbouring tokens are similar
x = x / x.norm(dim=-1, keepdim=True) * 6.0
report("local", x, x, v)
# Same comparison over 20 seeds (median relative error), so no conclusion rests on one draw.
def trial(seed):
g = torch.Generator().manual_seed(seed)
qq, kk, vv = (torch.randn(n, d, generator=g) for _ in range(3))
xx = torch.randn(n, d, generator=g).cumsum(0)
xx = xx / xx.norm(dim=-1, keepdim=True) * 6.0
row = []
for a, b in ((qq, kk), (xx, xx)):
ref = F.softmax(a @ b.T / d ** 0.5, dim=-1) @ vv
row += [rel_err(window(a, b, vv, w)[0], ref) for w in (4, 16)] + [rel_err(linear(a, b, vv), ref)]
return row
rows = torch.tensor([trial(s) for s in range(20)])
med = rows.median(dim=0).values
print("--- median relative error over 20 seeds")
print(f"random: window w=4 {med[0]:.2f}, window w=16 {med[1]:.2f}, linear {med[2]:.2f}")
print(f"local : window w=4 {med[3]:.2f}, window w=16 {med[4]:.2f}, linear {med[5]:.2f}")
print(f"local window w=16 beats random window w=16 in {(rows[:, 4] < rows[:, 1]).sum().item()} of 20 seeds")
Output:
tiled == full (exact): True
linear (reordered) == linear (quadratic order): True
--- random input (full attention scores computed: 4096)
tiled : scores per tile 1024, relative error 0.0000
window w=4 : scores computed 556, attention mass inside window 0.14, relative error 1.8768
window w=16: scores computed 1840, attention mass inside window 0.45, relative error 1.0044
linear : state size 256 numbers, relative error 0.6690
--- local input (full attention scores computed: 4096)
tiled : scores per tile 1024, relative error 0.0000
window w=4 : scores computed 556, attention mass inside window 0.54, relative error 0.7136
window w=16: scores computed 1840, attention mass inside window 0.93, relative error 0.1056
linear : state size 256 numbers, relative error 0.7717
--- median relative error over 20 seeds
random: window w=4 2.18, window w=16 1.11, linear 0.74
local : window w=4 0.84, window w=16 0.21, linear 0.82
local window w=16 beats random window w=16 in 20 of 20 seeds
Reading it:
- The tiled method matches full attention (error 0.0000) while holding only n by 16 scores at a time (1,024 instead of 4,096).
- A window helps when the attention is local. On the random input a window is a poor stand-in: with w = 4 it captures only 0.14 of the weight and the error is 1.8768 on this draw; the median over 20 seeds is 2.18 for w = 4 and 1.11 for w = 16. On the local input w = 16 captures 0.93 of the weight and the error falls to 0.1056 on this draw (median 0.21 over 20 seeds, and lower than the random-input w = 16 error in all 20), while computing 1,840 of the 4,096 scores.
- Errors above 1 on the random input come from a simple effect: full attention averages many unrelated random value vectors, which shrinks its output, while a narrow window averages only a few, which gives a longer vector that points elsewhere. Real text is usually far more local than random numbers, so the local input is the nearer picture, and only your own data can say how local your task is.
- Linear attention here has error 0.6690 on the random input and 0.7717 on the local one (medians over 20 seeds: 0.74 and 0.82): softmax and the feature map produce different weight shapes. These are untrained random projections on synthetic inputs, so the numbers measure how far a cheaper layer's output is from softmax attention's, not task quality. In practice a model with linear attention is trained as it is, and the fair comparison is its accuracy on your task against the full-attention model. What the numbers do show is that each approximation has an assumption about the attention pattern, not a ranking of methods. Measure on your task.
How to choose
Commit to this order: first use the exact tiled kernel and fix the memory problem without any accuracy loss. If FLOPs or length still do not fit, use a window plus global tokens when the task is mostly local (documents, code), and retrieval when relevant information is sparse. Consider linear or low-rank layers only if you can validate the quality loss on your own evaluation. What flips it: tasks that need exact copy or lookup from far away push you back toward full attention with more hardware, or retrieval.
Common mistakes
- Calling FlashAttention an approximation; it is exact and removes memory, not FLOPs.
- Expecting a window of w to give a receptive field (how far back a token's output can depend on, directly or through layers) of w; stacking L layers lets information travel about L times w.
- Ignoring that generation uses a growing cache: sparse patterns must also bound the cache.
Running the code
Save the program as demo.py and run python demo.py. The output above was produced with Python 3.12, numpy 2.1.3 and torch 2.5.1 (CPU). The seed is fixed in the program.
What is the basic intuition behind self-attention, and why did Transformers become the dominant architecture for modern language models?
Sample Answer
The intuition in plain words
When you read "the trophy did not fit in the suitcase because it was too big", you do not read the words in a fixed left-to-right pipe and hope the meaning of "it" survives. You glance back at the earlier words and pick the ones that matter for "it". Self-attention does exactly that for every word at once: each token looks at all the other tokens in the same sequence, decides how relevant each one is, and builds its new representation as a relevance-weighted blend of them. The relevance scores come from the content of the tokens, not from how far apart they are.
In a bit more detail: each token produces a query (what I am looking for), a key (what I offer for matching) and a value (the information I hand over). A token's new vector is the sum of all values, each weighted by how well that token's key matches the query. A softmax (a function that turns any list of numbers into positive weights summing to 1) makes the weights a proper average.
A toy you can trace
The program gives each word a tiny hand-set vector of four numbers (object, container, function word, pronoun), builds queries that look for objects and containers, and keys that mark function words and pronouns as unattractive. It also prints the query, some keys and some scores so you can follow how the weights arise. This is a hand-built stand-in for what training learns; in a real model nobody sets these numbers.
import numpy as np
# Toy sentence: "the trophy did not fit in the suitcase because it was too big".
# Hand-set 4-number "meaning" vectors: [is-an-object, is-a-container, is-a-function-word, is-a-pronoun].
words = ["the", "trophy", "did", "not", "fit", "in", "the", "suitcase", "because", "it", "was", "too", "big"]
emb = {
"the": [0, 0, 1, 0], "trophy": [1, 0, 0, 0], "did": [0, 0, 1, 0], "not": [0, 0, 1, 0],
"fit": [0, 0, 1, 0], "in": [0, 0, 1, 0], "suitcase": [0, 1, 0, 0], "because": [0, 0, 1, 0],
"it": [0.5, 0.5, 0, 1], "was": [0, 0, 1, 0], "too": [0, 0, 1, 0], "big": [0, 0, 1, 0],
}
X = np.array([emb[w] for w in words], dtype=float) # (13, 4)
# A query that asks "which token is an object or a container?" for every token.
Wq = np.array([[3, 0], [0, 3], [0, 0], [0, 0]], dtype=float) # (4, 2): looks for object / container
Wk = np.array([[1, 0], [0, 1], [-1, -1], [-1, -1]], dtype=float) # (4, 2): function words and pronouns get a negative key
Q, K = X @ Wq, X @ Wk
scores = Q @ K.T / np.sqrt(2)
w = np.exp(scores - scores.max(-1, keepdims=True))
w /= w.sum(-1, keepdims=True)
i = words.index("it")
print("query of 'it':", Q[i], " key of trophy:", K[1], " key of suitcase:", K[7], " key of 'the':", K[0], " key of 'it':", K[i])
print("score 'it' -> trophy:", round(float(scores[i, 1]), 3), " -> 'the':", round(float(scores[i, 0]), 3), " -> 'it':", round(float(scores[i, i]), 3))
print("positions: trophy =", words.index("trophy"), " it =", i, " gap =", i - words.index("trophy"))
order = np.argsort(-w[i], kind="stable")[:3]
print("attention from 'it':", [(words[j], round(float(w[i, j]), 3)) for j in order])
# Counting, not timing: sequential steps and pairwise connections for n tokens.
for n in (16, 128, 1024):
rnn_steps = n # hidden state t needs hidden state t-1
rnn_path = n - 1 # longest chain of steps between token 1 and token n
attn_steps = 1 # one layer: all n*n scores computed from the same inputs
pairs = n * n
print(f"n={n:5d} RNN sequential steps={rnn_steps:5d} longest path={rnn_path:5d} "
f"attention layer sequential steps={attn_steps} direct pairs={pairs}")
Output:
query of 'it': [1.5 1.5] key of trophy: [1. 0.] key of suitcase: [0. 1.] key of 'the': [-1. -1.] key of 'it': [-0.5 -0.5]
score 'it' -> trophy: 1.061 -> 'the': -2.121 -> 'it': -1.061
positions: trophy = 1 it = 9 gap = 8
attention from 'it': [('trophy', 0.394), ('suitcase', 0.394), ('it', 0.047)]
n= 16 RNN sequential steps= 16 longest path= 15 attention layer sequential steps=1 direct pairs=256
n= 128 RNN sequential steps= 128 longest path= 127 attention layer sequential steps=1 direct pairs=16384
n= 1024 RNN sequential steps= 1024 longest path= 1023 attention layer sequential steps=1 direct pairs=1048576
Tracing the first lines of the output by hand. The vector for "it" is [0.5, 0.5, 0, 1], so its query is [0.5 x 3, 0.5 x 3] = [1.5, 1.5]. The key of "trophy" is [1, 0] and the key of "suitcase" is [0, 1], so both score (1.5 x 1 + 1.5 x 0) / 1.414 = 1.061. Every function word ("the", "did", "not", "fit", "in", "because", "was", "too", "big") has key [-1, -1] and scores (-1.5 - 1.5) / 1.414 = -2.121, and "it" itself has key [-0.5, -0.5] and scores -1.061. Exponentiating, the two object/container tokens get e^1.061 = 2.89 each, the ten function-word tokens ("the" appears twice) 0.12 each, and "it" 0.35; the total is about 7.32, and 2.89 / 7.32 = 0.394, which is the printed weight. Only the last step is the softmax; the rest is a handful of multiplications.
So the weight from "it" goes to "trophy" and "suitcase" (0.394 each) and almost none to function words or to "it" itself (0.047). Two things to notice. First, the match did not depend on distance: "trophy" is at position 1 and "it" at position 9, eight positions back, and it still gets the weight; "suitcase" is two positions back and gets the same. Second, the toy cannot decide between the two candidates; choosing "trophy" because of "too big" is something a trained network has to learn from many examples, using several layers and heads. In a trained model the matrices are not hand-set 3s and -1s: training adjusts them until tokens that help predict the text receive high scores from the tokens that need them, and later layers combine the attended information with what else the model knows. Attention provides the direct access, training provides the judgement.
Why this architecture took over language modelling
These are the reasons usually given, each tied to something you can count:
- Short paths between any two tokens. A recurrent network (RNN) reads one token at a time and carries a single hidden state (a fixed-size vector of numbers that summarises everything read so far) forward, so information from token 1 reaches token n only after n - 1 sequential updates, and can fade on the way. In one attention layer every pair of tokens is connected directly (the "direct pairs" count in the output: n by n scores, each linking two tokens in one step). The counting lines at the end of the output show this: the longest chain is 15, 127 or 1023 steps for an RNN at n of 16, 128 and 1024, and one hop for attention.
- Parallel training. An RNN's step t needs step t - 1, so a sequence of n tokens needs n sequential steps (printed in the same block). In a Transformer, all n by n scores in a layer are computed from the same inputs in one batch of matrix multiplications. A GPU performs thousands of multiply-adds at once, so a few large matrix products run much faster than n small steps that must wait for each other. During generation the model still emits one token at a time, so this advantage applies to training and to reading a prompt.
- It scales with data and compute. Because training parallelises, it was practical to train much larger models on much more text. Published scaling studies of language models reported that test loss kept falling smoothly as parameters, data and compute grew, over the ranges they tested. That is an empirical finding behind the architecture's reach, not a theorem, and it says nothing about ranges nobody has tried.
- One simple, repeated block. Attention plus a small feed-forward network (two linear layers applied to each token's vector on its own), repeated, is easy to stack. The same block handles text, and, once the input is cut into tokens in another way (image patches, audio frames), images or audio too.
The price and the pitfalls
- The cost of the direct connections is the n squared pair count printed above: 1,048,576 pairs at n=1024. Long inputs get expensive in memory and time, which is why efficient attention variants exist: methods that compute only some of the n by n scores (for example, only those between nearby tokens) or compute them without storing the whole table.
- Attention itself ignores order, so position information has to be added separately.
- A high attention weight shows where information was read from, not that the model "understood" the relationship.
- A common mistake on this question: saying Transformers are "better because they have attention". Recurrent networks can have attention too; the decisive change was dropping the recurrence so training could run in parallel.
What roles do residual connections and layer normalization play in a Transformer block? Contrast pre-norm and post-norm placement briefly.
Sample Answer
The idea
A Transformer block wraps each of its two sub-layers (attention, then the feed-forward network) in two helpers. A residual connection (also called a skip connection) adds the sub-layer's input back to its output, so the sub-layer only has to learn a correction to what it was given. Layer normalization rescales each token's vector so that its entries have a stable mean and spread, which keeps the numbers flowing through dozens of layers in a range the next layer can handle. Where the normalization sits relative to the residual addition is the difference between post-norm (the original design) and pre-norm (common in deep models).
Terms used below. The residual stream is the running vector each token carries from layer to layer, to which every sub-layer adds its output. Initialization is the choice of random starting weights. Warmup means the learning rate (the step size of the weight updates) starts near zero and is raised gradually over the first training steps; the learning-rate schedule is the rule that sets the step size over training. Gradient flow is how well the learning signal travels backward from the loss to early layers. The identity matrix is the matrix that leaves a vector unchanged, so an identity term in a derivative means a signal passes through untouched. Root-mean-square (RMS) is the square root of the average squared entry, a typical size of the entries. Batch normalization normalizes each feature across the examples in a batch, instead of across the features of one token.
What each piece does
Residual connection. The block computes
y=x+F(x)where x is the token vectors entering the sub-layer and F is attention or the feed-forward network. Two consequences follow:
- The sub-layer starts as a small perturbation of the identity, so a freshly initialised deep stack still passes information through unchanged.
- During training, the derivative of y with respect to x is the identity matrix plus the derivative of F. The identity term gives gradients a direct path from the loss back to early layers, which is what makes stacks of 24, 48 or more layers trainable. With numbers: if each sub-layer's own derivative is 0.1, a 24-layer stack without skip connections multiplies 24 factors of 0.1 and the signal reaching the first layer is 0.1^24 = 1e-24, effectively zero. With y = x + F(x) each layer contributes 1 + 0.1 = 1.1 and the product is 1.1^24, about 9.85, so the signal survives. The program prints both.
Layer normalization. For each token separately, over its d_model features:
LN(x)=γ⊙σ2+ϵx−μ+βHere mu is the mean of that token's d_model entries, sigma squared is their variance (the average squared distance from the mean, dividing by d_model), epsilon is a tiny constant that avoids dividing by zero, gamma and beta are learned vectors of length d_model that let the model undo the normalization where useful, and the circled dot means element-wise multiplication. Because the statistics are computed within one token, the result does not depend on the other sequences in the batch (unlike batch normalization), so it behaves identically in training, at batch size 1 and on sequences of any length.
Pre-norm versus post-norm
| Post-norm (original Transformer) | Pre-norm | |
|---|---|---|
| Sub-layer update | y = LN(x + F(x)) | y = x + F(LN(x)) |
| Is the skip path left untouched? | No: LN sits on it after every sub-layer | Yes: the residual stream is a plain running sum |
| Scale of the residual stream | Reset to a fixed scale after every sub-layer | Grows as sub-layer outputs are added |
| Extra norm needed | None | A final LN before the output layer |
| Typical training behaviour | Needs careful warmup and learning-rate choice as depth grows | Usually trains stably at depth with less tuning |
The program below checks the layer norm formula against PyTorch, builds a 24-layer stack of each type with default initialization, and reports the scale of the residual stream. It also switches off both sub-layers of a block (zeroing their output weights) to show what is left of the skip path. This is a small synthetic setup (width 32, 4 heads, random inputs), so it shows the mechanism rather than the behaviour of a trained model.
import torch, torch.nn as nn, torch.nn.functional as F
torch.set_num_threads(1)
# 1) layer norm by hand against the library (biased variance, eps inside the sqrt)
x = torch.randn(3, 8)
mu, var = x.mean(-1, keepdim=True), x.var(-1, unbiased=False, keepdim=True)
mine = (x - mu) / torch.sqrt(var + 1e-5)
print("layer norm matches F.layer_norm:", torch.allclose(mine, F.layer_norm(x, (8,)), atol=1e-6))
# 2) deep stack of blocks, pre-norm vs post-norm, same sublayers, default init
class Block(nn.Module):
def __init__(s, d, pre):
super().__init__()
s.pre = pre
s.ln1, s.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
s.att = nn.MultiheadAttention(d, 4, batch_first=True)
s.ffn = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
def forward(s, x):
if s.pre:
h = s.ln1(x); x = x + s.att(h, h, h, need_weights=False)[0]
return x + s.ffn(s.ln2(x))
x = s.ln1(x + s.att(x, x, x, need_weights=False)[0])
return s.ln2(x + s.ffn(x))
def rms_profile(pre, seed, L=24, d=32):
torch.manual_seed(seed)
blocks = nn.ModuleList([Block(d, pre) for _ in range(L)])
h = torch.randn(4, 16, d)
out = []
with torch.no_grad():
for b in blocks:
h = b(h); out.append(h.pow(2).mean().sqrt().item())
return out
print("root-mean-square of the residual stream after layer 1, 6, 12, 24 (mean over 8 seeds)")
for pre in (True, False):
prof = torch.tensor([rms_profile(pre, s) for s in range(8)]).mean(0)
print("pre-norm " if pre else "post-norm", [round(prof[i - 1].item(), 3) for i in (1, 6, 12, 24)])
# 3) why the identity term matters: 24 layers whose own derivative is 0.1
f = 0.1
print("24 layers, sublayer derivative 0.1: without skip", f"{f ** 24:.1e}", " with skip (1 + 0.1)^24 =", round((1 + f) ** 24, 3))
# sublayers switched off (output projections zeroed): what is left is the skip path
def zeroed(pre):
torch.manual_seed(0)
b = Block(32, pre)
with torch.no_grad():
b.att.out_proj.weight.zero_(); b.att.out_proj.bias.zero_()
b.ffn[2].weight.zero_(); b.ffn[2].bias.zero_()
x = torch.randn(2, 5, 32) * 3
return torch.allclose(b(x), x, atol=1e-6)
print("block with dead sublayers returns its input unchanged pre-norm:", zeroed(True), " post-norm:", zeroed(False))
Output:
layer norm matches F.layer_norm: True
root-mean-square of the residual stream after layer 1, 6, 12, 24 (mean over 8 seeds)
pre-norm [1.036, 1.182, 1.382, 1.771]
post-norm [1.0, 1.0, 1.0, 1.0]
24 layers, sublayer derivative 0.1: without skip 1.0e-24 with skip (1 + 0.1)^24 = 9.85
block with dead sublayers returns its input unchanged pre-norm: True post-norm: False
In this setup the pre-norm residual stream's root-mean-square scale grows from 1.036 after layer 1 to 1.771 after layer 24 (it is a running sum of sub-layer outputs), while the post-norm stream is reset to scale 1.0 every layer by construction. The growth is expected and is not a defect: the stream is the input plus 48 sub-layer outputs (an attention output and a feed-forward output from each of the 24 blocks), which is why a final layer norm is applied before the output layer. This program measures only the forward scale of the stream; it does not train anything, so it cannot show which placement trains more stably. That evidence comes from analysis and experiments on trained models: Xiong et al. (2020) prove that at initialization the expected gradients of the parameters near the output layer are large in a post-norm Transformer, which makes a large learning rate unstable and is why post-norm needs a learning-rate warmup, while the gradients of a pre-norm Transformer are well behaved at initialization, so they could train it without warmup. In practice, instability shows up as a loss that spikes or diverges in the first steps of training. A pre-norm block whose sub-layers contribute nothing returns its input unchanged (True), whereas a post-norm block still renormalizes it (False): the skip path in pre-norm is a clean identity all the way through the stack.
Trade-offs and common mistakes
- Which to choose. Pre-norm is the safer default for deep stacks because gradients travel along an unnormalized identity path. The cost is a residual stream that grows with depth, which is why a final layer norm is added. Post-norm can be trained at depth but is more sensitive to warmup and learning rate. Which gives better final quality is an empirical question that depends on depth, learning-rate schedule and initialization, so the claim to avoid is that one is universally better.
- Mistake: saying layer norm "normalizes across the batch". It normalizes across the features of one token.
- Mistake: saying residual connections "prevent overfitting". They fix optimization (signal and gradient flow), not generalization.
- Mistake: omitting the final norm in a pre-norm model. The output layer would otherwise see an unnormalized stream.
Running the code
Install: pip install torch. Save the program to a file and run it with python. It uses fixed seeds.
Compute single-head attention by hand for a tiny example (two tokens, d_k = 2, given Q, K and V). Show the score matrix, the scaling, the row-wise softmax and the final output, and say what each attention row means.
Sample Answer
The setup
Single-head attention for 2 tokens with d_k = 2. Each token has a query (what it is looking for), a key (what it offers for matching) and a value (the content it passes on). Given:
Q=[1101],K=[1001],V=[1324]
Row i of each matrix belongs to token i. In a real model these three matrices are not typed in: they come from the token embeddings X (one row of numbers per token) multiplied by three learned weight matrices, Q = X W_Q, K = X W_K, V = X W_V. Here they are simply handed to you so the attention step can be done on its own. The formula is
Attention(Q,K,V)=softmax(dkQK⊤)V
where softmax is applied separately to each row.
Step by step
- Score matrix Q K^T (2 by 2): entry (i, j) is the dot product of query i with key j.
Row 0: (1,0) dot (1,0) = 1 and (1,0) dot (0,1) = 0. Row 1: (1,1) dot (1,0) = 1 and (1,1) dot (0,1) = 1. - Scaling by the square root of d_k = 2, which is 1.4142: 1 becomes 0.7071.
- Row-wise softmax: for row 0 the scaled scores are 0.7071 and 0; the weights are e^0.7071 over (e^0.7071 + e^0) = 0.6698 and 0.3302. For row 1 the two scores are equal, so each weight is 0.5.
- Output = weights times V: each output row is a weighted average of the rows of V. Row 0: 0.6698 times (1,2) plus 0.3302 times (3,4) = (1.6605, 2.6605). Row 1: 0.5 times (1,2) plus 0.5 times (3,4) = (2, 3).
The program does the same computation, adds the unscaled variant and compares with the library implementation.
import numpy as np
import torch
import torch.nn.functional as F
torch.set_num_threads(1)
Q = np.array([[1.0, 0.0], [1.0, 1.0]])
K = np.array([[1.0, 0.0], [0.0, 1.0]])
V = np.array([[1.0, 2.0], [3.0, 4.0]])
dk = Q.shape[1]
scores = Q @ K.T # (2 queries, 2 keys): row i, column j = q_i . k_j
scaled = scores / np.sqrt(dk)
e = np.exp(scaled - scaled.max(axis=1, keepdims=True))
weights = e / e.sum(axis=1, keepdims=True) # softmax across each ROW
out = weights @ V
np.set_printoptions(precision=4, suppress=True)
print("scores Q K^T:\n", scores)
print("scaled by sqrt(2):\n", scaled)
print("weights (row-wise softmax):\n", weights)
eu = np.exp(scores - scores.max(axis=1, keepdims=True))
print("weights without the 1/sqrt(d_k) scaling:\n", eu / eu.sum(axis=1, keepdims=True))
print("row sums:", weights.sum(axis=1))
print("output weights @ V:\n", out)
print("check row 0 by hand-style sum:", weights[0, 0] * V[0] + weights[0, 1] * V[1])
ref = F.scaled_dot_product_attention(*(torch.tensor(a, dtype=torch.float64) for a in (Q, K, V)))
print("matches library:", np.allclose(out, ref.numpy()))
Output:
scores Q K^T:
[[1. 0.]
[1. 1.]]
scaled by sqrt(2):
[[0.7071 0. ]
[0.7071 0.7071]]
weights (row-wise softmax):
[[0.6698 0.3302]
[0.5 0.5 ]]
weights without the 1/sqrt(d_k) scaling:
[[0.7311 0.2689]
[0.5 0.5 ]]
row sums: [1. 1.]
output weights @ V:
[[1.6605 2.6605]
[2. 3. ]]
check row 0 by hand-style sum: [1.6605 2.6605]
matches library: True
What each attention row means
Row i of the weight matrix is how token i divides one unit of attention across all tokens: entry (i, j) is how much token i reads from token j. Each row sums to 1 (the printed row sums), the columns do not have to. Row 0 puts 0.6698 on token 0 because its query (1,0) matches key 0 better than key 1; row 1's query (1,1) is equally close to both keys, so it takes a plain average of the two values. The output row is the resulting blend of the value vectors; a different row of the same matrix gives a different blend, which is why each token gets its own context-aware output.
What the scaling did
Without the 1/sqrt(d_k) division, row 0's weights would be 0.7311 and 0.2689 instead of 0.6698 and 0.3302: scaling softens the distribution. With only d_k = 2 the effect is small; with d_k = 64 or more the unscaled scores become large and the softmax saturates.
Causal variant and pitfalls
- A causal mask is a rule that stops each token from attending to later positions: before the softmax, the scores of those positions are set to minus infinity, so their weights become exactly 0. With a causal mask, token 0 may not see token 1, so row 0 is forced to (1, 0) and its output is V's row 0, (1, 2). Row 1 is unchanged here because it may see both.
- Softmax across rows, not columns.
- Scale by the square root of d_k, not by d_k, and not by the number of tokens.
- Keys and values have the same number of rows (one per token), but the values can have a different width than the keys.
Running the code
Save the program as demo.py and run python demo.py. The output above was produced with Python 3.12, numpy 2.1.3 and torch 2.5.1 (CPU). The program uses no random numbers, so the output is the same on every run.
Unlock Full Question Bank
Get access to all 31 Transformers and Attention interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.