Write scaled dot-product attention with a causal mask
Attention lets each token look at other tokens and take a weighted average of their values. In a language model a token may only look at itself and earlier tokens, never the future. That rule is the causal mask.
Write causal_attention(Q, K, V) for one head, where Q, K, V are NumPy arrays of shape (seq_len, d).
1. scores = Q @ K.T / sqrt(d)
2. Set scores[i, j] to -inf wherever j > i.
3. Softmax each row (subtract the row max first).
4. Return weights @ V, shape (seq_len, d).
def causal_attention(Q, K, V)Understand the idea
Attention lets each token build its output as a weighted average of value vectors, where the weights come from how well its query matches each key. In a language model a token must not peek at future tokens, like a student who may only read earlier pages of the exam. Worked example with d = 1 (so sqrt(d) = 1): Q = [[1], [1]], K = [[0], [2]], V = [[10], [20]]. Row 0 may only see itself, so its weight is 1 and its output is 10. Row 1 scores are 1*0 = 0 and 1*2 = 2. Softmax of [0, 2] is about [0.119, 0.881], so its output is 0.119*10 + 0.881*20 = 18.81. Rule: scores = Q K^T / sqrt(d); set scores[i, j] = -inf when j > i; softmax each row after subtracting its max; output = weights V. Every decoder-only LLM such as GPT or Llama runs this inside each attention head.
Similar problems
Part of the advanced LLM architecture track.