TExcelTAD
Home › Generative AI & LLMs › Attention

Attention

Take the sentence "The animal didn't cross the street because it was tired." To understand it, you must connect it to animal, not street. Attention is the mechanism that lets each token gather information from the other tokens that matter to it. It is the heart of the Transformer.

The intuition: a soft lookup

Attention works like a fuzzy dictionary lookup. Every token produces three vectors:

Vector Role Analogy
Query (Q) what this token is looking for a search query
Key (K) what this token offers to others a document's title
Value (V) the information it passes on the document's content

Each token compares its query with every key (dot product = similarity), turns the scores into weights with softmax, and takes the weighted average of the values. Instead of retrieving exactly one entry, it blends all of them — mostly the relevant ones.

Scaled dot-product attention

text
Attention(Q, K, V) = softmax( Q·Kᵀ / √d ) · V

d is the size of the key vectors. Dividing by √d keeps the scores from growing too large, which would make softmax extremely peaked.

python · try it yourself
import numpy as np

np.set_printoptions(precision=2, suppress=True)

def softmax(x):
    e = np.exp(x - x.max(axis=-1, keepdims=True))   # subtract max for stability
    return e / e.sum(axis=-1, keepdims=True)

tokens = ["the", "cat", "sat"]
Q = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
K = np.array([[1.0, 0.0], [0.0, 2.0], [1.0, 1.0]])
V = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])

d = K.shape[1]
scores = Q @ K.T / np.sqrt(d)
weights = softmax(scores)
output = weights @ V

print("scores:\n", scores)
print("attention weights (each row sums to 1):\n", weights)
print("output:\n", output)
scores:
 [[0.71 0.   0.71]
 [0.   1.41 0.71]
 [0.71 1.41 1.41]]
attention weights (each row sums to 1):
 [[0.4  0.2  0.4 ]
 [0.14 0.58 0.28]
 [0.2  0.4  0.4 ]]
output:
 [[0.4  0.2  0.4 ]
 [0.14 0.58 0.28]
 [0.2  0.4  0.4 ]]

Because the values here are one-hot vectors, each output row is its attention weights: you can read off how much of each token's information was mixed in. In a real model the values are rich vectors, so the output is a context-aware blend.

Where do Q, K and V come from?

They are not hand-written. Each token's embedding x is multiplied by three learned weight matrices: Q = x·W_Q, K = x·W_K, V = x·W_V. Training adjusts these matrices so that useful relationships (pronoun → noun, verb → subject, opening bracket → closing bracket) produce high scores.

Causal masking: no peeking ahead

A language model predicts the next token, so while processing position i it must not see tokens after i. A causal mask sets those scores to −∞ before softmax, which makes their weights exactly zero. The heatmap below shows the resulting triangular pattern:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(3)
tokens = ["The", "dog", "chased", "the", "ball", "."]
n, d = len(tokens), 8

X = rng.normal(size=(n, d))                       # stand-in embeddings
W_q, W_k = rng.normal(0, 0.4, (d, d)), rng.normal(0, 0.4, (d, d))  # small random weights
scores = (X @ W_q) @ (X @ W_k).T / np.sqrt(d)

mask = np.triu(np.ones((n, n), dtype=bool), k=1)  # True above the diagonal
scores[mask] = -np.inf
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)

fig, ax = plt.subplots(figsize=(5, 4))
ax.imshow(weights, cmap="Purples")
ax.set_xticks(range(n), tokens); ax.set_yticks(range(n), tokens)
ax.set_xlabel("attends to (key)"); ax.set_ylabel("token (query)")
ax.set_title("Causal attention weights")
plt.show()

print("row sums:", np.round(weights.sum(axis=1), 6))
print("weights above the diagonal are all zero:", bool(np.all(weights[mask] == 0)))
row sums: [1. 1. 1. 1. 1. 1.]
weights above the diagonal are all zero: True

The weights here come from random matrices, so the pattern inside the triangle means nothing — but the shape is exactly what every decoder LLM uses. The first token can only attend to itself; the last token can attend to everything before it.

Multi-head attention

One attention computation can only focus on one kind of relationship at a time. Transformers therefore run several heads in parallel, each with its own W_Q, W_K, W_V, then concatenate the results. One head might track grammar, another nearby tokens, another long-range references.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
n, d_model, n_heads = 4, 8, 2
d_head = d_model // n_heads
X = rng.normal(size=(n, d_model))

def attention(Q, K, V):
    s = Q @ K.T / np.sqrt(Q.shape[-1])
    s += np.triu(np.full((len(Q), len(Q)), -np.inf), k=1)   # causal mask
    w = np.exp(s - s.max(axis=-1, keepdims=True))
    w /= w.sum(axis=-1, keepdims=True)
    return w @ V

heads = []
for h in range(n_heads):
    Wq, Wk, Wv = (rng.normal(size=(d_model, d_head)) for _ in range(3))
    heads.append(attention(X @ Wq, X @ Wk, X @ Wv))
    print(f"head {h}: output shape {heads[-1].shape}")

W_o = rng.normal(size=(d_model, d_model))
out = np.concatenate(heads, axis=-1) @ W_o
print("combined output shape:", out.shape)
head 0: output shape (4, 4)
head 1: output shape (4, 4)
combined output shape: (4, 8)

Each head works in a smaller space (d_head = 4), and an output matrix W_o mixes the heads back together, so the result has the same shape as the input — ready for the next layer.

Note: Attention compares every token with every other token, so its cost grows with the square of the sequence length. That is one reason long context windows are expensive.

Go further: Attention from Scratch builds batched, masked, multi-head attention in NumPy and checks it against PyTorch.

Test yourself

In attention, what is the output for one token?

  1. The single most similar key
  2. A weighted average of the value vectors
  3. The sum of all queries
  4. The token's original embedding

What does the causal mask do in a decoder LLM?

  1. Hides offensive words
  2. Prevents each position from attending to later positions
  3. Removes the first token
  4. Doubles the attention weights

Why are attention scores divided by √d?

  1. To keep scores from growing so large that softmax becomes extremely peaked
  2. To make the output shorter
  3. To convert tokens to IDs
  4. It has no purpose