BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Debug and fix3 of 16 in topic

858. Fix the causal mask off-by-one

MediumDebug and fix

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.

Functiondef 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.tril for 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).
Topics
Debug and fix
Similar questions
  • Fix Adam missing bias correctionMedium
  • Fix attention scores without the transposeMedium
  • Fix the scaler that leaks test dataMedium
  • Fix the KV cache that grows the wrong axisMedium
All Debug and fix problems
Report
858 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np
​
def masked_self_attention(q, k, v):
q, k, v = (np.asarray(a, dtype=float) for a in (q, k, v))
T, d = q.shape
scores = q @ k.T / np.sqrt(d)
mask = np.triu(np.ones((T, T), dtype=bool), k=0)
scores = np.where(mask, -np.inf, scores)
scores = scores - scores.max(axis=1, keepdims=True)
w = np.exp(scores)
w = w / w.sum(axis=1, keepdims=True)
return w @ v
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS