TExcelTAD
Home › Linear Algebra & Matrix Theory › Attention as Matrix Products

Attention as Matrix Products

The attention mechanism at the heart of every transformer and LLM is three matrix multiplications and a softmax: softmax⁡(QKT/d)⋅V\operatorname{softmax}(QK^T/\sqrt{d}) \cdot V. This lesson builds it by hand in NumPy, adds the causal mask used by GPT-style models, and shows how multi-head attention is just a reshape.

Queries, keys and values

Take a sequence of TT tokens, each already turned into a dmodeld_{\text{model}}-dimensional vector (an embedding), stacked as the rows of XX (T×dmodelT \times d_{\text{model}}). Three learned matrices, applied like dense layers, give three views of every token:

Q=XWQ(T×d)queries: “what am I looking for?”K=XWK(T×d)keys: “what do I contain?”V=XWV(T×dv)values: “what do I pass on if chosen?”\begin{aligned} Q &= XW_Q && (T \times d) && \text{queries: ``what am I looking for?''} \\ K &= XW_K && (T \times d) && \text{keys: ``what do I contain?''} \\ V &= XW_V && (T \times d_v) && \text{values: ``what do I pass on if chosen?''} \end{aligned}

Scaled dot-product attention

S=QKT/d(T×T)S[i,j]=(qi⋅kj)/dA=softmax of each row of S(T×T)every row is positive and sums to 1Out=AV(T×dv)row i=weighted average of the value vectors\begin{aligned} S &= QK^T/\sqrt{d} && (T \times T) && S[i, j] = (\mathbf{q}_i \cdot \mathbf{k}_j)/\sqrt{d} \\ A &= \text{softmax of each row of } S && (T \times T) && \text{every row is positive and sums to 1} \\ \text{Out} &= AV && (T \times d_v) && \text{row } i = \text{weighted average of the value vectors} \end{aligned}

S[i,j]S[i, j] is a dot product: how well token ii's query matches token jj's key. The row softmax, softmax⁡(s)j=esj/∑kesk\operatorname{softmax}(\mathbf{s})_j = e^{s_j} / \sum_k e^{s_k}, turns scores into weights, and output row ii is the convex combination ∑jA[i,j] vj\sum_j A[i, j]\, \mathbf{v}_j: a matrix product AVAV. So each token's output lies in the span of the value vectors, mixed according to similarity.

Why divide by d\sqrt{d}? If the entries of q\mathbf{q} and k\mathbf{k} are independent with mean 0 and variance 1, then q⋅k\mathbf{q} \cdot \mathbf{k} is a sum of dd such products and has variance dd. Dividing by d\sqrt{d} brings the scores back to variance 1. Without it, for large dd the softmax saturates: one weight near 1, the rest near 0, and the gradients vanish.

python · try it yourself
import numpy as np

def softmax(S):
    S = S - S.max(axis=-1, keepdims=True)     # subtract row max: same result, no overflow
    E = np.exp(S)
    return E / E.sum(axis=-1, keepdims=True)

rng = np.random.default_rng(0)
T, d_model, d = 4, 8, 4
X = rng.normal(size=(T, d_model))
W_Q, W_K, W_V = (rng.normal(size=(d_model, d)) / np.sqrt(d_model) for _ in range(3))

Q, K, V = X @ W_Q, X @ W_K, X @ W_V
S = Q @ K.T / np.sqrt(d)
A = softmax(S)
out = A @ V
print("shapes Q, S, out:", Q.shape, S.shape, out.shape)
print("attention weights:\n", np.round(A, 3))
print("rows sum to 1:", np.allclose(A.sum(axis=1), 1))
print("row 0 of out = sum_j A[0,j] v_j:", np.allclose(out[0], sum(A[0, j] * V[j] for j in range(T))))
shapes Q, S, out: (4, 4) (4, 4) (4, 4)
attention weights:
 [[0.276 0.242 0.283 0.2  ]
 [0.212 0.137 0.287 0.364]
 [0.398 0.133 0.296 0.173]
 [0.19  0.27  0.236 0.305]]
rows sum to 1: True
row 0 of out = sum_j A[0,j] v_j: True

The scaling argument is easy to check numerically:

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
for d in (4, 64, 1024):
    q, k = rng.normal(size=(20000, d)), rng.normal(size=(20000, d))
    dots = np.sum(q * k, axis=1)
    print(f"d={d:5d}  var(q.k) = {dots.var():8.1f}   var(q.k/sqrt d) = {(dots / np.sqrt(d)).var():.3f}")
d=    4  var(q.k) =      4.0   var(q.k/sqrt d) = 1.005
d=   64  var(q.k) =     63.5   var(q.k/sqrt d) = 0.992
d= 1024  var(q.k) =    994.5   var(q.k/sqrt d) = 0.971

The causal mask

A language model predicts the next token, so token ii must not look at tokens j>ij > i. Before the softmax, set S[i,j]=−∞S[i, j] = -\infty above the diagonal; e−∞=0e^{-\infty} = 0, so those weights vanish and each row still sums to 1. The result AA is lower triangular.

python · try it yourself
import numpy as np

def softmax(S):
    S = S - S.max(axis=-1, keepdims=True); E = np.exp(S)
    return E / E.sum(axis=-1, keepdims=True)

rng = np.random.default_rng(0)
T, d = 5, 4
Q, K, V = rng.normal(size=(T, d)), rng.normal(size=(T, d)), rng.normal(size=(T, d))

mask = np.triu(np.ones((T, T), dtype=bool), k=1)          # True above the diagonal
S = np.where(mask, -np.inf, Q @ K.T / np.sqrt(d))
A = softmax(S)
print(np.round(A, 3))
out = A @ V
# Changing a future token must not change earlier outputs:
V2 = V.copy(); V2[4] += 100
print("outputs 0-3 unchanged:", np.allclose((A @ V2)[:4], out[:4]))
[[1.    0.    0.    0.    0.   ]
 [0.761 0.239 0.    0.    0.   ]
 [0.196 0.304 0.5   0.    0.   ]
 [0.21  0.122 0.531 0.137 0.   ]
 [0.136 0.064 0.124 0.188 0.487]]
outputs 0-3 unchanged: True

Token 0 can only attend to itself; token 4 sees everything.

Multi-head attention is a reshape

One attention pattern per layer is limiting, so transformers run hh heads in parallel, each with dimension dhead=dmodel/hd_{\text{head}} = d_{\text{model}} / h. Instead of hh separate matrix sets, compute one big Q=XWQQ = XW_Q (T×dmodelT \times d_{\text{model}}), then reshape it to (h,T,dhead)(h, T, d_{\text{head}}): the columns are split into hh blocks. Batched matrix multiplication (@ on 3D arrays) then does all heads at once, and the outputs are reshaped back and mixed by an output matrix WOW_O.

python · try it yourself
import numpy as np

def softmax(S):
    S = S - S.max(axis=-1, keepdims=True); E = np.exp(S)
    return E / E.sum(axis=-1, keepdims=True)

rng = np.random.default_rng(2)
T, d_model, h = 6, 8, 2
dh = d_model // h
X = rng.normal(size=(T, d_model))
W_Q, W_K, W_V, W_O = (rng.normal(size=(d_model, d_model)) / np.sqrt(d_model) for _ in range(4))

def split(M):                       # (T, d_model) -> (h, T, dh)
    return M.reshape(T, h, dh).transpose(1, 0, 2)

Q, K, V = split(X @ W_Q), split(X @ W_K), split(X @ W_V)
A = softmax(Q @ K.transpose(0, 2, 1) / np.sqrt(dh))           # (h, T, T)
heads = A @ V                                                  # (h, T, dh)
out = heads.transpose(1, 0, 2).reshape(T, d_model) @ W_O        # concat heads, mix
print("Q per head:", Q.shape, " A:", A.shape, " out:", out.shape)

# Same as running head 1 on its own column block:
q1, k1, v1 = (X @ W_Q)[:, dh:], (X @ W_K)[:, dh:], (X @ W_V)[:, dh:]
print("head 1 matches its column block:", np.allclose(heads[1], softmax(q1 @ k1.T / np.sqrt(dh)) @ v1))
print("attention parameters:", 4 * d_model * d_model)
Q per head: (2, 6, 4)  A: (2, 6, 6)  out: (6, 8)
head 1 matches its column block: True
attention parameters: 256

Cost and what it means

The score matrix is T×TT \times T, so attention costs about T2⋅dT^2 \cdot d operations and T2T^2 memory per head: doubling the context length quadruples the work. That is the linear-algebra reason for context-window limits and for techniques such as FlashAttention (computing AVAV in tiles without storing AA), KV caches (keeping KK and VV of earlier tokens during generation, since with the causal mask they never change) and sparse or low-rank attention approximations.

Note: Attention by itself is permutation-equivariant: shuffling the rows of XX just shuffles the output rows. Word order enters only through positional encodings added to XX (or rotations applied to QQ and KK, as in RoPE).

In software

  • Transformers. torch.nn.functional.scaled_dot_product_attention(Q, K, V, is_causal=True) is the code above, fused into one fast kernel (Attention, Transformers).
  • Context windows. The T2T^2 cost is why long contexts are expensive (Context Windows).
  • Retrieval. Attention is a "soft" nearest-neighbour lookup: compare a query with keys, return a similarity-weighted mix of values, the differentiable cousin of vector search.

Exercises

Exercise 1: A softmax by hand

Compute softmax⁡(0,ln⁡2,ln⁡5)\operatorname{softmax}(0, \ln 2, \ln 5).

Answer

(18,28,58)=(0.125,0.25,0.625)\left(\frac{1}{8}, \frac{2}{8}, \frac{5}{8}\right) = (0.125, 0.25, 0.625).

Solution

The exponentials are 1, 2, 5 with sum 8.

Exercise 2: Two tokens by hand

With q1=(1,0)\mathbf{q}_1 = (1, 0), k1=(1,0)\mathbf{k}_1 = (1, 0), k2=(0,1)\mathbf{k}_2 = (0, 1), d=2d = 2, v1=(10,0)\mathbf{v}_1 = (10, 0), v2=(0,10)\mathbf{v}_2 = (0, 10), find token 1's output (no mask).

Answer

About (6.70,3.30)(6.70, 3.30).

Solution
scores: (1/2,0)≈(0.7071,0)weights: e0.7071e0.7071+1≈2.02813.0281≈0.6698, and 0.3302output: 0.6698⋅(10,0)+0.3302⋅(0,10)≈(6.70,3.30)\begin{aligned} &\text{scores: } (1/\sqrt{2}, 0) \approx (0.7071, 0) \\ &\text{weights: } \frac{e^{0.7071}}{e^{0.7071} + 1} \approx \frac{2.0281}{3.0281} \approx 0.6698, \text{ and } 0.3302 \\ &\text{output: } 0.6698 \cdot (10, 0) + 0.3302 \cdot (0, 10) \approx (6.70, 3.30) \end{aligned}

Exercise 3: Shapes of multi-head attention

dmodel=512d_{\text{model}} = 512, h=8h = 8, T=100T = 100. Give the shapes of QQ after the reshape, of AA, and the number of entries of AA over all heads.

Answer

QQ: (8,100,64)(8, 100, 64); AA: (8,100,100)(8, 100, 100); 80,000 entries.

Solution

dhead=512/8=64d_{\text{head}} = 512/8 = 64. Each head has a 100×100100 \times 100 attention matrix; 8⋅10 000=80 0008 \cdot 10\,000 = 80\,000.

Exercise 4: Masked row (code)

For the scores S=[210130000]S = \begin{bmatrix} 2 & 1 & 0 \\ 1 & 3 & 0 \\ 0 & 0 & 0 \end{bmatrix} with a causal mask, compute AA.

Answer

Row 0: (1,0,0)(1, 0, 0); row 1: (0.1192,0.8808,0)(0.1192, 0.8808, 0); row 2: (13,13,13)\left(\frac{1}{3}, \frac{1}{3}, \frac{1}{3}\right).

Solution

Row 1 keeps (1,3)(1, 3): weights ee+e3=11+e2≈0.1192\frac{e}{e + e^3} = \frac{1}{1 + e^2} \approx 0.1192 and 0.8808. Row 2 keeps all three equal zeros, giving a uniform average.

python · try it yourself
import numpy as np
S = np.array([[2.0, 1, 0], [1, 3, 0], [0, 0, 0]])
S = np.where(np.triu(np.ones((3, 3), bool), 1), -np.inf, S)
E = np.exp(S - S.max(1, keepdims=True))
print(np.round(E / E.sum(1, keepdims=True), 4))
[[1.     0.     0.    ]
 [0.1192 0.8808 0.    ]
 [0.3333 0.3333 0.3333]]

Test yourself

In softmax⁡(QKT/d)V\operatorname{softmax}(QK^T/\sqrt{d})V, what does row ii of the result represent?

  1. The query of token ii
  2. A weighted average of value vectors, weighted by how well query ii matches each key
  3. The ii-th key
  4. A probability distribution over tokens

Why are attention scores divided by d\sqrt{d}?

  1. To make them integers
  2. The dot product of random dd-dimensional vectors has variance about dd; scaling keeps the softmax from saturating
  3. To make the matrix symmetric
  4. To normalize VV

How is the causal mask applied?

  1. Multiply AA by a lower-triangular matrix after the softmax
  2. Set the scores above the diagonal to −∞-\infty before the softmax
  3. Zero out the values VV
  4. Transpose KK