TExcelTAD

Attention from Scratch

A recurrent encoder reads a sentence token by token and hands the decoder one vector: its last hidden state. Whatever the sentence length, 5 tokens or 500, everything the decoder will ever know about the input has to fit into those few hundred numbers. In Training Sequence Models you saw the practical symptoms: long inputs are remembered worse than short ones, and the gradient from the last output to the first input passes through every step in between.

Attention removes the bottleneck. Instead of one summary vector, the model keeps a vector for every input position and, at each output step, computes a fresh weighted average of all of them. The weights are computed from the data: a position that is relevant right now gets a large weight, the rest get small ones. Every position is one step away from every other, so there is no long chain for information or gradients to cross. The derivation and the geometry of the dot product are in Dot-Product Attention; this lesson implements it in NumPy, adds the masks that real batches need, splits it into heads, and checks every piece against PyTorch.

Queries, keys and values

Each token's vector xix_i is projected three ways. The query qi=xiWQq_i = x_i W_Q says what token ii is looking for, the key kj=xjWKk_j = x_j W_K says what token jj offers, and the value vj=xjWVv_j = x_j W_V is what token jj hands over when it is chosen. The match between a query and a key is their dot product; a softmax over all keys turns the matches into weights that sum to 1; the output is the weighted sum of the values.

X (T x E) Q = X W_Q K = X W_K V = X W_V S = Q K^T / sqrt(d) T x T scores mask: -inf softmax rows A values A V output row i = sum over j of A_ij v_j scores, mask, weights

The lab: one sentence, six queries

The lab below uses the sentence "the cat sat on the mat" with fixed 4-dimensional embeddings and fixed WQW_Q, WKW_K (no positional information, so both "the" rows are identical). Row ii of the heatmap is query ii; each cell is a weight; the column on the right shows that every row sums to 1.000. It starts on row 3, "sat": its largest weight, 0.621, is on itself, followed by "cat" at 0.198. Drag the temperature TT: below 1 the row sharpens towards a single key, above 1 it spreads out (the readout gives the row's entropy in bits; 1.57 bits at T=1T = 1 against a maximum of 2.58 for six keys). Switch the mask to "causal" and the cells above the diagonal become masked: "sat" may now only look at "the", "cat" and itself.

Weights A (row = query)key →thecatsatonthemat1 the2 cat3 sat4 on5 the6 mat0.230.080.090.220.230.140.010.310.470.020.010.170.010.200.620.030.010.130.150.120.130.220.150.230.230.080.090.220.230.140.020.310.310.040.020.29row sum1.0001.0001.0001.0001.0001.000T = 1.0; d = 4; every token sees every tokenQuery "sat" (row 3)keyweightthes = 1.01 → 0.012cats = 3.79 → 0.198sats = 4.93 → 0.621ons = 1.89 → 0.030thes = 1.01 → 0.012mats = 3.35 → 0.127

The formula

For a sequence stacked into matrices Q∈RTq×dQ \in \mathbb{R}^{T_q \times d}, K∈RTk×dK \in \mathbb{R}^{T_k \times d} and V∈RTk×dvV \in \mathbb{R}^{T_k \times d_v}:

Attention⁡(Q,K,V)=softmax⁡(QK⊤d+M)V,Mij={0key j allowed for query i−∞otherwise\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\left(\frac{Q K^\top}{\sqrt{d}} + M\right) V, \qquad M_{ij} = \begin{cases} 0 & \text{key } j \text{ allowed for query } i \\ -\infty & \text{otherwise} \end{cases}

The softmax runs along each row (over keys). Dividing by d\sqrt{d} keeps the scores at unit scale when the entries of qq and kk are: a dot product of dd independent unit-variance terms has variance dd, and without the division the softmax saturates and its gradient vanishes (why). The mask MM is added before the softmax, so a forbidden key gets e−∞=0e^{-\infty} = 0 and the remaining weights still sum to 1. Two masks cover almost every case:

  • Padding mask: sequences in a batch have different lengths and are padded to the same TT. Pad positions must never be attended, so the mask removes those keys for every query.
  • Causal mask: a decoder that predicts token i+1i + 1 must not see tokens after ii. The mask removes keys j>ij > i, the upper triangle (Causal Masking).

The example reproduces the lab's numbers exactly from the same matrices.

python · try it yourself
import numpy as np

tokens = ["the", "cat", "sat", "on", "the", "mat"]
X = np.array([[2, 0, 0, 0.4], [0, 2, 0.6, 0], [0.4, 0.8, 2, 0],
              [1.2, 0, 0.4, 1.2], [2, 0, 0, 0.4], [0, 1.8, 0.2, 1]])
W_q = np.array([[1, 0, 0, 0.5], [0, 1.2, 0.4, 0], [0, 0.8, 1, 0], [0.5, 0, 0, 1]])
W_k = np.array([[0.8, 0, 0.2, 0], [0, 1, 0, 0.6], [0.2, 0.6, 0.9, 0], [0, 0, 0.4, 1]])

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

Q, K = X @ W_q, X @ W_k
d = Q.shape[-1]
S = Q @ K.T / np.sqrt(d)
A = softmax(S)
print("scores of 'sat':", np.round(S[2], 2).tolist())
print("weights of 'sat':", np.round(A[2], 3).tolist())
print("row sums:", np.round(A.sum(axis=1), 3).tolist())
print("most attended key per query:", [tokens[j] for j in A.argmax(axis=1)])
print("rows of the two 'the' tokens equal:", np.allclose(A[0], A[4]))

causal = np.triu(np.ones((6, 6), dtype=bool), k=1)   # True above the diagonal = future
A_c = softmax(np.where(causal, -np.inf, S))
print("causal weights of 'sat':", np.round(A_c[2], 3).tolist())
print("row 1 under the causal mask:", np.round(A_c[0], 3).tolist())
for T in (0.5, 1.0, 2.0):
    a = softmax(S[2] / T)
    H = -(a * np.log2(a)).sum()
    print(f"T = {T}: max weight {a.max():.3f}, entropy {H:.2f} bits")
scores of 'sat': [1.01, 3.79, 4.93, 1.89, 1.01, 3.35]
weights of 'sat': [0.012, 0.198, 0.621, 0.03, 0.012, 0.127]
row sums: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
most attended key per query: ['the', 'sat', 'sat', 'mat', 'the', 'cat']
rows of the two 'the' tokens equal: True
causal weights of 'sat': [0.015, 0.238, 0.747, 0.0, 0.0, 0.0]
row 1 under the causal mask: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
T = 0.5: max weight 0.872, entropy 0.68 bits
T = 1.0: max weight 0.621, entropy 1.57 bits
T = 2.0: max weight 0.397, entropy 2.23 bits

Three things to notice. The softmax is the stable version (subtract the row maximum), which also handles −∞-\infty correctly as long as one key in the row survives. Under the causal mask, the weight that "sat" gave to "on" and "mat" (0.03 and 0.127) is redistributed over the three allowed keys, so its own weight rises from 0.621 to 0.747, and the first token can only attend to itself (weight 1.0). And the two "the" rows are identical: attention by itself does not know where a token is. That is why transformers add positional encodings.

Batches with padding and a causal mask

A real implementation works on a batch (B, T, d) and accepts a boolean mask that broadcasts against the (B, T, T) scores. Below, the second sequence has only 3 real tokens and 2 padding positions. The padding mask has shape (B, 1, T) (one row, shared by every query), the causal mask (T, T); combined with & they broadcast to (B, T, T). The test at the end is the one that matters: overwrite the padding with garbage, and the outputs at the real positions must not change.

python · try it yourself
import numpy as np

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

def attention(Q, K, V, mask=None):
    """Q: (..., Tq, d), K and V: (..., Tk, d). mask: True where a key may be attended."""
    S = Q @ np.swapaxes(K, -1, -2) / np.sqrt(Q.shape[-1])
    if mask is not None:
        S = np.where(mask, S, -np.inf)
    A = softmax(S)
    return A @ V, A

rng = np.random.default_rng(0)
B, T, d = 2, 5, 8
x = rng.normal(size=(B, T, d))
lengths = np.array([5, 3])                     # the second sequence has 2 padding positions
key_ok = np.arange(T)[None, :] < lengths[:, None]            # (B, T)
pad_mask = key_ok[:, None, :]                                # (B, 1, T): same for every query
causal = np.tril(np.ones((T, T), dtype=bool))                # (T, T): key j <= query i
out, A = attention(x, x, x, pad_mask & causal)
print("mask shape:", (pad_mask & causal).shape)
print("weights, sequence 2, query 3:", np.round(A[1, 2], 3).tolist())
print("weight on padding keys (seq 2):", float(A[1, :, 3:].sum()))
print("output shape:", out.shape)

# Change the padded positions: the real positions' outputs do not move.
x2 = x.copy()
x2[1, 3:] = 99.0
out2, _ = attention(x2, x2, x2, pad_mask & causal)
print("real outputs unchanged:", np.allclose(out[1, :3], out2[1, :3]))
mask shape: (2, 5, 5)
weights, sequence 2, query 3: [0.071, 0.044, 0.885, 0.0, 0.0]
weight on padding keys (seq 2): 0.0
output shape: (2, 5, 8)
real outputs unchanged: True

Here Q=K=V=xQ = K = V = x to keep the code short; in a layer they come from three projections. The padded query rows (positions 4 and 5 of sequence 2) still produce outputs, which are meaningless; the loss must ignore them (the ignore_index / loss-mask trick from sequence training).

Multi-head attention is a reshape

One attention pattern per layer is limiting: a token may need to look at its subject and at the previous token at the same time. Multi-head attention runs hh attentions in parallel, each on its own dh=E/hd_h = E / h slice of the projected vectors, and concatenates the results before a final output projection WOW_O:

MHA⁡(X)=concat⁡(head1,…,headh) WO,headi=Attention⁡(XWQ(i),XWK(i),XWV(i))\operatorname{MHA}(X) = \operatorname{concat}(\text{head}_1, \dots, \text{head}_h)\, W_O, \qquad \text{head}_i = \operatorname{Attention}(X W_Q^{(i)}, X W_K^{(i)}, X W_V^{(i)})

In code there are no hh separate matrices. You project once with full E×EE \times E matrices, then reshape (B, T, E) to (B, T, h, d_h) and move the head axis forward to (B, h, T, d_h). The attention function, which only looks at the last two axes, then treats the heads as one more batch axis. The math of why the cost stays the same as one big head is in Multi-Head Attention; the check here is that the reshape gives exactly the same result as an explicit loop over column slices.

python · try it yourself
import numpy as np

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

def attention(Q, K, V, mask=None):
    S = Q @ np.swapaxes(K, -1, -2) / np.sqrt(Q.shape[-1])
    if mask is not None:
        S = np.where(mask, S, -np.inf)
    A = softmax(S)
    return A @ V, A

def split_heads(x, h):              # (B, T, E) -> (B, h, T, E/h)
    B, T, E = x.shape
    return x.reshape(B, T, h, E // h).transpose(0, 2, 1, 3)

def merge_heads(x):                 # (B, h, T, dh) -> (B, T, h*dh)
    B, h, T, dh = x.shape
    return x.transpose(0, 2, 1, 3).reshape(B, T, h * dh)

def mha(x, Wq, Wk, Wv, Wo, h, mask=None):
    Q, K, V = (split_heads(x @ W, h) for W in (Wq, Wk, Wv))
    out, A = attention(Q, K, V, mask)        # every head at once, shapes (B, h, T, T)
    return merge_heads(out) @ Wo, A

rng = np.random.default_rng(0)
B, T, E, h = 2, 4, 8, 2
x = rng.normal(size=(B, T, E))
Wq, Wk, Wv, Wo = (rng.normal(0, E ** -0.5, (E, E)) for _ in range(4))
y, A = mha(x, Wq, Wk, Wv, Wo, h)
print("output", y.shape, "weights", A.shape)

# The same thing with an explicit loop over heads: each head owns a slice of columns.
dh = E // h
heads = []
for i in range(h):
    cols = slice(i * dh, (i + 1) * dh)
    o, _ = attention(x @ Wq[:, cols], x @ Wk[:, cols], x @ Wv[:, cols])
    heads.append(o)
y_loop = np.concatenate(heads, axis=-1) @ Wo
print("reshape version == loop version:", np.allclose(y, y_loop))
print("y[0, 0]:", np.round(y[0, 0], 3).tolist())
print("parameters:", 4 * E * E)
output (2, 4, 8) weights (2, 2, 4, 4)
reshape version == loop version: True
y[0, 0]: [0.099, 0.197, 0.12, 0.521, 0.403, 0.15, 0.412, -1.028]
parameters: 256

The weights come back with shape (B, h, T, T): one attention map per head. The layer has 4E2=2564E^2 = 256 weights for E=8E = 8, independent of hh and of the sequence length; the cost that grows with length is the T×TT \times T score matrix.

The same in PyTorch

PyTorch offers the kernel as torch.nn.functional.scaled_dot_product_attention (which picks a fused, memory-efficient implementation when it can) and the full layer as nn.MultiheadAttention. The recorded example (run on a CPU, float64 so the comparison is tight) feeds both the same inputs as the NumPy code. To compare the layer, our four weight matrices are copied into it, which requires knowing its parameter layout:

  • in_proj_weight has shape (3E, E): the query, key and value projections stacked by rows, in that order. nn.Linear-style layers compute x @ W.T, so our x @ Wq matrix goes in transposed.
  • out_proj is an ordinary nn.Linear(E, E), again transposed. Both projections have biases by default; we zero them.
python · try it yourself
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn

def softmax(z):
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

def attention(Q, K, V, mask=None):
    S = Q @ np.swapaxes(K, -1, -2) / np.sqrt(Q.shape[-1])
    if mask is not None:
        S = np.where(mask, S, -np.inf)
    A = softmax(S)
    return A @ V, A

rng = np.random.default_rng(0)
B, T, E, h = 2, 5, 8, 2
x = rng.normal(size=(B, T, E))
key_ok = np.arange(T)[None, :] < np.array([5, 3])[:, None]      # (B, T), True = real token
causal = np.tril(np.ones((T, T), dtype=bool))

# 1. The functional kernel. A boolean attn_mask means True = may attend (same as ours).
xt = torch.tensor(x, dtype=torch.float64)
ours, _ = attention(x, x, x, key_ok[:, None, :] & causal)
theirs = F.scaled_dot_product_attention(xt, xt, xt, attn_mask=torch.tensor(key_ok[:, None, :] & causal))
print("SDPA with mask matches:", np.allclose(ours, theirs.numpy(), atol=1e-12))
ours_c, _ = attention(x, x, x, causal)
theirs_c = F.scaled_dot_product_attention(xt, xt, xt, is_causal=True)
print("SDPA is_causal matches:", np.allclose(ours_c, theirs_c.numpy(), atol=1e-12))

# 2. nn.MultiheadAttention with our weights copied in.
Wq, Wk, Wv, Wo = (rng.normal(0, E ** -0.5, (E, E)) for _ in range(4))
mha = nn.MultiheadAttention(E, h, batch_first=True, dtype=torch.float64)
print("in_proj_weight:", tuple(mha.in_proj_weight.shape), "out_proj.weight:", tuple(mha.out_proj.weight.shape))
with torch.no_grad():
    mha.in_proj_weight.copy_(torch.tensor(np.concatenate([Wq.T, Wk.T, Wv.T])))   # rows: q, k, v
    mha.in_proj_bias.zero_()
    mha.out_proj.weight.copy_(torch.tensor(Wo.T))                               # Linear computes x @ W.T
    mha.out_proj.bias.zero_()

def split(z):
    return z.reshape(B, T, h, E // h).transpose(0, 2, 1, 3)

o, A_heads = attention(split(x @ Wq), split(x @ Wk), split(x @ Wv), key_ok[:, None, None, :])
y_np = o.transpose(0, 2, 1, 3).reshape(B, T, E) @ Wo

# key_padding_mask uses the OPPOSITE convention: True = ignore this key.
y_t, A_avg = mha(xt, xt, xt, key_padding_mask=torch.tensor(~key_ok))
print("MHA output matches:", np.allclose(y_np, y_t.detach().numpy(), atol=1e-12))
print("returned weights:", tuple(A_avg.shape), "= mean over heads:", np.allclose(A_heads.mean(axis=1), A_avg.detach().numpy()))
_, A_all = mha(xt, xt, xt, key_padding_mask=torch.tensor(~key_ok), average_attn_weights=False)
print("average_attn_weights=False:", tuple(A_all.shape))
print("parameters:", sum(p.numel() for p in mha.parameters()))
SDPA with mask matches: True
SDPA is_causal matches: True
in_proj_weight: (24, 8) out_proj.weight: (8, 8)
MHA output matches: True
returned weights: (2, 5, 5) = mean over heads: True
average_attn_weights=False: (2, 2, 5, 5)
parameters: 288

Everything matches to 10−1210^{-12}. The details worth remembering:

  • Two mask conventions. In scaled_dot_product_attention a boolean attn_mask is True where attention is allowed. In nn.MultiheadAttention, key_padding_mask (and a boolean attn_mask) is True where it is forbidden. Passing the wrong one does not raise an error; it silently attends only to the padding. A float mask is added to the scores in both, so 0 and -inf mean the same everywhere.
  • The returned weights are averaged over heads by default: shape (B, T, T), not (B, h, T, T). Pass average_attn_weights=False for one map per head, or need_weights=False when you don't need them at all (that also lets PyTorch use the fused kernel).
  • Parameters: 288 = 4E2+4E4E^2 + 4E, the 256 weights plus four bias vectors of 8.
  • batch_first=True makes the layer take (B, T, E); the default is (T, B, E), a frequent source of wrong-but-running code.

Pitfalls

  • A row with every key masked. The softmax of a row of −∞-\infty is 0/00/0 = NaN, which then spreads through every later layer. It happens with left padding plus a causal mask, or with an empty sequence. Make sure each query can see at least one key (its own position usually), or replace NaN rows with zeros after the softmax.
  • Masking after the softmax. Multiplying the weights by a 0/1 mask leaves rows that no longer sum to 1. Mask the scores, before the softmax.
  • Forgetting the d\sqrt{d}. Training still runs, but with large head dimensions the softmax saturates early and learning is slow.
  • Mixing up the axes when splitting heads. x.reshape(B, h, T, dh) without the transpose is the classic bug: it runs, the shapes look right, and each "head" mixes positions. The loop-vs-reshape check above catches it.
  • Memory. The score matrix is T×TT \times T per head and per batch item. At T=4096T = 4096, h=16h = 16 and float32 that is 1 GiB per sequence for one layer's scores, which is why fused kernels (FlashAttention-style, used by scaled_dot_product_attention) never store it.

Practice

  1. In the lab, set the causal mask and query 6, "mat". Which keys can it attend to, and what is the maximum possible entropy of its row?
Answer

All six (it is the last token, so nothing is in its future): the causal mask changes nothing for the last row. The maximum entropy for six keys is log⁡26=2.58\log_2 6 = 2.58 bits.

  1. Without running it: if every score in a row increases by the same constant cc, how do the weights change? What if the mask's −∞-\infty is replaced by −109-10^9?
Answer

Not at all: softmax is invariant to adding a constant to the whole row. With −109-10^9 the forbidden weights are e−109=0e^{-10^9} = 0 in floating point, so the result is the same, and a fully masked row no longer gives NaN (it gives a uniform average over all keys, including the forbidden ones, which is still wrong but finite). Be careful in float16, where −109-10^9 overflows to −∞-\infty; libraries use the dtype's most negative finite number.

  1. Change split_heads in the multi-head example to x.reshape(B, h, T, E // h) (no transpose) and rerun. What does the loop-vs-reshape check print, and why?
Answer

False. Reshaping (B, T, E) straight to (B, h, T, d_h) reinterprets memory: the first "head" takes the first T⋅dhT \cdot d_h numbers, which are the first two tokens' full vectors, so each head mixes several positions' features instead of taking one slice of every position.

  1. In the PyTorch example, pass key_padding_mask=torch.tensor(key_ok) (the un-negated mask). What happens to sequence 2?
Answer

Its 3 real keys are now forbidden and the 2 padding keys allowed, so every query of sequence 2 attends only to padding. Sequence 1 has no padding, so every key is forbidden and its rows are NaN. No error is raised: always check a mask convention with a test like "changing the padding must not change the outputs".

Test yourself

What problem of a recurrent encoder-decoder does attention remove?

  1. The need for a loss function
  2. Squeezing the whole input into one fixed-size vector, with long paths between distant positions
  3. The need for embeddings
  4. The softmax at the output

Where is the causal mask applied?

  1. To the weights after the softmax, by multiplying with a 0/1 matrix
  2. To the scores before the softmax, setting keys j>ij > i to −∞-\infty
  3. To the values
  4. To the output projection

In the lab's sentence, why are the rows of the two 'the' tokens identical?

  1. Because of the causal mask
  2. Because the temperature is 1
  3. Because they have the same embedding and attention has no notion of position
  4. Because the softmax is rounded

nn.MultiheadAttention(8, 2) returns attention weights of shape (B, T, T). What are they?

  1. The weights of head 1
  2. The mean of the heads' weights
  3. The scores before the softmax
  4. The weights of the last head

For nn.MultiheadAttention, key_padding_mask is a boolean tensor in which True means…

  1. this key may be attended
  2. this key must be ignored
  3. this query is padding
  4. this head is disabled