Self-Attention from Scratch
🔍 What is self-attention? Self-attention lets every position in a sequence build its output from every other position. Each token has a query (what it is looking for), a key (what it offers) and a value (what it passes on). A token's output is the values averaged with weights given by how well its query matches each key.
Anthropic asked a research engineer, in the onsite ML programming round, to implement an unusual custom attention variant in PyTorch, make it run and test it, then answer questions such as why the scores are scaled and why there is a norm (the question).
The Prompt
Every attention variant starts from the standard version, so the interviewer wants it fluent: right shapes,
masks that hide the right thing, and no NaNs.
"Implement single-head self-attention. Given
xof shape(B, T, D)and the projection weights, return the attention output. Support a causal mask and a padding mask."
Clarifying Questions
You: What are the shapes? I'll assume the query and key projections map D to d_k, the value projection
maps D to d_v, and the output is (B, T, d_v).
Interviewer: Yes. One head, no biases, no output projection, no dropout.
You: How is the padding mask given, and what does True mean?
Interviewer: A boolean (B, T) array, True for real tokens. Padded positions must not be attended to.
You: With both masks, a padded query in a causal model can end up with no key it may look at. What should its output be?
Interviewer: Zeros, and no NaN anywhere, including in gradients.
You: NumPy or PyTorch? Can I use F.scaled_dot_product_attention?
Interviewer: NumPy first, then a PyTorch module. Don't call the built-in in your code, but you can test against it.
What You'll Build
masked_softmax(s, allowed) -> (B, T, T): a stable softmax over the last axis that leaves fully masked rows at zero.attention(x, Wq, Wk, Wv, causal, key_mask) -> (out, weights): NumPy, output(B, T, d_v)and weights(B, T, T).SelfAttention(d_model, d_k, d_v): a PyTorchnn.Modulewhoseforward(x, causal, key_mask)returns(B, T, d_v).
The Idea
Project the input three ways, score every query against every key, hide the pairs that aren't allowed, turn each row of scores into weights that sum to one, and average the values with them:
Q = x Wq (B, T, d_k)
K = x Wk (B, T, d_k)
V = x Wv (B, T, d_v)
S = Q K^T / sqrt(d_k) (B, T, T) S[b, i, j]: how well query i matches key j
S[not allowed] = -inf causal: j > i; padding: key j is padding
A = softmax(S, axis=-1) (B, T, T) each row sums to 1
out = A V (B, T, d_v)
Two facts are worth saying out loud. The score matrix is T x T per sequence, so time is O(B T^2 d) and memory
O(B T^2); that quadratic term is why long contexts are expensive. And the softmax runs over the key axis,
the last one, so each query's weights sum to one. Masks go in before the softmax as -inf, which exp turns into
exact zeros; masking after the softmax would leave rows that sum to less than one.
Implementation
The target is a batched version with no Python loops that never overflows and never produces NaN, then the
same thing as a PyTorch module. Each step below fixes one concrete failure of the step before.
Bad Solution: one query at a time
Approach
Write the math for one query at a time: list the keys it may see, score them, softmax, average. It is slow but hard to get wrong, which makes it the reference for the tests.
import math
import numpy as np
def attention_loops(x: np.ndarray, Wq: np.ndarray, Wk: np.ndarray, Wv: np.ndarray,
causal: bool = False, key_mask: np.ndarray | None = None) -> np.ndarray:
B, T, _ = x.shape
out = np.zeros((B, T, Wv.shape[1]))
for b in range(B):
q, k, v = x[b] @ Wq, x[b] @ Wk, x[b] @ Wv # (T, d_k), (T, d_k), (T, d_v)
for i in range(T):
allowed = [j for j in range(T)
if not (causal and j > i) and (key_mask is None or key_mask[b, j])]
if not allowed:
continue # nothing to attend to: zeros
s = np.array([q[i] @ k[j] for j in allowed]) / math.sqrt(q.shape[1])
w = np.exp(s - s.max())
w /= w.sum()
out[b, i] = sum(wj * v[j] for wj, j in zip(w, allowed))
return out
Challenges
It runs B * T * T interpreted dot products, so 32 sequences of 1,024 tokens is about 33 million Python steps.
Nothing here maps to a GPU either. It is the right first draft and the wrong answer.
Good Solution: batched matrix products
Approach
Compute all scores with one batched product, q @ k.transpose(0, 2, 1), which is (B, T, T). Apply each mask
by writing a large negative number into the hidden scores, then softmax and multiply by v.
def attention_naive(x: np.ndarray, Wq: np.ndarray, Wk: np.ndarray, Wv: np.ndarray,
causal: bool = False, key_mask: np.ndarray | None = None) -> np.ndarray:
T = x.shape[1]
q, k, v = x @ Wq, x @ Wk, x @ Wv # (B, T, d_k), (B, T, d_k), (B, T, d_v)
s = q @ k.transpose(0, 2, 1) / math.sqrt(q.shape[-1]) # (B, T, T)
if causal:
s = np.where(np.tril(np.ones((T, T), dtype=bool)), s, -1e9)
if key_mask is not None:
s = np.where(key_mask[:, None, :], s, -1e9) # (B, 1, T): hide keys
e = np.exp(s) # no max subtraction
return (e / e.sum(axis=-1, keepdims=True)) @ v # (B, T, d_v)
Challenges
It is fast, and on ordinary inputs it matches the loop version. Two inputs break it. A score above about 709
overflows exp in float64 (above about 11 in float16), giving inf / inf = NaN. And a fully masked row has every
entry exp(-1e9) = 0, so its weights are 0 / 0 = NaN. Subtracting the row max fixes the first, but then the
fully masked row becomes uniform weights over padding, which is wrong in a quieter way.
Great Solution: a stable masked softmax
Approach
Build one boolean allowed array of shape (B, T, T) from both masks and hand it to a softmax that subtracts
the row max and guards the one case where that fails: a row that is all -inf has a max of -inf, and
-inf - (-inf) is NaN. Replace that max with 0, so the row's exponentials are all exactly 0 and its weights
stay 0.
def masked_softmax(s: np.ndarray, allowed: np.ndarray) -> np.ndarray:
s = np.where(allowed, s, -np.inf) # (B, T, T)
m = s.max(axis=-1, keepdims=True)
m = np.where(np.isfinite(m), m, 0.0) # fully masked row: avoid inf - inf
e = np.exp(s - m) # masked entries -> exactly 0
return e / np.maximum(e.sum(axis=-1, keepdims=True), 1e-30) # all-zero row stays all zero
def attention(x: np.ndarray, Wq: np.ndarray, Wk: np.ndarray, Wv: np.ndarray,
causal: bool = False, key_mask: np.ndarray | None = None
) -> tuple[np.ndarray, np.ndarray]:
B, T, _ = x.shape
q, k, v = x @ Wq, x @ Wk, x @ Wv # (B, T, d_k), (B, T, d_k), (B, T, d_v)
s = q @ k.transpose(0, 2, 1) / math.sqrt(q.shape[-1]) # (B, T, T)
allowed = np.ones((B, T, T), dtype=bool)
if causal:
allowed &= np.tril(np.ones((T, T), dtype=bool)) # key j <= query i
if key_mask is not None:
allowed &= key_mask[:, None, :] # (B, 1, T): mask keys, not queries
a = masked_softmax(s, allowed) # (B, T, T)
return a @ v, a # (B, T, d_v), weights
Challenges
The output is now exact on every input, but memory is still O(B T^2) for the scores and weights. That is fine
for the interview and becomes the topic of a follow-up. np.einsum("bid,bjd->bij", q, k) computes the same
scores if you find it clearer; the point is to know what each axis means.
The PyTorch Version
The PyTorch module is the same math, and nn.Linear(D, d_k, bias=False) stores a (d_k, D) weight and computes
x @ W.T, so the projections need no manual transposes. Here softmax of an all -inf row returns NaN; a
second masked_fill sets every disallowed weight to zero, which removes those NaNs because every entry of such
a row is disallowed.
import torch
import torch.nn as nn
class SelfAttention(nn.Module):
def __init__(self, d_model: int, d_k: int, d_v: int) -> None:
super().__init__()
self.q = nn.Linear(d_model, d_k, bias=False)
self.k = nn.Linear(d_model, d_k, bias=False)
self.v = nn.Linear(d_model, d_v, bias=False)
self.scale = d_k ** -0.5
def forward(self, x: torch.Tensor, causal: bool = False,
key_mask: torch.Tensor | None = None) -> torch.Tensor:
B, T, _ = x.shape
q, k, v = self.q(x), self.k(x), self.v(x) # (B, T, d_k/d_v)
s = q @ k.transpose(-2, -1) * self.scale # (B, T, T)
allowed = torch.ones(B, T, T, dtype=torch.bool, device=x.device)
if causal:
allowed = allowed & torch.ones(T, T, dtype=torch.bool, device=x.device).tril()
if key_mask is not None:
allowed = allowed & key_mask[:, None, :] # (B, 1, T)
a = s.masked_fill(~allowed, float("-inf")).softmax(dim=-1) # fully masked row -> NaN
a = a.masked_fill(~allowed, 0.0) # ... -> zeros
return a @ v # (B, T, d_v)
Gradients stay clean too: masked_fill passes a zero gradient to the positions it overwrote, so the NaN in the
softmax's backward pass never reaches the scores. The tests below check this with gradcheck.
Common Mistakes
- Padding mask on the wrong axis. Symptom: no error, but real tokens still attend to padding. The mask must
broadcast as
(B, 1, T)to hide keys;(B, T, 1)hides queries instead. Fix: write the shape next to the indexing and test that changing a padded token changes nothing. .Ton a 3D array. Symptom: a shape error, or worse, a square batch where it silently runs..Treverses all three axes. Fix:transpose(0, 2, 1)in NumPy,transpose(-2, -1)in PyTorch.- Softmax over the wrong axis. Symptom: columns sum to one instead of rows, and causal outputs depend on the
future. Fix: softmax over the last axis and assert that
a.sum(-1)is all ones on a(2, 5)example. - Masking after the softmax. Symptom: rows sum to less than one and outputs shrink. Fix:
-infbefore the softmax.
Testing It
Test a known answer, agreement with the loop version, and two behaviors that catch mask bugs a comparison might share. Start with the known answer: with zero query weights every score is zero, so each query averages the values it may see, all of them without a mask and its prefix with a causal mask.
rng = np.random.default_rng(0)
B, T, D, dk, dv = 2, 5, 8, 4, 3
x = rng.normal(size=(B, T, D))
Wq, Wk, Wv = rng.normal(size=(D, dk)), rng.normal(size=(D, dk)), rng.normal(size=(D, dv))
v = x @ Wv
out, _ = attention(x, np.zeros_like(Wq), Wk, Wv)
assert np.allclose(out, v.mean(axis=1, keepdims=True).repeat(T, axis=1))
out, _ = attention(x, np.zeros_like(Wq), Wk, Wv, causal=True)
assert np.allclose(out, v.cumsum(axis=1) / np.arange(1, T + 1)[None, :, None])
Next, compare with the loop version under both masks, including a sequence whose first token is padding, so that in a causal model its first query has no allowed key. The same block shows the inputs that break the Good solution: large scores and that fully masked row.
key_mask = np.array([[True] * 5, [False, True, True, True, False]])
for causal in (False, True):
out, a = attention(x, Wq, Wk, Wv, causal, key_mask)
assert np.allclose(out, attention_loops(x, Wq, Wk, Wv, causal, key_mask))
assert not np.isnan(out).any()
assert np.allclose(out[1, 0], 0) # padded first query, causal: nothing to see
assert np.allclose(a[0].sum(-1), 1) # rows with any allowed key sum to 1
assert np.allclose(np.triu(a[0], k=1), 0) # causal: no weight on the future
assert np.allclose(attention_naive(x, Wq, Wk, Wv, True), attention(x, Wq, Wk, Wv, True)[0])
with np.errstate(all="ignore"):
assert np.isnan(attention_naive(100 * x, Wq, Wk, Wv)).any() # exp overflow
assert np.isnan(attention_naive(x, Wq, Wk, Wv, True, key_mask)).any() # 0 / 0 row
assert not np.isnan(attention(100 * x, Wq, Wk, Wv)[0]).any()
Then the behaviors. Under a causal mask, changing a later token must not change any earlier output; changing a padded token must not change anything. These catch a mask on the wrong axis even if the loop version had the same bug.
x2 = x.copy()
x2[:, 3] += 10.0 # change token 3 only
o1, _ = attention(x, Wq, Wk, Wv, causal=True)
o2, _ = attention(x2, Wq, Wk, Wv, causal=True)
assert np.allclose(o1[:, :3], o2[:, :3]) and not np.allclose(o1[:, 3], o2[:, 3])
x3 = x.copy()
x3[1, 4] = rng.normal(size=D) # token 4 of sequence 1 is padding
o1, _ = attention(x, Wq, Wk, Wv, key_mask=key_mask)
o3, _ = attention(x3, Wq, Wk, Wv, key_mask=key_mask)
assert np.allclose(o1[1, 1:4], o3[1, 1:4]) # real tokens never see the padding
For the module, compare against the built-in where both are defined, then run gradcheck in float64, which
compares autograd with finite differences, with the fully masked row included:
import torch.nn.functional as F
torch.manual_seed(0)
attn = SelfAttention(D, dk, dv).double()
xt = torch.randn(B, T, D, dtype=torch.float64, requires_grad=True)
q, k, v = attn.q(xt), attn.k(xt), attn.v(xt)
assert torch.allclose(attn(xt, causal=True), F.scaled_dot_product_attention(q, k, v, is_causal=True))
km = torch.tensor(key_mask)
assert torch.autograd.gradcheck(lambda t: attn(t, causal=True, key_mask=km), (xt,))
attn(xt, causal=True, key_mask=km).sum().backward()
assert torch.isfinite(xt.grad).all() and all(torch.isfinite(p.grad).all() for p in attn.parameters())
Run each test as soon as the code it covers exists: the zero-query case right after the NumPy version, the built-in comparison right after the module. A mask bug found in minute 15 costs a minute; found in minute 40, it costs the round.
Follow-ups
1) Why scale by sqrt(d_k)?
Without the scale, scores grow with the head size and the softmax saturates. If query and key entries are
independent with mean 0 and variance 1, their dot product sums d_k such products, so its variance is d_k. A
saturated softmax is nearly one-hot, and its gradient, A * (g - sum(A * g)), is close to zero everywhere. You can
show it in a few lines:
for d in (4, 64, 1024):
s = rng.normal(size=(200, 16, d)) @ rng.normal(size=(200, d, 16)) # 16 queries x 16 keys
a = masked_softmax(s, np.ones_like(s, dtype=bool))
a_scaled = masked_softmax(s / np.sqrt(d), np.ones_like(s, dtype=bool))
print(d, round(s.std(), 1), round(a.max(-1).mean(), 2), round(a_scaled.max(-1).mean(), 2))
The scores' standard deviation comes out at about 2, 8 and 32. The mean top weight without scaling climbs from
0.42 to 0.85 to 0.96, so at d_k = 1024 each query attends to one key; with scaling it stays near 0.25 at every
size. Any constant would work for one head size, and sqrt(d_k) is the one that works for all of them at
initialization.
2) Why put a norm in there?
Scaling fixes the variance at initialization, but training can still grow the query and key weights, and the
logits grow with them until the softmax collapses onto one key and training becomes unstable. Normalizing q and
k per vector, for example RMSNorm on each ("QK-norm"), bounds the dot product however large the weights get,
and a learned gain gives back control over how sharp attention can be. Separately, transformer blocks normalize
the input to attention (pre-norm) so the residual stream's growing scale doesn't feed straight into the
projections.
def rms_norm(t: torch.Tensor, gain: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
return t * torch.rsqrt(t.pow(2).mean(-1, keepdim=True) + eps) * gain
qn, kn = rms_norm(q, torch.ones(dk)), rms_norm(k, torch.ones(dk))
s = qn @ kn.transpose(-2, -1) * dk ** -0.5 # every |score| <= sqrt(d_k) with unit gains
assert s.abs().max() <= dk ** 0.5 + 1e-6
3) The T x T matrix doesn't fit for long sequences. What do you do?
You never need the whole matrix at once. Process keys in blocks and keep, per query, a running max m, a running
sum of exponentials l and a running weighted sum of values; when a block raises the max, rescale what you have by
exp(m_old - m_new). This online softmax is the idea behind FlashAttention: the same output with O(T * block)
memory.
def attention_blocked(q: np.ndarray, k: np.ndarray, v: np.ndarray, block: int = 2) -> np.ndarray:
T, d = q.shape # one sequence, no mask, for clarity
m, l, acc = np.full((T, 1), -np.inf), np.zeros((T, 1)), np.zeros((T, v.shape[1]))
for s0 in range(0, k.shape[0], block):
s = q @ k[s0:s0 + block].T / math.sqrt(d) # (T, block)
m_new = np.maximum(m, s.max(-1, keepdims=True))
p = np.exp(s - m_new)
r = np.exp(m - m_new) # rescale the old running sums
l, acc, m = l * r + p.sum(-1, keepdims=True), acc * r + p @ v[s0:s0 + block], m_new
return acc / l
q0, k0, v0 = x[0] @ Wq, x[0] @ Wk, x[0] @ Wv
assert np.allclose(attention_blocked(q0, k0, v0), attention(x[:1], Wq, Wk, Wv)[0][0])
4) How would you make it multi-head?
Project to H * d_head once, reshape to (B, T, H, d_head) and transpose to (B, H, T, d_head). The attention
code above then runs unchanged with the heads as an extra batch axis, and the result is reshaped back and passed
through an output projection; see Multi-Head and Grouped-Query Attention.
Cross-attention is the same code with queries from one sequence and keys and values from another, so the scores
become (B, T_q, T_k).
What is Expected at Each Level?
Junior
A junior candidate should write the formula from memory with the right shapes and get a batched NumPy version
running, with the softmax over the last axis and the sqrt(d_k) scale. A causal mask with np.tril is expected;
the fully masked row and the exact padding axis may need a hint. They should be able to say that the cost is
quadratic in sequence length.
Mid-level
A mid-level candidate asks about mask conventions and fully masked rows up front, writes a stable softmax without prompting, and moves to a clean PyTorch module. They test against a known answer and the built-in, and check that the future and padding don't leak. They explain the variance argument for the scale in a couple of sentences.
Senior
A senior or research engineer candidate does all of that quickly, then goes deeper: why softmax saturation kills
gradients, why QK-norm or pre-norm keeps training stable, how the online softmax gets memory to linear in T, and
how heads, grouped-query attention and a KV cache change the shapes. Given an unfamiliar
variant, they map it onto this skeleton, say which part changes, and write a test that would catch it being
wrong.