858. Fix the causal mask off-by-one
Why it matters Mask bugs are silent in training (loss still goes down) and loud at inference. The diagonal decides whether a token can see itself.
The starter code below runs, but it has a realistic bug. Read the spec, find the bug and fix it. Keep the function name and signature.
masked_self_attention(q, k, v) should compute single-head scaled dot-product attention where token i may attend to tokens 0 .. i, including itself: softmax(q @ k.T / sqrt(d) + mask) @ v, with mask[i, j] = -inf for j > i and 0 otherwise.
Inputs: q, k, v are lists or ndarrays of shape (T, d).
Return an ndarray of floats with shape (T, d), with no nan values. No rounding.
def masked_self_attention(q, k, v)Example 1
Input: masked_self_attention([[1.0, 0.0], [0.0, 1.0]], [[1.0, 0.0], [0.0, 1.0]], [[1.0, 2.0], [3.0, 4.0]])
Output: [[1.0, 2.0], [2.3395, 3.3395]]
Example 2
Input: q = [[1.0]], k = [[2.0]], v = [[5.0]]
Output: [[5.0]]
Example 3
Input: q = [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], k = [[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]], v = [[3.0, 0.0], [0.0, 3.0], [3.0, 3.0]]
Output: [[3.0, 0.0], [1.5, 1.5], [2.0, 2.0]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Look at row 0 of the mask. How many positions can token 0 attend to?
Hint 2
np.triu with k=0 keeps the diagonal; k=1 starts above it.
Hint 3
Change one argument.
Common mistakes
- Using
np.trilfor the mask, which blocks the past instead of the future. - Masking with a large negative number but forgetting the max shift.
- Masking after the softmax.
Understand the idea
np.triu(..., k=0) includes the diagonal, so token i cannot see itself and token 0 sees nothing at all. A row of only -inf gives exp(-inf) = 0 everywhere and 0 / 0 = nan. The causal mask should block only the strictly upper triangle, which is k=1.
Shapes and data flow
q, k, v: (T, d). scores and mask: (T, T).