Scaled dot-product attention with a mask
Problem
Shapes: Q (Tq, d), K (Tk, d), V (Tk, dv). Compute softmax(QKᵀ/√d)·V. mask is an optional boolean (Tq, Tk) array where True means “may attend”; masked positions must get weight exactly 0. Assume each row has at least one True. Return (output, weights).
Signature
def attention(Q, K, V, mask=None) -> tuple[np.ndarray, np.ndarray]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(attention([[0.0, 0.0]], [[1.0, 0.0],[0.0, 1.0]], [[1.0, 2.0],[3.0, 4.0]]), ([[2.0, 3.0]], [[0.5, 0.5]]))
True
>>> close(attention([[1.0, 0.0]], [[1.0, 0.0],[0.0, 1.0]], [[1.0],[0.0]]), ([[0.669762]], [[0.669762, 0.330238]]))
TrueHints
Scale Q*K^T by 1/sqrt(d).
Mask positions to -inf before the softmax, then max-subtract for stability.
Weights rows must sum to 1; return (output, weights).
Reference solution
import math
import numpy as np
def attention(Q, K, V, mask=None):
Q = np.asarray(Q, float); K = np.asarray(K, float); V = np.asarray(V, float)
s = Q @ K.T / math.sqrt(Q.shape[1])
if mask is not None:
s = np.where(np.asarray(mask, bool), s, -np.inf)
s = s - s.max(axis=1, keepdims=True)
w = np.exp(s)
w = w / w.sum(axis=1, keepdims=True)
return w @ V, wWhat a strong solution covers
- Correct scaling.
- Masks with −inf (or a large negative) before the softmax, with max-subtraction.
- Weights rows sum to 1.
- Discusses O(T²) memory and the causal mask construction.
Common mistakes
- multiplying weights by the mask after the softmax (rows no longer sum to 1)
- scaling by d instead of √d.